blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 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 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
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 115
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b5627577b15ed5ffb9f70acc6e6eaf08cb903d49 | 4c39680401a57998796b452d1bb361b32f897c1f | /ennakkotehtava-06/main.cpp | e1c56f860894c1ba1f413201012770dda0ea77b7 | [] | no_license | CheatCod3s/School-projects | 20a1ee523ebc7d5f4565d1eb293ef8f218ef3479 | c4fc2a8ce38d4f66c29d997de22f50f9215ca960 | refs/heads/master | 2021-01-12T09:19:37.271386 | 2017-02-08T13:21:14 | 2017-02-08T13:21:14 | 81,330,978 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,752 | cpp | #include <iostream>
#include <map>
#include <string>
using namespace std;
using Puhelinluettelo = map<string, string>;
int laske_nimet(Puhelinluettelo::const_iterator tutkittava,
Puhelinluettelo::const_iterator loppu,
char nimen_alkukirjain);
int main()
{
Puhelinluettelo luettelo = {
{ "Kalle", "111 1111" },
{ "Jarkko", "222 2222" },
{ "Kirsi", "333 3333" },
{ "Jaana", "444 4444" },
{ "Matti", "555 5555" },
{ "Minna", "666 6666" },
{ "Anja", "777 7777" },
{ "Eero", "888 8888" },
{ "Keijo", "999 9999" },
};
cout << "X: " << laske_nimet(luettelo.begin(), luettelo.end(), 'X') << endl;
cout << "K: " << laske_nimet(luettelo.begin(), luettelo.end(), 'K') << endl;
cout << "J: " << laske_nimet(luettelo.begin(), luettelo.end(), 'J') << endl;
cout << "M: " << laske_nimet(luettelo.begin(), luettelo.end(), 'M') << endl;
cout << "A: " << laske_nimet(luettelo.begin(), luettelo.end(), 'A') << endl;
cout << "E: " << laske_nimet(luettelo.begin(), luettelo.end(), 'E') << endl;
}
int laske_nimet(Puhelinluettelo::const_iterator tutkittava,
Puhelinluettelo::const_iterator loppu,
char nimen_alkukirjain){
if (tutkittava == loppu){
return 0;
} else if (tutkittava->first.front() > nimen_alkukirjain) {
return 0;
} else if (tutkittava->first.front() == nimen_alkukirjain){
++tutkittava;
return 1 + laske_nimet(tutkittava, loppu, nimen_alkukirjain);
} else {
++tutkittava;
return laske_nimet(tutkittava, loppu, nimen_alkukirjain);
}
}
| [
"[email protected]"
] | |
85132e6c4f0e87c6f15837cef75f18c950d7c721 | dd5356457879b9edf8c982a412e0068f94da697d | /SDK/RoCo_Arbitrator_CameraShake_classes.hpp | f770f43f5741968147fd28b1744c87f09282b8b9 | [] | no_license | ALEHACKsp/RoCo-SDK | 5ee6567294674b6933dcd0acda720f64712ccdbf | 3a9e37be3a48bc0a10aa9e4111865c996f3b5680 | refs/heads/master | 2023-05-14T16:54:49.296847 | 2021-06-08T20:09:37 | 2021-06-08T20:09:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 720 | hpp | #pragma once
// Rogue Company (0.60) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "RoCo_Arbitrator_CameraShake_structs.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass Arbitrator_CameraShake.Arbitrator_CameraShake_C
// 0x0000 (0x0160 - 0x0160)
class UArbitrator_CameraShake_C : public UCameraShake
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("BlueprintGeneratedClass Arbitrator_CameraShake.Arbitrator_CameraShake_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
d10d5b10d8a97f622907c41bf2685aafb17db530 | 06b7eb06edbcb424c33f41865f1b30f14f7fb67d | /Model.cpp | d38f52227bbc2d80e84b8fda3abcc38f881fb39d | [] | no_license | VladimirSpigiel/GameOfLife | 1564eed06d65ea961c8e8d73cbc17b981395041a | e897d021e7d1a167c611b21121d21e294eef7b62 | refs/heads/master | 2020-04-06T07:08:24.065199 | 2016-08-28T10:43:53 | 2016-08-28T10:43:53 | 64,558,341 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 663 | cpp | #include "stdafx.h"
#include "Model.h"
#include <iostream>
Model::Model(int width, int height):
_width(width),
_height(height),
_generation(0)
{
/* INIT THE GRID THAT CONTAINS THE CELLS*/
_h_grid = new Cell[_width * _height];
for (int i = 0; i < _width * _height; i++)
_h_grid[i] = DEAD_CELL;
for (int i = 0; i < _height; i++)
_h_grid[i * _width] = ALIVE_CELL;
}
Model::~Model()
{
if (_h_grid != NULL){
delete _h_grid;
_h_grid = NULL;
}
}
void Model::toggleCell(int x, int y)
{
if (x < _width && y < _height && x >= 0 && y >= 0) {
Cell &cell = _h_grid[y * _width + x];
cell = cell == DEAD_CELL ? ALIVE_CELL : DEAD_CELL;
}
}
| [
"[email protected]"
] | |
a7b53c6f3c9888123bab365030546f2305a3590c | d76df70b88f95748f8c8c17631a281a1b6cc0860 | /pyomo/contrib/appsi/cmodel/src/common.cpp | e8e2d3b58478e0002b7964fa49257d230e85fbd4 | [
"BSD-3-Clause"
] | permissive | aweltsch/pyomo | 2d603a5f367969c376d785c395104d2ad2a74131 | 6fd5b8aa94b21bfe3290bdb019b33b822d51b681 | refs/heads/master | 2022-05-30T01:20:00.102627 | 2022-05-03T21:54:39 | 2022-05-03T21:54:39 | 170,027,464 | 0 | 0 | null | 2019-02-10T21:08:03 | 2019-02-10T21:08:03 | null | UTF-8 | C++ | false | false | 92 | cpp | #include "common.hpp"
double inf = py::module_::import("math").attr("inf").cast<double>();
| [
"[email protected]"
] | |
d0c080ecbb6dec9dd00c0165edb3ff88f80c421f | fdb655cccd64b27894890ced60232c4d7237073f | /FenPrincipale.h | d203e418dbb720901e57fbb4c3202d21d5e89942 | [] | no_license | creatie/Zero-Editeur | 2f8061cd350128f3db6d4616744c07ad741c1039 | d0ffd4ca9d652db30a63a4fc96fa54a8fd73bbd5 | refs/heads/master | 2016-09-06T04:11:29.472495 | 2012-10-01T05:48:40 | 2012-10-01T05:48:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,750 | h | #ifndef FENPRINCIPALE_H
#define FENPRINCIPALE_H
#include <QApplication>
#include <QMainWindow>
#include <QLineEdit>
#include <QWidget>
#include <QFormLayout>
#include <QMdiArea>
#include <QTextEdit>
#include <QMenu>
#include <QMenuBar>
#include <QToolBar>
#include <QFontComboBox>
#include <QLabel>
#include <QDockWidget>
#include <QPushButton>
#include <QSpinBox>
#include <QTabWidget>
#include <QFont>
#include <QTabBar>
#include <QStatusBar>
#include <QDialog>
#include <QFile>
#include <QFileDialog>
#include <QMessageBox>
#include <QTextStream>
#include <QDebug>
#include "Editeur.h"
class FenPrincipale : public QMainWindow
{
Q_OBJECT
public:
FenPrincipale();
public slots:
void addOnglet();
void changerPolice(QFont police);
void supprimerOnglet(int index);
void montrerAbout();
void changerCurrTab(int index);
void marquerChangement(int index);
void ouvrirPreferences();
void sauvegarderFichier();
private:
void creerMenu();
void creerActions();
void creerToolBars();
void creerMdi();
void creerStatusBar();
// Menu ----------------
QMenu* menuFichier;
QMenu* menuEdition;
QMenu* menuAffichage;
QMenu* menuAide;
// Actions -------------
QAction* actionNouvelOnglet;
QAction* actionOuvrir;
QAction* actionSauvegarder;
QAction* actionSauvegarderComme;
QAction* actionQuitter;
QAction* actionPreferences;
QAction* actionAbout;
// Toolbars ------------
QToolBar* m_toolBarFichier;
// Statusbar -----------
QStatusBar* m_statusBar;
QTabWidget* m_zoneCentrale;
QTextEdit* m_currTextTab;
QFontComboBox* m_toolBarChoixPolice;
bool m_unsaved;
int m_lastIndex;
};
#endif // FENPRINCIPALE_H
| [
"[email protected]"
] | |
53e6542596a25110c90f593a4d9441dc5fb803c9 | fd9e01c634878a3cef730ba68ea7a2f156452916 | /cpp/src/arrow/compute/kernels/scalar_fill_null.cc | e6b454c664e0dbb328e7931098280dcb69af5aed | [
"Apache-2.0",
"MIT",
"BSD-3-Clause",
"BSD-2-Clause",
"Zlib",
"CC-BY-3.0",
"CC0-1.0",
"OpenSSL",
"ZPL-2.1",
"BSL-1.0",
"NTP",
"LicenseRef-scancode-unknown-license-reference",
"LLVM-exception",
"LicenseRef-scancode-public-domain",
"JSON",
"CC-BY-4.0",
"LicenseRef-scancode-protobuf"
] | permissive | a2un/arrow | e5e2c6d72991ca20203db272b8821305b041bf6a | a6b30de87f3b157dec13561dbecebe7652189498 | refs/heads/arrow-master | 2021-07-07T11:31:59.139741 | 2020-10-04T19:21:11 | 2020-10-04T19:21:11 | 195,855,519 | 2 | 0 | Apache-2.0 | 2020-10-04T23:28:38 | 2019-07-08T17:13:14 | C++ | UTF-8 | C++ | false | false | 6,274 | cc | // 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 <algorithm>
#include <cstring>
#include "arrow/compute/kernels/common.h"
#include "arrow/scalar.h"
#include "arrow/util/bit_block_counter.h"
#include "arrow/util/bit_util.h"
#include "arrow/util/bitmap_ops.h"
namespace arrow {
using internal::BitBlockCount;
using internal::BitBlockCounter;
namespace compute {
namespace internal {
namespace {
template <typename Type, typename Enable = void>
struct FillNullFunctor {};
template <typename Type>
struct FillNullFunctor<Type, enable_if_t<is_number_type<Type>::value>> {
using T = typename TypeTraits<Type>::CType;
static void Exec(KernelContext* ctx, const ExecBatch& batch, Datum* out) {
const ArrayData& data = *batch[0].array();
const Scalar& fill_value = *batch[1].scalar();
ArrayData* output = out->mutable_array();
// Ensure the kernel is configured properly to have no validity bitmap /
// null count 0 unless we explicitly propagate it below.
DCHECK(output->buffers[0] == nullptr);
T value = UnboxScalar<Type>::Unbox(fill_value);
if (data.MayHaveNulls() != 0 && fill_value.is_valid) {
KERNEL_ASSIGN_OR_RAISE(std::shared_ptr<Buffer> out_buf, ctx,
ctx->Allocate(data.length * sizeof(T)));
const uint8_t* is_valid = data.buffers[0]->data();
const T* in_values = data.GetValues<T>(1);
T* out_values = reinterpret_cast<T*>(out_buf->mutable_data());
int64_t offset = data.offset;
BitBlockCounter bit_counter(is_valid, data.offset, data.length);
while (offset < data.offset + data.length) {
BitBlockCount block = bit_counter.NextWord();
if (block.AllSet()) {
// Block all not null
std::memcpy(out_values, in_values, block.length * sizeof(T));
} else if (block.NoneSet()) {
// Block all null
std::fill(out_values, out_values + block.length, value);
} else {
for (int64_t i = 0; i < block.length; ++i) {
out_values[i] = BitUtil::GetBit(is_valid, offset + i) ? in_values[i] : value;
}
}
offset += block.length;
out_values += block.length;
in_values += block.length;
}
output->buffers[1] = out_buf;
} else {
*output = data;
}
}
};
template <typename Type>
struct FillNullFunctor<Type, enable_if_t<is_boolean_type<Type>::value>> {
static void Exec(KernelContext* ctx, const ExecBatch& batch, Datum* out) {
const ArrayData& data = *batch[0].array();
const Scalar& fill_value = *batch[1].scalar();
ArrayData* output = out->mutable_array();
bool value = UnboxScalar<BooleanType>::Unbox(fill_value);
if (data.MayHaveNulls() != 0 && fill_value.is_valid) {
KERNEL_ASSIGN_OR_RAISE(std::shared_ptr<Buffer> out_buf, ctx,
ctx->AllocateBitmap(data.length));
const uint8_t* is_valid = data.buffers[0]->data();
const uint8_t* data_bitmap = data.buffers[1]->data();
uint8_t* out_bitmap = out_buf->mutable_data();
int64_t data_offset = data.offset;
BitBlockCounter bit_counter(is_valid, data.offset, data.length);
int64_t out_offset = 0;
while (out_offset < data.length) {
BitBlockCount block = bit_counter.NextWord();
if (block.AllSet()) {
// Block all not null
::arrow::internal::CopyBitmap(data_bitmap, data_offset, block.length,
out_bitmap, out_offset);
} else if (block.NoneSet()) {
// Block all null
BitUtil::SetBitsTo(out_bitmap, out_offset, block.length, value);
} else {
for (int64_t i = 0; i < block.length; ++i) {
BitUtil::SetBitTo(out_bitmap, out_offset + i,
BitUtil::GetBit(is_valid, data_offset + i)
? BitUtil::GetBit(data_bitmap, data_offset + i)
: value);
}
}
data_offset += block.length;
out_offset += block.length;
}
output->buffers[1] = out_buf;
} else {
*output = data;
}
}
};
template <typename Type>
struct FillNullFunctor<Type, enable_if_t<is_null_type<Type>::value>> {
static void Exec(KernelContext* ctx, const ExecBatch& batch, Datum* out) {
// Nothing preallocated, so we assign into the output
*out->mutable_array() = *batch[0].array();
}
};
void AddBasicFillNullKernels(ScalarKernel kernel, ScalarFunction* func) {
auto AddKernels = [&](const std::vector<std::shared_ptr<DataType>>& types) {
for (const std::shared_ptr<DataType>& ty : types) {
kernel.signature =
KernelSignature::Make({InputType::Array(ty), InputType::Scalar(ty)}, ty);
kernel.exec = GenerateTypeAgnosticPrimitive<FillNullFunctor>(*ty);
DCHECK_OK(func->AddKernel(kernel));
}
};
AddKernels(NumericTypes());
AddKernels(TemporalTypes());
AddKernels({boolean(), null()});
}
} // namespace
void RegisterScalarFillNull(FunctionRegistry* registry) {
{
ScalarKernel fill_null_base;
fill_null_base.null_handling = NullHandling::COMPUTED_NO_PREALLOCATE;
fill_null_base.mem_allocation = MemAllocation::NO_PREALLOCATE;
auto fill_null = std::make_shared<ScalarFunction>("fill_null", Arity::Binary());
AddBasicFillNullKernels(fill_null_base, fill_null.get());
DCHECK_OK(registry->AddFunction(fill_null));
}
}
} // namespace internal
} // namespace compute
} // namespace arrow
| [
"[email protected]"
] | |
3fe78079f7ac97635c7de49d5798329847d152aa | 161f428f27116c1ab0ef05b0f3ff5260cbac6caa | /tmp/segment_segment_intersect.cpp | 88cdf192606f13b297f769d1b199351de86a4381 | [] | no_license | KarlLeell/libigl-python-bindings | cebc21447f6f2b276cde321c2ca166ff0b81622f | 1e76609823b018ac152b08d6c8384cea5031df3e | refs/heads/master | 2020-05-31T00:20:52.758553 | 2019-08-07T16:53:57 | 2019-08-07T16:53:57 | 190,031,924 | 0 | 0 | null | 2019-06-03T15:25:01 | 2019-06-03T15:25:01 | null | UTF-8 | C++ | false | false | 1,153 | cpp | // TODO: __example
// error at line 33 and 41, saying cross is only for certain size matrices
#include <npe.h>
#include <typedefs.h>
#include <igl/segment_segment_intersect.h>
const char* ds_segments_intersect = R"igl_Qu8mg5v7(
Determine whether two line segments A,B intersect
A: p + t*r : t \in [0,1]
B: q + u*s : u \in [0,1]
Parameters
----------
p 3-vector origin of segment A
r 3-vector direction of segment A
q 3-vector origin of segment B
s 3-vector direction of segment B
eps precision
Returns
-------
t scalar point of intersection along segment A, t \in [0,1]
u scalar point of intersection along segment B, u \in [0,1]
Returns true if intersection
See also
--------
Notes
-----
None
Examples
--------
)igl_Qu8mg5v7";
npe_function(segments_intersect)
npe_doc(ds_segments_intersect)
npe_arg(p, dense_float, dense_double)
npe_arg(r, npe_matches(p))
npe_arg(q, npe_matches(p))
npe_arg(s, npe_matches(p))
npe_begin_code()
double t;
double u;
double eps;
bool is_intersect = igl::segment_segment_intersect(p, r, q, s, t, u, eps);
return std::make_tuple(is_intersect, t, u, eps);
npe_end_code()
| [
"[email protected]"
] | |
be734114e146fe8e2d10050af26a081e62279e02 | 753a70bc416e8dced2853f278b08ef60cdb3c768 | /include/tensorflow/lite/c/c_api_experimental.cc | 4b812172937b443e76286dc0aa4c36c8dc0bffd8 | [
"MIT"
] | permissive | finnickniu/tensorflow_object_detection_tflite | ef94158e5350613590641880cb3c1062f7dd0efb | a115d918f6894a69586174653172be0b5d1de952 | refs/heads/master | 2023-04-06T04:59:24.985923 | 2022-09-20T16:29:08 | 2022-09-20T16:29:08 | 230,891,552 | 60 | 19 | MIT | 2023-03-25T00:31:18 | 2019-12-30T09:58:41 | C++ | UTF-8 | C++ | false | false | 1,758 | 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/lite/c/c_api_experimental.h"
#include "tensorflow/lite/c/c_api_internal.h"
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
TfLiteStatus TfLiteInterpreterResetVariableTensors(
TfLiteInterpreter* interpreter) {
return interpreter->impl->ResetVariableTensors();
}
void TfLiteInterpreterOptionsAddBuiltinOp(
TfLiteInterpreterOptions* options, TfLiteBuiltinOperator op,
const TfLiteRegistration* registration, int32_t min_version,
int32_t max_version) {
options->op_resolver.AddBuiltin(static_cast<tflite::BuiltinOperator>(op),
registration, min_version, max_version);
}
void TfLiteInterpreterOptionsAddCustomOp(TfLiteInterpreterOptions* options,
const char* name,
const TfLiteRegistration* registration,
int min_version, int max_version) {
options->op_resolver.AddCustom(name, registration, min_version, max_version);
}
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
| [
"[email protected]"
] | |
be4f04270d7eb14d4d8fda34f61641dbd5441e96 | 25739059dd91cc84a65ae3abb9a7a0213caa8c81 | /boost/boost/mpl/sizeof.hpp | 49f5fc8829c352a191586393bc0cf92f252098fb | [
"MIT"
] | permissive | MIPT-ILab/MDSP | 70a669111c6c4518e2500c4d775fe508b2661591 | e1d09a3b979b54c7b49883d48c05650476f366ae | refs/heads/master | 2020-12-26T21:49:38.410540 | 2018-11-01T09:11:30 | 2018-11-01T09:18:23 | 33,407,032 | 2 | 2 | MIT | 2018-11-01T09:11:31 | 2015-04-04T13:53:13 | C++ | UTF-8 | C++ | false | false | 907 | hpp |
#ifndef BOOST_MPL_SIZEOF_HPP_INCLUDED
#define BOOST_MPL_SIZEOF_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2000-2003
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id: sizeof.hpp 49267 2008-10-11 06:19:02Z agurtovoy $
// $Date: 2008-10-11 02:19:02 -0400 (Sat, 11 Oct 2008) $
// $Revision: 49267 $
#include <boost/mpl/size_t.hpp>
#include <boost/mpl/aux_/na_spec.hpp>
#include <boost/mpl/aux_/lambda_support.hpp>
namespace boost { namespace mpl {
template<
typename BOOST_MPL_AUX_NA_PARAM(T)
>
struct sizeof_
: mpl::size_t< sizeof(T) >
{
BOOST_MPL_AUX_LAMBDA_SUPPORT(1,sizeof_,(T))
};
BOOST_MPL_AUX_NA_SPEC_NO_ETI(1, sizeof_)
}}
#endif // BOOST_MPL_SIZEOF_HPP_INCLUDED
| [
"[email protected]"
] | |
a2b59ee6c47d4d0c22f44b1fe393ac9730d77389 | aa1ef21bf7aa0fab6d5b9f429b086eced97c7b8e | /kickstart/2019-practice/1.cpp | a5ccf9b82e1d39fb6748209d19058cc97c6fc2a8 | [] | no_license | vd-07/CP | ad8f7a0b71e53e2f83b0a69d344f3cf9b9c77580 | 15b0c69574111ebca4b9f428f84d10884bc65bcd | refs/heads/main | 2021-09-08T07:35:16.804319 | 2021-08-04T16:58:47 | 2021-08-04T16:58:47 | 207,377,244 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,889 | cpp | //Author : Vivek Dubey
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define ull unsigned long long int
#define READ(a) ll a; cin>>a
#define READ2(a,b) ll a,b; cin>>a>>b
#define f(i,s,e) for(int i=s;i<e;i++)
#define READC(c) char c; cin>>c
#define READA(a,n) ll a[n]; f(i,0,n) cin>>a[i]
#define READS(s) string s; cin>>s
#define FILL(x,y) memset(x,y,sizeof(x))
#define test ll t; cin>>t; while(t--)
#define mod 1000000007
#define fastIO ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define pb push_back
#define pii pair<int,int>
struct SegmentTreeNode {
int maxNum, secondMaxNum;
void assignLeaf(int value) {
maxNum=value;
secondMaxNum=-1;
}
void merge(SegmentTreeNode& left, SegmentTreeNode& right) {
maxNum=max(left.maxNum, right.maxNum);
secondMaxNum=min(max(left.maxNum, right.secondMaxNum), max(left.secondMaxNum, right.maxNum));
}
int getValue() {
return maxNum+secondMaxNum;
}
};
//Segment Tree Template from : https://gist.github.com/kartikkukreja/2e7685e1fc8dbca0001b#file-segment-tree-template-cpp
// T is the type of input array elements
// V is the type of required aggregate statistic
template<class T, class V>
class SegmentTree {
SegmentTreeNode* nodes;
int N;
public:
SegmentTree(T arr[], int N) {
this->N = N;
nodes = new SegmentTreeNode[getSegmentTreeSize(N)];
buildTree(arr, 1, 0, N-1);
}
~SegmentTree() {
delete[] nodes;
}
V getValue(int lo, int hi) {
SegmentTreeNode result = getValue(1, 0, N-1, lo, hi);
return result.getValue();
}
void update(int index, T value) {
update(1, 0, N-1, index, value);
}
private:
void buildTree(T arr[], int stIndex, int lo, int hi) {
if (lo == hi) {
nodes[stIndex].assignLeaf(arr[lo]);
return;
}
int left = 2 * stIndex, right = left + 1, mid = (lo + hi) / 2;
buildTree(arr, left, lo, mid);
buildTree(arr, right, mid + 1, hi);
nodes[stIndex].merge(nodes[left], nodes[right]);
}
SegmentTreeNode getValue(int stIndex, int left, int right, int lo, int hi) {
if (left == lo && right == hi)
return nodes[stIndex];
int mid = (left + right) / 2;
if (lo > mid)
return getValue(2*stIndex+1, mid+1, right, lo, hi);
if (hi <= mid)
return getValue(2*stIndex, left, mid, lo, hi);
SegmentTreeNode leftResult = getValue(2*stIndex, left, mid, lo, mid);
SegmentTreeNode rightResult = getValue(2*stIndex+1, mid+1, right, mid+1, hi);
SegmentTreeNode result;
result.merge(leftResult, rightResult);
return result;
}
int getSegmentTreeSize(int N) {
int size = 1;
for (; size < N; size <<= 1);
return size << 1;
}
void update(int stIndex, int lo, int hi, int index, T value) {
if (lo == hi) {
nodes[stIndex].assignLeaf(value);
return;
}
int left = 2 * stIndex, right = left + 1, mid = (lo + hi) / 2;
if (index <= mid)
update(left, lo, mid, index, value);
else
update(right, mid+1, hi, index, value);
nodes[stIndex].merge(nodes[left], nodes[right]);
}
};
ll power(ll x, ll y, ll p)
{
ll res = 1;
x = x % p;
while (y > 0){
if (y & 1)
res = (res*x) % p;
y = y>>1;
x = (x*x) % p;
}
return res;
}
ll modInverse(ll n, ll p)
{
return power(n, p-2, p)%p;
}
void solve(){
READ2(N,P);
READA(S,N);
__int128 v=2;
printf("%llu", v);
sort(S,S+N,greater<ll> ());
ll ans=0;
for(int i=0;i<P;i++)
ans+=(S[0]-S[i]);
ll rem=ans;
for(int i=P;i<N;i++){
ans+=(P-1)*(S[i-P+1]-S[i-P])+(S[i-P+1]-S[i]);
// cout<<ans<<"\n";
rem=min(ans,rem);
}
cout<<rem<<'\n';
}
int main(){
int t;
cin>>t;
for(int i=1;i<=t;i++) {
cout<<"Case #"<<i<<": ";
solve();
}
return 0;
} | [
"[email protected]"
] | |
301043b181b6153783bfd88f2e64a1ce28214185 | 8be083e9fbf15606201217d6c4b87c929e418065 | /tags/release-0.6/util/colorutil.cpp | 32dc0974ba55ec57b414f60eeac4973ee31515a7 | [
"Apache-2.0"
] | permissive | BGCX067/faint-graphics-editor-svn-to-git | 430768d441f3e9b353fbc128e132f7406ee48c0e | dad252f820d29ab336bcfa57138625dae6dfed60 | refs/heads/master | 2021-01-13T00:56:26.685520 | 2015-12-28T14:22:44 | 2015-12-28T14:22:44 | 48,752,914 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,751 | cpp | #include "colorutil.hh"
#include <cassert>
bool red_is_max( const faint::Color& c ){
return c.r >= c.g && c.r >= c.b;
}
bool green_is_max( const faint::Color& c ){
return c.g >= c.r && c.g >= c.b;
}
bool blue_is_max( const faint::Color& c ){
return c.b >= c.r && c.b >= c.g;
}
int color_max( const faint::Color& c ){
return std::max(std::max(c.r, c.g), c.b);
}
int color_min( const faint::Color& c ){
return std::min(std::min(c.r, c.g), c.b);
}
double get_hp( const faint::Color& color, const double C ){
int r = color.r;
int g = color.g;
int b = color.b;
if ( red_is_max(color) ){
return (g - b) / C + 6;
}
else if ( green_is_max(color) ){
return (b - r) / C + 2;
}
else if ( blue_is_max(color) ){
return ( r - g ) / C + 4;
}
assert(false);
return 0;
}
int get_hue( const faint::Color& color ){
const int M = color_max(color);
const int m = color_min(color);
const double C = M - m;
if ( C == 0 ){
// Undefined
return 0;
}
double hp = get_hp( color, C );
const double h = 60 * hp;
return int((h / 360.0) * 240 + 0.5) % 240;
}
int get_lightness( const faint::Color& c ){
const int M = color_max(c);
const int m = color_min(c);
return static_cast<int>(((( M + m ) / 2.0) / 255.0) * 240);
}
double get_raw_lightness( const faint::Color& c ){
const int M = color_max(c);
const int m = color_min(c);
return ( M + m ) / 2.0;
}
int get_saturation( const faint::Color& color ){
const int M = color_max(color);
const int m = color_min(color);
double C = M - m;
if ( C == 0 ){
return 0;
}
return static_cast<int>((C / (240 - std::abs(2 * get_lightness(color) - 240))) * 240);
}
| [
"[email protected]"
] | |
91b3eefd3a910f74cb46a79bffa99f1492979161 | d8effd075768aecbf0a590804e6c94127954d01c | /src/GameManager.h | 7b8042c1641af5a1b201c37a68d8bacb30388399 | [] | no_license | nozgames/noz-cpp | 55c88e0ea92408433ca34399f31007418d46a063 | 0466c938f54edf846c01dd195ce870b366821e99 | refs/heads/master | 2022-11-24T04:20:51.348835 | 2020-07-30T21:42:48 | 2020-07-30T21:42:48 | 283,881,452 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,290 | h | ///////////////////////////////////////////////////////////////////////////////
// Troglobite
// Copyright (C) 2015 NoZ Games, LLC
// http://www.nozgames.com
///////////////////////////////////////////////////////////////////////////////
#ifndef __FarmerZ_MainMenu_h__
#define __FarmerZ_MainMenu_h__
namespace FarmerZ {
class GameManager : public noz::Behavior {
NOZ_OBJECT()
private: NOZ_PROPERTY(Name=PlayButton) noz::ObjectPtr<noz::Button> play_button_;
private: NOZ_PROPERTY(Name=PlayButtonSound) noz::ObjectPtr<noz::AudioClip> play_button_sound_;
private: NOZ_PROPERTY(Name=Board) noz::ObjectPtr<noz::Node> board_;
private: NOZ_PROPERTY(Name=Animals) std::vector<noz::ObjectPtr<noz::Prefab>> animals_;
private: static GameManager* this_;
public: GameManager (void);
public: ~GameManager (void);
public: static void TransitionIn (void);
public: static void TransitionOut (void);
public: virtual void OnStart (void) override;
public: virtual void OnUpdate (void) override;
private: void OnPlayButton (UINode*);
private: NOZ_METHOD() void StateResetGame (void);
private: NOZ_METHOD() void StateStartGame (void);
private: void ResetBoard (void);
};
} // namespace FarmerZ
#endif //__FarmerZ_MainMenu_h__
| [
"[email protected]"
] | |
b4f4a0e14609ec1f5431fdf0703922173f69c236 | 08562491f9f7c1b3c259e5d32f24c43f34d5dfbf | /src/qt/recentrequeststablemodel.h | ec08a6ec68792c46c8b774f116494eb23172d22e | [
"MIT"
] | permissive | VoytekBear/CMTR | cf618a50c61eb27320ed89d056ed58ac0e49cb0b | f448cf4ba8d3209032ae05bba65a077e753d6d3f | refs/heads/master | 2021-01-02T00:10:57.680686 | 2019-05-21T13:40:19 | 2019-05-21T13:40:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,314 | h | // Copyright (c) 2011-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_QT_RECENTREQUESTSTABLEMODEL_H
#define BITCOIN_QT_RECENTREQUESTSTABLEMODEL_H
#include "walletmodel.h"
#include <QAbstractTableModel>
#include <QDateTime>
#include <QStringList>
class CWallet;
class RecentRequestEntry
{
public:
RecentRequestEntry() : nVersion(RecentRequestEntry::CURRENT_VERSION), id(0) {}
static const int CURRENT_VERSION = 1;
int nVersion;
int64_t id;
QDateTime date;
SendCoinsRecipient recipient;
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
unsigned int nDate = date.toTime_t();
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(id);
READWRITE(nDate);
READWRITE(recipient);
if (ser_action.ForRead())
date = QDateTime::fromTime_t(nDate);
}
};
class RecentRequestEntryLessThan
{
public:
RecentRequestEntryLessThan(int nColumn, Qt::SortOrder fOrder) : column(nColumn), order(fOrder) {}
bool operator()(RecentRequestEntry& left, RecentRequestEntry& right) const;
private:
int column;
Qt::SortOrder order;
};
/** Model for list of recently generated payment requests / coinmegatrend: URIs.
* Part of wallet model.
*/
class RecentRequestsTableModel : public QAbstractTableModel
{
Q_OBJECT
public:
explicit RecentRequestsTableModel(CWallet* wallet, WalletModel* parent);
~RecentRequestsTableModel();
enum ColumnIndex {
Date = 0,
Label = 1,
Message = 2,
Amount = 3,
NUMBER_OF_COLUMNS
};
/** @name Methods overridden from QAbstractTableModel
@{*/
int rowCount(const QModelIndex& parent) const;
int columnCount(const QModelIndex& parent) const;
QVariant data(const QModelIndex& index, int role) const;
bool setData(const QModelIndex& index, const QVariant& value, int role);
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
QModelIndex index(int row, int column, const QModelIndex& parent) const;
bool removeRows(int row, int count, const QModelIndex& parent = QModelIndex());
Qt::ItemFlags flags(const QModelIndex& index) const;
/*@}*/
const RecentRequestEntry& entry(int row) const { return list[row]; }
void addNewRequest(const SendCoinsRecipient& recipient);
void addNewRequest(const std::string& recipient);
void addNewRequest(RecentRequestEntry& recipient);
public slots:
void sort(int column, Qt::SortOrder order = Qt::AscendingOrder);
void updateDisplayUnit();
private:
WalletModel* walletModel;
QStringList columns;
QList<RecentRequestEntry> list;
int64_t nReceiveRequestsMaxId;
/** Updates the column title to "Amount (DisplayUnit)" and emits headerDataChanged() signal for table headers to react. */
void updateAmountColumnTitle();
/** Gets title for amount column including current display unit if optionsModel reference available. */
QString getAmountTitle();
};
#endif // BITCOIN_QT_RECENTREQUESTSTABLEMODEL_H
| [
"[email protected]"
] | |
015b4e566f909e50764c26dd88e366533ffb86eb | a826f4b3d83ee797f017acdb16d96fa62ce85e63 | /openjtalk/open_jtalk-1.05/mecab/src/learner_node.h | 60db65065e840641947641c75a2ef249e4c85c26 | [
"BSD-3-Clause"
] | permissive | hecomi/node-openjtalk-waf | 831ae200db1b8483ffd4b638b478fb6c1e811395 | a250531bab4401b64ae6acbfdff887980bc3fb1e | refs/heads/master | 2021-01-20T01:57:43.108574 | 2012-05-22T17:25:56 | 2012-05-22T17:25:56 | 4,409,570 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,049 | h | // MeCab -- Yet Another Part-of-Speech and Morphological Analyzer
//
//
// Copyright(C) 2001-2006 Taku Kudo <[email protected]>
// Copyright(C) 2004-2006 Nippon Telegraph and Telephone Corporation
#ifndef MECAB_LEARNER_NODE_H
#define MECAB_LEARNER_NODE_H
#include <cstring>
#include "mecab.h"
#include "common.h"
#include "utils.h"
namespace MeCab {
template <class T1, class T2> T1 repeat_find_if(T1 b, T1 e,
const T2& v, size_t n) {
T1 r = b;
for (size_t i = 0; i < n; ++i) {
r = std::find(b, e, v);
if (r == e) return e;
b = r + 1;
}
return r;
}
// NOTE: first argment: answer,
// second argment: system output
inline bool node_cmp_eq(const LearnerNode &node1,
const LearnerNode &node2,
size_t size, size_t unk_size) {
if (node1.length == node2.length &&
strncmp(node1.surface, node2.surface, node1.length) == 0) {
const char *p1 = node1.feature;
const char *p2 = node2.feature;
// There is NO case when node1 becomes MECAB_UNK_NODE
if (node2.stat == MECAB_UNK_NODE)
size = unk_size; // system cannot output other extra information
const char *r1 = repeat_find_if(p1, p1 + std::strlen(p1), ',', size);
const char *r2 = repeat_find_if(p2, p2 + std::strlen(p2), ',', size);
if (static_cast<size_t>(r1 - p1) == static_cast<size_t>(r2 - p2) &&
std::strncmp(p1, p2, static_cast<size_t>(r1 - p1)) == 0) {
return true;
}
}
return false;
}
inline bool is_empty(LearnerPath *path) {
return((!path->rnode->rpath && path->rnode->stat != MECAB_EOS_NODE) ||
(!path->lnode->lpath && path->lnode->stat != MECAB_BOS_NODE) );
}
inline void calc_expectation(LearnerPath *path, double *expected, double Z) {
if ( is_empty(path) ) return;
double c = std::exp(path->lnode->alpha +
path->cost +
path->rnode->beta - Z);
for (const int *f = path->fvector; *f != -1; ++f) {
expected[*f] += c;
}
if (path->rnode->stat != MECAB_EOS_NODE) {
for (const int *f = path->rnode->fvector; *f != -1; ++f) {
expected[*f] += c;
}
}
}
inline void calc_online_update(LearnerPath *path, double *expected) {
if ( is_empty(path) ) return;
for (const int *f = path->fvector; *f != -1; ++f) {
expected[*f] += 1.0;
}
if (path->rnode->stat != MECAB_EOS_NODE) {
for (const int *f = path->rnode->fvector; *f != -1; ++f) {
expected[*f] += 1.0;
}
}
}
inline void calc_alpha(LearnerNode *n) {
n->alpha = 0.0;
for (LearnerPath *path = n->lpath; path; path = path->lnext)
n->alpha = logsumexp(n->alpha,
path->cost + path->lnode->alpha,
path == n->lpath);
}
inline void calc_beta(LearnerNode *n) {
n->beta = 0.0;
for (LearnerPath *path = n->rpath; path; path = path->rnext)
n->beta = logsumexp(n->beta,
path->cost + path->rnode->beta,
path == n->rpath);
}
}
#endif
| [
"[email protected]"
] | |
11e9ea516cafb9b4d52dc0c983dbd8ff042a5f2b | 0080621ed911e10e92e12b59105ff3124fcd488c | /Homework/Assignment5/Assignment5_ewsc/Inventory.h | e3b789d7d6fa030f97a6125277f525c6b10e762c | [] | no_license | jthomas88/SPR17_CSC-17A | c7a724d774865c9ccf8e08bc49210c12ced02528 | c6badcf456cfbf1c7c9c0e90484d8147934e4f98 | refs/heads/master | 2021-01-21T09:02:41.843869 | 2017-05-17T01:28:01 | 2017-05-17T01:28:01 | 82,848,918 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 772 | h | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: Date.h
* Author: Jeff
*
* Created on May 3, 2017, 4:26 PM
*/
#ifndef INVENTORY_H
#define INVENTORY_H
#include <string>
using std::string;
class Inventory{
public:
//Constructor
Inventory();
//Setters
void setItem(int);
void setQty(int);
void setCost(float);
void setTtl();
//Getters
int getItem();
int getQty();
float getCost();
float getTtl();
private:
int item; //Item number
int qty; //Item quantity
float cost; //Cost per unit
float total; //Total cost
};
#endif /* INVENTORY_H */
| [
"[email protected]"
] | |
5edbe83e36702412d5a2e2476d4924fdf67de918 | 4b6ce43190821ec99aca27bbca1ccb4994dba977 | /animus-2/keyboard-specific-builds/terminus-mini/animus/animus.ino | 63d6e37d11e41eed75d2aae4bf429b0e2556e1ce | [
"Apache-2.0"
] | permissive | BlackCapCoder/animus-family | 9393036e5b0f79ba80a3939629c9624e5c30e86d | 6ff8b4239e85ffbab08347a51e6c9a13cd99153b | refs/heads/master | 2020-04-24T00:49:23.897141 | 2019-02-28T13:12:45 | 2019-02-28T13:12:45 | 171,577,222 | 0 | 0 | null | 2019-02-20T01:15:54 | 2019-02-20T01:15:54 | null | UTF-8 | C++ | false | false | 609 | ino | #define builder_row 4
#define builder_col 12
#define builder_kbname "Terminus Mini"
#define builder_kbvariant "Terminus Mini"
#define builder_kbdriver "Animus Innova x2.7.1"
#define builder_kbdriver_build "OEM"
#define builder_vpins 9, 8, 7, 6
#define builder_hpins A3, A2, A0, A1, 14, 15, 10, 16, 2, 3, 4, 5
#define builder_refresh 1
#include "EEPROM.h"
#include "KeyboardInterface.h"
// constants: change this only to edit keyboard info
const byte ROW = builder_row;
const byte COL = builder_col;
byte VPins[ROW] = {builder_vpins};
byte HPins[COL] = {builder_hpins};
byte RefreshDelay = builder_refresh;
| [
"[email protected]"
] | |
32a78e43a37676e03d83026c4846c2d6ad5fd7d5 | 756ddb3e7c098fda83a3578ab06f28b1749df06d | /After Mid-Exam Fall'2016/28 program/problem 13.cpp | 51ea11bde90ed9b2610080985125fda7ac7adb1c | [] | no_license | MrArman117/These-code-on-C-plus-plus-programming-language | 8b9fa990252d7e9726f3865ef43b8b4e18e79d99 | fe4bd7f49c209b156660ddab435aa3de24897a94 | refs/heads/master | 2020-04-10T18:54:08.088061 | 2019-01-04T06:41:06 | 2019-01-04T06:41:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 960 | cpp | ///Problem number 13
Consider the definition of the following class:
class Sample
{
private:
int x;
double y;
public :
Sample(); ///Constructor 1
Sample(int); ///Constructor 2
Sample(int, int); ///Constructor 3
Sample(int, double); ///Constructor 4
};
i. Write the definition of the constructor 1 so that the private member variables are initialized to 0.
ii. Write the definition of the constructor 2 so that the private member variable x is initialized according to the value of the parameter, and the private member variable y is initialized to 0.
iii. Write the definition of the constructors 3 and 4 so that the private member variables are initialized according to the values of the parameters.*/
Answer:
i.
Sample :: Sample()
{
x = 0;
y = 0;
}
ii.
Sample :: Sample(int a)
{
x = a;
y = 0;
}
iii.
Sample :: Sample(int a, int b)
{
x = a;
y = b;
}
Sample :: Sample(int a, double b)
{
x = a;
y = b;
}
| [
"[email protected]"
] | |
5994ba8a668bafa14e1af93b4639a4fe6d0b6508 | 7f2d4ffcfbd2437ab347adf0bf609acb2c222eb4 | /cl/include/SDK/activprof.h | d6e29391a2f3d3c3dcd3df0e783485389ed96163 | [] | no_license | mensong/CppScript | d46d5939e8ffad83897b4a28094351093752128c | 622e00b49137caf95812735b5938a794537825dd | refs/heads/master | 2023-06-08T11:16:47.076693 | 2023-05-28T04:35:25 | 2023-05-28T04:35:25 | 166,553,412 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 12,890 | h |
/* this ALWAYS GENERATED file contains the definitions for the interfaces */
/* File created by MIDL compiler version 7.00.0555 */
/* Compiler settings for activprof.idl:
Oicf, W1, Zp8, env=Win32 (32b run), target_arch=X86 7.00.0555
protocol : dce , ms_ext, c_ext, robust
error checks: allocation ref bounds_check enum stub_data
VC __declspec() decoration level:
__declspec(uuid()), __declspec(selectany), __declspec(novtable)
DECLSPEC_UUID(), MIDL_INTERFACE()
*/
/* @@MIDL_FILE_HEADING( ) */
#pragma warning( disable: 4049 ) /* more than 64k source lines */
/* verify that the <rpcndr.h> version is high enough to compile this file*/
#ifndef __REQUIRED_RPCNDR_H_VERSION__
#define __REQUIRED_RPCNDR_H_VERSION__ 475
#endif
/* verify that the <rpcsal.h> version is high enough to compile this file*/
#ifndef __REQUIRED_RPCSAL_H_VERSION__
#define __REQUIRED_RPCSAL_H_VERSION__ 100
#endif
#include "rpc.h"
#include "rpcndr.h"
#ifndef __RPCNDR_H_VERSION__
#error this stub requires an updated version of <rpcndr.h>
#endif // __RPCNDR_H_VERSION__
#ifndef COM_NO_WINDOWS_H
#include "windows.h"
#include "ole2.h"
#endif /*COM_NO_WINDOWS_H*/
#ifndef __activprof_h__
#define __activprof_h__
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
/* Forward Declarations */
#ifndef __IActiveScriptProfilerControl_FWD_DEFINED__
#define __IActiveScriptProfilerControl_FWD_DEFINED__
typedef interface IActiveScriptProfilerControl IActiveScriptProfilerControl;
#endif /* __IActiveScriptProfilerControl_FWD_DEFINED__ */
#ifndef __IActiveScriptProfilerCallback_FWD_DEFINED__
#define __IActiveScriptProfilerCallback_FWD_DEFINED__
typedef interface IActiveScriptProfilerCallback IActiveScriptProfilerCallback;
#endif /* __IActiveScriptProfilerCallback_FWD_DEFINED__ */
/* header files for imported files */
#include "unknwn.h"
#ifdef __cplusplus
extern "C"{
#endif
/* interface __MIDL_itf_activprof_0000_0000 */
/* [local] */
//=--------------------------------------------------------------------------=
// ActivProf.h
//=--------------------------------------------------------------------------=
// (C) Copyright 2000 Microsoft Corporation. All Rights Reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//=--------------------------------------------------------------------------=
//
#pragma comment(lib,"uuid.lib")
//
// Declarations for ActiveX Scripting profiling.
//
const HRESULT ACTIVPROF_E_PROFILER_PRESENT = MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0200);
const HRESULT ACTIVPROF_E_PROFILER_ABSENT = MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0201);
const HRESULT ACTIVPROF_E_UNABLE_TO_APPLY_ACTION = MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0202);
#ifndef __ActivProf_h
#define __ActivProf_h
typedef /* [public][public] */
enum __MIDL___MIDL_itf_activprof_0000_0000_0001
{ PROFILER_SCRIPT_TYPE_USER = 0,
PROFILER_SCRIPT_TYPE_DYNAMIC = ( PROFILER_SCRIPT_TYPE_USER + 1 ) ,
PROFILER_SCRIPT_TYPE_NATIVE = ( PROFILER_SCRIPT_TYPE_DYNAMIC + 1 )
} PROFILER_SCRIPT_TYPE;
typedef /* [public] */
enum __MIDL___MIDL_itf_activprof_0000_0000_0002
{ PROFILER_EVENT_MASK_TRACE_SCRIPT_FUNCTION_CALL = 0x1,
PROFILER_EVENT_MASK_TRACE_NATIVE_FUNCTION_CALL = 0x2,
PROFILER_EVENT_MASK_TRACE_ALL = ( PROFILER_EVENT_MASK_TRACE_SCRIPT_FUNCTION_CALL | PROFILER_EVENT_MASK_TRACE_NATIVE_FUNCTION_CALL )
} PROFILER_EVENT_MASK;
typedef LONG PROFILER_TOKEN;
extern RPC_IF_HANDLE __MIDL_itf_activprof_0000_0000_v0_0_c_ifspec;
extern RPC_IF_HANDLE __MIDL_itf_activprof_0000_0000_v0_0_s_ifspec;
#ifndef __IActiveScriptProfilerControl_INTERFACE_DEFINED__
#define __IActiveScriptProfilerControl_INTERFACE_DEFINED__
/* interface IActiveScriptProfilerControl */
/* [unique][uuid][object] */
EXTERN_C const IID IID_IActiveScriptProfilerControl;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("784b5ff0-69b0-47d1-a7dc-2518f4230e90")
IActiveScriptProfilerControl : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE StartProfiling(
/* [in] */ __RPC__in REFCLSID clsidProfilerObject,
/* [in] */ DWORD dwEventMask,
/* [in] */ DWORD dwContext) = 0;
virtual HRESULT STDMETHODCALLTYPE SetProfilerEventMask(
/* [in] */ DWORD dwEventMask) = 0;
virtual HRESULT STDMETHODCALLTYPE StopProfiling(
/* [in] */ HRESULT hrShutdownReason) = 0;
};
#else /* C style interface */
typedef struct IActiveScriptProfilerControlVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
__RPC__in IActiveScriptProfilerControl * This,
/* [in] */ __RPC__in REFIID riid,
/* [annotation][iid_is][out] */
__RPC__deref_out void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(
__RPC__in IActiveScriptProfilerControl * This);
ULONG ( STDMETHODCALLTYPE *Release )(
__RPC__in IActiveScriptProfilerControl * This);
HRESULT ( STDMETHODCALLTYPE *StartProfiling )(
__RPC__in IActiveScriptProfilerControl * This,
/* [in] */ __RPC__in REFCLSID clsidProfilerObject,
/* [in] */ DWORD dwEventMask,
/* [in] */ DWORD dwContext);
HRESULT ( STDMETHODCALLTYPE *SetProfilerEventMask )(
__RPC__in IActiveScriptProfilerControl * This,
/* [in] */ DWORD dwEventMask);
HRESULT ( STDMETHODCALLTYPE *StopProfiling )(
__RPC__in IActiveScriptProfilerControl * This,
/* [in] */ HRESULT hrShutdownReason);
END_INTERFACE
} IActiveScriptProfilerControlVtbl;
interface IActiveScriptProfilerControl
{
CONST_VTBL struct IActiveScriptProfilerControlVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define IActiveScriptProfilerControl_QueryInterface(This,riid,ppvObject) \
( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )
#define IActiveScriptProfilerControl_AddRef(This) \
( (This)->lpVtbl -> AddRef(This) )
#define IActiveScriptProfilerControl_Release(This) \
( (This)->lpVtbl -> Release(This) )
#define IActiveScriptProfilerControl_StartProfiling(This,clsidProfilerObject,dwEventMask,dwContext) \
( (This)->lpVtbl -> StartProfiling(This,clsidProfilerObject,dwEventMask,dwContext) )
#define IActiveScriptProfilerControl_SetProfilerEventMask(This,dwEventMask) \
( (This)->lpVtbl -> SetProfilerEventMask(This,dwEventMask) )
#define IActiveScriptProfilerControl_StopProfiling(This,hrShutdownReason) \
( (This)->lpVtbl -> StopProfiling(This,hrShutdownReason) )
#endif /* COBJMACROS */
#endif /* C style interface */
#endif /* __IActiveScriptProfilerControl_INTERFACE_DEFINED__ */
#ifndef __IActiveScriptProfilerCallback_INTERFACE_DEFINED__
#define __IActiveScriptProfilerCallback_INTERFACE_DEFINED__
/* interface IActiveScriptProfilerCallback */
/* [unique][uuid][object] */
EXTERN_C const IID IID_IActiveScriptProfilerCallback;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("740eca23-7d9d-42e5-ba9d-f8b24b1c7a9b")
IActiveScriptProfilerCallback : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE Initialize(
/* [in] */ DWORD dwContext) = 0;
virtual HRESULT STDMETHODCALLTYPE Shutdown(
/* [in] */ HRESULT hrReason) = 0;
virtual HRESULT STDMETHODCALLTYPE ScriptCompiled(
/* [in] */ PROFILER_TOKEN scriptId,
/* [in] */ PROFILER_SCRIPT_TYPE type,
/* [in] */ __RPC__in_opt IUnknown *pIDebugDocumentContext) = 0;
virtual HRESULT STDMETHODCALLTYPE FunctionCompiled(
/* [in] */ PROFILER_TOKEN functionId,
/* [in] */ PROFILER_TOKEN scriptId,
/* [string][in] */ __RPC__in_string const WCHAR *pwszFunctionName,
/* [string][in] */ __RPC__in_string const WCHAR *pwszFunctionNameHint,
/* [in] */ __RPC__in_opt IUnknown *pIDebugDocumentContext) = 0;
virtual HRESULT STDMETHODCALLTYPE OnFunctionEnter(
/* [in] */ PROFILER_TOKEN scriptId,
/* [in] */ PROFILER_TOKEN functionId) = 0;
virtual HRESULT STDMETHODCALLTYPE OnFunctionExit(
/* [in] */ PROFILER_TOKEN scriptId,
/* [in] */ PROFILER_TOKEN functionId) = 0;
};
#else /* C style interface */
typedef struct IActiveScriptProfilerCallbackVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
__RPC__in IActiveScriptProfilerCallback * This,
/* [in] */ __RPC__in REFIID riid,
/* [annotation][iid_is][out] */
__RPC__deref_out void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(
__RPC__in IActiveScriptProfilerCallback * This);
ULONG ( STDMETHODCALLTYPE *Release )(
__RPC__in IActiveScriptProfilerCallback * This);
HRESULT ( STDMETHODCALLTYPE *Initialize )(
__RPC__in IActiveScriptProfilerCallback * This,
/* [in] */ DWORD dwContext);
HRESULT ( STDMETHODCALLTYPE *Shutdown )(
__RPC__in IActiveScriptProfilerCallback * This,
/* [in] */ HRESULT hrReason);
HRESULT ( STDMETHODCALLTYPE *ScriptCompiled )(
__RPC__in IActiveScriptProfilerCallback * This,
/* [in] */ PROFILER_TOKEN scriptId,
/* [in] */ PROFILER_SCRIPT_TYPE type,
/* [in] */ __RPC__in_opt IUnknown *pIDebugDocumentContext);
HRESULT ( STDMETHODCALLTYPE *FunctionCompiled )(
__RPC__in IActiveScriptProfilerCallback * This,
/* [in] */ PROFILER_TOKEN functionId,
/* [in] */ PROFILER_TOKEN scriptId,
/* [string][in] */ __RPC__in_string const WCHAR *pwszFunctionName,
/* [string][in] */ __RPC__in_string const WCHAR *pwszFunctionNameHint,
/* [in] */ __RPC__in_opt IUnknown *pIDebugDocumentContext);
HRESULT ( STDMETHODCALLTYPE *OnFunctionEnter )(
__RPC__in IActiveScriptProfilerCallback * This,
/* [in] */ PROFILER_TOKEN scriptId,
/* [in] */ PROFILER_TOKEN functionId);
HRESULT ( STDMETHODCALLTYPE *OnFunctionExit )(
__RPC__in IActiveScriptProfilerCallback * This,
/* [in] */ PROFILER_TOKEN scriptId,
/* [in] */ PROFILER_TOKEN functionId);
END_INTERFACE
} IActiveScriptProfilerCallbackVtbl;
interface IActiveScriptProfilerCallback
{
CONST_VTBL struct IActiveScriptProfilerCallbackVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define IActiveScriptProfilerCallback_QueryInterface(This,riid,ppvObject) \
( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )
#define IActiveScriptProfilerCallback_AddRef(This) \
( (This)->lpVtbl -> AddRef(This) )
#define IActiveScriptProfilerCallback_Release(This) \
( (This)->lpVtbl -> Release(This) )
#define IActiveScriptProfilerCallback_Initialize(This,dwContext) \
( (This)->lpVtbl -> Initialize(This,dwContext) )
#define IActiveScriptProfilerCallback_Shutdown(This,hrReason) \
( (This)->lpVtbl -> Shutdown(This,hrReason) )
#define IActiveScriptProfilerCallback_ScriptCompiled(This,scriptId,type,pIDebugDocumentContext) \
( (This)->lpVtbl -> ScriptCompiled(This,scriptId,type,pIDebugDocumentContext) )
#define IActiveScriptProfilerCallback_FunctionCompiled(This,functionId,scriptId,pwszFunctionName,pwszFunctionNameHint,pIDebugDocumentContext) \
( (This)->lpVtbl -> FunctionCompiled(This,functionId,scriptId,pwszFunctionName,pwszFunctionNameHint,pIDebugDocumentContext) )
#define IActiveScriptProfilerCallback_OnFunctionEnter(This,scriptId,functionId) \
( (This)->lpVtbl -> OnFunctionEnter(This,scriptId,functionId) )
#define IActiveScriptProfilerCallback_OnFunctionExit(This,scriptId,functionId) \
( (This)->lpVtbl -> OnFunctionExit(This,scriptId,functionId) )
#endif /* COBJMACROS */
#endif /* C style interface */
#endif /* __IActiveScriptProfilerCallback_INTERFACE_DEFINED__ */
/* interface __MIDL_itf_activprof_0000_0002 */
/* [local] */
#endif // __ActivProf_h
extern RPC_IF_HANDLE __MIDL_itf_activprof_0000_0002_v0_0_c_ifspec;
extern RPC_IF_HANDLE __MIDL_itf_activprof_0000_0002_v0_0_s_ifspec;
/* Additional Prototypes for ALL interfaces */
/* end of Additional Prototypes */
#ifdef __cplusplus
}
#endif
#endif
| [
"[email protected]"
] | |
a61c875cb967eeb1813e7b231ec291d05db520e7 | 15836e69de43a02efbe8f0ce4e07f5274bcb144b | /Send17X.cpp | c0169b0feabf52a6cae6c09714a58749d92e9089 | [] | no_license | sephyroth67/433utils | 47d9768199a880c6680cf4e37ad7d11fc484098f | be5ddfaf16f91793a0a7ca2cea8bc56220e0aaf9 | refs/heads/master | 2021-01-10T04:56:14.348404 | 2015-10-18T19:18:50 | 2015-10-18T19:18:50 | 44,061,010 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,318 | cpp | /*
'codesend' hacked from 'send' by @justy
- The provided rc_switch 'send' command uses the form systemCode, unitCode, command
which is not suitable for our purposes. Instead, we call
send(code, length); // where length is always 24 and code is simply the code
we find using the RF_sniffer.ino Arduino sketch.
Usage: ./codesend decimalcode
(Use RF_Sniffer.ino to check that RF signals are being produced by the RPi's transmitter)
*/
#include "RCSwitch.h"
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
// This pin is not the first pin on the RPi GPIO header!
// Consult https://projects.drogon.net/raspberry-pi/wiringpi/pins/
// for more information.
int PIN = 0;
// Parse the firt parameter to this command as an integer
int code = atoi(argv[1]);
if (wiringPiSetup () == -1) return 1;
printf("sending code[%i]\n", code);
RCSwitch mySwitch = RCSwitch();
mySwitch.enableTransmit(PIN);
// Optional set pulse length.
mySwitch.setPulseLength(175);
// Optional set protocol (default is 1, will work for most outlets)
// mySwitch.setProtocol(2);
// Optional set number of transmission repetitions.
// mySwitch.setRepeatTransmit(15);
mySwitch.send(code, 24);
return 0;
}
| [
"[email protected]"
] | |
49ab277a3459d5740cfe4b401062e20f7627731b | 7cc9e293ebd8430f39c273382c729774135438c6 | /src/ArgsParser.cpp | 0650346c562bbdd1d569abe113cbc29def554566 | [] | no_license | ramiromagalhaes/facefind | 9824ae9014d00e37dc44d10224ce88fb203b4c08 | 3e8ff100c1939445d6301739befc938f0e7327e1 | refs/heads/master | 2020-06-07T12:35:20.192552 | 2012-09-12T01:18:15 | 2012-09-12T01:18:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,007 | cpp | /*
* CommandLineParser.cpp
*
* Created on: 07/09/2012
* Author: ramiro
*/
#include "ArgsParser.h"
ArgsParser::ArgsParser() {
HELP = "help";
DBPATH = "dbpath";
SEARCH = "search";
INITDB = "initdb";
SINGLE_IMG_EVAL = "eval";
}
Operation* ArgsParser::parse(int argc, char** argv) {
po::options_description desc("Program arguments");
desc.add_options()
(HELP, "This message.")
(SINGLE_IMG_EVAL, po::value<string>(), "Evaluates a single image without adding it to the database.")
(DBPATH, po::value<string>(), "The image database directory. This is mandatory for database operations.")
(SEARCH, po::value<int>(), "Searches the database located at <dbpath>.")
(INITDB, "Initializes the database with images located at <dbpath>.")
; //a bizarre usage of operator parentheses
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
ProgramParameters params;
//if SINGLE_IMG_EVAL argument was provided, ignore all other arguments.
if ( vm.count(SINGLE_IMG_EVAL) ) {
//TODO test if parameter was also provided.
params.imgpath = vm[SINGLE_IMG_EVAL].as<string>();
return new SingleImageEval(params);
}
//from now on, dbpath is a mandatory argument.
if ( !vm.count(DBPATH) ) {
cout << desc << endl;
throw 1;
}
//one of the following arguments is mandatory: initdb or search.
if ( !(vm.count(INITDB) || vm.count(SEARCH)) ) {
cout << "You must choose either to initialize the database or to search it." << endl;
throw 2;
}
//TODO test if parameter was provided.
params.dbpath = vm[DBPATH].as<string>();
if ( vm.count(INITDB) ) {
return new InitializeDatabase(params);
}
if ( vm.count(SEARCH) ) {
//TODO test if parameter was provided.
params.searchParam = vm[SEARCH].as<int>();
return new SearchDatabase(params);
}
assert(true);
throw -1; //should never reach this line...
}
| [
"[email protected]"
] | |
a0b3aeacbb8521caf72edf1f4d92881a3f72aae2 | 1e6e98f2a25caf35fa52e9ed751820b874d1912f | /include/mos/aud/buffer.hpp | 95b3f757e982949263d30d151e537e90131c205d | [
"MIT"
] | permissive | thom-bahm/mos | ee421f57d82c1a16fc3f993fe8583031ab94a97d | 9f1e1e32d2ba28908abc687efbd0cb3c42487328 | refs/heads/master | 2021-01-03T03:22:54.723808 | 2020-02-11T17:40:28 | 2020-02-11T17:40:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,386 | hpp | #pragma once
#include <atomic>
#include <string>
#include <memory>
#include <vector>
namespace mos {
namespace aud {
class Buffer;
using Shared_buffer = std::shared_ptr<Buffer>;
/** 16bit integer audio buffer. */
class Buffer final {
public:
using Samples = std::vector<short>;
template<class T>
/** Construct buffer from a container of shorts. */
Buffer(const T begin, const T end, const int channels = 1,
const unsigned int sample_rate = 44100u)
: channels_(channels), sample_rate_(sample_rate),
samples_(begin, end), id_(current_id_++) {}
/** Empty buffer constructor. */
explicit Buffer(int channels = 1, int sample_rate = 44100);
/** Construct from *.ogg file. */
explicit Buffer(const std::string &path);
/** Load shared buffer. */
static Shared_buffer load(const std::string &path);
Samples::const_iterator begin() const;
Samples::const_iterator end() const;
/** Raw data. */
const short *data() const;
/** Unique id. */
unsigned int id() const;
/** Get number of channels. */
int channels() const;
/** Get sample rate */
int sample_rate() const;
/** Duration in seconds. */
float duration() const;
/** Size of samples container. */
size_t size() const;
private:
static std::atomic_uint current_id_;
unsigned int id_;
Samples samples_;
int channels_;
int sample_rate_;
};
}
}
| [
"[email protected]"
] | |
b9ae6df78f41fe021b034b184facd496d0eed3b2 | 8eb458f2c3e7794ed405a8f2ea0eb3bad343bb07 | /c++面向对象/B0205.cpp | 73431932e57fbd445314b3925f8ef51907a8b7da | [] | no_license | cn-cs-S/cs_s | d8ffc8c5d38b72f319d807b8813570991761b8a1 | e8a32bde55f966f961d84603d3a15ec0e34414a6 | refs/heads/main | 2023-08-22T16:49:09.869172 | 2021-10-31T09:36:01 | 2021-10-31T09:36:01 | 321,030,567 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 371 | cpp | #include<iostream>
#include<iomanip>
double function(int n) {
double first = 1, second = 2;
double sum = 0;
for (int i = 0; i < n; i++)
{
sum += second / first;
second = first + second;
first = second - first;
}
return sum;
}
int main(){
int n;
std::cin >> n;
std::printf("%.2lf",function(n));
return 0;
} | [
"[email protected]"
] | |
aaa9dfe0043d892048f81a3f87d2b1fa174a2413 | 8aa739ac56b0bdd6afe24bbb23a5106053b7bd7b | /QT_Project_Mensche_Aergere_dich_nicht/piece_player_class.h | d059d1273cdefe30bca9d0cff04598597bc8c934 | [] | no_license | marina13594/NETB375_Mensche_aergere_dich_nicht | 7517b66b9fab607a22e8275aff4fa793f6b8386b | 7b4af8b2a23a12b8bb40d24bb6912148f619bd44 | refs/heads/master | 2020-12-31T01:48:20.375401 | 2014-12-03T11:15:32 | 2014-12-03T11:15:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,678 | h | #ifndef __PIECE_PLAYER_CLASS_H_INCLUDED__
#define __PIECE_PLAYER_H_INCLUDED__
#include <iostream>
#include <string>
using namespace std;
class Piece // 4 pieces per player,
{
private:
int piece_id; // 1-4 identifies the pieces
int piece_player_id; // 1-4 depending which player the piece belongs to
int moves; // 0-43, number of moves taken so far, when = 39, the piece is on finish position
int home_moves; // 1-4
public:
Piece(int input_piece_id, int input_piece_player_id);
int get_piece_id();
int get_piece_player_id();
int get_piece_moves();
bool is_piece_home();
};
class Player // holds player properties
{
private:
struct Home_node{
Piece* home_occupied_piece;
Home_node(){
home_occupied_piece = NULL;
}
};
string name;
int ID; // 1-4, decides turns and other events
int start_move; // starting position on field, node ID
int finish_move;// finish position on field, node ID
bool is_bot;
int active_player_pieces;
public:
Piece* piece_list[4];
Home_node* home_node_list[4];
bool home_score[4];
Player(string input_name, int input_ID, bool bot);
~Player();
string get_name();
int get_player_id();
int get_player_start();
int get_player_finish();
bool is_player_bot();
bool is_player_active();
int get_piece_current_node_id(int piece_id);// calculates pieces current node id by combining number of moves made and starting node ID
// modulus division by 39 (number of nodes) gives us the correct ID of the node
void update_score();
bool is_player_win();
void add_to_name(int x);
};
#endif
| [
"[email protected]"
] | |
b054440ace069e9c6d047d9423a4a6d91f2ddd31 | 41b4adb10cc86338d85db6636900168f55e7ff18 | /aws-cpp-sdk-iam/include/aws/iam/model/AssignmentStatusType.h | 6d12a3e96456ef42d74dabb8a2bea0a82c8e8a5f | [
"JSON",
"MIT",
"Apache-2.0"
] | permissive | totalkyos/AWS | 1c9ac30206ef6cf8ca38d2c3d1496fa9c15e5e80 | 7cb444814e938f3df59530ea4ebe8e19b9418793 | refs/heads/master | 2021-01-20T20:42:09.978428 | 2016-07-16T00:03:49 | 2016-07-16T00:03:49 | 63,465,708 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,128 | h | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/iam/IAM_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
namespace Aws
{
namespace IAM
{
namespace Model
{
enum class AssignmentStatusType
{
NOT_SET,
Assigned,
Unassigned,
Any
};
namespace AssignmentStatusTypeMapper
{
AWS_IAM_API AssignmentStatusType GetAssignmentStatusTypeForName(const Aws::String& name);
AWS_IAM_API Aws::String GetNameForAssignmentStatusType(AssignmentStatusType value);
} // namespace AssignmentStatusTypeMapper
} // namespace Model
} // namespace IAM
} // namespace Aws
| [
"[email protected]"
] | |
71eb4255b4f562f575d90f3e1a1aa61a3d0ca155 | 47987b94060d8290aff1e5400ba3101cc3b1153b | /alam_cpp_files/compcorr2.cpp | e426d837c8860e0584ded5dc837b356c357f302c | [] | no_license | TCNJ-ECE-IMPL/tissue_elastography | cbdec6c903c0dfa442ab82ef9a3357e9b350b0fa | f6586dda0c58f2ebd7546d4652106ac40e5c659f | refs/heads/master | 2021-05-26T11:39:43.182962 | 2020-05-28T17:44:18 | 2020-05-28T17:44:18 | 254,116,492 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,729 | cpp | #include "mex.h"
#include <math.h>
#include <string.h>
// ALL ARRAYS INITIALIZED USING "new". THUS, ALL 2-D ARRAYS ARE SIMULATED WITH 1D ARRAYS.
// VERSION 2.2: Correlation function numerator and denominator are computed without creating
// new variables (e.g., Xs, Ys, XsSQ, YsSQ, XsYs) for faster execution
// PROTOTYPE DECLARATIONS
double sum(double X[], int LenX);
void Intersect(const int Xix[], int LenX, const int Yix[], int LenY, long &Ix_i, int &Ix_e);
void CompCorr2(double *C, const double *X, int mX, int nX, const double *Y, int mY, int nY,
int MXR, int MXC, int MNR, int MNC, char *Option);
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]);
inline double square(double x) { return x * x; }
inline int square(int x) { return x * x; }
inline double product(double x, double y) { return x * y; }
inline int product(int x, int y) { return x * y; }
// COMPUTE THE SUM OF ELEMENTS
double sum(double X[], int LenX) {
double S=0;
for (int k=0; k<LenX; k++)
S += X[k];
return S;
}
// FIND INTERSECTION BETWEEN ARRAY INDICES
// Alternatively, intersect.m can be compiled with -ire option, but less desirable
void Intersect(const int Xix[], int LenX, const int Yix[], int LenY, long &Ix_i, int &Ix_e) {
if (Xix[0] > Yix[LenY-1]) { // No intersection
Ix_i = -2147483647; // To denote this to be a useless index
return;
}
else if (Xix[LenX-1] < Yix[0]) { // No intersection
Ix_i = -2147483647; // To denote this to be a useless index
return;
}
else if (Xix[0] > Yix[0]) {
if (Xix[LenX-1] > Yix[LenY-1]) {
Ix_i = Xix[0];
Ix_e = Yix[LenY-1];
}
else {
Ix_i = Xix[0];
Ix_e = Xix[LenX-1];
}
}
else {
if (Xix[LenX-1] > Yix[LenY-1]) {
Ix_i = Yix[0];
Ix_e = Yix[LenY-1];
}
else {
Ix_i = Yix[0];
Ix_e = Xix[LenX-1];
}
}
}
// COMPUTE CORRELATION FUNCTIONS
void CompCorr2(double *C, const double *X, int mX, int nX, const double *Y, int mY, int nY,
int MXR, int MXC, int MNR, int MNC, char *Option) {
int mC = MXR-MNR+1; // #Rows in C
int nC = MXC-MNC+1; // #Columns in C
int k,l,m,n;
for (k = 0; k < mC; k++)
for (l = 0; l < nC; l++)
*(C+k+l*mC) = 0;
//DECLARATION OF CONSTANT SIZE ARRAYS THAT WILL BE USED MANY TIMES
int * XixR = new int [mX]; // Row indices of X arrays
int * YixR = new int [mY]; // Row indices of Y arrays
int * XixC = new int [nX]; // Row indices of X arrays
int * YixC = new int [nY]; // Row indices of Y arrays
double norm_fac;
long IxR_i, IxC_i; // beginning of intersection used in the following loops
int IxR_e, IxC_e; // end of intersection
int cff_flg = strcmp(Option,"coeff");
if (cff_flg == 0) { // Correlation coefficient function (normalized)
for (k=MNR; k<=MXR; k++) {
for (l=MNC; l<=MXC; l++) {
// First in the row direction
for (m=0; m<mX; m++) // Row indices of X arrays
XixR[m] = m; // Row indices shifted for corr. computation
for (m=0; m<mY; m++) // Row indices of Y arrays
YixR[m] = m+k;
// find intersection between arrays to locate elements to use
Intersect(XixR, mX, YixR, mY, IxR_i, IxR_e);
// Now in the column direction
for (m=0; m<nX; m++) // Row indices of X arrays
XixC[m] = m; // Row indices shifted for corr. computation
for (m=0; m<nY; m++) // Row indices of Y arrays
YixC[m] = m+l;
// find intersection between arrays to locate elements to use
Intersect(XixC, nX, YixC, nY, IxC_i, IxC_e);
if (IxC_i != -2147483647 && IxR_i != -2147483647) { // Intersection between X and Y exists
int ItsctLenR = IxR_e-IxR_i+1;
int ItsctLenC = IxC_e-IxC_i+1;
// First, the numerator of the normalized correlation function at delay (k,l)
double dnum = 0;
for (m=0; m<=ItsctLenR-1; m++)
for (n=0; n<=ItsctLenC-1; n++)
dnum += product(X[(IxR_i + m)+(IxC_i + n)*mX],Y[(IxR_i + m - k)+(IxC_i + n - l)*mY]);
// X elements to be used in corr comp: X[(IxR_i + m)+(IxC_i + n)*mX]
// Y elements to be used in corr comp: Y[(IxR_i + m - k)+(IxC_i + n - l)*mY];
// Now, the denominator of the denominator correlation function at delay (k,l)
double ddenX = 0;
double ddenY = 0;
for (m=0; m<=ItsctLenR-1; m++) {
for (n=0; n<=ItsctLenC-1; n++) {
ddenX += square(X[(IxR_i + m)+(IxC_i + n)*mX]);
ddenY += square(Y[(IxR_i + m - k)+(IxC_i + n - l)*mY]);
}
}
double dden = sqrt(ddenX*ddenY);
// sqrt(ddenX*ddenY) is denominator
if (dden == 0)
*(C+(k-MNR)+(l-MNC)*mC) = 0;
else
*(C+(k-MNR)+(l-MNC)*mC) = dnum/dden;
}
}
}
}
else { // Unnormalized correlation function
for (k=MNR; k<=MXR; k++) {
for (l=MNC; l<=MXC; l++) {
// First in the row direction
for (m=0; m<mX; m++) // Row indices of X arrays
XixR[m] = m; // Row indices shifted for corr. computation
for (m=0; m<mY; m++) // Row indices of Y arrays
YixR[m] = m+k;
// find intersection between arrays to locate elements to use
Intersect(XixR, mX, YixR, mY, IxR_i, IxR_e);
// Now in the column direction
for (m=0; m<nX; m++) // Row indices of X arrays
XixC[m] = m; // Row indices shifted for corr. computation
for (m=0; m<nY; m++) // Row indices of Y arrays
YixC[m] = m+l;
// find intersection between arrays to locate elements to use
Intersect(XixC, nX, YixC, nY, IxC_i, IxC_e);
if (IxC_i != -2147483647 && IxR_i != -2147483647) { // Intersection between X and Y exists
int ItsctLenR = IxR_e-IxR_i+1;
int ItsctLenC = IxC_e-IxC_i+1;
double dsum = 0;
for (m=0; m<=ItsctLenR-1; m++)
for (n=0; n<=ItsctLenC-1; n++)
dsum += product(X[(IxR_i + m)+(IxC_i + n)*mX],Y[(IxR_i + m - k)+(IxC_i + n - l)*mY]);
// X elements to be used in corr comp: X[(IxR_i + m)+(IxC_i + n)*mX]
// Y elements to be used in corr comp: Y[(IxR_i + m - k)+(IxC_i + n - l)*mY]
// dsum is unnormalized correlation function at delay (k,l)
*(C+(k-MNR)+(l-MNC)*mC) = dsum;
}
}
}
}
// FREE MEMORY ASSIGNED AT THE BEGINNING
delete [] XixR;
XixR = NULL;
delete [] YixR;
YixR = NULL;
delete [] XixC;
XixC = NULL;
delete [] YixC;
YixC = NULL;
return;
}
// THE REQUIRED GATEWAY ROUTINE: mexFunction.
// THE NEXT FOUR LINES ARE THE REQUIRED ARGUMENTS.
void mexFunction(int nlhs,
mxArray *plhs[],
int nrhs,
const mxArray *prhs[]) {
double *C; // output
// rest are inputs
const double *X;
const double *Y;
double MXR;
double MXC;
double MNR;
double MNC;
// add check for proper number of arguments
// add check for proper type of arguments
int mX = mxGetM(prhs[0]);
int nX = mxGetN(prhs[0]);
X = mxGetPr(prhs[0]);
int mY = mxGetM(prhs[1]);
int nY = mxGetN(prhs[1]);
Y = mxGetPr(prhs[1]);
MXR = mxGetScalar(prhs[2]);
MXC = mxGetScalar(prhs[3]);
MNR = mxGetScalar(prhs[4]);
MNC = mxGetScalar(prhs[5]);
// Now convert 'Option' to a C++ string
int Olen = (mxGetM(prhs[6]) * mxGetN(prhs[6])) + 1;
char * O = new char [Olen];
if (O == NULL)
mexErrMsgTxt("Not enough heap space for Option.");
// Copy the string data from prhs[6] and place it into O
int status = mxGetString(prhs[6], O, Olen);
if (status != 0)
mexErrMsgTxt("Could not write Option to string.");
// create a double matrix for return argument
int mC = MXR-MNR+1; // #Rows in C
int nC = MXC-MNC+1; // #Columns in C
plhs[0] = mxCreateDoubleMatrix(mC,nC,mxREAL); // First argument, of Size
C = mxGetPr(plhs[0]);
CompCorr2(C, X, mX, nX, Y, mY, nY, int(MXR), int(MXC), int(MNR), int(MNC), O);
delete [] O;
}
| [
"[email protected]"
] | |
c20ba0c47a0c4430faad6de1e5deb1816819631f | 6701eae4550c7cd3d8703565c7be3a5e26248676 | /src/test/base32_tests.cpp | 0a4fd05fdef4626a23f39b673bf31933303600fb | [
"MIT"
] | permissive | stochastic-thread/bootstrapping-ellocash | 91de56a330090c004af31d861e6d4cfb8d8b9e36 | 9495f1e3741c7f893457e4f6602d6ef0d84b7b3d | refs/heads/master | 2021-09-05T05:00:19.403780 | 2018-01-24T08:09:44 | 2018-01-24T08:09:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 922 | cpp | // Copyright (c) 2012-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "test/test_ellocash.h"
#include "utilstrencodings.h"
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(base32_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(base32_testvectors)
{
static const std::string vstrIn[] = {"", "f", "fo", "foo", "foob", "fooba", "foobar"};
static const std::string vstrOut[] = {"", "my======", "mzxq====", "mzxw6===", "mzxw6yq=", "mzxw6ytb", "mzxw6ytboi======"};
for (unsigned int i = 0; i < sizeof(vstrIn) / sizeof(vstrIn[0]); i++) {
std::string strEnc = EncodeBase32(vstrIn[i]);
BOOST_CHECK(strEnc == vstrOut[i]);
std::string strDec = DecodeBase32(vstrOut[i]);
BOOST_CHECK(strDec == vstrIn[i]);
}
}
BOOST_AUTO_TEST_SUITE_END()
| [
"[email protected]"
] | |
7c3fb8b7fb43ce498ef7fa4e042be745abb428b4 | 04230fbf25fdea36a2d473233e45df21b6ff6fff | /1325-C.cpp | 9a99356f50db485784263a9fbba9da202a33177c | [
"MIT"
] | permissive | ankiiitraj/questionsSolved | 48074d674bd39fe67da1f1dc7c944b95a3ceac34 | 8452b120935a9c3d808b45f27dcdc05700d902fc | refs/heads/master | 2021-07-22T10:16:13.538256 | 2021-02-12T11:51:47 | 2021-02-12T11:51:47 | 241,689,398 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,759 | cpp | #include <bits/stdc++.h>
#define int long long int
#define len length
#define pb push_back
#define F first
#define S second
#define scnarr(a, n) for (int i = 0; i < n; ++i) cin >> a[i]
#define vi vector<int>
#define pii pair <int, int>
#define mii map <int, int>
#define faster ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)
using namespace std;
//Constants
const int MOD = 998244353; // 1e9 + 7
const int N = 100005; // 1e6 +1
void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
void __print(unsigned x) {cerr << x;}
void __print(unsigned long x) {cerr << x;}
void __print(unsigned long long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}
template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
#ifndef ONLINE_JUDGE
#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
#else
#define debug(x...)
#endif
/* -------------------------------Solution Sarted--------------------------------------*/
vi v[N];
map <pair<int,int>, int> weights;
int till, upto;
int ans;
bool visited[N], firstLeaf = false, done = false;
set <int> used;
void dfs(int i){
visited[i] = 1;
for(auto itr:v[i]){
if(!visited[itr]){
dfs(itr);
if(v[itr].size() == 1){
weights.insert({{i, itr}, till++});
}else{
weights.insert({{i, itr}, upto--});
}
}
}
}
int32_t main()
{
faster;
#ifndef ONLINE_JUDGE
freopen("ip.txt", "r", stdin);
freopen("op.txt", "w", stdout);
#endif
// int t; cin >> t; while(t--)
{
int n, x, y;
cin >> n;
till = 0, upto = n -2;
vector <pii> edges;
for (int i = 0; i < n -1; ++i){
cin >> x >> y;
edges.push_back({x, y});
v[x].push_back(y);
v[y].push_back(x);
}
dfs(1);
vi answer;
for(int i = 0; i < n -1; ++i){
if(weights.find({edges[i]}) != weights.end()){
answer.push_back(weights[edges[i]]);
}else if(weights.find({edges[i].second, edges[i].first}) != weights.end()){
answer.push_back(weights[{edges[i].second, edges[i].first}]);
}
}
for(auto itr:answer)
cout << itr << "\n";
}
return 0;
}
//Author : Ankit Raj
//InSearchForMeanings
//Problem Link :
| [
"[email protected]"
] | |
b93b614b97fe00deb3681df8e6dbd26e13a025f5 | 7a20b3db1a185ecdf12ad86f38edaa03742abd7b | /src/gpu/ops/GrSimpleMeshDrawOpHelper.cpp | 8b83271105cc3ce09ea5eed123b5d4d1a689c274 | [
"BSD-3-Clause"
] | permissive | revery-ui/esy-skia | 7ef96ceeca94d001264684b7dc1ac24db0381ad4 | 29349b9279ed24a73ec41acd7082caea9bd8c04e | refs/heads/master | 2022-05-29T17:50:23.722723 | 2022-04-02T09:37:52 | 2022-04-02T09:37:52 | 203,015,081 | 24 | 26 | BSD-3-Clause | 2022-04-02T09:37:52 | 2019-08-18T14:24:21 | C++ | UTF-8 | C++ | false | false | 7,527 | cpp | /*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrSimpleMeshDrawOpHelper.h"
#include "GrAppliedClip.h"
#include "GrProcessorSet.h"
#include "GrRect.h"
#include "GrUserStencilSettings.h"
GrSimpleMeshDrawOpHelper::GrSimpleMeshDrawOpHelper(const MakeArgs& args, GrAAType aaType,
Flags flags)
: fProcessors(args.fProcessorSet)
, fPipelineFlags(args.fSRGBFlags)
, fAAType((int)aaType)
, fRequiresDstTexture(false)
, fUsesLocalCoords(false)
, fCompatibleWithAlphaAsCoveage(false) {
SkDEBUGCODE(fDidAnalysis = false);
SkDEBUGCODE(fMadePipeline = false);
if (GrAATypeIsHW(aaType)) {
fPipelineFlags |= GrPipeline::kHWAntialias_Flag;
}
if (flags & Flags::kSnapVerticesToPixelCenters) {
fPipelineFlags |= GrPipeline::kSnapVerticesToPixelCenters_Flag;
}
}
GrSimpleMeshDrawOpHelper::~GrSimpleMeshDrawOpHelper() {
if (fProcessors) {
fProcessors->~GrProcessorSet();
}
}
GrDrawOp::FixedFunctionFlags GrSimpleMeshDrawOpHelper::fixedFunctionFlags() const {
return GrAATypeIsHW((this->aaType())) ? GrDrawOp::FixedFunctionFlags::kUsesHWAA
: GrDrawOp::FixedFunctionFlags::kNone;
}
bool GrSimpleMeshDrawOpHelper::isCompatible(const GrSimpleMeshDrawOpHelper& that,
const GrCaps& caps, const SkRect& thisBounds,
const SkRect& thatBounds) const {
if (SkToBool(fProcessors) != SkToBool(that.fProcessors)) {
return false;
}
if (fProcessors) {
if (*fProcessors != *that.fProcessors) {
return false;
}
if (fRequiresDstTexture ||
(fProcessors->xferProcessor() && fProcessors->xferProcessor()->xferBarrierType(caps))) {
if (GrRectsTouchOrOverlap(thisBounds, thatBounds)) {
return false;
}
}
}
bool result = fPipelineFlags == that.fPipelineFlags && fAAType == that.fAAType;
SkASSERT(!result || fCompatibleWithAlphaAsCoveage == that.fCompatibleWithAlphaAsCoveage);
SkASSERT(!result || fUsesLocalCoords == that.fUsesLocalCoords);
return result;
}
GrDrawOp::RequiresDstTexture GrSimpleMeshDrawOpHelper::xpRequiresDstTexture(
const GrCaps& caps, const GrAppliedClip* clip, GrPixelConfigIsClamped dstIsClamped,
GrProcessorAnalysisCoverage geometryCoverage, GrProcessorAnalysisColor* geometryColor) {
SkDEBUGCODE(fDidAnalysis = true);
GrProcessorSet::Analysis analysis;
if (fProcessors) {
GrProcessorAnalysisCoverage coverage = geometryCoverage;
if (GrProcessorAnalysisCoverage::kNone == coverage) {
coverage = clip->numClipCoverageFragmentProcessors()
? GrProcessorAnalysisCoverage::kSingleChannel
: GrProcessorAnalysisCoverage::kNone;
}
bool isMixedSamples = this->aaType() == GrAAType::kMixedSamples;
GrColor overrideColor;
analysis = fProcessors->finalize(*geometryColor, coverage, clip, isMixedSamples, caps,
dstIsClamped, &overrideColor);
if (analysis.inputColorIsOverridden()) {
*geometryColor = overrideColor;
}
} else {
analysis = GrProcessorSet::EmptySetAnalysis();
}
fRequiresDstTexture = analysis.requiresDstTexture();
fUsesLocalCoords = analysis.usesLocalCoords();
fCompatibleWithAlphaAsCoveage = analysis.isCompatibleWithCoverageAsAlpha();
return analysis.requiresDstTexture() ? GrDrawOp::RequiresDstTexture::kYes
: GrDrawOp::RequiresDstTexture::kNo;
}
GrDrawOp::RequiresDstTexture GrSimpleMeshDrawOpHelper::xpRequiresDstTexture(
const GrCaps& caps, const GrAppliedClip* clip, GrPixelConfigIsClamped dstIsClamped,
GrProcessorAnalysisCoverage geometryCoverage, GrColor* geometryColor) {
GrProcessorAnalysisColor color = *geometryColor;
auto result = this->xpRequiresDstTexture(caps, clip, dstIsClamped, geometryCoverage, &color);
color.isConstant(geometryColor);
return result;
}
SkString GrSimpleMeshDrawOpHelper::dumpInfo() const {
const GrProcessorSet& processors = fProcessors ? *fProcessors : GrProcessorSet::EmptySet();
SkString result = processors.dumpProcessors();
result.append("AA Type: ");
switch (this->aaType()) {
case GrAAType::kNone:
result.append(" none\n");
break;
case GrAAType::kCoverage:
result.append(" coverage\n");
break;
case GrAAType::kMSAA:
result.append(" msaa\n");
break;
case GrAAType::kMixedSamples:
result.append(" mixed samples\n");
break;
}
result.append(GrPipeline::DumpFlags(fPipelineFlags));
return result;
}
GrPipeline::InitArgs GrSimpleMeshDrawOpHelper::pipelineInitArgs(
GrMeshDrawOp::Target* target) const {
GrPipeline::InitArgs args;
args.fFlags = this->pipelineFlags();
args.fProxy = target->proxy();
args.fDstProxy = target->dstProxy();
args.fCaps = &target->caps();
args.fResourceProvider = target->resourceProvider();
return args;
}
GrPipeline* GrSimpleMeshDrawOpHelper::internalMakePipeline(GrMeshDrawOp::Target* target,
const GrPipeline::InitArgs& args) {
// A caller really should only call this once as the processor set and applied clip get
// moved into the GrPipeline.
SkASSERT(!fMadePipeline);
SkDEBUGCODE(fMadePipeline = true);
if (fProcessors) {
return target->allocPipeline(args, std::move(*fProcessors), target->detachAppliedClip());
} else {
return target->allocPipeline(args, GrProcessorSet::MakeEmptySet(),
target->detachAppliedClip());
}
}
GrSimpleMeshDrawOpHelperWithStencil::GrSimpleMeshDrawOpHelperWithStencil(
const MakeArgs& args, GrAAType aaType, const GrUserStencilSettings* stencilSettings,
Flags flags)
: INHERITED(args, aaType, flags)
, fStencilSettings(stencilSettings ? stencilSettings : &GrUserStencilSettings::kUnused) {}
GrDrawOp::FixedFunctionFlags GrSimpleMeshDrawOpHelperWithStencil::fixedFunctionFlags() const {
GrDrawOp::FixedFunctionFlags flags = INHERITED::fixedFunctionFlags();
if (fStencilSettings != &GrUserStencilSettings::kUnused) {
flags |= GrDrawOp::FixedFunctionFlags::kUsesStencil;
}
return flags;
}
bool GrSimpleMeshDrawOpHelperWithStencil::isCompatible(
const GrSimpleMeshDrawOpHelperWithStencil& that, const GrCaps& caps,
const SkRect& thisBounds, const SkRect& thatBounds) const {
return INHERITED::isCompatible(that, caps, thisBounds, thatBounds) &&
fStencilSettings == that.fStencilSettings;
}
const GrPipeline* GrSimpleMeshDrawOpHelperWithStencil::makePipeline(
GrMeshDrawOp::Target* target) {
auto args = INHERITED::pipelineInitArgs(target);
args.fUserStencil = fStencilSettings;
return this->internalMakePipeline(target, args);
}
SkString GrSimpleMeshDrawOpHelperWithStencil::dumpInfo() const {
SkString result = INHERITED::dumpInfo();
result.appendf("Stencil settings: %s\n", (fStencilSettings ? "yes" : "no"));
return result;
}
| [
"[email protected]"
] | |
dcbc011b8b87904641deb08e1a900b7c86b99252 | 72eb234212da5a8e5fdd8433546a9e4a697364a9 | /renderengine.h | c1ac193302587324f181991719f6e56e8bcc1c56 | [] | no_license | loosstef/grid-based-fluid-simulator | 03825c757c41e39d274b7758815a6c628987780f | 57ecb66404b82a21344529e39f2f3533f3ec841f | refs/heads/master | 2022-01-12T02:11:26.072310 | 2019-05-16T13:37:35 | 2019-05-16T13:37:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,715 | h | #ifndef RENDERENGINE_H
#define RENDERENGINE_H
#include <QObject>
#include <QPainter>
class QImage;
class Field;
class Grid;
class RenderEngineController;
enum RenderType {smoke, density, temperature};
class RenderEngine : public QObject
{
Q_OBJECT
public:
RenderEngine(const int width, const int height, const bool showVelocity = false);
QImage* render(const Field* field);
void showVelocity(const bool showVelocity) {this->mShowVelocity = showVelocity;}
RenderEngineController *getController();
void setVelocityScale(const double velScale);
void setVelocitySparseness(const int velSparseness) {this->mVelocitySparseness = velSparseness;}
private:
void renderGrid(QImage* image, const Grid* grid, double (*f)(double)) const;
void renderWalls(QImage* image, Grid* walls, int width, int height, double xScale, double yScale);
void renderVelocity(QImage* image, const Field* field);
double valueToColorIntensity(double value, double (*f)(double)) const;
static double smokeToColorIntensity(double value);
static double densityToColorIntensity(double value);
static double temperatureToColorIntensity(double value);
static Grid *generateTemperatureGrid(Grid* mass, Grid* energy);
static double weightedAverage(double value1, double value2, double weight, double minWeight, double maxWeight);
int mWidth;
int mHeight;
bool mShowVelocity;
double mVelocityScale = 1;
int mVelocitySparseness = 1;
QPainter mPainter;
RenderType mRenderType = smoke;
public slots:
void toggleShowVelocity(const bool visible);
void setRenderType(const RenderType renderType) {this->mRenderType = renderType;}
};
#endif // RENDERENGINE_H
| [
"[email protected]"
] | |
e3e2f9d79fdfd74698a386b479fedccfc3d079d3 | 04251e142abab46720229970dab4f7060456d361 | /lib/rosetta/source/src/protocols/task_operations/SelectByDeltaScoreOperation.cc | c980ac866914c143dd87016424b2da02bfa35018 | [] | no_license | sailfish009/binding_affinity_calculator | 216257449a627d196709f9743ca58d8764043f12 | 7af9ce221519e373aa823dadc2005de7a377670d | refs/heads/master | 2022-12-29T11:15:45.164881 | 2020-10-22T09:35:32 | 2020-10-22T09:35:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,553 | cc | // -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// (c) Copyright Rosetta Commons Member Institutions.
// (c) This file is part of the Rosetta software suite and is made available under license.
// (c) The Rosetta software is developed by the contributing members of the Rosetta Commons.
// (c) For more information, see http://www.rosettacommons.org. Questions about this can be
// (c) addressed to University of Washington CoMotion, email: [email protected].
/// @brief Restrict design to residues passing a user-specified threshold on a given score type.
/// @author Jacob Bale ([email protected])
// Unit Headers
#include <protocols/task_operations/SelectByDeltaScoreOperation.hh>
#include <protocols/task_operations/SelectByDeltaScoreOperationCreator.hh>
// Project Headers
#include <protocols/rosetta_scripts/util.hh>
#include <core/conformation/symmetry/SymmetryInfo.hh>
#include <core/conformation/symmetry/util.hh>
#include <core/conformation/Residue.hh>
#include <core/pack/task/PackerTask.hh>
#include <core/pose/Pose.hh>
#include <core/pose/PDBInfo.hh>
#include <core/pose/symmetry/util.hh>
#include <core/pose/util.hh>
#include <core/types.hh>
#include <core/scoring/ScoreFunction.hh>
#include <core/scoring/ScoreFunctionFactory.hh>
#include <core/scoring/Energies.hh>
#include <core/import_pose/import_pose.hh>
#include <core/scoring/hbonds/HBondOptions.hh>
#include <core/scoring/hbonds/HBondSet.hh>
#include <core/scoring/hbonds/hbonds.hh>
#include <core/scoring/methods/EnergyMethodOptions.hh>
#include <basic/options/option.hh>
#include <basic/options/keys/out.OptionKeys.gen.hh>
// Utility Headers
#include <basic/Tracer.hh>
#include <ObjexxFCL/format.hh>
#include <utility/string_util.hh>
#include <utility/tag/Tag.hh>
#include <utility/tag/XMLSchemaGeneration.hh>
#include <core/pack/task/operation/task_op_schemas.hh>
#include <utility/vector1.hh>
#include <utility/exit.hh>
// C++ Headers
static basic::Tracer TR( "protocols.task_operations.SelectByDeltaScoreOperation" );
namespace protocols {
namespace task_operations {
using namespace core::pack::task::operation;
using namespace utility::tag;
core::pack::task::operation::TaskOperationOP
SelectByDeltaScoreOperationCreator::create_task_operation() const
{
return utility::pointer::make_shared< SelectByDeltaScoreOperation >();
}
void SelectByDeltaScoreOperationCreator::provide_xml_schema( utility::tag::XMLSchemaDefinition & xsd ) const
{
SelectByDeltaScoreOperation::provide_xml_schema( xsd );
}
std::string SelectByDeltaScoreOperationCreator::keyname() const
{
return SelectByDeltaScoreOperation::keyname();
}
/// @brief default constructor
SelectByDeltaScoreOperation::SelectByDeltaScoreOperation() :
TaskOperation(),
scorefxn_(/* NULL */),
threshold_( 100 ),
reference_pose_(/* NULL */)
{}
/// @brief destructor
SelectByDeltaScoreOperation::~SelectByDeltaScoreOperation()= default;
/// @brief make clone
core::pack::task::operation::TaskOperationOP
SelectByDeltaScoreOperation::clone() const{
return utility::pointer::make_shared< SelectByDeltaScoreOperation >( *this );
}
core::scoring::ScoreFunctionOP SelectByDeltaScoreOperation::scorefxn() const{ return scorefxn_; }
void SelectByDeltaScoreOperation::scorefxn( core::scoring::ScoreFunctionOP scorefxn ){ scorefxn_ = scorefxn; }
core::scoring::ScoreType SelectByDeltaScoreOperation::score_type() const{ return score_type_; }
void SelectByDeltaScoreOperation::score_type( core::scoring::ScoreType const score_type ){ score_type_ = score_type; }
std::string SelectByDeltaScoreOperation::score_type_name() const{ return score_type_name_; }
void SelectByDeltaScoreOperation::score_type_name( std::string const & score_type_name ){ score_type_name_ = score_type_name; }
core::Real SelectByDeltaScoreOperation::threshold() const{ return threshold_; }
void SelectByDeltaScoreOperation::threshold( core::Real threshold ) { threshold_ = threshold; }
bool SelectByDeltaScoreOperation::lower() const{ return lower_; }
void SelectByDeltaScoreOperation::lower( bool lower ){ lower_ = lower; }
core::pose::PoseOP SelectByDeltaScoreOperation::reference_pose() const{ return reference_pose_; }
void SelectByDeltaScoreOperation::reference_pose( core::pose::PoseOP reference_pose ){ reference_pose_ = reference_pose; }
bool SelectByDeltaScoreOperation::individual_hbonds() const{ return individual_hbonds_; }
void SelectByDeltaScoreOperation::individual_hbonds( bool individual_hbonds ){ individual_hbonds_ = individual_hbonds; }
void
SelectByDeltaScoreOperation::apply( core::pose::Pose const & pose, core::pack::task::PackerTask & task ) const
{
core::pose::Pose refp( *reference_pose_ );
//refp.dump_pdb("reference_pose.pdb");
//Loop over the independent residues, assess score_type for each residue, and restrict residues to repacking based on whether or not they pass the user-provided threshold.
core::Size nres_asymmetric_unit, ref_nres_asymmetric_unit;
if ( core::conformation::symmetry::is_symmetric( refp.conformation() ) ) {
core::conformation::symmetry::SymmetryInfoCOP symm_info = core::pose::symmetry::symmetry_info(refp);
ref_nres_asymmetric_unit = symm_info->num_independent_residues();
} else {
ref_nres_asymmetric_unit = refp.size();
}
if ( core::conformation::symmetry::is_symmetric( pose.conformation() ) ) {
core::conformation::symmetry::SymmetryInfoCOP symm_info = core::pose::symmetry::symmetry_info(pose);
nres_asymmetric_unit = symm_info->num_independent_residues();
} else {
nres_asymmetric_unit = pose.size();
}
if ( nres_asymmetric_unit != ref_nres_asymmetric_unit ) {
utility_exit_with_message( "Reference pose and current pose have a different number of residues" );
}
core::Real delta_score;
core::pose::Pose p = pose;
std::string pymol_selection("select score_type_selection, resi ");
core::scoring::hbonds::HBondSet hbset, hbset_ref;
core::scoring::EnergyMap em, ref_em;
if ( individual_hbonds_ ) {
core::scoring::methods::EnergyMethodOptions myopt = scorefxn()->energy_method_options();
myopt.hbond_options().decompose_bb_hb_into_pair_energies(true);
scorefxn()->set_energy_method_options(myopt);
scorefxn()->score( refp );
scorefxn()->score( p );
// get the HBondSet
core::scoring::hbonds::fill_hbond_set(p,false,hbset);
core::scoring::hbonds::fill_hbond_set(refp,false,hbset_ref);
} else {
scorefxn()->score( refp );
scorefxn()->score( p );
}
for ( core::Size i=1; i<=nres_asymmetric_unit; i++ ) {
if ( individual_hbonds_ ) {
core::Real resi_hbond_bb_sc_energy = 0;
core::Real ref_resi_hbond_bb_sc_energy = 0;
for ( core::Size j=1; j<=nres_asymmetric_unit; j++ ) {
for ( core::Size ihb = 1; ihb <= hbset_ref.nhbonds(); ++ihb ) {
core::scoring::hbonds::HBond const & hb(hbset_ref.hbond(ihb));
if ( hb.don_res()==i && hb.acc_res()==j ) {
if ( !hb.don_hatm_is_protein_backbone() && hb.acc_atm_is_protein_backbone() ) {
ref_resi_hbond_bb_sc_energy += hb.energy();
TR << "Refpose donor sc resi: " << i << refp.residue(i).name3() << ". Refpose acceptor bb resi: " << j << refp.residue(j).name3() << std::endl;
}
}
if ( hb.don_res()==j && hb.acc_res()==i ) {
if ( hb.don_hatm_is_protein_backbone() && !hb.acc_atm_is_protein_backbone() ) {
ref_resi_hbond_bb_sc_energy += hb.energy();
TR << "Refpose acceptor sc resi: " << i << refp.residue(i).name3() << ". Refpose donor bb resi: " << j << refp.residue(j).name3() << std::endl;
}
}
}
for ( core::Size ihb = 1; ihb <= hbset.nhbonds(); ++ihb ) {
core::scoring::hbonds::HBond const & hb(hbset.hbond(ihb));
if ( hb.don_res()==i && hb.acc_res()==j ) {
if ( !hb.don_hatm_is_protein_backbone() && hb.acc_atm_is_protein_backbone() ) {
resi_hbond_bb_sc_energy += hb.energy();
TR << "Pose donor sc resi: " << i << refp.residue(i).name3() << ". Pose acceptor bb resi: " << j << refp.residue(j).name3() << std::endl;
}
}
if ( hb.don_res()==j && hb.acc_res()==i ) {
if ( hb.don_hatm_is_protein_backbone() && !hb.acc_atm_is_protein_backbone() ) {
resi_hbond_bb_sc_energy += hb.energy();
TR << "Pose acceptor sc resi: " << i << refp.residue(i).name3() << ". Pose donor bb resi: " << j << refp.residue(j).name3() << std::endl;
}
}
}
}
delta_score = resi_hbond_bb_sc_energy - ref_resi_hbond_bb_sc_energy;
TR << "Residue: CurrentPose - RefPose " << score_type_name_ << " : " << i << " " << resi_hbond_bb_sc_energy << " - " << ref_resi_hbond_bb_sc_energy << " = " << delta_score << std::endl;
} else {
ref_em = refp.energies().residue_total_energies( i );
ref_em *= scorefxn()->weights();
em = p.energies().residue_total_energies( i );
em *= scorefxn()->weights();
delta_score = em[score_type_] - ref_em[score_type_];
TR << "Residue: CurrentPose - RefPose " << score_type_name_ << " : " << i << " " << em[score_type_] << " - " << ref_em[score_type_] << " = " << delta_score << std::endl;
}
if ( (delta_score <= threshold_ && lower_ == false) || ( delta_score >= threshold_ && lower_ == true) ) {
task.nonconst_residue_task(i).prevent_repacking();
} else {
core::Size output_resi = i;
if ( !basic::options::option[ basic::options::OptionKeys::out::file::renumber_pdb ]() ) {
output_resi = pose.pdb_info()->number( i );
}
pymol_selection.append(ObjexxFCL::string_of(output_resi) + "+");
}
}
TR << pymol_selection << std::endl;
}
void
SelectByDeltaScoreOperation::parse_tag( TagCOP tag , DataMap & data)
{
scorefxn(protocols::rosetta_scripts::parse_score_function(tag, data));
score_type(core::scoring::score_type_from_name( tag->getOption<std::string>( "score_type", "total_score" ) ) );
score_type_name( tag->getOption<std::string>( "score_type", "total_score" ) );
threshold(tag->getOption< core::Real >("threshold", 100 ));
lower(tag->getOption< bool >("lower", false ));
individual_hbonds(tag->getOption< bool >("individual_hbonds", false ));
if ( tag->hasOption("reference_name") ) {
reference_pose_ = protocols::rosetta_scripts::saved_reference_pose(tag,data );
} else if ( tag->hasOption("reference_pdb") ) {
std::string reference_pdb_filename( tag->getOption< std::string >( "reference_pdb", "" ) );
reference_pose_ = core::import_pose::pose_from_file( reference_pdb_filename , core::import_pose::PDB_file);
}
}
void SelectByDeltaScoreOperation::provide_xml_schema( utility::tag::XMLSchemaDefinition & xsd )
{
AttributeList attributes;
rosetta_scripts::attributes_for_parse_score_function( attributes );
attributes
+ XMLSchemaAttribute::attribute_w_default( "score_type", xs_string, "Loop over the independent residues, assess score_type for each residue.", "total_score" )
+ XMLSchemaAttribute::attribute_w_default( "threshold", xsct_real, "Restrict residues to repack based on whether they pass this threshold.", "100" )
+ XMLSchemaAttribute::attribute_w_default( "lower", xsct_rosetta_bool, "Higher or lower than threshold.", "false" )
+ XMLSchemaAttribute::attribute_w_default( "individual_hbonds", xsct_rosetta_bool, "If true, get Hbond set.", "false" )
+ XMLSchemaAttribute( "reference_name", xs_string , "Name of reference pose." )
+ XMLSchemaAttribute( "reference_pdb", xs_string , "Reference pdb filename." );
task_op_schema_w_attributes( xsd, keyname(), attributes, "Restrict design to residues passing a user-specified threshold on a given score type." );
}
} //namespace task_operations
} //namespace protocols
| [
"[email protected]"
] | |
bb84cd3259c8d6bcdfa8919f447abad004738597 | 426af4169b030c4691867f9083e336b0fdf0aa2e | /My DSA Practice/Sorting/intersection.cpp | 3b54df1d60eb0956b08b0e0a027d9d83c0381cc5 | [] | no_license | kk-source/DSA-Practice-Repo | b0f896e7a7692786deb121e80258b793054c0094 | 06ae5af6a180910bcb03fe7c28a72befb3611114 | refs/heads/master | 2023-07-10T20:26:01.721486 | 2021-08-22T12:01:33 | 2021-08-22T12:01:33 | 372,847,622 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 597 | cpp | #include <iostream>
#include <string>
using namespace std;
void intersection(int arr[], int brr[], int n1, int n2){
int j=0,i=0;
while (i<n1 && j<n2){
if (arr[i]==brr[j]){
cout << arr[i] << " ";
while(arr[i]==brr[j])
j++;
i++;
}
else if (arr[i]>brr[j])
j++;
else
i++;
}
}
int main(){
int arr[]={1,1,3,3,3};
// int arr[]={3,5,10,10,10,15,15,20};
int brr[]={1,1,1,1,3,5,7};
// int brr[]={5,10,10,15,30};
int n1=5, n2=7;
intersection(arr, brr, n1, n2);
return 0;
} | [
"[email protected]"
] | |
d3a01ac671963924145d0d0c0c863542ddaebdf1 | 211f01b13e9165bde8e3a87128ed3fe74113b536 | /C++/문제_9019번.cpp | f360825d4093ffca293f3dfdad5781b1413de188 | [] | no_license | portfolioExpert/BackJoon | 9ee9d631322443e856d7d5a14f8f7379a32f9e05 | e38c7a1ac9f5e9ddc5d84ae9135791fc7c701e52 | refs/heads/master | 2023-08-03T10:21:41.119294 | 2023-07-24T22:33:17 | 2023-07-24T22:33:17 | 223,161,598 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,464 | cpp | //문제 9019번 DSLR -> BFS
#include <string>
#include <queue>
#include <cstring>
bool visit[10001];
string bfs(int go, int goal){
queue<pair<int,string>>q;
q.push({go, ""});
while(!q.empty()){
int now = q.front().first;
string str = q.front().second;
q.pop();
if(now == goal)
return str;
//D
if(visit[(now * 2) % 10000] == 0){
q.push({(now * 2) % 10000, str+'D'});
visit[(now * 2) % 10000] = 1;
}
//S
if(now == 0 && visit[9999] == 0){
q.push({9999, str+'S'});
visit[9999] = 1;
}
else if(now != 0 && visit[(now - 1)] == 0){
q.push({(now - 1), str+'S'});
visit[(now - 1)] = 1;
}
//L
if(visit[(now * 10) % 10000 + now / 1000] == 0){
q.push({(now * 10) % 10000 + now / 1000, str+'L'});
visit[(now * 10) % 10000 + now / 1000] = 1;
}
//R
if(visit[(now % 10) * 1000 + now / 10] == 0){
q.push({(now % 10) * 1000 + now / 10, str+'R'});
visit[(now % 10) * 1000 + now / 10] = 1;
}
}
return "";
}
int main(){
cin.tie(NULL);
ios_base::sync_with_stdio(false);
cout.tie(NULL);
int t;
cin >> t;
for(int i = 0;i<t;i++){
memset(visit, 0, sizeof(visit));
int now, goal;
cin >> now >> goal;
cout << bfs(now, goal) << "\n";
}
} | [
"[email protected]"
] | |
e5dc58e8d869da5a3cf2d5169f17363575410626 | 2a6f00859e1f762bc3fdab6fa15e703a0dd33322 | /src/qt/multisigdialog.h | 73eca2bce33bc6b1dbf70a713cbfd0f219b1c869 | [
"MIT"
] | permissive | nazarpechka/volvox-old | 839858e9b7c36ff49e5501824c8d3e0616e46d22 | 1b8e05a330183580371096cd9eb896a645417347 | refs/heads/master | 2020-03-07T17:27:30.072161 | 2019-02-10T14:21:00 | 2019-02-10T14:21:00 | 127,611,688 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,591 | h | #ifndef MULTISIGDIALOG_H
#define MULTISIGDIALOG_H
#include <QDialog>
#include <QWidget>
#include "multisigaddressentry.h"
#include "multisiginputentry.h"
#include "sendcoinsentry.h"
#include "walletmodel.h"
namespace Ui
{
class MultisigDialog;
}
class MultisigDialog : public QDialog
{
Q_OBJECT;
protected:
void keyPressEvent(QKeyEvent *);
public:
explicit MultisigDialog(QDialog *parent);
MultisigDialog();
~MultisigDialog();
void setModel(WalletModel *model);
public slots:
MultisigAddressEntry * addPubKey();
void clear();
void updateRemoveEnabled();
MultisigInputEntry * addInput();
SendCoinsEntry * addOutput();
private:
Ui::MultisigDialog *ui;
WalletModel *model;
private slots:
void showEvent(QShowEvent *event);
void hideEvent(QHideEvent *event);
void on_createAddressButton_clicked();
void on_copyMultisigAddressButton_clicked();
void on_copyRedeemScriptButton_clicked();
void on_saveRedeemScriptButton_clicked();
void on_saveMultisigAddressButton_clicked();
void removeEntry(MultisigAddressEntry *entry);
void on_createTransactionButton_clicked();
void on_transaction_textChanged();
void on_copyTransactionButton_clicked();
void on_pasteTransactionButton_clicked();
void on_signTransactionButton_clicked();
void on_copySignedTransactionButton_clicked();
void on_sendTransactionButton_clicked();
void removeEntry(MultisigInputEntry *entry);
void removeEntry(SendCoinsEntry *entry);
void updateAmounts();
};
#endif // MULTISIGDIALOG_H
| [
"[email protected]"
] | |
eebbd94f56a0991def544e714206871fabf7eb75 | 7fd5e6156d6a42b305809f474659f641450cea81 | /boost/numeric/ublas/detail/vector_assign.hpp | 3a36375373a72201d08f532d491fbbbd9854380f | [] | no_license | imos/icfpc2015 | 5509b6cfc060108c9e5df8093c5bc5421c8480ea | e998055c0456c258aa86e8379180fad153878769 | refs/heads/master | 2020-04-11T04:30:08.777739 | 2015-08-10T11:53:12 | 2015-08-10T11:53:12 | 40,011,767 | 8 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,562 | hpp | //
// Copyright (c) 2000-2002
// Joerg Walter, Mathias Koch
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// The authors gratefully acknowledge the support of
// GeNeSys mbH & Co. KG in producing this work.
//
#ifndef _BOOST_UBLAS_VECTOR_ASSIGN_
#define _BOOST_UBLAS_VECTOR_ASSIGN_
#include "boost/numeric/ublas/functional.hpp" // scalar_assign
// Required for make_conformant storage
#include <vector>
// Iterators based on ideas of Jeremy Siek
namespace boost { namespace numeric { namespace ublas {
namespace detail {
// Weak equality check - useful to compare equality two arbitary vector expression results.
// Since the actual expressions are unknown, we check for and arbitary error bound
// on the relative error.
// For a linear expression the infinity norm makes sense as we do not know how the elements will be
// combined in the expression. False positive results are inevitable for arbirary expressions!
template<class E1, class E2, class S>
BOOST_UBLAS_INLINE
bool equals (const vector_expression<E1> &e1, const vector_expression<E2> &e2, S epsilon, S min_norm) {
return norm_inf (e1 - e2) <= epsilon *
std::max<S> (std::max<S> (norm_inf (e1), norm_inf (e2)), min_norm);
}
template<class E1, class E2>
BOOST_UBLAS_INLINE
bool expression_type_check (const vector_expression<E1> &e1, const vector_expression<E2> &e2) {
typedef typename type_traits<typename promote_traits<typename E1::value_type,
typename E2::value_type>::promote_type>::real_type real_type;
return equals (e1, e2, BOOST_UBLAS_TYPE_CHECK_EPSILON, BOOST_UBLAS_TYPE_CHECK_MIN);
}
// Make sparse proxies conformant
template<class V, class E>
// BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.
void make_conformant (V &v, const vector_expression<E> &e) {
BOOST_UBLAS_CHECK (v.size () == e ().size (), bad_size ());
typedef typename V::size_type size_type;
typedef typename V::difference_type difference_type;
typedef typename V::value_type value_type;
// FIXME unbounded_array with push_back maybe better
std::vector<size_type> index;
typename V::iterator it (v.begin ());
typename V::iterator it_end (v.end ());
typename E::const_iterator ite (e ().begin ());
typename E::const_iterator ite_end (e ().end ());
if (it != it_end && ite != ite_end) {
size_type it_index = it.index (), ite_index = ite.index ();
while (true) {
difference_type compare = it_index - ite_index;
if (compare == 0) {
++ it, ++ ite;
if (it != it_end && ite != ite_end) {
it_index = it.index ();
ite_index = ite.index ();
} else
break;
} else if (compare < 0) {
increment (it, it_end, - compare);
if (it != it_end)
it_index = it.index ();
else
break;
} else if (compare > 0) {
if (*ite != value_type/*zero*/())
index.push_back (ite.index ());
++ ite;
if (ite != ite_end)
ite_index = ite.index ();
else
break;
}
}
}
while (ite != ite_end) {
if (*ite != value_type/*zero*/())
index.push_back (ite.index ());
++ ite;
}
for (size_type k = 0; k < index.size (); ++ k)
v (index [k]) = value_type/*zero*/();
}
}//namespace detail
// Explicitly iterating
template<template <class T1, class T2> class F, class V, class T>
// BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.
void iterating_vector_assign_scalar (V &v, const T &t) {
typedef F<typename V::iterator::reference, T> functor_type;
typedef typename V::difference_type difference_type;
difference_type size (v.size ());
typename V::iterator it (v.begin ());
BOOST_UBLAS_CHECK (v.end () - it == size, bad_size ());
#ifndef BOOST_UBLAS_USE_DUFF_DEVICE
while (-- size >= 0)
functor_type::apply (*it, t), ++ it;
#else
DD (size, 4, r, (functor_type::apply (*it, t), ++ it));
#endif
}
// Explicitly case
template<template <class T1, class T2> class F, class V, class T>
// BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.
void indexing_vector_assign_scalar (V &v, const T &t) {
typedef F<typename V::reference, T> functor_type;
typedef typename V::size_type size_type;
size_type size (v.size ());
#ifndef BOOST_UBLAS_USE_DUFF_DEVICE
for (size_type i = 0; i < size; ++ i)
functor_type::apply (v (i), t);
#else
size_type i (0);
DD (size, 4, r, (functor_type::apply (v (i), t), ++ i));
#endif
}
// Dense (proxy) case
template<template <class T1, class T2> class F, class V, class T>
// BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.
void vector_assign_scalar (V &v, const T &t, dense_proxy_tag) {
#ifdef BOOST_UBLAS_USE_INDEXING
indexing_vector_assign_scalar<F> (v, t);
#elif BOOST_UBLAS_USE_ITERATING
iterating_vector_assign_scalar<F> (v, t);
#else
typedef typename V::size_type size_type;
size_type size (v.size ());
if (size >= BOOST_UBLAS_ITERATOR_THRESHOLD)
iterating_vector_assign_scalar<F> (v, t);
else
indexing_vector_assign_scalar<F> (v, t);
#endif
}
// Packed (proxy) case
template<template <class T1, class T2> class F, class V, class T>
// BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.
void vector_assign_scalar (V &v, const T &t, packed_proxy_tag) {
typedef F<typename V::iterator::reference, T> functor_type;
typedef typename V::difference_type difference_type;
typename V::iterator it (v.begin ());
difference_type size (v.end () - it);
while (-- size >= 0)
functor_type::apply (*it, t), ++ it;
}
// Sparse (proxy) case
template<template <class T1, class T2> class F, class V, class T>
// BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.
void vector_assign_scalar (V &v, const T &t, sparse_proxy_tag) {
typedef F<typename V::iterator::reference, T> functor_type;
typename V::iterator it (v.begin ());
typename V::iterator it_end (v.end ());
while (it != it_end)
functor_type::apply (*it, t), ++ it;
}
// Dispatcher
template<template <class T1, class T2> class F, class V, class T>
BOOST_UBLAS_INLINE
void vector_assign_scalar (V &v, const T &t) {
typedef typename V::storage_category storage_category;
vector_assign_scalar<F> (v, t, storage_category ());
}
template<class SC, bool COMPUTED, class RI>
struct vector_assign_traits {
typedef SC storage_category;
};
template<bool COMPUTED>
struct vector_assign_traits<dense_tag, COMPUTED, packed_random_access_iterator_tag> {
typedef packed_tag storage_category;
};
template<>
struct vector_assign_traits<dense_tag, false, sparse_bidirectional_iterator_tag> {
typedef sparse_tag storage_category;
};
template<>
struct vector_assign_traits<dense_tag, true, sparse_bidirectional_iterator_tag> {
typedef sparse_proxy_tag storage_category;
};
template<bool COMPUTED>
struct vector_assign_traits<dense_proxy_tag, COMPUTED, packed_random_access_iterator_tag> {
typedef packed_proxy_tag storage_category;
};
template<>
struct vector_assign_traits<dense_proxy_tag, false, sparse_bidirectional_iterator_tag> {
typedef sparse_proxy_tag storage_category;
};
template<>
struct vector_assign_traits<dense_proxy_tag, true, sparse_bidirectional_iterator_tag> {
typedef sparse_proxy_tag storage_category;
};
template<>
struct vector_assign_traits<packed_tag, false, sparse_bidirectional_iterator_tag> {
typedef sparse_tag storage_category;
};
template<>
struct vector_assign_traits<packed_tag, true, sparse_bidirectional_iterator_tag> {
typedef sparse_proxy_tag storage_category;
};
template<bool COMPUTED>
struct vector_assign_traits<packed_proxy_tag, COMPUTED, sparse_bidirectional_iterator_tag> {
typedef sparse_proxy_tag storage_category;
};
template<>
struct vector_assign_traits<sparse_tag, true, dense_random_access_iterator_tag> {
typedef sparse_proxy_tag storage_category;
};
template<>
struct vector_assign_traits<sparse_tag, true, packed_random_access_iterator_tag> {
typedef sparse_proxy_tag storage_category;
};
template<>
struct vector_assign_traits<sparse_tag, true, sparse_bidirectional_iterator_tag> {
typedef sparse_proxy_tag storage_category;
};
// Explicitly iterating
template<template <class T1, class T2> class F, class V, class E>
// BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.
void iterating_vector_assign (V &v, const vector_expression<E> &e) {
typedef F<typename V::iterator::reference, typename E::value_type> functor_type;
typedef typename V::difference_type difference_type;
difference_type size (BOOST_UBLAS_SAME (v.size (), e ().size ()));
typename V::iterator it (v.begin ());
BOOST_UBLAS_CHECK (v.end () - it == size, bad_size ());
typename E::const_iterator ite (e ().begin ());
BOOST_UBLAS_CHECK (e ().end () - ite == size, bad_size ());
#ifndef BOOST_UBLAS_USE_DUFF_DEVICE
while (-- size >= 0)
functor_type::apply (*it, *ite), ++ it, ++ ite;
#else
DD (size, 2, r, (functor_type::apply (*it, *ite), ++ it, ++ ite));
#endif
}
// Explicitly indexing
template<template <class T1, class T2> class F, class V, class E>
// BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.
void indexing_vector_assign (V &v, const vector_expression<E> &e) {
typedef F<typename V::reference, typename E::value_type> functor_type;
typedef typename V::size_type size_type;
size_type size (BOOST_UBLAS_SAME (v.size (), e ().size ()));
#ifndef BOOST_UBLAS_USE_DUFF_DEVICE
for (size_type i = 0; i < size; ++ i)
functor_type::apply (v (i), e () (i));
#else
size_type i (0);
DD (size, 2, r, (functor_type::apply (v (i), e () (i)), ++ i));
#endif
}
// Dense (proxy) case
template<template <class T1, class T2> class F, class V, class E>
// BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.
void vector_assign (V &v, const vector_expression<E> &e, dense_proxy_tag) {
#ifdef BOOST_UBLAS_USE_INDEXING
indexing_vector_assign<F> (v, e);
#elif BOOST_UBLAS_USE_ITERATING
iterating_vector_assign<F> (v, e);
#else
typedef typename V::size_type size_type;
size_type size (BOOST_UBLAS_SAME (v.size (), e ().size ()));
if (size >= BOOST_UBLAS_ITERATOR_THRESHOLD)
iterating_vector_assign<F> (v, e);
else
indexing_vector_assign<F> (v, e);
#endif
}
// Packed (proxy) case
template<template <class T1, class T2> class F, class V, class E>
// BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.
void vector_assign (V &v, const vector_expression<E> &e, packed_proxy_tag) {
BOOST_UBLAS_CHECK (v.size () == e ().size (), bad_size ());
typedef F<typename V::iterator::reference, typename E::value_type> functor_type;
typedef typename V::difference_type difference_type;
typedef typename V::value_type value_type;
#if BOOST_UBLAS_TYPE_CHECK
vector<value_type> cv (v.size ());
indexing_vector_assign<scalar_assign> (cv, v);
indexing_vector_assign<F> (cv, e);
#endif
typename V::iterator it (v.begin ());
typename V::iterator it_end (v.end ());
typename E::const_iterator ite (e ().begin ());
typename E::const_iterator ite_end (e ().end ());
difference_type it_size (it_end - it);
difference_type ite_size (ite_end - ite);
if (it_size > 0 && ite_size > 0) {
difference_type size ((std::min) (difference_type (it.index () - ite.index ()), ite_size));
if (size > 0) {
ite += size;
ite_size -= size;
}
}
if (it_size > 0 && ite_size > 0) {
difference_type size ((std::min) (difference_type (ite.index () - it.index ()), it_size));
if (size > 0) {
it_size -= size;
if (!functor_type::computed) {
while (-- size >= 0) // zeroing
functor_type::apply (*it, value_type/*zero*/()), ++ it;
} else {
it += size;
}
}
}
difference_type size ((std::min) (it_size, ite_size));
it_size -= size;
ite_size -= size;
while (-- size >= 0)
functor_type::apply (*it, *ite), ++ it, ++ ite;
size = it_size;
if (!functor_type::computed) {
while (-- size >= 0) // zeroing
functor_type::apply (*it, value_type/*zero*/()), ++ it;
} else {
it += size;
}
#if BOOST_UBLAS_TYPE_CHECK
if (! disable_type_check<bool>::value)
BOOST_UBLAS_CHECK (detail::expression_type_check (v, cv),
external_logic ("external logic or bad condition of inputs"));
#endif
}
// Sparse case
template<template <class T1, class T2> class F, class V, class E>
// BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.
void vector_assign (V &v, const vector_expression<E> &e, sparse_tag) {
BOOST_UBLAS_CHECK (v.size () == e ().size (), bad_size ());
typedef F<typename V::iterator::reference, typename E::value_type> functor_type;
BOOST_STATIC_ASSERT ((!functor_type::computed));
typedef typename V::value_type value_type;
#if BOOST_UBLAS_TYPE_CHECK
vector<value_type> cv (v.size ());
indexing_vector_assign<scalar_assign> (cv, v);
indexing_vector_assign<F> (cv, e);
#endif
v.clear ();
typename E::const_iterator ite (e ().begin ());
typename E::const_iterator ite_end (e ().end ());
while (ite != ite_end) {
value_type t (*ite);
if (t != value_type/*zero*/())
v.insert_element (ite.index (), t);
++ ite;
}
#if BOOST_UBLAS_TYPE_CHECK
if (! disable_type_check<bool>::value)
BOOST_UBLAS_CHECK (detail::expression_type_check (v, cv),
external_logic ("external logic or bad condition of inputs"));
#endif
}
// Sparse proxy or functional case
template<template <class T1, class T2> class F, class V, class E>
// BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.
void vector_assign (V &v, const vector_expression<E> &e, sparse_proxy_tag) {
BOOST_UBLAS_CHECK (v.size () == e ().size (), bad_size ());
typedef F<typename V::iterator::reference, typename E::value_type> functor_type;
typedef typename V::size_type size_type;
typedef typename V::difference_type difference_type;
typedef typename V::value_type value_type;
#if BOOST_UBLAS_TYPE_CHECK
vector<value_type> cv (v.size ());
indexing_vector_assign<scalar_assign> (cv, v);
indexing_vector_assign<F> (cv, e);
#endif
detail::make_conformant (v, e);
typename V::iterator it (v.begin ());
typename V::iterator it_end (v.end ());
typename E::const_iterator ite (e ().begin ());
typename E::const_iterator ite_end (e ().end ());
if (it != it_end && ite != ite_end) {
size_type it_index = it.index (), ite_index = ite.index ();
while (true) {
difference_type compare = it_index - ite_index;
if (compare == 0) {
functor_type::apply (*it, *ite);
++ it, ++ ite;
if (it != it_end && ite != ite_end) {
it_index = it.index ();
ite_index = ite.index ();
} else
break;
} else if (compare < 0) {
if (!functor_type::computed) {
functor_type::apply (*it, value_type/*zero*/());
++ it;
} else
increment (it, it_end, - compare);
if (it != it_end)
it_index = it.index ();
else
break;
} else if (compare > 0) {
increment (ite, ite_end, compare);
if (ite != ite_end)
ite_index = ite.index ();
else
break;
}
}
}
if (!functor_type::computed) {
while (it != it_end) { // zeroing
functor_type::apply (*it, value_type/*zero*/());
++ it;
}
} else {
it = it_end;
}
#if BOOST_UBLAS_TYPE_CHECK
if (! disable_type_check<bool>::value)
BOOST_UBLAS_CHECK (detail::expression_type_check (v, cv),
external_logic ("external logic or bad condition of inputs"));
#endif
}
// Dispatcher
template<template <class T1, class T2> class F, class V, class E>
BOOST_UBLAS_INLINE
void vector_assign (V &v, const vector_expression<E> &e) {
typedef typename vector_assign_traits<typename V::storage_category,
F<typename V::reference, typename E::value_type>::computed,
typename E::const_iterator::iterator_category>::storage_category storage_category;
vector_assign<F> (v, e, storage_category ());
}
template<class SC, class RI>
struct vector_swap_traits {
typedef SC storage_category;
};
template<>
struct vector_swap_traits<dense_proxy_tag, sparse_bidirectional_iterator_tag> {
typedef sparse_proxy_tag storage_category;
};
template<>
struct vector_swap_traits<packed_proxy_tag, sparse_bidirectional_iterator_tag> {
typedef sparse_proxy_tag storage_category;
};
// Dense (proxy) case
template<template <class T1, class T2> class F, class V, class E>
// BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.
void vector_swap (V &v, vector_expression<E> &e, dense_proxy_tag) {
typedef F<typename V::iterator::reference, typename E::iterator::reference> functor_type;
typedef typename V::difference_type difference_type;
difference_type size (BOOST_UBLAS_SAME (v.size (), e ().size ()));
typename V::iterator it (v.begin ());
typename E::iterator ite (e ().begin ());
while (-- size >= 0)
functor_type::apply (*it, *ite), ++ it, ++ ite;
}
// Packed (proxy) case
template<template <class T1, class T2> class F, class V, class E>
// BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.
void vector_swap (V &v, vector_expression<E> &e, packed_proxy_tag) {
typedef F<typename V::iterator::reference, typename E::iterator::reference> functor_type;
typedef typename V::difference_type difference_type;
typename V::iterator it (v.begin ());
typename V::iterator it_end (v.end ());
typename E::iterator ite (e ().begin ());
typename E::iterator ite_end (e ().end ());
difference_type it_size (it_end - it);
difference_type ite_size (ite_end - ite);
if (it_size > 0 && ite_size > 0) {
difference_type size ((std::min) (difference_type (it.index () - ite.index ()), ite_size));
if (size > 0) {
ite += size;
ite_size -= size;
}
}
if (it_size > 0 && ite_size > 0) {
difference_type size ((std::min) (difference_type (ite.index () - it.index ()), it_size));
if (size > 0)
it_size -= size;
}
difference_type size ((std::min) (it_size, ite_size));
it_size -= size;
ite_size -= size;
while (-- size >= 0)
functor_type::apply (*it, *ite), ++ it, ++ ite;
}
// Sparse proxy case
template<template <class T1, class T2> class F, class V, class E>
// BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.
void vector_swap (V &v, vector_expression<E> &e, sparse_proxy_tag) {
BOOST_UBLAS_CHECK (v.size () == e ().size (), bad_size ());
typedef F<typename V::iterator::reference, typename E::iterator::reference> functor_type;
typedef typename V::size_type size_type;
typedef typename V::difference_type difference_type;
detail::make_conformant (v, e);
// FIXME should be a seperate restriction for E
detail::make_conformant (e (), v);
typename V::iterator it (v.begin ());
typename V::iterator it_end (v.end ());
typename E::iterator ite (e ().begin ());
typename E::iterator ite_end (e ().end ());
if (it != it_end && ite != ite_end) {
size_type it_index = it.index (), ite_index = ite.index ();
while (true) {
difference_type compare = it_index - ite_index;
if (compare == 0) {
functor_type::apply (*it, *ite);
++ it, ++ ite;
if (it != it_end && ite != ite_end) {
it_index = it.index ();
ite_index = ite.index ();
} else
break;
} else if (compare < 0) {
increment (it, it_end, - compare);
if (it != it_end)
it_index = it.index ();
else
break;
} else if (compare > 0) {
increment (ite, ite_end, compare);
if (ite != ite_end)
ite_index = ite.index ();
else
break;
}
}
}
#if BOOST_UBLAS_TYPE_CHECK
increment (ite, ite_end);
increment (it, it_end);
#endif
}
// Dispatcher
template<template <class T1, class T2> class F, class V, class E>
BOOST_UBLAS_INLINE
void vector_swap (V &v, vector_expression<E> &e) {
typedef typename vector_swap_traits<typename V::storage_category,
typename E::const_iterator::iterator_category>::storage_category storage_category;
vector_swap<F> (v, e, storage_category ());
}
}}}
#endif
| [
"[email protected]"
] | |
34e1431a6af7892e7e11d1cda061ea9503171be3 | e5422975481b1283b4a8a5207c2ff9a5e0d73ff1 | /dlls/cbase.cpp | 12ed81c72c41749f49dad4dc7e6d3b628d47c03b | [] | no_license | mittorn/hlwe_src | ae6ebd30c3dc2965f501b7e5ee460a7c7de58892 | 7abbe2ab834d636af4224a0bd0c192c958242b49 | refs/heads/master | 2021-01-13T16:30:25.223519 | 2015-12-01T19:07:15 | 2015-12-01T19:07:15 | 47,205,047 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 31,760 | cpp | #include "extdll.h"
#include "util.h"
#include "cbase.h"
#include "saverestore.h"
#include "client.h"
#include "decals.h"
#include "gamerules.h"
#include "game.h"
#include "player.h"
//LLAPb begin
#include "ss_mgr.h"
extern DLL_GLOBAL Vector g_vecAttackDir;//Moved here - it's used by CBaseEntity::TakeDamage
extern CScriptMgr *pScriptMgr;
bool ScriptsActive() { return pScriptMgr != 0; };
void CBaseEntity::KeyValue( KeyValueData* pkvd )
{
if (FStrEq(pkvd->szKeyName, "scriptfile"))
{
script_file = ALLOC_STRING(pkvd->szValue);
pkvd->fHandled = TRUE;
}
else
pkvd->fHandled = FALSE;
}
void CBaseEntity::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value )
{
if (!scripted || !ScriptsActive())
{
RealUse( pActivator, pCaller, useType, value );
return;
}
GenericFunction *pfn = my_script->funcs->GetFn(M_USE);
if (!pfn)
{
RealUse( pActivator, pCaller, useType, value );
return;
}
if (NoErrors())
{
pfn->PreExecute();
int i = ENTINDEX(edict()), j = ENTINDEX(pCaller->edict()),
t = (int)useType;
double v = value;
if (pfn->argc > 0)
pfn->PassArg(0, Type(&i, _INT));
if (pfn->argc > 1)
pfn->PassArg(1, Type(&j, _INT));
if (pfn->argc > 2)
pfn->PassArg(2, Type(&t, _INT));
if (pfn->argc > 3)
pfn->PassArg(3, Type(&v, DOUBLE));
switch (pfn->specification)
{
case SPECIFICATION_BEFORE:
pfn->Execute();
RealUse( pActivator, pCaller, useType, value );
break;
case SPECIFICATION_INSTEAD:
pfn->Execute();
break;
default:
RealUse( pActivator, pCaller, useType, value );
pfn->Execute();
break;
}
}
else
RealUse( pActivator, pCaller, useType, value );
}
void CBaseEntity::RealUse( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value )
{
if (m_pfnUse)
(this->*m_pfnUse)( pActivator, pCaller, useType, value );
}
int CBaseEntity :: TakeDamage( entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int bitsDamageType )
{
if (!scripted || !ScriptsActive())
{
return RealTakeDamage( pevInflictor, pevAttacker, flDamage, bitsDamageType );
}
GenericFunction *pfn = my_script->funcs->GetFn(M_DAMAGED);
if (!pfn)
{
return RealTakeDamage( pevInflictor, pevAttacker, flDamage, bitsDamageType );
}
if (NoErrors())
{
pfn->PreExecute();
int i = ENTINDEX(edict()), j = ENTINDEX(ENT(pevAttacker));
double v = flDamage;
TraceResult tr;
if (pevInflictor == pevAttacker && pevAttacker)//yep... bad way
{
CBaseEntity *pEnt = CBaseEntity::Instance(pevAttacker);
if (pEnt->IsPlayer())
{
CBasePlayer *pPlayer = (CBasePlayer*)pEnt;
if (pPlayer)
{
UTIL_MakeVectors(pPlayer->pev->v_angle);
Vector vec_dir = gpGlobals->v_forward * 32000;
UTIL_TraceLine(pPlayer->GetGunPosition(), pevInflictor->origin + vec_dir, dont_ignore_monsters, ENT(pevInflictor), &tr);
}
else
UTIL_TraceLine(pevInflictor->origin, pev->origin, dont_ignore_monsters, ENT(pevInflictor), &tr);
}
else
UTIL_TraceLine(pevInflictor->origin, pev->origin, dont_ignore_monsters, ENT(pevInflictor), &tr);
}
else
UTIL_TraceLine(pevInflictor->origin, pev->origin, dont_ignore_monsters, ENT(pevInflictor), &tr);
double x = tr.vecEndPos.x;
double y = tr.vecEndPos.y;
double z = tr.vecEndPos.z;
Type arg3[3] = {Type(&x, DOUBLE), Type(&y, DOUBLE), Type(&z, DOUBLE)};
if (pfn->argc > 0)
pfn->PassArg(0, Type(&i, _INT));
if (pfn->argc > 1)
pfn->PassArg(1, Type(&j, _INT));
if (pfn->argc > 2)
pfn->PassArg(2, Type(&v, DOUBLE));
if (pfn->argc > 3)
pfn->PassArg(3, Type(&arg3[0], VECTOR_T, 3));
if (pfn->argc > 4)
pfn->PassArg(4, Type(&bitsDamageType, _INT));
if (pfn->argc > 5)
pfn->PassArg(5, Type(&tr.iHitgroup, _INT));
switch (pfn->specification)
{
case SPECIFICATION_BEFORE:
{
Type res = pfn->Execute();
if (res.my_type == DOUBLE)
return RealTakeDamage( pevInflictor, pevAttacker, res.doublev, bitsDamageType );
else if (res.my_type == _INT)
return RealTakeDamage( pevInflictor, pevAttacker, res.intv, bitsDamageType );
return RealTakeDamage( pevInflictor, pevAttacker, flDamage, bitsDamageType );
}
case SPECIFICATION_INSTEAD:
pfn->Execute();
return 1;
default:
{
int v = RealTakeDamage( pevInflictor, pevAttacker, flDamage, bitsDamageType );
pfn->Execute();
return v;
}
}
}
else
return RealTakeDamage( pevInflictor, pevAttacker, flDamage, bitsDamageType );
}
// inflict damage on this entity. bitsDamageType indicates type of damage inflicted, ie: DMG_CRUSH
int CBaseEntity :: RealTakeDamage( entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int bitsDamageType )
{
Vector vecTemp;
if (!pev->takedamage)
return 0;
// UNDONE: some entity types may be immune or resistant to some bitsDamageType
// if Attacker == Inflictor, the attack was a melee or other instant-hit attack.
// (that is, no actual entity projectile was involved in the attack so use the shooter's origin).
if ( pevAttacker == pevInflictor )
{
vecTemp = pevInflictor->origin - ( VecBModelOrigin(pev) );
}
else
// an actual missile was involved.
{
vecTemp = pevInflictor->origin - ( VecBModelOrigin(pev) );
}
// this global is still used for glass and other non-monster killables, along with decals.
g_vecAttackDir = vecTemp.Normalize();
// save damage based on the target's armor level
// figure momentum add (don't let hurt brushes or other triggers move player)
if ((!FNullEnt(pevInflictor)) && (pev->movetype == MOVETYPE_WALK || pev->movetype == MOVETYPE_STEP) && (pevAttacker->solid != SOLID_TRIGGER) )
{
Vector vecDir = pev->origin - (pevInflictor->absmin + pevInflictor->absmax) * 0.5;
vecDir = vecDir.Normalize();
float flForce = flDamage * ((32 * 32 * 72.0) / (pev->size.x * pev->size.y * pev->size.z)) * 5;
if (flForce > 1000.0)
flForce = 1000.0;
pev->velocity = pev->velocity + vecDir * flForce;
}
// do the damage
pev->health -= flDamage;
if (pev->health <= 0)
{
Killed( pevAttacker, GIB_NORMAL );
return 0;
}
return 1;
}
void CBaseEntity::ReSpawn( void )
{
if (scripted && ScriptsActive())
{
GenericFunction *pfn = my_script->funcs->GetFn(M_SPAWN);
if (!pfn)
{
RealReSpawn();
return;
}
if (NoErrors())
{
pfn->PreExecute();
int i = ENTINDEX(edict());
if (pfn->argc > 0)
pfn->PassArg(0, Type(&i, _INT));
switch (pfn->specification)
{
case SPECIFICATION_BEFORE:
pfn->Execute();
RealReSpawn();
break;
case SPECIFICATION_INSTEAD:
pfn->Execute();
break;
default:
RealReSpawn();
pfn->Execute();
break;
}
}
else
RealReSpawn();
}
else
RealReSpawn();
}
//LLAPb end
void EntvarsKeyvalue( entvars_t *pev, KeyValueData *pkvd );
extern "C" void PM_Move ( struct playermove_s *ppmove, int server );
extern "C" void PM_Init ( struct playermove_s *ppmove );
extern "C" char PM_FindTextureType( char *name );
extern Vector VecBModelOrigin( entvars_t* pevBModel );
static DLL_FUNCTIONS gFunctionTable =
{
GameDLLInit, //pfnGameInit
DispatchSpawn, //pfnSpawn
DispatchThink, //pfnThink
DispatchUse, //pfnUse
DispatchTouch, //pfnTouch
DispatchBlocked, //pfnBlocked
DispatchKeyValue, //pfnKeyValue
DispatchSave, //pfnSave
DispatchRestore, //pfnRestore
DispatchObjectCollsionBox, //pfnAbsBox
SaveWriteFields, //pfnSaveWriteFields
SaveReadFields, //pfnSaveReadFields
SaveGlobalState, //pfnSaveGlobalState
RestoreGlobalState, //pfnRestoreGlobalState
ResetGlobalState, //pfnResetGlobalState
ClientConnect, //pfnClientConnect
ClientDisconnect, //pfnClientDisconnect
ClientKill, //pfnClientKill
ClientPutInServer, //pfnClientPutInServer
ClientCommand, //pfnClientCommand
ClientUserInfoChanged, //pfnClientUserInfoChanged
ServerActivate, //pfnServerActivate
ServerDeactivate, //pfnServerDeactivate
PlayerPreThink, //pfnPlayerPreThink
PlayerPostThink, //pfnPlayerPostThink
StartFrame, //pfnStartFrame
ParmsNewLevel, //pfnParmsNewLevel
ParmsChangeLevel, //pfnParmsChangeLevel
GetGameDescription, //pfnGetGameDescription Returns string describing current .dll game.
PlayerCustomization, //pfnPlayerCustomization Notifies .dll of new customization for player.
SpectatorConnect, //pfnSpectatorConnect Called when spectator joins server
SpectatorDisconnect, //pfnSpectatorDisconnect Called when spectator leaves the server
SpectatorThink, //pfnSpectatorThink Called when spectator sends a command packet (usercmd_t)
Sys_Error, //pfnSys_Error Called when engine has encountered an error
PM_Move, //pfnPM_Move
PM_Init, //pfnPM_Init Server version of player movement initialization
PM_FindTextureType, //pfnPM_FindTextureType
SetupVisibility, //pfnSetupVisibility Set up PVS and PAS for networking for this client
UpdateClientData, //pfnUpdateClientData Set up data sent only to specific client
AddToFullPack, //pfnAddToFullPack
CreateBaseline, //pfnCreateBaseline Tweak entity baseline for network encoding, allows setup of player baselines, too.
RegisterEncoders, //pfnRegisterEncoders Callbacks for network encoding
GetWeaponData, //pfnGetWeaponData
CmdStart, //pfnCmdStart
CmdEnd, //pfnCmdEnd
ConnectionlessPacket, //pfnConnectionlessPacket
GetHullBounds, //pfnGetHullBounds
CreateInstancedBaselines, //pfnCreateInstancedBaselines
InconsistentFile, //pfnInconsistentFile
AllowLagCompensation, //pfnAllowLagCompensation
};
static void SetObjectCollisionBox( entvars_t *pev );
#ifndef _WIN32
extern "C" {
#endif
int GetEntityAPI( DLL_FUNCTIONS *pFunctionTable, int interfaceVersion )
{
if ( !pFunctionTable || interfaceVersion != INTERFACE_VERSION )
{
return FALSE;
}
memcpy( pFunctionTable, &gFunctionTable, sizeof( DLL_FUNCTIONS ) );
return TRUE;
}
int GetEntityAPI2( DLL_FUNCTIONS *pFunctionTable, int *interfaceVersion )
{
if ( !pFunctionTable || *interfaceVersion != INTERFACE_VERSION )
{
// Tell engine what version we had, so it can figure out who is out of date.
*interfaceVersion = INTERFACE_VERSION;
return FALSE;
}
memcpy( pFunctionTable, &gFunctionTable, sizeof( DLL_FUNCTIONS ) );
return TRUE;
}
#ifndef _WIN32
}
#endif
//LLAPb: I do not trust this callback, there's a lots of directly calls of "Spawn" in code. Must be reason...
int DispatchSpawn( edict_t *pent )
{
CBaseEntity *pEntity = (CBaseEntity *)GET_PRIVATE(pent);
if (pEntity)
{
// Initialize these or entities who don't link to the world won't have anything in here
pEntity->pev->absmin = pEntity->pev->origin - Vector(1,1,1);
pEntity->pev->absmax = pEntity->pev->origin + Vector(1,1,1);
//LLAPb begin
if (!FStringNull(pEntity->script_file))
{
pEntity->PRECACHE_SCRIPT((char*)STRING(pEntity->script_file));
}
if (pEntity->scripted && ScriptsActive())
{
GenericFunction *pfn = pEntity->my_script->funcs->GetFn(M_SPAWN);
if (!pfn)
{
pEntity->Spawn();
goto LLAPb_end;
}
if (NoErrors())
{
pfn->PreExecute();
int i = ENTINDEX(pent);
if (pfn->argc > 0)
pfn->PassArg(0, Type(&i, _INT));
switch (pfn->specification)
{
case SPECIFICATION_BEFORE:
pfn->Execute();
pEntity->Spawn();
break;
case SPECIFICATION_INSTEAD:
pfn->Execute();
break;
default:
pEntity->Spawn();
pfn->Execute();
break;
}
}
else
pEntity->Spawn();
}
else
pEntity->Spawn();
LLAPb_end:
//LLAPb end
// Try to get the pointer again, in case the spawn function deleted the entity.
// UNDONE: Spawn() should really return a code to ask that the entity be deleted, but
// that would touch too much code for me to do that right now.
pEntity = (CBaseEntity *)GET_PRIVATE(pent);
if ( pEntity )
{
pEntity->pev->colormap = ENTINDEX(pent);
if ( g_pGameRules && !g_pGameRules->IsAllowedToSpawn( pEntity ) )
return -1; // return that this entity should be deleted
if ( pEntity->pev->flags & FL_KILLME )
return -1;
}
// Handle global stuff here
if ( pEntity && pEntity->pev->globalname )
{
const globalentity_t *pGlobal = gGlobalState.EntityFromTable( pEntity->pev->globalname );
if ( pGlobal )
{
// Already dead? delete
if ( pGlobal->state == GLOBAL_DEAD )
return -1;
else if ( !FStrEq( STRING(gpGlobals->mapname), pGlobal->levelName ) )
pEntity->MakeDormant(); // Hasn't been moved to this level yet, wait but stay alive
// In this level & not dead, continue on as normal
}
else
{
// Spawned entities default to 'On'
gGlobalState.EntityAdd( pEntity->pev->globalname, gpGlobals->mapname, GLOBAL_ON );
// ALERT( at_console, "Added global entity %s (%s)\n", STRING(pEntity->pev->classname), STRING(pEntity->pev->globalname) );
}
}
}
return 0;
}
void DispatchKeyValue( edict_t *pentKeyvalue, KeyValueData *pkvd )
{
if ( !pkvd || !pentKeyvalue )
return;
EntvarsKeyvalue( VARS(pentKeyvalue), pkvd );
// If the key was an entity variable, or there's no class set yet, don't look for the object, it may
// not exist yet.
if ( pkvd->fHandled || pkvd->szClassName == NULL )
return;
// Get the actualy entity object
CBaseEntity *pEntity = (CBaseEntity *)GET_PRIVATE(pentKeyvalue);
if ( !pEntity )
return;
pEntity->KeyValue( pkvd );
}
// HACKHACK -- this is a hack to keep the node graph entity from "touching" things (like triggers)
// while it builds the graph
BOOL gTouchDisabled = FALSE;
void DispatchTouch( edict_t *pentTouched, edict_t *pentOther )
{
if ( gTouchDisabled )
return;
CBaseEntity *pEntity = (CBaseEntity *)GET_PRIVATE(pentTouched);
CBaseEntity *pOther = (CBaseEntity *)GET_PRIVATE( pentOther );
//LLAPb changes begin
if ( pEntity && pOther && ! ((pEntity->pev->flags | pOther->pev->flags) & FL_KILLME) )
{
if (!pEntity->scripted || !ScriptsActive())
{
pEntity->Touch( pOther );
return;
}
GenericFunction *pfn = pEntity->my_script->funcs->GetFn(M_TOUCH);
if (!pfn)
{
pEntity->Touch( pOther );
return;
}
if (NoErrors())
{
pfn->PreExecute();
int i = ENTINDEX(pentTouched), j = ENTINDEX(pentOther);
if (pfn->argc > 0)
pfn->PassArg(0, Type(&i, _INT));
if (pfn->argc > 1)
pfn->PassArg(1, Type(&j, _INT));
switch (pfn->specification)
{
case SPECIFICATION_BEFORE:
pfn->Execute();
pEntity->Touch( pOther );
break;
case SPECIFICATION_INSTEAD:
pfn->Execute();
break;
default:
pEntity->Touch( pOther );
pfn->Execute();
break;
}
}
else
pEntity->Touch( pOther );
}
//LLAPb changes end
}
//LLAPb: this function is bullshit!!! Must of all calls of "Use" are coming not from engine. Fuck!!!
void DispatchUse( edict_t *pentUsed, edict_t *pentOther )
{
CBaseEntity *pEntity = (CBaseEntity *)GET_PRIVATE(pentUsed);
CBaseEntity *pOther = (CBaseEntity *)GET_PRIVATE(pentOther);
//LLAPb begin
if (pEntity && !(pEntity->pev->flags & FL_KILLME) )
{
if (!pEntity->scripted || !ScriptsActive())
{
pEntity->Use( pOther, pOther, USE_TOGGLE, 0 );
return;
}
GenericFunction *pfn = pEntity->my_script->funcs->GetFn(M_USE);
if (!pfn)
{
pEntity->Use( pOther, pOther, USE_TOGGLE, 0 );
return;
}
if (NoErrors())
{
pfn->PreExecute();
int i = ENTINDEX(pentUsed), j = ENTINDEX(pentOther), t = (int)USE_TOGGLE;
double v = 0;
if (pfn->argc > 0)
pfn->PassArg(0, Type(&i, _INT));
if (pfn->argc > 1)
pfn->PassArg(1, Type(&j, _INT));
if (pfn->argc > 2)
pfn->PassArg(2, Type(&t, _INT));
if (pfn->argc > 3)
pfn->PassArg(3, Type(&v, DOUBLE));
switch (pfn->specification)
{
case SPECIFICATION_BEFORE:
pfn->Execute();
pEntity->Use( pOther, pOther, USE_TOGGLE, 0 );
break;
case SPECIFICATION_INSTEAD:
pfn->Execute();
break;
default:
pEntity->Use( pOther, pOther, USE_TOGGLE, 0 );
pfn->Execute();
break;
}
}
else
pEntity->Use( pOther, pOther, USE_TOGGLE, 0 );
}
//LLAPb end
}
void DispatchThink( edict_t *pent )
{
CBaseEntity *pEntity = (CBaseEntity *)GET_PRIVATE(pent);
if (pEntity)
{
if ( FBitSet( pEntity->pev->flags, FL_DORMANT ) )
ALERT( at_error, "Dormant entity %s is thinking!!\n", STRING(pEntity->pev->classname) );
//LLAPb begin
if (!pEntity->scripted || !ScriptsActive())
{
pEntity->Think();
return;
}
GenericFunction *pfn = pEntity->my_script->funcs->GetFn(M_THINK);
if (!pfn)
{
pEntity->Think();
return;
}
if (NoErrors())
{
pfn->PreExecute();
int i = ENTINDEX(pent);
double f = gpGlobals->frametime;
if (pfn->argc > 0)
pfn->PassArg(0, Type(&i, _INT));
if (pfn->argc > 1)
pfn->PassArg(1, Type(&f, DOUBLE));
switch (pfn->specification)
{
case SPECIFICATION_BEFORE:
pfn->Execute();
pEntity->Think();
break;
case SPECIFICATION_INSTEAD:
pfn->Execute();
break;
default:
pEntity->Think();
pfn->Execute();
break;
}
}
else
//LLAPb end
pEntity->Think();
}
}
void DispatchBlocked( edict_t *pentBlocked, edict_t *pentOther )
{
CBaseEntity *pEntity = (CBaseEntity *)GET_PRIVATE( pentBlocked );
CBaseEntity *pOther = (CBaseEntity *)GET_PRIVATE( pentOther );
if (pEntity)
pEntity->Blocked( pOther );
}
void DispatchSave( edict_t *pent, SAVERESTOREDATA *pSaveData )
{
CBaseEntity *pEntity = (CBaseEntity *)GET_PRIVATE(pent);
if ( pEntity && pSaveData )
{
ENTITYTABLE *pTable = &pSaveData->pTable[ pSaveData->currentIndex ];
if ( pTable->pent != pent )
ALERT( at_error, "ENTITY TABLE OR INDEX IS WRONG!!!!\n" );
if ( pEntity->ObjectCaps() & FCAP_DONT_SAVE )
return;
// These don't use ltime & nextthink as times really, but we'll fudge around it.
if ( pEntity->pev->movetype == MOVETYPE_PUSH )
{
float delta = pEntity->pev->nextthink - pEntity->pev->ltime;
pEntity->pev->ltime = gpGlobals->time;
pEntity->pev->nextthink = pEntity->pev->ltime + delta;
}
pTable->location = pSaveData->size; // Remember entity position for file I/O
pTable->classname = pEntity->pev->classname; // Remember entity class for respawn
CSave saveHelper( pSaveData );
pEntity->Save( saveHelper );
pTable->size = pSaveData->size - pTable->location; // Size of entity block is data size written to block
}
}
// Find the matching global entity. Spit out an error if the designer made entities of
// different classes with the same global name
CBaseEntity *FindGlobalEntity( string_t classname, string_t globalname )
{
edict_t *pent = FIND_ENTITY_BY_STRING( NULL, "globalname", STRING(globalname) );
CBaseEntity *pReturn = CBaseEntity::Instance( pent );
if ( pReturn )
{
if ( !FClassnameIs( pReturn->pev, STRING(classname) ) )
{
ALERT( at_console, "Global entity found %s, wrong class %s\n", STRING(globalname), STRING(pReturn->pev->classname) );
pReturn = NULL;
}
}
return pReturn;
}
int DispatchRestore( edict_t *pent, SAVERESTOREDATA *pSaveData, int globalEntity )
{
CBaseEntity *pEntity = (CBaseEntity *)GET_PRIVATE(pent);
if ( pEntity && pSaveData )
{
entvars_t tmpVars;
Vector oldOffset;
CRestore restoreHelper( pSaveData );
if ( globalEntity )
{
CRestore tmpRestore( pSaveData );
tmpRestore.PrecacheMode( 0 );
tmpRestore.ReadEntVars( "ENTVARS", &tmpVars );
// HACKHACK - reset the save pointers, we're going to restore for real this time
pSaveData->size = pSaveData->pTable[pSaveData->currentIndex].location;
pSaveData->pCurrentData = pSaveData->pBaseData + pSaveData->size;
// -------------------
const globalentity_t *pGlobal = gGlobalState.EntityFromTable( tmpVars.globalname );
// Don't overlay any instance of the global that isn't the latest
// pSaveData->szCurrentMapName is the level this entity is coming from
// pGlobla->levelName is the last level the global entity was active in.
// If they aren't the same, then this global update is out of date.
if ( !FStrEq( pSaveData->szCurrentMapName, pGlobal->levelName ) )
return 0;
// Compute the new global offset
oldOffset = pSaveData->vecLandmarkOffset;
CBaseEntity *pNewEntity = FindGlobalEntity( tmpVars.classname, tmpVars.globalname );
if ( pNewEntity )
{
// ALERT( at_console, "Overlay %s with %s\n", STRING(pNewEntity->pev->classname), STRING(tmpVars.classname) );
// Tell the restore code we're overlaying a global entity from another level
restoreHelper.SetGlobalMode( 1 ); // Don't overwrite global fields
pSaveData->vecLandmarkOffset = (pSaveData->vecLandmarkOffset - pNewEntity->pev->mins) + tmpVars.mins;
pEntity = pNewEntity;// we're going to restore this data OVER the old entity
pent = ENT( pEntity->pev );
// Update the global table to say that the global definition of this entity should come from this level
gGlobalState.EntityUpdate( pEntity->pev->globalname, gpGlobals->mapname );
}
else
{
// This entity will be freed automatically by the engine. If we don't do a restore on a matching entity (below)
// or call EntityUpdate() to move it to this level, we haven't changed global state at all.
return 0;
}
}
if ( pEntity->ObjectCaps() & FCAP_MUST_SPAWN )
{
pEntity->Restore( restoreHelper );
pEntity->Spawn();
}
else
{
pEntity->Restore( restoreHelper );
pEntity->Precache( );
}
//LLAPb begin
//Call function "LOAD" from here. Remember, that args was already passed to it
//LLAPb end
// Again, could be deleted, get the pointer again.
pEntity = (CBaseEntity *)GET_PRIVATE(pent);
if (pEntity)pEntity->pev->colormap = ENTINDEX(pent);
#if 0
if ( pEntity && pEntity->pev->globalname && globalEntity )
{
ALERT( at_console, "Global %s is %s\n", STRING(pEntity->pev->globalname), STRING(pEntity->pev->model) );
}
#endif
// Is this an overriding global entity (coming over the transition), or one restoring in a level
if ( globalEntity )
{
// ALERT( at_console, "After: %f %f %f %s\n", pEntity->pev->origin.x, pEntity->pev->origin.y, pEntity->pev->origin.z, STRING(pEntity->pev->model) );
pSaveData->vecLandmarkOffset = oldOffset;
if ( pEntity )
{
UTIL_SetOrigin( pEntity->pev, pEntity->pev->origin );
pEntity->OverrideReset();
}
}
else if ( pEntity && pEntity->pev->globalname )
{
const globalentity_t *pGlobal = gGlobalState.EntityFromTable( pEntity->pev->globalname );
if ( pGlobal )
{
// Already dead? delete
if ( pGlobal->state == GLOBAL_DEAD )
return -1;
else if ( !FStrEq( STRING(gpGlobals->mapname), pGlobal->levelName ) )
{
pEntity->MakeDormant(); // Hasn't been moved to this level yet, wait but stay alive
}
// In this level & not dead, continue on as normal
}
else
{
ALERT( at_error, "Global Entity %s (%s) not in table!!!\n", STRING(pEntity->pev->globalname), STRING(pEntity->pev->classname) );
// Spawned entities default to 'On'
gGlobalState.EntityAdd( pEntity->pev->globalname, gpGlobals->mapname, GLOBAL_ON );
}
}
}
return 0;
}
void DispatchObjectCollsionBox( edict_t *pent )
{
CBaseEntity *pEntity = (CBaseEntity *)GET_PRIVATE(pent);
if (pEntity)
{
pEntity->SetObjectCollisionBox();
}
else
SetObjectCollisionBox( &pent->v );
}
void SaveWriteFields( SAVERESTOREDATA *pSaveData, const char *pname, void *pBaseData, TYPEDESCRIPTION *pFields, int fieldCount )
{
CSave saveHelper( pSaveData );
saveHelper.WriteFields( pname, pBaseData, pFields, fieldCount );
}
void SaveReadFields( SAVERESTOREDATA *pSaveData, const char *pname, void *pBaseData, TYPEDESCRIPTION *pFields, int fieldCount )
{
CRestore restoreHelper( pSaveData );
restoreHelper.ReadFields( pname, pBaseData, pFields, fieldCount );
}
edict_t * EHANDLE::Get( void )
{
if (m_pent)
{
if (m_pent->serialnumber == m_serialnumber)
return m_pent;
else
return NULL;
}
return NULL;
};
edict_t * EHANDLE::Set( edict_t *pent )
{
m_pent = pent;
if (pent)
m_serialnumber = m_pent->serialnumber;
return pent;
};
EHANDLE :: operator CBaseEntity *()
{
return (CBaseEntity *)GET_PRIVATE( Get( ) );
};
CBaseEntity * EHANDLE :: operator = (CBaseEntity *pEntity)
{
if (pEntity)
{
m_pent = ENT( pEntity->pev );
if (m_pent)
m_serialnumber = m_pent->serialnumber;
}
else
{
m_pent = NULL;
m_serialnumber = 0;
}
return pEntity;
}
EHANDLE :: operator int ()
{
return Get() != NULL;
}
CBaseEntity * EHANDLE :: operator -> ()
{
return (CBaseEntity *)GET_PRIVATE( Get( ) );
}
//LLAPb begin
void CBaseEntity::PRECACHE_SCRIPT ( char *filename )
{
my_script = CreateScript (filename);
if (NoErrors())
scripted = true;
else
{
FreeScript( my_script );
my_script = 0;
scripted = false;
}
}
void CBaseEntity::UNLOAD_SCRIPT ()
{
if (my_script) FreeScript(my_script);
my_script = 0;
scripted = false;
}
//LLAPb end
// give health
int CBaseEntity :: TakeHealth( float flHealth, int bitsDamageType )
{
if (!pev->takedamage)
return 0;
// heal
if ( pev->health >= pev->max_health )
return 0;
pev->health += flHealth;
if (pev->health > pev->max_health)
pev->health = pev->max_health;
return 1;
}
void CBaseEntity :: Killed( entvars_t *pevAttacker, int iGib )
{
pev->takedamage = DAMAGE_NO;
pev->deadflag = DEAD_DEAD;
UTIL_Remove( this );
}
CBaseEntity *CBaseEntity::GetNextTarget( void )
{
if ( FStringNull( pev->target ) )
return NULL;
edict_t *pTarget = FIND_ENTITY_BY_TARGETNAME ( NULL, STRING(pev->target) );
if ( FNullEnt(pTarget) )
return NULL;
return Instance( pTarget );
}
// Global Savedata for Delay
TYPEDESCRIPTION CBaseEntity::m_SaveData[] =
{
DEFINE_FIELD( CBaseEntity, m_pGoalEnt, FIELD_CLASSPTR ),
DEFINE_FIELD( CBaseEntity, m_pfnThink, FIELD_FUNCTION ), // UNDONE: Build table of these!!!
DEFINE_FIELD( CBaseEntity, m_pfnTouch, FIELD_FUNCTION ),
DEFINE_FIELD( CBaseEntity, m_pfnUse, FIELD_FUNCTION ),
DEFINE_FIELD( CBaseEntity, m_pfnBlocked, FIELD_FUNCTION ),
//LLAPb begin
DEFINE_FIELD( CBaseEntity, script_file, FIELD_STRING ),
DEFINE_FIELD( CBaseEntity, scripted, FIELD_INTEGER )
//LLAPb end
};
int CBaseEntity::Save( CSave &save )
{
int res;
if ( save.WriteEntVars( "ENTVARS", pev ) )
{
res = save.WriteFields( "BASE", this, m_SaveData, ARRAYSIZE(m_SaveData) );
//LLAPb begin
if (res)
{
//Find function "SAVE", store an array, returned by it
}
//LLAPb end
}
return res;
}
int CBaseEntity::Restore( CRestore &restore )
{
int status;
status = restore.ReadEntVars( "ENTVARS", pev );
if ( status )
status = restore.ReadFields( "BASE", this, m_SaveData, ARRAYSIZE(m_SaveData) );
//LLAPb begin
//Precache script
//if ( status )
//status = restore.ReadScriptVars( "SAMOGON" ... );
//Find function "LOAD", pass args to it, but don't call it!!!
//LLAPb end
if ( pev->modelindex != 0 && !FStringNull(pev->model) )
{
Vector mins, maxs;
mins = pev->mins; // Set model is about to destroy these
maxs = pev->maxs;
PRECACHE_MODEL( (char *)STRING(pev->model) );
SET_MODEL(ENT(pev), STRING(pev->model));
UTIL_SetSize(pev, mins, maxs); // Reset them
}
return status;
}
// Initialize absmin & absmax to the appropriate box
void SetObjectCollisionBox( entvars_t *pev )
{
if ( (pev->solid == SOLID_BSP) &&
(pev->angles.x || pev->angles.y|| pev->angles.z) )
{ // expand for rotation
float max, v;
int i;
max = 0;
for (i=0 ; i<3 ; i++)
{
v = fabs( ((float *)pev->mins)[i]);
if (v > max)
max = v;
v = fabs( ((float *)pev->maxs)[i]);
if (v > max)
max = v;
}
for (i=0 ; i<3 ; i++)
{
((float *)pev->absmin)[i] = ((float *)pev->origin)[i] - max;
((float *)pev->absmax)[i] = ((float *)pev->origin)[i] + max;
}
}
else
{
pev->absmin = pev->origin + pev->mins;
pev->absmax = pev->origin + pev->maxs;
}
pev->absmin.x -= 1;
pev->absmin.y -= 1;
pev->absmin.z -= 1;
pev->absmax.x += 1;
pev->absmax.y += 1;
pev->absmax.z += 1;
}
void CBaseEntity::SetObjectCollisionBox( void )
{
::SetObjectCollisionBox( pev );
}
int CBaseEntity :: Intersects( CBaseEntity *pOther )
{
if ( pOther->pev->absmin.x > pev->absmax.x ||
pOther->pev->absmin.y > pev->absmax.y ||
pOther->pev->absmin.z > pev->absmax.z ||
pOther->pev->absmax.x < pev->absmin.x ||
pOther->pev->absmax.y < pev->absmin.y ||
pOther->pev->absmax.z < pev->absmin.z )
return 0;
return 1;
}
void CBaseEntity :: MakeDormant( void )
{
SetBits( pev->flags, FL_DORMANT );
// Don't touch
pev->solid = SOLID_NOT;
// Don't move
pev->movetype = MOVETYPE_NONE;
// Don't draw
SetBits( pev->effects, EF_NODRAW );
// Don't think
pev->nextthink = 0;
// Relink
UTIL_SetOrigin( pev, pev->origin );
}
int CBaseEntity :: IsDormant( void )
{
return FBitSet( pev->flags, FL_DORMANT );
}
BOOL CBaseEntity :: IsInWorld( void )
{
// position
if (pev->origin.x >= 8192) return FALSE;
if (pev->origin.y >= 8192) return FALSE;
if (pev->origin.z >= 8192) return FALSE;
if (pev->origin.x <= -8192) return FALSE;
if (pev->origin.y <= -8192) return FALSE;
if (pev->origin.z <= -8192) return FALSE;
// speed
if (pev->velocity.x >= 1000000) return FALSE;
if (pev->velocity.y >= 1000000) return FALSE;
if (pev->velocity.z >= 1000000) return FALSE;
if (pev->velocity.x <= -1000000) return FALSE;
if (pev->velocity.y <= -1000000) return FALSE;
if (pev->velocity.z <= -1000000) return FALSE;
return TRUE;
}
int CBaseEntity::ShouldToggle( USE_TYPE useType, BOOL currentState )
{
if ( useType != USE_TOGGLE && useType != USE_SET )
{
if ( (currentState && useType == USE_ON) || (!currentState && useType == USE_OFF) )
return 0;
}
return 1;
}
// NOTE: szName must be a pointer to constant memory, e.g. "monster_class" because the entity
// will keep a pointer to it after this call.
CBaseEntity * CBaseEntity::Create( char *szName, const Vector &vecOrigin, const Vector &vecAngles, edict_t *pentOwner )
{
edict_t *pent;
CBaseEntity *pEntity;
pent = CREATE_NAMED_ENTITY( MAKE_STRING( szName ));
if ( FNullEnt( pent ) )
{
ALERT ( at_console, "NULL Ent in Create!\n" );
return NULL;
}
pEntity = Instance( pent );
pEntity->pev->owner = pentOwner;
pEntity->pev->origin = vecOrigin;
pEntity->pev->angles = vecAngles;
DispatchSpawn( pEntity->edict() );
return pEntity;
} | [
"[email protected]"
] | |
28b906913e51b8dc425227e4af597a523f153611 | a2e04e4eac1cf93bb4c1d429e266197152536a87 | /Cpp/SDK/Title_MA_07_MerchantCommander_classes.h | 2b38ab8efaaf2d7a30c07ec54b32a461125b0260 | [] | no_license | zH4x-SDK/zSoT-SDK | 83a4b9fcdf628637613197cf644b7f4d101bb0cb | 61af221bee23701a5df5f60091f96f2cf929846e | refs/heads/main | 2023-07-16T18:23:41.914014 | 2021-08-27T15:44:23 | 2021-08-27T15:44:23 | 400,555,804 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 786 | h | #pragma once
// Name: SoT, Version: 2.2.1.1
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass Title_MA_07_MerchantCommander.Title_MA_07_MerchantCommander_C
// 0x0000 (FullSize[0x00E0] - InheritedSize[0x00E0])
class UTitle_MA_07_MerchantCommander_C : public UTitleDesc
{
public:
static UClass* StaticClass()
{
static UClass* ptr = UObject::FindClass("BlueprintGeneratedClass Title_MA_07_MerchantCommander.Title_MA_07_MerchantCommander_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
07f8d636510a722791b2607629fe5ac725b71fb7 | f3660c7c295b6f7d26cdb287015d710fe9637ed0 | /src/30.cpp | 1117f3daa6cc1bd1c9e6147a07ffdbd47527a2cb | [] | no_license | freehawkzk/leetCode | d32e081cab2f772fc7b33056e228eb3709cb19f2 | 990019bf9eca7f619f69fe1157d7a0488f8a83c6 | refs/heads/master | 2021-01-10T11:47:44.846832 | 2020-09-14T07:14:01 | 2020-09-14T07:14:01 | 55,280,051 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,480 | cpp | #include <string>
#include<vector>
#include <algorithm>
#include <iostream>
std::vector<int> findSubstring(std::string s, std::vector<std::string>& words)
{
if (s.length() == 0)
return std::vector<int>();
if (words.size() == 0)
return std::vector<int>();
std::string s0 = s;
std::vector<int> res;
std::string t;
std::sort(words.begin(), words.end());
for (int i = 0;i< words.size();i++)
{
t += words[i];
}
size_t pos = std::string::npos;
int n = 0;
while (( pos = s.find(t))!=std::string::npos)
{
if (res.size() == 0)
res.push_back(pos);
else
res.push_back(pos + n);
n=n+pos+1;
s = s.substr(pos+1, s.length());
}
while (std::next_permutation(words.begin(),words.end()))
{
std::string t;
for (int i = 0; i < words.size(); i++)
{
t += words[i];
}
size_t pos = std::string::npos;
s = s0;
std::vector<int> res1;
int n = 0;
while ((pos = s.find(t)) != std::string::npos)
{
if (res1.size() == 0)
res1.push_back(pos);
else
res1.push_back(pos +n);
n=n+pos+1;
s = s.substr(pos+1, s.length());
}
for (int i = 0;i<res1.size();i++)
{
res.push_back(res1[i]);
}
}
return res;
}
int main()
{
std::string s = "pjzkrkevzztxductzzxmxsvwjkxpvukmfjywwetvfnujhweiybwvvsrfequzkhossmootkmyxgjgfordrpapjuunmqnxxdrqrfgkrsjqbszgiqlcfnrpjlcwdrvbumtotzylshdvccdmsqoadfrpsvnwpizlwszrtyclhgilklydbmfhuywotjmktnwrfvizvnmfvvqfiokkdprznnnjycttprkxpuykhmpchiksyucbmtabiqkisgbhxngmhezrrqvayfsxauampdpxtafniiwfvdufhtwajrbkxtjzqjnfocdhekumttuqwovfjrgulhekcpjszyynadxhnttgmnxkduqmmyhzfnjhducesctufqbumxbamalqudeibljgbspeotkgvddcwgxidaiqcvgwykhbysjzlzfbupkqunuqtraxrlptivshhbihtsigtpipguhbhctcvubnhqipncyxfjebdnjyetnlnvmuxhzsdahkrscewabejifmxombiamxvauuitoltyymsarqcuuoezcbqpdaprxmsrickwpgwpsoplhugbikbkotzrtqkscekkgwjycfnvwfgdzogjzjvpcvixnsqsxacfwndzvrwrycwxrcismdhqapoojegggkocyrdtkzmiekhxoppctytvphjynrhtcvxcobxbcjjivtfjiwmduhzjokkbctweqtigwfhzorjlkpuuliaipbtfldinyetoybvugevwvhhhweejogrghllsouipabfafcxnhukcbtmxzshoyyufjhzadhrelweszbfgwpkzlwxkogyogutscvuhcllphshivnoteztpxsaoaacgxyaztuixhunrowzljqfqrahosheukhahhbiaxqzfmmwcjxountkevsvpbzjnilwpoermxrtlfroqoclexxisrdhvfsindffslyekrzwzqkpeocilatftymodgztjgybtyheqgcpwogdcjlnlesefgvimwbxcbzvaibspdjnrpqtyeilkcspknyylbwndvkffmzuriilxagyerjptbgeqgebiaqnvdubrtxibhvakcyotkfonmseszhczapxdlauexehhaireihxsplgdgmxfvaevrbadbwjbdrkfbbjjkgcztkcbwagtcnrtqryuqixtzhaakjlurnumzyovawrcjiwabuwretmdamfkxrgqgcdgbrdbnugzecbgyxxdqmisaqcyjkqrntxqmdrczxbebemcblftxplafnyoxqimkhcykwamvdsxjezkpgdpvopddptdfbprjustquhlazkjfluxrzopqdstulybnqvyknrchbphcarknnhhovweaqawdyxsqsqahkepluypwrzjegqtdoxfgzdkydeoxvrfhxusrujnmjzqrrlxglcmkiykldbiasnhrjbjekystzilrwkzhontwmehrfsrzfaqrbbxncphbzuuxeteshyrveamjsfiaharkcqxefghgceeixkdgkuboupxnwhnfigpkwnqdvzlydpidcljmflbccarbiegsmweklwngvygbqpescpeichmfidgsjmkvkofvkuehsmkkbocgejoiqcnafvuokelwuqsgkyoekaroptuvekfvmtxtqshcwsztkrzwrpabqrrhnlerxjojemcxel";
std::vector<std::string> words = { "dhvf","sind","ffsl","yekr","zwzq","kpeo","cila","tfty","modg","ztjg","ybty","heqg","cpwo","gdcj","lnle","sefg","vimw","bxcb" };
std::vector<int> v = findSubstring(s, words);
for (int i = 0;i<v.size();i++)
{
std::cout << v[i] << std::endl;
}
return 0;
} | [
"[email protected]"
] | |
1b298ee9601e240be70660126046775c7a5f27c7 | ac1c9fbc1f1019efb19d0a8f3a088e8889f1e83c | /out/release/gen/services/viz/public/mojom/compositing/video_detector_observer.mojom-blink.cc | 1324762ac1e3faccff19a17ed1eb93d67bc6adeb | [
"BSD-3-Clause"
] | permissive | xueqiya/chromium_src | 5d20b4d3a2a0251c063a7fb9952195cda6d29e34 | d4aa7a8f0e07cfaa448fcad8c12b29242a615103 | refs/heads/main | 2022-07-30T03:15:14.818330 | 2021-01-16T16:47:22 | 2021-01-16T16:47:22 | 330,115,551 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,953 | cc | // services/viz/public/mojom/compositing/video_detector_observer.mojom-blink.cc is auto generated by mojom_bindings_generator.py, do not edit
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-private-field"
#elif defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable:4056)
#pragma warning(disable:4065)
#pragma warning(disable:4756)
#endif
#include "services/viz/public/mojom/compositing/video_detector_observer.mojom-blink.h"
#include <math.h>
#include <stdint.h>
#include <utility>
#include "base/hash/md5_constexpr.h"
#include "base/logging.h"
#include "base/run_loop.h"
#include "base/task/common/task_annotator.h"
#include "mojo/public/cpp/bindings/lib/generated_code_util.h"
#include "mojo/public/cpp/bindings/lib/message_internal.h"
#include "mojo/public/cpp/bindings/lib/serialization_util.h"
#include "mojo/public/cpp/bindings/lib/unserialized_message_context.h"
#include "mojo/public/cpp/bindings/lib/validate_params.h"
#include "mojo/public/cpp/bindings/lib/validation_context.h"
#include "mojo/public/cpp/bindings/lib/validation_errors.h"
#include "mojo/public/interfaces/bindings/interface_control_messages.mojom.h"
#include "services/viz/public/mojom/compositing/video_detector_observer.mojom-params-data.h"
#include "services/viz/public/mojom/compositing/video_detector_observer.mojom-shared-message-ids.h"
#include "services/viz/public/mojom/compositing/video_detector_observer.mojom-blink-import-headers.h"
#include "mojo/public/cpp/bindings/lib/wtf_serialization.h"
#ifndef SERVICES_VIZ_PUBLIC_MOJOM_COMPOSITING_VIDEO_DETECTOR_OBSERVER_MOJOM_BLINK_JUMBO_H_
#define SERVICES_VIZ_PUBLIC_MOJOM_COMPOSITING_VIDEO_DETECTOR_OBSERVER_MOJOM_BLINK_JUMBO_H_
#endif
namespace viz {
namespace mojom {
namespace blink {
const char VideoDetectorObserver::Name_[] = "viz.mojom.VideoDetectorObserver";
VideoDetectorObserverProxy::VideoDetectorObserverProxy(mojo::MessageReceiverWithResponder* receiver)
: receiver_(receiver) {
}
void VideoDetectorObserverProxy::OnVideoActivityStarted(
) {
#if BUILDFLAG(MOJO_TRACE_ENABLED)
TRACE_EVENT0("mojom", "viz::mojom::VideoDetectorObserver::OnVideoActivityStarted");
#endif
const bool kExpectsResponse = false;
const bool kIsSync = false;
const uint32_t kFlags =
((kExpectsResponse) ? mojo::Message::kFlagExpectsResponse : 0) |
((kIsSync) ? mojo::Message::kFlagIsSync : 0);
mojo::Message message(
internal::kVideoDetectorObserver_OnVideoActivityStarted_Name, kFlags, 0, 0, nullptr);
auto* buffer = message.payload_buffer();
::viz::mojom::internal::VideoDetectorObserver_OnVideoActivityStarted_Params_Data::BufferWriter
params;
mojo::internal::SerializationContext serialization_context;
params.Allocate(buffer);
message.AttachHandlesFromSerializationContext(
&serialization_context);
#if defined(ENABLE_IPC_FUZZER)
message.set_interface_name(VideoDetectorObserver::Name_);
message.set_method_name("OnVideoActivityStarted");
#endif
// This return value may be ignored as false implies the Connector has
// encountered an error, which will be visible through other means.
ignore_result(receiver_->Accept(&message));
}
void VideoDetectorObserverProxy::OnVideoActivityEnded(
) {
#if BUILDFLAG(MOJO_TRACE_ENABLED)
TRACE_EVENT0("mojom", "viz::mojom::VideoDetectorObserver::OnVideoActivityEnded");
#endif
const bool kExpectsResponse = false;
const bool kIsSync = false;
const uint32_t kFlags =
((kExpectsResponse) ? mojo::Message::kFlagExpectsResponse : 0) |
((kIsSync) ? mojo::Message::kFlagIsSync : 0);
mojo::Message message(
internal::kVideoDetectorObserver_OnVideoActivityEnded_Name, kFlags, 0, 0, nullptr);
auto* buffer = message.payload_buffer();
::viz::mojom::internal::VideoDetectorObserver_OnVideoActivityEnded_Params_Data::BufferWriter
params;
mojo::internal::SerializationContext serialization_context;
params.Allocate(buffer);
message.AttachHandlesFromSerializationContext(
&serialization_context);
#if defined(ENABLE_IPC_FUZZER)
message.set_interface_name(VideoDetectorObserver::Name_);
message.set_method_name("OnVideoActivityEnded");
#endif
// This return value may be ignored as false implies the Connector has
// encountered an error, which will be visible through other means.
ignore_result(receiver_->Accept(&message));
}
// static
bool VideoDetectorObserverStubDispatch::Accept(
VideoDetectorObserver* impl,
mojo::Message* message) {
switch (message->header()->name) {
case internal::kVideoDetectorObserver_OnVideoActivityStarted_Name: {
#if BUILDFLAG(MOJO_TRACE_ENABLED)
TRACE_EVENT1(
"mojom",
"(Impl)viz::mojom::VideoDetectorObserver::OnVideoActivityStarted",
"message", message->name());
#endif
static constexpr uint32_t kMessageHash = base::MD5Hash32Constexpr(
"(Impl)viz::mojom::VideoDetectorObserver::OnVideoActivityStarted");
base::TaskAnnotator::ScopedSetIpcHash scoped_ipc_hash(kMessageHash);
mojo::internal::MessageDispatchContext dispatch_context(message);
DCHECK(message->is_serialized());
internal::VideoDetectorObserver_OnVideoActivityStarted_Params_Data* params =
reinterpret_cast<internal::VideoDetectorObserver_OnVideoActivityStarted_Params_Data*>(
message->mutable_payload());
mojo::internal::SerializationContext serialization_context;
serialization_context.TakeHandlesFromMessage(message);
bool success = true;
VideoDetectorObserver_OnVideoActivityStarted_ParamsDataView input_data_view(params, &serialization_context);
if (!success) {
ReportValidationErrorForMessage(
message,
mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED,
VideoDetectorObserver::Name_, 0, false);
return false;
}
// A null |impl| means no implementation was bound.
DCHECK(impl);
impl->OnVideoActivityStarted();
return true;
}
case internal::kVideoDetectorObserver_OnVideoActivityEnded_Name: {
#if BUILDFLAG(MOJO_TRACE_ENABLED)
TRACE_EVENT1(
"mojom",
"(Impl)viz::mojom::VideoDetectorObserver::OnVideoActivityEnded",
"message", message->name());
#endif
static constexpr uint32_t kMessageHash = base::MD5Hash32Constexpr(
"(Impl)viz::mojom::VideoDetectorObserver::OnVideoActivityEnded");
base::TaskAnnotator::ScopedSetIpcHash scoped_ipc_hash(kMessageHash);
mojo::internal::MessageDispatchContext dispatch_context(message);
DCHECK(message->is_serialized());
internal::VideoDetectorObserver_OnVideoActivityEnded_Params_Data* params =
reinterpret_cast<internal::VideoDetectorObserver_OnVideoActivityEnded_Params_Data*>(
message->mutable_payload());
mojo::internal::SerializationContext serialization_context;
serialization_context.TakeHandlesFromMessage(message);
bool success = true;
VideoDetectorObserver_OnVideoActivityEnded_ParamsDataView input_data_view(params, &serialization_context);
if (!success) {
ReportValidationErrorForMessage(
message,
mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED,
VideoDetectorObserver::Name_, 1, false);
return false;
}
// A null |impl| means no implementation was bound.
DCHECK(impl);
impl->OnVideoActivityEnded();
return true;
}
}
return false;
}
// static
bool VideoDetectorObserverStubDispatch::AcceptWithResponder(
VideoDetectorObserver* impl,
mojo::Message* message,
std::unique_ptr<mojo::MessageReceiverWithStatus> responder) {
switch (message->header()->name) {
case internal::kVideoDetectorObserver_OnVideoActivityStarted_Name: {
break;
}
case internal::kVideoDetectorObserver_OnVideoActivityEnded_Name: {
break;
}
}
return false;
}
static const mojo::internal::GenericValidationInfo kVideoDetectorObserverValidationInfo[] = {
{&internal::VideoDetectorObserver_OnVideoActivityStarted_Params_Data::Validate,
nullptr /* no response */},
{&internal::VideoDetectorObserver_OnVideoActivityEnded_Params_Data::Validate,
nullptr /* no response */},
};
bool VideoDetectorObserverRequestValidator::Accept(mojo::Message* message) {
const char* name = ::viz::mojom::blink::VideoDetectorObserver::Name_;
return mojo::internal::ValidateRequestGenericPacked(message, name, kVideoDetectorObserverValidationInfo);
}
} // namespace blink
} // namespace mojom
} // namespace viz
namespace mojo {
} // namespace mojo
#if defined(__clang__)
#pragma clang diagnostic pop
#elif defined(_MSC_VER)
#pragma warning(pop)
#endif | [
"[email protected]"
] | |
0becf55680f30e0ba8203f29eca55f2e4dd90547 | d89fd32d0909e77031f10afc36175887e13673f4 | /src/ContextMenu.cpp | 42ad950371ed0c4454c4aceb400aae28a04ef6d4 | [
"MIT"
] | permissive | ExpLife0011/NAntMenu | def3fc0c3e28083a876fdf0599ce48b389d3796a | 6f5f5e8835d29099b7d4eb27f6a4293bfc83be90 | refs/heads/master | 2020-04-14T12:23:11.398415 | 2015-11-05T02:58:52 | 2015-11-05T07:56:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,748 | cpp | /* NAntMenu - Implementation of the context menu handler
* Copyright (C) 2003 Mathias Hasselmann <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "ContextMenu.h"
#define MODULENAME L##"NAntMenu.dll"
#define CMDINFO(Caption, Verb, Help) \
{ Caption, Verb, Help, L##Caption, L##Verb, L##Help }
#ifdef _UNICODE
#define T(Str) L##Str
#define Caption wcsCaption
#define Help wcsHelp
#define Verb wcsVerb
#else
#define T(Str) Str
#define Caption strCaption
#define Help strHelp
#define Verb strVerb
#endif
#define StrLen _tcslen
CNAntCommand CNAntContextMenu::commands[] =
{
CMDINFO("Edit", "NAntMenuEdit" ,"Edit this build script"),
CMDINFO("Explore", "NAntMenuBrowse" ,"Explore the project's folder"),
CMDINFO("Command Prompt", "NAntMenuShell" ,"Open a command prompt for the project's folder"),
CMDINFO("Help", "NAntMenuHelp" ,"Display help files for NAnt"),
CMDINFO("Default", "NAntMenuDefault" ,"Build the project's default target")
};
static bool Failed(LONG result)
{
if (NOERROR != result)
{
SetLastError(result);
return true;
}
return false;
}
HRESULT STDMETHODCALLTYPE
CNAntContextMenu::UpdateRegistry(BOOL bRegister)
{
OLECHAR clsid[64];
HMODULE module;
TCHAR filename[MAX_PATH];
if (!StringFromGUID2(CLSID_CNAntContextMenu, clsid, sizeof(clsid)) ||
NULL == (module = GetModuleHandle(MODULENAME)) ||
!GetModuleFileName(module, filename, sizeof(filename)))
{
MessageBox(0, L"Cannot locate " MODULENAME L".", 0, 0);
return HRESULT_FROM_WIN32(GetLastError());
}
bstr_t nClass(bstr_t("CLSID\\") + clsid);
OutputDebugString(nClass);
if (bRegister)
{
//
// Register the COM object
//
CRegKey rClass;
CRegKey rInProc;
if (Failed(rClass.Create(HKEY_CLASSES_ROOT, nClass)) ||
Failed(rClass.SetStringValue(NULL, L"NAntMenu Shell Extension")) ||
Failed(rInProc.Create(rClass, L"InprocServer32")) ||
Failed(rInProc.SetStringValue(NULL, filename)) ||
Failed(rInProc.SetStringValue(L"ThreadingModel", L"Apartment")))
{
MessageBox(0, L"Cannot register COM object.", 0, 0);
return HRESULT_FROM_WIN32(GetLastError());
}
//
// Register the file type
//
CRegKey rDotBuild;
CRegKey rNAntScript;
CRegKey rDefaultIcon;
CRegKey rNAntMenu;
bstr_t defaultIcon(bstr_t(filename) + ",0");
if (Failed(rDotBuild.Create(HKEY_CLASSES_ROOT, L".build")) ||
Failed(rDotBuild.SetStringValue(NULL, L"NAntBuildScript")) ||
Failed(rNAntScript.Create(HKEY_CLASSES_ROOT, L"NAntBuildScript")) ||
Failed(rNAntScript.SetStringValue(NULL, L"NAnt Build Script")) ||
Failed(rDefaultIcon.Create(rNAntScript, L"DefaultIcon")) ||
Failed(rDefaultIcon.SetStringValue(NULL, defaultIcon)) ||
Failed(rNAntMenu.Create(rNAntScript, L"shellex\\ContextMenuHandlers\\NAntMenu")) ||
Failed(rNAntMenu.SetStringValue(NULL, bstr_t(clsid))))
{
MessageBox(0, L"Cannot register file type.", 0, 0);
return HRESULT_FROM_WIN32(GetLastError());
}
}
else
{
//
// Unregister the file type
//
CRegKey rHKEY_CR;
rHKEY_CR.Attach(HKEY_CLASSES_ROOT); //Attach will assert if m_hKey is non-NULL.
if (
Failed(rHKEY_CR.DeleteSubKey(L".build")) ||
Failed(rHKEY_CR.RecurseDeleteKey(L"NAntBuildScript"))
)
{
MessageBox(0, L"Unregister COM:Cannot Unregister file type.", 0, 0);
return HRESULT_FROM_WIN32(GetLastError());
}
//
// Unregister the COM object
//
bstr_t cClass(clsid);
CRegKey rClass;
OutputDebugString(nClass);
if (Failed(rClass.Open(HKEY_CLASSES_ROOT, nClass))) {
MessageBox(0, L"Unregister COM: Cannot open GUID", 0, 0);
return HRESULT_FROM_WIN32(GetLastError());
}
if (Failed(rClass.DeleteSubKey (L"InprocServer32"))) {
MessageBox(0, L"Unregister COM: Cannot Delete InprocServer32", 0, 0);
return HRESULT_FROM_WIN32(GetLastError());
}
if (Failed(rClass.Open(HKEY_CLASSES_ROOT,L"CLSID"))) {
MessageBox(0, L"Unregister COM: Cannot Open CLSID", 0, 0);
return HRESULT_FROM_WIN32(GetLastError());
}
if (Failed(rClass.DeleteSubKey(cClass))){
MessageBox(0, L"Unregister COM: Cannot delete GUID", 0, 0);
return HRESULT_FROM_WIN32(GetLastError());
}
}
SHChangeNotify (SHCNE_ASSOCCHANGED,SHCNF_IDLIST, NULL,NULL);
return S_OK;
}
HRESULT CNAntContextMenu::LoadScript(LPCTSTR filename)
{
HRESULT result = S_OK;
if (!this->script)
result = this->script.CoCreateInstance(L"Msxml2.DOMDocument");
this->targetCount = 0;
this->defaultTarget = 0;
if (!this->targets)
{
CNAntTarget * t = targets;
this->targets = 0;
delete[] t;
}
VARIANT_BOOL scriptLoaded;
CComPtr<IXMLDOMElement> project;
variant_t defaultTarget;
CComPtr<IXMLDOMNodeList> targetList;
if (SUCCEEDED(result) &&
SUCCEEDED(result = this->script->load(variant_t(filename), &scriptLoaded)) && scriptLoaded &&
SUCCEEDED(this->script->get_documentElement(&project)) && project &&
SUCCEEDED(project->getAttribute(bstr_t("default"), &defaultTarget)) &&
SUCCEEDED(this->script->selectNodes(bstr_t("/project/target[@description]"),&targetList)) &&
SUCCEEDED(targetList->get_length(&this->targetCount)))
{
bstr_t defaultTargetName(defaultTarget);
CComPtr<IXMLDOMNode> node;
CComPtr<IXMLDOMElement> target;
variant_t name, desc;
this->targets = new CNAntTarget[this->targetCount + 1];
CNAntTarget * first = this->targets;
while (SUCCEEDED(targetList->nextNode(&node)) && node &&
SUCCEEDED(node.QueryInterface(&target)) &&
SUCCEEDED(target->getAttribute(bstr_t("name"), &name)) &&
SUCCEEDED(target->getAttribute(bstr_t("description"), &desc)))
{
first->name = name;
first->desc = desc;
if (!this->defaultTarget && first->name == defaultTargetName)
this->defaultTarget = first;
first++;
}
if (!this->defaultTarget && defaultTargetName.length())
{
this->defaultTarget = this->targets + this->targetCount;
first->name = defaultTargetName;
first->desc = L"Build the default target";
}
}
return result;
}
HRESULT STDMETHODCALLTYPE
CNAntContextMenu::Initialize(LPCITEMIDLIST pidlFolder,
LPDATAOBJECT dataObject, HKEY hkeyProgID)
{
HRESULT result = E_FAIL;
if (dataObject)
{
FORMATETC format =
{
CF_HDROP, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL
};
STGMEDIUM medium;
result = dataObject->GetData(&format, &medium);
if (S_OK == result)
{
HDROP hDrop = HDROP(GlobalLock(medium.hGlobal));
if (1 == DragQueryFile(hDrop, 0xFFFFFFFF, NULL, 0) &&
0 != DragQueryFile(hDrop, 0, this->filename,
sizeof(this->filename)))
{
result = this->LoadScript(this->filename);
}
else
{
*this->filename = '\0';
result = HRESULT_FROM_WIN32(GetLastError());
}
HMODULE module = GetModuleHandle(MODULENAME);
const INT icx = GetSystemMetrics(SM_CXSMICON);
const INT icy = GetSystemMetrics(SM_CXSMICON);
this->hIcons[IdCmd_Edit] = HICON(LoadImage(module, L"edit", IMAGE_ICON, icx, icy, 0));
this->hIcons[IdCmd_Browse] = HICON(LoadImage(module, L"explore", IMAGE_ICON, icx, icy, 0));
this->hIcons[IdCmd_Shell] = HICON(LoadImage(module, L"shell", IMAGE_ICON, icx, icy, 0));
this->hIcons[IdCmd_Help] = HICON(LoadImage(module, L"help", IMAGE_ICON, icx, icy, 0));
this->hIcons[IdCmd_Default] =HICON(LoadImage(module, L"build", IMAGE_ICON, icx, icy, 0));
GlobalUnlock(hDrop);
GlobalFree(medium.hGlobal);
}
}
return result;
}
static BOOL MenuItemSetDefault(HMENU hMenu, UINT uItem,
BOOL fByPosition, BOOL fDefault)
{
MENUITEMINFO itemInfo;
memset(&itemInfo, 0, sizeof(itemInfo));
itemInfo.cbSize = sizeof(itemInfo);
itemInfo.fMask = MIIM_STATE;
if (GetMenuItemInfo(hMenu, uItem, fByPosition, &itemInfo))
{
itemInfo.fState = fDefault ?
itemInfo.fState | MFS_DEFAULT :
itemInfo.fState & ~MFS_DEFAULT;
return SetMenuItemInfo(hMenu, uItem, fByPosition, &itemInfo);
}
return FALSE;
}
HRESULT STDMETHODCALLTYPE
CNAntContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu, UINT idCmdFirst, UINT idCmdLast, UINT uFlags)
{
if (!(uFlags & CMF_DEFAULTONLY))
{
HMENU hPopup = CreateMenu();
this->idCmdFirst = idCmdFirst;
CNAntTarget const * first = this->targets;
CNAntTarget const * const last = first + this->targetCount;
while (first < last &&
AppendMenu(hPopup, MF_STRING, idCmdFirst, first->name) &&
MenuItemSetDefault(hPopup, idCmdFirst, FALSE, first == this->defaultTarget))
{
idCmdFirst++;
first++;
}
AppendMenu(hPopup, MF_SEPARATOR, 0, NULL);
AppendMenu(hPopup, MF_OWNERDRAW | MF_STRING, idCmdFirst++, T("&Edit"));
AppendMenu(hPopup, MF_OWNERDRAW | MF_STRING, idCmdFirst++, T("&Browse"));
AppendMenu(hPopup, MF_OWNERDRAW | MF_STRING, idCmdFirst++, T("&Shell"));
AppendMenu(hPopup, MF_SEPARATOR, 0, NULL);
AppendMenu(hPopup, MF_OWNERDRAW | MF_STRING, idCmdFirst++, T("&Help"));
HMODULE module = GetModuleHandle(MODULENAME);
HBITMAP bitimage = (HBITMAP)LoadBitmap( module, L"nantbuild");
if (!InsertMenu(hMenu, indexMenu, MF_BYPOSITION | MF_STRING | MF_POPUP, UINT_PTR(hPopup), T("NAnt")))
return HRESULT_FROM_WIN32(GetLastError());
//FormatMessage
if (!SetMenuItemBitmaps(hMenu,indexMenu, MF_BYPOSITION, bitimage, bitimage))
return HRESULT_FROM_WIN32(GetLastError());
if (this->defaultTarget)
{
bstr_t caption = T("NAnt (") + this->defaultTarget->name + T(")");
MENUITEMINFO itemInfo;
memset(&itemInfo, 0, sizeof(itemInfo));
itemInfo.cbSize = sizeof(itemInfo);
itemInfo.fMask = MIIM_ID | MIIM_TYPE | MIIM_STATE;
itemInfo.wID = idCmdFirst++;
itemInfo.fType = MFT_STRING | MFT_OWNERDRAW;
itemInfo.fState = MFS_DEFAULT;
itemInfo.dwTypeData = caption;
if (!InsertMenuItem(hMenu, indexMenu, TRUE, &itemInfo))
return HRESULT_FROM_WIN32(GetLastError());
}
return MAKE_HRESULT(SEVERITY_SUCCESS, 0, idCmdFirst);
}
return E_FAIL;
}
inline bstr_t GetDescription(const CNAntTarget & target)
{
return target.desc;
}
inline bstr_t GetVerb(const CNAntTarget & target)
{
return "NAntMenuRun" + target.name;
}
inline LPCSTR GetHelpA(const CNAntCommand & cmdInfo)
{
return cmdInfo.strHelp;
}
inline LPCWSTR GetHelpW(const CNAntCommand & cmdInfo)
{
return cmdInfo.wcsHelp;
}
inline LPCSTR GetVerbA(const CNAntCommand & cmdInfo)
{
return cmdInfo.strVerb;
}
inline LPCWSTR GetVerbW(const CNAntCommand & cmdInfo)
{
return cmdInfo.wcsVerb;
}
template <class CharType>
HRESULT CNAntContextMenu::CopyHelpString(UINT idCmd,
HRESULT (*copyFunc)(CharType *, size_t, const CharType *),
bstr_t (*targetFunc)(const CNAntTarget & target),
const CharType * (*sourceFunc)(const CNAntCommand & cmdInfo),
CharType * strBuf,
UINT cchMax)
{
if (idCmd < this->targetCount)
{
HRESULT hResult = copyFunc(strBuf, cchMax, targetFunc(this->targets[idCmd]));
return hResult;
}
idCmd-= this->targetCount;
if (idCmd < IdCmd_Last)
{
HRESULT hResult = copyFunc(strBuf, cchMax, sourceFunc(commands[idCmd]));
return hResult;
}
return E_FAIL;
}
HRESULT STDMETHODCALLTYPE CNAntContextMenu::GetCommandString(
UINT_PTR idCmd, UINT uType, UINT * pwReserved, LPSTR pszName, UINT cchMax)
{
LPWSTR pwszName = LPWSTR(pszName);
switch(uType)
{
case GCS_VALIDATEA:
case GCS_VALIDATEW:
return idCmd >= this->idCmdFirst &&
idCmd < this->idCmdFirst + this->targetCount + 2 ?
S_OK : S_FALSE;
case GCS_HELPTEXTA: //Ansi Help Text
return this->CopyHelpString(idCmd, StringCchCopyA, GetDescription, GetHelpA, pszName, cchMax);
case GCS_HELPTEXTW:
return this->CopyHelpString(idCmd, StringCchCopyW, GetDescription, GetHelpW, pwszName, cchMax);
case GCS_VERBA: //Ansi verb
return this->CopyHelpString(idCmd, StringCchCopyA, GetVerb, GetVerbA, pszName, cchMax);
case GCS_VERBW:
return this->CopyHelpString(idCmd, StringCchCopyW, GetVerb, GetVerbW, pwszName, cchMax);
}
return E_FAIL;
}
HRESULT CNAntContextMenu::BuildTarget(const CNAntTarget & target)
{
TCHAR path[MAX_PATH];
StrCpy(path, this->filename);
LPTSTR filename = StrRChr(path, path + StrLen(path), '\\');
if (filename)
{
*filename++ = '\0';
bstr_t cmdline =
"/c title NAnt - " + target.name + " - " + filename +
" && nant -buildfile:\"" + filename + "\" " + target.name +
" && timeout /t 30 || timeout /t 30";
ShellExecute(NULL, T("open"), T("cmd.exe"), cmdline, path, SW_SHOWNORMAL);
return S_OK;
}
return E_FAIL;
}
HRESULT STDMETHODCALLTYPE CNAntContextMenu::InvokeCommand(LPCMINVOKECOMMANDINFO lpici)
{
BOOL fEx = FALSE;
BOOL fUnicode = FALSE;
if(lpici->cbSize == sizeof(CMINVOKECOMMANDINFOEX))
{
fEx = TRUE;
if((lpici->fMask & CMIC_MASK_UNICODE))
{
fUnicode = TRUE;
OutputDebugString(L"Unicode");
}
}
if (!fUnicode && HIWORD(lpici->lpVerb))
{
MessageBoxA(0, lpici->lpVerb, "__FUNCTION__", 0);//TODO:
OutputDebugStringA(lpici->lpVerb);
// If the verb is not recognized by the context menu handler, it
// must return E_FAIL to allow it to be passed on to the other
// context menu handlers that might implement that verb.
return E_FAIL;
}
// For the Unicode case, if the high-order word is not zero, the
// command's verb string is in lpcmi->lpVerbW.
else if(fUnicode && HIWORD(((CMINVOKECOMMANDINFOEX*)lpici)->lpVerbW))
{
// If the verb is not recognized by the context menu handler, it
// must return E_FAIL to allow it to be passed on to the other
// context menu handlers that might implement that verb.
OutputDebugString(((CMINVOKECOMMANDINFOEX*)lpici)->lpVerbW);
return E_FAIL;
}
// If the command cannot be identified through the verb string, then
// check the identifier offset.
else
{
LONG idCmd = LOWORD(lpici->lpVerb);
if (idCmd < this->targetCount)
{
return this->BuildTarget(this->targets[idCmd]);
}
else
{
idCmd-= this->targetCount;
TCHAR path[MAX_PATH];
StrCpy(path, this->filename);
LPTSTR filename = StrRChr(path, path + StrLen(path), '\\');
if (filename)
*filename++ = '\0';
else
{
filename= this->filename;
*path = '\0';
}
switch(idCmd)
{
case IdCmd_Edit:
if (ShellExecute(NULL, T("edit"), this->filename,NULL, NULL, SW_SHOWNORMAL)) return S_OK;
return HRESULT_FROM_WIN32(GetLastError());
case IdCmd_Browse:
OutputDebugString(path);
if (ShellExecute(NULL, T("explore"), path, NULL, NULL, SW_SHOWNORMAL))return S_OK;
return HRESULT_FROM_WIN32(GetLastError());
case IdCmd_Shell:
if (ShellExecute(NULL, T("open"), T("cmd.exe"), NULL, path, SW_SHOWNORMAL))return S_OK;
return HRESULT_FROM_WIN32(GetLastError());
case IdCmd_Help:
if (LaunchHelp()) return S_OK;
return HRESULT_FROM_WIN32(GetLastError());
case IdCmd_Default:
if (this->defaultTarget)
return this->BuildTarget(*this->defaultTarget);
break;
}
}
}
return E_FAIL;
}
HRESULT STDMETHODCALLTYPE CNAntContextMenu::HandleMenuMsg(
UINT uMsg, WPARAM wParam, LPARAM lParam)
{
LRESULT noResult;
return this->HandleMenuMsg2(uMsg, wParam, lParam, &noResult);
}
HRESULT STDMETHODCALLTYPE CNAntContextMenu::HandleMenuMsg2(UINT uMsg,
WPARAM wParam, LPARAM lParam, LRESULT * plResult)
{
if (NULL == plResult) return E_INVALIDARG;
switch(uMsg)
{
case WM_INITMENUPOPUP:
return NOERROR;
case WM_MENUSELECT:
return NOERROR;
case WM_DRAWITEM:
return this->DrawItem(HMENU(wParam), LPDRAWITEMSTRUCT(lParam));
case WM_MEASUREITEM:
return this->MeasureItem(HMENU(wParam), LPMEASUREITEMSTRUCT(lParam));
case WM_MENUCHAR:
return this->OnMenuChar(HMENU(lParam), LOWORD(wParam), HIWORD(wParam), *plResult);
}
wchar_t str[100];
wsprintf(str, L"Unexpected uMsg in HandleMenuMsg2: %d", uMsg);
MessageBox(0, str, 0, 0);
return E_NOTIMPL;
}
LPCTSTR CNAntContextMenu::GetMenuCaption(UINT itemId, HICON * hIcon)
{
UINT cmdId = itemId - this->idCmdFirst;
if (cmdId < this->targetCount)
{
if (hIcon) *hIcon = this->hIcons[IdCmd_Default];
return this->targets[cmdId].name;
}
cmdId-= this->targetCount;
if (cmdId < IdCmd_Last)
{
if (hIcon) *hIcon = this->hIcons[cmdId];
return commands[cmdId].Caption;
}
if (hIcon) *hIcon = NULL;
return L"Unknown item";
}
HRESULT CNAntContextMenu::DrawItem(
HMENU hMenu, LPDRAWITEMSTRUCT pDrawItem)
{
if (NULL == pDrawItem) return E_INVALIDARG;
if (pDrawItem->itemAction & (ODA_DRAWENTIRE | ODA_SELECT))
{
COLORREF crText = GetTextColor(pDrawItem->hDC);
COLORREF crBkgnd = GetBkColor(pDrawItem->hDC);
if (pDrawItem->itemState & ODS_SELECTED)
{
crText = SetTextColor(pDrawItem->hDC,
GetSysColor(pDrawItem->itemState & ODS_GRAYED ?
COLOR_GRAYTEXT : COLOR_HIGHLIGHTTEXT));
SetBkColor(pDrawItem->hDC, GetSysColor(COLOR_HIGHLIGHT));
}
HICON hIcon;
LPCTSTR caption = this->GetMenuCaption(pDrawItem->itemID, &hIcon);
HBRUSH bkBrush = CreateSolidBrush(GetBkColor(pDrawItem->hDC));
FillRect(pDrawItem->hDC, &pDrawItem->rcItem, bkBrush);
RECT rc = pDrawItem->rcItem;
const DWORD wa = rc.right - rc.left + 1;
const DWORD ha = rc.bottom - rc.top + 1;
const DWORD wi = GetSystemMetrics(SM_CXSMICON);
const DWORD hi = GetSystemMetrics(SM_CYSMICON);
DrawIconEx(pDrawItem->hDC,rc.left - 1, rc.top + (ha - hi) / 2, hIcon, wi, hi, 0, NULL, DI_NORMAL | DI_COMPAT);
DeleteObject(bkBrush);
rc.left+= wi;
DrawText(pDrawItem->hDC, caption, -1, &rc, DT_SINGLELINE | DT_LEFT | DT_VCENTER);
}
return NOERROR;
}
HRESULT CNAntContextMenu::MeasureItem(
HMENU hMenu, LPMEASUREITEMSTRUCT pMeasureItem)
{
if (NULL == pMeasureItem)
return E_INVALIDARG;
RECT rc;
LPCTSTR caption = this->GetMenuCaption(pMeasureItem->itemID);
if (DrawText(GetDC(NULL), caption, -1, &rc, DT_SINGLELINE | DT_CALCRECT))
{
pMeasureItem->itemWidth = rc.right - rc.left + 1;
pMeasureItem->itemHeight = rc.bottom - rc.top + 1;
return NOERROR;
}
return HRESULT_FROM_WIN32(GetLastError());
}
HRESULT CNAntContextMenu::OnMenuChar(
HMENU hMenu, WORD type, WORD charcode, LRESULT & result)
{
result = MNC_IGNORE;
return NOERROR;
}
//Launch Help based on location of Nant.exe in PATH
HRESULT CNAntContextMenu::LaunchHelp()
{
LPTSTR pszPath=NULL;
DWORD nSize = ExpandEnvironmentStrings(T("%PATH%"),NULL, 0);
pszPath = (LPTSTR)LocalAlloc(LPTR, nSize* sizeof(TCHAR));
LocalLock(pszPath);
if (ExpandEnvironmentStrings(T("%PATH%"),pszPath, nSize))
{
#ifdef _DEBUG
OutputDebugString(pszPath);
#endif
TCHAR seps[] = T(";");
TCHAR *token;
TCHAR *next_token1 = NULL;
TCHAR nantexe[MAX_PATH];
TCHAR nantHelpPath[MAX_PATH];
BOOL isFound = FALSE;
/* Establish string and get the first token: */
token = wcstok_s( pszPath, seps, &next_token1 );
while ( token != NULL && (! isFound ))
{
#ifdef _DEBUG
OutputDebugString(token);
#endif
PathCombine(nantexe,token,T("nant.exe"));
if (PathFileExists(nantexe))
{
isFound=TRUE;
#ifdef _DEBUG
OutputDebugString(nantexe);
#endif
//therefor the help file is ..\doc\help\index.html
PathCombine(nantHelpPath,token,T("..\\doc\\help\\index.html"));
#ifdef _DEBUG
OutputDebugString(nantHelpPath);
#endif
if (PathFileExists(nantHelpPath))
{
OutputDebugString(nantHelpPath);
if (ShellExecute(NULL, T("open"), nantHelpPath,NULL, NULL, SW_SHOWNORMAL)) {
pszPath=(LPTSTR)LocalFree(pszPath);
return S_OK;
}
else
{
DWORD retval=HRESULT_FROM_WIN32(GetLastError());
pszPath=(LPTSTR)LocalFree(pszPath);
return retval;
}
}
}
/* While there are tokens in "string" */
token = wcstok_s( NULL, seps, &next_token1);
/* Get next token: */
}
}
if (pszPath != NULL) pszPath =(LPTSTR)LocalFree(pszPath);
return S_FALSE;
}
// vim:ts=4:sw=4
| [
"[email protected]"
] | |
d39a8c9219204f46988c38608f0b8cd35c2d33a1 | a9cfa4e5aa62d4d189c134c93e28c6613b1a883c | /ChromaSDK/RzChromaSDKDefines.h | 64d13606e3d8cc382d1cccc37bcf4af24d221cf7 | [] | no_license | jeanrodriguez27/chromeIt | 39e65c30d07cd891a1537d003e6c685dd30fba14 | e4f72a864172818731a0f929fc6dd2c5f0d661d0 | refs/heads/master | 2020-04-05T01:15:10.861556 | 2017-06-21T19:24:55 | 2017-06-21T19:24:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,676 | h | //! \file RzChromaSDKDefines.h
//! \brief Definitions of global and static variables.
#ifndef _RZSCHROMADKDEFINES_H_
#define _RZSCHROMADKDEFINES_H_
#pragma once
#ifndef GUID_DEFINED
#include <Guiddef.h>
#endif
namespace ChromaSDK
{
// Keyboards
//! Razer Blackwidow Chroma device.
// {2EA1BB63-CA28-428D-9F06-196B88330BBB}
static const GUID BLACKWIDOW_CHROMA =
{ 0x2ea1bb63, 0xca28, 0x428d, { 0x9f, 0x06, 0x19, 0x6b, 0x88, 0x33, 0x0b, 0xbb } };
//! Razer Blackwidow Chroma Tournament Edition device.
// {ED1C1B82-BFBE-418F-B49D-D03F05B149DF}
static const GUID BLACKWIDOW_CHROMA_TE =
{ 0xed1c1b82, 0xbfbe, 0x418f, { 0xb4, 0x9d, 0xd0, 0x3f, 0x5, 0xb1, 0x49, 0xdf } };
//! Razer Deathstalker device.
// {18C5AD9B-4326-4828-92C4-2669A66D2283}
static const GUID DEATHSTALKER_CHROMA =
{ 0x18c5ad9b, 0x4326, 0x4828, { 0x92, 0xc4, 0x26, 0x69, 0xa6, 0x6d, 0x22, 0x83 } };
//! Overwatch Keyboard.
// {872AB2A9-7959-4478-9FED-15F6186E72E4}
static const GUID OVERWATCH_KEYBOARD =
{ 0x872ab2a9, 0x7959, 0x4478, { 0x9f, 0xed, 0x15, 0xf6, 0x18, 0x6e, 0x72, 0xe4 } };
//! Razer Blackwidow X Chroma device.
// {5AF60076-ADE9-43D4-B574-52599293B554}
static const GUID BLACKWIDOW_X_CHROMA =
{ 0x5af60076, 0xade9, 0x43d4, { 0xb5, 0x74, 0x52, 0x59, 0x92, 0x93, 0xb5, 0x54 } };
//! Razer Blackwidow X TE Chroma device.
// {2D84DD51-3290-4AAC-9A89-D8AFDE38B57C}
static const GUID BLACKWIDOW_X_TE_CHROMA =
{ 0x2d84dd51, 0x3290, 0x4aac, { 0x9a, 0x89, 0xd8, 0xaf, 0xde, 0x38, 0xb5, 0x7c } };
//! Razer Ornata Chroma
// {803378C1-CC48-4970-8539-D828CC1D420A}
static const GUID ORNATA_CHROMA =
{ 0x803378c1, 0xcc48, 0x4970,{ 0x85, 0x39, 0xd8, 0x28, 0xcc, 0x1d, 0x42, 0xa } };
//! Razer Blade Stealth.
// {C83BDFE8-E7FC-40E0-99DB-872E23F19891}
static const GUID BLADE_STEALTH =
{ 0xc83bdfe8, 0xe7fc, 0x40e0, { 0x99, 0xdb, 0x87, 0x2e, 0x23, 0xf1, 0x98, 0x91 } };
//! Razer Blade
// {F2BEDFAF-A0FE-4651-9D41-B6CE603A3DDD}
static const GUID BLADE =
{ 0xf2bedfaf, 0xa0fe, 0x4651, { 0x9d, 0x41, 0xb6, 0xce, 0x60, 0x3a, 0x3d, 0xdd } };
// Mice
//! Razer Deathadder Chroma device.
// {AEC50D91-B1F1-452F-8E16-7B73F376FDF3}
static const GUID DEATHADDER_CHROMA =
{ 0xaec50d91, 0xb1f1, 0x452f, { 0x8e, 0x16, 0x7b, 0x73, 0xf3, 0x76, 0xfd, 0xf3 } };
//! Razer Mamba Chroma Tournament Edition device.
// {7EC00450-E0EE-4289-89D5-0D879C19061A}
static const GUID MAMBA_CHROMA_TE =
{ 0x7ec00450, 0xe0ee, 0x4289, { 0x89, 0xd5, 0xd, 0x87, 0x9c, 0x19, 0x6, 0x1a } };
//! Razer Diamondback device.
// {FF8A5929-4512-4257-8D59-C647BF9935D0}
static const GUID DIAMONDBACK_CHROMA =
{ 0xff8a5929, 0x4512, 0x4257, { 0x8d, 0x59, 0xc6, 0x47, 0xbf, 0x99, 0x35, 0xd0 } };
//! Razer Mamba device.
// {D527CBDC-EB0A-483A-9E89-66D50463EC6C}
static const GUID MAMBA_CHROMA =
{ 0xd527cbdc, 0xeb0a, 0x483a, { 0x9e, 0x89, 0x66, 0xd5, 0x4, 0x63, 0xec, 0x6c } };
//! Razer Naga Epic device.
// {D714C50B-7158-4368-B99C-601ACB985E98}
static const GUID NAGA_EPIC_CHROMA =
{ 0xd714c50b, 0x7158, 0x4368, { 0xb9, 0x9c, 0x60, 0x1a, 0xcb, 0x98, 0x5e, 0x98 } };
//! Razer Naga device.
// {F1876328-6CA4-46AE-BE04-BE812B414433}
static const GUID NAGA_CHROMA =
{ 0xf1876328, 0x6ca4, 0x46ae, { 0xbe, 0x4, 0xbe, 0x81, 0x2b, 0x41, 0x44, 0x33 } };
//! Razer Orochi Chroma device.
// {52C15681-4ECE-4DD9-8A52-A1418459EB34}
static const GUID OROCHI_CHROMA =
{ 0x52c15681, 0x4ece, 0x4dd9, { 0x8a, 0x52, 0xa1, 0x41, 0x84, 0x59, 0xeb, 0x34 } };
//! Razer Naga Hex Chroma device.
// {195D70F5-F285-4CFF-99F2-B8C0E9658DB4}
static const GUID NAGA_HEX_CHROMA =
{ 0x195d70f5, 0xf285, 0x4cff, { 0x99, 0xf2, 0xb8, 0xc0, 0xe9, 0x65, 0x8d, 0xb4 } };
// Headsets
//! Razer Kraken 7.1 Chroma device.
// {CD1E09A5-D5E6-4A6C-A93B-E6D9BF1D2092}
static const GUID KRAKEN71_CHROMA =
{ 0xcd1e09a5, 0xd5e6, 0x4a6c, { 0xa9, 0x3b, 0xe6, 0xd9, 0xbf, 0x1d, 0x20, 0x92 } };
//! Razer ManO'War device.
// {DF3164D7-5408-4A0E-8A7F-A7412F26BEBF}
static const GUID MANOWAR_CHROMA =
{ 0xdf3164d7, 0x5408, 0x4a0e, { 0x8a, 0x7f, 0xa7, 0x41, 0x2f, 0x26, 0xbe, 0xbf } };
// Mouse mat
//! Razer Firefly device.
// {80F95A94-73D2-48CA-AE9A-0986789A9AF2}
static const GUID FIREFLY_CHROMA =
{ 0x80f95a94, 0x73d2, 0x48ca, { 0xae, 0x9a, 0x9, 0x86, 0x78, 0x9a, 0x9a, 0xf2 } };
// Keypads
//! Razer Tartarus device.
// {00F0545C-E180-4AD1-8E8A-419061CE505E}
static const GUID TARTARUS_CHROMA =
{ 0xf0545c, 0xe180, 0x4ad1, { 0x8e, 0x8a, 0x41, 0x90, 0x61, 0xce, 0x50, 0x5e } };
//! Razer Orbweaver device.
// {9D24B0AB-0162-466C-9640-7A924AA4D9FD}
static const GUID ORBWEAVER_CHROMA =
{ 0x9d24b0ab, 0x162, 0x466c, { 0x96, 0x40, 0x7a, 0x92, 0x4a, 0xa4, 0xd9, 0xfd } };
// Systems
// {35F6F18D-1AE5-436C-A575-AB44A127903A}
static const GUID LENOVO_Y900 =
{ 0x35f6f18d, 0x1ae5, 0x436c, { 0xa5, 0x75, 0xab, 0x44, 0xa1, 0x27, 0x90, 0x3a } };
// {47DB1FA7-6B9B-4EE6-B6F4-4071A3B2053B}
static const GUID LENOVO_Y27 =
{ 0x47db1fa7, 0x6b9b, 0x4ee6, { 0xb6, 0xf4, 0x40, 0x71, 0xa3, 0xb2, 0x5, 0x3b } };
// Accessories
// {0201203B-62F3-4C50-83DD-598BABD208E0}
static const GUID CORE_CHROMA =
{ 0x201203b, 0x62f3, 0x4c50, { 0x83, 0xdd, 0x59, 0x8b, 0xab, 0xd2, 0x8, 0xe0 } };
}
#endif
| [
"[email protected]"
] | |
0ea9d89e2d239d4688ecd45dbefc23441ef8dc6f | feff7883394bdcd37dae1ef26daae682bd5a7641 | /cocos2dx/platform/linux/CCAccelerometer_linux.h | e0b7a415148405c1fc72f01351571ac23e1c3bde | [] | no_license | blacklensama/TVPortable | 1f4049ec22378700211e6c1e63dba8999d084998 | 98ed3bd6efcad6ad716b95aa4e97f615847a25d4 | refs/heads/master | 2020-03-30T06:15:33.086265 | 2012-08-26T03:02:47 | 2012-08-26T03:02:47 | 6,469,645 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 689 | h | /*
* CCAccelerometer_linux.h
*
* Created on: Aug 9, 2011
* Author: laschweinski
*/
#ifndef CCACCELEROMETER_LINUX_H_
#define CCACCELEROMETER_LINUX_H_
#include "CCCommon.h"
namespace cocos2d {
class CCAccelerometer
{
public:
CCAccelerometer();
~CCAccelerometer();
static CCAccelerometer* sharedAccelerometer() { return NULL; };
void removeDelegate(CCAccelerometerDelegate* pDelegate) {CC_UNUSED_PARAM(pDelegate);};
void addDelegate(CCAccelerometerDelegate* pDelegate) {CC_UNUSED_PARAM(pDelegate);};
void setDelegate(CCAccelerometerDelegate* pDelegate) {CC_UNUSED_PARAM(pDelegate);}
};
}//namespace cocos2d
#endif /* CCACCELEROMETER_LINUX_H_ */
| [
"[email protected]"
] | |
4299e867bc01e7dc36eac5f9acc758ced4e1102e | 0a1ec42ddace93933d677475a4938f1c2d58a552 | /engine/game/gameConnection.h | fab6e415fe8e557a274ebb2ebb999d245503a42e | [] | no_license | ClayHanson/tge-152-fork | f8a242e401e3ea85eebfc75ff2b3dfc84b4fa056 | f19fae0c05ee0dbd9822a73ba1fca0fe95d43f53 | refs/heads/master | 2023-03-16T14:30:30.793979 | 2013-05-01T05:51:43 | 2013-05-01T05:51:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,250 | h | //-----------------------------------------------------------------------------
// Torque Game Engine
// Copyright (C) GarageGames.com, Inc.
//-----------------------------------------------------------------------------
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
// Arcane-FX
// Changes:
// db-cache -- implementation of datablock caching system.
// obj-select -- implementation of object selection used for spell targeting.
// zoned-in -- connection is flagged as "zoned-in" when client is fully
// connected and user can interact with it.
// Copyright (C) Faust Logic, Inc.
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
#ifndef _GAMECONNECTION_H_
#define _GAMECONNECTION_H_
#ifndef _SIMBASE_H_
#include "console/simBase.h"
#endif
#ifndef _SHAPEBASE_H_
#include "game/shapeBase.h"
#endif
#ifndef _NETCONNECTION_H_
#include "sim/netConnection.h"
#endif
#ifndef _MOVEMANAGER_H_
#include "game/moveManager.h"
#endif
#ifndef _BITVECTOR_H_
#include "core/bitVector.h"
#endif
enum GameConnectionConstants
{
MaxClients = 126,
DataBlockQueueCount = 16
};
class AudioProfile;
class MatrixF;
class MatrixF;
class Point3F;
class MoveManager;
struct Move;
struct AuthInfo;
#define GameString "Torque Game Engine Demo"
// AFX CODE BLOCK (db-cache) <<
//
// To disable datablock caching, remove or comment out the AFX_CAP_DATABLOCK_CACHE define below.
// Also, at a minimum, the following script preferences should be set to false:
// $pref::Client::EnableDatablockCache = false; (in arcane.fx/client/defaults.cs)
// $Pref::Server::EnableDatablockCache = false; (in arcane.fx/server/defaults.cs)
// Alternatively, all script code marked with "DATABLOCK CACHE CODE" can be removed or
// commented out.
//
#define AFX_CAP_DATABLOCK_CACHE
// AFX CODE BLOCK (db-cache) >>
class GameConnection : public NetConnection
{
private:
typedef NetConnection Parent;
enum PrivateConstants {
MoveCountBits = 5,
/// MaxMoveCount should not exceed the MoveManager's
/// own maximum (MaxMoveQueueSize)
MaxMoveCount = 30,
};
typedef Vector<Move> MoveList;
SimObjectPtr<ShapeBase> mControlObject;
SimObjectPtr<ShapeBase> mCameraObject;
U32 mDataBlockSequence;
char mDisconnectReason[256];
U32 mMissionCRC; // crc of the current mission file from the server
private:
U32 mLastControlRequestTime;
S32 mDataBlockModifiedKey;
S32 mMaxDataBlockModifiedKey;
/// @name Client side first/third person
/// @{
///
bool mFirstPerson; ///< Are we currently first person or not.
bool mUpdateFirstPerson; ///< Set to notify client or server of first person change.
bool mUpdateCameraFov; ///< Set to notify server of camera FOV change.
F32 mCameraFov; ///< Current camera fov (in degrees).
F32 mCameraPos; ///< Current camera pos (0-1).
F32 mCameraSpeed; ///< Camera in/out speed.
/// @}
/// @name Move Packets
/// Write/read move data to the packet.
/// @{
///
void moveWritePacket(BitStream *bstream);
void moveReadPacket(BitStream *bstream);
/// @}
public:
/// @name Protocol Versions
///
/// Protocol versions are used to indicated changes in network traffic.
/// These could be changes in how any object transmits or processes
/// network information. You can specify backwards compatibility by
/// specifying a MinRequireProtocolVersion. If the client
/// protocol is >= this min value, the connection is accepted.
///
/// Torque (V12) SDK 1.0 uses protocol = 1
///
/// Torque SDK 1.1 uses protocol = 2
/// Torque SDK 1.4 uses protocol = 12
/// @{
static const U32 CurrentProtocolVersion;
static const U32 MinRequiredProtocolVersion;
/// @}
/// Configuration
enum Constants {
BlockTypeMove = NetConnectionBlockTypeCount,
GameConnectionBlockTypeCount,
MaxConnectArgs = 16,
DataBlocksDone = NumConnectionMessages,
DataBlocksDownloadDone,
};
/// Set connection arguments; these are passed to the server when we connect.
void setConnectArgs(U32 argc, const char **argv);
const char * getConnectArgs(S32 idx) const;
S32 getConnectArgsCount() const { return mConnectArgc;}
/// Set the server password to use when we join.
void setJoinPassword(const char *password);
/// @name Event Handling
/// @{
virtual void onTimedOut();
virtual void onConnectTimedOut();
virtual void onDisconnect(const char *reason);
virtual void onConnectionRejected(const char *reason);
virtual void onConnectionEstablished(bool isInitiator);
virtual void handleStartupError(const char *errorString);
/// @}
/// @name Packet I/O
/// @{
virtual void writeConnectRequest(BitStream *stream);
virtual bool readConnectRequest(BitStream *stream, const char **errorString);
virtual void writeConnectAccept(BitStream *stream);
virtual bool readConnectAccept(BitStream *stream, const char **errorString);
/// @}
bool canRemoteCreate();
private:
/// @name Connection State
/// This data is set with setConnectArgs() and setJoinPassword(), and
/// sent across the wire when we connect.
/// @{
U32 mConnectArgc;
char *mConnectArgv[MaxConnectArgs];
char *mJoinPassword;
/// @}
protected:
struct GamePacketNotify : public NetConnection::PacketNotify
{
S32 cameraFov;
GamePacketNotify();
};
PacketNotify *allocNotify();
U32 mLastMoveAck;
U32 mLastClientMove;
U32 mFirstMoveIndex;
U32 mMoveCredit;
U32 mLastControlObjectChecksum;
Vector<SimDataBlock *> mDataBlockLoadList;
MoveList mMoveList;
bool mAIControlled;
AuthInfo * mAuthInfo;
static S32 mLagThresholdMS;
S32 mLastPacketTime;
bool mLagging;
/// @name Flashing
////
/// Note, these variables are not networked, they are for the local connection only.
/// @{
F32 mDamageFlash;
F32 mWhiteOut;
F32 mBlackOut;
S32 mBlackOutTimeMS;
S32 mBlackOutStartTimeMS;
bool mFadeToBlack;
/// @}
/// @name Packet I/O
/// @{
void readPacket (BitStream *bstream);
void writePacket (BitStream *bstream, PacketNotify *note);
void packetReceived (PacketNotify *note);
void packetDropped (PacketNotify *note);
void connectionError (const char *errorString);
void writeDemoStartBlock (ResizeBitStream *stream);
bool readDemoStartBlock (BitStream *stream);
void handleRecordedBlock (U32 type, U32 size, void *data);
/// @}
public:
DECLARE_CONOBJECT(GameConnection);
void handleConnectionMessage(U32 message, U32 sequence, U32 ghostCount);
void preloadDataBlock(SimDataBlock *block);
void fileDownloadSegmentComplete();
void preloadNextDataBlock(bool hadNew);
static void consoleInit();
void setDisconnectReason(const char *reason);
GameConnection();
~GameConnection();
U32 getDataBlockSequence() { return mDataBlockSequence; }
void setDataBlockSequence(U32 seq) { mDataBlockSequence = seq; }
bool onAdd();
void onRemove();
static GameConnection *getConnectionToServer() { return dynamic_cast<GameConnection*>((NetConnection *) mServerConnection); }
static GameConnection *getLocalClientConnection() { return dynamic_cast<GameConnection*>((NetConnection *) mLocalClientConnection); }
/// @name Control object
/// @{
///
void setControlObject(ShapeBase *co);
ShapeBase* getControlObject() { return mControlObject; }
void setCameraObject(ShapeBase *co);
ShapeBase* getCameraObject();
bool getControlCameraTransform(F32 dt,MatrixF* mat);
bool getControlCameraVelocity(Point3F *vel);
bool getControlCameraFov(F32 * fov);
bool setControlCameraFov(F32 fov);
bool isValidControlCameraFov(F32 fov);
void setFirstPerson(bool firstPerson);
/// @}
void detectLag();
/// @name Datablock management
/// @{
S32 getDataBlockModifiedKey () { return mDataBlockModifiedKey; }
void setDataBlockModifiedKey (S32 key) { mDataBlockModifiedKey = key; }
S32 getMaxDataBlockModifiedKey () { return mMaxDataBlockModifiedKey; }
void setMaxDataBlockModifiedKey (S32 key) { mMaxDataBlockModifiedKey = key; }
/// @}
/// @name Fade control
/// @{
F32 getDamageFlash() { return mDamageFlash; }
F32 getWhiteOut() { return mWhiteOut; }
void setBlackOut(bool fadeToBlack, S32 timeMS);
F32 getBlackOut();
/// @}
/// @name Move Management
/// @{
void pushMove(const Move &mv);
bool getNextMove(Move &curMove);
bool isBacklogged();
virtual void getMoveList(Move**,U32* numMoves);
virtual void clearMoves(U32 count);
void collectMove(U32 simTime);
virtual bool areMovesPending();
void incMoveCredit(U32 count);
/// @}
/// @name Authentication
///
/// This is remnant code from Tribes 2.
/// @{
void setAuthInfo(const AuthInfo *info);
const AuthInfo *getAuthInfo();
/// @}
/// @name Sound
/// @{
void play2D(const AudioProfile *profile);
void play3D(const AudioProfile *profile, const MatrixF *transform);
/// @}
/// @name Misc.
/// @{
bool isFirstPerson() { return mCameraPos == 0; }
bool isAIControlled() { return mAIControlled; }
void doneScopingScene();
void demoPlaybackComplete();
void setMissionCRC(U32 crc) { mMissionCRC = crc; }
U32 getMissionCRC() { return(mMissionCRC); }
/// @}
// AFX CODE BLOCK (obj-select) <<
// GameConnection is modified to keep track of object selections which are used in
// spell targeting. This code stores the current object selection as well as the
// current rollover object beneath the cursor. The rollover object is treated as a
// pending object selection and actual object selection is usually made by promoting
// the rollover object to the current object selection.
private:
SimObjectPtr<SimObject> mRolloverObj;
SimObjectPtr<SimObject> mPreSelectedObj;
SimObjectPtr<SimObject> mSelectedObj;
SimObjectPtr<SimObject> mDestObj; //DARREN MOD: mouse click movement
bool mChangedSelectedObj;
U32 mPreSelectTimestamp;
Point3F mDestPoint; //DARREN MOD: mouse click movement
Point3F mOldDestPoint;
VectorF mDestNormal;
S8 mDestChanged;//DARREN MOD: 0: no update 1: updated -1: ready to stop
protected:
virtual void onDeleteNotify(SimObject*);
public:
void setRolloverObj(SimObject*);
void setDestPointNormal(SimObject* dest, const Point3F & point, const VectorF & normal);
SimObject* getRolloverObj() { return mRolloverObj; }
void setSelectedObj(SimObject*, bool propagate_to_client=false);
void setDestObj(SimObject*, bool);
SimObject* getSelectedObj() { return mSelectedObj; }
void setPreSelectedObjFromRollover();
void clearPreSelectedObj();
void setSelectedObjFromPreSelected();
// AFX CODE BLOCK (obj-select) >>
// AFX CODE BLOCK (zoned-in) <<
// Flag is added to indicate when a client is fully connected or "zoned-in".
// This information determines when AFX will startup active effects on a newly
// added client.
private:
bool zoned_in;
public:
bool isZonedIn() const { return zoned_in; }
void setZonedIn() { zoned_in = true; }
// AFX CODE BLOCK (zoned-in) >>
#ifdef AFX_CAP_DATABLOCK_CACHE // AFX CODE BLOCK (db-cache) <<
private:
static StringTableEntry server_cache_filename;
static StringTableEntry client_cache_filename;
static bool server_cache_on;
static bool client_cache_on;
BitStream* client_db_stream;
char* curr_stringBuf;
U32 server_cache_CRC;
public:
void repackClientDatablock(BitStream*, S32 start_pos);
void saveDatablockCache(bool on_server);
void loadDatablockCache();
bool loadDatablockCache_Begin();
bool loadDatablockCache_Continue();
void tempDisableStringBuffering(BitStream* bs) const;
void restoreStringBuffering(BitStream* bs) const;
void setServerCacheCRC(U32 crc) { server_cache_CRC = crc; }
static void resetDatablockCache();
static bool serverCacheEnabled() { return server_cache_on; }
static bool clientCacheEnabled() { return client_cache_on; }
static const char* serverCacheFilename() { return server_cache_filename; }
static const char* clientCacheFilename() { return client_cache_filename; }
#endif // AFX CODE BLOCK (db-cache) >>
};
#endif
| [
"mint@mint.(none)"
] | mint@mint.(none) |
8eff7a323c266f078ce6d8eac9d961e386911dd0 | 10718ab2477dd2110c260745a99a5b2d2f71d185 | /OWPJON/LINUX/Local/ThroughSerial/RemoteWorker/DeviceGeneric/DeviceGeneric.cpp | d3463f102916a1460c4933a688490fa3be2081b7 | [
"CC-BY-3.0",
"MIT"
] | permissive | drtrigon/sketchbook | 841aaab3a1d26d03730473a9c0c33dd0e23ded40 | fa58bf767cce2537c86e5ce1638771a164a5b118 | refs/heads/master | 2021-12-25T05:51:55.953619 | 2021-11-27T22:53:11 | 2021-11-27T22:53:11 | 127,468,266 | 8 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 5,978 | cpp | /**
* @brief Example-Code for a generic Server (e.g. Sensor, Display)
*
* @file OWPJON/LINUX/Local/ThroughSerial/RemoteWorker/DeviceGeneric/DeviceGeneric.cpp
*
* @author drtrigon
* @date 2018-07-06
* @version 1.0
* @li first version derived from PJON 11.0 examples
* examples/LINUX/Local/EthernetTCP/RemoteWorker/Transmitter/Transmitter.cpp
*
* TODO: THIS CODE NEEDS AN UPDATE - ADOPT IT TO THE LATEST LUDP CODE (LINUX/Local/LocalUDP/...)
* Also considering LUDP_RESPONSE_TIMEOUT versus TS_RESPONSE_TIME_OUT.
*
* It sends REQUESTS to device id 44 which is on a SWBB bus connected to the
* Tunnel, and receives replies back.
* Device 44 is the example:
* OWPJON/ARDUINO/Local/SoftwareBitBang/DeviceGeneric/
*
* This demonstrates the concept with a process on a PC or a RPI transparently
* being part of a SWBB bus via a Tunnel. The Tunnel/Surrogate will "phone home"
* to the RemoteWorker to create a permanent link.
*
* @see https://github.com/gioblu/PJON/blob/master/examples/LINUX/Local/EthernetTCP/RemoteWorker/Transmitter/Transmitter.cpp
*
* @verbatim
* OneWire PJON Generic "OWPG" scheme:
* Server e.g. linux machine or raspi
* OWPJON/LINUX/Local/LocalUDP/RemoteWorker/DeviceGeneric/
* OWPJON/LINUX/Local/ThroughSerial/RemoteWorker/DeviceGeneric/ (this sketch)
* Tunnel(er) similar to 1wire master (similar cause we are on a multi-master bus) e.g. AVR
* OWPJON/ARDUINO/Local/SoftwareBitBang/Tunneler/BlinkingSwitch/
* OWPJON/ARDUINO/Local/SoftwareBitBang/Tunneler/BlinkingSwitch_SWBB-TS/
* OWPJON/ARDUINO/Local/ThroughSerial/SoftwareBitBangSurrogate/Surrogate/ (obsolete)
* Devices e.g. AVR
* OWPJON/ARDUINO/Local/SoftwareBitBang/DeviceGeneric/
* OWPJON/ARDUINO/Local/SoftwareBitBang/OWP_DG_LCD_Sensors/
* ...
*
* Compatible with: ubuntu 14.04, raspi
*
* Compile wiringPi using:
* $ git clone git://git.drogon.net/wiringPi
* $ cd wiringPi
* $ ./build
*
* Example sending READ_INFO 0x01 to device id 44:
* $ printf "\x01" | sudo ./owpshell /dev/ttyACM0 9600 44
* owp:dg:v1
* $ printf "\x11" | sudo ./owpshell /dev/ttyACM0 9600 44 | unpack.py f
* 4.771999835968018,
* $ printf "\x12" | sudo ./owpshell /dev/ttyACM0 9600 44 | unpack.py f
* 28.02459144592285,
* More info can be found in @ref OWPJON/README.md.
*
* Thanks to:
* gioblu - PJON 11.0 and support
* @see https://www.pjon.org/
* @see https://github.com/gioblu/PJON
* fredilarsen - support
* @endverbatim
*/
// For printf used below
#include <stdio.h>
// PJON library
#include <inttypes.h>
#include <stdlib.h>
#include <string.h>
// RPI serial interface
#include <wiringPi.h>
#ifndef RPI
#define RPI true
#endif
#define TS_RESPONSE_TIME_OUT 35000
/* Maximum accepted timeframe between transmission and synchronous
acknowledgement. This timeframe is affected by latency and CRC computation.
Could be necessary to higher this value if devices are separated by long
physical distance and or if transmitting long packets. */
//// Define one of these modes
//#define ETCP_SINGLE_DIRECTION
////#define ETCP_SINGLE_SOCKET_WITH_ACK
#define PJON_INCLUDE_TS true // Include only ThroughSerial
#include <PJON.h>
//PJON<EthernetTCP> bus(45);
PJON<ThroughSerial> bus(45);
//bool EXIT = false;
#define BLOCK_SIZE 256
//uint8_t buffer[BLOCK_SIZE];
char buffer[BLOCK_SIZE];
static void receiver_function(uint8_t *payload, uint16_t length, const PJON_Packet_Info &packet_info)
{
fwrite(payload, sizeof(char), length, stdout);
printf("\n"); // print newline - causes also a flush
// EXIT = true;
};
void loop()
{
bus.update();
bus.receive(1000);
//bus.receive();
// // Show the number of sockets created after startup
// // (Try disconnecting the Ethernet cable for a while to see it increase when reconnected.)
// static uint32_t last = millis();
// if (millis() - last > 5000) {
// last = millis();
// printf("CONNECT COUNT: %d\n", bus.strategy.link.get_connection_count());
// }
}
int main(int argc, char* argv[]) // or char** argv
{
// Welcome to RemoteWorker 1 (Transmitter)
// bus.strategy.link.set_id(bus.device_id());
//bus.strategy.link.keep_connection(true);
//#ifdef ETCP_SINGLE_DIRECTION
// bus.strategy.link.single_initiate_direction(true);
//#elif ETCP_SINGLE_SOCKET_WITH_ACK
// bus.strategy.link.single_socket(true);
//#endif
uint32_t baud_rate = atoi(argv[2]);
// Opening serial...
int s = serialOpen(argv[1], baud_rate);
if(int(s) < 0) {
printf("Serial open fail!\n");
return 1;
}
// Setting serial...
bus.strategy.set_serial(s);
bus.strategy.set_baud_rate(baud_rate);
bus.set_receiver(receiver_function);
// bus.strategy.link.start_listening();
// bus.set_synchronous_acknowledge(false);
// Opening bus...
bus.begin();
// Attempting to send a packet...
//bus.send(44, "B", 1);
size_t l;
if(argc < 5) // get data to send from stdin or command line (stdin allows \0)
//l = fread(buffer, BLOCK_SIZE, sizeof(char), stdin);
l = fread(buffer, sizeof(*buffer), sizeof(buffer)/sizeof(*buffer), stdin);
else {
strcpy(buffer, argv[4]);
l = strlen(argv[4]);
}
for(int i = 0; i < 3; ++i) { // try 3 times (using timeout), then exit
//bus.send(argv[3][0], buffer, l);
bus.send(atoi(argv[3]), buffer, l);
// Attempting to roll bus...
//bus.update();
// Attempting to receive from bus...
//bus.receive();
// Success!
//while (true) loop();
//while (!EXIT) loop();
for(int j = 0; j < 5000; ++j) { // do timeout 5000 times ~ 5s
bus.update();
// TODO: use error handler callback
switch (bus.receive(1000)) { // 1ms timeout
case PJON_ACK:
return 0;
break;
// case PJON_NAK: // re-try; send data again
// break;
// case PJON_BUSY:
// // ...
// break;
// case PJON_FAIL:
// // ...
// break;
default:
break;
}
}
}
return 0;
}
| [
"ursin@ThinkPad-T440-ursin"
] | ursin@ThinkPad-T440-ursin |
b4c5e39fafbe0f320395c924f3373ddbe0ed0724 | 843e995a92a6ceb1c207cc3b58c528da073562bd | /Orbis Toolbox/LncUtil.h | 2fd05674abf0981d8202e0d3fb201e71546e7219 | [] | no_license | PSTools/Orbis-Toolbox | d3dd710366c91d4478c76805050dc1a0513319af | 59caaf1d19b1787d2c67cb423dd4ea73d10c8784 | refs/heads/main | 2023-06-26T04:48:31.691451 | 2021-07-28T14:56:07 | 2021-07-28T14:56:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,280 | h | #pragma once
class LncUtil
{
public:
enum Boot
{
None = 0,
Eap = 1
};
enum Flag : unsigned long
{
Flag_None = 0UL,
SkipLaunchCheck = 1UL,
SkipResumeCheck = 1UL,
SkipSystemUpdateCheck = 2UL,
RebootPatchInstall = 4UL,
VRMode = 8UL,
NonVRMode = 16UL
};
struct LaunchAppParam
{
unsigned int size;
int userId;
int appAttr;
int enableCrashReport;
Flag checkFlag;
};
enum AppType
{
Invalid = -1,
Unknown,
ShellUI,
Daemon,
CDLG,
MiniApp,
BigApp,
ShellCore,
ShellApp
};
struct AppStatus
{
int appId;
int launchRequestAppId;
char appType;
};
static int GetAppStatus(AppStatus* Status);
static int SuspendApp(int appId, Flag flag = Flag_None);
static int ResumeApp(int appId, Flag flag = Flag_None);
static int SetControllerFocus(int appId);
static int SetAppFocus(int appId, Flag flag = Flag_None);
static int GetAppId(const char* titleId);
static int LaunchApp(const char* titleId, char* args, int argsSize, LaunchAppParam* param);
static int KillApp(int appId, int userId = -1);
static int ForceKillApp(int appId, int userId = -1);
static int KillLocalProcess(int appId, int appLocalPid);
static void SystemShutdown(Boot flag);
static void SystemReboot();
static void SystemSuspend();
private:
}; | [
"[email protected]"
] | |
fbe5a1b6e7be2c4277a46bee5bab8ea1f8d023ae | c8425121ceedc177f6e45f9f79b9ce849dd246eb | /main.cpp | 0af084bb81a1a4bb10bb3874c1f3015357796fde | [] | no_license | Metallink/Coding_battle_2018 | defa22dbe6d73a617e9606fde4884aad85d98056 | 3b63418cbc444890b8e5df9f1b49cb0f7178196a | refs/heads/master | 2020-04-02T01:00:39.460792 | 2018-10-21T12:43:30 | 2018-10-21T12:43:30 | 153,833,011 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 855 | cpp | #include <iostream>
#include <string>
#include "a_loot_sharing.h"
#include "b_the_parrots.h"
#include "c_sea_storm.h"
using namespace std;
int main() {
int choix(0), stop(0);
cout << "================== CODING BATTLE ==================" << endl;
cout << "Choose your exercice or Press 9 to exit " << endl;
cin >> choix;
while (!stop) {
switch (choix) {
case 1 :
loot();
break;
case 2 :
parrot();
break;
case 3 :
cout << (seaStorm() ? "YES" : "NO") << endl;
break;
case 0:
cout << "Bye !" << endl;
stop = 1;
default:
cout << "Wrong input, please try again" << endl;
break;
}
}
return 0;
} | [
"[email protected]"
] | |
c3fe116e884cc32cdedaa8cbec1f2145ec76e784 | 0c82a4ac606839fa2e4dc9ec5a32850853708b63 | /1.1/ArmnnDriverImpl.cpp | a5e32766b0dba9e03ee8d5a487fd9bb9fc92359b | [
"MIT"
] | permissive | sycomix/android-nn-driver | 1f0a40a427cee8aeefd22bdf672dd256fa6c4cde | 205bb9907cbe74b696a6ef77a090206c1626c1f3 | refs/heads/master | 2020-03-30T11:35:03.581467 | 2018-09-11T11:41:24 | 2018-09-11T11:41:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,799 | cpp | //
// Copyright © 2017 Arm Ltd. All rights reserved.
// See LICENSE file in the project root for full license information.
//
#include "ArmnnDriverImpl.hpp"
#include "../1.0/ArmnnDriverImpl.hpp"
#include <OperationsUtils.h>
#include <log/log.h>
#include <boost/assert.hpp>
#include <ValidateHal.h>
using namespace std;
using namespace android;
using namespace android::nn;
using namespace android::hardware;
namespace
{
void NotifyCallbackAndCheck(const sp<IPreparedModelCallback>& callback,
ErrorStatus errorStatus,
const sp<IPreparedModel>& preparedModelPtr)
{
Return<void> returned = callback->notify(errorStatus, preparedModelPtr);
// This check is required, if the callback fails and it isn't checked it will bring down the service
if (!returned.isOk())
{
ALOGE("V1_1::ArmnnDriverImpl::prepareModel_1_1: hidl callback failed to return properly: %s ",
returned.description().c_str());
}
}
Return<ErrorStatus> FailPrepareModel(ErrorStatus error,
const string& message,
const sp<IPreparedModelCallback>& callback)
{
ALOGW("V1_1::ArmnnDriverImpl::prepareModel_1_1: %s", message.c_str());
NotifyCallbackAndCheck(callback, error, nullptr);
return error;
}
} // namespace
namespace armnn_driver
{
namespace V1_1
{
Return<void> ArmnnDriverImpl::getCapabilities_1_1(
const armnn::IRuntimePtr& runtime,
neuralnetworks::V1_1::IDevice::getCapabilities_1_1_cb cb)
{
ALOGV("V1_1::ArmnnDriverImpl::getCapabilities_1_1()");
neuralnetworks::V1_0::IDevice::getCapabilities_cb cb_1_0 =
[&](ErrorStatus status, const neuralnetworks::V1_0::Capabilities& capabilities)
{
BOOST_ASSERT_MSG(compliantWithV1_1(capabilities),
"V1_1::ArmnnDriverImpl: V1_0::Capabilities not compliant with V1_1::Capabilities");
cb(status, convertToV1_1(capabilities));
};
V1_0::ArmnnDriverImpl::getCapabilities(runtime, cb_1_0);
return Void();
}
Return<void> ArmnnDriverImpl::getSupportedOperations_1_1(
const armnn::IRuntimePtr& runtime,
const DriverOptions& options,
const neuralnetworks::V1_1::Model& model,
neuralnetworks::V1_1::IDevice::getSupportedOperations_1_1_cb cb)
{
ALOGV("V1_1::ArmnnDriverImpl::getSupportedOperations_1_1()");
if(compliantWithV1_0(model))
{
V1_0::ArmnnDriverImpl::getSupportedOperations(runtime, options, convertToV1_0(model), cb);
}
else
{
std::vector<bool> result;
if (!runtime)
{
ALOGW("V1_1::ArmnnDriverImpl::getSupportedOperations_1_1: Device unavailable");
cb(ErrorStatus::DEVICE_UNAVAILABLE, result);
return Void();
}
if (!android::nn::validateModel(model))
{
ALOGW("V1_1::ArmnnDriverImpl::getSupportedOperations_1_1: Invalid model passed as input");
cb(ErrorStatus::INVALID_ARGUMENT, result);
return Void();
}
result.assign(model.operations.size(), false);
cb(ErrorStatus::NONE, result);
}
return Void();
}
Return<ErrorStatus> ArmnnDriverImpl::prepareModel_1_1(
const armnn::IRuntimePtr& runtime,
const armnn::IGpuAccTunedParametersPtr& clTunedParameters,
const DriverOptions& options,
const neuralnetworks::V1_1::Model& model,
const sp<IPreparedModelCallback>& cb)
{
ALOGV("V1_1::ArmnnDriverImpl::prepareModel_1_1()");
if(compliantWithV1_0(model))
{
return V1_0::ArmnnDriverImpl::prepareModel(runtime, clTunedParameters, options, convertToV1_0(model), cb,
model.relaxComputationFloat32toFloat16 && options.GetFp16Enabled());
}
else
{
if (cb.get() == nullptr)
{
ALOGW("V1_1::ArmnnDriverImpl::prepareModel_1_1: Invalid callback passed to prepareModel");
return ErrorStatus::INVALID_ARGUMENT;
}
if (!runtime)
{
return FailPrepareModel(ErrorStatus::DEVICE_UNAVAILABLE,
"V1_1::ArmnnDriverImpl::prepareModel_1_1: Device unavailable", cb);
}
if (!android::nn::validateModel(model))
{
return FailPrepareModel(ErrorStatus::INVALID_ARGUMENT,
"V1_1::ArmnnDriverImpl::prepareModel_1_1: Invalid model passed as input", cb);
}
FailPrepareModel(ErrorStatus::GENERAL_FAILURE,
"V1_1::ArmnnDriverImpl::prepareModel_1_1: Unsupported model", cb);
return ErrorStatus::NONE;
}
}
} // armnn_driver::namespace V1_1
} // namespace armnn_driver
| [
"[email protected]"
] | |
02cc9aa6bd066592c70fa56b18f8c3f980547e49 | de51ca68306b46a9f0f9217cb4e5f9c4d5308e8e | /II/Final/Point/point.cpp | d4d1568131d6a54d0691c7ee33880350baeb4439 | [] | no_license | alioshag/Cplusplus | 5c180e2a5baf678be0a9f4c1425f283034e96936 | 9cf027a199529272fa32579f7ae421bca7a6c666 | refs/heads/master | 2020-12-24T06:57:24.199726 | 2016-08-25T16:43:10 | 2016-08-25T16:43:10 | 58,066,471 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,714 | cpp | /****************************************************************************
filename: "point-template.cpp", final#1
author: Aliosha Gonzalez
synopsis: This is the implementation of the class Point. The interface is in the file
"point-template.h"
*******************************************************************************/
#include "pointtemplate.h"
#include <iostream>
#include <cstdlib>
using namespace std;
//mutators
template<class T>
void Point<T>::reset_location(T theX, T theY)
{
x = theX;
y = theY;
}
//operators
Point<T>& Point::operator=(const Point<T> &rhs)
{
cout << "operator= of Point template\n";
if (this == &rhs) //if the right side is the same as the left side
{
return *this;
}
else
{
x = rhs.getX(); //deep copy instead of shallow copy-->(x=rhs.x)
y = rhs.getY(); //deep copy
return *this;
}
}
void Point<T>::operator+(T Delta)
{
cout << "operator+ Delta\n";
x = getX() + Delta;
y = getY() + Delta;
}
T Point<T>::operator-(const Point<T> &rhs)
{
cout << "operator-(const Point &rhs)\n";
double d; //distance
d = sqrt(static_cast<double>((x-rhs.x)*(x-rhs.x) + (y-rhs.y)*(y-rhs.y)));
return static_cast<int>(d);
}
T Point<T>::operator-(Point<T> &rhs)
{
cout << "operator-(Point &rhs)\n";
double d; //distance
d = sqrt(static_cast<double>((x-rhs.x)*(x-rhs.x) + (y-rhs.y)*(y-rhs.y)));
return static_cast<int>(d);
}
ostream& operator<<(ostream &os, const Point<T> &rhs)
{
os << "x=" << rhs.x << ", y=" << rhs.y << endl;
return os;
}
| [
"[email protected]"
] | |
037510efe30efecb1630575983d3d61dcca62eec | 96fa9ba68d0db13e753c27dade9d62cd9f552de1 | /src/spring_attacher_gpu.hpp | 493405ca133e40705345034cdb863f3af045feb6 | [] | no_license | Reichard/biomechanic_depth_matching | d517e6be2391dd4702a9ea3ccdd5433883eb6cf6 | e6b65a4fb00dddee0272f048216398e3ae7723c7 | refs/heads/master | 2021-09-17T14:18:08.871587 | 2017-12-14T14:25:50 | 2017-12-14T14:25:50 | 112,749,930 | 2 | 1 | null | 2018-04-06T09:26:13 | 2017-12-01T14:37:09 | C++ | UTF-8 | C++ | false | false | 422 | hpp | #pragma once
#include <GL/glew.h>
#include <GL/gl.h>
#include <cuda.h>
#include <cudaGL.h>
struct vec3f {
float x,y,z;
};
struct vec3i {
int x,y,z;
};
void attach_gpu_springs( float *data, float* association_data, float* springs, unsigned int* triangles,
float *vertices, float *normals, float* weights, unsigned int size, unsigned int width, unsigned int height );
void map_association_surface(CUarray &array);
| [
"[email protected]"
] | |
c55ecf8fa44bd5681d0eb4c44eb04609ced86dc7 | 096d93d58a06ad0c8fc9e2fd1dbf4366e1b11ae0 | /t1_ex22_hotel/myDates.h | 984e24875b494a332ded342cc4ddb5204dd76576 | [] | no_license | vsulabs/cpp_task1ex22_hotel | 06c14e00693e46dd7ed3c9e1d2bf8b112ad98056 | 215ea8bea9194328950f13cfcb22809eabe0abf4 | refs/heads/master | 2021-01-13T15:54:06.745795 | 2016-11-11T20:00:47 | 2016-11-11T20:00:47 | 79,897,062 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 3,054 | h | #pragma once
#include <string>
static const int MaxYear = 2020;
static const int MaxMonth = 12;
static const int MaxDay = 31;
static const int MinYear = 1950;
static const int MinMonth = 1;
static const int MinDay = 1;
static const int DaysPerYear = 365;
static const int DaysPerMonth = 31;
static const int date_size = 11;
class myDates // дата
{
int day; // день
int month; // месяц
int year; // год
public:
// конструктор, может служить конструктором без параметров
myDates(
int d = MinDay,
int m = MinMonth,
int y = MinYear );
myDates(const myDates& other); // конструктор копирования
myDates(std::string& dataStr); // парсинг из строки
void copy_by(const myDates& other);
int getDay() const { return day; } // свойство доступа к полю день
int getMonth() const { return month; } // свойство доступа к полю месяц
int getYear() const { return year; } // свойство доступа к полю год
void print() const ; // выводит на экран текущую дату в текстовом виде
void printFormat() const ; // выводит на экран текущую дату в формате дд.мм.гггг.
myDates& operator =(const myDates& other); // оператор присваивания осуществляет присваивание
// операторы сравнения
bool operator ==(const myDates& other) const;
bool operator !=(const myDates& other) const;
bool operator > (const myDates& other) const;
bool operator < (const myDates& other) const;
bool operator >=(const myDates& other) const;
bool operator <=(const myDates& other) const;
myDates operator + (int days) const;
myDates operator + (const myDates& other) const;
// перегруженные операторы ввода-вывода
std::ostream& operator << (std::ostream& output) const;
std::istream& operator >> (std::istream& input);
std::string toString() const; // сохранение даты в виде строки
// fixedBegin и fixedOut - диапазон, на вхождение в который делается проверка
// возвращает 1, если диапазон дат in out пересекается с диапазоном fixedBegin, fixedEnd
// возвращает 0, если ни дата in или дата out не попадает в диапазон fixedBegin, fixedEnd
static bool dates_crossed(
const myDates& fixedBegin,
const myDates& fixedEnd,
const myDates& in,
const myDates& out);
// подсчет количества дней между двумя датами
static int daysBetween(
const myDates& begin,
const myDates& end);
// меняет местами значения begin и end, если end меньше чем begin
static void days_correct(
myDates& begin,
myDates& end);
~myDates();
};
| [
"[email protected]"
] | |
b9023106778a787440304ce8ccc0ad75edc4c1b3 | de1fc8272ca500fb13a93c9d053cdd75634329cd | /Book_Source/Cpp-Primer-Plus-programming-exercises-master/Cpp-Primer-Plus-programming-exercises-master/code/Chapter12/12_2_string2.cpp | e23431d87201a4021698fe611c092e78fb491c49 | [] | no_license | hohaidang/CPP_Basic2Advance | ada69129123c14491c29803a3f7224b924616a80 | cdb733e9b24c7ad4927deab57fff389f521d0ea3 | refs/heads/master | 2021-05-21T10:31:46.627204 | 2021-03-29T07:16:43 | 2021-03-29T07:16:43 | 252,654,029 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,605 | cpp | // By luckycallor
// Welcome to my site: www.luckycallor.com
#include<cstring>
#include<cctype>
#include"12_2_string2.h"
using std::cin;
using std::cout;
using std::endl;
int String::num_strings = 0;
int String::HowMany()
{
return num_strings;
}
String::String(const char* s)
{
len = std::strlen(s);
str = new char[len+1];
std::strcpy(str,s);
num_strings++;
}
String::String()
{
len = 4;
str = new char[len+1];
str[0] = '\0';
num_strings++;
}
String::String(const String& st)
{
num_strings++;
len = st.len;
str = new char[len+1];
std::strcpy(str,st.str);
}
String::~String()
{
--num_strings;
delete [] str;
}
String& String::operator=(const String& st)
{
if(this == &st) return *this;
delete [] str;
len = st.len;
str = new char[len+1];
std::strcpy(str,st.str);
return *this;
}
String& String::operator=(const char* s)
{
delete [] str;
len = std::strlen(s);
str = new char[len+1];
std::strcpy(str,s);
return *this;
}
char& String::operator[](int i)
{
return str[i];
}
const char& String::operator[](int i)const
{
return str[i];
}
String operator+(const String& st1,const String& st2)
{
char temp[st1.len+st2.len+1];
std::strcpy(temp,st1.str);
std::strcpy(temp+st1.len,st2.str);
return String(temp);
}
String operator+(const String& st,const char* cst)
{
char temp[st.len+std::strlen(cst)+1];
std::strcpy(temp,st.str);
std::strcpy(temp+st.len,cst);
return String(temp);
}
String operator+(const char* cst,const String& st)
{
char temp[std::strlen(cst)+st.len+1];
std::strcpy(temp,cst);
std::strcpy(temp+std::strlen(cst),st.str);
return String(temp);
}
void String::stringlow()
{
for(int i=0;i<len;++i) str[i] = std::tolower(str[i]);
}
void String::stringup()
{
for(int i=0;i<len;++i) str[i] = std::toupper(str[i]);
}
int String::has(char c) const
{
int cnt = 0;
for(int i=0;i<len;++i){
if(str[i] == c) cnt++;
}
return cnt;
}
bool operator<(const String& st1,const String& st2)
{
return (std::strcmp(st1.str,st2.str) < 0);
}
bool operator>(const String& st1,const String& st2)
{
return st2 < st1;
}
bool operator==(const String& st1,const String& st2)
{
return (std::strcmp(st1.str,st2.str) == 0);
}
ostream& operator<<(ostream& os,const String& st)
{
os << st.str;
return os;
}
istream& operator>>(istream& is,String& st)
{
char temp[String::CINLIM];
is.get(temp,String::CINLIM);
if(is) st = temp;
while(is && is.get() != '\n') continue;
return is;
}
| [
"[email protected]"
] | |
b7a67007216c0b6ffa9dc9602628abdd0fb7da39 | 30114f6730aac693971d826f58e46f6d158e6957 | /MFC/general/npp/np.h | ae3eb90dba8550d1ccb7a361471a6813640ca382 | [] | no_license | oudream/vc_example_official | 67111751a416df93cdc4b9f1048d93f482819992 | 8075deebd4755b2a7531a8f918c19ad2e82e2b23 | refs/heads/master | 2020-06-14T08:00:01.267447 | 2019-07-03T01:03:59 | 2019-07-03T01:03:59 | 194,953,887 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,520 | h | // np.h : main header file for the NP application
//
// This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.
//
#ifndef __AFXWIN_H__
#error include 'stdafx.h' before including this file for PCH
#endif
#include "resource.h" // main symbols
// application defines
#define COMBO_HEIGHT 100 // width of edit control for combobox
#define COMBO_WIDTH 160 // drop down height
#define HISTORY_COUNT 10 // number of entries for the last search selections
#define TIMER_ID 2 // timer ID for clock on status bar
/////////////////////////////////////////////////////////////////////////////
// CNotepadApp:
// See np.cpp for the implementation of this class
//
class CNotepadApp : public CWinApp
{
public:
CNotepadApp();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CNotepadApp)
public:
virtual BOOL InitInstance();
virtual BOOL OnIdle(LONG lCount);
//}}AFX_VIRTUAL
// Implementation
//{{AFX_MSG(CNotepadApp)
afx_msg void OnAppAbout();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
| [
"[email protected]"
] | |
f51e5306ad8a4bcf2ec8def76bfb725d451342c5 | 0e7864a673553f6d2a9c10e8804aab375f909198 | /TMegaSelector/interface/TMegaSelector.h | aea066da733bfd9f2b00ed798f8c08d21e307e04 | [] | no_license | jjswan33/FinalStateAnalysis | 5917044ff9580bd62ff137927605eb60209e30d8 | d1d44806068570f7223abc1e3ea02dc6e9764919 | refs/heads/master | 2021-01-23T21:33:19.682884 | 2012-05-20T12:07:30 | 2012-05-20T12:07:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,988 | h | #ifndef TMEGASELECTOR_F965XW8K
#define TMEGASELECTOR_F965XW8K
/*
* TMegaSelector
*
* An enhanced version of TSelector.
*
*/
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <TBranchProxyDirector.h>
#include "TBranchProxy.h"
#include "TSelector.h"
#include "FinalStateAnalysis/TMegaSelector/interface/TMegaSelection.h"
#include "FinalStateAnalysis/TMegaSelector/interface/TMegaSelectionFactory.h"
#include "FinalStateAnalysis/TMegaSelector/interface/TMegaSelectionSet.h"
class TMegaSelector : public TSelector {
public:
TMegaSelector(TTree *tree=0);
virtual ~TMegaSelector();
TTree *chain;
// Abstract interface for derived classes
virtual void MegaInit(TTree* /*tree*/) {}
virtual Bool_t MegaNotify() { return true; }
virtual void MegaBegin() {}
virtual void MegaSlaveBegin(TTree* /* tree */) {}
virtual Bool_t MegaProcess(Long64_t entry)=0;
virtual void MegaSlaveTerminate() {}
virtual void MegaTerminate() {}
/// Build a cut on an integer branch and add it to [selection]
void MakeIntCut(const std::string& selection, const std::string& branch,
const std::string& op, Int_t value, bool abs=false);
/// Build a cut on an float branch and add it to [selection]
void MakeFloatCut(const std::string& selection, const std::string& branch,
const std::string& op, Float_t value, bool abs=false);
/// Build a cut on an double branch and add it to [selection]
void MakeDoubleCut(const std::string& selection, const std::string& branch,
const std::string& op, Double_t value, bool abs=false);
// Get the TMegaSelectionSet with the given name. If it doesn't exists,
// this will return null.
TMegaSelectionSet* GetSelectionSet(const std::string& name) const;
// Set which selection set to use for filtering. Any entries (rows) which
// do not pass this selection will not be passed to MegaProcess.
void SetFilterSelection(const std::string&);
/// Get the total number of processed entries
unsigned int GetProcessedEntries() const;
/// Get the number of entries that were filtered
unsigned int GetFilteredEntries() const;
/// Do not read branch on calls to chain->GetEntry()
void DisableBranch(const std::string& branch);
/// Do read branch on calls to chain->GetEntry()
void EnableBranch(const std::string& branch);
// Needed for ROOT to call the virtual functions correctly
virtual Int_t Version() const { return 2; }
/* Advanced selector interface */
// Add a TMegaSelection to the named selection set. Does not take
// ownership.
void AddToSelection(const std::string& name, const TMegaSelection& select);
// Add a TMegaSelection to the named selection set. Takes ownershipt.
void AddToSelection(const std::string& name,
std::auto_ptr<TMegaSelection> select);
/// Get the factory to build TMegaSelections
const TMegaSelectionFactory* factory();
ClassDef( TMegaSelector, 1 ); // Enhanced TSelector
private:
void Init(TTree* tree);
Bool_t Notify();
void Begin(TTree*);
void SlaveBegin(TTree*);
void SlaveTerminate();
void Terminate();
Bool_t Process(Long64_t entry);
// Keep track of entries processed
unsigned int filteredEntries_;
unsigned int allEntries_;
ROOT::TBranchProxyDirector director_; //!Manages the proxies
// Factory class to build selections
std::auto_ptr<TMegaSelectionFactory> factory_;
// The entry and tree currently being processed
Long64_t currentEntry_;
typedef std::map<std::string, TMegaSelectionSet*> SelectionSetMap;
SelectionSetMap selections_;
// The selection to use for filtering calls to MegaProcess();
TMegaSelectionSet* filterSelection_;
// These get applied on each call to Init()
std::vector<std::pair<std::string, int> > branchCommands_;
};
#endif /* end of include guard: TMEGASELECTOR_F965XW8K */
| [
"[email protected]"
] | |
1f90d421e75bd6594c8b441b8d1baa3617403ac4 | d358db68a1c7fadba89b26ce6739fd72c3dbdf3f | /chapter4/explicit-refs/src/nameless/translator.cpp | 219673f4ec0a742fca82f5057d8e0c5318cd3eb5 | [] | no_license | lie-yan/eopl | 428863e189523b3ba80f4cf51995003e3a9d8eb0 | f4c8afc81f2558c117617dda09e18d4400bba941 | refs/heads/master | 2020-03-29T06:17:32.323307 | 2019-11-14T13:28:51 | 2019-11-14T13:28:51 | 149,618,333 | 0 | 0 | null | 2019-11-14T13:27:49 | 2018-09-20T14:00:39 | C++ | UTF-8 | C++ | false | false | 7,004 | cpp | //
// Created by Lie Yan on 2019-01-27.
//
#include "translator.h"
#include "built_in.h"
#include <fmt/ostream.h>
#include <boost/type_index.hpp>
#include <numeric>
#include <gsl/gsl>
namespace eopl {
template<typename T>
std::string error_message (const T& t) {
return fmt::format("{} should not appear in the program for translation_of()",
boost::typeindex::type_id<T>().pretty_name());
}
SpStaticEnv make_initial_senv () {
return
StaticEnv::extend(
StaticEnv::make_empty(),
Symbol{"emptylist"}
);
}
Program translation_of (const Program& program, const SpStaticEnv& senv) {
return
Program{
translation_of(program.exp1, senv)
};
}
struct TranslationOfVisitor {
const SpStaticEnv& senv;
template<typename T>
Expression operator () (const boost::recursive_wrapper<T>& e) {
return translation_of(e.get(), senv);
}
template<typename T>
Expression operator () (const T& e) { return translation_of(e, senv); }
};
Expression translation_of (const Expression& exp, const SpStaticEnv& senv) {
return std::visit(TranslationOfVisitor{senv}, *exp);
}
Expression translation_of (const ConstExp& exp, const SpStaticEnv& senv) {
return to_exp(exp);
}
Expression translation_of (const VarExp& exp, const SpStaticEnv& senv) {
if (built_in::find_built_in(exp.var)) {
return to_exp(exp);
} else {
return
to_exp(
NamelessVarExp{
StaticEnv::apply(senv, exp.var)
});
}
}
Expression translation_of (const NamelessVarExp& exp, const SpStaticEnv& senv) {
throw std::runtime_error(error_message(exp));
}
Expression translation_of (const IfExp& exp, const SpStaticEnv& senv) {
return
to_exp(
IfExp{
translation_of(exp.cond, senv),
translation_of(exp.then_, senv),
translation_of(exp.else_, senv)
});
}
Expression translation_of (const LetExp& exp, const SpStaticEnv& senv, std::false_type) {
Expects(!exp.star);
std::vector<Symbol> var_list;
std::transform(std::begin(exp.clauses), std::end(exp.clauses),
std::back_inserter(var_list),
[] (const LetExp::Clause& c) {
return c.var;
});
std::vector<Expression> exp_list;
std::transform(std::begin(exp.clauses), std::end(exp.clauses),
std::back_inserter(exp_list),
[] (const LetExp::Clause& c) {
return c.exp;
});
return
to_exp(
NamelessLetExp{
translation_of(exp_list, senv),
translation_of(exp.body, StaticEnv::extend(senv, std::move(var_list))),
exp.star
});
}
Expression translation_of (const LetExp& exp, const SpStaticEnv& senv, std::true_type) {
Expects(exp.star);
std::vector<Expression> exp_list{};
auto new_senv = std::accumulate(std::begin(exp.clauses), std::end(exp.clauses),
senv,
[&exp_list] (SpStaticEnv& acc, const LetExp::Clause& c) {
exp_list.push_back(translation_of(c.exp, acc));
return StaticEnv::extend(std::move(acc), c.var);
});
return
to_exp(
NamelessLetExp{
exp_list,
translation_of(exp.body, new_senv),
exp.star
});
}
Expression translation_of (const LetExp& exp, const SpStaticEnv& senv) {
if (exp.star) {
return translation_of(exp, senv, std::true_type());
} else {
return translation_of(exp, senv, std::false_type());
}
}
Expression translation_of (const NamelessLetExp& exp, const SpStaticEnv& senv) {
throw std::runtime_error(error_message(exp));
}
Expression translation_of (const CondExp& exp, const SpStaticEnv& senv) {
CondExp::ClauseList target;
std::transform(std::begin(exp.clauses), std::end(exp.clauses),
std::back_inserter(target),
[&senv] (const CondExp::Clause& c) {
return CondExp::Clause{
translation_of(c.cond, senv),
translation_of(c.body, senv)};
});
return
to_exp(
CondExp{
std::move(target)
});
}
Expression translation_of (const UnpackExp& exp, const SpStaticEnv& senv) {
Expression pack = translation_of(exp.pack, senv);
Expression body = translation_of(exp.body, StaticEnv::extend(senv, exp.vars));
return
to_exp(
NamelessUnpackExp{
exp.vars.size(),
pack,
body
});
}
Expression translation_of (const NamelessUnpackExp& exp, const SpStaticEnv& senv) {
throw std::runtime_error(error_message(exp));
}
Expression translation_of (const ProcExp& exp, const SpStaticEnv& senv) {
return
to_exp(
NamelessProcExp{
translation_of(exp.body, StaticEnv::extend(senv, exp.params))
});
}
Expression translation_of (const NamelessProcExp& exp, const SpStaticEnv& senv) {
throw std::runtime_error(error_message(exp));
}
Expression translation_of (const CallExp& exp, const SpStaticEnv& senv) {
return
to_exp(
CallExp{
translation_of(exp.rator, senv),
translation_of(exp.rands, senv)
});
}
Expression translation_of (const LetrecExp& exp, const SpStaticEnv& senv) {
std::vector<Symbol> proc_names;
std::transform(std::begin(exp.proc_list), std::end(exp.proc_list),
std::back_inserter(proc_names),
[] (const LetrecProcSpec& spec) {
return spec.name;
});
auto letrec_senv = StaticEnv::extend(senv, std::move(proc_names));
auto to_nameless = [&letrec_senv] (const LetrecProcSpec& spec) {
auto new_senv = StaticEnv::extend(letrec_senv, spec.params);
return NamelessLetrecProcSpec{
spec.params.size(),
translation_of(spec.body, new_senv)
};
};
std::vector<NamelessLetrecProcSpec> proc_list;
std::transform(std::begin(exp.proc_list), std::end(exp.proc_list),
std::back_inserter(proc_list),
to_nameless);
auto body = translation_of(exp.body, letrec_senv);
return to_exp(
NamelessLetrecExp{
std::move(proc_list),
std::move(body)
});
}
Expression translation_of (const NamelessLetrecExp& exp, const SpStaticEnv& senv) {
throw std::runtime_error(error_message(exp));
}
std::vector<Expression> translation_of (const std::vector<Expression>& exp_list, const SpStaticEnv& senv) {
std::vector<Expression> ret;
std::transform(std::begin(exp_list),
std::end(exp_list),
std::back_inserter(ret),
[&senv] (const Expression& e) -> Expression {
return translation_of(e, senv);
});
return ret;
}
} | [
"[email protected]"
] | |
4eb31e22387d575ceb8052a37fa38729c2c9b2c5 | 23a90914cf22932f841b470397c8ab47b84f1e70 | /chapter5/ex5_21.cpp | 62e36bd1d1ec7a50ddafbe04551495444b3489a0 | [] | no_license | suisuihan/cpp-primer | e5debbf3f74063fc8450d9e5fa6a071a3b9bf6b5 | 402754e7af5aaa7219b7dea5649bffe073406431 | refs/heads/master | 2020-04-12T05:40:12.803413 | 2016-10-11T17:08:22 | 2016-10-11T17:08:22 | 61,215,946 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 415 | cpp | #include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string currStr, preStr;
bool repeated = false;
while(cin >> currStr){
if(currStr == preStr){
if(isupper(currStr.at(0))){
repeated = true;
break;
}
else
continue;
}
preStr = currStr;
}
if(repeated)
cout << "repeat string is: " << currStr << endl;
else
cout << "nothing happen!" << endl;
} | [
"[email protected]"
] | |
263151caf5d67a49616d65be1eb60363104271e1 | 89c5b38b8d84867a44753ed668e5702e382d8e29 | /W/widget.hpp | a3835b384f5bd99512e7c49a9149657d706d42fc | [] | no_license | HunorLaczko/Sudoku | 19d26a0bbd03ea3e19de1d1453c81acb23ba1155 | 5f028d8f8918d647654975ce26da7fc38b9b47b4 | refs/heads/master | 2021-05-31T07:41:13.618934 | 2016-05-20T10:29:25 | 2016-05-20T10:29:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 866 | hpp | #ifndef WIDGET_HPP_INCLUDED
#define WIDGET_HPP_INCLUDED
#include "graphics.hpp"
#include<iostream>
#include<cmath>
#include<time.h>
#include<vector>
#include<sstream>
#include<functional>
#include<cmath>
#include<iostream>
#include<cstring>
#include<string>
using namespace genv;
using namespace std;
const int size_x=1280;
const int size_y=720;
namespace W
{
class Window;
struct Color
{
unsigned char r,g,b;
};
class Widget
{
protected:
float x,y,a,b;
Color col;
bool selected;
Window *ablak;
public:
Widget(float xx, float yy, float aa, float bb, Color coll, bool akt, Window *win);
virtual ~Widget(){}
virtual void draw()=0;
virtual void handle(genv::event ev);
virtual void setActive(bool value);
virtual bool is_focusable()=0;
virtual bool is_selected(int xx, int yy);
};
}
#endif // WIDGET_HPP_INCLUDED
| [
"[email protected]"
] | |
fb6402bcd30ea7187e984eecac5bc5bccda925fe | b642258ff318d22abc28428a82a3f0f5138d678a | /Compression/Delta/C_Delta.cpp | e957c6c698e10c7d886d4f2c01824bc82ff5cae2 | [] | no_license | manuelVzla01/freearc | 783b11692802833cde746d4a1c1b9d2158c1ec8b | 4bdc5e8df22588f436c04afc4041359ded9d2df6 | refs/heads/master | 2021-04-02T03:07:58.842227 | 2020-03-18T13:48:11 | 2020-03-18T13:48:11 | 248,237,175 | 2 | 0 | null | 2020-03-18T13:20:05 | 2020-03-18T13:20:05 | null | WINDOWS-1251 | C++ | false | false | 3,796 | cpp | extern "C" {
#include "C_Delta.h"
}
#define DELTA_LIBRARY
#include "Delta.cpp"
/*-------------------------------------------------*/
/* Реализация класса DELTA_METHOD */
/*-------------------------------------------------*/
// Конструктор, присваивающий параметрам метода сжатия значения по умолчанию
DELTA_METHOD::DELTA_METHOD()
{
BlockSize = 8*mb;
ExtendedTables = 0;
}
// Функция распаковки
int DELTA_METHOD::decompress (CALLBACK_FUNC *callback, void *auxdata)
{
// Use faster function from DLL if possible
static FARPROC f = LoadFromDLL ("delta_decompress");
if (!f) f = (FARPROC) delta_decompress;
return ((int (__cdecl *)(MemSize, int, CALLBACK_FUNC*, void*)) f)
(BlockSize, ExtendedTables, callback, auxdata);
}
#ifndef FREEARC_DECOMPRESS_ONLY
// Функция упаковки
int DELTA_METHOD::compress (CALLBACK_FUNC *callback, void *auxdata)
{
// Use faster function from DLL if possible
static FARPROC f = LoadFromDLL ("delta_compress");
if (!f) f = (FARPROC) delta_compress;
return ((int (__cdecl *)(MemSize, int, CALLBACK_FUNC*, void*)) f)
(BlockSize, ExtendedTables, callback, auxdata);
}
// Записать в buf[MAX_METHOD_STRLEN] строку, описывающую метод сжатия и его параметры (функция, обратная к parse_DELTA)
void DELTA_METHOD::ShowCompressionMethod (char *buf)
{
DELTA_METHOD defaults; char BlockSizeStr[100]=":";
showMem (BlockSize, BlockSizeStr+1);
sprintf (buf, "delta%s%s", BlockSize!=defaults.BlockSize? BlockSizeStr:"", ExtendedTables? ":x":"");
}
#endif // !defined (FREEARC_DECOMPRESS_ONLY)
// Конструирует объект типа DELTA_METHOD с заданными параметрами упаковки
// или возвращает NULL, если это другой метод сжатия или допущена ошибка в параметрах
COMPRESSION_METHOD* parse_DELTA (char** parameters)
{
if (strcmp (parameters[0], "delta") == 0) {
// Если название метода (нулевой параметр) - "delta", то разберём остальные параметры
DELTA_METHOD *p = new DELTA_METHOD;
int error = 0; // Признак того, что при разборе параметров произошла ошибка
// Переберём все параметры метода (или выйдем раньше при возникновении ошибки при разборе очередного параметра)
while (*++parameters && !error)
{
char* param = *parameters;
if (strlen(param)==1) switch (*param) { // Однобуквенные параметры
case 'x': p->ExtendedTables = 1; continue;
}
switch (*param) { // Параметры, содержащие значения
case 'b': p->BlockSize = parseMem (param+1, &error); continue;
}
// Сюда мы попадаем, если в параметре не указано его название
// Если этот параметр удастся разобрать как объём памяти,
// то присвоим его значение полю BlockSize
p->BlockSize = parseMem (param, &error);
}
if (error) {delete p; return NULL;} // Ошибка при парсинге параметров метода
return p;
} else
return NULL; // Это не метод DELTA
}
static int DELTA_x = AddCompressionMethod (parse_DELTA); // Зарегистрируем парсер метода DELTA
| [
"bulatz@3a4f7f31-9599-433d-91b1-573e8b61252c"
] | bulatz@3a4f7f31-9599-433d-91b1-573e8b61252c |
bfac0a4ff97e8041cf6405f59e44e30317d97987 | 30b27778394fbdc76fe00612efad8f48f4560731 | /src/Main/Match.hpp | ca3c6072b5277c0727792b435d3c77df7a1e120a | [] | no_license | ArtronicsGame/MatchLogic | 86a531cd5ca8f4f9fcf761047690611705bdfdff | 8d5703977da0829632362b996e2d4601c74da57c | refs/heads/master | 2022-01-25T15:52:21.304789 | 2019-05-23T20:31:33 | 2019-05-23T20:31:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,015 | hpp | #ifndef _MATCH_H
#define _MATCH_H
#include <bits/stdc++.h>
#include <thread>
#include <InternalHeaders.hpp>
using namespace std;
using namespace chrono;
using namespace nlohmann;
class Match : public MiddleConnection, public b2ContactListener{
private:
const float32 _timeStep = 1.0f / 50.0f;
const int32 _velocityIterations = 6;
const int32 _positionIterations = 2;
b2World* _world;
bool _notEnded = true;
vector<json> _frameAction;
int _gamePeriod = 0.25 * 60 * 50; // Min * Sec/Min * FPS
AtomicQueue<json> events;
thread* logic;
public:
json _actions;
string _matchId = "N/A";
map<int, b2Body*> heroes;
map<int, Heroes> heroTypes;
public:
void BeginContact(b2Contact* contact);
Match();
void OnMessage(string msg, int id);
void OnPacket(UDPPacket packet, int id);
void OnMatchStart();
void EndMatch();
void FinalEnd();
//Game Section
string getWorldJSON();
void frame();
void run();
void preprocess();
void sendAndStore(json message);
};
#endif | [
"[email protected]"
] | |
4e03f9ebfa1c5e37676f45c73e470052776b7fd3 | 9a618daca7a26aee767a9de8316eed5dc90c70d3 | /Sample/core/delegate.cpp | 459cc5f09c878e370d11c4cd1bc9b5763d8bfb4e | [] | no_license | phr34k/vdsl | 054cca3cbd305a3c19e2f93d6e4e0edaadac2b47 | 8f3ce4cfba70b4621e73c3f4ac150ff95358d3ec | refs/heads/master | 2023-09-04T10:29:25.713656 | 2023-08-08T14:12:18 | 2023-08-08T14:12:18 | 9,781,234 | 6 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 3,519 | cpp | /**
* Domain Specific Visual Programming Language
* Copyright (c) 2013 NHTV UNIVERSITY OF APPLIED SCIENCES
* 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. Neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*
* Author: Lawrence Kok
*
*/
#include <stddef.h>
#include "delegate.h"
Delegate::Delegate()
{
this->functions = NULL;
}
bool Delegate::Add(DelegateCallback func)
{
//Loop over all functions see if it already exists
//and return false if it does.
__DelegateItem* p = this->functions;
__DelegateItem* p2 = NULL;
while( p != NULL )
{
if( p->function == func )
return false;
p = p->next;
p2 = p;
};
//Function callback already exists, we use p2 as a helper
//to quickly see our p before it becomes NULL
if( p2 == NULL )
{
this->functions = new __DelegateItem();
this->functions->function = func;
this->functions->next = NULL;
}
else
{
p2->next = new __DelegateItem();
p2->next->function = func;
p2->next->next = NULL;
}
return true;
}
bool Delegate::Remove(DelegateCallback func)
{
//Loop over all functions see if it already exists
//and return true if it does remove it.
__DelegateItem* p = this->functions;
__DelegateItem* p2 = NULL;
while( p != NULL )
{
if( p->function == func )
{
if( p2 != NULL )
p2->next = p->next;
else
this->functions = p->next;
delete p;
return true;
}
p = p->next;
p2 = p;
};
//The function is not found so return false
return false;
}
void Delegate::Execute()
{
//Loop over all functions see if it already exists
//and return false if it does.
__DelegateItem* p = this->functions;
while( p != NULL )
{
if( p->function != NULL )
{
//Excute function
DelegateCallback c = p->function;
//Need to set p = p->next before calling the function because if we remove it
//we get a exception that. Because we're trying to delete element p while element p is still
//on our stack.
p = p->next;
(*c)();
}
else
{
//Just to prevent infinite loops
p = p->next;
}
};
} | [
"[email protected]"
] | |
ccb2be100a5e83d02f2610f485c7cc00a7c93647 | 1ad370cc9d0c4e687ac1548fde6700c46df70499 | /职工管理系统/职工管理系统/employee.h | 5b830a8e3e27005719ff2263ea28aa184e1688cd | [] | no_license | zhuoer123/Staff-Management-System | 9d4aef8898b371eb7aaeb5607fdefb01d13ec066 | 81d81a2ffb64b9113699e76a0031e1f42648d074 | refs/heads/main | 2023-02-07T09:37:11.106375 | 2020-12-30T13:10:15 | 2020-12-30T13:10:15 | 325,169,925 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 278 | h | #pragma once
#include<iostream>
#include "worker.h"
#include<string>
using namespace std;
class Employee : public Worker
{
public:
//显示个人信息
virtual void showInfo();
//获取岗位名称
virtual string getDeptNam();
Employee(int Id, string name, int dId);
}; | [
"[email protected]"
] | |
e32acf903df53b0929888ee83dcbb79d6e63897f | 3187dd3c1186cf97781987e455f5d11244f90aec | /src/sysc/kernel/sc_module_registry.cpp | de0c39618dd6dae8d7d3496454233feba6052c54 | [
"Apache-2.0"
] | permissive | Muriukidavid/systemc-2.3.2 | fe5d9d57636025cfdc0dee7eb9c8114ca19628ad | c5d203ac014277b9d2c2af895edc43537a15674e | refs/heads/master | 2020-03-13T13:17:48.813825 | 2018-04-26T09:48:42 | 2018-04-26T09:48:42 | 131,135,420 | 0 | 1 | Apache-2.0 | 2018-06-28T15:17:19 | 2018-04-26T09:51:26 | C++ | UTF-8 | C++ | false | false | 5,077 | cpp | /*****************************************************************************
Licensed to Accellera Systems Initiative Inc. (Accellera) under one or
more contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright ownership.
Accellera 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.
*****************************************************************************/
/*****************************************************************************
sc_module_registry.cpp -- Registry for all modules.
FOR INTERNAL USE ONLY.
Original Author: Martin Janssen, Synopsys, Inc., 2001-05-21
CHANGE LOG AT THE END OF THE FILE
*****************************************************************************/
#include "sysc/kernel/sc_kernel_ids.h"
#include "sysc/kernel/sc_module.h"
#include "sysc/kernel/sc_module_registry.h"
#include "sysc/kernel/sc_simcontext.h"
namespace sc_core {
// ----------------------------------------------------------------------------
// CLASS : sc_module_registry
//
// Registry for all modules.
// FOR INTERNAL USE ONLY!
// ----------------------------------------------------------------------------
void
sc_module_registry::insert( sc_module& module_ )
{
if( sc_is_running() ) {
SC_REPORT_ERROR( SC_ID_INSERT_MODULE_, "simulation running" );
return;
}
if( m_simc->elaboration_done() ) {
SC_REPORT_ERROR( SC_ID_INSERT_MODULE_, "elaboration done" );
return;
}
#ifdef DEBUG_SYSTEMC
// check if module_ is already inserted
for( int i = size() - 1; i >= 0; -- i ) {
if( &module_ == m_module_vec[i] ) {
SC_REPORT_ERROR( SC_ID_INSERT_MODULE_, "already inserted" );
return;
}
}
#endif
// insert
m_module_vec.push_back( &module_ );
}
void
sc_module_registry::remove( sc_module& module_ )
{
int i;
for( i = 0; i < size(); ++ i ) {
if( &module_ == m_module_vec[i] ) {
break;
}
}
if( i == size() ) {
SC_REPORT_ERROR( SC_ID_REMOVE_MODULE_, 0 );
return;
}
// remove
m_module_vec[i] = m_module_vec.back();
m_module_vec.pop_back();
}
// constructor
sc_module_registry::sc_module_registry( sc_simcontext& simc_ )
: m_construction_done(0), m_module_vec(), m_simc( &simc_ )
{}
// destructor
sc_module_registry::~sc_module_registry()
{}
// called when construction is done
bool
sc_module_registry::construction_done()
{
if( size() == m_construction_done )
// nothing has been updated
return true;
for( ; m_construction_done < size(); ++m_construction_done ) {
m_module_vec[m_construction_done]->construction_done();
}
return false;
}
// called when elaboration is done
void
sc_module_registry::elaboration_done()
{
bool error = false;
for( int i = 0; i < size(); ++ i ) {
m_module_vec[i]->elaboration_done( error );
}
}
// called before simulation begins
void
sc_module_registry::start_simulation()
{
for( int i = 0; i < size(); ++ i ) {
m_module_vec[i]->start_simulation();
}
}
// called after simulation ends
void
sc_module_registry::simulation_done()
{
for( int i = 0; i < size(); ++ i ) {
m_module_vec[i]->simulation_done();
}
}
} // namespace sc_core
// $Log: sc_module_registry.cpp,v $
// Revision 1.8 2011/08/26 20:46:10 acg
// Andy Goodrich: moved the modification log to the end of the file to
// eliminate source line number skew when check-ins are done.
//
// Revision 1.7 2011/08/24 22:05:51 acg
// Torsten Maehne: initialization changes to remove warnings.
//
// Revision 1.6 2011/05/09 04:07:49 acg
// Philipp A. Hartmann:
// (1) Restore hierarchy in all phase callbacks.
// (2) Ensure calls to before_end_of_elaboration.
//
// Revision 1.5 2011/02/18 20:27:14 acg
// Andy Goodrich: Updated Copyrights.
//
// Revision 1.4 2011/02/14 17:51:40 acg
// Andy Goodrich: proper pushing an poppping of the module hierarchy for
// start_of_simulation() and end_of_simulation.
//
// Revision 1.3 2011/02/13 21:47:37 acg
// Andy Goodrich: update copyright notice.
//
// Revision 1.2 2008/05/22 17:06:26 acg
// Andy Goodrich: updated copyright notice to include 2008.
//
// Revision 1.1.1.1 2006/12/15 20:20:05 acg
// SystemC 2.3
//
// Revision 1.4 2006/01/26 21:04:54 acg
// Andy Goodrich: deprecation message changes and additional messages.
//
// Revision 1.3 2006/01/13 18:44:30 acg
// Added $Log to record CVS changes into the source.
//
// Taf!
| [
"[email protected]"
] | |
d727cdfafccc72a54d0e5c50f644b554a134c67e | 24add982437a199f4a31c4d222984159bc27bcf0 | /stato_led/stato_led.ino | febfe3d78513ce4c06facedb8e579ac48e0eead3 | [] | no_license | GiorCocc/arduino | ce42b63ecaee26b427102c5e2e1ee859ca3f87f0 | 07d0973d034b287a9d3bf363bfd097d663123516 | refs/heads/master | 2023-03-03T10:01:46.129076 | 2021-02-13T09:19:50 | 2021-02-13T09:19:50 | 336,261,289 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 611 | ino | const int A=1;
const int B=2;
const int r=8;
const int v=9;
const int g=10;
int stateButtonA=0;
int stateButtonB=0;
int stateLedR=0;
int stateLedV=0;
int stateLedG=0;
void setup()
{
pinMode(1, INPUT);
pinMode(2, INPUT);
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
}
void loop()
{
stateButtonA=digitalRead(A);
stateButtonB=digitalRead(B);
stateLedG=stateButtonA&&stateButtonB;
stateLedV=!stateButtonA&&stateButtonB;
stateLedR=stateButtonA&&!stateButtonB;
digitalWrite(r, stateLedR);
digitalWrite(g, stateLedG);
digitalWrite(v, stateLedV);
delay(1000);
}
| [
"[email protected]"
] | |
34a9e925173088717b3f5b08e5420bddf756ded1 | fa3b89c5ead0d403f7db4be81f791a272f4fe62e | /alg/poj/archive/3100/5998603_CE.cpp | f78b7bf0eec820dcb6ba28feca2a3882914dfec3 | [] | no_license | ruleless/programming | aa32e916a5b3792ead2a6d48ab924d3554cd085f | c381d1ef7b1c7c0aff17603484e19a027593429b | refs/heads/master | 2022-11-14T02:07:47.443657 | 2022-11-03T23:47:32 | 2022-11-03T23:47:32 | 86,163,253 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 385 | cpp | #include<iostream>
#include<cmath>
using namespace std;
int main()
{
// freopen("in.txt","r",stdin);
int N,B,i,j,k;
while(scanf("%d%d",&B,&N)!=EOF&& !(B==0&&N==0) )
{
for(i=1;int (pow(i,N))<=B;i++);
if(int( pow(i,N) )==B)
k=i;
else
{
if(int( pow(i,N) )-B>B-int( pow(i-1,N) ) )
k=i-1;
else
k=i;
}
printf("%d\n",k);
}
return 0;
} | [
"[email protected]"
] | |
d96f44dd570c7816409122e2ea300960f41f9ced | 1cb93ce35651d1352587b50f9f3be94d6053d94a | /media/libstagefright/renderfright/gl/filters/BlurFilter.h | 593a8fd54ea4105859180d1d6bcf81f8379bd32c | [
"Apache-2.0",
"LicenseRef-scancode-unicode"
] | permissive | LineageOS/android_frameworks_av | 7a685135784cd7dfad88c524acb7044cab188db5 | be311717b151597a000cf3435812c56f915f2f4c | refs/heads/lineage-19.1 | 2023-07-25T06:37:24.324351 | 2023-05-11T00:26:30 | 2023-07-07T12:58:22 | 75,639,894 | 26 | 628 | NOASSERTION | 2022-10-02T20:13:57 | 2016-12-05T15:41:27 | C++ | UTF-8 | C++ | false | false | 2,953 | h | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <ui/GraphicTypes.h>
#include "../GLESRenderEngine.h"
#include "../GLFramebuffer.h"
#include "../GLVertexBuffer.h"
#include "GenericProgram.h"
using namespace std;
namespace android {
namespace renderengine {
namespace gl {
/**
* This is an implementation of a Kawase blur, as described in here:
* https://community.arm.com/cfs-file/__key/communityserver-blogs-components-weblogfiles/
* 00-00-00-20-66/siggraph2015_2D00_mmg_2D00_marius_2D00_notes.pdf
*/
class BlurFilter {
public:
// Downsample FBO to improve performance
static constexpr float kFboScale = 0.25f;
// Maximum number of render passes
static constexpr uint32_t kMaxPasses = 4;
// To avoid downscaling artifacts, we interpolate the blurred fbo with the full composited
// image, up to this radius.
static constexpr float kMaxCrossFadeRadius = 30.0f;
explicit BlurFilter(GLESRenderEngine& engine);
virtual ~BlurFilter(){};
// Set up render targets, redirecting output to offscreen texture.
status_t setAsDrawTarget(const DisplaySettings&, uint32_t radius);
// Execute blur passes, rendering to offscreen texture.
status_t prepare();
// Render blur to the bound framebuffer (screen).
status_t render(bool multiPass);
private:
uint32_t mRadius;
void drawMesh(GLuint uv, GLuint position);
string getVertexShader() const;
string getFragmentShader() const;
string getMixFragShader() const;
GLESRenderEngine& mEngine;
// Frame buffer holding the composited background.
GLFramebuffer mCompositionFbo;
// Frame buffers holding the blur passes.
GLFramebuffer mPingFbo;
GLFramebuffer mPongFbo;
uint32_t mDisplayWidth = 0;
uint32_t mDisplayHeight = 0;
uint32_t mDisplayX = 0;
uint32_t mDisplayY = 0;
// Buffer holding the final blur pass.
GLFramebuffer* mLastDrawTarget;
// VBO containing vertex and uv data of a fullscreen triangle.
GLVertexBuffer mMeshBuffer;
GenericProgram mMixProgram;
GLuint mMPosLoc;
GLuint mMUvLoc;
GLuint mMMixLoc;
GLuint mMTextureLoc;
GLuint mMCompositionTextureLoc;
GenericProgram mBlurProgram;
GLuint mBPosLoc;
GLuint mBUvLoc;
GLuint mBTextureLoc;
GLuint mBOffsetLoc;
};
} // namespace gl
} // namespace renderengine
} // namespace android
| [
"[email protected]"
] | |
c296baf12e67fcbabe1407a53c34bef735012d77 | 5b0449150ae2a959c4a26adc8ba8737f86ccba0c | /queen_threads/Queen.cpp | e6a6f8486ecb4c5b0290165026d2afa76eb2829d | [] | no_license | LF0614/cpp_hodgepodges | 74aa5ed1b9825abe749d8ae06467dcf64457403f | 97e0d0bf4d23737f0f8f196f9407317315c6662b | refs/heads/master | 2021-05-11T13:29:14.240338 | 2017-11-18T14:35:37 | 2017-11-18T14:35:47 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 741 | cpp | #include "Queen.h"
#include <iostream>
using namespace std;
int Queen::length;
Queen::Queen(int len,int* result)
:resultCnt(0),
resultRow(result)
{
length = len;
}
bool Queen::isEffective(int col,int row)
{
for(int i=0;i<col;i++)
{
//判断皇后是否行相同,或者对角线上。
if(resultRow[i]==row || abs(i-col)==abs(resultRow[i]-row))
return false;
}
return true;
}
void Queen::solve(int col)
{
if(col==length)
{
resultCnt++;
return;
}
for(int i=0;i<length;i++)
{
if(isEffective(col,i))
{
resultRow[col] = i;
solve(col+1);
}
}
}
int Queen::getResultCnt()
{
return resultCnt;
}
| [
"[email protected]"
] | |
2d4f3f5e6b0b63f07f419971234462b2d384ad02 | c0553ed15833c9cedd73b43359e6cc510087f826 | /tron2_knowledge/src/tron2/knowledge/Slang.h | 0c57369f70a58f39b9274fe3f4003af691ebd42a | [] | no_license | albarral/tron2 | d633050f7d3de4f565467af32bc71e5f544ac3ff | b131b3cff1298f370617ad8918d4f2e8a1a7b3ef | refs/heads/master | 2020-03-08T23:06:20.510938 | 2018-10-02T11:16:03 | 2018-10-02T11:16:03 | 128,452,459 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,219 | h | #ifndef __TRON2_KNOWLEDGE_SLANG_H
#define __TRON2_KNOWLEDGE_SLANG_H
/***************************************************************************
* Copyright (C) 2018 by Migtron Robotics *
* [email protected] *
***************************************************************************/
#include <map>
#include "tron2/knowledge/Concept.h"
namespace tron2
{
// A Slang is class used for distributing knowledge concepts and allow their faster interpretation.
// All concepts in a slang share a common property (ie. the initial letter) and are mapped by name.
class Slang
{
private:
char letter; // slang letter (initial letter of all concept names)
std::map<std::string, Concept> mapConcepts; // map <name, Concept>
public:
Slang(char letter);
~Slang();
char getLetter() {return letter;};
// gets slang size
int getSize() {return mapConcepts.size();};
// clears all slang concepts
void clear();
// adds given concept to slang (checking the letter restriction)
bool addConcept(Concept& oConcept);
// searches the slang for the given concept name
Concept* findConcept(std::string word);
std::string toString();
};
}
#endif
| [
"[email protected]"
] | |
dbb2de1e1004b3a779471378d7b2e58df3d01e6b | 5fbf8f4af22d5c94e6fd55eabb1c1ca124ad2110 | /net/TimerId.h | b114480b78f1edc641c240fd15f28344c3e1f894 | [] | no_license | L-admin/eznet | ad6b605e86ca9f35d094994878a3fcc6deaae0ac | fd99cc02e43fb81d72ea766a6e2ccfd0b5b99f5d | refs/heads/main | 2023-01-23T10:13:39.670458 | 2020-11-30T13:49:43 | 2020-11-30T13:49:43 | 311,340,069 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 490 | h | #pragma once
#include <stdint.h>
namespace net
{
class Timer;
class TimerId
{
public:
TimerId() : timer_(nullptr), sequence_(0)
{
}
TimerId(Timer *timer, int64_t seq) : timer_(timer),
sequence_(seq)
{
}
Timer *getTimer()
{
return timer_;
}
// default copy-ctor, dtor and assignment are okay
friend class TimerQueue;
private:
Timer *timer_;
int64_t sequence_;
};
} // namespace net
| [
"[email protected]"
] | |
08aac71e770e30f8076bd92b82c4df139c7908a9 | a524dcf80cb0058861958b39544b52aae5b557d3 | /earley-cc/AuthorizeProblem.h | 317ae4b02f03723349e76cf3670465a074f40c7e | [
"MIT"
] | permissive | attgm/earley-cc | 806cb4642376aba028e5921e5599910abec42a3c | 6ced522d60a12a6594f9bad54127a77d36b893e6 | refs/heads/master | 2023-04-01T09:40:05.021684 | 2023-03-31T13:06:41 | 2023-03-31T13:06:41 | 300,111,704 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,134 | h | // AuthorizeProblem.h
// 1999 - 2023 Atsushi Tagami
//
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
#pragma once
#ifndef AUTHORIZE_PROGLEM_H_
#define AUTHORIZE_PROGLEM_H_
#include <memory>
#include "Grammar.h"
#include "Quadruplet.h"
#include "Registration.h"
//-- AuthorizeQuad
// Quadruplet for authorize fcreate_new_elementproblem
class AuthorizeQuad : public Quadruplet {
public:
AuthorizeQuad(int rule_id, int dot_loc)
: Quadruplet(rule_id, dot_loc), prob_(0.0){};
void add(int /* rule_id */, double prob);
void merge(std::unique_ptr<AuthorizeQuad> const &quadruplet);
void multiply(std::unique_ptr<AuthorizeQuad> const &quadruplet);
double get_probability(void) const { return prob_; };
private:
double prob_;
};
//--
class AuthorizeRegistration : public Registration<AuthorizeQuad> {
public:
AuthorizeRegistration(std::shared_ptr<Grammar> grammar);
protected:
std::unique_ptr<AuthorizeQuad> create_quad(int rule_id, int dot_loc) {
return std::make_unique<AuthorizeQuad>(rule_id, dot_loc);
}
};
#endif // AUTHORIZE_PROGLEM_H_
| [
"[email protected]"
] | |
ff23c6cc3cc5613a4affc7b194583d3631ba91f8 | b0f84330d1c303543d549d54678c30143ecfc8ae | /old/MoneyTransfers.cpp | f52090edfe5650fdd1dc4aaf40d0bf8a4520f612 | [] | no_license | scottScottScott/WeAreTalkingAboutPractice | bfd871909886007ceefde258302a0785145fdfcc | 4afdf3f7299118c1c5294e15b26a4cc35976f39a | refs/heads/master | 2021-01-01T05:47:05.292273 | 2017-08-10T03:12:17 | 2017-08-10T03:12:17 | 33,291,806 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 389 | cpp | #include <iostream>
#include <vector>
#include <map>
using namespace std;
typedef long long ll;
int main() {
int n;
cin >> n;
vector<ll> banks(n);
for(int i = 0; i < n; i++)
scanf("%I64d", &banks[i]);
map<ll, int> M;
int result = 0;
for(int i = 0; i < n; i++) {
if(i != 0) banks[i] += banks[i - 1];
result = max(result, ++M[banks[i]]);
}
cout << n - result << endl;
}
| [
"[email protected]"
] | |
b0d19972d6e2d16e9a29e0bf91fa0879a63aab65 | ea8aa77c861afdbf2c9b3268ba1ae3f9bfd152fe | /stl_teach4.cpp | 224bd5bce965757a856f664b1898cf5ef56390c7 | [] | no_license | lonelam/SolveSet | 987a01e72d92f975703f715e6a7588d097f7f2e5 | 66a9a984d7270ff03b9c2dfa229d99b922907d57 | refs/heads/master | 2021-04-03T02:02:03.108669 | 2018-07-21T14:25:53 | 2018-07-21T14:25:53 | 62,948,874 | 9 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 388 | cpp | #include <deque>
#include <iostream>
using namespace std;
int main()
{
deque<int> Q(2, 1);
Q.push_back(4);
Q.push_front(-1);
for (auto i = Q.begin(); i != Q.end(); i++)
{
cout << *i <<",";
}
cout << endl;
Q.pop_back();
for (int x : Q)
{
cout << x << ",";
}
cout << endl;
Q.emplace_front(10);
cout << Q[1] << endl;
}
| [
"[email protected]"
] | |
b3a333ce48c3eb4e4fb62c8c55ea4330ec85ba95 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/collectd/gumtree/collectd_old_hunk_277.cpp | 9acf9ad6fcbd52471c5ac6f3d4f349d8cb16c915 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 249 | cpp | {
double tmp = atof (value);
if ((tmp < 0.0) || (tmp >= 1.0))
{
fprintf (stderr, "rrdtool: `XFF' must "
"be in the range 0 to 1 (exclusive).");
return (1);
}
xff = tmp;
}
else if (strcasecmp ("WritesPerSecond", key) == 0)
{
| [
"[email protected]"
] | |
9037ec0eb91275b359a8b49e773fda6e27b6b390 | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /services/service_manager/public/cpp/service_keepalive.h | 6a1488993d76ed8e3f53adb42819f2b0f89c37e7 | [
"BSD-3-Clause"
] | permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 4,347 | h | // Copyright 2018 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 SERVICES_SERVICE_MANAGER_PUBLIC_CPP_SERVICE_KEEPALIVE_H_
#define SERVICES_SERVICE_MANAGER_PUBLIC_CPP_SERVICE_KEEPALIVE_H_
#include "base/component_export.h"
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "base/observer_list.h"
#include "base/observer_list_types.h"
#include "base/optional.h"
#include "base/timer/timer.h"
namespace service_manager {
class ServiceBinding;
class ServiceKeepaliveRef;
// Service implementations are responsible for managing their own lifetime and
// as such are expected to call |ServiceBinding::RequestClose()| on their own
// ServiceBinding when they are no longer in use by any clients and otherwise
// have no reason to keep running (e.g. no active UI visible).
//
// ServiceKeepalive helps Service implementations accomplish this by vending
// instances of ServiceKeepaliveRef (see |CreateRef()| below). Once any
// ServiceKeepaliveRef has been created by a ServiceKeepalive, the
// ServiceKeepalive begins keeping track of the number of existing
// ServiceKeepaliveRefs.
//
// If the ServiceKeepalive's number of living ServiceKeepaliveRef instances goes
// to zero, the service is considered idle. If the ServiceKeepalive is
// configured with an idle timeout, it will automatically invoke
// |ServiceBinding::RequestClose()| on its associated ServiceBinding once the
// service has remained idle for that continuous duration.
//
// Services can use this mechanism to vend ServiceKeepaliveRefs to various parts
// of their implementation (e.g. to individual bound interface implementations)
// in order to safely and cleanly distribute their lifetime control.
class COMPONENT_EXPORT(SERVICE_MANAGER_CPP) ServiceKeepalive {
public:
class Observer : public base::CheckedObserver {
public:
~Observer() override {}
// Invoked whenever the ServiceKeepalive detects that the service has been
// idle for at least the idle time delta specified (if any) upon
// construction of the ServiceKeepalive.
virtual void OnIdleTimeout() {}
// Invoked whenever the ServiceKeepalive detects new activity again after
// having been idle for any amount of time.
virtual void OnIdleTimeoutCancelled() {}
};
// Constructs a ServiceKeepalive to control the lifetime behavior of
// |*binding|. Note that if either |binding| or |idle_timeout| is null, this
// object will not do any automatic lifetime management and will instead only
// maintain an internal ref-count which the consumer can query.
ServiceKeepalive(ServiceBinding* binding,
base::Optional<base::TimeDelta> idle_timeout);
~ServiceKeepalive();
// Constructs a new ServiceKeepaliveRef associated with this ServiceKeepalive.
// New refs may be created either by calling this method again or by calling
// |Clone()| on any another ServiceKeepaliveRef.
std::unique_ptr<ServiceKeepaliveRef> CreateRef();
// Returns |true| iff there are no existing ServiceKeepaliveRef instances
// associated with this ServiceKeepalive.
bool HasNoRefs();
void AddObserver(Observer* observer);
void RemoveObserver(Observer* observer);
private:
friend class ServiceKeepaliveRefImpl;
void AddRef();
void ReleaseRef();
void OnTimerExpired();
ServiceBinding* const binding_;
const base::Optional<base::TimeDelta> idle_timeout_;
base::Optional<base::OneShotTimer> idle_timer_;
base::ObserverList<Observer> observers_;
int ref_count_ = 0;
base::WeakPtrFactory<ServiceKeepalive> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(ServiceKeepalive);
};
// Objects which can be created by a |ServiceKeepalive| and cloned from each
// other. The ServiceBinding referenced by a ServiceKeepalive is considered
// active as long as one of these objects exists and is associated with that
// ServiceKeepalive.
class COMPONENT_EXPORT(SERVICE_MANAGER_CPP) ServiceKeepaliveRef {
public:
virtual ~ServiceKeepaliveRef() {}
// Creates a new ServiceKeepaliveRef associated with the same ServiceKeepalive
// as |this|.
virtual std::unique_ptr<ServiceKeepaliveRef> Clone() = 0;
};
} // namespace service_manager
#endif // SERVICES_SERVICE_MANAGER_PUBLIC_CPP_SERVICE_KEEPALIVE_H_
| [
"[email protected]"
] | |
45a332ca847c981db5b3c864356e98b5f87c9f58 | 6f867bcd07b064ea6998ac4e4f6f458620005c19 | /src/privatesend-client.h | 174be2220abf7f073ee9f8352b842eda39a7c58a | [
"MIT"
] | permissive | jesusleon1995/hustcoin | 8c23f86b85e57ef8f439a53703ec690f80b69c3f | f2e2a32440f70a2dcc9462ede3c80aab6433ca91 | refs/heads/master | 2020-03-15T21:16:23.061661 | 2018-05-06T15:58:18 | 2018-05-06T15:58:18 | 132,351,401 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,683 | h | // Copyright (c) 2014-2017 The HustCoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef PRIVATESENDCLIENT_H
#define PRIVATESENDCLIENT_H
#include "masternode.h"
#include "privatesend.h"
#include "wallet/wallet.h"
#include "privatesend-util.h"
class CPrivateSendClient;
class CConnman;
static const int DENOMS_COUNT_MAX = 100;
static const int DEFAULT_PRIVATESEND_ROUNDS = 2;
static const int DEFAULT_PRIVATESEND_AMOUNT = 1000;
static const int DEFAULT_PRIVATESEND_LIQUIDITY = 0;
static const bool DEFAULT_PRIVATESEND_MULTISESSION = false;
// Warn user if mixing in gui or try to create backup if mixing in daemon mode
// when we have only this many keys left
static const int PRIVATESEND_KEYS_THRESHOLD_WARNING = 100;
// Stop mixing completely, it's too dangerous to continue when we have only this many keys left
static const int PRIVATESEND_KEYS_THRESHOLD_STOP = 50;
// The main object for accessing mixing
extern CPrivateSendClient privateSendClient;
/** Used to keep track of current status of mixing pool
*/
class CPrivateSendClient : public CPrivateSendBase
{
private:
// Keep track of the used Masternodes
std::vector<COutPoint> vecMasternodesUsed;
std::vector<CAmount> vecDenominationsSkipped;
std::vector<COutPoint> vecOutPointLocked;
int nCachedLastSuccessBlock;
int nMinBlocksToWait; // how many blocks to wait after one successful mixing tx in non-multisession mode
// Keep track of current block height
int nCachedBlockHeight;
int nEntriesCount;
bool fLastEntryAccepted;
std::string strLastMessage;
std::string strAutoDenomResult;
masternode_info_t infoMixingMasternode;
CMutableTransaction txMyCollateral; // client side collateral
CKeyHolderStorage keyHolderStorage; // storage for keys used in PrepareDenominate
/// Check for process
void CheckPool();
void CompletedTransaction(PoolMessage nMessageID);
bool IsDenomSkipped(CAmount nDenomValue) {
return std::find(vecDenominationsSkipped.begin(), vecDenominationsSkipped.end(), nDenomValue) != vecDenominationsSkipped.end();
}
bool WaitForAnotherBlock();
// Make sure we have enough keys since last backup
bool CheckAutomaticBackup();
bool JoinExistingQueue(CAmount nBalanceNeedsAnonymized, CConnman& connman);
bool StartNewQueue(CAmount nValueMin, CAmount nBalanceNeedsAnonymized, CConnman& connman);
/// Create denominations
bool CreateDenominated(CConnman& connman);
bool CreateDenominated(const CompactTallyItem& tallyItem, bool fCreateMixingCollaterals, CConnman& connman);
/// Split up large inputs or make fee sized inputs
bool MakeCollateralAmounts(CConnman& connman);
bool MakeCollateralAmounts(const CompactTallyItem& tallyItem, bool fTryDenominated, CConnman& connman);
/// As a client, submit part of a future mixing transaction to a Masternode to start the process
bool SubmitDenominate(CConnman& connman);
/// step 1: prepare denominated inputs and outputs
bool PrepareDenominate(int nMinRounds, int nMaxRounds, std::string& strErrorRet, std::vector<CTxDSIn>& vecTxDSInRet, std::vector<CTxOut>& vecTxOutRet);
/// step 2: send denominated inputs and outputs prepared in step 1
bool SendDenominate(const std::vector<CTxDSIn>& vecTxDSIn, const std::vector<CTxOut>& vecTxOut, CConnman& connman);
/// Get Masternode updates about the progress of mixing
bool CheckPoolStateUpdate(PoolState nStateNew, int nEntriesCountNew, PoolStatusUpdate nStatusUpdate, PoolMessage nMessageID, int nSessionIDNew=0);
// Set the 'state' value, with some logging and capturing when the state changed
void SetState(PoolState nStateNew);
/// As a client, check and sign the final transaction
bool SignFinalTransaction(const CTransaction& finalTransactionNew, CNode* pnode, CConnman& connman);
void RelayIn(const CDarkSendEntry& entry, CConnman& connman);
void SetNull();
public:
int nPrivateSendRounds;
int nPrivateSendAmount;
int nLiquidityProvider;
bool fEnablePrivateSend;
bool fPrivateSendMultiSession;
int nCachedNumBlocks; //used for the overview screen
bool fCreateAutoBackups; //builtin support for automatic backups
CPrivateSendClient() :
nCachedLastSuccessBlock(0),
nMinBlocksToWait(1),
txMyCollateral(CMutableTransaction()),
nPrivateSendRounds(DEFAULT_PRIVATESEND_ROUNDS),
nPrivateSendAmount(DEFAULT_PRIVATESEND_AMOUNT),
nLiquidityProvider(DEFAULT_PRIVATESEND_LIQUIDITY),
fEnablePrivateSend(false),
fPrivateSendMultiSession(DEFAULT_PRIVATESEND_MULTISESSION),
nCachedNumBlocks(std::numeric_limits<int>::max()),
fCreateAutoBackups(true) { SetNull(); }
void ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv, CConnman& connman);
void ClearSkippedDenominations() { vecDenominationsSkipped.clear(); }
void SetMinBlocksToWait(int nMinBlocksToWaitIn) { nMinBlocksToWait = nMinBlocksToWaitIn; }
void ResetPool();
void UnlockCoins();
std::string GetStatus();
bool GetMixingMasternodeInfo(masternode_info_t& mnInfoRet);
bool IsMixingMasternode(const CNode* pnode);
/// Passively run mixing in the background according to the configuration in settings
bool DoAutomaticDenominating(CConnman& connman, bool fDryRun=false);
void CheckTimeout();
void UpdatedBlockTip(const CBlockIndex *pindex);
};
void ThreadCheckPrivateSendClient(CConnman& connman);
#endif
| [
"[email protected]"
] | |
7c34517d154e3c082d53bfcf7cd127dec2779a4b | ea8d40ce4bdef093bb99fce3f7d6d2700491b69b | /Logger.cpp | 65068007a42c73fc6dd17701c7f34020772fc8e7 | [] | no_license | gaolj/RpcServer | 9c5645690c73754843e96438d4c6b7bc07cf650f | cff94bd180625c8394cae7bef17fe0bff49c7384 | refs/heads/master | 2021-01-10T11:13:00.177144 | 2016-04-18T06:48:26 | 2016-04-18T06:48:26 | 50,810,807 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,757 | cpp | #include "Logger.h"
#include <fstream>
#include <boost/log/common.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/attributes.hpp>
#include <boost/log/sinks.hpp>
#include <boost/log/support/date_time.hpp>
#include <boost/log/support/exception.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/console.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/utility/setup/from_stream.hpp> // init_from_stream
#include <boost/log/utility/setup/filter_parser.hpp> // register_simple_filter_factory
BOOST_LOG_ATTRIBUTE_KEYWORD(_severity, "Severity", SeverityLevel)
BOOST_LOG_ATTRIBUTE_KEYWORD(_timestamp, "TimeStamp", boost::posix_time::ptime)
BOOST_LOG_ATTRIBUTE_KEYWORD(_uptime, "Uptime", attrs::timer::value_type)
BOOST_LOG_ATTRIBUTE_KEYWORD(_scope, "Scope", attrs::named_scope::value_type)
BOOST_LOG_ATTRIBUTE_KEYWORD(_remoteAddress, "RemoteAddress", std::string)
BOOST_LOG_ATTRIBUTE_KEYWORD(_errorCode, "ErrorCode", int32_t)
logging::formatting_ostream& operator <<
(
logging::formatting_ostream& strm,
logging::to_log_manip< SeverityLevel, tag::_severity > const& manip
)
{
static const char* strings[] =
{
"TRACE",
"DEBUG",
"NTFY ",
"INFO ",
"WARN ",
"ERROR",
"FATAL"
};
SeverityLevel level = manip.get();
if (static_cast< std::size_t >(level) < sizeof(strings) / sizeof(*strings))
strm << strings[level];
else
strm << static_cast< int >(level);
return strm;
}
void initLogger()
{
#ifdef _DEBUG
auto mode = std::ios::trunc;
#else
auto mode = std::ios::app;
#endif
//logging::register_simple_formatter_factory<SeverityLevel, char>("Severity");
//logging::register_simple_filter_factory<SeverityLevel, char>("Severity");
//std::ifstream settings("log.ini");
//if (!settings.is_open())
// std::cout << "Could not open log.ini file" << std::endl;
//else
// logging::init_from_stream(settings);
logging::add_file_log(
keywords::file_name = "log/Server1_%3N.log",
keywords::open_mode = mode,
keywords::auto_flush = true,
keywords::rotation_size = 10 * 1024 * 1024,
keywords::time_based_rotation = sinks::file::rotation_at_time_point(0, 0, 0),
//keywords::filter = _severity == trace,
keywords::format = expr::stream
<< expr::format_date_time(_timestamp, "%Y-%m-%d %H:%M:%S.%f")
<< " " << expr::attr< attrs::current_thread_id::value_type >("ThreadID")
<< " " << _severity
<< " " << expr::message
<< " " << expr::format_named_scope(_scope, keywords::format = "%c", keywords::iteration = expr::reverse, keywords::depth = 3));
logging::add_file_log(
keywords::file_name = "log/Server2_%3N.log",
keywords::open_mode = mode,
keywords::auto_flush = true,
keywords::rotation_size = 10 * 1024 * 1024,
keywords::time_based_rotation = sinks::file::rotation_at_time_point(0, 0, 0),
keywords::filter = _severity.or_default(debug) >= debug,
keywords::format = expr::stream
<< expr::format_date_time(_timestamp, "%Y-%m-%d %H:%M:%S.%f")
<< " " << expr::attr< attrs::current_thread_id::value_type >("ThreadID")
<< " " << _severity
<< expr::if_(expr::has_attr(_remoteAddress))
[
expr::stream << " " << _remoteAddress
]
<< expr::if_(expr::has_attr(_uptime))
[
expr::stream << " " << _uptime
]
<< " " << expr::message
<< expr::if_(expr::has_attr(_errorCode))
[
expr::stream << " (" << _errorCode << ")"
]
<< expr::if_(_severity >= notify)
[
expr::stream << " " << expr::format_named_scope(_scope, keywords::format = "[%c@%F:%l]", keywords::iteration = expr::reverse, keywords::depth = 3)
]);
logging::add_common_attributes();
logging::core::get()->add_global_attribute("Scope", attrs::named_scope());
logging::core::get()->set_filter(_severity >= debug);
} | [
"[email protected]"
] | |
220f5b254d9ff9c3177f5007fe3406f5ea5b80bf | 0dc683feaa3b34b30159c34528e08e45815a6b2d | /FourDeltaOne.SourceCode/T5M/deps/include/cpprest/interopstream.h | 9b9c7f116f29918f07fa57bab6bcf3fb04331615 | [] | no_license | wanfl/nta_sources | 6c119e6610abb7387fd00e42dc174a4d5e3e7911 | c6d6e9d8966af266bdd840c0c274a245b7119f23 | refs/heads/master | 2020-06-21T18:20:10.791089 | 2017-09-13T17:51:20 | 2017-09-13T17:51:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,470 | h | /***
* ==++==
*
* Copyright (c) Microsoft Corporation. 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.
*
* ==--==
* =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
*
* interopstream.h
*
* Adapter classes for async and STD stream buffers, used to connect std-based and async-based APIs.
*
* For the latest on this and related APIs, please see http://casablanca.codeplex.com.
*
* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
****/
#pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1800)
#include <ppltasks.h>
namespace pplx = Concurrency;
#else
#include "pplx/pplxtasks.h"
#endif
#include "cpprest/astreambuf.h"
#include "cpprest/streams.h"
#ifdef _MS_WINDOWS
#include <safeint.h>
#endif
#ifndef _CONCRT_H
#ifndef _LWRCASE_CNCRRNCY
#define _LWRCASE_CNCRRNCY
// Note to reader: we're using lower-case namespace names everywhere, but the 'Concurrency' namespace
// is capitalized for historical reasons. The alias let's us pretend that style issue doesn't exist.
namespace Concurrency { }
namespace concurrency = Concurrency;
#endif
#endif
#pragma warning(push)
// Suppress unreferenced formal parameter warning as they are required for documentation
#pragma warning(disable : 4100)
// Inherited via dominance. Disabling is necessary for iostream, and exactly what STL does.
#pragma warning(disable: 4250)
namespace Concurrency { namespace streams {
template<typename CharType> class stdio_ostream;
template<typename CharType> class stdio_istream;
#pragma region Asynchronous streams on top of synchronous stream buffers.
namespace details {
/// <summary>
/// The basic_stdio_buffer class serves to support interoperability with STL stream buffers.
/// Sitting atop a std::streambuf, which does all the I/O, instances of this class may read
/// and write data to standard iostreams. The class itself should not be used in application
/// code, it is used by the stream definitions farther down in the header file.
/// </summary>
template<typename _CharType>
class basic_stdio_buffer : public streambuf_state_manager<_CharType>
{
typedef std::char_traits<_CharType> traits;
typedef typename traits::int_type int_type;
typedef typename traits::pos_type pos_type;
typedef typename traits::off_type off_type;
/// <summary>
/// Private constructor
/// </summary>
basic_stdio_buffer(_In_ std::basic_streambuf<_CharType>* streambuf, std::ios_base::openmode mode)
: m_buffer(streambuf), streambuf_state_manager<_CharType>(mode)
{
}
public:
/// <summary>
/// Destructor
/// </summary>
virtual ~basic_stdio_buffer()
{
if( this->can_read() || this->can_write() ) {
this->close().wait();
}
}
private:
//
// The functions overridden below here are documented elsewhere.
// See astreambuf.h for further information.
//
virtual bool can_seek() const { return this->is_open(); }
virtual bool has_size() const { return false; }
virtual size_t in_avail() const { return (size_t)m_buffer->in_avail(); }
virtual size_t buffer_size(std::ios_base::openmode direction = std::ios_base::in) const { return 0; }
virtual void set_buffer_size(size_t size, std::ios_base::openmode direction = std::ios_base::in) { return; }
virtual pplx::task<bool> _sync() { return pplx::task_from_result(m_buffer->pubsync() != std::char_traits<_CharType>::eof()); }
virtual pplx::task<int_type> _putc(_CharType ch) { return pplx::task_from_result(m_buffer->sputc(ch)); }
virtual pplx::task<size_t> _putn(const _CharType *ptr, size_t size) { return pplx::task_from_result((size_t)m_buffer->sputn(ptr, size)); }
size_t _sgetn(_Out_writes_ (size) _CharType *ptr, _In_ size_t size) const { return m_buffer->sgetn(ptr, size); }
virtual size_t _scopy(_Out_writes_ (size) _CharType *, _In_ size_t size) { (size); return (size_t)-1; }
virtual pplx::task<size_t> _getn(_Out_writes_ (size) _CharType *ptr, _In_ size_t size) { return pplx::task_from_result((size_t)m_buffer->sgetn(ptr, size)); }
virtual int_type _sbumpc() { return m_buffer->sbumpc(); }
virtual int_type _sgetc() { return m_buffer->sgetc(); }
virtual pplx::task<int_type> _bumpc() { return pplx::task_from_result<int_type>(m_buffer->sbumpc()); }
virtual pplx::task<int_type> _getc() { return pplx::task_from_result<int_type>(m_buffer->sgetc()); }
virtual pplx::task<int_type> _nextc() { return pplx::task_from_result<int_type>(m_buffer->snextc()); }
virtual pplx::task<int_type> _ungetc() { return pplx::task_from_result<int_type>(m_buffer->sungetc()); }
virtual pos_type getpos(std::ios_base::openmode mode) const { return m_buffer->pubseekoff(0, std::ios_base::cur, mode); }
virtual pos_type seekpos(pos_type pos, std::ios_base::openmode mode) { return m_buffer->pubseekpos(pos, mode); }
virtual pos_type seekoff(off_type off, std::ios_base::seekdir dir, std::ios_base::openmode mode) { return m_buffer->pubseekoff(off, dir, mode); }
virtual _CharType* _alloc(size_t count) { return nullptr; }
virtual void _commit(size_t count) {}
virtual bool acquire(_Out_writes_ (count) _CharType*& ptr, _In_ size_t& count) { return false; }
virtual void release(_Out_writes_ (count) _CharType *ptr, _In_ size_t count) { }
template<typename CharType> friend class concurrency::streams::stdio_ostream;
template<typename CharType> friend class concurrency::streams::stdio_istream;
std::basic_streambuf<_CharType>* m_buffer;
};
} // namespace details
/// <summary>
/// stdio_ostream represents an async ostream derived from a standard synchronous stream, as
/// defined by the "std" namespace. It is constructed from a reference to a standard stream, which
/// must be valid for the lifetime of the asynchronous stream.
/// </summary>
/// <typeparam name="CharType">
/// The data type of the basic element of the <c>stdio_ostream</c>.
/// </typeparam>
/// <remarks>
/// Since std streams are not reference-counted, great care must be taken by an application to make
/// sure that the std stream does not get destroyed until all uses of the asynchronous stream are
/// done and have been serviced.
/// </remarks>
template<typename CharType>
class stdio_ostream : public basic_ostream<CharType>
{
public:
/// <summary>
/// Constructor
/// </summary>
/// <typeparam name="AlterCharType">
/// The data type of the basic element of the source output stream.
/// </typeparam>
/// <param name="stream">The synchronous stream that this is using for its I/O</param>
template <typename AlterCharType>
stdio_ostream(std::basic_ostream<AlterCharType>& stream)
: basic_ostream<CharType>(streams::streambuf<AlterCharType>(std::shared_ptr<details::basic_stdio_buffer<AlterCharType>>(new details::basic_stdio_buffer<AlterCharType>(stream.rdbuf(), std::ios_base::out))))
{
}
/// <summary>
/// Copy constructor
/// </summary>
/// <param name="other">The source object</param>
stdio_ostream(const stdio_ostream &other) : basic_ostream<CharType>(other) { }
/// <summary>
/// Assignment operator
/// </summary>
/// <param name="other">The source object</param>
/// <returns>A reference to the output stream object that contains the result of the assignment.</returns>
stdio_ostream & operator =(const stdio_ostream &other) { basic_ostream<CharType>::operator=(other); return *this; }
};
/// <summary>
/// stdio_istream represents an async istream derived from a standard synchronous stream, as
/// defined by the "std" namespace. It is constructed from a reference to a standard stream, which
/// must be valid for the lifetime of the asynchronous stream.
/// </summary>
/// <typeparam name="CharType">
/// The data type of the basic element of the <c>stdio_istream</c>.
/// </typeparam>
/// <remarks>
/// Since std streams are not reference-counted, great care must be taken by an application to make
/// sure that the std stream does not get destroyed until all uses of the asynchronous stream are
/// done and have been serviced.
/// </remarks>
template<typename CharType>
class stdio_istream : public basic_istream<CharType>
{
public:
/// <summary>
/// Constructor
/// </summary>
/// <typeparam name="AlterCharType">
/// The data type of the basic element of the source <c>istream</c>
/// </typeparam>
/// <param name="stream">The synchronous stream that this is using for its I/O</param>
template <typename AlterCharType>
stdio_istream(std::basic_istream<AlterCharType>& stream)
: basic_istream<CharType>(streams::streambuf<AlterCharType>(std::shared_ptr<details::basic_stdio_buffer<AlterCharType>>(new details::basic_stdio_buffer<AlterCharType>(stream.rdbuf(), std::ios_base::in))))
{
}
/// <summary>
/// Copy constructor
/// </summary>
/// <param name="other">The source object</param>
stdio_istream(const stdio_istream &other) : basic_istream<CharType>(other) { }
/// <summary>
/// Assignment operator
/// </summary>
/// <param name="other">The source object</param>
/// <returns>A reference to the input stream object that contains the result of the assignment.</returns>
stdio_istream & operator =(const stdio_istream &other) { basic_istream<CharType>::operator=(other); return *this; }
};
#pragma endregion
#pragma region Synchronous streams on top of asynchronous stream buffers.
namespace details {
/// <summary>
/// IO streams stream buffer implementation used to interface with an async streambuffer underneath.
/// Used for implementing the standard synchronous streams that provide interop between std:: and concurrency::streams::
/// </summary>
template<typename CharType>
class basic_async_streambuf : public std::basic_streambuf<CharType>
{
public:
typedef std::char_traits<CharType> traits;
typedef typename traits::int_type int_type;
typedef typename traits::pos_type pos_type;
typedef typename traits::off_type off_type;
basic_async_streambuf(streams::streambuf<CharType> async_buf) : m_buffer(async_buf)
{
}
protected:
//
// The following are the functions in std::basic_streambuf that we need to override.
//
/// <summary>
/// Writes one byte to the stream buffer.
/// </summary>
int_type overflow(int_type ch)
{
try
{
return m_buffer.putc(CharType(ch)).get();
}
catch(...)
{
return traits::eof();
}
}
/// <summary>
/// Gets one byte from the stream buffer without moving the read position.
/// </summary>
int_type underflow()
{
try
{
return m_buffer.getc().get();
}
catch(...)
{
return traits::eof();
}
}
/// <summary>
/// Gets one byte from the stream buffer and move the read position one character.
/// </summary>
int_type uflow()
{
try
{
return m_buffer.bumpc().get();
}
catch(...)
{
return traits::eof();
}
}
/// <summary>
/// Gets a number of characters from the buffer and place it into the provided memory block.
/// </summary>
std::streamsize xsgetn(_Out_writes_ (count) CharType* ptr, _In_ std::streamsize count)
{
size_t cnt = size_t(count);
size_t read_so_far = 0;
try
{
while (read_so_far < cnt)
{
size_t rd = m_buffer.getn(ptr+read_so_far, cnt-read_so_far).get();
read_so_far += rd;
if ( rd == 0 )
break;
}
return read_so_far;
}
catch(...)
{
return 0;
}
}
/// <summary>
/// Writes a given number of characters from the provided block into the stream buffer.
/// </summary>
std::streamsize xsputn(const CharType* ptr, std::streamsize count)
{
try
{
return m_buffer.putn(ptr, (size_t)count).get();
}
catch(...)
{
return 0;
}
}
/// <summary>
/// Synchronizes with the underlying medium.
/// </summary>
int sync() // must be int as per std::basic_streambuf
{
try
{
m_buffer.sync().wait();
}
catch(...)
{
}
return 0;
}
/// <summary>
/// Seeks to the given offset relative to the beginning, end, or current position.
/// </summary>
pos_type seekoff(off_type offset,
std::ios_base::seekdir dir,
std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out)
{
try
{
if ( dir == std::ios_base::cur && offset == 0) // Special case for getting the current position.
return m_buffer.getpos(mode);
return m_buffer.seekoff(offset,dir,mode);
}
catch(...)
{
return (pos_type(-1));
}
}
/// <summary>
/// Seeks to the given offset relative to the beginning of the stream.
/// </summary>
pos_type seekpos(pos_type pos,
std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out)
{
try
{
return m_buffer.seekpos(pos, mode);
}
catch(...)
{
return (pos_type(-1));
}
}
private:
concurrency::streams::streambuf<CharType> m_buffer;
};
} // namespace details
/// <summary>
/// A concrete STL ostream which relies on an asynchronous stream for its I/O.
/// </summary>
/// <typeparam name="CharType">
/// The data type of the basic element of the stream.
/// </typeparam>
template<typename CharType>
class async_ostream : public std::basic_ostream<CharType>
{
public:
/// <summary>
/// Constructor
/// </summary>
/// <typeparam name="AlterCharType">
/// The data type of the basic element of the source ostream.
/// </typeparam>
/// <param name="astream">The asynchronous stream whose stream buffer should be used for I/O</param>
template <typename AlterCharType>
async_ostream(streams::basic_ostream<AlterCharType> astream)
: std::basic_ostream<CharType>(&m_strbuf),
m_strbuf(astream.streambuf())
{
}
/// <summary>
/// Constructor
/// </summary>
/// <typeparam name="AlterCharType">
/// The data type of the basic element of the source <c>streambuf</c>.
/// </typeparam>
/// <param name="strbuf">The asynchronous stream buffer to use for I/O</param>
template <typename AlterCharType>
async_ostream(streams::streambuf<AlterCharType> strbuf)
: std::basic_ostream<CharType>(&m_strbuf),
m_strbuf(strbuf)
{
}
private:
details::basic_async_streambuf<CharType> m_strbuf;
};
/// <summary>
/// A concrete STL istream which relies on an asynchronous stream for its I/O.
/// </summary>
/// <typeparam name="CharType">
/// The data type of the basic element of the stream.
/// </typeparam>
template<typename CharType>
class async_istream : public std::basic_istream<CharType>
{
public:
/// <summary>
/// Constructor
/// </summary>
/// <typeparam name="AlterCharType">
/// The data type of the basic element of the source istream.
/// </typeparam>
/// <param name="astream">The asynchronous stream whose stream buffer should be used for I/O</param>
template <typename AlterCharType>
async_istream(streams::basic_istream<AlterCharType> astream)
: std::basic_istream<CharType>(&m_strbuf),
m_strbuf(astream.streambuf())
{
}
/// <summary>
/// Constructor
/// </summary>
/// <typeparam name="AlterCharType">
/// The data type of the basic element of the source <c>streambuf</c>.
/// </typeparam>
/// <param name="strbuf">The asynchronous stream buffer to use for I/O</param>
template <typename AlterCharType>
async_istream(streams::streambuf<AlterCharType> strbuf)
: std::basic_istream<CharType>(&m_strbuf),
m_strbuf(strbuf)
{
}
private:
details::basic_async_streambuf<CharType> m_strbuf;
};
/// <summary>
/// A concrete STL istream which relies on an asynchronous stream buffer for its I/O.
/// </summary>
/// <typeparam name="CharType">
/// The data type of the basic element of the stream.
/// </typeparam>
template<typename CharType>
class async_iostream : public std::basic_iostream<CharType>
{
public:
/// <summary>
/// Constructor
/// </summary>
/// <param name="strbuf">The asynchronous stream buffer to use for I/O</param>
async_iostream(streams::streambuf<CharType> strbuf)
: std::basic_iostream<CharType>(&m_strbuf),
m_strbuf(strbuf)
{
}
private:
details::basic_async_streambuf<CharType> m_strbuf;
};
#pragma endregion
#if defined(__cplusplus_winrt)
#pragma region WinRT streams interop
/// <summary>
/// Static class containing factory functions for WinRT streams implemented on top of Casablanca async streams.
/// </summary>
/// <remarks>WinRT streams are defined in terms of single-byte characters only.</remarks>
class winrt_stream
{
public:
/// <summary>
/// Creates a WinRT <c>IInputStream</c> reference from an asynchronous stream buffer.
/// </summary>
/// <param name="buffer">A stream buffer based on a single-byte character.</param>
/// <returns>A reference to a WinRT <c>IInputStream</c>.</returns>
/// <remarks>
/// The stream buffer passed in must allow reading.
/// The stream buffer is shared with the caller, allowing data to be passed between the two contexts. For
/// example, using a <c>producer_consumer_buffer</c>, a Casablanca-based caller can pass data to a WinRT component.
/// </remarks>
_ASYNCRTIMP static Windows::Storage::Streams::IInputStream^ create_input_stream(concurrency::streams::streambuf<uint8_t> buffer);
/// <summary>
/// Creates a WinRT <c>IOutputStream</c> reference from an asynchronous stream buffer.
/// </summary>
/// <param name="buffer">A stream buffer based on a single-byte character.</param>
/// <returns>A reference to a WinRT <c>IOutputStream</c>.</returns>
/// <remarks>
/// The stream buffer passed in must allow writing.
/// The stream buffer is shared with the caller, allowing data to be passed between the two contexts. For
/// example, using a <c>producer_consumer_buffer</c>, a Casablanca-based caller can retrieve data from a WinRT component.
/// </remarks>
_ASYNCRTIMP static Windows::Storage::Streams::IOutputStream^ create_output_stream(concurrency::streams::streambuf<uint8_t> buffer);
/// <summary>
/// Creates a WinRT <c>IRandomAccessStream reference from an asynchronous input stream.
/// </summary>
/// <param name="buffer">A stream based on a single-byte character.</param>
/// <returns>A reference to a WinRT <c>IRandomAccessStream</c>.</returns>
/// <remarks>
/// The stream buffer is shared with the caller, allowing data to be passed between the two contexts. For
/// example, using a <c>producer_consumer_buffer</c>, a Casablanca-based caller can pass data to and retrieve data
/// from a WinRT component.
/// </remarks>
_ASYNCRTIMP static Windows::Storage::Streams::IRandomAccessStream^ create_random_access_stream(concurrency::streams::streambuf<uint8_t> buffer);
};
#endif
#pragma endregion
}} // namespaces
#pragma warning(pop) // 4100
| [
"[email protected]"
] | |
f7ad9019f23a7cdb08146fa4c666e16c44f0336f | 711e5c8b643dd2a93fbcbada982d7ad489fb0169 | /XPSP1/NT/enduser/netmeeting/ui/msconf/clcnflnk.cpp | dcc1140584e80dea27752e92b86a32b3122949c0 | [] | no_license | aurantst/windows-XP-SP1 | 629a7763c082fd04d3b881e0d32a1cfbd523b5ce | d521b6360fcff4294ae6c5651c539f1b9a6cbb49 | refs/heads/master | 2023-03-21T01:08:39.870106 | 2020-09-28T08:10:11 | 2020-09-28T08:10:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,900 | cpp | // File: conflnk.cpp
#include "precomp.h"
#include <shellapi.h>
#include <shlstock.h>
#include <ConfDir.h>
#include <ConfCli.h>
#include "clCnfLnk.hpp"
#include "resource.h"
#include "atlbase.h"
#include "confevt.h"
#include "sdkInternal.h"
#include "nameres.h"
/////////////////////////////////////////////////////////////////////
// Initialize GUIDs
//
#pragma data_seg(".text")
#define INITGUID
#include <initguid.h>
#include "CLinkId.h"
// from shlguid.h - must keep in sync
DEFINE_SHLGUID(CLSID_ShellLink, 0x00021401L, 0, 0);
#ifndef _UNICODE
DEFINE_SHLGUID(IID_IShellLink, 0x000214EEL, 0, 0);
DEFINE_SHLGUID(IID_IShellExtInit, 0x000214E8L, 0, 0);
DEFINE_SHLGUID(IID_IShellPropSheetExt, 0x000214E9L, 0, 0);
#endif // _UNICODE
#undef INITGUID
#pragma data_seg()
/////////////////////////////////////////////////////////////////////
#ifdef DEBUG
BOOL IsValidPCConfLink(PCCConfLink pcConfLink)
{
return(
IS_VALID_READ_PTR(pcConfLink, CConfLink) &&
FLAGS_ARE_VALID(pcConfLink->m_dwFlags, ALL_CONFLNK_FLAGS) &&
(! pcConfLink->m_pszFile ||
IS_VALID_STRING_PTR(pcConfLink->m_pszFile, STR)) &&
(! pcConfLink->m_pszName ||
IS_VALID_STRING_PTR(pcConfLink->m_pszName, STR)) &&
IS_VALID_STRUCT_PTR((PCRefCount)pcConfLink, CRefCount) &&
IS_VALID_INTERFACE_PTR((PCIDataObject)pcConfLink, IDataObject) &&
IS_VALID_INTERFACE_PTR((PCIPersistFile)pcConfLink, IPersistFile) &&
IS_VALID_INTERFACE_PTR((PCIPersistStream)pcConfLink, IPersistStream) &&
IS_VALID_INTERFACE_PTR((PCIShellExtInit)pcConfLink, IShellExtInit) &&
IS_VALID_INTERFACE_PTR((PCIShellPropSheetExt)pcConfLink, IShellPropSheetExt) &&
IS_VALID_INTERFACE_PTR((PCIConferenceLink)pcConfLink, IConferenceLink));
}
#endif /* DEBUG */
CConfLink::CConfLink(OBJECTDESTROYEDPROC ObjectDestroyed) :
RefCount (ObjectDestroyed),
m_dwFlags (0),
m_dwCallFlags (0),
m_dwTransport (0),
m_pszFile (NULL),
m_pszName (NULL),
m_pszRemoteConfName (NULL),
m_pszAddress (NULL)
{
DebugEntry(CConfLink::CConfLink);
// Don't validate this until after construction.
ASSERT( !ObjectDestroyed ||
IS_VALID_CODE_PTR(ObjectDestroyed, OBJECTDESTROYEDPROC));
ASSERT(IS_VALID_STRUCT_PTR(this, CConfLink));
DebugExitVOID(CConfLink::CConfLink);
return;
}
CConfLink::~CConfLink(void)
{
DebugEntry(CConfLink::~CConfLink);
ASSERT(IS_VALID_STRUCT_PTR(this, CConfLink));
delete m_pszFile;
m_pszFile = NULL;
delete m_pszName;
m_pszName = NULL;
delete m_pszAddress;
m_pszAddress = NULL;
delete m_pszRemoteConfName;
m_pszRemoteConfName = NULL;
ASSERT(IS_VALID_STRUCT_PTR(this, CConfLink));
DebugExitVOID(CConfLink::~CConfLink);
return;
}
HRESULT STDMETHODCALLTYPE CConfLink::SetAddress(PCSTR pcszAddress)
{
HRESULT hr;
PSTR pszNewAddress = NULL;
DebugEntry(CConfLink::SetAddress);
ASSERT(IS_VALID_STRUCT_PTR(this, CConfLink));
ASSERT( !pcszAddress ||
IS_VALID_STRING_PTR(pcszAddress, CSTR));
pszNewAddress = new char[lstrlen(pcszAddress) + 1];
if (NULL != pszNewAddress)
{
lstrcpy(pszNewAddress, pcszAddress);
hr = S_OK;
}
else
{
hr = E_OUTOFMEMORY;
}
if (S_OK == hr)
{
if (NULL != m_pszAddress)
{
delete m_pszAddress;
}
m_pszAddress = pszNewAddress;
Dirty(TRUE);
TRACE_OUT(("CConfLink::SetAddress(): Set Address to %s.",
CHECK_STRING(m_pszAddress)));
}
ASSERT(IS_VALID_STRUCT_PTR(this, CConfLink));
ASSERT( hr == S_OK ||
hr == E_OUTOFMEMORY);
DebugExitHRESULT(CConfLink::SetAddress, hr);
return(hr);
}
HRESULT STDMETHODCALLTYPE CConfLink::GetAddress(PSTR *ppszAddress)
{
HRESULT hr;
DebugEntry(CConfLink::GetAddress);
ASSERT(IS_VALID_STRUCT_PTR(this, CConfLink));
ASSERT(IS_VALID_WRITE_PTR(ppszAddress, PSTR));
*ppszAddress = NULL;
if (NULL != m_pszAddress)
{
*ppszAddress = NULL;
LPMALLOC pMalloc;
if (SUCCEEDED(SHGetMalloc(&pMalloc)))
{
// (+ 1) for null terminator.
*ppszAddress = (PSTR) pMalloc->Alloc(lstrlen(m_pszAddress) + 1);
pMalloc->Release();
pMalloc = NULL;
}
if (NULL != *ppszAddress)
{
lstrcpy(*ppszAddress, m_pszAddress);
hr = S_OK;
TRACE_OUT(("CConfLink::GetAddress(): Got Address %s.", *ppszAddress));
}
else
{
hr = E_OUTOFMEMORY;
}
}
else
{
// No Name.
hr = S_FALSE;
}
ASSERT(IS_VALID_STRUCT_PTR(this, CConfLink));
ASSERT( (hr == S_OK &&
IS_VALID_STRING_PTR(*ppszAddress, STR)) ||
(( hr == S_FALSE ||
hr == E_OUTOFMEMORY) &&
! *ppszAddress));
DebugExitHRESULT(CConfLink::GetAddress, hr);
return(hr);
}
HRESULT STDMETHODCALLTYPE CConfLink::SetRemoteConfName(PCSTR pcszRemoteConfName)
{
HRESULT hr;
DebugEntry(CConfLink::SetRemoteConfName);
ASSERT(IS_VALID_STRUCT_PTR(this, CConfLink));
ASSERT( !pcszRemoteConfName ||
IS_VALID_STRING_PTR(pcszRemoteConfName, CSTR));
PSTR pszNewRemoteConfName = new char[lstrlen(pcszRemoteConfName) + 1];
if (NULL != pszNewRemoteConfName)
{
lstrcpy(pszNewRemoteConfName, pcszRemoteConfName);
hr = S_OK;
}
else
{
hr = E_OUTOFMEMORY;
}
if (S_OK == hr)
{
if (NULL != m_pszRemoteConfName)
{
delete m_pszRemoteConfName;
}
m_pszRemoteConfName = pszNewRemoteConfName;
Dirty(TRUE);
TRACE_OUT(("CConfLink::SetRemoteConfName(): Set RemoteConfName to %s.",
CHECK_STRING(m_pszRemoteConfName)));
}
ASSERT(IS_VALID_STRUCT_PTR(this, CConfLink));
ASSERT( hr == S_OK ||
hr == E_OUTOFMEMORY);
DebugExitHRESULT(CConfLink::SetRemoteConfName, hr);
return(hr);
}
HRESULT STDMETHODCALLTYPE CConfLink::GetRemoteConfName(PSTR *ppszRemoteConfName)
{
HRESULT hr;
DebugEntry(CConfLink::GetRemoteConfName);
ASSERT(IS_VALID_STRUCT_PTR(this, CConfLink));
ASSERT(IS_VALID_WRITE_PTR(ppszRemoteConfName, PSTR));
*ppszRemoteConfName = NULL;
if (NULL != m_pszRemoteConfName)
{
*ppszRemoteConfName = NULL;
LPMALLOC pMalloc;
if (SUCCEEDED(SHGetMalloc(&pMalloc)))
{
// (+ 1) for null terminator.
*ppszRemoteConfName = (PSTR) pMalloc->Alloc(lstrlen(m_pszRemoteConfName) + 1);
pMalloc->Release();
pMalloc = NULL;
}
if (NULL != *ppszRemoteConfName)
{
lstrcpy(*ppszRemoteConfName, m_pszRemoteConfName);
hr = S_OK;
TRACE_OUT(("CConfLink::GetRemoteConfName(): Got RemoteConfName %s.",
*ppszRemoteConfName));
}
else
{
hr = E_OUTOFMEMORY;
}
}
else
{
// No Name.
hr = S_FALSE;
}
ASSERT(IS_VALID_STRUCT_PTR(this, CConfLink));
ASSERT( (hr == S_OK &&
IS_VALID_STRING_PTR(*ppszRemoteConfName, STR)) ||
(( hr == S_FALSE ||
hr == E_OUTOFMEMORY) &&
! *ppszRemoteConfName));
DebugExitHRESULT(CConfLink::GetRemoteConfName, hr);
return(hr);
}
HRESULT STDMETHODCALLTYPE CConfLink::SetName(PCSTR pcszName)
{
HRESULT hr;
BOOL bChanged;
PSTR pszNewName = NULL;
DebugEntry(CConfLink::SetName);
ASSERT(IS_VALID_STRUCT_PTR(this, CConfLink));
ASSERT( !pcszName ||
IS_VALID_STRING_PTR(pcszName, CSTR));
bChanged = ! ((! pcszName && ! m_pszName) ||
(pcszName && m_pszName &&
! lstrcmp(pcszName, m_pszName)));
if (bChanged && pcszName)
{
pszNewName = new(char[lstrlen(pcszName) + 1]);
if (pszNewName)
{
lstrcpy(pszNewName, pcszName);
hr = S_OK;
}
else
{
hr = E_OUTOFMEMORY;
}
}
else
{
hr = S_OK;
}
if (hr == S_OK)
{
if (bChanged)
{
if (m_pszName)
{
delete m_pszName;
}
m_pszName = pszNewName;
Dirty(TRUE);
TRACE_OUT(("CConfLink::SetName(): Set Name to %s.",
CHECK_STRING(m_pszName)));
}
else
{
TRACE_OUT(("CConfLink::SetName(): Name already %s.",
CHECK_STRING(m_pszName)));
}
}
ASSERT(IS_VALID_STRUCT_PTR(this, CConfLink));
ASSERT( hr == S_OK ||
hr == E_OUTOFMEMORY);
DebugExitHRESULT(CConfLink::SetName, hr);
return(hr);
}
HRESULT STDMETHODCALLTYPE CConfLink::GetName(PSTR *ppszName)
{
HRESULT hr;
DebugEntry(CConfLink::GetName);
ASSERT(IS_VALID_STRUCT_PTR(this, CConfLink));
ASSERT(IS_VALID_WRITE_PTR(ppszName, PSTR));
*ppszName = NULL;
if (m_pszName)
{
*ppszName = NULL;
LPMALLOC pMalloc;
if (SUCCEEDED(SHGetMalloc(&pMalloc)))
{
// (+ 1) for null terminator.
*ppszName = (PSTR) pMalloc->Alloc(lstrlen(m_pszName) + 1);
pMalloc->Release();
pMalloc = NULL;
}
// ChrisPi: I changed this to use the above implementation because
// SHAlloc is not available in the sdk shell32.lib
// *ppszName = (PSTR)SHAlloc(lstrlen(m_pszURL) + 1);
if (*ppszName)
{
lstrcpy(*ppszName, m_pszName);
hr = S_OK;
TRACE_OUT(("CConfLink::GetName(): Got Name %s.", *ppszName));
}
else
{
hr = E_OUTOFMEMORY;
}
}
else
{
// No Name.
hr = S_FALSE;
}
ASSERT(IS_VALID_STRUCT_PTR(this, CConfLink));
ASSERT( (hr == S_OK &&
IS_VALID_STRING_PTR(*ppszName, STR)) ||
(( hr == S_FALSE ||
hr == E_OUTOFMEMORY) &&
! *ppszName));
DebugExitHRESULT(CConfLink::GetName, hr);
return(hr);
}
HRESULT STDMETHODCALLTYPE CConfLink::SetTransport(DWORD dwTransport)
{
HRESULT hr;
DebugEntry(CConfLink::SetTransport);
ASSERT(IS_VALID_STRUCT_PTR(this, CConfLink));
m_dwTransport = dwTransport;
Dirty(TRUE);
TRACE_OUT(("CConfLink::SetTransport(): Set Transport to %#8x.",
m_dwTransport));
hr = S_OK;
ASSERT(IS_VALID_STRUCT_PTR(this, CConfLink));
DebugExitHRESULT(CConfLink::SetTransport, hr);
return(hr);
}
HRESULT STDMETHODCALLTYPE CConfLink::GetTransport(DWORD *pdwTransport)
{
HRESULT hr;
DebugEntry(CConfLink::GetTransport);
ASSERT(IS_VALID_STRUCT_PTR(this, CConfLink));
ASSERT(IS_VALID_WRITE_PTR(pdwTransport, PDWORD));
*pdwTransport = m_dwTransport;
hr = S_OK;
TRACE_OUT(("CConfLink::GetTransport(): Got Transport %#8x.",
*pdwTransport));
ASSERT(IS_VALID_STRUCT_PTR(this, CConfLink));
DebugExitHRESULT(CConfLink::GetTransport, hr);
return(hr);
}
HRESULT STDMETHODCALLTYPE CConfLink::SetCallFlags(DWORD dwCallFlags)
{
HRESULT hr;
DebugEntry(CConfLink::SetCallFlags);
ASSERT(IS_VALID_STRUCT_PTR(this, CConfLink));
m_dwCallFlags = dwCallFlags;
Dirty(TRUE);
TRACE_OUT(("CConfLink::SetCallFlags(): Set CallFlags to %#8x.",
m_dwCallFlags));
hr = S_OK;
ASSERT(IS_VALID_STRUCT_PTR(this, CConfLink));
DebugExitHRESULT(CConfLink::SetCallFlags, hr);
return(hr);
}
HRESULT STDMETHODCALLTYPE CConfLink::GetCallFlags(DWORD *pdwCallFlags)
{
HRESULT hr;
DebugEntry(CConfLink::GetCallFlags);
ASSERT(IS_VALID_STRUCT_PTR(this, CConfLink));
ASSERT(IS_VALID_WRITE_PTR(pdwCallFlags, PDWORD));
*pdwCallFlags = m_dwCallFlags;
hr = S_OK;
TRACE_OUT(("CConfLink::GetCallFlags(): Got CallFlags %#8x.",
*pdwCallFlags));
ASSERT(IS_VALID_STRUCT_PTR(this, CConfLink));
DebugExitHRESULT(CConfLink::GetCallFlags, hr);
return(hr);
}
#define STR_CALLTO _T("callto:")
#define STR_CONFERENCE _T("+conference=")
#define STR_GATEWAY _T("+gateway=")
#define STR_SECURE _T("+secure=true")
#define STR_PHONE _T("+type=phone")
#define STR_NO_AV _T("+av=false")
#define STR_NO_DATA _T("+data=false")
//--------------------------------------------------------------------------//
// CConfLink::InvokeCommand. //
//--------------------------------------------------------------------------//
HRESULT
STDMETHODCALLTYPE
CConfLink::InvokeCommand
(
PCLINVOKECOMMANDINFO pclici
){
DebugEntry( CConfLink::InvokeCommand );
ASSERT( IS_VALID_STRUCT_PTR( this, CConfLink ) );
ASSERT( IS_VALID_STRUCT_PTR( pclici, CCLINVOKECOMMANDINFO ) );
HRESULT result = E_INVALIDARG;
if(m_pszAddress)
{
if( m_dwTransport == NAMETYPE_CALLTO )
{
result = shellCallto( m_pszAddress, IS_FLAG_SET( pclici->dwFlags, ICL_INVOKECOMMAND_FL_ALLOW_UI ) );
}
else
{
long lMax = lstrlen(STR_CALLTO) +
lstrlen(STR_CONFERENCE) +
lstrlen(STR_GATEWAY) +
lstrlen(STR_PHONE) +
lstrlen(STR_SECURE) +
lstrlen(STR_NO_AV) +
lstrlen(STR_NO_DATA) +
lstrlen(m_pszAddress) +
(m_pszRemoteConfName ? lstrlen(m_pszRemoteConfName) : 0) +
1;
LPTSTR url = (TCHAR*) _alloca(lMax);
lstrcpy( url, STR_CALLTO );
if( m_dwTransport != NAMETYPE_H323GTWY )
{
lstrcat( url, m_pszAddress );
}
else
{
TCHAR * const pSlash = (TCHAR * const) _StrChr( m_pszAddress, '/' );
if( pSlash != NULL )
{
*pSlash = '\0';
lstrcat( url, pSlash + 1 );
lstrcat( url, STR_GATEWAY );
}
lstrcat( url, m_pszAddress );
lstrcat( url, STR_PHONE );
}
if( m_pszRemoteConfName != NULL )
{
lstrcat( url, STR_CONFERENCE );
lstrcat( url, m_pszRemoteConfName );
}
if( IS_FLAG_SET( m_dwCallFlags, CRPCF_SECURE ) )
{
lstrcat( url, STR_SECURE );
}
if( IS_FLAG_CLEAR( m_dwCallFlags, (CRPCF_AUDIO | CRPCF_VIDEO) ) )
{
lstrcat( url, STR_NO_AV );
}
if( IS_FLAG_CLEAR( m_dwCallFlags, CRPCF_DATA) )
{
lstrcat( url, STR_NO_DATA );
}
result = shellCallto( url, IS_FLAG_SET( pclici->dwFlags, ICL_INVOKECOMMAND_FL_ALLOW_UI ) );
}
ASSERT( IS_VALID_STRUCT_PTR( this, CConfLink ) );
DebugExitHRESULT( CConfLink::InvokeCommand, result );
}
return( result );
} // End of CConfLink::InvokeCommand.
//--------------------------------------------------------------------------//
// shellCallto. //
//--------------------------------------------------------------------------//
HRESULT
shellCallto
(
const TCHAR * const url,
const bool notifyOnError
){
ASSERT( url != NULL );
ASSERT( url[ 0 ] != '\0' );
TRACE_OUT( ("shellCallto: url:\"%s\"", url) );
HRESULT result;
if( url == NULL )
{
result = E_POINTER;
}
else if( url[ 0 ] == '\0' )
{
result = E_INVALIDARG;
}
else
{
result = ::CoInitializeEx( NULL, COINIT_APARTMENTTHREADED );
if( SUCCEEDED( result ) )
{
IInternalConfExe * internalConf;
HRESULT result;
result = CoCreateInstance( CLSID_NmManager, NULL, CLSCTX_ALL, IID_IInternalConfExe, (LPVOID *) &internalConf );
if( SUCCEEDED( result ) && (internalConf != NULL) )
{
result = internalConf->ShellCalltoProtocolHandler( CComBSTR( url ), FALSE );
internalConf->Release();
}
::CoUninitialize();
}
if( FAILED( result ) && notifyOnError )
{
TCHAR message[ MAX_PATH ];
TCHAR title[ MAX_PATH ];
::LoadString( g_hInst, // handle to module containing string resource
IDS_COULD_NOT_CALL, // resource identifier
message, // pointer to buffer for resource
ARRAY_ELEMENTS( message ) ); // size of buffer
::LoadString( g_hInst, // handle to module containing string resource
IDS_LAUNCH_ERROR, // resource identifier
title, // pointer to buffer for resource
ARRAY_ELEMENTS( title ) ); // size of buffer
::MessageBox( NULL, message, title, MB_ICONERROR | MB_OK );
}
}
return( result );
} // End of shellCallto.
ULONG STDMETHODCALLTYPE CConfLink::AddRef(void)
{
ULONG ulcRef;
DebugEntry(CConfLink::AddRef);
ASSERT(IS_VALID_STRUCT_PTR(this, CConfLink));
ulcRef = RefCount::AddRef();
ASSERT(IS_VALID_STRUCT_PTR(this, CConfLink));
DebugExitULONG(CConfLink::AddRef, ulcRef);
return(ulcRef);
}
ULONG STDMETHODCALLTYPE CConfLink::Release(void)
{
ULONG ulcRef;
DebugEntry(CConfLink::Release);
ASSERT(IS_VALID_STRUCT_PTR(this, CConfLink));
ulcRef = RefCount::Release();
DebugExitULONG(CConfLink::Release, ulcRef);
return(ulcRef);
}
HRESULT STDMETHODCALLTYPE CConfLink::QueryInterface(REFIID riid,
PVOID *ppvObject)
{
HRESULT hr = S_OK;
DebugEntry(CConfLink::QueryInterface);
ASSERT(IS_VALID_STRUCT_PTR(this, CConfLink));
ASSERT(IsValidREFIID(riid));
ASSERT(IS_VALID_WRITE_PTR(ppvObject, PVOID));
if (riid == IID_IDataObject)
{
*ppvObject = (PIDataObject)this;
TRACE_OUT(("CConfLink::QueryInterface(): Returning IDataObject."));
}
#if 0 // These are currently unsupported interfaces:
else if (riid == IID_IExtractIcon)
{
*ppvObject = NULL;
hr = E_NOINTERFACE;
// *ppvObject = (PIExtractIcon)this;
TRACE_OUT(("CConfLink::QueryInterface(): NOT Returning IExtractIcon!"));
}
else if (riid == IID_INewShortcutHook)
{
*ppvObject = NULL;
hr = E_NOINTERFACE;
// *ppvObject = (PINewShortcutHook)this;
TRACE_OUT(("CConfLink::QueryInterface(): NOT Returning INewShortcutHook!"));
}
else if (riid == IID_IShellExecuteHook)
{
*ppvObject = NULL;
hr = E_NOINTERFACE;
// *ppvObject = (PIShellExecuteHook)this;
TRACE_OUT(("CConfLink::QueryInterface(): NOT Returning IShellExecuteHook!"));
}
else if (riid == IID_IShellLink)
{
*ppvObject = NULL;
hr = E_NOINTERFACE;
// *ppvObject = (PIShellLink)this;
TRACE_OUT(("CConfLink::QueryInterface(): NOT Returning IShellLink!"));
}
#endif /* DEBUG */
// Supported interfaces:
else if (riid == IID_IShellExtInit)
{
*ppvObject = (PIShellExtInit)this;
TRACE_OUT(("CConfLink::QueryInterface(): Returning IShellExtInit."));
}
else if (riid == IID_IShellPropSheetExt)
{
*ppvObject = (PIShellPropSheetExt)this;
TRACE_OUT(("CConfLink::QueryInterface(): Returning IShellPropSheetExt."));
}
else if (riid == IID_IPersist)
{
*ppvObject = (PIPersist)(PIPersistStream)this;
TRACE_OUT(("CConfLink::QueryInterface(): Returning IPersist."));
}
else if (riid == IID_IPersistFile)
{
*ppvObject = (PIPersistFile)this;
TRACE_OUT(("CConfLink::QueryInterface(): Returning IPersistFile."));
}
else if (riid == IID_IPersistStream)
{
*ppvObject = (PIPersistStream)this;
TRACE_OUT(("CConfLink::QueryInterface(): Returning IPersistStream."));
}
else if (riid == IID_IConferenceLink)
{
*ppvObject = (PIConferenceLink)this;
TRACE_OUT(("CConfLink::QueryInterface(): Returning IConferenceLink."));
}
else if (riid == IID_IUnknown)
{
*ppvObject = (PIUnknown) (PIConferenceLink) this;
TRACE_OUT(("CConfLink::QueryInterface(): Returning IUnknown."));
}
else
{
TRACE_OUT(("CConfLink::QueryInterface(): Called on unknown interface."));
*ppvObject = NULL;
hr = E_NOINTERFACE;
}
if (hr == S_OK)
{
AddRef();
}
ASSERT(IS_VALID_STRUCT_PTR(this, CConfLink));
DebugExitHRESULT(CConfLink::QueryInterface, hr);
return(hr);
}
/* O P E N C O N F L I N K */
/*-------------------------------------------------------------------------
%%Function: OpenConfLink
-------------------------------------------------------------------------*/
void WINAPI OpenConfLink(HWND hwndParent, HINSTANCE hinst,
PSTR pszCmdLine, int nShowCmd)
{
HRESULT hr;
CConfLink conflink(NULL);
// int nResult;
DebugEntry(OpenConfLink);
ASSERT(IS_VALID_HANDLE(hwndParent, WND));
ASSERT(IS_VALID_HANDLE(hinst, INSTANCE));
ASSERT(IS_VALID_STRING_PTR(pszCmdLine, STR));
ASSERT(IsValidShowCmd(nShowCmd));
// Assume the entire command line is a Conference Link file path.
// TrimWhiteSpace(pszCmdLine);
TRACE_OUT(("OpenConfLink(): Trying to open Conference Link %s.",
pszCmdLine));
#if 0
TCHAR szBuf[256];
wsprintf(szBuf, "Launching conference link %s", pszCmdLine);
::MessageBox( NULL,
szBuf,
"Conference Link Extension",
MB_ICONINFORMATION);
#endif
hr = conflink.LoadFromFile(pszCmdLine, TRUE);
if (hr == S_OK)
{
CLINVOKECOMMANDINFO clici;
clici.dwcbSize = sizeof(clici);
clici.hwndParent = hwndParent;
clici.pcszVerb = NULL;
clici.dwFlags = ( ICL_INVOKECOMMAND_FL_ALLOW_UI |
ICL_INVOKECOMMAND_FL_USE_DEFAULT_VERB);
hr = conflink.InvokeCommand(&clici);
}
else
{
// BUGBUG: need resource here INTL
::MessageBox( hwndParent,
_TEXT("There was an error while identifying the conference"),
_TEXT("Conference Shortcut Error"),
MB_ICONINFORMATION);
// if (MyMsgBox(hwndParent, MAKEINTRESOURCE(IDS_SHORTCUT_ERROR_TITLE),
// MAKEINTRESOURCE(IDS_LOADFROMFILE_FAILED),
// (MB_OK | MB_ICONEXCLAMATION), &nResult, pszCmdLine))
//
// ASSERT(nResult == IDOK);
}
DebugExitVOID(OpenConfLink);
return;
}
/* A N Y M E A T */
/*-------------------------------------------------------------------------
%%Function: AnyMeat
Return TRUE if the string has any non-whitespace characters
-------------------------------------------------------------------------*/
BOOL AnyMeat(PCSTR pcsz)
{
TCHAR ch;
ASSERT((!pcsz) || IS_VALID_STRING_PTR(pcsz, CSTR));
if (NULL == pcsz)
return FALSE;
while (0 != (ch = *pcsz++))
{
switch (ch)
{
case _T(' '): // Space
case _T('\t'): // Tab
case 0x00A0: // Non-breaking space
break;
default:
return TRUE; // found a non-whitespace character
}
}
return FALSE;
}
HRESULT MyReleaseStgMedium(PSTGMEDIUM pstgmed)
{
HRESULT hr;
ASSERT(IS_VALID_STRUCT_PTR(pstgmed, CSTGMEDIUM));
if (pstgmed->pUnkForRelease)
hr = pstgmed->pUnkForRelease->Release();
else
{
switch(pstgmed->tymed)
{
case TYMED_HGLOBAL:
hr = (! GlobalFree(pstgmed->hGlobal)) ? S_OK : E_HANDLE;
break;
#if 0 /* Only TYMED_HGLOBAL is ever used */
case TYMED_ISTREAM:
hr = pstgmed->pstm->Release();
break;
case TYMED_ISTORAGE:
hr = pstgmed->pstm->Release();
break;
case TYMED_FILE:
{
PIMalloc pMalloc = NULL;
if (SUCCEEDED(SHGetMalloc(&pMalloc)))
{
pMalloc->Free(pstgmed->lpszFileName);
pMalloc->Release();
pMalloc = NULL;
pstgmed->lpszFileName = NULL;
}
hr = S_OK;
break;
}
case TYMED_GDI:
hr = (DeleteObject(pstgmed->hBitmap)) ? S_OK : E_HANDLE;
break;
case TYMED_MFPICT:
hr = (DeleteMetaFile((HMETAFILE)(pstgmed->hMetaFilePict)) &&
! GlobalFree(pstgmed->hMetaFilePict)) ? S_OK : E_HANDLE;
break;
case TYMED_ENHMF:
hr = (DeleteEnhMetaFile(pstgmed->hEnhMetaFile)) ? S_OK : E_HANDLE;
break;
#endif // 0
default:
ASSERT(pstgmed->tymed == TYMED_NULL);
hr = S_OK;
break;
}
}
return(hr);
}
| [
"[email protected]"
] | |
9b54cfacb82c8f78b3c43fda14f9a738472110c1 | b7f3edb5b7c62174bed808079c3b21fb9ea51d52 | /chromeos/crosapi/cpp/window_snapshot.cc | 947ed426de06afb1f8a797518752b878bc579c1b | [
"BSD-3-Clause"
] | permissive | otcshare/chromium-src | 26a7372773b53b236784c51677c566dc0ad839e4 | 64bee65c921db7e78e25d08f1e98da2668b57be5 | refs/heads/webml | 2023-03-21T03:20:15.377034 | 2020-11-16T01:40:14 | 2020-11-16T01:40:14 | 209,262,645 | 18 | 21 | BSD-3-Clause | 2023-03-23T06:20:07 | 2019-09-18T08:52:07 | null | UTF-8 | C++ | false | false | 352 | cc | // Copyright 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 "chromeos/crosapi/cpp/window_snapshot.h"
namespace crosapi {
WindowSnapshot::WindowSnapshot() = default;
WindowSnapshot::~WindowSnapshot() = default;
} // namespace crosapi
| [
"[email protected]"
] | |
7b5b926c6d7ecb8e6ccbcab5ddf85424d0eb998e | 04fb36f9e8a440b5bf0ff2c4efedbdd4b41dedce | /eIDApplicationManageProject/eIDApplicationManageGUI/eIDApplicationManageGUI.cpp | b6c2d7afdfddd11c0f3df7edcc878898822b6ac3 | [] | no_license | JackBro/eIDApplicationManageProject | e20f575b39561ee822ffcac0fe142cead615e66b | e4de5356983042de4c3c88f6ceec2ae6ebb627b5 | refs/heads/master | 2020-06-14T01:51:52.038486 | 2014-11-03T02:10:13 | 2014-11-03T02:10:13 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 459 | cpp | // eIDApplicationManageGUI.cpp: 主项目文件。
#include "stdafx.h"
#include "MainForm.h"
using namespace eIDApplicationManageGUI;
[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
// 在创建任何控件之前启用 Windows XP 可视化效果
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
// 创建主窗口并运行它
Application::Run(gcnew MainForm());
return 0;
}
| [
"[email protected]"
] | |
18ec32cb074e197b4d9595b27e36f8bb5c9f6e2e | aa2c3e56f6712c7806796433ddfa6a1ee2b55b2d | /lib/SILGen/ResultPlan.h | e2f0cb5a4eb11b5088eb46b2b63e387417920a30 | [
"Apache-2.0",
"Swift-exception"
] | permissive | CocoPPaPlay/swift | 92dddbe5c8b1217722ef2c8ab2abd6732c076429 | 6e3698f7e8ac6884753dafa218f837a41c468af1 | refs/heads/master | 2020-11-29T15:25:50.725771 | 2017-03-28T19:10:29 | 2017-03-28T19:10:29 | 87,479,584 | 1 | 0 | null | 2017-04-06T22:10:07 | 2017-04-06T22:10:06 | null | UTF-8 | C++ | false | false | 3,025 | h | //===--- ResultPlan.h -----------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#ifndef SWIFT_SILGEN_RESULTPLAN_H
#define SWIFT_SILGEN_RESULTPLAN_H
#include "Callee.h"
#include "ManagedValue.h"
#include "swift/AST/Types.h"
#include "swift/Basic/LLVM.h"
#include "swift/SIL/SILLocation.h"
#include <memory>
namespace swift {
class CanType;
class SILValue;
namespace Lowering {
class AbstractionPattern;
class Initialization;
class RValue;
class SILGenFunction;
class SGFContext;
class CalleeTypeInfo;
/// An abstract class for working with results.of applies.
class ResultPlan {
public:
virtual RValue finish(SILGenFunction &SGF, SILLocation loc, CanType substType,
ArrayRef<ManagedValue> &directResults) = 0;
virtual ~ResultPlan() = default;
virtual void
gatherIndirectResultAddrs(SmallVectorImpl<SILValue> &outList) const = 0;
virtual Optional<std::pair<ManagedValue, ManagedValue>>
emitForeignErrorArgument(SILGenFunction &SGF, SILLocation loc) {
return None;
}
};
using ResultPlanPtr = std::unique_ptr<ResultPlan>;
/// The class for building result plans.
struct ResultPlanBuilder {
SILGenFunction &SGF;
SILLocation loc;
const CalleeTypeInfo &calleeTypeInfo;
/// A list of all of the results that we are tracking in reverse order. The
/// reason that it is in reverse order is to allow us to simply traverse the
/// list by popping values off the back.
SmallVector<SILResultInfo, 8> allResults;
ResultPlanBuilder(SILGenFunction &SGF, SILLocation loc,
const CalleeTypeInfo &calleeTypeInfo)
: SGF(SGF), loc(loc), calleeTypeInfo(calleeTypeInfo),
// We reverse the order so we can pop values off the back.
allResults(reversed(calleeTypeInfo.substFnType->getResults())) {}
ResultPlanPtr build(Initialization *emitInto, AbstractionPattern origType,
CanType substType);
ResultPlanPtr buildForTuple(Initialization *emitInto,
AbstractionPattern origType,
CanTupleType substType);
static ResultPlanPtr computeResultPlan(SILGenFunction &SGF,
const CalleeTypeInfo &calleeTypeInfo,
SILLocation loc,
SGFContext evalContext);
~ResultPlanBuilder() {
assert(allResults.empty() && "didn't consume all results!");
}
private:
ResultPlanPtr buildTopLevelResult(Initialization *init, SILLocation loc);
};
} // end namespace Lowering
} // end namespace swift
#endif
| [
"[email protected]"
] | |
bc431b9a595ea34cf30c8b5a63e51b1ed165574b | 93cc3e0471ee2404d7715257ec6d76916b9041ae | /chrome/browser/content_settings/mixed_content_settings_tab_helper_browsertest.cc | 6a8bd44db7b34a4cbbae20d5b65ee730d4d5fb07 | [
"BSD-3-Clause"
] | permissive | alfeyo/chromium | 578330bbaf6c723be07a522d0d56a51e54c41358 | 3443d881f81decceb423a69759ca53538f019cb4 | refs/heads/master | 2023-06-25T16:41:38.018547 | 2021-08-12T07:27:21 | 2021-08-12T07:27:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,104 | 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 "chrome/browser/content_settings/mixed_content_settings_tab_helper.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_content_setting_bubble_model_delegate.h"
#include "chrome/browser/ui/content_settings/content_setting_bubble_model.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "components/network_session_configurator/common/network_switches.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/prerender_test_util.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_utils.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "url/gurl.h"
class MixedContentSettingsTabHelperBrowserTest : public InProcessBrowserTest {
public:
MixedContentSettingsTabHelperBrowserTest()
: prerender_helper_(base::BindRepeating(
&MixedContentSettingsTabHelperBrowserTest::web_contents,
base::Unretained(this))) {}
~MixedContentSettingsTabHelperBrowserTest() override = default;
void SetUp() override {
prerender_helper_.SetUp(&ssl_server_);
InProcessBrowserTest::SetUp();
}
void SetUpOnMainThread() override {
host_resolver()->AddRule("*", "127.0.0.1");
ssl_server_.AddDefaultHandlers(GetChromeTestDataDir());
ssl_server_.SetSSLConfig(net::EmbeddedTestServer::CERT_OK);
ASSERT_TRUE(ssl_server_.Start());
}
protected:
void SetUpCommandLine(base::CommandLine* command_line) override {
// For using an HTTPS server.
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kIgnoreCertificateErrors);
}
content::test::PrerenderTestHelper* prerender_helper() {
return &prerender_helper_;
}
content::WebContents* web_contents() {
return browser()->tab_strip_model()->GetActiveWebContents();
}
content::RenderFrameHost* current_frame_host() {
return web_contents()->GetMainFrame();
}
net::EmbeddedTestServer* test_server() { return &ssl_server_; }
private:
content::test::PrerenderTestHelper prerender_helper_;
net::EmbeddedTestServer ssl_server_{net::EmbeddedTestServer::TYPE_HTTPS};
};
// Tests that the prerending doesn't affect the mixed content's insecure status
// in the primary page.
IN_PROC_BROWSER_TEST_F(MixedContentSettingsTabHelperBrowserTest,
KeepInsecureInPrerendering) {
GURL primary_url(
test_server()->GetURL("/content_setting_bubble/mixed_script.html"));
auto* helper = MixedContentSettingsTabHelper::FromWebContents(web_contents());
// Loads a primary page that has mixed content.
EXPECT_TRUE(content::NavigateToURL(web_contents(), primary_url));
// Mixed content should be blocked at first.
EXPECT_FALSE(helper->IsRunningInsecureContentAllowed(*current_frame_host()));
// Emulates link clicking on the mixed script bubble to allow mixed content
// to run.
content::TestNavigationObserver observer(
browser()->tab_strip_model()->GetActiveWebContents());
std::unique_ptr<ContentSettingBubbleModel> model(
ContentSettingBubbleModel::CreateContentSettingBubbleModel(
browser()->content_setting_bubble_model_delegate(),
browser()->tab_strip_model()->GetActiveWebContents(),
ContentSettingsType::MIXEDSCRIPT));
model->OnCustomLinkClicked();
// Waits for reload.
observer.Wait();
// Mixed content should no longer be blocked.
EXPECT_TRUE(helper->IsRunningInsecureContentAllowed(*current_frame_host()));
// Loads a page in the prerendering.
GURL prerender_url(test_server()->GetURL(
"/content_setting_bubble/mixed_script.html?prerendering"));
const int host_id = prerender_helper()->AddPrerender(prerender_url);
content::RenderFrameHost* prerender_rfh =
prerender_helper()->GetPrerenderedMainFrameHost(host_id);
// Mixed content should be blocked in the prerendering page.
EXPECT_FALSE(helper->IsRunningInsecureContentAllowed(*prerender_rfh));
// Mixed content should keep to be unblocked in the primary page.
EXPECT_TRUE(helper->IsRunningInsecureContentAllowed(*current_frame_host()));
// Activates the page from the prerendering.
prerender_helper()->NavigatePrimaryPage(prerender_url);
// Mixed content should be blocked in the new page.
EXPECT_FALSE(helper->IsRunningInsecureContentAllowed(*current_frame_host()));
}
// Tests that the prerending doesn't affect the mixed content's insecure status
// with the main frame.
IN_PROC_BROWSER_TEST_F(MixedContentSettingsTabHelperBrowserTest,
DoNotAffectInsecureOfPrimaryPageInPrerendering) {
GURL primary_url(
test_server()->GetURL("/content_setting_bubble/mixed_script.html"));
auto* helper = MixedContentSettingsTabHelper::FromWebContents(web_contents());
// Loads a primary page that has mixed content.
EXPECT_TRUE(content::NavigateToURL(web_contents(), primary_url));
// Mixed content should be blocked in the page.
EXPECT_FALSE(helper->IsRunningInsecureContentAllowed(*current_frame_host()));
// Loads a page in the prerendering.
GURL prerender_url(
test_server()->GetURL("/content_setting_bubble/mixed_script.html"));
const int host_id = prerender_helper()->AddPrerender(prerender_url);
content::RenderFrameHost* prerender_rfh =
prerender_helper()->GetPrerenderedMainFrameHost(host_id);
// Mixed content should be blocked in the prerendering page.
EXPECT_FALSE(helper->IsRunningInsecureContentAllowed(*prerender_rfh));
helper->AllowRunningOfInsecureContent(*prerender_rfh);
// Mixed content should be unblocked in the prerendering page.
EXPECT_TRUE(helper->IsRunningInsecureContentAllowed(*prerender_rfh));
// Mixed content should keep to be blocked in the primary page.
EXPECT_FALSE(helper->IsRunningInsecureContentAllowed(*current_frame_host()));
// Activates the page from the prerendering.
prerender_helper()->NavigatePrimaryPage(prerender_url);
// Mixed content should keep to be unblocked in the new page.
EXPECT_TRUE(helper->IsRunningInsecureContentAllowed(*current_frame_host()));
}
// Tests that the activated page keeps the mixed content's secure status
// after the prerending page is activated.
IN_PROC_BROWSER_TEST_F(MixedContentSettingsTabHelperBrowserTest,
DoNotAffectSecureOfPrerenderingPage) {
GURL primary_url(
test_server()->GetURL("/content_setting_bubble/mixed_script.html"));
auto* helper = MixedContentSettingsTabHelper::FromWebContents(web_contents());
// Loads a primary page that has mixed content.
EXPECT_TRUE(content::NavigateToURL(web_contents(), primary_url));
// Mixed content should be blocked in the activated page.
EXPECT_FALSE(helper->IsRunningInsecureContentAllowed(*current_frame_host()));
// Loads a page in the prerendering.
GURL prerender_url(
test_server()->GetURL("/content_setting_bubble/mixed_script.html"));
int host_id = prerender_helper()->AddPrerender(prerender_url);
content::RenderFrameHost* prerender_rfh =
prerender_helper()->GetPrerenderedMainFrameHost(host_id);
// Mixed content should be blocked in the prerendering page.
EXPECT_FALSE(helper->IsRunningInsecureContentAllowed(*prerender_rfh));
helper->AllowRunningOfInsecureContent(*current_frame_host());
// Mixed content should be unblocked in the activated page.
EXPECT_TRUE(helper->IsRunningInsecureContentAllowed(*current_frame_host()));
// Mixed content should keep to be blocked in the prerendering page.
EXPECT_FALSE(helper->IsRunningInsecureContentAllowed(*prerender_rfh));
// Activates the page from the prerendering.
prerender_helper()->NavigatePrimaryPage(prerender_url);
// Mixed content should keep to be blocked in the activated page.
EXPECT_FALSE(helper->IsRunningInsecureContentAllowed(*current_frame_host()));
}
| [
"[email protected]"
] | |
93b4a87669fa16eb063f27daa3138dd172b14bdb | f3b9721f67c6cb305d1ac7f84adac8671a37a8db | /threewaycomminucation.cpp | 5d7d6561f9aae9594205523f5c161008eaa48ccb | [] | no_license | Shivamnema/Coding | 741138fb6e4588afe0ca26e79f3a70c55d114407 | 688b7a4f6d475dfa9c0adc81a28f81f0087b74a8 | refs/heads/master | 2021-06-06T10:03:36.730318 | 2016-09-11T19:37:06 | 2016-09-11T19:37:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 209 | cpp | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(void) {
int T;
cin>> T;
while (T >= 0)
{
cout<< "hello";
T--;
}
return 0;
} | [
"[email protected]"
] | |
eb370dc2f63de67ee4df4b123ea359418bca1ada | a290f3830d584e2317df13e38760514a3c331a53 | /Week 4/fallDistance.cpp | 919351ee49bd317df0dc08d77bcf072459c07fe0 | [] | no_license | jredp/CS-161 | 404ed185119bcc66b679c6b3326593b0bf3314d3 | 955e05d69674dda411a19e1b9d021235cdecb7b5 | refs/heads/master | 2021-01-22T16:18:01.023618 | 2017-09-04T19:06:50 | 2017-09-04T19:06:50 | 102,393,087 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,049 | cpp | /*********************************************************************
** Author: Jared Parkinson
** Date: 10/20/2015
** Description: Assignment 4 - Week 4 - Project 4.a - fallDistance.cpp
*********************************************************************/
#include <iostream>
#include <cmath> //To use pow
using namespace std;
//Define Function to be used
double fallDistance(int);
/* //Main TEST for Return
int main()
{
//Define Variables
int time;
//Request Time Input
cout << "input time in seconds\n";
cin >> time;
fallDistance(time); //Apply fallDistance function
cout << fallDistance(time) << endl;
return 0;
} */
/**************************************************************
* Description: Return the [Fall Distance] for [Time in Seconds]
* Parameters: Requires [time] variable in seconds
* Return Value: [Fall Distance] as a double result
**************************************************************/
double fallDistance(int time)
{
// Return the distance as result when called
return (.5 * 9.8) * pow(time,2.0);
} | [
"[email protected]"
] | |
064cded134ed391a23d893bf0dc997cd87d5365f | 600df3590cce1fe49b9a96e9ca5b5242884a2a70 | /components/sync/driver/protocol_event_observer.h | 651069aca08e21140341b4a958022cbe8005f685 | [
"BSD-3-Clause"
] | permissive | metux/chromium-suckless | efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a | 72a05af97787001756bae2511b7985e61498c965 | refs/heads/orig | 2022-12-04T23:53:58.681218 | 2017-04-30T10:59:06 | 2017-04-30T23:35:58 | 89,884,931 | 5 | 3 | BSD-3-Clause | 2022-11-23T20:52:53 | 2017-05-01T00:09:08 | null | UTF-8 | C++ | false | false | 581 | h | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_SYNC_DRIVER_PROTOCOL_EVENT_OBSERVER_H_
#define COMPONENTS_SYNC_DRIVER_PROTOCOL_EVENT_OBSERVER_H_
namespace syncer {
class ProtocolEvent;
class ProtocolEventObserver {
public:
ProtocolEventObserver();
virtual ~ProtocolEventObserver();
virtual void OnProtocolEvent(const ProtocolEvent& event) = 0;
};
} // namespace syncer
#endif // COMPONENTS_SYNC_DRIVER_PROTOCOL_EVENT_OBSERVER_H_
| [
"[email protected]"
] | |
fd786540f921ebbcf768115fb932a08c26ee1fc2 | 101d615aa82e6f6897f6018c73404136f96abc4d | /第十四章/模板类和友元/frnd2tmp非模板友元.cpp | e51fcc6db8f3513525d4e916b926b85053b0e8e8 | [] | no_license | Endsnotmeans/C- | e1254b4bbd858c9bbb418bbd3c1117861ece0769 | cc5b9a5fb138bff8aff3b79627848a5d0e0b1906 | refs/heads/master | 2021-01-20T08:34:59.053874 | 2017-11-11T15:35:18 | 2017-11-11T15:35:18 | 101,566,412 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,422 | cpp | // frnd2tmp.cpp -- 非模板友元template class with non-template friends
#include <iostream>
using std::cout;
using std::endl;
template <typename T>
class HasFriend
{
private:
T item;
static int ct;
public:
HasFriend(const T & i) : item(i) {ct++;}
~HasFriend() {ct--; }
friend void counts(); //无模板类参数
friend void reports(HasFriend<T> &); //有模版类参数
};
// each specialization has its own static data member
template <typename T>
int HasFriend<T>::ct = 0; //初始化ct为0,用作用域解析符
// non-template friend to all HasFriend<T> classes
void counts()
{
cout << "int count: " << HasFriend<int>::ct << "; ";
cout << "double count: " << HasFriend<double>::ct << endl;
}
// non-template friend to the HasFriend<int> class
void reports(HasFriend<int> & hf)
{
cout <<"HasFriend<int>: " << hf.item << endl;
}
// non-template friend to the HasFriend<double> class
void reports(HasFriend<double> & hf)
{
cout <<"HasFriend<double>: " << hf.item << endl;
}
int main()
{
cout << "No objects declared: ";
counts();
HasFriend<int> hfi1(10);
cout << "After hfi1 declared: ";
counts();
HasFriend<int> hfi2(20);
cout << "After hfi2 declared: ";
counts();
HasFriend<double> hfdb(10.5);
cout << "After hfdb declared: ";
counts();
reports(hfi1);
reports(hfi2);
reports(hfdb);
return 0;
}
| [
"[email protected]"
] | |
81625622db44a251ba3b1842d0610bafafb1093e | 418977e32d146aa8f1a39101e6f0e097086a5962 | /UVA/10330.cpp | 7baa29971b92fb1cc95d56c27f7adaaa0f71e947 | [] | no_license | WaleedAbdelhakim/Competitive-Programming | 7ded88dbedbb5cfe5546a1d1def95e020e6a275d | 45b73d3d1581e39321d7a4cdfa5b2a297b3d4ee9 | refs/heads/master | 2021-07-13T12:27:43.447255 | 2020-07-11T22:32:07 | 2020-07-11T22:32:07 | 170,042,819 | 6 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,555 | cpp | #include <bits/stdc++.h>
using namespace std;
struct edge {
int to , cap;
};
const int N = 205; // make sure is greater than max_node will ever be
int dist[N] , p[N] , src , max_node , snk; // don't forget to set src and snk
vector<edge> edges;
vector<int> adj[N];
void addAugEdge(int u , int v , int c) {
max_node = max(max_node , max(u , v));
adj[u].push_back(edges.size());
edges.push_back({v , c});
adj[v].push_back(edges.size());
edges.push_back({u , 0}); // c if undirected 0 if directed
}
bool bfs() {
memset(dist , -1 , (max_node + 1) * sizeof dist[0]);
queue<int> q;
q.push(src);
dist[src] = 0;
while (q.size()) {
int cur = q.front();
q.pop();
for (int ci : adj[cur]) {
auto &e = edges[ci];
if (dist[e.to] == -1 && e.cap) {
q.push(e.to);
dist[e.to] = dist[cur] + 1;
}
}
}
return dist[snk] != -1;
}
int dfs (int node , int flow) {
if (node == snk || !flow)
return flow;
for (; p[node] < adj[node].size() ; p[node]++) {
auto &e= edges[adj[node][p[node]]];
auto &re = edges[adj[node][p[node]]^1];
if (dist[node] + 1 != dist[e.to]) continue;
int push = dfs(e.to , min(flow , e.cap));
if (push) {
e.cap -= push;
re.cap += push;
return push;
}
}
return 0;
}
long long dinic() {
long long flow = 0;
while (bfs()) {
memset(p , 0 , sizeof p);
while (int f = dfs(src , 1e9)) // make sure that no edge has cap greater than 1e9
flow += f;
}
return flow;
}
void init() { // every test case
edges.clear();
for (int i = 0 ;i <= max_node;i++)
adj[i].clear();
max_node = 0;
}
int main() {
#ifndef ONLINE_JUDGE
freopen("input.in" , "r" , stdin);
#endif
int n , m , u , v , c , b , d;
while (scanf("%d" , &n) == 1) {
init();
src = N - 1 , snk = N - 2;
for (int i = 1 ;i <= n ;i++) {
scanf("%d" , &c);
addAugEdge(i , i + n , c);
}
scanf("%d" , &m);
while (m--) {
scanf("%d%d%d" , &u , &v , &c);
addAugEdge(u + n , v , c);
}
scanf("%d%d" , &b , &d);
while (b--) {
scanf("%d" , &u);
addAugEdge(src , u , 1e9);
}
while (d--) {
scanf("%d" , &v);
addAugEdge(v + n , snk , 1e9);
}
printf("%lld\n" , dinic());
}
}
| [
"[email protected]"
] | |
7a3c7e1a34870d3332c6797677219da1bedd2a57 | 4c2480c4651581179de4a8817948f90166dc8a6b | /include/avhttp/detail/handler_type_requirements.hpp | 4a4603368ee4b4eb34fca7784469512cb95ed1d4 | [
"BSL-1.0"
] | permissive | hadesh/avhttp | a4afd0357bf67af80a1f3afe36f7d0655f5169d8 | b96a893cdf347fc35e04d1ed7fb0e0ae15133df5 | refs/heads/master | 2021-01-18T14:44:20.089561 | 2013-06-09T19:13:47 | 2013-06-09T19:13:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,260 | hpp | //
// detail/handler_type_requirements.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2013 Jack (jack dot wgm at gmail dot com)
// Copyright (c) 2003, Arvid Norberg
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef __HANDLER_TYPE_REQUIREMENTS_HPP__
#define __HANDLER_TYPE_REQUIREMENTS_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/config.hpp>
#include <boost/asio/detail/handler_type_requirements.hpp>
namespace boost {
namespace asio {
namespace detail {
#if defined(BOOST_ASIO_ENABLE_HANDLER_TYPE_REQUIREMENTS)
#define BOOST_ASIO_OPEN_HANDLER_CHECK( \
handler_type, handler) \
\
BOOST_ASIO_HANDLER_TYPE_REQUIREMENTS_ASSERT( \
sizeof(boost::asio::detail::one_arg_handler_test( \
handler, \
static_cast<const boost::system::error_code*>(0))) == 1, \
"OpenHandler type requirements not met") \
\
typedef boost::asio::detail::handler_type_requirements< \
sizeof( \
boost::asio::detail::argbyv( \
boost::asio::detail::clvref(handler))) + \
sizeof( \
boost::asio::detail::lvref(handler)( \
boost::asio::detail::lvref<const boost::system::error_code>()), \
char(0))>
#define BOOST_ASIO_REQUEST_HANDLER_CHECK( \
handler_type, handler) \
\
BOOST_ASIO_HANDLER_TYPE_REQUIREMENTS_ASSERT( \
sizeof(boost::asio::detail::one_arg_handler_test( \
handler, \
static_cast<const boost::system::error_code*>(0))) == 1, \
"OpenHandler type requirements not met") \
\
typedef boost::asio::detail::handler_type_requirements< \
sizeof( \
boost::asio::detail::argbyv( \
boost::asio::detail::clvref(handler))) + \
sizeof( \
boost::asio::detail::lvref(handler)( \
boost::asio::detail::lvref<const boost::system::error_code>()), \
char(0))>
#else
#define BOOST_ASIO_OPEN_HANDLER_CHECK( \
handler_type, handler) \
typedef int
#endif
} // namespace detail
} // namespace asio
} // namespace boost
#endif // __HANDLER_TYPE_REQUIREMENTS_HPP__
| [
"[email protected]"
] | |
f0ce4f858446279cffcabd3204c1b1454c36a02f | e5fa7e1e60d098b448fd562deb26f8dd33274d68 | /Commands/BlinkyOff.h | 8ed807575ec9e4d3eae1b367bfba236b5e0134d3 | [] | no_license | errorcodexero/command | 20a867fe43656fdc3a930aa10e539e1614114d27 | f9cbda069df147871129b59ddc25258e5542ae83 | refs/heads/master | 2016-09-06T00:26:09.598684 | 2012-12-05T06:06:59 | 2012-12-05T06:06:59 | 40,694,092 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 308 | h | #ifndef BLINKY_OFF_H
#define BLINKY_OFF_H
#include "../CommandBase.h"
class BlinkyOff: public CommandBase {
public:
BlinkyOff();
virtual void Initialize();
virtual void Execute();
virtual bool IsFinished();
virtual void End();
virtual void Interrupted();
};
#endif
| [
"stevet@RHUBARB"
] | stevet@RHUBARB |
964d4c7fc6f720c78fc8cca9c58bec13142b44ac | 4982979ef3edb4aa25b6a48771c367b08d3497b4 | /ai_chainer.cpp | df3598e484eec223c3b7503ab635be59692a8b24 | [] | no_license | kusano/codevs2019 | ee0346592feb5321fb4373fc6e25ad8554a98529 | c9d5887446ff8dc646046dea508bcc396f0f82e5 | refs/heads/master | 2020-05-15T18:49:47.822114 | 2019-05-10T07:32:44 | 2019-05-10T07:42:21 | 182,439,534 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,441 | cpp | #include "ai_chainer.h"
#include <iostream>
using namespace std;
void AIChainer::initialize(Game &game, int seed)
{
};
Move AIChainer::think(Game &game)
{
Move move;
search(0, 2, game.fields[0], game.packs+game.turn, &move);
return move;
}
int AIChainer::search(int depth, int maxDepth, Field &field, char pack[][4],
Move *move)
{
if (depth==maxDepth)
{
if (field.isDead())
return 0;
// 連鎖候補は長く、ブロックは多く、高さは低く
return
field.candChain()*10000 +
(100-field.maxHeight())*100 +
(200-field.blockNum());
}
int maxScore = -1;
if (depth==0)
*move = Move(0, 0, false);
for (int pos=0; pos<9; pos++)
for (int rotate=0; rotate<4; rotate++)
{
Move m(pos, rotate, false);
// TODO: 500ターンを越えたとき
Result result = field.move(m, pack[depth]);
int score;
if (!field.isDead())
score = search(depth+1, maxDepth, field, pack, move);
else
score = 0;
field.undo();
// 10連鎖以上が可能なら打つ
if (depth==0 && result.chain>=10)
{
*move = m;
return score;
}
if (score > maxScore)
{
maxScore = score;
if (depth==0)
*move = m;
}
}
return maxScore;
}
| [
"[email protected]"
] | |
af61e7beb6f2a454b42e246d5c5bcb50e6c4471e | 19eb97436a3be9642517ea9c4095fe337fd58a00 | /private/inet/urlmon/astg/stgwrap.hxx | a1a203d999dcacb374c0d3e622abfb7a8284972c | [] | no_license | oturan-boga/Windows2000 | 7d258fd0f42a225c2be72f2b762d799bd488de58 | 8b449d6659840b6ba19465100d21ca07a0e07236 | refs/heads/main | 2023-04-09T23:13:21.992398 | 2021-04-22T11:46:21 | 2021-04-22T11:46:21 | 360,495,781 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,666 | hxx | //+---------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1992 - 1995.
//
// File: stgwrap.hxx
//
// Contents: IStorage and IStream wrappers for async docfile
//
// Classes: CAsyncStorage
// CAsyncRootStorage
// CAsyncStream
// CConnectionPoint
//
// Functions:
//
// History: 27-Dec-95 SusiA Created
//
//----------------------------------------------------------------------------
#ifndef __ASYNCEXPDF_HXX__
#define __ASYNCEXPDF_HXX__
#include "sinklist.hxx"
#include "filllkb.hxx"
//BUGBUG: defined in dfmsp.hxx.
typedef DWORD LPSTGSECURITY;
//+---------------------------------------------------------------------------
//
// Class: CAsyncStorage
//
// Purpose: Wrap storage objects for Async Docfiles
//
// Interface:
//
// History: 28-Dec-95 SusiA Created
//
// Notes:
//
//----------------------------------------------------------------------------
class CAsyncStorage:
public IStorage,
public IConnectionPointContainer
{
public:
inline CAsyncStorage(IStorage *pstg, CFillLockBytes *pflb);
inline ~CAsyncStorage(void);
// IUnknown
STDMETHOD(QueryInterface)(REFIID iid, void **ppvObj);
STDMETHOD_(ULONG, AddRef)(void);
STDMETHOD_(ULONG, Release)(void);
// IStorage
STDMETHOD(CreateStream)(OLECHAR const *pwcsName,
DWORD grfMode,
DWORD reserved1,
DWORD reserved2,
IStream **ppstm);
STDMETHOD(OpenStream)(OLECHAR const *pwcsName,
void *reserved1,
DWORD grfMode,
DWORD reserved2,
IStream **ppstm);
STDMETHOD(CreateStorage)(OLECHAR const *pwcsName,
DWORD grfMode,
DWORD reserved1,
LPSTGSECURITY reserved2,
IStorage **ppstg);
STDMETHOD(OpenStorage)(OLECHAR const *pwcsName,
IStorage *pstgPriority,
DWORD grfMode,
SNB snbExclude,
DWORD reserved,
IStorage **ppstg);
STDMETHOD(CopyTo)(DWORD ciidExclude,
IID const *rgiidExclude,
SNB snbExclude,
IStorage *pstgDest);
STDMETHOD(MoveElementTo)(OLECHAR const *lpszName,
IStorage *pstgDest,
OLECHAR const *lpszNewName,
DWORD grfFlags);
STDMETHOD(Commit)(DWORD grfCommitFlags);
STDMETHOD(Revert)(void);
STDMETHOD(EnumElements)(DWORD reserved1,
void *reserved2,
DWORD reserved3,
IEnumSTATSTG **ppenm);
STDMETHOD(DestroyElement)(OLECHAR const *pwcsName);
STDMETHOD(RenameElement)(OLECHAR const *pwcsOldName,
OLECHAR const *pwcsNewName);
STDMETHOD(SetElementTimes)(const OLECHAR *lpszName,
FILETIME const *pctime,
FILETIME const *patime,
FILETIME const *pmtime);
STDMETHOD(SetClass)(REFCLSID clsid);
STDMETHOD(SetStateBits)(DWORD grfStateBits, DWORD grfMask);
STDMETHOD(Stat)(STATSTG *pstatstg, DWORD grfStatFlag);
//From IConnectionPointContainer
STDMETHOD(EnumConnectionPoints)(IEnumConnectionPoints **ppEnum);
STDMETHOD(FindConnectionPoint)(REFIID iid, IConnectionPoint **ppCP);
SCODE Notify(void);
protected:
LONG _cReferences;
IStorage *_pRealStg;
CFillLockBytes *_pflb;
CConnectionPoint _cpoint;
};
inline CAsyncStorage::CAsyncStorage(IStorage *pstg, CFillLockBytes *pflb)
{
_cReferences = 1;
_pRealStg = pstg;
_pflb = pflb;
}
inline CAsyncStorage::~CAsyncStorage(void)
{
if (_pRealStg != NULL)
_pRealStg->Release;
}
//+---------------------------------------------------------------------------
//
// Class: CAsyncRootStorage
//
// Purpose: Wrap Root Storage objects for Async Docfiles
//
// Interface:
//
// History: 28-Dec-95 SusiA Created
//
// Notes:
//
//----------------------------------------------------------------------------
class CAsyncRootStorage:
public IRootStorage,
public CAsyncStorage
{
public:
inline CAsyncRootStorage(IStorage *pstg, CFillLockBytes *pflb);
// IUnknown
STDMETHOD(QueryInterface)(REFIID iid, void **ppvObj);
STDMETHOD_(ULONG, AddRef)(void);
STDMETHOD_(ULONG, Release)(void);
// IRootStorage
STDMETHOD(SwitchToFile)(OLECHAR *ptcsFile);
};
inline CAsyncRootStorage::CAsyncRootStorage(IStorage *pstg, CFillLockBytes *pflb)
:CAsyncStorage(pstg, pflb)
{
}
//+---------------------------------------------------------------------------
//
// Class: CAsyncStream
//
// Purpose: Wrap Stream objects for Async Docfiles
//
// Interface:
//
// History: 28-Dec-95 SusiA Created
//
// Notes:
//
//----------------------------------------------------------------------------
class CAsyncStream:
public IStream,
public IConnectionPointContainer
{
public:
inline CAsyncStream(IStream *pstm, CFillLockBytes *pflb);
inline ~CAsyncStream(void);
// From IUnknown
STDMETHOD(QueryInterface)(REFIID iid, void **ppvObj);
STDMETHOD_(ULONG,AddRef)(void);
STDMETHOD_(ULONG,Release)(void);
// From IStream
STDMETHOD(Read)(VOID HUGEP *pv,
ULONG cb,
ULONG *pcbRead);
STDMETHOD(Write)(VOID const HUGEP *pv,
ULONG cb,
ULONG *pcbWritten);
STDMETHOD(Seek)(LARGE_INTEGER dlibMove,
DWORD dwOrigin,
ULARGE_INTEGER *plibNewPosition);
STDMETHOD(SetSize)(ULARGE_INTEGER cb);
STDMETHOD(CopyTo)(IStream *pstm,
ULARGE_INTEGER cb,
ULARGE_INTEGER *pcbRead,
ULARGE_INTEGER *pcbWritten);
STDMETHOD(Commit)(DWORD grfCommitFlags);
STDMETHOD(Revert)(void);
STDMETHOD(LockRegion)(ULARGE_INTEGER libOffset,
ULARGE_INTEGER cb,
DWORD dwLockType);
STDMETHOD(UnlockRegion)(ULARGE_INTEGER libOffset,
ULARGE_INTEGER cb,
DWORD dwLockType);
STDMETHOD(Stat)(STATSTG *pstatstg, DWORD grfStatFlag);
STDMETHOD(Clone)(IStream **ppstm);
//From IConnectionPointContainer
STDMETHOD(EnumConnectionPoints)(IEnumConnectionPoints **ppEnum);
STDMETHOD(FindConnectionPoint)(REFIID iid, IConnectionPoint **ppCP);
SCODE Notify(void);
private:
LONG _cReferences;
IStream *_pRealStm;
CFillLockBytes *_pflb;
CConnectionPoint _cpoint;
};
inline CAsyncStream::CAsyncStream(IStream *pstm, CFillLockBytes *pflb)
{
_cReferences = 1;
_pRealStm = pstm;
_pflb = pflb;
}
inline CAsyncStream::~CAsyncStream(void)
{
if (_pRealStm != NULL)
_pRealStm->Release;
}
//+---------------------------------------------------------------------------
//
// Class: CAsyncEnumSTATSTG
//
// Purpose: Wrap EnumSTATSTG objects for Async Docfiles
//
// Interface:
//
// History: 28-Dec-95 SusiA Created
//
// Notes:
//
//----------------------------------------------------------------------------
class CAsyncEnum
: public IEnumSTATSTG,
public IConnectionPointContainer
{
public:
inline CAsyncEnum(IEnumSTATSTG *penum, CFillLockBytes *pflb);
inline ~CAsyncEnum(void);
// From IUnknown
STDMETHOD(QueryInterface)(REFIID iid, void **ppvObj);
STDMETHOD_(ULONG,AddRef)(void);
STDMETHOD_(ULONG,Release)(void);
// IEnumSTATSTG
STDMETHOD(Next)(ULONG celt, STATSTG FAR *rgelt, ULONG *pceltFetched);
STDMETHOD(Skip)(ULONG celt);
STDMETHOD(Reset)(void);
STDMETHOD(Clone)(IEnumSTATSTG **ppenm);
//From IConnectionPointContainer
STDMETHOD(EnumConnectionPoints)(IEnumConnectionPoints **ppEnum);
STDMETHOD(FindConnectionPoint)(REFIID iid, IConnectionPoint **ppCP);
SCODE Notify(void);
private:
LONG _cReferences;
IEnumSTATSTG *_pRealEnum;
CFillLockBytes *_pflb;
CConnectionPoint _cpoint;
};
inline CAsyncEnum::CAsyncEnum(IEnumSTATSTG *penum, CFillLockBytes *pflb)
{
_cReferences = 1;
_pRealEnum = penum;
_pflb = pflb;
}
inline CAsyncEnum::~CAsyncEnum(void)
{
if (_pRealEnum != NULL)
_pRealEnum->Release;
}
#endif // #ifndef __ASYNCEXPDF_HXX__
| [
"[email protected]"
] | |
3e9015bbd976a79947b5ebd3d27c78139460f1e7 | 33e10b258847052ad5acb8e053644b1a31bda74f | /Game/Scene/Clear/Clear.cpp | e651dab68920ffd206caba0e29cd5265b47b5631 | [] | no_license | BayaSea0907/MyGameEngine | 45d202697f95dbedef9a87334f4c0972601ee2f7 | 9724a85794587cce267d107cc4c4a9a1c284fde1 | refs/heads/master | 2020-12-06T05:34:33.492163 | 2020-01-08T18:11:03 | 2020-01-08T18:11:03 | 232,360,294 | 0 | 0 | null | 2020-01-08T18:11:05 | 2020-01-07T15:55:07 | C++ | UTF-8 | C++ | false | false | 288 | cpp | #include "Clear.h"
CClear::CClear()
{
}
CClear::~CClear()
{
}
GameObject* CClear::GetGameObject()
{
return NULL;
}
void CClear::Update()
{
}
void CClear::ReleaseGameObject()
{
}
void CClear::Release()
{
}
MySceneState CClear::GetNextSceneState()
{
return m_eNextSceneState;
} | [
"[email protected]"
] | |
48909e4bcf5253cdbceca4e7521d80738f46f345 | 9a15bcf5bce5c4fbdf2fc9cb464e38d66354dd6d | /test/config/checkpoint.cpp | 77fa8d0cf98226ff075ed8321df4431118614dbd | [
"MIT"
] | permissive | ccccbjcn/nuls-v2-cplusplus-sdk | 4102eebf0d3a4c5e6d6330d300bf1a72eb4b8a98 | 3d5a76452fe0673eba490b26e5a95fea3d5788df | refs/heads/master | 2021-04-08T10:38:04.717948 | 2020-04-22T02:26:28 | 2020-04-22T02:26:28 | 248,767,898 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,023 | cpp | /**
* Copyright (c) 2020 libnuls developers (see AUTHORS)
*
* This file is part of libnuls.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <sstream>
#include <string>
#include <boost/lexical_cast.hpp>
#include <boost/program_options.hpp>
#include <boost/test/unit_test.hpp>
#include <nuls/system.hpp>
using namespace nuls::system;
using namespace nuls::system::config;
using namespace boost::program_options;
BOOST_AUTO_TEST_SUITE(checkpoint_tests)
#define CHECKPOINT_HASH_A "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"
#define CHECKPOINT_A CHECKPOINT_HASH_A ":0"
#define CHECKPOINT_B "0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d:11111"
#define CHECKPOINT_C "000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6:33333"
#define CHECKPOINT_ABC CHECKPOINT_A "\n" CHECKPOINT_B "\n" CHECKPOINT_C
// ------------------------------------------------------------------------- //
BOOST_AUTO_TEST_SUITE(checkpoint__construct)
BOOST_AUTO_TEST_CASE(checkpoint__construct__default__null_hash)
{
const checkpoint check;
BOOST_REQUIRE(check.hash() == null_hash);
BOOST_REQUIRE_EQUAL(check.height(), 0u);
}
BOOST_AUTO_TEST_CASE(checkpoint__construct__copy__expected)
{
const checkpoint check1(CHECKPOINT_C);
const checkpoint check2(check1);
BOOST_REQUIRE_EQUAL(check2.height(), check1.height());
BOOST_REQUIRE_EQUAL(encode_hash(check2.hash()), encode_hash(check1.hash()));
}
BOOST_AUTO_TEST_CASE(checkpoint__construct__string__expected)
{
const checkpoint genesis(CHECKPOINT_B);
BOOST_REQUIRE_EQUAL(genesis.height(), 11111u);
BOOST_REQUIRE_EQUAL(genesis.to_string(), CHECKPOINT_B);
}
BOOST_AUTO_TEST_CASE(checkpoint__construct__digest__expected)
{
const size_t expected_height = 42;
const auto expected_hash = CHECKPOINT_HASH_A;
hash_digest digest;
decode_hash(digest, expected_hash);
const checkpoint genesis(digest, expected_height);
BOOST_REQUIRE_EQUAL(genesis.height(), expected_height);
BOOST_REQUIRE_EQUAL(encode_hash(genesis.hash()), expected_hash);
}
BOOST_AUTO_TEST_CASE(checkpoint__construct__invalid_height_value__throws_invalid_option_value)
{
// 2^64
BOOST_REQUIRE_THROW(checkpoint(CHECKPOINT_HASH_A ":18446744073709551616"), invalid_option_value);
}
BOOST_AUTO_TEST_CASE(checkpoint__construct__invalid_height_characters__throws_invalid_option_value)
{
// 21 characters
BOOST_REQUIRE_THROW(checkpoint(CHECKPOINT_HASH_A ":1000000000100000000001"), invalid_option_value);
}
BOOST_AUTO_TEST_CASE(checkpoint__construct__bogus_height_characters__throws_invalid_option_value)
{
BOOST_REQUIRE_THROW(checkpoint(CHECKPOINT_HASH_A ":xxx"), invalid_option_value);
}
BOOST_AUTO_TEST_CASE(checkpoint__construct__bogus_line_hash__throws_invalid_option_value)
{
BOOST_REQUIRE_THROW(checkpoint("bogus:42"), invalid_option_value);
}
BOOST_AUTO_TEST_CASE(checkpoint__construct__bogus_hash__throws_invalid_option_value)
{
BOOST_REQUIRE_THROW(checkpoint("bogus", 42), invalid_option_value);
}
BOOST_AUTO_TEST_SUITE_END()
// ------------------------------------------------------------------------- //
BOOST_AUTO_TEST_SUITE(checkpoint__istream)
BOOST_AUTO_TEST_CASE(checkpoint__istream__empty__expected)
{
checkpoint deserialized;
std::stringstream serialized(CHECKPOINT_A);
serialized >> deserialized;
BOOST_REQUIRE_EQUAL(deserialized.to_string(), CHECKPOINT_A);
}
BOOST_AUTO_TEST_SUITE_END()
// ------------------------------------------------------------------------- //
BOOST_AUTO_TEST_SUITE(checkpoint__ostream)
static const checkpoint::list test_checkpoints_list(
{
{ CHECKPOINT_A },
{ CHECKPOINT_B },
{ CHECKPOINT_C }
});
BOOST_AUTO_TEST_CASE(checkpoint__ostream__empty__expected)
{
std::stringstream serialized;
serialized << checkpoint::list();
BOOST_REQUIRE_EQUAL(serialized.str(), "");
}
BOOST_AUTO_TEST_CASE(checkpoint__ostream__populated__expected)
{
std::stringstream serialized;
serialized << test_checkpoints_list;
BOOST_REQUIRE_EQUAL(serialized.str(), CHECKPOINT_ABC);
}
BOOST_AUTO_TEST_CASE(checkpoint__ostream__boost_lexical_cast__expected)
{
using namespace boost;
const auto serialized = lexical_cast<std::string>(test_checkpoints_list);
BOOST_REQUIRE_EQUAL(serialized, CHECKPOINT_ABC);
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()
| [
"[email protected]"
] | |
24e08bbde92365740607a5b78095b7b3ce5a15db | 877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a | /app/src/main/cpp/dir7941/dir7942/dir8062/dir8063/dir12766/dir12767/dir13029/dir15097/dir15260/dir15321/dir15524/dir15932/dir16604/file16642.cpp | f993869c795e90e6bc86111ecf2a9993dfd2bcae | [] | no_license | tgeng/HugeProject | 829c3bdfb7cbaf57727c41263212d4a67e3eb93d | 4488d3b765e8827636ce5e878baacdf388710ef2 | refs/heads/master | 2022-08-21T16:58:54.161627 | 2020-05-28T01:54:03 | 2020-05-28T01:54:03 | 267,468,475 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 115 | cpp | #ifndef file16642
#error "macro file16642 must be defined"
#endif
static const char* file16642String = "file16642"; | [
"[email protected]"
] | |
06373767e49dc7c879024b6d4fb7dad13d658f03 | 0676032b18133a46adeace89196bc769a87500d1 | /2019-2020第一学期训练/Educational Codeforces Round 76/E. The Contest - quick.cpp | a6c93195ba1784d58fc15646cb07694c8f9eba76 | [] | no_license | zhushaoben/training | ce47c19934f67fc21f4571f99973d16561ede195 | 530f2b5dc1a2d1e4a02c22f034e251160d0b42af | refs/heads/master | 2021-07-11T22:32:54.227626 | 2020-10-30T12:49:24 | 2020-10-30T12:49:24 | 213,320,465 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 696 | cpp | #include<bits/stdc++.h>
using namespace std;
#define maxn 200000
int f[maxn+5],a[maxn+5],sum[4];
//f[i] denote the minimum answer that first i problems are distributed to programmer 1 or programmer 2
//and remaining problems are distributed to programmer 3
int main(){
int k1,k2,k3,x,n;scanf("%d%d%d",&k1,&k2,&k3),n=k1+k2+k3;
for(int i=0;i<k1;i++)scanf("%d",&x),a[x]=1;
for(int i=0;i<k2;i++)scanf("%d",&x),a[x]=2;
for(int i=0;i<k3;i++)scanf("%d",&x),a[x]=3;
int ans=f[0]=n-k3;
for(int i=1;i<=n;i++){
sum[a[i]]++;
if(a[i]==1)f[i]=f[i-1];
else if(a[i]==2)f[i]=f[i-1]-1;
else f[i]=f[i-1]+1;
ans=min(ans,f[i]=min(f[i],n-i-k3+sum[3]+sum[2]+sum[3]));
}
printf("%d",ans);
return 0;
}
| [
"[email protected]"
] | |
55edf5c6d619eba9ea63f8eac207f74ec0e63464 | 15f0af55597b15f91c88eb84fcd7e6467b5e14ea | /FS_3_ENG/1_Muta/FemaleZMB/config.cpp | f069d5a00745f37029d2d51e235e51217768acc7 | [] | no_license | Vldl/P.A-traduction | a0f5a136201ae2e726d8625aaaddf26eca540118 | ceac5be92c1d22b13cddeff7e0843ccffb9b14e7 | refs/heads/master | 2023-08-15T03:15:07.604615 | 2021-09-27T12:38:54 | 2021-09-27T12:38:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,235 | cpp | ////////////////////////////////////////////////////////////////////
//DeRap: FS_3\1_Muta\FemaleZMB\config.bin
//Produced from mikero's Dos Tools Dll version 7.46
//https://bytex.market/products/item/weodpphdknnzm70o0h8q/Mikero%27s%20Dos%20Tools
//'now' is Wed Aug 12 00:04:13 2020 : 'file' last modified on Tue Jun 02 01:39:40 2020
////////////////////////////////////////////////////////////////////
#define _ARMA_
class CfgPatches
{
class DZ_Characters_Zombies
{
units[] = {"Hermit_NewAI"};
weapons[] = {};
requiredVersion = 0.1;
requiredAddons[] = {"DZ_Characters"};
};
};
class CfgVehicles
{
class ZombieMaleBase;
class FS_Saharov;
class FS_ZombieType2_Base: ZombieMaleBase
{
scope = 0;
hiddenSelections[] = {"vkComFidovPublic"};
model = "FS_3\1_Muta\FemaleZMB\FemaleZMB.p3d";
hiddenSelectionsMaterials[] = {""};
htMin = 6000;
htMax = 8800;
afMax = 5555;
mfMax = 5555;
mFact = 5555;
tBody = 5555;
displayName = "Zombie";
descriptionShort = "Enemy";
class Cargo
{
itemsCargoSize[] = {10,20};
allowOwnedCargoManipulation = 1;
openable = 0;
};
class DamageSystem
{
class GlobalHealth
{
class Health
{
hitpoints = 700;
healthLevels[] = {{1,{"FS_3_Data\FemaleZMB\data\Damaged\Damag.rvmat"}},{0.7,{"FS_3_Data\FemaleZMB\data\Damaged\Damag2.rvmat"}},{0.5,{"FS_3_Data\FemaleZMB\data\Damaged\Damag2.rvmat"}},{0.3,{"FS_3_Data\FemaleZMB\data\Damaged\Damag3.rvmat"}},{0,{"FS_3_Data\FemaleZMB\data\Damaged\Damag3.rvmat"}}};
};
};
class DamageZones
{
class Head
{
class Health
{
hitpoints = 600;
transferToGlobalCoef = 1;
};
class ArmorType
{
class Projectile
{
class Health
{
damage = 1;
};
};
};
componentNames[] = {"Head"};
fatalInjuryCoef = 0.1;
inventorySlots[] = {"Headgear","Mask"};
};
class Torso
{
class Health
{
hitpoints = 1000;
transferToGlobalCoef = 1;
};
class ArmorType
{
class Projectile
{
class Health
{
damage = 1;
};
};
};
componentNames[] = {"Spine1","Spine3"};
fatalInjuryCoef = -1;
inventorySlots[] = {"Vest","Body","Back"};
};
class LeftArm
{
class Health
{
hitpoints = 1000;
transferToGlobalCoef = 0.33;
};
class ArmorType
{
class Projectile
{
class Health
{
damage = 1;
};
};
};
componentNames[] = {"LeftArm","LeftForeArm"};
fatalInjuryCoef = -1;
};
class RightArm
{
class Health
{
hitpoints = 1000;
transferToGlobalCoef = 0.33;
};
class ArmorType
{
class Projectile
{
class Health
{
damage = 1;
};
};
};
componentNames[] = {"RightArm","RightForeArm"};
fatalInjuryCoef = -1;
};
class LeftLeg
{
class Health
{
hitpoints = 1000;
transferToGlobalCoef = 0.33;
};
class ArmorType
{
class Projectile
{
class Health
{
damage = 1;
};
};
};
componentNames[] = {"LeftLeg","LeftUpLeg"};
fatalInjuryCoef = -1;
inventorySlots[] = {"Legs"};
};
class RightLeg
{
class Health
{
hitpoints = 1000;
transferToGlobalCoef = 0.33;
};
class ArmorType
{
class Projectile
{
class Health
{
damage = 1;
};
};
};
componentNames[] = {"RightLeg","RightUpLeg"};
fatalInjuryCoef = -1;
inventorySlots[] = {"Legs"};
};
class LeftFoot
{
class Health
{
hitpoints = 1000;
transferToGlobalCoef = 0.1;
};
class ArmorType
{
class Projectile
{
class Health
{
damage = 1;
};
};
};
transferToZonesNames[] = {"LeftLeg"};
transferToZonesCoefs[] = {0.1};
componentNames[] = {"LeftFoot"};
fatalInjuryCoef = -1;
inventorySlots[] = {"Feet"};
};
class RightFoot
{
class Health
{
hitpoints = 1000;
transferToGlobalCoef = 0.1;
};
class ArmorType
{
class Projectile
{
class Health
{
damage = 8;
};
};
};
transferToZonesNames[] = {"RightLeg"};
transferToZonesCoefs[] = {0.1};
componentNames[] = {"RightFoot"};
fatalInjuryCoef = -1;
inventorySlots[] = {"Feet"};
};
};
};
class AnimEvents
{
class Steps
{
class Walk1
{
soundLookupTable = "walkErc_Boots_Zmb_LookupTable";
noise = "ZombieStepNoise";
id = 1;
};
class Walk2
{
soundLookupTable = "walkErc_Boots_Zmb_LookupTable";
noise = "ZombieStepNoise";
id = 2;
};
class Walk3
{
soundLookupTable = "walkErc_Boots_Zmb_LookupTable";
noise = "ZombieStepNoise";
id = 3;
};
class Walk4
{
soundLookupTable = "walkErc_Boots_Zmb_LookupTable";
noise = "ZombieStepNoise";
id = 4;
};
class Run1
{
soundLookupTable = "runErc_Boots_Zmb_LookupTable";
noise = "ZombieStepNoise";
id = 5;
};
class Run2
{
soundLookupTable = "runErc_Boots_Zmb_LookupTable";
noise = "ZombieStepNoise";
id = 6;
};
class Run3
{
soundLookupTable = "runErc_Boots_Zmb_LookupTable";
noise = "ZombieStepNoise";
id = 7;
};
class Run4
{
soundLookupTable = "runErc_Boots_Zmb_LookupTable";
noise = "ZombieStepNoise";
id = 8;
};
class Sprint1
{
soundLookupTable = "sprintErc_Boots_Zmb_LookupTable";
noise = "ZombieStepNoise";
id = 9;
};
class Sprint2
{
soundLookupTable = "sprintErc_Boots_Zmb_LookupTable";
noise = "ZombieStepNoise";
id = 10;
};
class Sprint3
{
soundLookupTable = "sprintErc_Boots_Zmb_LookupTable";
noise = "ZombieStepNoise";
id = 11;
};
class Sprint4
{
soundLookupTable = "sprintErc_Boots_Zmb_LookupTable";
noise = "ZombieStepNoise";
id = 12;
};
class Scuff1
{
soundLookupTable = "scuffErc_Boots_Zmb_LookupTable";
noise = "ZombieStepNoise";
id = 17;
};
class Scuff2
{
soundLookupTable = "scuffErc_Boots_Zmb_LookupTable";
noise = "ZombieStepNoise";
id = 18;
};
class Sccuff3
{
soundLookupTable = "scuffErc_Boots_Zmb_LookupTable";
noise = "ZombieStepNoise";
id = 19;
};
class Scuff4
{
soundLookupTable = "scuffErc_Boots_Zmb_LookupTable";
noise = "ZombieStepNoise";
id = 20;
};
class landFeetErc
{
soundLookupTable = "landFeetErc_Boots_Zmb_LookupTable";
noise = "ZombieStepNoise";
id = 21;
};
class landFootErc
{
soundLookupTable = "landFootErc_Boots_Zmb_LookupTable";
noise = "ZombieStepNoise";
id = 22;
};
class Bodyfall
{
soundLookupTable = "bodyfall_Zmb_LookupTable";
noise = "ZombieStepNoise";
id = 23;
};
class Bodyfall_Hand
{
soundLookupTable = "bodyfall_hand_Zmb_LookupTable";
noise = "ZombieStepNoise";
id = 24;
};
class Bodyfall_Slide
{
soundLookupTable = "bodyfall_slide_Zmb_LookupTable";
noise = "ZombieStepNoise";
id = 25;
};
class Prone_Walk_L
{
soundLookupTable = "walkProne_Zmb_LookupTable";
noise = "ZombieStepNoise";
id = 27;
};
class Prone_Walk_R
{
soundLookupTable = "walkProne_Zmb_LookupTable";
noise = "ZombieStepNoise";
id = 28;
};
class Prone_Run_L
{
soundLookupTable = "runProne_Zmb_LookupTable";
noise = "ZombieStepNoise";
id = 29;
};
class Prone_Run_R
{
soundLookupTable = "runProne_Zmb_LookupTable";
noise = "ZombieStepNoise";
id = 30;
};
};
class Sounds
{
class Attack_Light1
{
soundSet = "Zmb_Attack_Light1_SoundSet";
id = 1;
};
class Attack_Light2
{
soundSet = "Zmb_Attack_Light2_SoundSet";
id = 2;
};
class Attack_Heavy1
{
soundSet = "Zmb_Attack_Heavy1_SoundSet";
id = 3;
};
class Attack_Heavy2
{
soundSet = "Zmb_Attack_Heavy2_SoundSet";
id = 4;
};
class TwoHands
{
soundSet = "Zmb_Attack_TwoHands_SoundSet";
id = 5;
};
};
class SoundVoice
{
class LightHit
{
soundSet = "FV_ST_PACK_Zombi_hit_Soundset";
id = 1;
};
class HeavyHit
{
soundSet = "FV_ST_PACK_Zombi_hit_Soundset";
id = 2;
};
class Attack
{
soundSet = "FV_ST_PACK_Zombi_Attack_Soundset";
id = 5;
};
class Jump
{
soundSet = "ZmbM_Skinny_Old_Jump_Soundset";
id = 10;
};
class Land
{
soundSet = "ZmbM_Skinny_Old_Land_Soundset";
id = 11;
};
class CallToArmsShort
{
soundSet = "FV_ST_PACK_Zombi_Attack_Soundset";
id = 20;
};
};
};
};
class FS_ZombieType2: FS_ZombieType2_Base
{
scope = 2;
hiddenSelectionsTextures[] = {"FS_3_Data\FemaleZMB\data\telo_co.paa"};
};
class FS_ZombieType2_noTkan: FS_ZombieType2_Base
{
scope = 2;
model = "FS_3\1_Muta\FemaleZMB\FemaleZMBnoTK.p3d";
hiddenSelectionsTextures[] = {"FS_3_Data\FemaleZMB\data\telo_co.paa"};
};
};
class CfgNonAIVehicles
{
class ProxyHands;
class ProxyAK_47_v58_Proxy: ProxyHands
{
model = "\dz\Characters\Proxies\ak_47_v58_proxy.p3d";
};
class ProxyBack;
class ProxyBackpack_DZ: ProxyBack
{
model = "\dz\Characters\Proxies\Backpack_DZ.p3d";
};
class ProxyEyewear;
class ProxyEyewear_DZ: ProxyEyewear
{
model = "\dz\Characters\Proxies\Eyewear_DZ.p3d";
};
class ProxyHeadgear;
class ProxyHeadgear_DZ: ProxyHeadgear
{
model = "\dz\Characters\Proxies\Headgear_DZ.p3d";
};
class ProxyMask;
class ProxyMask_DZ: ProxyMask
{
model = "\dz\Characters\Proxies\Mask_DZ.p3d";
};
class ProxyVest;
class ProxyVest_DZ: ProxyVest
{
model = "\dz\Characters\Proxies\Vest_DZ.p3d";
};
class ProxyMelee;
class ProxyMelee_DZ: ProxyMelee
{
model = "\dz\Characters\Proxies\Melee_DZ.p3d";
};
};
| [
"[email protected]"
] | |
2d432ef61d59a9d868ac84e4516e0d5adf4cc8b3 | 7f62f204ffde7fed9c1cb69e2bd44de9203f14c8 | /DboClient/Tool/TSTool/Shape_UnifiedNarration.cpp | fb84d279144277832d8ffca01c6f4947a36530b4 | [] | no_license | 4l3dx/DBOGLOBAL | 9853c49f19882d3de10b5ca849ba53b44ab81a0c | c5828b24e99c649ae6a2953471ae57a653395ca2 | refs/heads/master | 2022-05-28T08:57:10.293378 | 2020-05-01T00:41:08 | 2020-05-01T00:41:08 | 259,094,679 | 3 | 3 | null | 2020-04-29T17:06:22 | 2020-04-26T17:43:08 | null | UHC | C++ | false | false | 1,606 | cpp | #include "stdafx.h"
#include "Shape_UnifiedNarration.h"
#include "resource.h"
#include "TSDoc.h"
#include "Attr_CONT_UnifiedNarration.h"
#include "EntityRegisterDiag.h"
#include "AttrEntityMng.h"
#include "OptionListBox.h"
IMPLEMENT_SERIAL( CShape_UnifiedNarration, CShape_GEntityCont, 1 )
CShape_UnifiedNarration::CShape_UnifiedNarration( const CPoint &point )
: CShape_GEntityCont( point, _T("CT_UnifiedNarration") )
{
CString strData;
strData.Format( _T("-1") );
AddAttr( _T("idx"), strData );
}
CShape_UnifiedNarration::~CShape_UnifiedNarration( void )
{
}
void CShape_UnifiedNarration::ShowContAttrEditBox( void )
{
CAttr_CONT_UnifiedNarration AttrPage;
AttrPage.AddAttr( _T("cid"), m_strContId );
AttrPage.AddAttr( _T("idx"), GetAttr( _T("idx") ) );
COptionListBox clListBox;
CEntityRegisterDiag clDiag;
clDiag.SetListControl( &clListBox );
clDiag.AddAttrPage( &AttrPage );
if ( IDOK == clDiag.DoModal() && clDiag.GetEditedAttrPage() )
{
CString strValue;
strValue = AttrPage.GetAttr( _T("cid") );
if ( strValue.GetLength() != 0 ) m_strContId = strValue;
strValue = AttrPage.GetAttr( _T("idx") );
if ( strValue.GetLength() != 0 ) SetAttr( _T("idx"), strValue );
UpdateHeightInfo();
GetDoc()->OnShapeChange( this );
}
}
void CShape_UnifiedNarration::ShowEntityAttrAddBox( void )
{
AfxMessageBox( _T("등록 시킬 수 있는 엔티티들이 존재하지 않습니다") );
}
void CShape_UnifiedNarration::GetProperty( CNtlTSScrProperty& clProperty )
{
clProperty.m_defProperty["cid"] = m_strContId;
clProperty.m_defProperty["idx"] = GetAttr( _T("idx") );
}
| [
"[email protected]"
] | |
ea0f924b3333dcc066b6d8c9322bf0fb5c9b2c5c | 069832c21c56ced036d4f6143d9b2b9017d5a918 | /cpp/P4_r2.cpp | 78b822374745df27b78e91e89305434f025c4549 | [] | no_license | Traeyee/leetcode | 1f3c3ac5cb6ba2531454ba012cb5cb2fccedb076 | 9c2cfc12375e09650c9a48bcfd170dbfca0dcc9c | refs/heads/master | 2022-05-07T04:01:06.163792 | 2022-03-08T01:44:03 | 2022-03-08T01:44:03 | 235,553,066 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,631 | cpp | /**
* @author [email protected]
* @time 2022-01-11 14:25
* @brief
*/
#include <algorithm>
#include <climits>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
class Solution {
public:
int findKthSortedArrays(vector<int>& nums1, vector<int>& nums2, int k) {
int n1 = nums1.size(), n2 = nums2.size();
// TODO: 各种特殊情况
if (nums1[n1 - 1] <= nums2[0]) {
if (k <= n1) {
return nums1[k - 1];
} else {
return nums2[k - n1 - 1];
}
}
// 因为 (i + 1) + (j + 1) = k,所以确定i必能确定j,我们以i为移动点
// 假设存在i使得上式成立
int l, r;
while (1) {
int i = (r - l) / 2 + l;
int j = k - i - 2;
// TODO: 各种越界
if (nums1[i] <= nums2[j]) {
if (nums2[j] <= nums1[i + 1]) {
return nums2[j];
} else {
l = i + 1;
continue;
}
} else {
if (nums1[i] <= nums2[j + 1]) {
return nums1[i];
}
if (nums1[i] > nums2[j + 1]) {
r = i - 1;
continue;
}
}
}
}
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {}
}; | [
"[email protected]"
] | |
9803f1af7d10883a24b83daa1feac09aa8b06b3b | 88ae8695987ada722184307301e221e1ba3cc2fa | /chrome/browser/nearby_sharing/wifi_network_configuration/wifi_network_configuration_handler.cc | a761ed6b7cfb913cfa78a62102bcbd6fba1f44d9 | [
"BSD-3-Clause"
] | permissive | iridium-browser/iridium-browser | 71d9c5ff76e014e6900b825f67389ab0ccd01329 | 5ee297f53dc7f8e70183031cff62f37b0f19d25f | refs/heads/master | 2023-08-03T16:44:16.844552 | 2023-07-20T15:17:00 | 2023-07-23T16:09:30 | 220,016,632 | 341 | 40 | BSD-3-Clause | 2021-08-13T13:54:45 | 2019-11-06T14:32:31 | null | UTF-8 | C++ | false | false | 3,271 | cc | // Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/nearby_sharing/wifi_network_configuration/wifi_network_configuration_handler.h"
#include "chrome/browser/nearby_sharing/logging/logging.h"
#include "chrome/browser/nearby_sharing/nearby_share_metrics_logger.h"
#include "chromeos/ash/components/network/network_configuration_handler.h"
#include "chromeos/ash/services/network_config/in_process_instance.h"
#include "chromeos/services/network_config/public/mojom/cros_network_config.mojom.h"
namespace {
chromeos::network_config::mojom::SecurityType MojoSecurityTypeFromAttachment(
const WifiCredentialsAttachment::SecurityType& security_type) {
switch (security_type) {
case WifiCredentialsAttachment::SecurityType::kWpaPsk:
return chromeos::network_config::mojom::SecurityType::kWpaPsk;
case WifiCredentialsAttachment::SecurityType::kWep:
return chromeos::network_config::mojom::SecurityType::kWepPsk;
default:
return chromeos::network_config::mojom::SecurityType::kNone;
}
}
} // namespace
WifiNetworkConfigurationHandler::WifiNetworkConfigurationHandler() {
ash::network_config::BindToInProcessInstance(
cros_network_config_remote_.BindNewPipeAndPassReceiver());
}
WifiNetworkConfigurationHandler::~WifiNetworkConfigurationHandler() = default;
void WifiNetworkConfigurationHandler::ConfigureWifiNetwork(
const WifiCredentialsAttachment& wifi_credentials_attachment,
chromeos::network_config::mojom::CrosNetworkConfig::ConfigureNetworkCallback
callback) {
auto wifi = chromeos::network_config::mojom::WiFiConfigProperties::New();
wifi->passphrase = wifi_credentials_attachment.wifi_password();
wifi->security = MojoSecurityTypeFromAttachment(
wifi_credentials_attachment.security_type());
wifi->ssid = wifi_credentials_attachment.ssid();
wifi->hidden_ssid =
chromeos::network_config::mojom::HiddenSsidMode::kDisabled;
auto config = chromeos::network_config::mojom::ConfigProperties::New();
config->type_config =
chromeos::network_config::mojom::NetworkTypeConfigProperties::NewWifi(
std::move(wifi));
config->auto_connect =
chromeos::network_config::mojom::AutoConnectConfig::New(true);
cros_network_config_remote_->ConfigureNetwork(
std::move(config), /*shared=*/false,
base::BindOnce(
&WifiNetworkConfigurationHandler::OnConfigureWifiNetworkResult,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void WifiNetworkConfigurationHandler::OnConfigureWifiNetworkResult(
chromeos::network_config::mojom::CrosNetworkConfig::ConfigureNetworkCallback
callback,
const absl::optional<std::string>& network_guid,
const std::string& error_message) {
if (network_guid) {
NS_LOG(VERBOSE) << __func__ << ": Successfully configured to network";
RecordNearbyShareWifiConfigurationResultMetric(/*success=*/true);
} else {
NS_LOG(WARNING) << __func__ << ": Failed to configure network because "
<< error_message;
RecordNearbyShareWifiConfigurationResultMetric(/*success=*/false);
}
std::move(callback).Run(network_guid, error_message);
}
| [
"[email protected]"
] | |
b75b156b12bbb78500f1c6042a8baa7918d20168 | eff175427c1a60ac7d0c14308d4278d93e2abe66 | /src/qtgui/mainwindow.cpp | fb63875807d1b49f0907ed01b921adc41558bad8 | [] | no_license | ellery92/lyucam | 29f60e67b354e04256b9ad926bebc3eaaf77b856 | 53f6f7d6678470a5ffde46951526148348634e08 | refs/heads/master | 2020-03-25T19:59:56.834158 | 2018-08-16T03:34:08 | 2018-08-16T03:34:08 | 144,110,523 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,778 | cpp | #include <QtWidgets>
#include "mainwindow.h"
#include <QAbstractTableModel>
#include <vector>
#include <string>
#include <rc_genicam_api/system.h>
#include <rc_genicam_api/interface.h>
#include <rc_genicam_api/device.h>
#include <rc_genicam_api/stream.h>
#include <rc_genicam_api/config.h>
#include <rc_genicam_api/exception.h>
#include <rc_genicam_api/pixel_formats.h>
#include <rc_genicam_api/image.h>
#include "imageviewer/image-viewer.h"
#include "tcontainer.h"
const QString system_keys[] =
{ "ID", "Ventdor", "Model", "Vendor version",
"TL type", "Pathname", "GenTL version"};
const QString interf_keys[] =
{ "ID", "Display Name", "TL type:"};
const QString device_keys[] =
{ "ID", "Vendor", "Model", "TL type", "Display name", "Aceess status",
"Serial number", "Version", "TS Frequency"};
struct imageRecvThreadParam {
std::thread th;
bool stop;
bool pause;
std::shared_ptr<rcg::Stream> stream;
pal::ImageViewer *imageViewer;
};
struct imageRecvThreadParam imageParam;
void imageRecvThreadFunc(struct imageRecvThreadParam *pImageParam)
{
while (!pImageParam->stop) {
const rcg::Buffer *buffer = pImageParam->stream->grab(1000);
if (buffer) {
if (!buffer->getIsIncomplete() && buffer->getImagePresent()) {
size_t width = buffer->getWidth();
size_t height = buffer->getHeight();
const unsigned char *p=static_cast<const unsigned char *>(buffer->getBase())+buffer->getImageOffset();
size_t px = buffer->getXPadding();
uint64_t format = buffer->getPixelFormat();
static QImage image;
size_t pstep;
switch (format) {
case Mono8:
if (image.isNull() || image.width() != width || image.height() != height
|| image.format() != QImage::Format_Grayscale8)
image = QImage(width, height, QImage::Format_Grayscale8);
for (size_t k=0; k<height; k++) {
memcpy(image.scanLine(k), p, width);
p += width + px;
}
break;
case YCbCr411_8: // convert and store as color image
pstep = (width>>2) * 6 + px;
if (image.isNull() || image.width() != width || image.height() != height
|| image.format() != QImage::Format_RGB888)
image = QImage(width, height, QImage::Format_RGB888);
for (size_t k=0; k<height; k++) {
uchar *data = image.scanLine(k);
for (size_t i=0; i<width; i+=4) {
uint8_t rgb[12];
rcg::convYCbCr411toQuadRGB(rgb, p, static_cast<int>(i));
for (int j=0; j<12; j++)
*data++ = static_cast<uchar>(rgb[j]);
}
p += pstep;
}
break;
default:
break;
}
pImageParam->imageViewer->setImage(image);
} else if (buffer->getIsIncomplete()) {
std::cerr << "storeBuffer(): Received incomplete buffer" << std::endl;
} else if (!buffer->getImagePresent()) {
std::cerr << "storeBuffer(): Received buffer without image" << std::endl;
}
}
}
}
RectLabel::RectLabel()
{
QTimer *timer = new QTimer(this);
QObject::connect(timer, &QTimer::timeout, [=] {
char tip[256];
QPoint pt = parentWidget()->mapToParent(pos());
QGraphicsView *imageView = (QGraphicsView*)parentWidget()->parentWidget();
QRect rc(pt.x(), pt.y(), size().width(), size().height());
QPolygonF polyf = imageView->mapToScene(rc);
QRectF rcf = polyf.boundingRect();
sprintf(tip, "(%d, %d, %d, %d)", (int)rcf.x(), (int)rcf.y(),
(int)rcf.width(), (int)rcf.height());
setText(tip);
});
timer->start(500);
}
MainWindow::MainWindow()
{
imageViewer = new pal::ImageViewer("", this);
setCentralWidget(imageViewer);
QLabel *lab1 = new RectLabel;
lab1->setStyleSheet("border: 1px solid red");
lab1->setAlignment(Qt::AlignLeft | Qt::AlignTop);
TContainer *con1 = new TContainer(imageViewer->getView(), QPoint(10, 10), lab1);
createDeviceWindow();
createActions();
}
void MainWindow::addFeatureNode(QTreeWidgetItem *parent, GenApi::INode *node)
{
if (node != 0) {
switch (node->GetPrincipalInterfaceType()) {
case GenApi::intfIValue:
break;
case GenApi::intfIBase:
break;
case GenApi::intfIInteger:
{
GenApi::IInteger *p=dynamic_cast<GenApi::IInteger *>(node);
if (GenApi::IsReadable(p))
addFeatureInt(parent, node);
break;
}
case GenApi::intfIBoolean:
{
GenApi::IBoolean *p=dynamic_cast<GenApi::IBoolean *>(node);
if (GenApi::IsReadable(p))
addFeatureBool(parent, node);
break;
}
case GenApi::intfICommand:
{
if (node->GetAccessMode() == GenApi::RW)
addFeatureCmd(parent, node);
break;
}
case GenApi::intfIFloat:
{
GenApi::IFloat *p=dynamic_cast<GenApi::IFloat *>(node);
if (GenApi::IsReadable(p))
addFeatureFloat(parent, node);
break;
}
case GenApi::intfIString:
{
GenApi::IString *p=dynamic_cast<GenApi::IString *>(node);
if (GenApi::IsReadable(p))
addFeatureString(parent, node);
break;
}
case GenApi::intfIRegister:
break;
case GenApi::intfICategory:
{
if (node->GetName() != "Root")
parent = addFeatureCategory(node);
GenApi::ICategory *root=dynamic_cast<GenApi::ICategory *>(node);
if (root != 0) {
GenApi::FeatureList_t feature;
root->GetFeatures(feature);
for (size_t i=0; i<feature.size(); i++)
addFeatureNode(parent, feature[i]->GetNode());
}
}
break;
case GenApi::intfIEnumeration:
{
GenApi::IEnumeration *p=dynamic_cast<GenApi::IEnumeration *>(node);
if (GenApi::IsReadable(p))
addFeatureEnum(parent, node);
break;
}
case GenApi::intfIEnumEntry:
break;
case GenApi::intfIPort:
break;
}
}
}
void MainWindow::onDeviceItemClicked(QTreeWidgetItem *item, int col)
{
std::cout << item->text(0).toStdString() << std::endl;
const QVariant &data = item->data(0, Qt::UserRole);
deviceInfoView->clear();
if (data.isNull())
return;
const QHash<QString, QVariant> &hash = data.toHash();
const QString &type = hash["type"].toString();
QString *keys = NULL;
int len = 0;
if ( type == "system") {
keys = (QString *)&system_keys;
len = sizeof(system_keys) / sizeof(system_keys[0]);
} else if (type == "interface") {
keys = (QString *)&interf_keys;
len = sizeof(interf_keys) / sizeof(interf_keys[0]);
} else if (type == "device") {
keys = (QString *)&device_keys;
len = sizeof(device_keys) / sizeof(device_keys[0]);
curDeviceID = hash["ID"].toString().toStdString();
}
for (int i = 0; i < len; i++)
deviceInfoView->addItem(keys[i] + ": " + hash[keys[i]].toString());
}
void MainWindow::updateDeviceTree()
{
deviceTree->clear();
std::vector<std::shared_ptr<rcg::System> > system=rcg::System::getSystems();
QHash<QString, QVariant> hash;
for (size_t i=0; i<system.size(); i++) {
try {
system[i]->open();
} catch (rcg::GenTLException &e) {
std::cout << e.what();
continue;
}
QTreeWidgetItem *sysitem = new QTreeWidgetItem(deviceTree);
sysitem->setText(0, system[i]->getID().c_str());
hash.clear();
hash["type"] = "system";
int n = 0;
hash[system_keys[n++]] = system[i]->getID().c_str();
hash[system_keys[n++]] = system[i]->getVendor().c_str();
hash[system_keys[n++]] = system[i]->getModel().c_str();
hash[system_keys[n++]] = system[i]->getVersion().c_str();
hash[system_keys[n++]] = system[i]->getTLType().c_str();
hash[system_keys[n++]] = system[i]->getPathname().c_str();
hash[system_keys[n++]] = system[i]->getMajorVersion();
sysitem->setData(0, Qt::UserRole, QVariant(hash));
std::vector<std::shared_ptr<rcg::Interface> > interf=system[i]->getInterfaces();
for (size_t k=0; k<interf.size(); k++) {
try {
interf[k]->open();
} catch (rcg::GenTLException &e) {
std::cout << e.what();
continue;
}
QTreeWidgetItem *interfitem = new QTreeWidgetItem(sysitem);
interfitem->setText(0, interf[k]->getDisplayName().c_str());
hash.clear();
hash["type"] = "interface";
int n = 0;
hash[interf_keys[n++]] = interf[k]->getID().c_str();
hash[interf_keys[n++]] = interf[k]->getDisplayName().c_str();
hash[interf_keys[n++]] = interf[k]->getTLType().c_str();
interfitem->setData(0, Qt::UserRole, QVariant(hash));
std::vector<std::shared_ptr<rcg::Device> > device=interf[k]->getDevices();
for (size_t j=0; j<device.size(); j++) {
QTreeWidgetItem *devitem = new QTreeWidgetItem(interfitem);
devitem->setText(0, device[j]->getDisplayName().c_str());
if (curDeviceID.empty())
setCurDevice(device[j]->getID());
hash.clear();
hash["type"] = "device";
int n = 0;
hash[device_keys[n++]] = device[j]->getID().c_str();
hash[device_keys[n++]] = device[j]->getVendor().c_str();
hash[device_keys[n++]] = device[j]->getModel().c_str();
hash[device_keys[n++]] = device[j]->getTLType().c_str();
hash[device_keys[n++]] = device[j]->getDisplayName().c_str();
hash[device_keys[n++]] = device[j]->getAccessStatus().c_str();
hash[device_keys[n++]] = device[j]->getSerialNumber().c_str();
hash[device_keys[n++]] = device[j]->getVersion().c_str();
hash[device_keys[n++]] = (qulonglong)device[j]->getTimestampFrequency();
devitem->setData(0, Qt::UserRole, QVariant(hash));
}
interf[k]->close();
}
system[i]->close();
}
}
void MainWindow::setCurDevice(std::string const &dev)
{
curDeviceID = dev;
if (curActiveDeviceID.empty()) {
if (!curDeviceID.empty())
connAct->setEnabled(true);
else
connAct->setEnabled(false);
}
}
void MainWindow::setCurActiveDevice(std::string const &dev)
{
curActiveDeviceID = dev;
if (!curActiveDeviceID.empty()) {
connAct->setEnabled(false);
disconnAct->setEnabled(true);
} else {
connAct->setEnabled(true);
disconnAct->setEnabled(false);
}
}
MainWindow::~MainWindow() {
}
void MainWindow::createActions()
{
toolbar = new QToolBar();
QList<QByteArray> formats = QImageReader::supportedImageFormats();
QStringList list;
for (auto &fmt : formats)
list.append("*." + QString(fmt));
auto filter = "Images (" + list.join(" ") + ")";
toolbar->addAction(QIcon("data/icons/open_file.png"), "update",[=] {
QString path = QFileDialog::getOpenFileName(nullptr, "Pick an image file",nullptr, filter);
if (path.isEmpty())
return;
imageViewer->setImage(QImage(path));
});
updateAct = toolbar->addAction(QIcon("data/icons/update.png"), "update",
this, &MainWindow::updateDeviceTree);
connAct = toolbar->addAction(QIcon("data/icons/connect.png"), "connect",
this, &MainWindow::openDevice);
connAct->setEnabled(false);
disconnAct = toolbar->addAction(QIcon("data/icons/disconnect.png"), "disconnect",
this, &MainWindow::closeDevice);
disconnAct->setEnabled(false);
toolbar->addAction(QIcon("data/icons/device_attribute.png"), "device attribute",
[=] { deviceDock->setVisible(!deviceDock->isVisible()); });
imageStartAct = toolbar->addAction(QIcon("data/icons/start_acquisition.png"),
"start acquisition", [=] {
if (imageParam.pause) {
imageParam.pause = false;
imageStartAct->setEnabled(false);
imageStopAct->setEnabled(true);
imagePauseAct->setEnabled(true);
return;
}
std::shared_ptr<rcg::Device> dev=rcg::getDevice(curActiveDeviceID.c_str());
if (dev) {
std::vector<std::shared_ptr<rcg::Stream> > stream=dev->getStreams();
if (stream.size() > 0) {
// opening first stream
try {
stream[0]->open();
stream[0]->startStreaming();
imageParam.stop = false;
imageParam.pause = false;
imageParam.stream = stream[0];
imageParam.imageViewer = this->imageViewer;
imageParam.th = std::thread(imageRecvThreadFunc, &imageParam);
imageStartAct->setEnabled(false);
imageStopAct->setEnabled(true);
imagePauseAct->setEnabled(true);
} catch (rcg::GenTLException &e) {
std::cout << e.what() << std::endl;
}
}
}
});
imagePauseAct = toolbar->addAction(QIcon("data/icons/pause.png"), "pause", [=] {
imageParam.pause = true;
imageStartAct->setEnabled(true);
imagePauseAct->setEnabled(false);
imageStopAct->setEnabled(false);
});
imageStopAct = toolbar->addAction(QIcon("data/icons/stop_acquisition.png"),
"stop acquisition", [=] {
std::shared_ptr<rcg::Device> dev=rcg::getDevice(curActiveDeviceID.c_str());
if (dev) {
std::vector<std::shared_ptr<rcg::Stream> > stream=dev->getStreams();
if (stream.size() > 0) {
imageParam.stop = true;
imageParam.th.join();
stream[0]->stopStreaming();
stream[0]->close();
}
}
imageStartAct->setEnabled(true);
imageStopAct->setEnabled(false);
imagePauseAct->setEnabled(false);
});
addToolBar(toolbar);
}
void MainWindow::createDeviceWindow()
{
deviceDock = new QDockWidget(tr("Device Infomation"), this);
deviceDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
QTabWidget *tab = new QTabWidget(deviceDock);
deviceDock->setWidget(tab);
QWidget *pageDevice = new QWidget();
tab->addTab(pageDevice, "Device");
QVBoxLayout *deviceLayout = new QVBoxLayout();
deviceTree = new QTreeWidget;
deviceLayout->addWidget(deviceTree);
QObject::connect(deviceTree, &QTreeWidget::itemClicked,
this, &MainWindow::onDeviceItemClicked);
deviceInfoView = new QListWidget();
deviceLayout->addWidget(deviceInfoView);
pageDevice->setLayout(deviceLayout);
featureTree = new QTreeWidget;
featureTree->setColumnCount(2);
featureTree->setSelectionMode(QAbstractItemView::NoSelection);
featureTree->setFocusPolicy(Qt::NoFocus);
tab->addTab(featureTree, "Feature");
addDockWidget(Qt::RightDockWidgetArea, deviceDock);
}
void MainWindow::openDevice()
{
try {
std::shared_ptr<rcg::Device> dev=rcg::getDevice(curDeviceID.c_str());
if (dev) {
dev->open(rcg::Device::CONTROL);
setCurActiveDevice(curDeviceID);
std::shared_ptr<GenApi::CNodeMapRef> nodemap = dev->getRemoteNodeMap();
addFeatureNode(NULL, nodemap->_GetNode("Root"));
}
} catch (rcg::GenTLException &e) {
std::cout << e.what();
}
}
void MainWindow::closeDevice()
{
try {
std::shared_ptr<rcg::Device> dev=rcg::getDevice(curActiveDeviceID.c_str());
if (dev) {
dev->close();
setCurActiveDevice("");
featureTree->clear();
}
} catch (rcg::GenTLException &e) {
std::cout << e.what();
}
}
QTreeWidgetItem *MainWindow::addFeatureCategory(GenApi::INode *node)
{
QTreeWidgetItem *topitem = new QTreeWidgetItem(featureTree);
topitem->setText(0, node->GetName().c_str());
return topitem;
}
QTreeWidgetItem* MainWindow::addFeatureInt(QTreeWidgetItem *parent, GenApi::INode *node)
{
QTreeWidgetItem *item = new QTreeWidgetItem(parent);
item->setText(0, node->GetName().c_str());
QWidget *widget = new QWidget();
QHBoxLayout *layout = new QHBoxLayout();
widget->setLayout(layout);
GenApi::IInteger *p=dynamic_cast<GenApi::IInteger *>(node);
QSlider *slider = new QSlider(Qt::Horizontal);
slider->setMinimum(p->GetMin());
slider->setMaximum(p->GetMax());
slider->setValue(p->GetValue());
slider->setSingleStep(p->GetInc());
QSpinBox *spinBox = new QSpinBox();
spinBox->setMinimum(p->GetMin());
spinBox->setMaximum(p->GetMax());
spinBox->setValue(p->GetValue());
spinBox->setSingleStep(p->GetInc());
QObject::connect(slider, &QSlider::valueChanged,
[=](int v) { spinBox->setValue(v); p->SetValue(v); });
QObject::connect(spinBox, QOverload<int>::of(&QSpinBox::valueChanged),
[=](int v) { slider->setValue(v); p->SetValue(v); });
if (!GenApi::IsWritable(p)) {
slider->setEnabled(false);
spinBox->setEnabled(false);
}
layout->addWidget(slider);
layout->addWidget(spinBox);
featureTree->setItemWidget(item, 1, widget);
return item;
}
QTreeWidgetItem *MainWindow::addFeatureFloat(QTreeWidgetItem *parent, GenApi::INode *node)
{
QTreeWidgetItem *item = new QTreeWidgetItem(parent);
item->setText(0, node->GetName().c_str());
QWidget *widget = new QWidget();
QHBoxLayout *layout = new QHBoxLayout();
widget->setLayout(layout);
GenApi::IFloat *p=dynamic_cast<GenApi::IFloat *>(node);
QSlider *slider = new QSlider(Qt::Horizontal);
slider->setMinimum(p->GetMin());
slider->setMaximum(p->GetMax());
slider->setValue(p->GetValue());
slider->setSingleStep(p->GetInc());
QDoubleSpinBox *spinBox = new QDoubleSpinBox;
spinBox->setMinimum(p->GetMin());
spinBox->setMaximum(p->GetMax());
spinBox->setValue(p->GetValue());
spinBox->setSingleStep(p->GetInc());
QObject::connect(slider, &QSlider::valueChanged,
[=](int v) { spinBox->setValue(v); p->SetValue(v); });
QObject::connect(spinBox, QOverload<double>::of(&QDoubleSpinBox::valueChanged),
[=](double v) { slider->setValue(v); p->SetValue(v); });
if (!GenApi::IsWritable(p)) {
slider->setEnabled(false);
spinBox->setEnabled(false);
}
layout->addWidget(slider);
layout->addWidget(spinBox);
featureTree->setItemWidget(item, 1, widget);
return item;
}
QTreeWidgetItem *MainWindow::addFeatureBool(QTreeWidgetItem *parent, GenApi::INode *node)
{
QTreeWidgetItem *item = new QTreeWidgetItem(parent);
item->setText(0, node->GetName().c_str());
QWidget *widget = new QWidget();
QHBoxLayout *layout = new QHBoxLayout();
widget->setLayout(layout);
QCheckBox *checkBox = new QCheckBox;
GenApi::IBoolean *p=dynamic_cast<GenApi::IBoolean *>(node);
checkBox->setCheckState(p->GetValue() ? Qt::Checked : Qt::Unchecked);
if (!GenApi::IsWritable(p))
checkBox->setEnabled(false);
layout->addWidget(checkBox);
featureTree->setItemWidget(item, 1, widget);
return item;
}
QTreeWidgetItem *MainWindow::addFeatureEnum(QTreeWidgetItem *parent, GenApi::INode *node)
{
QTreeWidgetItem *item = new QTreeWidgetItem(parent);
item->setText(0, node->GetName().c_str());
QWidget *widget = new QWidget();
QHBoxLayout *layout = new QHBoxLayout();
widget->setLayout(layout);
QComboBox *comboBox = new QComboBox();
GenApi::IEnumeration *p=dynamic_cast<GenApi::IEnumeration *>(node);
GenApi::StringList_t list;
p->GetSymbolics(list);
for (size_t i=0; i<list.size(); i++)
comboBox->addItem(list[i].c_str());
if (p->GetCurrentEntry() != 0)
comboBox->setCurrentText(p->GetCurrentEntry()->GetSymbolic().c_str());
if (!GenApi::IsWritable(p))
comboBox->setEnabled(false);
layout->addWidget(comboBox);
featureTree->setItemWidget(item, 1, widget);
return item;
}
QTreeWidgetItem *MainWindow::addFeatureCmd(QTreeWidgetItem *parent, GenApi::INode *node)
{
QTreeWidgetItem *item = new QTreeWidgetItem(parent);
item->setText(0, node->GetName().c_str());
QWidget *widget = new QWidget();
QHBoxLayout *layout = new QHBoxLayout();
widget->setLayout(layout);
QPushButton *btn = new QPushButton("Execute");
layout->addWidget(btn);
featureTree->setItemWidget(item, 1, widget);
return item;
}
QTreeWidgetItem *MainWindow::addFeatureString(QTreeWidgetItem *parent, GenApi::INode *node)
{
QTreeWidgetItem *item = new QTreeWidgetItem(parent);
item->setText(0, node->GetName().c_str());
QWidget *widget = new QWidget();
QHBoxLayout *layout = new QHBoxLayout();
widget->setLayout(layout);
GenApi::IString *p=dynamic_cast<GenApi::IString *>(node);
QLineEdit *lineEdit = new QLineEdit();
lineEdit->setText(p->GetValue().c_str());
layout->addWidget(lineEdit);
// if (!GenApi::IsWritable(p))
lineEdit->setReadOnly(true);
featureTree->setItemWidget(item, 1, widget);
return item;
}
| [
"[email protected]"
] | |
b50dcee4f8451f6b5c30edeb3e8e14c4a21ace76 | 5d87019542fd6d61116ad55c63978f7672e5b781 | /BtnKeepPress/BtnKeepPress.cpp | 59fd725d4313f92126d844a8b97cc8dcd14eaec5 | [] | no_license | Autumn-X/QtDemo | 7d2b4c30172ff428218142219924277de6af1d21 | c7512e319ada0c2a33fcefc795934bfbdd487f3e | refs/heads/master | 2021-07-09T12:20:16.703453 | 2017-09-29T08:38:55 | 2017-09-29T08:38:55 | 104,846,651 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,632 | cpp | #include "BtnKeepPress.h"
#include "ui_BtnKeepPress.h"
BtnKeepPress::BtnKeepPress(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::BtnKeepPress)
{
ui->setupUi(this);
m_auto_repeat_count = 0;
m_self_inc = 1;
m_value = 0;
ui->btnDec->setAutoRepeat(true); // 设置按钮自动重复点击事件
ui->btnInc->setAutoRepeat(true);
qApp->installEventFilter(this); // 安装事件过虑器
}
BtnKeepPress::~BtnKeepPress()
{
qApp->removeEventFilter(this);
delete ui;
}
bool BtnKeepPress::eventFilter(QObject *watched, QEvent *event)
{
QList<QPushButton *> btnMove; // 记录要监控的按钮
btnMove.append(ui->btnDec);
btnMove.append(ui->btnInc);
foreach (QPushButton * L, btnMove){
if ((L->objectName() == watched->objectName())){
if (event->type() == QEvent::MouseButtonRelease){
if (!((QKeyEvent *)event)->isAutoRepeat()){ // 按钮松开
m_auto_repeat_count = 0;
m_self_inc = 1;
}
}
}
}
return QWidget::eventFilter(watched, event);
}
void BtnKeepPress::SeleIncValuePro()
{
if (m_self_inc < m_inc_max){
++ m_auto_repeat_count;
m_self_inc += m_auto_repeat_count / 10;
}else{
m_self_inc = m_inc_max;
}
}
void BtnKeepPress::SetValue(int value)
{
m_value += value;
ui->labelValue->setText(QString::number(m_value));
}
void BtnKeepPress::on_btnDec_clicked()
{
SeleIncValuePro();
SetValue(-m_self_inc);
}
void BtnKeepPress::on_btnInc_clicked()
{
SeleIncValuePro();
SetValue(m_self_inc);
}
| [
"[email protected]"
] | |
2a5282c234862b843a96fe62ef36ed7bbf8d60dc | 055e78502297026a4ca9b340f25ee1c678e6ca9d | /OccTry-vc14-64/Command/ScCmdFFD.h | 8523154b80a6871b3d6bbd93b51ac2b2f9c1c6cb | [] | no_license | ymqhyq/OccTry-vc14 | 1ceb759720fcd405e7b82de826f80e71a0713b76 | a80ffe78211e2c4659e6f7be6be4736997d46417 | refs/heads/master | 2020-12-22T11:46:22.993613 | 2020-01-29T01:58:29 | 2020-01-29T01:58:29 | 236,754,637 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,173 | h | #pragma once
#include "ScCommand.h"
//变形控制器.
//要支持在UCS中的变形,需要注意CS的转换。
class TcFFDFrame{
public:
TcFFDFrame();
//是否在变形范围内
BOOL InRange(const gp_Pnt& pnt);
//1点变形
BOOL DeformPnt(const gp_Pnt& pnt,gp_Pnt& respnt);
//计算局部坐标
gp_Pnt CalcLcsCoord(const gp_Pnt& pnt);
int Index(int ix,int iy,int iz);
public:
int _l,_m,_n;//局部坐标系中,x、y、z方向的分割数。
int _tcnt;//总点个数
STR3D _ctlpnts;//变形控制点的坐标,WCS。
STR3D _ffdpnts;//ffd改变后的坐标
// gp_Ax2 _lcs;//Frame局部坐标系
gp_Vec _Sx,_Ty,_Uz;//局部坐标系的三个向量
PNT3D _min;
PNT3D _max;//最小和最大两个点的坐标。
gp_Ax2 _ucs;//用户坐标系,在该坐标系内部,是一个box,但在wcs下,则未必了。
};
class ScCmdFFD : public ScCommand
{
public:
ScCmdFFD(void);
~ScCmdFFD(void);
//启动和结束命令
virtual int Begin(Handle(AIS_InteractiveContext) aCtx);
virtual int End();
//点选方式下的消息响应函数
virtual void InputEvent(const CPoint& point,int nState,
const Handle(V3d_View)& aView);
//鼠标移动的响应函数
virtual void MoveEvent(const CPoint& point,
const Handle(V3d_View)& aView);
protected:
//比较漫长的过程。复杂的处理
enum{S_OBJECT,S_PNT1,S_PNT2,S_PNT3,S_OPTION,S_SELPNT,S_BASPNT,S_NEWPNT};
BOOL HasSelObj();
BOOL MakeFFDFrame();
BOOL ShowRect(gp_Pnt pnt1,gp_Pnt pnt2);
BOOL ShowBox(gp_Pnt pnt1,gp_Pnt pnt2,gp_Pnt pnt3);
BOOL CalcBoxCorner(gp_Pnt pnt1,gp_Pnt pnt2,gp_Pnt pnt3);
BOOL ShowChangeFrame(gp_Pnt newpnt);
BOOL FindPnts(PNT3D pnt);
BOOL MakeFFD(BOOL bDone);
TopoDS_Face DeformFace(const TopoDS_Face& aFace);
TopoDS_Shape SewFaces(const TopoDS_Compound& aC);
TopoDS_Shape DeformFaceWire(const TopoDS_Face& aFace,const TopoDS_Face& aNewFace);
TopoDS_Face BuildDeformedFace(const Handle(Geom_Surface)& aNewSurf,const TopoDS_Face& aFace);
TopoDS_Wire BuildDeformedWire(const TopoDS_Wire& aWire,
const Handle(Geom_Surface)& aNewSurf,const TopoDS_Face& aFace);
TcFFDFrame m_ffdFrame;//变形控制器
gp_Pnt m_pnt1,m_pnt2,m_pnt3;
PNT3D m_boxCorner[8];//
TopTools_SequenceOfShape m_seqOfV;//选中的点
gp_Pnt m_ptBas;
};
//两个修改类。从Occ中继承
DEFINE_STANDARD_HANDLE(ScFFD_Modification,BRepTools_Modification)
class ScFFD_Modification : public BRepTools_Modification{
public:
ScFFD_Modification();
void SetFFDFrame(TcFFDFrame *pFrm) { m_ffdFrame = pFrm; }
virtual Standard_Boolean NewSurface(
const TopoDS_Face& F,
Handle(Geom_Surface)& S,
TopLoc_Location& L,
Standard_Real& Tol,
Standard_Boolean& RevWires,
Standard_Boolean& RevFace);
virtual Standard_Boolean NewCurve(
const TopoDS_Edge& E,
Handle(Geom_Curve)& C,
TopLoc_Location& L,
Standard_Real& Tol);
virtual Standard_Boolean NewPoint(
const TopoDS_Vertex& V,
gp_Pnt& P,
Standard_Real& Tol);
virtual Standard_Boolean NewCurve2d(
const TopoDS_Edge& E,
const TopoDS_Face& F,
const TopoDS_Edge& NewE,
const TopoDS_Face& NewF,
Handle(Geom2d_Curve)& C,
Standard_Real& Tol);
virtual Standard_Boolean NewParameter(
const TopoDS_Vertex& V,
const TopoDS_Edge& E,
Standard_Real& P,
Standard_Real& Tol) ;
virtual GeomAbs_Shape Continuity(
const TopoDS_Edge& E,
const TopoDS_Face& F1,
const TopoDS_Face& F2,
const TopoDS_Edge& NewE,
const TopoDS_Face& NewF1,
const TopoDS_Face& NewF2) ;
protected:
//yxk20200104
//DEFINE_STANDARD_RTTI(ScFFD_Modification)
DEFINE_STANDARD_RTTIEXT(ScFFD_Modification,BRepTools_Modification)
//endyxk
protected:
TcFFDFrame *m_ffdFrame;
};
class TcFFDeformShape : public BRepBuilderAPI_ModifyShape {
public:
void* operator new(size_t,void* anAddress)
{
return anAddress;
}
void* operator new(size_t size)
{
return Standard::Allocate(size);
}
void operator delete(void *anAddress)
{
if (anAddress) Standard::Free((Standard_Address&)anAddress);
}
TcFFDeformShape();
void Perform(const TopoDS_Shape& S,TcFFDFrame *pFrm);
}; | [
"[email protected]"
] | |
c31d35868808efa619b5c14917b722b738cda841 | d52370be4993dea78904227a215920855d627473 | /src/ShowWelcomeUseCase/domain/ShowWelcomeUseCase.h | 1cb2f9076136177ab9836e4e3d7fdfcd9130176f | [] | no_license | Self-fish/the-machine | db9c06e0888654e7adcdc121b15faf4a0aed5ca3 | 8355b745902c00ec80f86b04243771f7d3760d82 | refs/heads/master | 2021-01-02T11:19:32.940680 | 2020-03-02T21:18:14 | 2020-03-02T21:18:14 | 239,598,381 | 0 | 0 | null | 2020-02-24T21:39:39 | 2020-02-10T19:46:04 | C++ | UTF-8 | C++ | false | false | 326 | h | #ifndef ShowWelcomeUseCase_h
#define ShowWelcomeUseCase_h
#include "../controller/WelcomeScreenController.h"
class ShowWelcomeUseCase {
public:
ShowWelcomeUseCase(WelcomeScreenController* lController);
void showScreen();
private:
WelcomeScreenController* welcomeScreenController;
void freeResources();
};
#endif
| [
"[email protected]"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.