blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
247
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 4
111
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
58
| visit_date
timestamp[ns]date 2015-07-25 18:16:41
2023-09-06 10:45:08
| revision_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| github_id
int64 3.89k
689M
โ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 25
values | gha_event_created_at
timestamp[ns]date 2012-06-07 00:51:45
2023-09-14 21:58:52
โ | gha_created_at
timestamp[ns]date 2008-03-27 23:40:48
2023-08-24 19:49:39
โ | gha_language
stringclasses 159
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
10.5M
| extension
stringclasses 111
values | filename
stringlengths 1
195
| text
stringlengths 7
10.5M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
441d2b73f2b4576dda72cd6a02957f1cab34dc5d
|
5b94cf771f7150bf1ebac3b51b76a306622529a8
|
/orockets.h
|
74f2567c1a5a84552bbd04d6be591887e21afa33
|
[] |
no_license
|
erezsh/zodengine
|
79dc8b2825d5a751587c154ec9ca3e9ab3023b38
|
27d29020b9a187a090860e21bf52f8e7a91771e7
|
refs/heads/master
| 2023-09-03T09:16:49.748391
| 2013-04-13T11:25:02
| 2013-04-13T11:25:17
| 5,296,561
| 7
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 384
|
h
|
orockets.h
|
#ifndef _OROCKETS_H_
#define _OROCKETS_H_
#include "zobject.h"
class ORockets : public ZObject
{
public:
ORockets(ZTime *ztime_, ZSettings *zsettings_ = NULL);
static void Init();
void DoRender(ZMap &the_map, SDL_Surface *dest, int shift_x = 0, int shift_y = 0);
int Process();
void SetOwner(team_type owner_);
private:
static ZSDL_Surface render_img;
};
#endif
|
4b28038514e361eb728fa681844b0f3197a8a930
|
c07410a5b42cbdd6f72c36089c455bdde557bc29
|
/include/MS.h
|
3f0de2ff092e0bce9007da2888b87e875df4f5f6
|
[] |
no_license
|
SmithJrBlaquaLuigi/Corona
|
1e10357910be193ce58da52971b76fa792203cd2
|
93fe3509f272c22103841f2e5b172670b339dddb
|
refs/heads/master
| 2020-03-17T07:44:02.148208
| 2018-05-07T16:53:25
| 2018-05-07T16:53:25
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 553
|
h
|
MS.h
|
#ifndef MS_H
#define MS_H
#include "JGeometry.h"
#include "types.h"
using namespace JGeometry;
// a bunch of functions starting with "Ms" that I feel are important to document
f32 MsVECMag2(Vec *);
void MsVECNormalize(Vec *, Vec *);
bool MsIsInSight(TVec3<f32> const &, f32, TVec3<f32> const &, f32, f32, f32);
void MsMtxSetTRS(f32 *[4], f32, f32, f32, f32, f32, f32, f32, f32, f32);
void MsMtxSetXYZRPH(f32 *[4], f32, f32, f32, u16, u16, u16);
void MsMtxSetRotRPH(f32 *[4], f32, f32, f32);
void MsGetRotFromZaxis(TVec3<f32> const &);
#endif // MS_H
|
6378e9fbea9459a0f1419834fdd1be9add866b75
|
9cbef3a40c13ac2505e875ce3c7654111ec699a0
|
/Zombie/Zombie/Surviviour.cpp
|
3ac548b9a845f635f9fa2850fae5dccd2e105187
|
[] |
no_license
|
SeanBrennan645/Old-Code-Projects
|
1d991dc517ef7702d4f847e9a5136a94c616f183
|
cf4e8cb3a537490bbf5760980283406024aa62d1
|
refs/heads/main
| 2023-07-10T01:23:40.092676
| 2021-08-07T13:27:04
| 2021-08-07T13:27:04
| 393,689,787
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,425
|
cpp
|
Surviviour.cpp
|
#include "Surviviour.h"
Surviviour::Surviviour()
{
//sets symbol
setName('S');
}
Surviviour::~Surviviour()
{
}
//checks if zombie has killed survivor
void Surviviour::checkIfEaten(int zombieYPos, int zombieXPos)
{
if ((zombieYPos == getYPos()) && (zombieXPos == getXPos()))
{
kill();
}
}
//checks if player has saved survivor
void Surviviour::checkIfSaved(int playerYPos, int playerXPos)
{
if ((playerYPos == getYPos()) && (playerXPos == getXPos()))
{
kill();
}
}
void Surviviour::relocate()
{
/*when status is set to 0 surviors coordinates are set to 0,0
this removes them from the map so the player can't pick
up several survivors from one position*/
if (checkStatus() == 0)
{
setPrev();
clearPrev();
changeX((-getXPos()));
changeY((-getYPos()));
}
}
//checks that survivor hasn't spawned on a manhole
void Surviviour::checkManholes(int manholeY, int manholeX, int gridSize)
{
while ((manholeY == getYPos()) && (manholeX == getXPos()))
{
setPos(gridSize);
}
}
//checks that survivor hasn't spawned on a zombie
void Surviviour::checkZombies(int zombieY, int zombieX, int gridSize)
{
while ((zombieY == getYPos()) && (zombieX == getXPos()))
{
setPos(gridSize);
}
}
//checks that survivor hasn't spawned on player
void Surviviour::checkSpawn(int playerYPos, int playerXPos, int gridSize)
{
while ((playerYPos == getYPos()) && (playerXPos == getXPos()))
{
setPos(gridSize);
}
}
|
05c6fb308162fa145b5aa1fa93f103f87cfa07c2
|
6b7d28bb7a3f5bdf40050dfce1f5c49d8560841d
|
/tests/gen.cpp
|
d3ae95d412980d0bd2d00a28ceaf90b3e5189db6
|
[
"MIT"
] |
permissive
|
Es7evam/Knapsack-AI
|
e9c5ea3a2f980f1d86ea7c016e24e02c9bf7e1f5
|
6a41ef5d57025bbe1139fce8d2280320b54ed635
|
refs/heads/master
| 2020-05-04T11:43:59.642055
| 2019-04-22T01:19:29
| 2019-04-22T01:19:29
| 179,114,232
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 635
|
cpp
|
gen.cpp
|
#include <bits/stdc++.h>
using namespace std;
int main(void){
int n;
double sz;
vector<pair<double, double>> v;
srand(time(NULL));
string filename;
for(int i=8;i<=800;i++){
filename = to_string(i) + "-test.txt";
freopen(filename.c_str(), "w", stdout);
// Gerar tamanho da nro de itens e tamanho da mochila
n = (rand()%20)+8;
sz = (double)(rand()%100000)/10.0;
// Gerar cada item
double value, weight;
cout << n << " " << sz << endl;
for(int j=0;j<n;j++){
value = (double)(rand()%100000)/10.0;
weight = (double)(rand()%23000)/10.0;
weight += 700;
cout << value << " " << weight << endl;
}
}
}
|
bb32043dfe14316e14836c17952737cd2e791c04
|
d88810476d3ee4d828e68e05d67b5f2e297f799c
|
/components/pango_python/src/pyinterpreter.cpp
|
a9d091d6e5d02dcad4cd572164415769bd9f5b65
|
[
"MIT"
] |
permissive
|
stevenlovegrove/Pangolin
|
b84830b8a0d065ff5e76cbc4b8b229d639ab11c8
|
d484494645cb7361374ac0ef6b27e9ee6feffbd7
|
refs/heads/master
| 2023-09-03T03:29:38.010162
| 2023-05-30T17:30:27
| 2023-06-06T20:11:04
| 1,096,480
| 2,151
| 960
|
MIT
| 2023-06-28T21:39:24
| 2010-11-20T01:50:32
|
C++
|
UTF-8
|
C++
| false
| false
| 6,854
|
cpp
|
pyinterpreter.cpp
|
/* This file is part of the Pangolin Project.
* http://github.com/stevenlovegrove/Pangolin
*
* Copyright (c) 2011 Steven Lovegrove
*
* 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 <pangolin/python/pyinterpreter.h>
#include <pangolin/utils/file_utils.h>
#include <pangolin/var/varextra.h>
#include <pangolin/factory/factory_registry.h>
#include <pybind11/embed.h>
namespace py = pybind11;
#include "pypangolin/pypangoio.h"
namespace pangolin
{
void PyInterpreter::NewVarCallback(const pangolin::VarState::Event& e)
{
if(e.action == VarState::Event::Action::Added) {
const std::string name = e.var->Meta().full_name;
const size_t dot = name.find_first_of('.');
if(dot != std::string::npos) {
const std::string base_prefix = name.substr(0,dot);
if( base_prefixes.find(base_prefix) == base_prefixes.end() ) {
base_prefixes.insert(base_prefix);
std::string cmd =
base_prefix + std::string(" = pypangolin.Var('") +
base_prefix + std::string("')\n");
PyRun_SimpleString(cmd.c_str());
}
}
}
}
PyInterpreter::PyInterpreter()
{
using namespace py_pangolin;
auto pypangolin = py::module_::import("pypangolin");
auto sys = py::module_::import("sys");
if(sys) {
// TODO: What is the lifetime of PyPangoIO?
PyPangoIO* wrap_stdout = new PyPangoIO(line_queue, ConsoleLineTypeStdout);
PyPangoIO* wrap_stderr = new PyPangoIO(line_queue, ConsoleLineTypeStderr);
sys.add_object("stdout", py::cast(wrap_stdout), true);
sys.add_object("stderr", py::cast(wrap_stderr), true);
} else {
pango_print_error("Couldn't import module sys.\n");
}
// Attempt to setup readline completion
py::exec(
"import pypangolin\n"
"try:\n"
" import readline\n"
"except ImportError:\n"
" import pyreadline as readline\n"
"\n"
"import rlcompleter\n"
"pypangolin.completer = rlcompleter.Completer()\n"
);
CheckPrintClearError();
// Get reference to rlcompleter.Completer() for tab-completion
pycompleter = pypangolin.attr("completer");
pycomplete = pycompleter.attr("complete");
// Register for notifications on var additions
var_added_connection = VarState::I().RegisterForVarEvents(
std::bind(&PyInterpreter::NewVarCallback,this,std::placeholders::_1),
true
);
CheckPrintClearError();
// TODO: For some reason the completion will crash when the command contains '.'
// unless we have executed anything that returns a value...
// We probably have a PyRef issue, maybe?
py::eval<py::eval_single_statement>("import sys");
py::eval<py::eval_single_statement>("sys.version");
}
PyInterpreter::~PyInterpreter()
{
}
std::string PyInterpreter::ToString(const py::object& py)
{
auto pystr = py::repr(py);
return std::string(PyUnicode_AsUTF8(pystr.ptr()));
}
void PyInterpreter::CheckPrintClearError()
{
if(PyErr_Occurred()) {
PyErr_Print();
PyErr_Clear();
}
}
py::object PyInterpreter::EvalExec(const std::string& cmd)
{
py::object ret = py::none();
if(!cmd.empty()) {
try {
ret = py::eval(cmd);
} catch (const pybind11::error_already_set& e) {
line_queue.push(
InterpreterLine(e.what(), ConsoleLineTypeStderr)
);
}
CheckPrintClearError();
}
return ret;
}
std::vector<std::string> PyInterpreter::Complete(const std::string& cmd, int max_options)
{
// TODO: When there is exactly 1 completion and it is smaller than our current string, we must invoke again with the prefix removed.
std::vector<std::string> ret;
PyErr_Clear();
if(pycomplete) {
for(int i=0; i < max_options; ++i) {
auto args = PyTuple_Pack( 2, PyUnicode_FromString(cmd.c_str()), PyLong_FromSize_t(i) );
auto result = PyObject_CallObject(pycomplete.ptr(), args);
if (result && PyUnicode_Check(result)) {
std::string res_str(PyUnicode_AsUTF8(result));
ret.push_back( res_str );
Py_DecRef(args);
Py_DecRef(result);
}else{
Py_DecRef(args);
Py_DecRef(result);
break;
}
}
}
return ret;
}
void PyInterpreter::PushCommand(const std::string& cmd)
{
if(!cmd.empty()) {
try {
py::eval<py::eval_single_statement>(cmd);
} catch (const pybind11::error_already_set& e) {
line_queue.push(
InterpreterLine(e.what(), ConsoleLineTypeStderr)
);
}
}
}
bool PyInterpreter::PullLine(InterpreterLine& line)
{
if(line_queue.size()) {
line = line_queue.front();
line_queue.pop();
return true;
}else{
return false;
}
}
PANGOLIN_REGISTER_FACTORY_WITH_STATIC_INITIALIZER(PyInterpreter)
{
struct PyInterpreterFactory final : public TypedFactoryInterface<InterpreterInterface> {
std::map<std::string,Precedence> Schemes() const override
{
return {{"python",10}};
}
const char* Description() const override
{
return "Python line interpreter.";
}
ParamSet Params() const override
{
return {{}};
}
std::unique_ptr<InterpreterInterface> Open(const Uri& /*uri*/) override {
return std::unique_ptr<InterpreterInterface>(new PyInterpreter());
}
};
return FactoryRegistry::I()->RegisterFactory<InterpreterInterface>(std::make_shared<PyInterpreterFactory>());
}
}
|
fcce856a3d8ef403496c410edb03f3847c67704c
|
44e0809e73874e8d40ce5c1bdcbb2d9277bf7fb0
|
/dev/isct_orientation3d/OrientImage.h
|
ea73aef9343919392a0044e70f9f0973f3725425
|
[
"MIT"
] |
permissive
|
PaulBautin/spinalcordtoolbox
|
05e1e99c6929e45ee134114870e28c5b2e5346b3
|
81ebad505180ab18270eb926cca4a134996f8c45
|
refs/heads/master
| 2021-03-22T14:38:59.516905
| 2020-03-19T15:32:38
| 2020-03-19T15:32:38
| 248,795,012
| 1
| 0
|
MIT
| 2020-03-20T15:54:05
| 2020-03-20T15:54:04
| null |
UTF-8
|
C++
| false
| false
| 1,810
|
h
|
OrientImage.h
|
//
// OrientImage.h
// Test
//
// Created by benji_admin on 2013-09-22.
// Copyright (c) 2013 benji_admin. All rights reserved.
//
#ifndef __Test__OrientImage__
#define __Test__OrientImage__
#include <itkImage.h>
#include <itkOrientImageFilter.h>
#include <itkSpatialOrientationAdapter.h>
typedef itk::SpatialOrientationAdapter SpatialOrientationAdapterType;
typedef itk::SpatialOrientation::ValidCoordinateOrientationFlags OrientationType;
template <typename InputImageType>
class OrientImage
{
public:
typedef typename InputImageType::Pointer InputImagePointer;
OrientImage() {};
~OrientImage() {};
void setInputImage(InputImagePointer image)
{
image_ = image;
SpatialOrientationAdapterType adapt;
initialImageOrientation_ = adapt.FromDirectionCosines(image_->GetDirection());
};
OrientationType getOrientationFromDirection(typename InputImageType::DirectionType direction)
{
SpatialOrientationAdapterType adapt;
return adapt.FromDirectionCosines(direction);
};
InputImagePointer getOutputImage() { return outputImage_; };
OrientationType getInitialImageOrientation() { return initialImageOrientation_; };
void orientation(OrientationType desiredOrientation)
{
typename itk::OrientImageFilter<InputImageType,InputImageType>::Pointer orienter = itk::OrientImageFilter<InputImageType,InputImageType>::New();
orienter->UseImageDirectionOn();
orienter->SetDesiredCoordinateOrientation(desiredOrientation);
orienter->SetInput(image_);
orienter->Update();
outputImage_ = orienter->GetOutput();
};
private:
InputImagePointer image_, outputImage_;
OrientationType initialImageOrientation_;
};
#endif /* defined(__Test__OrientImage__) */
|
3b19fc0af555e56b260f8a4550ded8fca62e894c
|
e7e3f3d92c7df7613a0854fd9ff8a3177a41accc
|
/cpp/updater/taskGatherer/strategies/impl/DownloadFilesFirst.h
|
69cf7c58e63ebd011d133bbadfe366b8fa3253f4
|
[] |
no_license
|
andronov-alexey/code-samples
|
1a0e0ab437f7aa44c7967f7266867ad28c98d631
|
1df33b543c7c2ace52f800243d12ecbd06b29bd2
|
refs/heads/master
| 2022-07-23T15:00:52.297222
| 2022-06-22T09:39:38
| 2022-06-22T09:39:38
| 114,187,322
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 187
|
h
|
DownloadFilesFirst.h
|
#pragma once
#include "KeepInitialOrdering.h"
class DownloadFilesFirst : public KeepInitialOrdering {
private:
virtual void _reorderTasks(const TaskQueue & _initialTasks) override;
};
|
e547a2c11746b349a2e74e3439430714c1885466
|
85c3e18522388fc6d405d3fe504b787cd97937aa
|
/src/include/XERenderer/OgreSceneManager.hpp
|
82e092ff2a44bd8db1e1f159e895cc8d0c20a989
|
[
"MIT"
] |
permissive
|
blockspacer/FrankE
|
2d454f77a15f02d8ac681c68730b20d189af131f
|
72faca02759b54aaec842831f3c7a051e7cf5335
|
refs/heads/master
| 2021-05-21T10:01:23.650983
| 2019-11-12T17:44:54
| 2019-11-12T17:44:54
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,169
|
hpp
|
OgreSceneManager.hpp
|
#ifndef __OGRESCENEMANAGER_HPP__
#define __OGRESCENEMANAGER_HPP__
//#include <Ogre/OgreMain/include/OgreMesh.h>
#include <sfml/Config.hpp>
//#include <Ogre/OgreMain/include/OgreVector3.h>
//#include <Ogre/OgreMain/include/OgreQuaternion.h>
#include <Ogre/OgreMain/include/OgreNode.h>
//#include <Ogre/OgreMain/include/OgreColourValue.h>
namespace Ogre
{
class Camera;
class SceneManager;
class SceneNode;
class TerrainGroup;
}
namespace XE {
class GraphicsManager;
class Scene;
class OgreSceneManager
{
public:
OgreSceneManager(GraphicsManager& gmanager);
void create();
void destroy();
void clearItems();
//change only in Renderthread!!! needed for createworkspace
Ogre::SceneManager *__OgreSceneMgrPtr;
private:
Ogre::SceneNode* __lRootSceneNode; // lRootSceneNode = mSceneMgr->getRootSceneNode();
Ogre::TerrainGroup* mTerrainGrp;
GraphicsManager& mGraphicsManager;
//-------------------------------
//todo updated from Renderer!!
//Ogre::Vector3 mDirection;
// Ogre::Quaternion m_worldOrientation;
// Ogre::Matrix4 m_transform;
//-------------------------------
};
}
#endif //__OGRESCENEMANAGER_HPP__
|
d048c96cf2f6850697f2e1c67b907d0ee10e94f6
|
a749064d841e4faf8fed78a0ac30434da7311a06
|
/server/Clustering/kmeans.h
|
21a68dade5a5d700264b99b3cf2b4939709ab9c1
|
[] |
no_license
|
zyavgarov/Clustering
|
f51d67c8179ca7d96f704da2d6a5fdfb66380804
|
23d32ce543e6a59b831a5e204cff3532a59121b9
|
refs/heads/main
| 2023-07-11T14:02:26.315535
| 2023-07-10T14:38:36
| 2023-07-10T14:38:36
| 360,912,096
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 386
|
h
|
kmeans.h
|
// Created by Zyavgarov Rustam
#ifndef INTERFACE4__KMEANS_H_
#define INTERFACE4__KMEANS_H_
#include "../Field.h"
class kmeans {
int clusters_number;
int err_;
static void kmeans_fprintf (vector<int> &nearest_cluster, vector<Point> &cores, int iteration);
public:
explicit kmeans (int clusters_number);
int err () const;
void k_means ();
};
#endif //INTERFACE4__KMEANS_H_
|
205a788b640dd959337b6d9f7edde9d6ef01de31
|
cc22ee5af45ac1b04fb16a1fe33cf6fe84e806fe
|
/2/test1.cpp
|
ea1720d43d8f7e9b18d307420dd8cbf143005735
|
[] |
no_license
|
lzch/cpp_primer
|
87f464f70e7a34fd00cc39def4c53480ee0e1a92
|
a490d57811d6322e96786c4b4a881cef12cdb7be
|
refs/heads/master
| 2021-01-01T16:24:09.029060
| 2017-07-21T03:49:13
| 2017-07-21T03:49:13
| 97,826,788
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 179
|
cpp
|
test1.cpp
|
// show name , email
#include <iostream>
using namespace std;
int main()
{
cout << "Name : lizc" << endl;
cout << "Email: lzch24035@163.com" << endl;
return 0;
}
|
8179e7ef0e5ea9a523a69ea70f5d0d97d548ce62
|
a987be7e6b120fe3341601b7d8f3a423fc2b67f9
|
/spoj/spPERMUT2.cpp
|
39344a63d13635c6c37909a47822ba277ba10a2e
|
[] |
no_license
|
rushout09/ProblemSolving
|
85391b3f3e210c05839453970c222b1dc6904a37
|
001635e2b16e64296be7d2270d37e998c1297529
|
refs/heads/master
| 2020-07-21T19:03:48.044630
| 2019-10-21T06:19:40
| 2019-10-21T06:19:40
| 206,950,820
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 493
|
cpp
|
spPERMUT2.cpp
|
#include <iostream>
using namespace std;
int main(){
while(true){
int n;
cin>>n;
if(n==0)
break;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
int f = 0;
for(int i=0;i<n;i++){
if(arr[arr[i]-1]!=i+1){
f=1;
break;
}
}
if(f==1){
cout<<"not ambiguous"<<endl;
}
else{
cout<<"ambiguous"<<endl;
}
}
}
|
703b0a76c7cef538a31ab46a58caa29e9adb3332
|
3538be2e6287019ceec0d644f6e5486f5b1cdaf0
|
/Volume2/0258/0258.cpp
|
3c5a724432d8c543c4cdf4872665856c367067d8
|
[] |
no_license
|
ry0u/AOJ
|
e3b80cffde32918d0cf01ffc5e1ed3a0f24de413
|
62b6c3e816e2b3085de8ff390add987c64e5dcbf
|
refs/heads/master
| 2021-01-13T01:26:53.686196
| 2016-01-27T17:17:57
| 2016-01-27T17:17:57
| 23,257,433
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 552
|
cpp
|
0258.cpp
|
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#define REP(i,k,n) for(int i=k;i<n;i++)
#define rep(i,n) for(int i=0;i<n;i++)
using namespace std;
int main()
{
int n;
while(cin >> n && n)
{
vector<int> v(n+1);
rep(i,n+1) cin >> v[i];
rep(i,n+1)
{
bool flag = true;
vector<int> p;
rep(j,n+1)
{
if(i != j) p.push_back(v[j]);
}
int ret = p[1] - p[0];
rep(j,n-1)
{
if(p[j+1] - p[j] != ret) flag = false;
}
if(flag)
{
cout << v[i] << endl;
break;
}
}
}
}
|
bbd58b2e53165695aa845dab1bd8b13b3d076dbc
|
8b98203f29315123a1eec780886989ae13182af9
|
/xcode_cmd_test1/Lib/Dict.hpp
|
02b760eaef03710b136f3968ef436012ba0ac835
|
[] |
no_license
|
denghe/69net
|
6f9ade30a4bfc796f975daa75069c61cbd3e8c8b
|
1ff2b90cd8dc0b7bdf7e360386796a7f9e90f62f
|
refs/heads/master
| 2020-04-05T23:19:40.374220
| 2019-12-28T03:37:59
| 2019-12-28T03:37:59
| 20,693,720
| 7
| 6
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,379
|
hpp
|
Dict.hpp
|
๏ปฟ#ifndef _DICT_HPP__
#define _DICT_HPP__
namespace xxx
{
template <typename TK, typename TV>
Dict<TK, TV>::Dict( int capacity /*= 64 */ )
{
pool.Init( sizeof( Node ), 4096, capacity );
int prime = GetPrime( capacity );
nodes.Reserve( prime );
buckets.Resize( prime );
}
template <typename TK, typename TV>
Dict<TK, TV>::Dict( Dict const& o )
: Dict( o.Size() )
{
operator=( o );
}
template <typename TK, typename TV>
Dict<TK, TV>::Dict( Dict&& o )
{
buckets = std::move( o.buckets );
nodes = std::move( o.nodes );
pool = std::move( o.pool );
}
template <typename TK, typename TV>
Dict<TK, TV>& Dict<TK, TV>::operator=( Dict const& o )
{
if( this == &o ) return *this;
Clear();
Reserve( o.Size() );
for( int i = 0; i < o.Size(); ++i )
{
auto on = o.Data()[ i ];
uint mod = on->hash % (uint)buckets.Size();
auto n = (Node*)pool.Alloc();
n->next = buckets[ mod ];
n->hash = on->hash;
n->index = nodes.Size();
new ( &n->key ) TK( on->key );
new ( &n->value ) TV( on->value );
buckets[ mod ] = n;
nodes.Push( n );
}
return *this;
}
template <typename TK, typename TV>
Dict<TK, TV>& Dict<TK, TV>::operator=( Dict&& o )
{
buckets = std::move( o.buckets );
nodes = std::move( o.nodes );
pool = std::move( o.pool );
return *this;
}
template <typename TK, typename TV>
Dict<TK, TV>::~Dict()
{
for( int i = 0; i < nodes.Size(); ++i )
Dispose( nodes[ i ] );
}
template <typename TK, typename TV>
template <typename VT>
std::pair<typename Dict<TK, TV>::Node*, bool> Dict<TK, TV>::Insert( TK const& k, VT && v, bool replace /*= false */ )
{
return Emplace( replace, k, std::forward<VT>( v ) );
}
template <typename TK, typename TV>
template<typename ...VPTS>
std::pair<typename Dict<TK, TV>::Node*, bool> Dict<TK, TV>::Emplace( bool replace, TK const& k, VPTS&& ...vps )
{
std::pair<typename Dict<TK, TV>::Node*, bool> rtv;
uint hashCode = (uint)GetHashCode( k );
uint mod = hashCode % (uint)buckets.Size();
auto node = buckets[ mod ];
while( node )
{
if( node->hash == hashCode && EqualsTo( node->key, k ) )
{
if( replace ) node->value = TV( std::forward<VPTS>( vps )... );
rtv.first = node;
rtv.second = false;
return rtv;
}
node = node->next;
};
auto n = (Node*)pool.Alloc();
n->next = buckets[ mod ];
n->hash = hashCode;
n->index = nodes.Size();
new ( &n->key ) TK( k );
new ( &n->value ) TV( std::forward<VPTS>( vps )... );
buckets[ mod ] = n;
nodes.Push( n );
if( nodes.Size() == buckets.Size() ) Resize();
rtv.first = n;
rtv.second = true;
return rtv;
}
template <typename TK, typename TV>
typename Dict<TK, TV>::Node* Dict<TK, TV>::Find( TK const& k )
{
uint hashCode = (uint)GetHashCode( k );
uint mod = hashCode % (uint)buckets.Size();
auto node = buckets[ mod ];
while( node )
{
if( node->hash == hashCode && EqualsTo( node->key, k ) ) return node;
node = node->next;
}
return nullptr;
}
template <typename TK, typename TV>
void Dict<TK, TV>::Erase( TK const& k )
{
auto n = Find( k );
if( !n ) return;
Erase( n );
}
template <typename TK, typename TV>
void Dict<TK, TV>::Erase( Node* n )
{
auto mod = n->hash % (uint)buckets.Size();
auto node = buckets[ mod ];
if( node == n )
{
buckets[ mod ] = node->next;
}
else
{
auto parent = node;
while( ( node = node->next ) )
{
if( node == n )
{
parent->next = node->next;
break;
}
parent = node;
}
}
auto last = nodes.Top();
nodes.Pop();
if( n != last )
{
nodes[ n->index ] = last;
last->index = n->index;
}
Dispose( n );
pool.Free( n );
}
template <typename TK, typename TV>
TV& Dict<TK, TV>::operator[]( TK const& k )
{
uint hashCode = (uint)GetHashCode( k );
uint mod = hashCode % (uint)buckets.Size();
auto node = buckets[ mod ];
while( node )
{
if( node->hash == hashCode && EqualsTo( node->key, k ) )
{
return node->value;
}
node = node->next;
};
auto n = (Node*)pool.Alloc(); // new & Init
n->next = buckets[ mod ];
n->hash = hashCode;
n->index = nodes.Size();
new ( &n->key ) TK( k );
new ( &n->value ) TV();
buckets[ mod ] = n;
nodes.Push( n );
if( nodes.Size() == buckets.Size() ) Resize(); // grow
return n->value;
}
template <typename TK, typename TV>
TV& Dict<TK, TV>::At( TK const& k )
{
return operator[]( k );
}
template <typename TK, typename TV>
void Dict<TK, TV>::Clear()
{
for( int i = 0; i < nodes.Size(); ++i )
{
Dispose( nodes[ i ] );
pool.Free( nodes[ i ] );
}
nodes.Clear();
memset( buckets.Data(), 0, buckets.ByteSize() );
}
template <typename TK, typename TV>
void Dict<TK, TV>::Reserve( int capacity )
{
if( capacity <= buckets.Size() ) return;
int prime = GetPrime( (int)Round2n( capacity ) );
nodes.Reserve( prime );
buckets.Resize( prime, false );
memset( buckets.Data(), 0, buckets.ByteSize() ); // clean up
for( int i = 0; i < nodes.Size(); ++i )
{
auto& o = nodes[ i ];
auto mod = o->hash % prime;
o->next = buckets[ mod ];
buckets[ mod ] = o;
}
}
template <typename TK, typename TV>
List<typename Dict<TK, TV>::Node*> const & Dict<TK, TV>::Data() const
{
return nodes;
}
template <typename TK, typename TV>
int Dict<TK, TV>::Size() const
{
return nodes.Size();
}
template <typename TK, typename TV>
void Dict<TK, TV>::Dispose( Node* n )
{
n->key.~TK();
n->value.~TV();
}
template <typename TK, typename TV>
bool Dict<TK, TV>::Empty()
{
return nodes.Size() == 0;
}
template <typename TK, typename TV>
void Dict<TK, TV>::Resize()
{
int prime = GetPrime( nodes.Size() * 3 );
nodes.Reserve( prime );
buckets.Resize( prime, false );
memset( buckets.Data(), 0, buckets.ByteSize() ); // clean up
for( int i = 0; i < nodes.Size(); ++i )
{
auto& o = nodes[ i ];
auto mod = o->hash % prime;
o->next = buckets[ mod ];
buckets[ mod ] = o;
}
}
template <typename TK, typename TV>
void Dict<TK, TV>::WriteTo( ByteBuffer& bb ) const
{
bb.VarWrite( (uint)nodes.Size() );
for( int i = 0; i < nodes.Size(); ++i )
{
bb.Write( nodes[ i ]->key );
bb.Write( nodes[ i ]->value );
}
}
template <typename TK, typename TV>
void Dict<TK, TV>::FastWriteTo( ByteBuffer& bb ) const
{
bb.FastVarWrite( (uint)nodes.Size() );
for( int i = 0; i < nodes.Size(); ++i )
{
bb.FastWrite( nodes[ i ]->key );
bb.FastWrite( nodes[ i ]->value );
}
}
template <typename TK, typename TV>
bool Dict<TK, TV>::ReadFrom( ByteBuffer& bb )
{
int len;
if( !bb.VarRead( *(uint*)&len ) || len < 0 ) return false;
Clear();
Reserve( len );
for( int i = 0; i < len; ++i )
{
auto n = (Node*)pool.Alloc(); // malloc
if( !std::is_pod<TK>::value ) new ( &n->key ) TK(); // new key
if( !bb.Read( n->key ) )
{
if( !std::is_pod<TK>::value ) n->key.~TK(); // delete key
pool.Free( n ); // free
return false;
}
if( !std::is_pod<TV>::value ) new ( &n->value ) TV(); // new value
if( !bb.Read( n->value ) )
{
if( !std::is_pod<TV>::value ) n->value.~TV(); // delete value
pool.Free( n ); // free
return false;
}
n->hash = (uint)GetHashCode( n->key );
uint mod = n->hash % (uint)buckets.Size();
n->index = i;//nodes.Size();
n->next = buckets[ mod ];
buckets[ mod ] = n;
nodes.Push( n );
}
return true;
}
}
#endif
|
e61865620669efca8e5326e1e39f61eee3250473
|
45bd342b841e9d8b51a6e87ab116cfcc8978a4eb
|
/Plugins/ObjectDeliverer/Source/ObjectDeliverer/Public/Protocol/ProtocolUdpSocketSender.h
|
6b98b945f218a3b0c82d6d3f591a902584dae63f
|
[
"MIT"
] |
permissive
|
ayumax/ObjectDeliverer
|
349ff275a2affeba2182db40288b6ba7ef2c8927
|
6a2571e00e8f0e754e8d295872a1a1d28f4a274d
|
refs/heads/master
| 2023-06-01T06:36:44.412910
| 2023-05-14T13:16:56
| 2023-05-14T13:18:06
| 164,864,304
| 142
| 37
|
MIT
| 2023-05-14T13:18:07
| 2019-01-09T13:04:48
|
C++
|
UTF-8
|
C++
| false
| false
| 1,527
|
h
|
ProtocolUdpSocketSender.h
|
// Copyright 2019 ayumax. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "ProtocolSocketBase.h"
#include "ProtocolUdpSocketSender.generated.h"
UCLASS(BlueprintType, Blueprintable)
class OBJECTDELIVERER_API UProtocolUdpSocketSender : public UProtocolSocketBase
{
GENERATED_BODY()
public:
UProtocolUdpSocketSender();
~UProtocolUdpSocketSender();
/**
* Initialize UDP.
* @param IpAddress - The ip address of the destination.
* @param Port - The port number of the destination.
*/
UFUNCTION(BlueprintCallable, Category = "ObjectDeliverer|Protocol")
virtual void Initialize(const FString& IpAddress = "localhost", int32 Port = 8000);
UFUNCTION(BlueprintCallable, Category = "ObjectDeliverer|Protocol")
UProtocolUdpSocketSender* WithSendBufferSize(int32 SizeInBytes);
virtual void Start() override;
virtual void Close() override;
virtual void Send(const TArray<uint8>& DataBuffer) const override;
virtual void RequestSend(const TArray<uint8>& DataBuffer) override;
public:
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta = (ExposeOnSpawn = true), Category = "ObjectDeliverer|Protocol")
FString DestinationIpAddress = "localhost";
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta = (ExposeOnSpawn = true), Category = "ObjectDeliverer|Protocol")
int32 DestinationPort = 8000;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta = (ExposeOnSpawn = true), Category = "ObjectDeliverer|Protocol")
int32 SendBufferSize = 1024 * 1024;
protected:
FIPv4Endpoint DestinationEndpoint;
};
|
292211fb2b8185744850fa1640a5651c1156b888
|
24c710d3354a613dd2ea95d8f123be4d5d4407c2
|
/module_01/ex03/ZombieHorde.cpp
|
cf5d2a3e6ef5a81694b74bde36bc0db50ff4082e
|
[] |
no_license
|
jiyoon1156/CPP_Module
|
442166e9950c9aeaf38b4690011e71fe855ed34b
|
e297350c86a38caf0699db9a8bc293564d749c1e
|
refs/heads/master
| 2022-12-08T17:34:16.277373
| 2020-09-05T03:57:08
| 2020-09-05T03:57:08
| 286,356,183
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,342
|
cpp
|
ZombieHorde.cpp
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ZombieHorde.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jhur <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/08/13 10:41:33 by jhur #+# #+# */
/* Updated: 2020/08/13 12:58:12 by jhur ### ########.fr */
/* */
/* ************************************************************************** */
#include "ZombieHorde.hpp"
ZombieHorde::ZombieHorde(int N)
{
std::string random_name[5] = {"z1", "z2", "z3", "z4", "z5"};
this->n = N;
random_zombie = new Zombie[this->n];
for(int i = 0; i < n; i++)
{
random_zombie[i].setName(random_name[rand() % 5]);
random_zombie[i].setType("random");
random_zombie[i].announce();
}
}
ZombieHorde::~ZombieHorde()
{
delete []random_zombie;
std::cout << "All the zombies are killed" << std::endl;
}
|
79226acab9f640ec507fc695e87baea150e638a1
|
cbc49ab614d9e2da825bbc45f2ae86d2088fce29
|
/src/gzplugins/gzjointcmdplugin/gzjntcommandplugin.h
|
4fd8dccbf1818b026a079feb1354d339e680536b
|
[] |
no_license
|
johnmichaloski/gzgwendolen
|
ef442ac7f0af9507c251fbf39ab1c30a5737ddf5
|
5186694a52ade82db206bcf0b3d25737011f8aee
|
refs/heads/main
| 2023-01-04T07:44:46.821304
| 2020-11-04T17:50:31
| 2020-11-04T17:50:31
| 304,719,185
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,001
|
h
|
gzjntcommandplugin.h
|
/*
* DISCLAIMER:
* This software was produced by the National Institute of Standards
* and Technology (NIST), an agency of the U.S. government, and by statute is
* not subject to copyright in the United States. Recipients of this software
* assume all responsibility associated with its operation, modification,
* maintenance, and subsequent redistribution.
*
* See NIST Administration Manual 4.09.07 b and Appendix I.
*/
#ifndef GZJNTCMDPLUGIN_H
#define GZJNTCMDPLUGIN_H
#include <gazebo/gazebo.hh>
#include <gazebo/physics/physics.hh>
#include <gazebo/transport/transport.hh>
#include <gazebo/msgs/msgs.hh>
#include <string>
#include <boost/bind.hpp>
#include <boost/thread/mutex.hpp>
#include "JointsComm.pb.h"
namespace gazebo
{
typedef boost::shared_ptr<gazebo::msgs::JointCmd const> ConstJointCmdPtr;
typedef boost::shared_ptr<message::JointsComm const> ConstJointsCommPtr;
enum CONTROL_TYPE {
NO_CONTROL=0,
POSITION_CONTROL,
VELOCITY_CONTROL,
FORCE_TORQUE_CONTROL
};
/**
* @brief The gzJntCmdPlugin class is a gzebo plugin that one would insert
* into either the world or sdf file. It read/writes Google protobuf custom message
*
\code
package message;
message JointsComm {
repeated string name = 1;
repeated double position = 2;
repeated double velocity = 3;
repeated double effort = 4;
}
\endcode
The joint communication custom message acts like the ROS sensor
message joint status.
*/
class gzJntCmdPlugin : public ModelPlugin
{
public:
/**
* @brief gzJntCmdPlugin empty constructor. Sets flags and
* set timing to 0.005 seconds.
*/
gzJntCmdPlugin();
~gzJntCmdPlugin();
/**
* @brief Load overloaded model plugin method to setup the pluing.
* Initializes paraemters, saves world, parsed SDF for parameter values,
* and creates pusblisher and subscriber for joint status and commands.
* @param[in] _model Pointer to the Model
* @param[in] _sdf Pointer to the SDF element of the plugin. The sdf contains
* the parameter settings used by this plugin.
*/
virtual void Load(physics::ModelPtr _model, sdf::ElementPtr _sdf);
/**
* @brief setJntPosition mutexed update of a joint value that will be written
* to Gazebo robot model.
* @param name name of the joint.
* @param pos position of the robot joint.
*/
void setJntPosition(const std::string &name, const double &pos);
void updateJointStatus();
/**
* @brief publishJointStates publishes all the joint positions to
* Gazebo simulation at once. But only if the joints are different.
*/
void publishJointStates();
/**
* @brief onUpdate handles the Gazebo world update event callback.
* @param _info
*/
void onUpdate (const common::UpdateInfo & _info);
/// \brief Handle incoming joint command message
/// \param[in] _msg allow joint name or pos/vel Pid values
void onMsg(const ConstJointCmdPtr &msg);
/**
* @brief onJointsCommMsg deprecated handling of gazebo one-by-one
* joint update message.
* @param msg
*/
void onJointsCommMsg(const ConstJointsCommPtr &msg);
/**
* @brief fingers names of gripper finger joints to ignore when updating robot.
*/
std::vector<std::string> fingers;
private:
/// \brief A node used for transport
transport::NodePtr node;
transport::SubscriberPtr sub; /// \brief A subscriber to a robots joints topic.
transport::SubscriberPtr finger_sub; /// \brief A subscriber to a gripper finger topic.
transport::SubscriberPtr subJointsComm; /// \brief A subscriber to a robots joints comm topic.
gazebo::transport::PublisherPtr pub; // feedback of joint values
/// \brief Pointer to the model.
physics::ModelPtr model;
/// \brief Pointer to the world.
physics::WorldPtr world;
/// \brief Pointer to the joint.
physics::JointPtr joint;
std::string topicName;
std::string robotCmd_topicName;
std::string robotStatus_topicName;
// std::string finger_topicName;
std::vector<CONTROL_TYPE> joint_typeControl;
std::string model_name;
std::vector<physics::JointPtr> joints_ptr;
// dynamic values
std::vector<double> joint_pos;
std::vector<double> joint_vel;
std::vector<double> joint_effort;
// saved
std::vector<double> myjoint_postarget;
std::vector<double> myjoint_veltarget;
std::vector<double> myjoint_efftarget;
bool bFlag;
common::Time updateRate; ///nano seconds between two updates
double update_rate_;
double update_period_;
common::Time last_update_time_;
boost::mutex m;
private:
// Pointer to the update event connection
event::ConnectionPtr updateConnection;
bool b_debug;
std::vector<std::string> joint_names;
int _nstatus;
};
// Tell Gazebo about this plugin, so that Gazebo can call Load on this plugin.
GZ_REGISTER_MODEL_PLUGIN(gzJntCmdPlugin)
}
#endif // GzJntCmdPlugin_H
|
0d152def6f3aaed1d8ad4c2582e9b304dedd6b88
|
0f2f893893431fb16ab42b19b704200f2aad3176
|
/Arrays/Sum of All Elements of an Array/main.cpp
|
2e447bec24bb4fda0fba3fc35b6b6158cc0faaae
|
[] |
no_license
|
Snehanko/Basic-Cpp-Programs
|
081e30ba8fc9779ec9d2451fff38c78dbe4f259f
|
e4b949bdd3bc9e6489baac0bdf43391abf615581
|
refs/heads/main
| 2023-06-26T07:38:24.894215
| 2021-07-28T15:03:56
| 2021-07-28T15:03:56
| 390,393,840
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 214
|
cpp
|
main.cpp
|
#include <iostream>
using namespace std;
int main()
{
int arr[]={4,6,8,10,12};
int sum;
for(int i:arr){
sum+=i;
}
cout<<"Sum of All Elements of Array- "<<sum<<endl;
return 0;
}
|
d49e074ab50d530849a8c2893332af9e6c85d14f
|
32554d2b2fcd173826f41f5e416e5e4d09566a03
|
/src/game/client/components/damageind.cpp
|
f585e4d3066512753ccf9bf00fcbdefe2bd1c4d8
|
[
"LicenseRef-scancode-other-permissive",
"Zlib"
] |
permissive
|
fasterthanlime/teeworlds-ai
|
741171227a987977f2a19cbb94d4ae60a6ddff32
|
82d3e372578a676937672fa012b6ab2110325015
|
refs/heads/master
| 2020-04-10T04:01:56.613815
| 2013-11-27T20:59:23
| 2013-11-27T20:59:23
| 329,879
| 7
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,335
|
cpp
|
damageind.cpp
|
#include <engine/e_client_interface.h>
#include <game/generated/g_protocol.hpp>
#include <game/generated/gc_data.hpp>
#include <game/gamecore.hpp> // get_angle
#include <game/client/ui.hpp>
#include <game/client/render.hpp>
#include "damageind.hpp"
DAMAGEIND::DAMAGEIND()
{
lastupdate = 0;
num_items = 0;
}
DAMAGEIND::ITEM *DAMAGEIND::create_i()
{
if (num_items < MAX_ITEMS)
{
ITEM *p = &items[num_items];
num_items++;
return p;
}
return 0;
}
void DAMAGEIND::destroy_i(DAMAGEIND::ITEM *i)
{
num_items--;
*i = items[num_items];
}
void DAMAGEIND::create(vec2 pos, vec2 dir)
{
ITEM *i = create_i();
if (i)
{
i->pos = pos;
i->life = 0.75f;
i->dir = dir*-1;
i->startangle = (( (float)rand()/(float)RAND_MAX) - 1.0f) * 2.0f * pi;
}
}
void DAMAGEIND::on_render()
{
gfx_texture_set(data->images[IMAGE_GAME].id);
gfx_quads_begin();
for(int i = 0; i < num_items;)
{
vec2 pos = mix(items[i].pos+items[i].dir*75.0f, items[i].pos, clamp((items[i].life-0.60f)/0.15f, 0.0f, 1.0f));
items[i].life -= client_frametime();
if(items[i].life < 0.0f)
destroy_i(&items[i]);
else
{
gfx_setcolor(1.0f,1.0f,1.0f, items[i].life/0.1f);
gfx_quads_setrotation(items[i].startangle + items[i].life * 2.0f);
select_sprite(SPRITE_STAR1);
draw_sprite(pos.x, pos.y, 48.0f);
i++;
}
}
gfx_quads_end();
}
|
055c2f2eba57b8bb583088db40171a394208a5d3
|
ca1784cefa22c7e8c5d297f397004ee0b0a491c0
|
/dex/dxgioffsets.h
|
61ec7d5b4cf94db59a02833d483142d953f259ce
|
[] |
no_license
|
ere336/Overwatchcheat
|
e3e1f80987fcbcd83777c416a2056553e5e80e6f
|
3184cec749652a819f1d0645da1c2afca2d36dba
|
refs/heads/main
| 2023-05-07T05:44:20.080213
| 2021-05-31T03:31:53
| 2021-05-31T03:31:53
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,121
|
h
|
dxgioffsets.h
|
#pragma once
#include <Windows.h>
#include <stdint.h>
#include <d3d11.h>
#include <VersionHelpers.h>
#include <dxgi1_2.h>
#include "singleton.h"
#define DUMMY_WNDCLASS "get_addrs_wndclass"
static const IID dxgiFactory2 =
{ 0x50c83a1c, 0xe072, 0x4c48, { 0x87, 0xb0, 0x36, 0x30, 0xfa, 0x36, 0xa6, 0xd0 } };
typedef HRESULT(WINAPI *d3d10create_t)(IDXGIAdapter*, D3D10_DRIVER_TYPE,
HMODULE, UINT, UINT, DXGI_SWAP_CHAIN_DESC*,
IDXGISwapChain**, IUnknown**);
typedef HRESULT(WINAPI *create_fac_t)(IID *id, void**);
struct dxgi_info {
HMODULE module;
HWND hwnd;
IDXGISwapChain *swap;
};
struct dxgi_offsets {
uint32_t present;
uint32_t resize;
uint32_t present1;
uint32_t drawindexed;
};
class DXGIOffsets
: public Singleton<DXGIOffsets>
{
friend class Singleton<DXGIOffsets>;
public:
bool Initialize();
dxgi_offsets GetDXGIOffsets();
void* GetPresentAddr();
HMODULE GetDXGIModule();
private:
bool initDXGI();
uint32_t vtable_offset(HMODULE module, void *cls,
unsigned int offset);
void closeDXGI();
bool InitSystemPath();
char system_path[MAX_PATH] = { 0 };
dxgi_info info = {};
};
|
425ceef60154335f97c600827320f1b2fa212292
|
8f4129710e50599e8dea86c64f5091b8015396f0
|
/Strings/S8/Fmt.cpp
|
0916ab1d3495dfed126f0d5e6d1c038937c1caa2
|
[] |
no_license
|
DarshanDesk/ProgrammingChallenges-CPP
|
d82f7f068c2b9821755aa5bcbcac359819ebb7d1
|
9857c6a060a13499c156e9c32cad357a85c9f799
|
refs/heads/master
| 2023-04-01T01:44:18.201719
| 2021-03-24T19:56:59
| 2021-03-24T19:56:59
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,862
|
cpp
|
Fmt.cpp
|
//
// Created by Oฤuz Kerem Yฤฑldฤฑz on 9.01.2021.
//
#include <iostream>
#include <fstream>
using namespace std;
void print(string &added) {
string word = "";
string remaining = "";
int t = 0;
if (added.at(0) == ' ') {
while (added.at(t) == ' ') {
remaining += " ";
t++;
}
}
for (int i = 0; i < added.length(); i++) {
if (added.at(i) != ' ') {
word += added.at(i);
} else {
if (remaining.length() + word.length() < 72) {
if (remaining.length() == 0){
remaining = word;
} else {
remaining += " " + word;
}
} else {
cout << remaining << endl;
remaining = word;
}
word = "";
}
}
if (word.length() != 0){
remaining += " " + word;
}
cout << remaining << endl;
}
int main() {
fstream file;
file.open("Unix.txt", ios::in);
if (file.fail()) {
cout << "file not reading" << endl;
} else {
string line;
string added = "";
int i = 0;
while (!file.eof()) {
getline(file, line);
if (line != "") {
if (i == 0) {
added += "";
i++;
} else {
added += " ";
}
added += line;
} else {
if (added.length() > 72) {
print(added);
cout << "" << endl;
added = "";
i = 0;
} else {
cout << added;
added = "";
cout << "" << endl;
i = 0;
}
}
}
}
}
|
a221db5e18bf33031e3cbb1ed8e900496dbd6c96
|
e5b136d24afe47484371ca8087c43f024aa6fdb3
|
/garnet/drivers/video/amlogic-decoder/teec_context.h
|
96da02aa81d1130e02b462fde6c16c470602d903
|
[
"BSD-3-Clause"
] |
permissive
|
deveshd020/fuchsia
|
92d5ded7c84a7f9eae092d4c35ef923cd7852bd4
|
810c7b868d2e7b580f5ccbe1cb26e45746ae3ac5
|
refs/heads/master
| 2021-01-03T09:43:21.757097
| 2020-02-06T01:06:22
| 2020-02-06T01:06:22
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 615
|
h
|
teec_context.h
|
// Copyright 2019 The Fuchsia 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 GARNET_DRIVERS_VIDEO_AMLOGIC_DECODER_TEEC_CONTEXT_H_
#define GARNET_DRIVERS_VIDEO_AMLOGIC_DECODER_TEEC_CONTEXT_H_
#include <lib/zx/channel.h>
#include <tee-client-api/tee-client-types.h>
class TeecContext {
public:
TeecContext();
~TeecContext();
TEEC_Context& context();
void SetClientChannel(zx::channel client_channel);
private:
TEEC_Context context_{};
};
#endif // GARNET_DRIVERS_VIDEO_AMLOGIC_DECODER_TEEC_CONTEXT_H_
|
633e6cdffe22b3a45829bebfe2608f59557b1866
|
1ef7f9ea91eba1d1890a8f438470dbd20e8c9bf5
|
/libraries/render-utils/src/BloomEffect.cpp
|
ddd63f012f933af15c99e1c40cc748f7d8c097b7
|
[
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] |
permissive
|
ZappoMan/hifi
|
43861c556be40be04839ae0804fbc8eb560eeb8d
|
0a1f07755e71aca5a599c19c570f1d0130e06c7a
|
refs/heads/master
| 2020-04-05T22:53:44.168451
| 2018-04-18T01:02:34
| 2018-04-18T01:02:34
| 9,376,434
| 1
| 0
| null | 2017-02-24T01:36:02
| 2013-04-11T17:41:25
|
C++
|
UTF-8
|
C++
| false
| false
| 14,226
|
cpp
|
BloomEffect.cpp
|
//
// BloomEffect.cpp
// render-utils/src/
//
// Created by Olivier Prat on 09/25/17.
// Copyright 2017 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include "BloomEffect.h"
#include "gpu/Context.h"
#include "gpu/StandardShaderLib.h"
#include <render/BlurTask.h>
#include <render/ResampleTask.h>
#include "BloomThreshold_frag.h"
#include "BloomApply_frag.h"
#define BLOOM_BLUR_LEVEL_COUNT 3
BloomThreshold::BloomThreshold(unsigned int downsamplingFactor) :
_downsamplingFactor(downsamplingFactor) {
assert(downsamplingFactor > 0);
}
void BloomThreshold::configure(const Config& config) {
_threshold = config.threshold;
}
void BloomThreshold::run(const render::RenderContextPointer& renderContext, const Inputs& inputs, Outputs& outputs) {
assert(renderContext->args);
assert(renderContext->args->hasViewFrustum());
RenderArgs* args = renderContext->args;
const auto frameTransform = inputs.get0();
const auto inputFrameBuffer = inputs.get1();
assert(inputFrameBuffer->hasColor());
auto inputBuffer = inputFrameBuffer->getRenderBuffer(0);
auto bufferSize = gpu::Vec2u(inputBuffer->getDimensions());
// Downsample resolution
bufferSize.x /= _downsamplingFactor;
bufferSize.y /= _downsamplingFactor;
if (!_outputBuffer || _outputBuffer->getSize() != bufferSize) {
auto colorTexture = gpu::TexturePointer(gpu::Texture::createRenderBuffer(inputBuffer->getTexelFormat(), bufferSize.x, bufferSize.y,
gpu::Texture::SINGLE_MIP, gpu::Sampler(gpu::Sampler::FILTER_MIN_MAG_LINEAR_MIP_POINT)));
_outputBuffer = gpu::FramebufferPointer(gpu::Framebuffer::create("BloomThreshold"));
_outputBuffer->setRenderBuffer(0, colorTexture);
}
static const int COLOR_MAP_SLOT = 0;
static const int THRESHOLD_SLOT = 1;
if (!_pipeline) {
auto vs = gpu::StandardShaderLib::getDrawTransformUnitQuadVS();
auto ps = BloomThreshold_frag::getShader();
gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps);
gpu::Shader::BindingSet slotBindings;
slotBindings.insert(gpu::Shader::Binding("colorMap", COLOR_MAP_SLOT));
slotBindings.insert(gpu::Shader::Binding("threshold", THRESHOLD_SLOT));
gpu::Shader::makeProgram(*program, slotBindings);
gpu::StatePointer state = gpu::StatePointer(new gpu::State());
_pipeline = gpu::Pipeline::create(program, state);
}
glm::ivec4 viewport{ 0, 0, bufferSize.x, bufferSize.y };
gpu::doInBatch("BloomThreshold::run", args->_context, [&](gpu::Batch& batch) {
batch.enableStereo(false);
batch.setViewportTransform(viewport);
batch.setProjectionTransform(glm::mat4());
batch.resetViewTransform();
batch.setModelTransform(gpu::Framebuffer::evalSubregionTexcoordTransform(bufferSize, viewport));
batch.setPipeline(_pipeline);
batch.setFramebuffer(_outputBuffer);
batch.setResourceTexture(COLOR_MAP_SLOT, inputBuffer);
batch._glUniform1f(THRESHOLD_SLOT, _threshold);
batch.draw(gpu::TRIANGLE_STRIP, 4);
});
outputs = _outputBuffer;
}
BloomApply::BloomApply() {
}
void BloomApply::configure(const Config& config) {
_intensity = config.intensity;
}
void BloomApply::run(const render::RenderContextPointer& renderContext, const Inputs& inputs) {
assert(renderContext->args);
assert(renderContext->args->hasViewFrustum());
RenderArgs* args = renderContext->args;
static auto BLUR0_SLOT = 0;
static auto BLUR1_SLOT = 1;
static auto BLUR2_SLOT = 2;
static auto INTENSITY_SLOT = 3;
if (!_pipeline) {
auto vs = gpu::StandardShaderLib::getDrawTransformUnitQuadVS();
auto ps = BloomApply_frag::getShader();
gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps);
gpu::Shader::BindingSet slotBindings;
slotBindings.insert(gpu::Shader::Binding("blurMap0", BLUR0_SLOT));
slotBindings.insert(gpu::Shader::Binding("blurMap1", BLUR1_SLOT));
slotBindings.insert(gpu::Shader::Binding("blurMap2", BLUR2_SLOT));
slotBindings.insert(gpu::Shader::Binding("intensity", INTENSITY_SLOT));
gpu::Shader::makeProgram(*program, slotBindings);
gpu::StatePointer state = gpu::StatePointer(new gpu::State());
state->setDepthTest(gpu::State::DepthTest(false, false));
_pipeline = gpu::Pipeline::create(program, state);
}
const auto frameBuffer = inputs.get0();
const auto framebufferSize = frameBuffer->getSize();
const auto blur0FB = inputs.get1();
const auto blur1FB = inputs.get2();
const auto blur2FB = inputs.get3();
const glm::ivec4 viewport{ 0, 0, framebufferSize.x, framebufferSize.y };
gpu::doInBatch("BloomApply::run", args->_context, [&](gpu::Batch& batch) {
batch.enableStereo(false);
batch.setFramebuffer(frameBuffer);
batch.setViewportTransform(viewport);
batch.setProjectionTransform(glm::mat4());
batch.resetViewTransform();
batch.setPipeline(_pipeline);
batch.setModelTransform(gpu::Framebuffer::evalSubregionTexcoordTransform(framebufferSize, viewport));
batch.setResourceTexture(BLUR0_SLOT, blur0FB->getRenderBuffer(0));
batch.setResourceTexture(BLUR1_SLOT, blur1FB->getRenderBuffer(0));
batch.setResourceTexture(BLUR2_SLOT, blur2FB->getRenderBuffer(0));
batch._glUniform1f(INTENSITY_SLOT, _intensity / 3.0f);
batch.draw(gpu::TRIANGLE_STRIP, 4);
});
}
void BloomDraw::run(const render::RenderContextPointer& renderContext, const Inputs& inputs) {
assert(renderContext->args);
assert(renderContext->args->hasViewFrustum());
RenderArgs* args = renderContext->args;
const auto frameBuffer = inputs.get0();
const auto bloomFrameBuffer = inputs.get1();
if (frameBuffer && bloomFrameBuffer) {
const auto framebufferSize = frameBuffer->getSize();
if (!_pipeline) {
auto vs = gpu::StandardShaderLib::getDrawTransformUnitQuadVS();
auto ps = gpu::StandardShaderLib::getDrawTextureOpaquePS();
gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps);
gpu::Shader::BindingSet slotBindings;
gpu::Shader::makeProgram(*program, slotBindings);
gpu::StatePointer state = gpu::StatePointer(new gpu::State());
state->setDepthTest(gpu::State::DepthTest(false, false));
state->setBlendFunction(true, gpu::State::ONE, gpu::State::BLEND_OP_ADD, gpu::State::ONE,
gpu::State::ZERO, gpu::State::BLEND_OP_ADD, gpu::State::ONE);
_pipeline = gpu::Pipeline::create(program, state);
}
gpu::doInBatch("BloomDraw::run", args->_context, [&](gpu::Batch& batch) {
batch.enableStereo(false);
batch.setFramebuffer(frameBuffer);
batch.setViewportTransform(args->_viewport);
batch.setProjectionTransform(glm::mat4());
batch.resetViewTransform();
batch.setPipeline(_pipeline);
batch.setModelTransform(gpu::Framebuffer::evalSubregionTexcoordTransform(framebufferSize, args->_viewport));
batch.setResourceTexture(0, bloomFrameBuffer->getRenderBuffer(0));
batch.draw(gpu::TRIANGLE_STRIP, 4);
});
}
}
DebugBloom::DebugBloom() {
}
void DebugBloom::configure(const Config& config) {
_mode = static_cast<DebugBloomConfig::Mode>(config.mode);
assert(_mode < DebugBloomConfig::MODE_COUNT);
}
void DebugBloom::run(const render::RenderContextPointer& renderContext, const Inputs& inputs) {
assert(renderContext->args);
assert(renderContext->args->hasViewFrustum());
RenderArgs* args = renderContext->args;
const auto frameBuffer = inputs.get0();
const auto combinedBlurBuffer = inputs.get4();
const auto framebufferSize = frameBuffer->getSize();
const auto level0FB = inputs.get1();
const auto level1FB = inputs.get2();
const auto level2FB = inputs.get3();
const gpu::TexturePointer levelTextures[BLOOM_BLUR_LEVEL_COUNT] = {
level0FB->getRenderBuffer(0),
level1FB->getRenderBuffer(0),
level2FB->getRenderBuffer(0)
};
static auto TEXCOORD_RECT_SLOT = 1;
if (!_pipeline) {
auto vs = gpu::StandardShaderLib::getDrawTexcoordRectTransformUnitQuadVS();
auto ps = gpu::StandardShaderLib::getDrawTextureOpaquePS();
gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps);
gpu::Shader::BindingSet slotBindings;
slotBindings.insert(gpu::Shader::Binding(std::string("texcoordRect"), TEXCOORD_RECT_SLOT));
gpu::Shader::makeProgram(*program, slotBindings);
gpu::StatePointer state = gpu::StatePointer(new gpu::State());
state->setDepthTest(gpu::State::DepthTest(false));
_pipeline = gpu::Pipeline::create(program, state);
}
gpu::doInBatch("DebugBloom::run", args->_context, [&](gpu::Batch& batch) {
batch.enableStereo(false);
batch.setFramebuffer(frameBuffer);
batch.setViewportTransform(args->_viewport);
batch.setProjectionTransform(glm::mat4());
batch.resetViewTransform();
batch.setPipeline(_pipeline);
Transform modelTransform;
if (_mode == DebugBloomConfig::MODE_ALL_LEVELS) {
batch._glUniform4f(TEXCOORD_RECT_SLOT, 0.0f, 0.0f, 1.f, 1.f);
modelTransform = gpu::Framebuffer::evalSubregionTexcoordTransform(framebufferSize, args->_viewport / 2);
modelTransform.postTranslate(glm::vec3(-1.0f, 1.0f, 0.0f));
batch.setModelTransform(modelTransform);
batch.setResourceTexture(0, levelTextures[0]);
batch.draw(gpu::TRIANGLE_STRIP, 4);
modelTransform.postTranslate(glm::vec3(2.0f, 0.0f, 0.0f));
batch.setModelTransform(modelTransform);
batch.setResourceTexture(0, levelTextures[1]);
batch.draw(gpu::TRIANGLE_STRIP, 4);
modelTransform.postTranslate(glm::vec3(-2.0f, -2.0f, 0.0f));
batch.setModelTransform(modelTransform);
batch.setResourceTexture(0, levelTextures[2]);
batch.draw(gpu::TRIANGLE_STRIP, 4);
modelTransform.postTranslate(glm::vec3(2.0f, 0.0f, 0.0f));
batch.setModelTransform(modelTransform);
batch.setResourceTexture(0, combinedBlurBuffer->getRenderBuffer(0));
batch.draw(gpu::TRIANGLE_STRIP, 4);
} else {
auto viewport = args->_viewport;
auto blurLevel = _mode - DebugBloomConfig::MODE_LEVEL0;
viewport.z /= 2;
batch._glUniform4f(TEXCOORD_RECT_SLOT, 0.5f, 0.0f, 0.5f, 1.f);
modelTransform = gpu::Framebuffer::evalSubregionTexcoordTransform(framebufferSize, viewport);
modelTransform.postTranslate(glm::vec3(-1.0f, 0.0f, 0.0f));
batch.setModelTransform(modelTransform);
batch.setResourceTexture(0, levelTextures[blurLevel]);
batch.draw(gpu::TRIANGLE_STRIP, 4);
}
});
}
void BloomConfig::setIntensity(float value) {
auto task = static_cast<render::Task::TaskConcept*>(_task);
auto blurJobIt = task->editJob("BloomApply");
assert(blurJobIt != task->_jobs.end());
blurJobIt->getConfiguration()->setProperty("intensity", value);
}
float BloomConfig::getIntensity() const {
auto task = static_cast<render::Task::TaskConcept*>(_task);
auto blurJobIt = task->getJob("BloomApply");
assert(blurJobIt != task->_jobs.end());
return blurJobIt->getConfiguration()->property("intensity").toFloat();
}
void BloomConfig::setSize(float value) {
std::string blurName{ "BloomBlurN" };
auto sigma = 0.5f+value*3.5f;
for (auto i = 0; i < BLOOM_BLUR_LEVEL_COUNT; i++) {
blurName.back() = '0' + i;
auto task = static_cast<render::Task::TaskConcept*>(_task);
auto blurJobIt = task->editJob(blurName);
assert(blurJobIt != task->_jobs.end());
auto& gaussianBlur = blurJobIt->edit<render::BlurGaussian>();
auto gaussianBlurParams = gaussianBlur.getParameters();
gaussianBlurParams->setFilterGaussianTaps(5, sigma);
// Gaussian blur increases at each level to have a slower rolloff on the edge
// of the response
sigma *= 1.5f;
}
}
Bloom::Bloom() {
}
void Bloom::configure(const Config& config) {
std::string blurName{ "BloomBlurN" };
for (auto i = 0; i < BLOOM_BLUR_LEVEL_COUNT; i++) {
blurName.back() = '0' + i;
auto blurConfig = config.getConfig<render::BlurGaussian>(blurName);
blurConfig->setProperty("filterScale", 1.0f);
}
}
void Bloom::build(JobModel& task, const render::Varying& inputs, render::Varying& outputs) {
// Start by computing threshold of color buffer input at quarter resolution
const auto bloomInputBuffer = task.addJob<BloomThreshold>("BloomThreshold", inputs, 4U);
// Multi-scale blur, each new blur is half resolution of the previous pass
const auto blurFB0 = task.addJob<render::BlurGaussian>("BloomBlur0", bloomInputBuffer, true);
const auto blurFB1 = task.addJob<render::BlurGaussian>("BloomBlur1", blurFB0, true, 2U);
const auto blurFB2 = task.addJob<render::BlurGaussian>("BloomBlur2", blurFB1, true, 2U);
const auto& input = inputs.get<Inputs>();
const auto& frameBuffer = input[1];
// Mix all blur levels at quarter resolution
const auto applyInput = BloomApply::Inputs(bloomInputBuffer, blurFB0, blurFB1, blurFB2).asVarying();
task.addJob<BloomApply>("BloomApply", applyInput);
// And them blend result in additive manner on top of final color buffer
const auto drawInput = BloomDraw::Inputs(frameBuffer, bloomInputBuffer).asVarying();
task.addJob<BloomDraw>("BloomDraw", drawInput);
const auto debugInput = DebugBloom::Inputs(frameBuffer, blurFB0, blurFB1, blurFB2, bloomInputBuffer).asVarying();
task.addJob<DebugBloom>("DebugBloom", debugInput);
}
|
e228992e8bcce6798d7d64703b8f0be8321a8ca3
|
d440f2be1035076d54d0c83b2419c42c2ad5c5ed
|
/src/components.cpp
|
c1a6fcb91fbc0bf9dcba06cfe91974bc63f4b64a
|
[] |
no_license
|
lasty/ld33_monster
|
d3caffc964ac0321ed60dc65203791207985de1d
|
5390870bee5f1e7f719103815a5f434635a64567
|
refs/heads/master
| 2016-09-10T01:39:27.549580
| 2015-08-24T01:37:17
| 2015-08-24T01:37:17
| 41,184,516
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,775
|
cpp
|
components.cpp
|
//
// Created by Tristan on 23/08/2015.
//
#include "components.h"
#include "entity.h"
#include "renderer.h"
#include "world.h"
#include <glm/geometric.hpp>
#include <iostream>
#include <sstream>
////////////////////////////////////////////////////////////////////////////////
Component::Component()
{}
Component::~Component()
{}
void Component::Render(int x, int y, Camera &cam)
{ }
void Component::Update(float dt)
{ }
////////////////////////////////////////////////////////////////////////////////
SpriteComponent::SpriteComponent(AnimatedSprite s)
: animated_sprite(s)
{ }
void SpriteComponent::Update(float dt)
{
animated_sprite.Update(dt);
}
void SpriteComponent::Render(int x, int y, Camera &cam)
{
animated_sprite.Render(x, y, zoom, cam);
}
////////////////////////////////////////////////////////////////////////////////
CollisionComponent::CollisionComponent(Entity *entity, World *world, int w, int h)
: entity(entity)
, world(world)
{
boundingbox.w = w;
boundingbox.h = h;
const auto & pos = entity->GetPositionAsPoint();
SetPosition(pos.x, pos.y);
}
void CollisionComponent::SetPosition(int x, int y)
{
boundingbox.x = x - (boundingbox.w / 2);
boundingbox.y = y - (boundingbox.h / 2);
}
float CollisionComponent::GetRadius() const
{
float max = glm::max(boundingbox.w, boundingbox.h);
return max/2.0f;
}
bool CollisionComponent::HasEntityCollisionAt(int x, int y) const
{
if (not world) return false;
SDL_Rect newbb = boundingbox;
newbb.x = x - (boundingbox.w / 2);
newbb.y = y - (boundingbox.h / 2);
return world->HasCollisionEntity(newbb, entity);
}
bool CollisionComponent::HasWorldCollisionAt(int x, int y) const
{
if (not world) return false;
SDL_Rect newbb = boundingbox;
newbb.x = x - (boundingbox.w / 2);
newbb.y = y - (boundingbox.h / 2);
return world->HasCollisionWorld(newbb);
}
bool CollisionComponent::HasCollisionAt(int x, int y) const
{
return HasWorldCollisionAt(x, y) or HasEntityCollisionAt(x, y);
}
bool CollisionComponent::HasCollision() const
{
if (not world) return false;
return world->HasCollisionAny(boundingbox, entity);
}
////////////////////////////////////////////////////////////////////////////////
MovableComponent::MovableComponent(Entity *entity, int x, int y)
:entity(entity)
,position{x, y}
{
}
void MovableComponent::SetPosition(float x, float y)
{
position.x = x;
position.y = y;
}
////////////////////////////////////////////////////////////////////////////////
PhysicsComponent::PhysicsComponent(Entity *entity, World *world, bool gravity)
: entity(entity)
, world(world)
, gravity(gravity)
{
assert(entity);
assert(world);
}
void PhysicsComponent::Update(float dt)
{
assert(entity);
assert(entity->GetCollision());
assert(entity->GetPosition());
glm::vec2 pos = entity->GetPosition()->GetPosition();
glm::vec2 pos_old = pos;
if (gravity)
{
//pos.y += 1;
glm::vec2 gravity_vec { 0.0f, 32 * 18.0f };
velocity += (gravity_vec * dt);
}
//Try splitting horizontal and vertical components, getting buggy with both at the same time
//Horizontal
glm::vec2 new_pos_horiz = pos;
new_pos_horiz.x += (velocity.x * dt);
bool collided_world_horiz = entity->GetCollision()->HasWorldCollisionAt((int)new_pos_horiz.x, (int)new_pos_horiz.y);
bool collided_entity_horiz = entity->GetCollision()->HasEntityCollisionAt((int)new_pos_horiz.x, (int)new_pos_horiz.y);
bool collided_any_horiz = collided_world_horiz or collided_entity_horiz;
//Vertical
glm::vec2 new_pos_vert = pos;
new_pos_vert.y += (velocity.y * dt);
bool collided_world_vert = entity->GetCollision()->HasWorldCollisionAt((int)new_pos_vert.x, (int)new_pos_vert.y);
bool collided_entity_vert = entity->GetCollision()->HasEntityCollisionAt((int)new_pos_vert.x, (int)new_pos_vert.y);
bool collided_any_vert = collided_world_vert or collided_entity_vert;
//pos += (velocity * dt); TODO
//SDL_Point newpos{int(pos.x), int(pos.y)}; //TODO?
if (collided_any_horiz)
{
float radius = entity->GetCollision()->GetBoundingBox().w / 2;
glm::vec2 collision_point = new_pos_horiz + (glm::normalize(velocity) * radius);
SDL_Point collision_pt { int(collision_point.x), int(collision_point.y) };
//rebound in other direction
velocity.x = velocity.x * -0.5f;
float how_hard = glm::distance(new_pos_horiz, pos_old);
if (how_hard > 0.1f)
{
if (collided_world_horiz)
{
world->AddParticleEffect(collision_pt, "dust");
}
else //collided with entity
{
world->AddParticleEffect(collision_pt, "blood");
}
}
}
else
{
pos.x = new_pos_horiz.x;
}
if (collided_any_vert)
{
float radius = entity->GetCollision()->GetBoundingBox().h / 2;
glm::vec2 collision_point = new_pos_vert + (glm::normalize(velocity) * radius);
SDL_Point collision_pt { int(collision_point.x), int(collision_point.y) };
//rebound in other direction
velocity.y = velocity.y * -0.5f;
float how_hard = glm::distance(new_pos_vert, pos_old);
if (how_hard > 0.1f)
{
if (collided_world_vert)
{
world->AddParticleEffect(collision_pt, "dust");
}
else //collided with entity
{
world->AddParticleEffect(collision_pt, "blood");
}
}
}
else
{
pos.y = new_pos_vert.y;
}
//if (pos_old != pos)
{
//place new position
entity->GetPosition()->SetPosition(pos.x, pos.y);
entity->GetCollision()->SetPosition((int)pos.x, (int)pos.y);
}
}
void PhysicsComponent::Impulse(const glm::vec2 &force)
{
velocity += force;
}
////////////////////////////////////////////////////////////////////////////////
Colour bounding_box_colour1 { "green" };
Colour bounding_box_colour2 { "red" };
DebugComponent::DebugComponent(Entity *entity, Renderer &renderer, Font &font, std::string debug_text, Colour colour)
: entity(entity)
, renderer(renderer)
, text(renderer, font, debug_text, colour)
, debug_text(debug_text)
{
}
void DebugComponent::SetText(const std::string &new_text)
{
if (debug_text != new_text)
{
debug_text = new_text;
text.SetText(new_text);
}
}
void DebugComponent::Update(float dt)
{
std::stringstream ss;
ss << entity->name;
if (entity->GetAIStateName())
{
ss << " - " << *entity->GetAIStateName();
}
SetText(ss.str());
}
void DebugComponent::Render(int x, int y, Camera &cam)
{
int xoff = 0;
int yoff = 0;
if (entity->GetCollision())
{
SDL_Rect bb = entity->GetCollision()->GetBoundingBox();
if (entity->GetCollision()->HasCollision())
{
renderer.SetDrawColour(bounding_box_colour2);
}
else
{
renderer.SetDrawColour(bounding_box_colour1);
}
renderer.DrawRect(bb, cam);
xoff = bb.x - x;
yoff = bb.y - y;
}
text.Render(x+xoff, y-yoff, 0.5f, cam);
}
////////////////////////////////////////////////////////////////////////////////
|
db9a5fc1f13796721f40b4f243f36287d5c3bc37
|
a2206795a05877f83ac561e482e7b41772b22da8
|
/Source/PV/build/VTK/Wrapping/Python/vtkPlanesPython.cxx
|
ca1554d8c742808358853475ab4364890f1358d6
|
[] |
no_license
|
supreethms1809/mpas-insitu
|
5578d465602feb4d6b239a22912c33918c7bb1c3
|
701644bcdae771e6878736cb6f49ccd2eb38b36e
|
refs/heads/master
| 2020-03-25T16:47:29.316814
| 2018-08-08T02:00:13
| 2018-08-08T02:00:13
| 143,947,446
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 18,398
|
cxx
|
vtkPlanesPython.cxx
|
// python wrapper for vtkPlanes
//
#define VTK_WRAPPING_CXX
#define VTK_STREAMS_FWD_ONLY
#include "vtkPythonArgs.h"
#include "vtkPythonOverload.h"
#include "vtkConfigure.h"
#include <vtksys/ios/sstream>
#include "vtkIndent.h"
#include "vtkPlanes.h"
#if defined(VTK_BUILD_SHARED_LIBS)
# define VTK_PYTHON_EXPORT VTK_ABI_EXPORT
# define VTK_PYTHON_IMPORT VTK_ABI_IMPORT
#else
# define VTK_PYTHON_EXPORT VTK_ABI_EXPORT
# define VTK_PYTHON_IMPORT VTK_ABI_EXPORT
#endif
extern "C" { VTK_PYTHON_EXPORT void PyVTKAddFile_vtkPlanes(PyObject *, const char *); }
extern "C" { VTK_PYTHON_EXPORT PyObject *PyVTKClass_vtkPlanesNew(const char *); }
#ifndef DECLARED_PyVTKClass_vtkImplicitFunctionNew
extern "C" { PyObject *PyVTKClass_vtkImplicitFunctionNew(const char *); }
#define DECLARED_PyVTKClass_vtkImplicitFunctionNew
#endif
static const char **PyvtkPlanes_Doc();
static PyObject *
PyvtkPlanes_GetClassName(PyObject *self, PyObject *args)
{
vtkPythonArgs ap(self, args, "GetClassName");
vtkObjectBase *vp = ap.GetSelfPointer(self, args);
vtkPlanes *op = static_cast<vtkPlanes *>(vp);
PyObject *result = NULL;
if (op && ap.CheckArgCount(0))
{
const char *tempr = (ap.IsBound() ?
op->GetClassName() :
op->vtkPlanes::GetClassName());
if (!ap.ErrorOccurred())
{
result = ap.BuildValue(tempr);
}
}
return result;
}
static PyObject *
PyvtkPlanes_IsA(PyObject *self, PyObject *args)
{
vtkPythonArgs ap(self, args, "IsA");
vtkObjectBase *vp = ap.GetSelfPointer(self, args);
vtkPlanes *op = static_cast<vtkPlanes *>(vp);
char *temp0 = NULL;
PyObject *result = NULL;
if (op && ap.CheckArgCount(1) &&
ap.GetValue(temp0))
{
int tempr = (ap.IsBound() ?
op->IsA(temp0) :
op->vtkPlanes::IsA(temp0));
if (!ap.ErrorOccurred())
{
result = ap.BuildValue(tempr);
}
}
return result;
}
static PyObject *
PyvtkPlanes_NewInstance(PyObject *self, PyObject *args)
{
vtkPythonArgs ap(self, args, "NewInstance");
vtkObjectBase *vp = ap.GetSelfPointer(self, args);
vtkPlanes *op = static_cast<vtkPlanes *>(vp);
PyObject *result = NULL;
if (op && ap.CheckArgCount(0))
{
vtkPlanes *tempr = (ap.IsBound() ?
op->NewInstance() :
op->vtkPlanes::NewInstance());
if (!ap.ErrorOccurred())
{
result = ap.BuildVTKObject(tempr);
if (result && PyVTKObject_Check(result))
{
PyVTKObject_GetObject(result)->UnRegister(0);
PyVTKObject_SetFlag(result, VTK_PYTHON_IGNORE_UNREGISTER, 1);
}
}
}
return result;
}
static PyObject *
PyvtkPlanes_SafeDownCast(PyObject *, PyObject *args)
{
vtkPythonArgs ap(args, "SafeDownCast");
vtkObject *temp0 = NULL;
PyObject *result = NULL;
if (ap.CheckArgCount(1) &&
ap.GetVTKObject(temp0, "vtkObject"))
{
vtkPlanes *tempr = vtkPlanes::SafeDownCast(temp0);
if (!ap.ErrorOccurred())
{
result = ap.BuildVTKObject(tempr);
}
}
return result;
}
static PyObject *
PyvtkPlanes_EvaluateFunction_s1(PyObject *self, PyObject *args)
{
vtkPythonArgs ap(self, args, "EvaluateFunction");
vtkObjectBase *vp = ap.GetSelfPointer(self, args);
vtkPlanes *op = static_cast<vtkPlanes *>(vp);
double temp0[3];
double save0[3];
const int size0 = 3;
PyObject *result = NULL;
if (op && ap.CheckArgCount(1) &&
ap.GetArray(temp0, size0))
{
ap.SaveArray(temp0, save0, size0);
double tempr = (ap.IsBound() ?
op->EvaluateFunction(temp0) :
op->vtkPlanes::EvaluateFunction(temp0));
if (ap.ArrayHasChanged(temp0, save0, size0) &&
!ap.ErrorOccurred())
{
ap.SetArray(0, temp0, size0);
}
if (!ap.ErrorOccurred())
{
result = ap.BuildValue(tempr);
}
}
return result;
}
static PyObject *
PyvtkPlanes_EvaluateFunction_s2(PyObject *self, PyObject *args)
{
vtkPythonArgs ap(self, args, "EvaluateFunction");
vtkObjectBase *vp = ap.GetSelfPointer(self, args);
vtkPlanes *op = static_cast<vtkPlanes *>(vp);
double temp0;
double temp1;
double temp2;
PyObject *result = NULL;
if (op && ap.CheckArgCount(3) &&
ap.GetValue(temp0) &&
ap.GetValue(temp1) &&
ap.GetValue(temp2))
{
double tempr = (ap.IsBound() ?
op->EvaluateFunction(temp0, temp1, temp2) :
op->vtkPlanes::EvaluateFunction(temp0, temp1, temp2));
if (!ap.ErrorOccurred())
{
result = ap.BuildValue(tempr);
}
}
return result;
}
static PyObject *
PyvtkPlanes_EvaluateFunction(PyObject *self, PyObject *args)
{
int nargs = vtkPythonArgs::GetArgCount(self, args);
switch(nargs)
{
case 1:
return PyvtkPlanes_EvaluateFunction_s1(self, args);
case 3:
return PyvtkPlanes_EvaluateFunction_s2(self, args);
}
vtkPythonArgs::ArgCountError(nargs, "EvaluateFunction");
return NULL;
}
static PyObject *
PyvtkPlanes_EvaluateGradient(PyObject *self, PyObject *args)
{
vtkPythonArgs ap(self, args, "EvaluateGradient");
vtkObjectBase *vp = ap.GetSelfPointer(self, args);
vtkPlanes *op = static_cast<vtkPlanes *>(vp);
double temp0[3];
double save0[3];
const int size0 = 3;
double temp1[3];
double save1[3];
const int size1 = 3;
PyObject *result = NULL;
if (op && ap.CheckArgCount(2) &&
ap.GetArray(temp0, size0) &&
ap.GetArray(temp1, size1))
{
ap.SaveArray(temp0, save0, size0);
ap.SaveArray(temp1, save1, size1);
if (ap.IsBound())
{
op->EvaluateGradient(temp0, temp1);
}
else
{
op->vtkPlanes::EvaluateGradient(temp0, temp1);
}
if (ap.ArrayHasChanged(temp0, save0, size0) &&
!ap.ErrorOccurred())
{
ap.SetArray(0, temp0, size0);
}
if (ap.ArrayHasChanged(temp1, save1, size1) &&
!ap.ErrorOccurred())
{
ap.SetArray(1, temp1, size1);
}
if (!ap.ErrorOccurred())
{
result = ap.BuildNone();
}
}
return result;
}
static PyObject *
PyvtkPlanes_SetPoints(PyObject *self, PyObject *args)
{
vtkPythonArgs ap(self, args, "SetPoints");
vtkObjectBase *vp = ap.GetSelfPointer(self, args);
vtkPlanes *op = static_cast<vtkPlanes *>(vp);
vtkPoints *temp0 = NULL;
PyObject *result = NULL;
if (op && ap.CheckArgCount(1) &&
ap.GetVTKObject(temp0, "vtkPoints"))
{
if (ap.IsBound())
{
op->SetPoints(temp0);
}
else
{
op->vtkPlanes::SetPoints(temp0);
}
if (!ap.ErrorOccurred())
{
result = ap.BuildNone();
}
}
return result;
}
static PyObject *
PyvtkPlanes_GetPoints(PyObject *self, PyObject *args)
{
vtkPythonArgs ap(self, args, "GetPoints");
vtkObjectBase *vp = ap.GetSelfPointer(self, args);
vtkPlanes *op = static_cast<vtkPlanes *>(vp);
PyObject *result = NULL;
if (op && ap.CheckArgCount(0))
{
vtkPoints *tempr = (ap.IsBound() ?
op->GetPoints() :
op->vtkPlanes::GetPoints());
if (!ap.ErrorOccurred())
{
result = ap.BuildVTKObject(tempr);
}
}
return result;
}
static PyObject *
PyvtkPlanes_SetNormals(PyObject *self, PyObject *args)
{
vtkPythonArgs ap(self, args, "SetNormals");
vtkObjectBase *vp = ap.GetSelfPointer(self, args);
vtkPlanes *op = static_cast<vtkPlanes *>(vp);
vtkDataArray *temp0 = NULL;
PyObject *result = NULL;
if (op && ap.CheckArgCount(1) &&
ap.GetVTKObject(temp0, "vtkDataArray"))
{
if (ap.IsBound())
{
op->SetNormals(temp0);
}
else
{
op->vtkPlanes::SetNormals(temp0);
}
if (!ap.ErrorOccurred())
{
result = ap.BuildNone();
}
}
return result;
}
static PyObject *
PyvtkPlanes_GetNormals(PyObject *self, PyObject *args)
{
vtkPythonArgs ap(self, args, "GetNormals");
vtkObjectBase *vp = ap.GetSelfPointer(self, args);
vtkPlanes *op = static_cast<vtkPlanes *>(vp);
PyObject *result = NULL;
if (op && ap.CheckArgCount(0))
{
vtkDataArray *tempr = (ap.IsBound() ?
op->GetNormals() :
op->vtkPlanes::GetNormals());
if (!ap.ErrorOccurred())
{
result = ap.BuildVTKObject(tempr);
}
}
return result;
}
static PyObject *
PyvtkPlanes_SetFrustumPlanes(PyObject *self, PyObject *args)
{
vtkPythonArgs ap(self, args, "SetFrustumPlanes");
vtkObjectBase *vp = ap.GetSelfPointer(self, args);
vtkPlanes *op = static_cast<vtkPlanes *>(vp);
double temp0[24];
double save0[24];
const int size0 = 24;
PyObject *result = NULL;
if (op && ap.CheckArgCount(1) &&
ap.GetArray(temp0, size0))
{
ap.SaveArray(temp0, save0, size0);
if (ap.IsBound())
{
op->SetFrustumPlanes(temp0);
}
else
{
op->vtkPlanes::SetFrustumPlanes(temp0);
}
if (ap.ArrayHasChanged(temp0, save0, size0) &&
!ap.ErrorOccurred())
{
ap.SetArray(0, temp0, size0);
}
if (!ap.ErrorOccurred())
{
result = ap.BuildNone();
}
}
return result;
}
static PyObject *
PyvtkPlanes_SetBounds_s1(PyObject *self, PyObject *args)
{
vtkPythonArgs ap(self, args, "SetBounds");
vtkObjectBase *vp = ap.GetSelfPointer(self, args);
vtkPlanes *op = static_cast<vtkPlanes *>(vp);
double temp0[6];
const int size0 = 6;
PyObject *result = NULL;
if (op && ap.CheckArgCount(1) &&
ap.GetArray(temp0, size0))
{
if (ap.IsBound())
{
op->SetBounds(temp0);
}
else
{
op->vtkPlanes::SetBounds(temp0);
}
if (!ap.ErrorOccurred())
{
result = ap.BuildNone();
}
}
return result;
}
static PyObject *
PyvtkPlanes_SetBounds_s2(PyObject *self, PyObject *args)
{
vtkPythonArgs ap(self, args, "SetBounds");
vtkObjectBase *vp = ap.GetSelfPointer(self, args);
vtkPlanes *op = static_cast<vtkPlanes *>(vp);
double temp0;
double temp1;
double temp2;
double temp3;
double temp4;
double temp5;
PyObject *result = NULL;
if (op && ap.CheckArgCount(6) &&
ap.GetValue(temp0) &&
ap.GetValue(temp1) &&
ap.GetValue(temp2) &&
ap.GetValue(temp3) &&
ap.GetValue(temp4) &&
ap.GetValue(temp5))
{
if (ap.IsBound())
{
op->SetBounds(temp0, temp1, temp2, temp3, temp4, temp5);
}
else
{
op->vtkPlanes::SetBounds(temp0, temp1, temp2, temp3, temp4, temp5);
}
if (!ap.ErrorOccurred())
{
result = ap.BuildNone();
}
}
return result;
}
static PyObject *
PyvtkPlanes_SetBounds(PyObject *self, PyObject *args)
{
int nargs = vtkPythonArgs::GetArgCount(self, args);
switch(nargs)
{
case 1:
return PyvtkPlanes_SetBounds_s1(self, args);
case 6:
return PyvtkPlanes_SetBounds_s2(self, args);
}
vtkPythonArgs::ArgCountError(nargs, "SetBounds");
return NULL;
}
static PyObject *
PyvtkPlanes_GetNumberOfPlanes(PyObject *self, PyObject *args)
{
vtkPythonArgs ap(self, args, "GetNumberOfPlanes");
vtkObjectBase *vp = ap.GetSelfPointer(self, args);
vtkPlanes *op = static_cast<vtkPlanes *>(vp);
PyObject *result = NULL;
if (op && ap.CheckArgCount(0))
{
int tempr = (ap.IsBound() ?
op->GetNumberOfPlanes() :
op->vtkPlanes::GetNumberOfPlanes());
if (!ap.ErrorOccurred())
{
result = ap.BuildValue(tempr);
}
}
return result;
}
static PyObject *
PyvtkPlanes_GetPlane_s1(PyObject *self, PyObject *args)
{
vtkPythonArgs ap(self, args, "GetPlane");
vtkObjectBase *vp = ap.GetSelfPointer(self, args);
vtkPlanes *op = static_cast<vtkPlanes *>(vp);
int temp0;
PyObject *result = NULL;
if (op && ap.CheckArgCount(1) &&
ap.GetValue(temp0))
{
vtkPlane *tempr = (ap.IsBound() ?
op->GetPlane(temp0) :
op->vtkPlanes::GetPlane(temp0));
if (!ap.ErrorOccurred())
{
result = ap.BuildVTKObject(tempr);
}
}
return result;
}
static PyObject *
PyvtkPlanes_GetPlane_s2(PyObject *self, PyObject *args)
{
vtkPythonArgs ap(self, args, "GetPlane");
vtkObjectBase *vp = ap.GetSelfPointer(self, args);
vtkPlanes *op = static_cast<vtkPlanes *>(vp);
int temp0;
vtkPlane *temp1 = NULL;
PyObject *result = NULL;
if (op && ap.CheckArgCount(2) &&
ap.GetValue(temp0) &&
ap.GetVTKObject(temp1, "vtkPlane"))
{
if (ap.IsBound())
{
op->GetPlane(temp0, temp1);
}
else
{
op->vtkPlanes::GetPlane(temp0, temp1);
}
if (!ap.ErrorOccurred())
{
result = ap.BuildNone();
}
}
return result;
}
static PyObject *
PyvtkPlanes_GetPlane(PyObject *self, PyObject *args)
{
int nargs = vtkPythonArgs::GetArgCount(self, args);
switch(nargs)
{
case 1:
return PyvtkPlanes_GetPlane_s1(self, args);
case 2:
return PyvtkPlanes_GetPlane_s2(self, args);
}
vtkPythonArgs::ArgCountError(nargs, "GetPlane");
return NULL;
}
static PyMethodDef PyvtkPlanes_Methods[] = {
{(char*)"GetClassName", PyvtkPlanes_GetClassName, METH_VARARGS,
(char*)"V.GetClassName() -> string\nC++: const char *GetClassName()\n\n"},
{(char*)"IsA", PyvtkPlanes_IsA, METH_VARARGS,
(char*)"V.IsA(string) -> int\nC++: int IsA(const char *name)\n\n"},
{(char*)"NewInstance", PyvtkPlanes_NewInstance, METH_VARARGS,
(char*)"V.NewInstance() -> vtkPlanes\nC++: vtkPlanes *NewInstance()\n\n"},
{(char*)"SafeDownCast", PyvtkPlanes_SafeDownCast, METH_VARARGS | METH_STATIC,
(char*)"V.SafeDownCast(vtkObject) -> vtkPlanes\nC++: vtkPlanes *SafeDownCast(vtkObject* o)\n\n"},
{(char*)"EvaluateFunction", PyvtkPlanes_EvaluateFunction, METH_VARARGS,
(char*)"V.EvaluateFunction([float, float, float]) -> float\nC++: double EvaluateFunction(double x[3])\nV.EvaluateFunction(float, float, float) -> float\nC++: double EvaluateFunction(double x, double y, double z)\n\n"},
{(char*)"EvaluateGradient", PyvtkPlanes_EvaluateGradient, METH_VARARGS,
(char*)"V.EvaluateGradient([float, float, float], [float, float, float])\nC++: void EvaluateGradient(double x[3], double n[3])\n\n"},
{(char*)"SetPoints", PyvtkPlanes_SetPoints, METH_VARARGS,
(char*)"V.SetPoints(vtkPoints)\nC++: virtual void SetPoints(vtkPoints *)\n\nSpecify a list of points defining points through which the planes\npass.\n"},
{(char*)"GetPoints", PyvtkPlanes_GetPoints, METH_VARARGS,
(char*)"V.GetPoints() -> vtkPoints\nC++: vtkPoints *GetPoints()\n\nSpecify a list of points defining points through which the planes\npass.\n"},
{(char*)"SetNormals", PyvtkPlanes_SetNormals, METH_VARARGS,
(char*)"V.SetNormals(vtkDataArray)\nC++: void SetNormals(vtkDataArray *normals)\n\nSpecify a list of normal vectors for the planes. There is a\none-to-one correspondence between plane points and plane normals.\n"},
{(char*)"GetNormals", PyvtkPlanes_GetNormals, METH_VARARGS,
(char*)"V.GetNormals() -> vtkDataArray\nC++: vtkDataArray *GetNormals()\n\nSpecify a list of normal vectors for the planes. There is a\none-to-one correspondence between plane points and plane normals.\n"},
{(char*)"SetFrustumPlanes", PyvtkPlanes_SetFrustumPlanes, METH_VARARGS,
(char*)"V.SetFrustumPlanes([float, float, float, float, float, float,\n float, float, float, float, float, float, float, float, float,\n float, float, float, float, float, float, float, float,\n float])\nC++: void SetFrustumPlanes(double planes[24])\n\nAn alternative method to specify six planes defined by the camera\nview frustrum. See vtkCamera::GetFrustumPlanes() documentation.\n"},
{(char*)"SetBounds", PyvtkPlanes_SetBounds, METH_VARARGS,
(char*)"V.SetBounds((float, float, float, float, float, float))\nC++: void SetBounds(const double bounds[6])\nV.SetBounds(float, float, float, float, float, float)\nC++: void SetBounds(double xmin, double xmax, double ymin,\n double ymax, double zmin, double zmax)\n\nAn alternative method to specify six planes defined by a bounding\nbox. The bounding box is a six-vector defined as\n(xmin,xmax,ymin,ymax,zmin,zmax). It defines six planes orthogonal\nto the x-y-z coordinate axes.\n"},
{(char*)"GetNumberOfPlanes", PyvtkPlanes_GetNumberOfPlanes, METH_VARARGS,
(char*)"V.GetNumberOfPlanes() -> int\nC++: int GetNumberOfPlanes()\n\nReturn the number of planes in the set of planes.\n"},
{(char*)"GetPlane", PyvtkPlanes_GetPlane, METH_VARARGS,
(char*)"V.GetPlane(int) -> vtkPlane\nC++: vtkPlane *GetPlane(int i)\nV.GetPlane(int, vtkPlane)\nC++: void GetPlane(int i, vtkPlane *plane)\n\nCreate and return a pointer to a vtkPlane object at the ith\nposition. Asking for a plane outside the allowable range returns\nNULL. This method always returns the same object. Use\nGetPlane(int i, vtkPlane *plane) instead\n"},
{NULL, NULL, 0, NULL}
};
static vtkObjectBase *PyvtkPlanes_StaticNew()
{
return vtkPlanes::New();
}
PyObject *PyVTKClass_vtkPlanesNew(const char *modulename)
{
PyObject *cls = PyVTKClass_New(&PyvtkPlanes_StaticNew,
PyvtkPlanes_Methods,
"vtkPlanes", modulename,
NULL, NULL,
PyvtkPlanes_Doc(),
PyVTKClass_vtkImplicitFunctionNew(modulename));
return cls;
}
const char **PyvtkPlanes_Doc()
{
static const char *docstring[] = {
"vtkPlanes - implicit function for convex set of planes\n\n",
"Superclass: vtkImplicitFunction\n\n",
"vtkPlanes computes the implicit function and function gradient for a\nset of planes. The planes must define a convex space.\n\nThe function value is the closest first order distance of a point to\nthe convex region defined by the planes. The function gradient is the\nplane normal at the function value. Note that the normals must point\noutside of the convex region. Thus, a negative function value means",
"\nthat a point is inside the convex region.\n\nThere are several methods to define the set of planes. The most\ngeneral is to supply an instance of vtkPoints and an instance of\nvtkDataArray. (The points define a point on the plane, and the\nnormals corresponding plane normals.) Two other specialized ways are\nto 1) supply six planes defining the view frustrum of a camera, and\n2) provide a bounding box.\n",
"\nSee Also:\n\nvtkCamera\n\n",
NULL
};
return docstring;
}
void PyVTKAddFile_vtkPlanes(
PyObject *dict, const char *modulename)
{
PyObject *o;
o = PyVTKClass_vtkPlanesNew(modulename);
if (o && PyDict_SetItemString(dict, (char *)"vtkPlanes", o) != 0)
{
Py_DECREF(o);
}
}
|
0e4b8a65183eb8c719aefe3535891a3ee1f1c3e7
|
3d3d1316d82c7d9a7ee5a7c56963c5f13215add2
|
/lib/io/ValueToString.cpp
|
fc0baf516aad3972d78258d55fe08acfdf7210fa
|
[] |
no_license
|
mcopik/profile-tool
|
bdb97d33fbc2260c5781b95f8219ed03d9c871f5
|
8754ab1f71a57f5421c0514c6bc3e76b69c37d91
|
refs/heads/master
| 2020-03-11T09:05:01.915139
| 2018-07-26T14:49:50
| 2018-07-26T14:49:50
| 129,901,448
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,582
|
cpp
|
ValueToString.cpp
|
#include "io/ValueToString.hpp"
#include "io/SCEVAnalyzer.hpp"
#include "util/util.hpp"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/Value.h"
#include "llvm/IR/Constants.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include <ostream>
llvm::Optional<std::string> ValueToString::toString(const Constant * val)
{
assert(val);
if(const ConstantInt * integer = dyn_cast<ConstantInt>(val)) {
return std::to_string(integer->getSExtValue());
} else if(const GlobalVariable * var = dyn_cast<GlobalVariable>(val)) {
return var->getName().str();
} else if(const UndefValue * var = dyn_cast<UndefValue>(val)) {
return llvm::Optional<std::string>();
}
else {
//FIXME:
return llvm::Optional<std::string>();
//assert(!"Unknown type!");
}
}
llvm::Optional<std::string> ValueToString::toString(const Argument * arg)
{
assert(arg);
const Function * f = arg->getParent();
if(f->hasName()) {
// remove leading underscores - some symbolic solvers (e.g. Matlab's) go crazy because of that
std::string name = f->getName().str();
auto idx = name.find_first_not_of("_");
name = name.substr(idx, name.length() - idx + 1);
return cppsprintf("%s_%d", name, arg->getArgNo());
} else {
return cppsprintf("unknown_function(%s)", arg->getArgNo());
}
}
llvm::Optional<std::string> ValueToString::toString(Value * value)
{
assert(value);
//dbgs() << "Print: " << *value << "\n";
const SCEV * scev = SE.isSCEVable(value->getType()) ? SE.getSCEV(value) : nullptr;
//if(scev)
// dbgs() << "Print SCEV: " << *scev << "\n";
if(const Constant * val = dyn_cast<Constant>(value)) {
return toString(val);
} else if(const Argument * arg = dyn_cast<Argument>(value)) {
return toString(arg);
} else if(scev && scevPrinter.couldBeIV(scev)) {
return scevPrinter.toString(scev, false);
} else if(Instruction * instr = dyn_cast<Instruction>(value)) {
return toString(instr);
}
else {
if(value->hasName()) {
return value->getName().str();
} else {
dbgs() << "Unknown name: " << *value << " " << value->getValueID() << "\n";
// report lack of name
assert(!"Name unknown!");
}
}
}
llvm::Optional<std::string> ValueToString::toString(Instruction * instr, bool exitsOnSuccess)
{
dbgs() << instr << '\n';
if(instr->isCast()) {
//TODO: implement casts - for the momement ignore
return toString(instr->getOperand(0));
} else if(const BinaryOperator * op = dyn_cast<BinaryOperator>(instr)) {//const SCEV * scev = SE.getSCEV(value)) {
//return scevPrinter.toString(scev);
return toString(op);
} else if(const ICmpInst * cmp_instr = dyn_cast<ICmpInst>(instr)) {
return toString(cmp_instr, exitsOnSuccess);
} else if(const LoadInst * load_instr = dyn_cast<LoadInst>(instr)) {
//TODO: get debug information
//std::string type;
//raw_string_ostream os(type);
if(const GetElementPtrInst * get_inst = dyn_cast<GetElementPtrInst>(load_instr->getOperand(0))) {
return toString(get_inst);
} else if(ConstantExpr * const_expr = dyn_cast<ConstantExpr>(load_instr->getOperand(0))) {
//dbgs() << *const_expr << " " << const_expr->isGEPWithNoNotionalOverIndexing() << "\n";
//FIXME:
//assert(const_expr->isGEPWithNoNotionalOverIndexing());
if(!const_expr->isGEPWithNoNotionalOverIndexing())
return llvm::Optional<std::string>();
Value * x = const_expr->getOperand(0);
// dbgs() << dyn_cast<GlobalVariable>(x)->getName() << " " << isa<ConstantArray>(x) << " " << *const_expr->getOperand(1) << "\n";
//return toString(dyn_cast<GetElementPtrInst>(const_expr->getAsInstruction()));
return cppsprintf("%s_%d", toString(x), dyn_cast<ConstantInt>(const_expr->getOperand(2))->getUniqueInteger().getSExtValue());
}
return load_instr->getOperand(0)->getName().str();//->print(os);
//return os.str();
} else if(const PHINode * phi = dyn_cast<PHINode>(instr)) {
std::string str;
llvm::raw_string_ostream ss(str);
phi->print(ss);
log << "Detected unsolvable PHI: " << ss.str();
const DebugLoc & loc = phi->getDebugLoc();
auto * scope = phi->getFunction()->getSubprogram();
if(loc) {
log << "; file: " << loc.get()->getFilename().str() << " line: " << loc.getLine() << "\n";
} else if (scope) {
log << "; function: " << scope->getName().str() << " file: " << scope->getFilename().str() << " line: " << scope->getLine() << "\n";
} else {
log << ";\n";
}
return llvm::Optional<std::string>();
} else if(const CallInst * invoke = dyn_cast<CallInst>(instr)) {
//dbgs() << "Function: " << invoke->getOperand(0) << "\n";
// TODO: process simple function calls
return llvm::Optional<std::string>();
}
//FIXME:
return llvm::Optional<std::string>();
//assert(!"Unknown instr type!");
}
llvm::Optional<std::string> ValueToString::toString(const ICmpInst * integer_comparison, bool exitOnSuccess)
{
//dbgs() << *integer_comparison << "\n";
std::string val;
// Get negation!
switch (integer_comparison->getPredicate()) {
case CmpInst::ICMP_EQ:
val += exitOnSuccess ? " ~= " : " == ";
break;
case CmpInst::ICMP_NE:
val += exitOnSuccess ? " == " : " ~= ";
break;
case CmpInst::ICMP_UGT:
case CmpInst::ICMP_SGT:
val += exitOnSuccess ? " <= " : " > ";
break;
case CmpInst::ICMP_UGE:
case CmpInst::ICMP_SGE:
val += exitOnSuccess ? " < " : " >= ";
break;
case CmpInst::ICMP_ULT:
case CmpInst::ICMP_SLT:
val += exitOnSuccess ? " >= " : " < ";
break;
case CmpInst::ICMP_ULE:
case CmpInst::ICMP_SLE:
val += exitOnSuccess ? " > " : " <= ";
break;
}
return cppsprintf("%s%s%s", toString(integer_comparison->getOperand(0)), val, toString(integer_comparison->getOperand(1)));
}
llvm::Optional<std::string> ValueToString::toString(const BinaryOperator * op)
{
llvm::Optional<std::string> op1 = toString(op->getOperand(0));
llvm::Optional<std::string> op2 = toString(op->getOperand(1));
std::string op_str;
switch(op->getOpcode())
{
case BinaryOperator::FMul:
case BinaryOperator::Mul:
op_str = " * ";
break;
case BinaryOperator::FAdd:
case BinaryOperator::Add:
op_str = " + ";
break;
case BinaryOperator::FSub:
case BinaryOperator::Sub:
op_str = " - ";
break;
case BinaryOperator::FDiv:
op_str = " / ";
break;
// TODO: verify it is indeed multiplication by two?
case BinaryOperator::Shl:
op_str = " * ";
op2 = cppsprintf("( 2^(%s) )", op2);
break;
default:
//FIXME:
//assert(!"Unknown binary operator!");
return llvm::Optional<std::string>();
}
return cppsprintf("%s%s%s", op1, op_str, op2);
}
llvm::Optional<std::string> ValueToString::toString(const GetElementPtrInst * get)
{
//dbgs() << get->getNumOperands() << "\n";
//assert(false);
//FIXME:
return llvm::Optional<std::string>();
}
|
b7db4cdd5b4c65b19cee14887f8c90379a1e59b2
|
22564fcbec899e6990a3ffeb7d5bd6570ac1557c
|
/TCP_็ฝ็ป่ฎก็ฎๅจ/cal_protocol.hpp
|
e4da7968ad1c94a4a53cc839c52b6cefa16020ea
|
[] |
no_license
|
Mjianjianjiao/Linux
|
6703ece57cc8086b8a5ed7e91bfa729738521bea
|
9d8928e33d6215a3b2be0d3c3b154f9137ca5a88
|
refs/heads/master
| 2020-04-02T16:51:07.940731
| 2020-01-22T01:32:47
| 2020-01-22T01:32:47
| 154,631,576
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 161
|
hpp
|
cal_protocol.hpp
|
#pragma once
#include <iostream>
typedef struct Request{
int x;
int y;
char singel;
}request;
typedef struct Reponse{
int sum;
int status;
}reponse;
|
7eeb434613acd1915e25615a01a1c00cea51de00
|
2eaf198cab76506045fcc4d312abd12afc9fc713
|
/src/ripple/server/impl/BasePeer.h
|
bc5375b87f7f170c0e45119197accb3c52c8b436
|
[
"LicenseRef-scancode-free-unknown",
"ISC"
] |
permissive
|
XRPLF/rippled
|
26c378a72f65dde2ee9427a8a106505a60a3303d
|
300b7e078a4bc511f30b74509d416e5081ec3650
|
refs/heads/develop
| 2023-08-31T00:07:03.935167
| 2023-08-21T23:22:59
| 2023-08-21T23:23:06
| 2,724,167
| 267
| 126
|
ISC
| 2023-09-14T21:57:05
| 2011-11-07T04:40:15
|
C++
|
UTF-8
|
C++
| false
| false
| 3,300
|
h
|
BasePeer.h
|
//------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2012, 2013 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef RIPPLE_SERVER_BASEPEER_H_INCLUDED
#define RIPPLE_SERVER_BASEPEER_H_INCLUDED
#include <ripple/beast/utility/WrappedSink.h>
#include <ripple/server/Port.h>
#include <ripple/server/impl/LowestLayer.h>
#include <ripple/server/impl/io_list.h>
#include <boost/asio.hpp>
#include <atomic>
#include <cassert>
#include <functional>
#include <string>
namespace ripple {
// Common part of all peers
template <class Handler, class Impl>
class BasePeer : public io_list::work
{
protected:
using clock_type = std::chrono::system_clock;
using error_code = boost::system::error_code;
using endpoint_type = boost::asio::ip::tcp::endpoint;
using waitable_timer = boost::asio::basic_waitable_timer<clock_type>;
Port const& port_;
Handler& handler_;
endpoint_type remote_address_;
beast::WrappedSink sink_;
beast::Journal const j_;
boost::asio::executor_work_guard<boost::asio::executor> work_;
boost::asio::strand<boost::asio::executor> strand_;
public:
BasePeer(
Port const& port,
Handler& handler,
boost::asio::executor const& executor,
endpoint_type remote_address,
beast::Journal journal);
void
close() override;
private:
Impl&
impl()
{
return *static_cast<Impl*>(this);
}
};
//------------------------------------------------------------------------------
template <class Handler, class Impl>
BasePeer<Handler, Impl>::BasePeer(
Port const& port,
Handler& handler,
boost::asio::executor const& executor,
endpoint_type remote_address,
beast::Journal journal)
: port_(port)
, handler_(handler)
, remote_address_(remote_address)
, sink_(
journal.sink(),
[] {
static std::atomic<unsigned> id{0};
return "##" + std::to_string(++id) + " ";
}())
, j_(sink_)
, work_(executor)
, strand_(executor)
{
}
template <class Handler, class Impl>
void
BasePeer<Handler, Impl>::close()
{
if (!strand_.running_in_this_thread())
return post(
strand_, std::bind(&BasePeer::close, impl().shared_from_this()));
error_code ec;
ripple::get_lowest_layer(impl().ws_).socket().close(ec);
}
} // namespace ripple
#endif
|
938791fe711c9cf32c4390362219b8906c2c5178
|
8893759f93c5dce996f76ed40eaa1d6a435cb4a6
|
/Flavio/commit1.cpp
|
e2a1d366899b0a78157fcecd7479daad9e40ff1c
|
[] |
no_license
|
UnPComp2013/Grupo4
|
dbcc9902b32f611e3795742f6f69f4b38a31913d
|
2b42f73259dbb4f431bfb10e84c9205fa8b26828
|
refs/heads/master
| 2020-06-05T01:03:54.283639
| 2014-11-07T01:56:15
| 2014-11-07T01:56:15
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 428
|
cpp
|
commit1.cpp
|
#include <iostream>
using namespace std;
int main()
{
int a,b,c=0;
cout<<"Enter value of 1st variable: ";
cin>>a;
cout<<"Enter value of 2nd variable: ";
cin>>b;
///{ Write your code here
if(a>b)
{
cout<<"Greater value is "<<a;
}
else if(a<b)
{
cout<<"Greater value is "<<b;
}
else if(a=b)
{
cout<<"Both are equal";
}
}
|
69bc3b43feae61bf91fffc7f9d643caa676f64ab
|
6f41a5edf34f357f599c75e9dfab3d629a36490a
|
/src/10953.cpp
|
8ed6a2137bc2154879dbc33d0f32b47604cd5423
|
[] |
no_license
|
beotborry/BaekjoonPS
|
3ca78e896f80fe00d36b30b50cc79f5b3cb44555
|
6a114222949419ca96f2038f2ec21fdfe41e7912
|
refs/heads/master
| 2020-12-13T20:16:56.661270
| 2020-01-18T04:13:23
| 2020-01-18T04:13:23
| 234,521,444
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 274
|
cpp
|
10953.cpp
|
#include <iostream>
#include <cstring>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int T; cin >> T;
while(T--) {
string order; cin >> order;
int a, b;
a = order[0] - '0';
b = order[2] - '0';
cout << a + b << "\n";
}
}
|
bdc9c4c15624e3817c3171cb902ed1f9f98233ca
|
ff9a1c835af0d8f7263bec5a29d49e8e67182793
|
/ๅๆ่ฎบๆ/my own/active camera v1.0/viewbutton/MainFrm.h
|
56e223e493d7f6500a9eb6f9bdd0bec1ac89e921
|
[] |
no_license
|
xhyangxianjun/autotracking
|
0a2f598dbdaacfc58a6743894fbfb6c8fd67ed64
|
5b7d20f9086e73c78457338ef0dfb22c8c9a55df
|
refs/heads/master
| 2022-02-12T14:46:17.066264
| 2018-10-01T23:57:31
| 2018-10-01T23:57:31
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,431
|
h
|
MainFrm.h
|
// MainFrm.h : interface of the CMainFrame class
//
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_MAINFRM_H__501697B9_F75E_49A2_8CF1_6AC18015DADF__INCLUDED_)
#define AFX_MAINFRM_H__501697B9_F75E_49A2_8CF1_6AC18015DADF__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "XPReBar.h" // Added by ClassView
#include "XPSliderCtrl.h" // Added by ClassView
class CMainFrame : public CFrameWnd
{
protected: // create from serialization only
CMainFrame();
DECLARE_DYNCREATE(CMainFrame)
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CMainFrame)
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CMainFrame();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected: // control bar embedded members
CStatusBar m_wndStatusBar;
CToolBar m_wndToolBar;
CXPReBar m_wndReBar;
CXPSliderCtrl m_wndSlider;
CImageList m_imglistToolBarHighLighted;
CImageList m_imglistToolBarDisabled;
CImageList m_imglistToolBar;
// Generated message map functions
protected:
void OnUpdatePlayerState(CCmdUI *pCmdUI);
LRESULT OnUpdateCursorPosition(WPARAM wParam, LPARAM lParam);
LRESULT OnUpdateFPS(WPARAM wParam, LPARAM lParam);
LRESULT OnUpdatePositions(WPARAM wParam, LPARAM lParam);
//{{AFX_MSG(CMainFrame)
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnClose();
afx_msg void OnOpen();
afx_msg void OnAdjust();
afx_msg void OnCapture();
afx_msg void OnPause();
afx_msg void OnPlay();
afx_msg void OnStep();
afx_msg void OnStop();
afx_msg void OnPurge();
afx_msg void OnUpdateOpen(CCmdUI* pCmdUI);
afx_msg void OnUpdatePlay(CCmdUI* pCmdUI);
afx_msg void OnUpdatePause(CCmdUI* pCmdUI);
afx_msg void OnUpdatePurge(CCmdUI* pCmdUI);
afx_msg void OnUpdateStop(CCmdUI* pCmdUI);
afx_msg void OnUpdateStep(CCmdUI* pCmdUI);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_MAINFRM_H__501697B9_F75E_49A2_8CF1_6AC18015DADF__INCLUDED_)
|
b2799ba6deb9703920dff358f04ffd466f40509b
|
435a32fff97a829d82e3cdafa13604929a8aa33c
|
/Tests/voxel/PolyVoxVolume.cpp
|
bb45eade87a095db04d5e6325f5e334c43774590
|
[
"BSD-2-Clause-Views"
] |
permissive
|
DarkMagicCK/UKN
|
b2d264183a5788ef8a01d29dc34a9ec37c6863fc
|
2e48607d7bb2a660371296223ea6a48b8a328af1
|
refs/heads/master
| 2021-01-23T21:01:43.595581
| 2013-08-27T19:19:19
| 2013-08-27T19:19:19
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,355
|
cpp
|
PolyVoxVolume.cpp
|
#include "PolyVoxVolume.h"
#undef MessageBox
#include "mist/SysUtil.h"
#include "PolyVoxCore/CubicSurfaceExtractorWithNormals.h"
#include "PolyVoxCore/MarchingCubesSurfaceExtractor.h"
#include "PolyVoxCore/SurfaceMesh.h"
#include "PolyVoxCore/SimpleVolume.h"
namespace ukn {
namespace voxel {
using namespace PolyVox;
void createSphereInVolume(SimpleVolume<uint8_t>& volData, float fRadius)
{
//This vector hold the position of the center of the volume
Vector3DFloat v3dVolCenter(volData.getWidth() / 2, volData.getHeight() / 2, volData.getDepth() / 2);
//This three-level for loop iterates over every voxel in the volume
for (int z = 0; z < volData.getDepth(); z++)
{
for (int y = 0; y < volData.getHeight(); y++)
{
for (int x = 0; x < volData.getWidth(); x++)
{
//Store our current position as a vector...
Vector3DFloat v3dCurrentPos(x,y,z);
//And compute how far the current position is from the center of the volume
float fDistToCenter = (v3dCurrentPos - v3dVolCenter).length();
uint8_t uVoxelValue = 0;
//If the current voxel is less than 'radius' units from the center then we make it solid.
if(fDistToCenter <= fRadius)
{
//Our new voxel value
uVoxelValue = 255;
}
//Wrte the voxel value into the volume
volData.setVoxelAt(x, y, z, uVoxelValue);
}
}
}
}
void createPlaneInVolume(SimpleVolume<uint8_t>& volData, int thickess)
{
//This vector hold the position of the center of the volume
Vector3DFloat v3dVolCenter(volData.getWidth() / 2, volData.getHeight() / 2, volData.getDepth() / 2);
//This three-level for loop iterates over every voxel in the volume
for (int z = 0; z < volData.getDepth(); z++)
{
for (int y = 0; y < volData.getHeight(); y++)
{
for (int x = 0; x < volData.getWidth(); x++)
{
if(y < thickess)
volData.setVoxelAt(x, y, z, 255);
else
volData.setVoxelAt(x, y, z, 0);
}
}
}
}
std::vector<VertexUVNormal> tranform_pv_vertex_to_vertex_uv_normal(const std::vector<PositionMaterialNormal>& pv) {
std::vector<VertexUVNormal> n;
std::for_each(pv.begin(), pv.end(), [&](const PositionMaterialNormal& pvv) {
VertexUVNormal vtx;
vtx.normal = Vector3(pvv.getNormal().getX(),
pvv.getNormal().getY(),
pvv.getNormal().getZ());
vtx.position = Vector3(pvv.getPosition().getX(),
pvv.getPosition().getY(),
pvv.getPosition().getZ());
vtx.uv = Vector2(0, 0);
n.push_back(vtx);
});
return n;
}
struct PVVertexMeshNormalVertex {
static ukn::vertex_elements_type Format() {
vertex_elements_type static_format = VertexElementsBuilder()
.add(VertexElement(VU_Position, EF_Float3, 0))
.add(VertexElement(VU_Normal, EF_Float3, 0))
.add(VertexElement(VU_UV/* for material? */, EF_Float, 0))
.to_vector();
return static_format;
}
};
SimplePolyvoxVolume::SimplePolyvoxVolume() {
}
SimplePolyvoxVolume::~SimplePolyvoxVolume() {
}
Box SimplePolyvoxVolume::getBound() const {
return Box();
}
const UknString& SimplePolyvoxVolume::getName() const {
static UknString name(L"SimplePolyvoxVolume");
return name;
}
RenderBufferPtr SimplePolyvoxVolume::getRenderBuffer() const {
return mRenderBuffer;
}
void SimplePolyvoxVolume::initSphere() {
//Create an empty volume and then place a sphere in it
SimpleVolume<uint8_t> volData(PolyVox::Region(Vector3DInt32(0, 0, 0),
Vector3DInt32(63, 63, 63)));
createSphereInVolume(volData, 30);
//A mesh object to hold the result of surface extraction
SurfaceMesh<PositionMaterialNormal> mesh;
//Create a surface extractor. Comment out one of the following two lines to decide which type gets created.
CubicSurfaceExtractorWithNormals< SimpleVolume<uint8_t> > surfaceExtractor(&volData, volData.getEnclosingRegion(), &mesh);
//MarchingCubesSurfaceExtractor< SimpleVolume<uint8_t> > surfaceExtractor(&volData, volData.getEnclosingRegion(), &mesh);
//Execute the surface extractor.
surfaceExtractor.execute();
// std::vector<VertexUVNormal> vertices(tranform_pv_vertex_to_vertex_uv_normal(mesh.getVertices()));
this->createBuffers(mesh);
MaterialPtr default_mat = MakeSharedPtr<Material>();
default_mat->ambient = color::Skyblue.getRGB();
default_mat->diffuse = color::Skyblue.getRGB();
default_mat->emit = float3(0, 0, 0);
default_mat->opacity = 1.f;
default_mat->shininess = 10.f;
default_mat->specular = float3(0, 0, 0);
default_mat->specular_power = 16.f;
mMaterial = default_mat;
}
void SimplePolyvoxVolume::initPlane(int thickness) {
SimpleVolume<uint8_t> volData(PolyVox::Region(Vector3DInt32(0, 0, 0),
Vector3DInt32(128, 128, 128)));
createPlaneInVolume(volData, thickness);
SurfaceMesh<PositionMaterialNormal> mesh;
CubicSurfaceExtractorWithNormals< SimpleVolume<uint8_t> > surfaceExtractor(&volData, volData.getEnclosingRegion(), &mesh);
surfaceExtractor.execute();
this->createBuffers(mesh);
MaterialPtr default_mat = MakeSharedPtr<Material>();
default_mat->ambient = color::Lightgrey.getRGB();
default_mat->diffuse = color::Lightgrey.getRGB();
default_mat->emit = float3(0, 0, 0);
default_mat->opacity = 1.f;
default_mat->shininess = 10.f;
default_mat->specular = float3(0, 0, 0);
default_mat->specular_power = 16.f;
mMaterial = default_mat;
}
void SimplePolyvoxVolume::createBuffers(const SurfaceMesh<PositionMaterialNormal>& mesh) {
ukn::GraphicFactory& gf = Context::Instance().getGraphicFactory();
ukn::GraphicBufferPtr vtxBuffer = gf.createVertexBuffer(GraphicBuffer::None,
GraphicBuffer::Static,
mesh.getVertices().size(),
&mesh.getVertices()[0],
PVVertexMeshNormalVertex::Format());
ukn::GraphicBufferPtr idxBuffer = gf.createIndexBuffer(GraphicBuffer::None,
GraphicBuffer::Static,
mesh.getIndices().size(),
&mesh.getIndices()[0]);
if(vtxBuffer && idxBuffer) {
mRenderBuffer = gf.createRenderBuffer();
mRenderBuffer->bindVertexStream(vtxBuffer, PVVertexMeshNormalVertex::Format());
mRenderBuffer->bindIndexStream(idxBuffer);
mRenderBuffer->useIndexStream(true);
} else {
log_error(L"Error building volume data");
}
}
}
}
|
d372259b6392c0d0b78c2bf61eb55dc54a532681
|
9134496e7db9ed0f132fe446d092cbeabde3d251
|
/LabWork_5/LabWork_5.cpp
|
5272210494e56c066c0b90e601382668aac258cc
|
[] |
no_license
|
vitoss-ux/ITMO.Cpp
|
b692ded539a02d15d0e98bdad82d0816e2cf11fc
|
62bd28dfcdb8236765afefec728acebbc0084133
|
refs/heads/main
| 2023-07-01T22:47:29.417651
| 2021-08-23T19:39:22
| 2021-08-23T19:39:22
| 385,296,225
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,458
|
cpp
|
LabWork_5.cpp
|
๏ปฟ// LabWork_5.cpp : ะญัะพั ัะฐะนะป ัะพะดะตัะถะธั ััะฝะบัะธั "main". ะะดะตัั ะฝะฐัะธะฝะฐะตััั ะธ ะทะฐะบะฐะฝัะธะฒะฐะตััั ะฒัะฟะพะปะฝะตะฝะธะต ะฟัะพะณัะฐะผะผั.
//
#include <iostream>
#include <cmath>
#include <Windows.h>
using namespace std;
// ะะตัะตะดะฐัะฐ ะผะฐััะธะฒะฐ ะฒ ััะฝะบัะธั
void ArrayData(int, int[]);
void ArraySorter(int, int[]);
int main()
{
SetConsoleOutputCP(1251);
SetConsoleCP(1251);
const int n = 10;
int mas[n];
for (int i = 0; i < n; i++) {
cout << "mas[" << i << "] = ";
cin >> mas[i]; // ะทะฐะฟะพะปะฝัะตะผ ะผะฐััะธะฒ ะธะท 10 ัะป-ัะพะฒ ั ะบะปะฐะฒะธะฐัััั
}
ArrayData(n, mas);
ArraySorter(n, mas);
}
void ArrayData(int n, int mas[]) {
int sum = 0;
for (int i = 0; i < n; i++) {
sum += mas[i]; // ััะผะผะฐ ะฒัะตั
ัะป-ัะพะฒ ะผะฐััะธะฒะฐ
}
cout << "ะกัะผะผะฐ ัะปะตะผะตะฝัะพะฒ ะผะฐััะธะฒะฐ: " << sum << endl;
int average = sum / n;
cout << "ะกัะตะดะฝะตะต ะทะฝะฐัะตะฝะธะต ัะปะตะผะตะฝัะพะฒ ะผะฐััะธะฒะฐ: " << average << endl;
int even = 0;
int odd = 0; // ััะตััะธะบ ะธะฝะดะตะบัะฐ ัะตัะฝัะน/ะฝะต ัะตัะฝัะน
for (int i = 0; i < n; i++) {
if (i % 2 == 0)
even += mas[i]; // ัะบะปะฐะดัะฒะฐะตะผ ัะตัะฝัะต ะธะฝะดะตะบัั
else
odd += mas[i];
}
cout << "ะกัะผะผะฐ ัะปะตะผะตะฝัะพะฒ ะผะฐััะธะฒะฐ ั ะะ ัะตัะฝัะผ ะธะฝะดะตะบัะพะผ: " << odd << endl;
cout << "ะกัะผะผะฐ ัะปะตะผะตะฝัะพะฒ ะผะฐััะธะฒะฐ ั ัะตัะฝัะผ ะธะฝะดะตะบัะพะผ: " << even << endl;
int max = mas[0]; // ััะตััะธะบะธ ะดะปั ัะปะตะผะตะฝัะพะฒ ะผะฐััะธะฒะฐ ะธ ะธะฝะดะตะบัะฐ
int min = mas[0];
int maxInd = 0;
int minInd = 0;
for (int i = 0; i < n; i++) {
if (max < mas[i])
max = mas[i];
if (min > mas[i])
min = mas[i];
if (mas[i] > mas[maxInd])
maxInd = i;
if (mas[i] < mas[minInd])
minInd = i;
}
cout << "ะะฐะบัะธะผะฐะปัะฝัะน ัะปะตะผะตะฝั: " << max << " ะะฝะดะตะบั: " << maxInd << endl;
cout << "ะะธะฝะธะผะฐะปัะฝัะน ัะปะตะผะตะฝั: " << min << " ะะฝะดะตะบั: " << minInd << endl;
int c = 1;
for (int i = min(maxInd, minInd) + 1; i < max(maxInd, minInd); i++) {
c *= mas[i];
}
cout << "ะัะพะธะทะฒะตะดะตะฝะธะต ัะปะตะผะตะฝัะพะฒ ะผะตะถะดั ะผะฐะบัะธะผะฐะปัะฝัะผ ะธ ะผะธะฝะธะผะฐะปัะฝัะผ: " << c << endl;
}
void ArraySorter(int N, int mas[]) {
int min = 0;
int buf = 0;
for (int i = 0; i < N; i++) // ัะพััะธัะพะฒะบะฐ ะผะฐััะธะฒะฐ
{
min = i;
for (int j = i + 1; j < N; j++)
min = (mas[j] < mas[min]) ? j : min;
if (i != min)
{
buf = mas[i];
mas[i] = mas[min];
mas[min] = buf;
}
}
cout << "ะััะพััะธัะพะฒะฐะฝะฝัะน ะผะฐััะธะฒ: ";
for (int i = 0; i < N; i++)
cout << mas[i] << "|";
}
// ะฒะพะทะฒัะฐั ะผะฐััะธะฒะฐ ะธะท ััะฝะบัะธั
int* max_vect(int, int[], int[]);
int main()
{
SetConsoleOutputCP(1251);
SetConsoleCP(1251);
int a[] = {1, 2, 3, 4, 5, 6, 7, 2};
int b[] = {7, 6, 5, 4, 3, 2, 1, 3};
int kc = sizeof(a) / sizeof(a[0]); //ะะพะปะธัะตััะฒะพ ัะปะตะผะตะฝัะพะฒ ะผะฐััะธะฒะฐ
int* c; //ะฃะบะฐะทะฐัะตะปั ะฝะฐ ัะตะทัะปััะธััััะธะน ะผะฐััะธะฒ
c = max_vect(kc, a, b); //ะฒัะทะพะฒ ััะฝะบัะธะธ ะดะปั ัะพะทะดะฐะฝะธั ะผะฐััะธะฒะฐ
for (int i = 0; i < kc; i++) //ะัะฒะพะด ัะตะทัะปััะฐัะฐ.
cout << c[i] << " ";
cout << endl;
delete[]c;
}
int* max_vect(int kc, int a[], int b[])
{
int* c = new int[kc];
for (int i = 0; i < kc; i++)
{
c[i] = max(a[i], b[i]);
}
return c;
}
|
5d6ea5e2950d0c8f463a76a08176129466781549
|
a98d5ba1cde141fd4148146137f465d3b924741c
|
/Disassembler.hpp
|
c6e560cda6ee6de9ea3caef9737c79f89972ed4c
|
[
"MIT"
] |
permissive
|
jonesdy/Chip8-Disassembler
|
3beac039c556d089f1753ac848df85d71be6201d
|
08fb80fc71f7a541dd4e3d0a41d0fe93710c3caf
|
refs/heads/master
| 2016-08-06T20:59:30.600607
| 2014-03-01T17:42:05
| 2014-03-01T17:42:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 416
|
hpp
|
Disassembler.hpp
|
#ifndef DISASSEMBLER_HPP
#define DISASSEMBLER_HPP
#include <fstream>
#include <iostream>
#include <string>
class Disassembler
{
public:
Disassembler();
void disassemble(const std::string &fileName);
~Disassembler();
static const int PROGRAM_START = 512;
private:
void loadProgram(const std::string &fileName);
char hexToChar(int h);
unsigned char *buffer;
unsigned int bufferLen;
};
#endif
|
ad1ddbfae542fdf168484ee46a45528996c3956f
|
d5bd083dbcacce8cf62ebbd73c77c14c8247e057
|
/system/netd/server/StrictController.cpp
|
a04124df7c6f92929d1caaa404b765b9dd877a90
|
[] |
no_license
|
RetronixTechInc/android-retronix
|
ab0e10840dab5dc7b0879737953ebf2e1916f2b0
|
cd7d794dea51c3b287da0d35ddb18c1bdef00372
|
refs/heads/RTX_NXP_Android601
| 2021-11-16T03:58:58.169998
| 2021-11-15T01:51:02
| 2021-11-15T01:51:02
| 198,991,737
| 4
| 5
| null | 2020-03-08T23:21:29
| 2019-07-26T09:49:01
|
Java
|
UTF-8
|
C++
| false
| false
| 7,951
|
cpp
|
StrictController.cpp
|
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LOG_TAG "StrictController"
#define LOG_NDEBUG 0
#include <cutils/log.h>
#include "ConnmarkFlags.h"
#include "NetdConstants.h"
#include "StrictController.h"
const char* StrictController::LOCAL_OUTPUT = "st_OUTPUT";
const char* StrictController::LOCAL_CLEAR_DETECT = "st_clear_detect";
const char* StrictController::LOCAL_CLEAR_CAUGHT = "st_clear_caught";
const char* StrictController::LOCAL_PENALTY_LOG = "st_penalty_log";
const char* StrictController::LOCAL_PENALTY_REJECT = "st_penalty_reject";
StrictController::StrictController(void) {
}
int StrictController::enableStrict(void) {
char connmarkFlagAccept[16];
char connmarkFlagReject[16];
char connmarkFlagTestAccept[32];
char connmarkFlagTestReject[32];
sprintf(connmarkFlagAccept, "0x%x", ConnmarkFlags::STRICT_RESOLVED_ACCEPT);
sprintf(connmarkFlagReject, "0x%x", ConnmarkFlags::STRICT_RESOLVED_REJECT);
sprintf(connmarkFlagTestAccept, "0x%x/0x%x",
ConnmarkFlags::STRICT_RESOLVED_ACCEPT,
ConnmarkFlags::STRICT_RESOLVED_ACCEPT);
sprintf(connmarkFlagTestReject, "0x%x/0x%x",
ConnmarkFlags::STRICT_RESOLVED_REJECT,
ConnmarkFlags::STRICT_RESOLVED_REJECT);
int res = 0;
disableStrict();
// Chain triggered when cleartext socket detected and penalty is log
res |= execIptables(V4V6, "-N", LOCAL_PENALTY_LOG, NULL);
res |= execIptables(V4V6, "-A", LOCAL_PENALTY_LOG,
"-j", "CONNMARK", "--or-mark", connmarkFlagAccept, NULL);
res |= execIptables(V4V6, "-A", LOCAL_PENALTY_LOG,
"-j", "NFLOG", "--nflog-group", "0", NULL);
// Chain triggered when cleartext socket detected and penalty is reject
res |= execIptables(V4V6, "-N", LOCAL_PENALTY_REJECT, NULL);
res |= execIptables(V4V6, "-A", LOCAL_PENALTY_REJECT,
"-j", "CONNMARK", "--or-mark", connmarkFlagReject, NULL);
res |= execIptables(V4V6, "-A", LOCAL_PENALTY_REJECT,
"-j", "NFLOG", "--nflog-group", "0", NULL);
res |= execIptables(V4V6, "-A", LOCAL_PENALTY_REJECT,
"-j", "REJECT", NULL);
// Create chain to detect non-TLS traffic. We use a high-order
// mark bit to keep track of connections that we've already resolved.
res |= execIptables(V4V6, "-N", LOCAL_CLEAR_DETECT, NULL);
res |= execIptables(V4V6, "-N", LOCAL_CLEAR_CAUGHT, NULL);
// Quickly skip connections that we've already resolved
res |= execIptables(V4V6, "-A", LOCAL_CLEAR_DETECT,
"-m", "connmark", "--mark", connmarkFlagTestReject,
"-j", "REJECT", NULL);
res |= execIptables(V4V6, "-A", LOCAL_CLEAR_DETECT,
"-m", "connmark", "--mark", connmarkFlagTestAccept,
"-j", "RETURN", NULL);
// Look for IPv4 TCP/UDP connections with TLS/DTLS header
res |= execIptables(V4, "-A", LOCAL_CLEAR_DETECT, "-p", "tcp",
"-m", "u32", "--u32", "0>>22&0x3C@ 12>>26&0x3C@ 0&0xFFFF0000=0x16030000 &&"
"0>>22&0x3C@ 12>>26&0x3C@ 4&0x00FF0000=0x00010000",
"-j", "CONNMARK", "--or-mark", connmarkFlagAccept, NULL);
res |= execIptables(V4, "-A", LOCAL_CLEAR_DETECT, "-p", "udp",
"-m", "u32", "--u32", "0>>22&0x3C@ 8&0xFFFF0000=0x16FE0000 &&"
"0>>22&0x3C@ 20&0x00FF0000=0x00010000",
"-j", "CONNMARK", "--or-mark", connmarkFlagAccept, NULL);
// Look for IPv6 TCP/UDP connections with TLS/DTLS header. The IPv6 header
// doesn't have an IHL field to shift with, so we have to manually add in
// the 40-byte offset at every step.
res |= execIptables(V6, "-A", LOCAL_CLEAR_DETECT, "-p", "tcp",
"-m", "u32", "--u32", "52>>26&0x3C@ 40&0xFFFF0000=0x16030000 &&"
"52>>26&0x3C@ 44&0x00FF0000=0x00010000",
"-j", "CONNMARK", "--or-mark", connmarkFlagAccept, NULL);
res |= execIptables(V6, "-A", LOCAL_CLEAR_DETECT, "-p", "udp",
"-m", "u32", "--u32", "48&0xFFFF0000=0x16FE0000 &&"
"60&0x00FF0000=0x00010000",
"-j", "CONNMARK", "--or-mark", connmarkFlagAccept, NULL);
// Skip newly classified connections from above
res |= execIptables(V4V6, "-A", LOCAL_CLEAR_DETECT,
"-m", "connmark", "--mark", connmarkFlagTestAccept,
"-j", "RETURN", NULL);
// Handle TCP/UDP payloads that didn't match TLS/DTLS filters above,
// which means we've probably found cleartext data. The TCP variant
// depends on u32 returning false when we try reading into the message
// body to ignore empty ACK packets.
res |= execIptables(V4, "-A", LOCAL_CLEAR_DETECT, "-p", "tcp",
"-m", "state", "--state", "ESTABLISHED",
"-m", "u32", "--u32", "0>>22&0x3C@ 12>>26&0x3C@ 0&0x0=0x0",
"-j", LOCAL_CLEAR_CAUGHT, NULL);
res |= execIptables(V6, "-A", LOCAL_CLEAR_DETECT, "-p", "tcp",
"-m", "state", "--state", "ESTABLISHED",
"-m", "u32", "--u32", "52>>26&0x3C@ 40&0x0=0x0",
"-j", LOCAL_CLEAR_CAUGHT, NULL);
res |= execIptables(V4V6, "-A", LOCAL_CLEAR_DETECT, "-p", "udp",
"-j", LOCAL_CLEAR_CAUGHT, NULL);
return res;
}
int StrictController::disableStrict(void) {
int res = 0;
// Flush any existing rules
res |= execIptables(V4V6, "-F", LOCAL_OUTPUT, NULL);
res |= execIptables(V4V6, "-F", LOCAL_PENALTY_LOG, NULL);
res |= execIptables(V4V6, "-F", LOCAL_PENALTY_REJECT, NULL);
res |= execIptables(V4V6, "-F", LOCAL_CLEAR_CAUGHT, NULL);
res |= execIptables(V4V6, "-F", LOCAL_CLEAR_DETECT, NULL);
res |= execIptables(V4V6, "-X", LOCAL_PENALTY_LOG, NULL);
res |= execIptables(V4V6, "-X", LOCAL_PENALTY_REJECT, NULL);
res |= execIptables(V4V6, "-X", LOCAL_CLEAR_CAUGHT, NULL);
res |= execIptables(V4V6, "-X", LOCAL_CLEAR_DETECT, NULL);
return res;
}
int StrictController::setUidCleartextPenalty(uid_t uid, StrictPenalty penalty) {
char uidStr[16];
sprintf(uidStr, "%d", uid);
int res = 0;
if (penalty == ACCEPT) {
// Clean up any old rules
execIptables(V4V6, "-D", LOCAL_OUTPUT,
"-m", "owner", "--uid-owner", uidStr,
"-j", LOCAL_CLEAR_DETECT, NULL);
execIptables(V4V6, "-D", LOCAL_CLEAR_CAUGHT,
"-m", "owner", "--uid-owner", uidStr,
"-j", LOCAL_PENALTY_LOG, NULL);
execIptables(V4V6, "-D", LOCAL_CLEAR_CAUGHT,
"-m", "owner", "--uid-owner", uidStr,
"-j", LOCAL_PENALTY_REJECT, NULL);
} else {
// Always take a detour to investigate this UID
res |= execIptables(V4V6, "-I", LOCAL_OUTPUT,
"-m", "owner", "--uid-owner", uidStr,
"-j", LOCAL_CLEAR_DETECT, NULL);
if (penalty == LOG) {
res |= execIptables(V4V6, "-I", LOCAL_CLEAR_CAUGHT,
"-m", "owner", "--uid-owner", uidStr,
"-j", LOCAL_PENALTY_LOG, NULL);
} else if (penalty == REJECT) {
res |= execIptables(V4V6, "-I", LOCAL_CLEAR_CAUGHT,
"-m", "owner", "--uid-owner", uidStr,
"-j", LOCAL_PENALTY_REJECT, NULL);
}
}
return res;
}
|
ea0373896700e99c1937a0f888d152eaef5b179b
|
ad74f7a42e8dec14ec7576252fcbc3fc46679f27
|
/AresSupernode/AresSNClientConnection.cpp
|
79f83dc8d3a42a92f50680e1fd9842183fd766bd
|
[] |
no_license
|
radtek/TrapperKeeper
|
56fed7afa259aee20d6d81e71e19786f2f0d9418
|
63f87606ae02e7c29608fedfdf8b7e65339b8e9a
|
refs/heads/master
| 2020-05-29T16:49:29.708375
| 2013-05-15T08:33:23
| 2013-05-15T08:33:23
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,690
|
cpp
|
AresSNClientConnection.cpp
|
#include "StdAfx.h"
#include "AresSNClientConnection.h"
#include "AresSupernodeSystem.h"
#include "..\AresProtector\AresPacket.h"
#include "..\AresProtector\AresHost.h"
#include "..\AresProtector\AresUtilityClass.h"
#include "..\tkcom\TinySQL.h"
#include "AresUserName.h"
//#include "AresConstants.h"
//#include <sha.h>
//#include "altsha.h"
#include <mmsystem.h>
#include "..\AresDataCollector\ProcessorJob.h"
#include "zlib\zlib.h"
UINT g_id_counter2=0;
AresSNClientConnection::AresSNClientConnection(PeerSocket *ps)
{
mp_ps_con=ps;
ps->SetSocketEventListener(this);
Init(ps->GetIP(),ps->GetPort());
//put all other init into the Init() function;
}
void AresSNClientConnection::Init(const char *host_ip,unsigned short port){
//generate 50 common spoof hashes
mb_clean=false;
AresSupernodeSystemRef ref;
m_str_ip=host_ip;
m_port=port;
unsigned int ip1,ip2,ip3,ip4;
sscanf(host_ip,"%u.%u.%u.%u",&ip1,&ip2,&ip3,&ip4);
m_remote_ip=(ip1<<24)|(ip2<<16)|(ip3<<8)|(ip4<<0);
m_status="Connecting...";
mb_marked_for_death=false;
m_create_time=CTime::GetCurrentTime();
m_death_time=CTime::GetCurrentTime();
m_state=GetTickCount();
mb_dead=false;
m_id=++g_id_counter2;
// TRACE("AresSNClientConnection::AresSNClientConnection() id=%d\n",m_id);
m_con_handle=0;
}
AresSNClientConnection::~AresSNClientConnection(void)
{
CleanUp();
}
void AresSNClientConnection::Update(void)
{
if(mb_dead)
return;
if(m_last_receive.HasTimedOut(1200) && !mb_marked_for_death){ //10 minutes of waiting then we drop
m_status="idle";
Kill();
return;
}
if(m_last_purge.HasTimedOut(30)){
PurgeEvents();
m_last_purge.Refresh();
}
CTime now=CTime::GetCurrentTime();
CTimeSpan alive_time=GetAliveTime();
CTimeSpan dead_time=CTime::GetCurrentTime()-m_death_time;
if(!mb_marked_for_death && m_create_time<(now-CTimeSpan(4,0,0,0))){ //if its older than 4 days, lets drop it so we can unload old files
m_status="Died of old age";
Kill();
return;
}
//if(!mb_marked_for_death && mv_processor_job.Size()>0){
//ProcessorJob* job=(ProcessorJob*)mv_processor_job.Get(0);
//if(job->mb_done){
// FinishMessage0x62();
// mv_processor_job.Remove(0);
//}
//}
//if(!mb_marked_for_death && mb_fully_connected && m_last_ping_sent.HasTimedOut(60)){
//m_last_ping_sent.Refresh();
//SendMessage0x67();
//}
}
void AresSNClientConnection::Kill(void)
{
mb_marked_for_death=true;
m_death_time=CTime::GetCurrentTime();
m_status+=" - Destroying";
CleanUp();
}
CString AresSNClientConnection::GetFormattedAgeString(void)
{
CString tmp;
CTimeSpan dif=CTime::GetCurrentTime()-m_create_time;
unsigned int total_secs=(unsigned int)dif.GetTotalSeconds();
static unsigned int secs_in_day=60*60*24;
static unsigned int secs_in_hour=60*60;
static unsigned int secs_in_minute=60;
unsigned int days=total_secs/secs_in_day;
unsigned int remaining_secs=total_secs-days*secs_in_day;
unsigned int hours=remaining_secs/secs_in_hour;
remaining_secs-=(hours*secs_in_hour);
unsigned int minutes=remaining_secs/secs_in_minute;
remaining_secs-=(minutes*secs_in_minute);
tmp.Format("%.2d:%.2d:%.2d:%.2d",days,hours,minutes,remaining_secs);
return tmp;
}
void AresSNClientConnection::ProcessPacket(AresPacket& packet)
{
if(mb_marked_for_death || !mp_ps_con)
return;
int type=packet.GetMessageType();
AresSupernodeSystemRef ref;
CString log_msg;
if(type!=0x07){
log_msg.Format("AresSNClientConnection %s:%u ProcessPacket() type=0x%X length=%u",this->m_str_ip.c_str(),this->m_port,type,packet.GetLength());
TRACE("%s\n",log_msg);
}
ref.System()->LogToFile(log_msg);
if(packet.GetMessageType()==0x5d && packet.GetLength()==0x03){
//we are looking for supernode connections
//init message
//respond with a 0x38 message
//unsigned char data[]={0x03,0x00,0x5a,0x04,0x03,0x05};
}
else if(packet.GetMessageType()==0x5a){
//Kill(); //we don't like clients at this time
}
else if(packet.GetMessageType()==0x7){
Kill(); //we don't like whomever/whatever this is
}
}
LinkedList* AresSNClientConnection::GetEventList(void)
{
return &m_event_list;
}
/*
#ifdef TKSOCKETSYSTEM
void AresSNClientConnection::OnClose(){
TRACE("AresSNClientConnection::OnClose() %s:%u\n",m_str_ip.c_str(),m_port);
AresSupernodeSystemRef ref;
CString log_msg;
log_msg.Format("Supernode %s:%u OnClose() =(",this->m_str_ip.c_str(),this->m_port);
ref.System()->LogConnectionInfo(log_msg);
log_msg.Format("AresSNClientConnection OnClose() BEGIN %s:%u",this->m_str_ip.c_str(),this->m_port);
ref.System()->LogToFile(log_msg);
mb_connected=false;
if(mb_has_connected){
m_status="Connection Lost";
}
else
m_status="Could Not Connect";
Kill();
log_msg.Format("AresSNClientConnection OnClose() END %s:%u",this->m_str_ip.c_str(),this->m_port);
ref.System()->LogToFile(log_msg);
}
void AresSNClientConnection::OnSend(){
//TRACE("AresSNClientConnection::OnSend() %s\n",m_str_ip.c_str());
}
void AresSNClientConnection::OnReceive(byte *data,UINT length){
if(length>0)
m_last_receive.Refresh();
AresSupernodeSystemRef ref;
CString log_msg;
log_msg.Format("AresSNClientConnection::OnReceive BEGIN %s, %d bytes received",m_str_ip.c_str(),length);
ref.System()->LogToFile(log_msg);
//TRACE("AresSNClientConnection::OnReceive() %s received %d bytes of data\n",m_str_ip.c_str(),length);
m_receive_buffer.WriteBytes(data,length);
AresPacket *packet=new AresPacket();
if(packet->Read(&m_receive_buffer)){
Vector v_tmp;
v_tmp.Add(packet);
RecordReceiveEvent(packet);
ProcessPacket(*packet);
}
else{
if(packet->IsBad())
Kill(); //lets close this connection because they sent us something that seems to be invalid
delete packet;
};
log_msg.Format("AresSNClientConnection::OnReceive END %s, %d bytes received",m_str_ip.c_str(),length);
ref.System()->LogToFile(log_msg);
}
#endif
*/
void AresSNClientConnection::CleanUp(void)
{
AresSupernodeSystemRef ref;
CString log_msg;
log_msg.Format("AresSNClientConnection::CleanUp() BEGIN %s",m_str_ip.c_str());
ref.System()->LogToFile(log_msg);
#ifdef TKSOCKETSYSTEM
if(m_con_handle!=NULL){
AresSupernodeSystemRef ref;
ref.System()->GetTCPSystem()->CloseConnection(m_con_handle);
m_con_handle=NULL;
}
#else
if(mp_ps_con){
if(mp_ps_con->m_hSocket!=INVALID_SOCKET){
SOCKET s=mp_ps_con->Detach();
closesocket(s);
}
delete mp_ps_con;
}
mp_ps_con=NULL;
#endif
mb_clean=true;
log_msg.Format("AresSNClientConnection::CleanUp() END %s",m_str_ip.c_str());
ref.System()->LogToFile(log_msg);
//_ASSERTE( _CrtCheckMemory( ) );
}
void AresSNClientConnection::RecordReceiveEvent(AresPacket* packet)
{
CSingleLock lock(&m_event_list.m_list_lock,TRUE);
AresSupernodeSystemRef ref;
if(ref.System()->GetEventCacheTime()>0)
m_event_list.Add(packet);
}
void AresSNClientConnection::RecordSendEvent(AresPacket* packet)
{
CSingleLock lock(&m_event_list.m_list_lock,TRUE);
AresSupernodeSystemRef ref;
if(ref.System()->GetEventCacheTime()>0)
m_event_list.Add(packet);
}
//call to remove events that have expired past the cache time
void AresSNClientConnection::PurgeEvents(void)
{
if(m_event_list.Size()==0)
return;
m_event_list.StartIteration();
AresSupernodeSystemRef ref;
unsigned int cache_time=ref.System()->GetEventCacheTime();
CTime now=CTime::GetCurrentTime();;
while(true){
AresPacket *ap=(AresPacket*)m_event_list.GetCurrent();
if(!ap)
break;
CTimeSpan ts=now-*ap->GetCreatedTime();
if((ts.GetTotalSeconds()/60)>=cache_time){
m_event_list.RemoveCurrentAndAdvance();
}
else break; //can just stop here because we know that anything else is going to be even newer
}
}
void AresSNClientConnection::SendData(byte* data, UINT length)
{
#ifdef TKSOCKETSYSTEM
AresSupernodeSystemRef ref;
m_con_handle=ref.System()->GetTCPSystem()->SendData(m_con_handle,data,length);
#else
mp_ps_con->Send(data,length);
#endif
}
UINT AresSNClientConnection::GetConHandle(void)
{
return m_con_handle;
}
#ifndef TKSOCKETSYSTEM
void AresSNClientConnection::OnClose(CAsyncSocket* src){
TRACE("AresSNClientConnection::OnClose() %s:%u\n",m_str_ip.c_str(),m_port);
AresSupernodeSystemRef ref;
CString log_msg;
log_msg.Format("AresSNClientConnection::OnClose() BEGIN %s",m_str_ip.c_str());
ref.System()->LogToFile(log_msg);
log_msg.Format("Supernode %s:%u OnClose() =(",this->m_str_ip.c_str(),this->m_port);
ref.System()->LogConnectionInfo(log_msg);
m_status="Connection Lost";
Kill();
log_msg.Format("AresSNClientConnection::OnClose() END %s",m_str_ip.c_str());
ref.System()->LogToFile(log_msg);
}
void AresSNClientConnection::OnSend(CAsyncSocket* src){
//TRACE("AresDCConnection::OnSend() %s\n",m_str_ip.c_str());
}
void AresSNClientConnection::OnReceive(CAsyncSocket* src,byte *data,UINT length){
if(length>0)
m_last_receive.Refresh();
AresSupernodeSystemRef ref;
CString log_msg;
log_msg.Format("AresSNClientConnection::OnReceive() BEGIN %s, %d bytes received",m_str_ip.c_str(),length);
ref.System()->LogToFile(log_msg);
//TRACE("AresSNClientConnection::OnReceive() %s received %d bytes of data\n",m_str_ip.c_str(),length);
m_receive_buffer.WriteBytes(data,length);
AresPacket *packet=new AresPacket();
if(packet->Read(&m_receive_buffer)){
Vector v_tmp;
v_tmp.Add(packet);
RecordReceiveEvent(packet);
ProcessPacket(*packet);
}
else{
if(packet->IsBad())
Kill(); //lets close this connection because they sent us something that seems to be invalid
delete packet;
};
log_msg.Format("AresSNClientConnection::OnReceive() END %s, %d bytes received",m_str_ip.c_str(),length);
ref.System()->LogToFile(log_msg);
}
#endif
void AresSNClientConnection::SendMessage0x38(void)
{
}
|
926343bb8d74e521da4c555f6cef28889c3942c0
|
07d44374267af466946230cc2ed1fed902164075
|
/PandaSQL/Optimizer/Join/JoinPath.cpp
|
c048d8648a9f44e9394bf8f5cb9a32dc93629d09
|
[] |
no_license
|
b-xiang/PandaSQL
|
24287304997333112177c8c492e2dd35dc901376
|
ffb112066325ff9b64325ff8ca17e0234eca3891
|
refs/heads/master
| 2020-05-30T16:36:20.778321
| 2013-03-15T08:35:42
| 2013-03-15T08:35:42
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 123
|
cpp
|
JoinPath.cpp
|
#include "stdafx.h"
#include "Optimizer/Join/JoinPath.h"
#include "Node/RelNode.h"
namespace PandaSQL
{
} // PandaSQL
|
1e660e6d578a1afb2940f63b0bd57ca22677fac6
|
647cadc35d2a688319ed957bd0c832884c0df514
|
/Project.cpp
|
919ed70e3bb360dd02c15f7dade56c510c604601
|
[] |
no_license
|
Sara-Rahman/admin
|
d7a3d3584d9468376765dc59f7054a3445bb0b98
|
f6897f06a0d95eaf44f57188294b82d801fb8de5
|
refs/heads/master
| 2022-11-25T15:11:43.073426
| 2020-07-30T06:42:59
| 2020-07-30T06:42:59
| 283,693,669
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 14,691
|
cpp
|
Project.cpp
|
#include<iostream>
#include<fstream>
#include<string.h>
#include<conio.h>
#include<stdlib.h>
using namespace std;
class sara
{
private :
char serial[100],name_h[100],name_w[100],age_h[5],age_w[5],marriage[10],div_date[10],reason[50],child[10],child_stay[10];
double percent,stock;
public :
sara()
{
strcpy(serial,"Not inserted");
strcpy(name_h,"Not inserted");
strcpy(name_w,"Not inserted");
strcpy(age_h,"Not inserted");
strcpy(age_w,"Not inserted");
strcpy(marriage,"Not inserted");
strcpy(div_date,"Not inserted");
strcpy(reason,"Not inserted");
strcpy(child,"Not inserted");
strcpy(child_stay,"Not inserted");
percent =0;
stock=0;
}
void insert_data();
void show_data();
void store_data_to_file();
void view_all_data();
void see_data();
void search_data( char *);
void search_data_with_update( char *);
void edit_data();
void delete_file_data(char *);
void delete_data();
};
void sara ::insert_data()
{
cout << endl<<endl<<endl;
cout << "Enter Serial No : ";
cin>>serial;
cout << "Enter Husband's Name : ";
cin>>name_h;
cout << "Enter Wife's Name : ";
cin>>name_w;
cout << "Enter Husband's Age : ";
cin>>age_h;
cout << "Enter Wife's Age : ";
cin>>age_w;
cout << "Enter Marriage Date : ";
cin>>marriage;
cout << "Enter Divorce Date : ";
cin>>div_date;
cout << "Enter Reason : ";
cin>>reason;
cout << "Enter Number Of Children : ";
cin>>child;
cout << "Enter Children Stay With : ";
cin>>child_stay;
cout << "Enter Percentage : ";
cin>>percent;
}
void sara::show_data()
{
cout <<"Serial No :"<<serial<<" [] "<<"Husband's Name :"<<name_h<< "[] "<<"Wife's Name :"<<name_w<<" [] "<<"Husband's Age :"<<age_h<<" [] "<<"Wife's Age :"<<age_w<<" [] "<<"Marriage Date :"<<marriage<<" [] "<<"Divorce Date :"<<div_date<<" [] "<<"Reason :"<<reason<<" [] "<<"Number Of Children :"<<child<<" [] "<<"Children Stay With :"<<child_stay<<" [] "<<"Percentage :"<<percent<<endl;
}
void sara::store_data_to_file()
{
if(serial == "Not inserted")
{
cout<< "Data is not inserted";
}
else
{
ofstream file;
file.open("SARA.txt",ios::app|ios::binary);
file.write((char*)this,sizeof(*this));
file.close();
}
}
void sara::view_all_data()
{
ifstream file ;
file.open("SARA.txt",ios::in|ios::binary);
if(!file)
{
cout << "File does not exist" <<endl;
}
else
{
file.read((char*)this,sizeof(*this));
while(!(file.eof()))
{
show_data();
file.read((char*)this,sizeof(*this));
}
file.close();
}
}
void sara::search_data(char *t)
{
ifstream file;
int ck=0;
file.open("SARA.txt",ios::in|ios::binary);
if(!file)
{
cout << "File does not exist "<<endl;
}
else
{
file.read((char *)this,sizeof(*this));
while(!file.eof())
{
if(!strcmp(t,serial))
{
show_data();
ck++;
}
file.read((char *)this,sizeof(*this));
}
if(ck==0)
{
cout << "Record does not found " <<endl;
}
file.close();
}
}
void sara::search_data_with_update(char *k)
{
fstream file;
int ck=0;
file.open("SARA.txt",ios::in|ios::ate|ios::out|ios::binary);
file.seekg(0);
file.read((char *)this,sizeof(*this));
while(!file.eof())
{
if(!strcmp(k,serial))
{
cout << "You are trying to see the data "<<endl<<endl;
show_data();
edit_data();
file.seekg(file.tellp()-sizeof(*this));
file.write((char *)this,sizeof(*this));
ck++;
}
file.read((char *)this,sizeof(*this));
}
if(ck==0)
{
cout << "Invalid insertion "<<endl;
}
file.close();
}
void sara::delete_file_data(char *l)
{
ifstream fin;
ofstream fout;
fin.open("SARA.txt",ios::in|ios::binary);
if(!fin.is_open())
{
cout << "Error opening file "<<endl;
}
else
{
fout.open("tem.dat",ios::out|ios::binary);
fin.read((char *)this,sizeof(*this));
while(!fin.eof())
{
if(strcmp(l,serial))
{
fout.write((char *)this,sizeof(*this));
}
fin.read((char *)this,sizeof(*this));
}
fin.close();
fout.close();
remove("SARA.dat");
rename("Sara.dat","SARA.dat");
}
}
void sara::edit_data()
{
double a;
cout << "Enter How many data you want to see : ";
cin >> a ;
if (a >0 && stock >=a)
{
stock =stock - a;
cout << " Thank You " <<endl;
}
else
{
cout << "Data is not available " <<endl;
}
}
void sara::see_data()
{
cout <<endl<<endl<<"Serial No :"<<serial<<" [] "<<"Husband's Name :"<<name_h<< "[] "<<"Wife's Name :"<<name_w<<" [] "<<"Husband's Age :"<<age_h<<" [] "<<"Wife's Age :"<<age_w<<" [] "<<"Marriage Date :"<<marriage<<" [] "<<"Divorce Date :"<<div_date<<" [] "<<"Reason :"<<reason<<" [] "<<"Number Of Children :"<<child<<" [] "<<"Children Stay With :"<<child_stay<<" [] "<<"Percentage :"<<percent<<endl<<endl;
view_all_data();
char p[100];
double a;
cout <<endl<<endl<< "Enter Serial No : ";
cin>>p;
search_data_with_update(p);
}
int Menu()
{
int ch;
cout << endl<<"\t<<----------------- Welcome To The Database Of Divorced People In BD --------------->> " << endl <<endl <<endl;
cout << "1. Admin " << endl;
cout << "2. User " << endl;
cout << "Press 0 to exit " << endl;
cout << endl<<endl<<"Enter your choice : ";
cin>> ch;
return ch;
}
int admin()
{
cout <<endl<<endl<< "You have successfully logged in as Admin " <<endl <<endl;
cout << "1. Insert Data"<<endl;
cout << "2. View all data"<<endl;
cout << "3. Search data"<<endl;
cout << "4. Delete specific data " <<endl;
cout << "5. Delete whole file " <<endl;
cout << "6. Main menu " <<endl;
cout << "Press 0 to exit" <<endl;
int a;
cout << endl<<endl<<"Enter your choice : ";
cin >> a;
return a;
}
int user()
{
cout << "1. View all member"<<endl;
cout << "2. See specific one"<<endl;
cout << "Press 0 to exit" <<endl;
int a;
cout << endl<<endl<<"Enter your choice : ";
cin >> a;
return a;
}
void details ()
{
cout <<endl<<endl<<"Serial No" <<" [] " << " Husband's Name"<<" [] " << " Wife's Name"<<" [] " << " Husband's Age"<< " Wife's Age"<< " Marriage Date "<< " Divorce Date"<< " Number Of Children "<<" Children Stay With" <<" [] "<<" Percentage "<<" [] "<<endl<<endl;
}
int main()
{
cout<<" "<<endl;
cout<<" "<<endl;
cout<<" "<<endl;
cout<<"\t\t\t WELCOME TO IUBAT"<<endl;
cout<<"\t\t\t __ "<<endl;
cout<<"\t\t\t _ |____| _"<<endl;
cout<<"\t\t\t |_ | [==||==] | _|"<<endl;
cout<<"\t\t\t | | _ || | | "<<endl;
cout<<"\t\t\t | | | ) || /\\ | | "<<endl;
cout<<"\t\t\t | | |_) || /--\\ | | "<<endl;
cout<<"\t\t\t | | || | | "<<endl;
cout<<"\t\t\t '. '.____||____.' .' "<<endl;
cout<<"\t\t\t '---|____|---' "<<endl;
cout<<" "<<endl;
cout<<"\t\t *****************************************"<<endl;
cout<<"\t \t "<<endl;
cout<<"" <<endl;
cout<<" Name : Shahida Rahman"<<endl;
cout<<" ID : 18103214"<<endl;
cout<<" Sec : B"<<endl;
cout<<endl;
cout<<endl;
cout<<endl;
cout<<"\t\t\t WELCOME TO THE DATABASE OF DIVORCED PEOPLE IN BD "<<endl;
cout<<"\t\t--------------------------------------------"<<endl;
cout<<endl;
cout<<endl;
cout<<endl;
cout<<endl;
string pass ="";
char ch;
cout << "Enter Password\n";
ch = _getch();
while(ch != 13)
{
pass.push_back(ch);
cout <<'*';
ch = _getch();
}
if(pass == "123"){
cout << "\nAccess granted :P\n";
}else{
cout << "\nAccess aborted...\n";
cout<<"Serial No :"<<" [] "<<"Husband's Name :"<< "[] "<<"Wife's Name :"<<" [] "<<"Husband's Age :"<<" [] "<<"Wife's Age :"<<" [] "<<"Marriage Date :"<<" [] "<<"Divorce Date :"<<" [] "<<"Reason :"" [] "<<"Number Of Children :"<<" [] "<<"Children Stay With :"<<" [] "<<"Percentage :"<<endl;
}
sara c1;
x:
while(1)
{
system("cls");
switch(Menu())
{
case 1:
switch(admin())
{
case 1:
c1.insert_data();
c1.store_data_to_file();
system("cls");
cout<< endl<<"Data Successfully Recorded to the file "<<endl;
cout<< "Press any key";
getch();
break;
case 2:
details ();
c1.view_all_data();
cout<<endl<< "Press any key";
getch();
break;
case 3:
system ("cls");
char p[100];
cout <<endl<<endl<<"You are going to search from here --->" <<endl;
details ();
c1.view_all_data();
cout << endl<<"Enter Serial No to : ";
cin>>p;
system ("cls");
cout << "Search result ==>>"<<endl<<endl;
c1.search_data(p);
cout<<endl<<endl<< "Press any key";
getch();
break;
case 4:
char o[100];
details ();
c1.view_all_data();
cout << endl<<"Enter Serial No to delete : ";
cin>>o;
system ("cls");
c1.view_all_data();
c1.delete_file_data(o);
cout << endl<<"You have successfully deleted the record "<<endl<<endl;
getch();
cout <<endl<<endl<< "Press any key "<<endl;
break;
case 5:
system("cls");
char c;
cout << endl<<endl<<endl<< "Are you sure for deleting the whole file ?? ";
cout << endl<<endl<< "You can not reach the file again";
cout << endl<< "Press ( Y ) to confirm";
cout << endl<< "Press ( N ) to confirm";
cout << endl<< "Enter your choice : ";
cin>>c;
if(c=='Y' ||c=='y')
{
remove("cycle.dat");
cout<<endl <<endl<<"You have successfully Deleted the whole file ...."<<endl;
break;
}
else
{
system("cls");
goto x;
}
case 6:
system("cls");
goto x;
case 0:
cout << endl<<"You have Successfully logged out "<<endl;
cout<<endl<<endl<< "Press any key";
getch();
exit(0);
break;
default :
cout << "Invalid Choice "<<endl;
exit(0);
}
goto x;
case 2:
y:
switch(user()){
case 1:
system("cls");
details ();
c1.view_all_data();
cout<<endl<<endl<< "Press any key";
getch();
system("cls");
goto y;
case 2:
c1.see_data();
cout<<endl<<endl<< "Press any key";
getch();
break ;
case 0:
cout <<endl<<endl<<endl<< " THANK YOU " << endl;
cout<<endl<<endl<< "Press any key";
getch();
exit(0);
break;
default:
cout << "Invalid choice " <<endl;
}
case 0:
cout <<endl<<endl<<endl<< " THANK YOU " << endl;
cout<<endl<<endl<< "Press any key";
getch();
exit(0);
break;
default:
cout <<endl<<endl<< "Invalid choice " <<endl;
cout<<endl<<endl<< "Press any key";
getch();
exit(0);
}
}
return 0;
}
|
d79a619d5498216d64f299a9cef4fa52ec52c71b
|
2b1b459706bbac83dad951426927b5798e1786fc
|
/zircon/vdso/goldens/public/internal/testonly-cdecls.inc
|
5cf415b6d42b11c9e37459efae6a1453f4b485e5
|
[
"BSD-3-Clause",
"MIT",
"BSD-2-Clause"
] |
permissive
|
gnoliyil/fuchsia
|
bc205e4b77417acd4513fd35d7f83abd3f43eb8d
|
bc81409a0527580432923c30fbbb44aba677b57d
|
refs/heads/main
| 2022-12-12T11:53:01.714113
| 2022-01-08T17:01:14
| 2022-12-08T01:29:53
| 445,866,010
| 4
| 3
|
BSD-2-Clause
| 2022-10-11T05:44:30
| 2022-01-08T16:09:33
|
C++
|
UTF-8
|
C++
| false
| false
| 2,740
|
inc
|
testonly-cdecls.inc
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// WARNING: THIS FILE IS MACHINE GENERATED BY //tools/kazoo. DO NOT EDIT.
#ifndef _ZX_SYSCALL_DECL
#error "<zircon/testonly-syscalls.h> is the public API header"
#endif
_ZX_SYSCALL_DECL(syscall_test_0, zx_status_t, /* no attributes */, 0,
(), (void))
_ZX_SYSCALL_DECL(syscall_test_1, zx_status_t, /* no attributes */, 1,
(a), (
int32_t a))
_ZX_SYSCALL_DECL(syscall_test_2, zx_status_t, /* no attributes */, 2,
(a, b), (
int32_t a,
int32_t b))
_ZX_SYSCALL_DECL(syscall_test_3, zx_status_t, /* no attributes */, 3,
(a, b, c), (
int32_t a,
int32_t b,
int32_t c))
_ZX_SYSCALL_DECL(syscall_test_4, zx_status_t, /* no attributes */, 4,
(a, b, c, d), (
int32_t a,
int32_t b,
int32_t c,
int32_t d))
_ZX_SYSCALL_DECL(syscall_test_5, zx_status_t, /* no attributes */, 5,
(a, b, c, d, e), (
int32_t a,
int32_t b,
int32_t c,
int32_t d,
int32_t e))
_ZX_SYSCALL_DECL(syscall_test_6, zx_status_t, /* no attributes */, 6,
(a, b, c, d, e, f), (
int32_t a,
int32_t b,
int32_t c,
int32_t d,
int32_t e,
int32_t f))
_ZX_SYSCALL_DECL(syscall_test_7, zx_status_t, /* no attributes */, 7,
(a, b, c, d, e, f, g), (
int32_t a,
int32_t b,
int32_t c,
int32_t d,
int32_t e,
int32_t f,
int32_t g))
_ZX_SYSCALL_DECL(syscall_test_8, zx_status_t, /* no attributes */, 8,
(a, b, c, d, e, f, g, h), (
int32_t a,
int32_t b,
int32_t c,
int32_t d,
int32_t e,
int32_t f,
int32_t g,
int32_t h))
_ZX_SYSCALL_DECL(syscall_test_handle_create, zx_status_t, /* no attributes */, 2,
(return_value, out), (
zx_status_t return_value,
_ZX_SYSCALL_ANNO(acquire_handle("Fuchsia")) zx_handle_t* out))
_ZX_SYSCALL_DECL(syscall_test_widening_signed_narrow, int64_t, /* no attributes */, 4,
(a, b, c, d), (
int64_t a,
int32_t b,
int16_t c,
int8_t d))
_ZX_SYSCALL_DECL(syscall_test_widening_signed_wide, int64_t, /* no attributes */, 4,
(a, b, c, d), (
int64_t a,
int32_t b,
int16_t c,
int8_t d))
_ZX_SYSCALL_DECL(syscall_test_widening_unsigned_narrow, uint64_t, /* no attributes */, 4,
(a, b, c, d), (
uint64_t a,
uint32_t b,
uint16_t c,
uint8_t d))
_ZX_SYSCALL_DECL(syscall_test_widening_unsigned_wide, uint64_t, /* no attributes */, 4,
(a, b, c, d), (
uint64_t a,
uint32_t b,
uint16_t c,
uint8_t d))
_ZX_SYSCALL_DECL(syscall_test_wrapper, zx_status_t, /* no attributes */, 3,
(a, b, c), (
int32_t a,
int32_t b,
int32_t c))
|
d0e5ce0a93bd36060feddc24f59825f599618c8a
|
db29182d389d8e85c48765788efe8fdc775086dc
|
/status_writer.h
|
8d482f3573675add15c07819b46fe5e5b525e892
|
[
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] |
permissive
|
flightaware/beast-splitter
|
eb7ffd925094e2e10525141ddf8ac2e227261666
|
05428fce609e3e48b5308439eb94614baf538003
|
refs/heads/master
| 2022-12-22T12:35:05.795236
| 2022-12-14T03:00:34
| 2022-12-14T03:00:34
| 59,662,036
| 27
| 9
|
BSD-2-Clause
| 2022-10-06T07:43:29
| 2016-05-25T12:39:02
|
C++
|
UTF-8
|
C++
| false
| false
| 3,103
|
h
|
status_writer.h
|
// -*- c++ -*-
// Copyright (c) 2015-2016, FlightAware LLC.
// Copyright (c) 2015, Oliver Jowett <oliver@mutability.co.uk>
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef STATUS_WRITER_H
#define STATUS_WRITER_H
#include <boost/asio/io_service.hpp>
#include <boost/asio/steady_timer.hpp>
#include "beast_input.h"
#include "modes_filter.h"
#include "modes_message.h"
namespace splitter {
class StatusWriter : public std::enable_shared_from_this<StatusWriter> {
public:
typedef std::shared_ptr<StatusWriter> pointer;
const std::chrono::milliseconds timeout_interval = std::chrono::milliseconds(2500);
// factory method, this class must always be constructed via make_shared
static pointer create(boost::asio::io_service &service, modes::FilterDistributor &distributor, beast::BeastInput::pointer input, const std::string &path) { return pointer(new StatusWriter(service, distributor, input, path)); }
void start();
void close();
private:
StatusWriter(boost::asio::io_service &service_, modes::FilterDistributor &distributor_, beast::BeastInput::pointer input_, const std::string &path);
void write(const modes::Message &message);
void reset_timeout();
void status_timeout(const boost::system::error_code &ec = boost::system::error_code());
void write_status_file(const std::string &gps_color = std::string(), const std::string &gps_message = std::string(), int pps_offset = -9999);
boost::asio::io_service &service;
modes::FilterDistributor &distributor;
beast::BeastInput::pointer input;
std::string path;
std::string temppath;
modes::FilterDistributor::handle filter_handle;
boost::asio::steady_timer timeout_timer;
};
}; // namespace splitter
#endif
|
0eb1dc7cfe0536980c92e4e4824c06f15cdba590
|
184bcf7925e6718b3021946581576f8cae80526b
|
/Game/2016-EM/C.cpp
|
e94edcf380ac6055fe8a674cff9c5c52faa7903f
|
[] |
no_license
|
iPhreetom/ACM
|
a99be74de61df37c427ffb685b375febad74ed9a
|
f3e639172be326846fe1f70437dcf98c90241aa0
|
refs/heads/master
| 2021-06-14T08:11:24.003465
| 2019-09-13T22:54:34
| 2019-09-13T22:54:34
| 142,748,718
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 892
|
cpp
|
C.cpp
|
#include <bits/stdc++.h>
#define int long long
#define double long double
#define endl '\n'
using namespace std;
struct node{
double l,r,v;
node(){};
node(double l,double r,double v)
{
this->v = v;
this->l = l;
this->r = r;
};
};
vector<node> a;
double x,y;
bool check(double v){
double time = 0;
for(int i=1;i<a.size();i++){
time += (a[i].l - a[i-1].r)/v + (a[i].r - a[i].l)/(v*a[i].v);
}
if(time >= x)return 1;
else return 0;
}
signed main()
{
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin>>x>>y;
if(x < 0)x = -x;
int n;
cin>>n;
a.push_back(node(0,0,1));
for(int i=0; i<=0; i++)
{
double l,r,v;
a.push_back(node(l,r,v));
}
double l = 0;
double r = 1e9;
int cnt = 10;
while(cnt--){
double mid = l+(r-l)/2;
if(check(mid))l = mid;
else r = mid;
cout<<r<<endl;
}
cout<<fixed<<setprecision(10)<<l<<endl;
cout<<r<<endl;
return 0;
}
|
a404146757d558cc35dd51fbf6c346c9562d3ef1
|
9c172493199ba987acfa51c1b323be00efb852cd
|
/Medium/103.BinaryTreeZigzagLevelOrderTraversal/bfs.cpp
|
b5fbacccbb7a0f284a760c02f200875e54033a30
|
[] |
no_license
|
FriedCosey/LeetCode
|
92a1084eeb8937d498411105ef6909ca4ca0d783
|
71a86e9bde3e3c9b1159085a773d370f3a75278c
|
refs/heads/master
| 2021-07-11T08:03:20.516199
| 2019-01-10T01:26:40
| 2019-01-10T01:26:40
| 138,459,041
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 999
|
cpp
|
bfs.cpp
|
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> res;
if(root == NULL)
return res;
queue<TreeNode*> bfs;
bfs.push(root);
int right = 1;
vector<int> tmp;
vector<TreeNode*> nodes;
int counter = 0;
while(!bfs.empty()){
int total = bfs.size();
tmp.resize(total);
counter = right == -1 ? total - 1 : 0;
for(int i = 0; i < total; i++){
TreeNode* cur = bfs.front();
bfs.pop();
tmp[counter] = cur->val;
counter += right;
if(cur->left)
bfs.push(cur->left);
if(cur->right)
bfs.push(cur->right);
}
res.push_back(tmp);
tmp.clear();
right *= -1;
}
return res;
}
};
|
ba72ad93f8bb185195c9eea25eb2eaaa6a147f34
|
41f313194e8fabd3bafc0163690317e4406e9c63
|
/Checkout/CheckoutTest.cpp
|
599962712acca7d9ffa0491c01394434925fd073
|
[] |
no_license
|
chris12/CheckoutTotalKata
|
c94bcbbfebb77ac423fdbb39eb0fbf6b547d9603
|
fc55a8147126d887a79833b032925de24007f587
|
refs/heads/master
| 2020-05-03T00:11:04.130629
| 2019-04-03T23:35:23
| 2019-04-03T23:35:23
| 178,302,653
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,741
|
cpp
|
CheckoutTest.cpp
|
#include "Checkout.h"
#include "gtest\gtest.h"
void SetUpTestCase() {
Checkout checkout;
}
TEST(CheckoutTest, WhenGetPriceOfItemIsCalledForACanOfSoupItReturnsTheRegularPrice) {
Checkout checkout;
EXPECT_DOUBLE_EQ(1.89, checkout.GetPriceOfItem("soup"));
}
TEST(CheckoutTest, WhenGetPriceOfItemIsCalledForAPoundOfGroundBeefItReturnsTheRegularPrice) {
Checkout checkout;
EXPECT_DOUBLE_EQ(5.99, checkout.GetPriceOfItem("Ground Beef", 1.0));
}
TEST(CheckoutTest, WhenGetPriceOfItemIsCalledForAPoundOfBananasItReturnsTheRegularPrice) {
Checkout checkout;
EXPECT_DOUBLE_EQ(2.38, checkout.GetPriceOfItem("Bananas", 1.0));
}
TEST(CheckoutTest, WhenSoupIsScannedThePriceIsAddedToCheckoutTotalAndReturned) {
Checkout checkout;
EXPECT_EQ("1.89", checkout.ScanItem("soup", 0.0));
}
TEST(CheckoutTest, WhenTwoPoundsOfGroundBeefIsScannedThePriceIsAddedToCheckoutTotalAndReturned) {
Checkout checkout;
EXPECT_EQ("11.98", checkout.ScanItem("Ground Beef", 2.0));
}
TEST(CheckoutTest, WhenThreePoundsOfBananasIsScannedThePriceIsAddedToCheckoutTotalAndReturned) {
Checkout checkout;
EXPECT_EQ("7.14", checkout.ScanItem("Bananas", 3.0));
}
TEST(CheckoutTest, WhenSoupTwoptTwoPoundsGroundBeefAndOnePtSevenPoundsOfBannanasArePurchasedCorrectTotalIsReturned) {
Checkout checkout;
EXPECT_EQ("1.89", checkout.ScanItem("soup"));
EXPECT_EQ("15.07", checkout.ScanItem("Ground Beef", 2.2));
EXPECT_EQ("19.11", checkout.ScanItem("Bananas", 1.7));
}
TEST(CheckoutTest, WhenItemIsRemovedAfterScanningTheTotalPriceIsReturnedWithTheRemovedItemTotalSubtracted) {
Checkout checkout;
EXPECT_EQ("11.98", checkout.ScanItem("Ground Beef", 2.0));
EXPECT_EQ("13.87", checkout.ScanItem("soup"));
EXPECT_EQ("11.98", checkout.RemoveItemFromOrder("soup"));
}
TEST(CheckoutTest, WhenUserCreatesAnItemThePriceIsReturnedCorrectly) {
Checkout checkout;
checkout.AddItem("soup", 1.77, 1.59, 4, false);
EXPECT_DOUBLE_EQ(1.77, checkout.GetPriceOfItem("soup"));
}
TEST(CheckoutTest, WhenNewItemIsAddedToCheckoutsItemDirectoryAndThenScannedTheCorrectTotalIsReturned) {
Checkout checkout;
checkout.AddItem("Chicken Breast", 1.99, 1.49, 4, true);
EXPECT_EQ("2.98", checkout.ScanItem("Chicken Breast", 2.0));
}
TEST(CheckoutTest, WhenItemIsOnSaleTheSaleLimitIsCorrectlyFollowed) {
Checkout checkout;
checkout.AddItem("soup", 1.89, 0.99, 3, true);
checkout.AddItem("Ground Beef", 5.99, 4.50, 2, true);
EXPECT_EQ("0.99", checkout.ScanItem("soup"));
EXPECT_EQ("1.98", checkout.ScanItem("soup"));
EXPECT_EQ("2.97", checkout.ScanItem("soup"));
EXPECT_EQ("4.86", checkout.ScanItem("soup"));
EXPECT_EQ("9.36", checkout.ScanItem("Ground Beef", 1.0));
EXPECT_EQ("16.11", checkout.ScanItem("Ground Beef", 1.5));
EXPECT_EQ("28.09", checkout.ScanItem("Ground Beef", 2.0));
}
TEST(CheckoutTest, WhenItemIsBuyOneGetOneFreeTheTotalPriceWillBeThePriceOfOneItem) {
Checkout checkout;
Item juice;
juice.name = "Juice";
juice.isOnSale = true;
juice.price = 1.99;
juice.saleLimit = 6;
juice.saleType = BOGO;
checkout.AddItem(juice);
EXPECT_EQ("1.99", checkout.ScanItem("Juice"));
EXPECT_EQ("1.99", checkout.ScanItem("Juice"));
}
TEST(CheckoutTest, WhenItemIsBuyOneGetOneFreeWithALimitOfFourTheSixthItemWillNotBeFree) {
Checkout checkout;
Item juice;
juice.name = "Juice";
juice.isOnSale = true;
juice.price = 1.99;
juice.saleLimit = 4;
juice.saleType = BOGO;
checkout.AddItem(juice);
EXPECT_EQ("1.99", checkout.ScanItem("Juice"));
EXPECT_EQ("1.99", checkout.ScanItem("Juice"));
EXPECT_EQ("3.98", checkout.ScanItem("Juice"));
EXPECT_EQ("3.98", checkout.ScanItem("Juice"));
EXPECT_EQ("5.97", checkout.ScanItem("Juice"));
EXPECT_EQ("7.96", checkout.ScanItem("Juice"));
}
TEST(CheckoutTest, WhenSoupIsBuyThreeForFiveWithALimitOfThreeTheCorrectTotalIsReturnedForThreeAndSixCansOfSoup) {
Checkout checkout;
Item soup;
soup.name = "soup";
soup.isOnSale = true;
soup.price = 1.89;
soup.saleLimit = 3;
soup.saleType = BUYXFORY;
soup.buyXItems = 3;
soup.forYprice = 5.00;
checkout.AddItem(soup);
EXPECT_EQ("1.67", checkout.ScanItem("soup"));
EXPECT_EQ("3.33", checkout.ScanItem("soup"));
EXPECT_EQ("5.00", checkout.ScanItem("soup"));
EXPECT_EQ("6.89", checkout.ScanItem("soup"));
EXPECT_EQ("8.78", checkout.ScanItem("soup"));
EXPECT_EQ("10.67", checkout.ScanItem("soup"));
}
TEST(CheckoutTest, WhenThreeCansOfSoupAreBoughtGetJuiceAtFiftyPercentOff) {
Checkout checkout;
Item soup, juice;
soup.name = "soup";
soup.isOnSale = false;
soup.price = 1.89;
soup.saleLimit = 3;
soup.buyXItems = 3;
juice.name = "juice";
juice.isOnSale = true;
juice.saleType = BUYXGETYOFF;
juice.saleItemBundled = "soup";
juice.buyXItems = 3;
juice.forYprice = .5;
juice.price = 1.99;
juice.saleLimit = 2;
checkout.AddItem(soup);
checkout.AddItem(juice);
EXPECT_EQ("1.89", checkout.ScanItem("soup"));
EXPECT_EQ("3.78", checkout.ScanItem("soup"));
EXPECT_EQ("5.67", checkout.ScanItem("soup"));
EXPECT_EQ("6.67", checkout.ScanItem("juice"));
EXPECT_EQ("7.66", checkout.ScanItem("juice"));
EXPECT_EQ("9.65", checkout.ScanItem("juice"));
}
TEST(CheckoutTest, WhenResetTotalIsCalledThePriceIsCorrectlyResetToZero) {
Checkout checkout;
Item soup, juice;
soup.name = "soup";
soup.price = 1.00;
soup.isOnSale = false;
juice.name = "juice";
juice.price = 0.0;
juice.isOnSale = false;
checkout.AddItem(soup);
checkout.AddItem(juice);
EXPECT_EQ("0.00", checkout.ScanItem("juice"));
EXPECT_EQ("1.00", checkout.ScanItem("soup"));
EXPECT_EQ("1.00", checkout.ScanItem("juice"));
checkout.ResetTotal();
EXPECT_EQ("0.00", checkout.ScanItem("juice"));
}
TEST(CheckoutTest, WhenSaleEndsPriceRevertsBackToRegularPrice) {
Checkout checkout;
Item salsa;
salsa.name = "salsa";
salsa.price = 2.00;
salsa.isOnSale = true;
salsa.salePrice = 1.00;
salsa.saleType = DISCOUNT;
salsa.saleLimit = 5;
checkout.AddItem(salsa);
EXPECT_EQ("1.00", checkout.ScanItem(salsa.name));
salsa.isOnSale = false;
salsa.saleType = NONE;
checkout.EditItem(salsa);
EXPECT_EQ("3.00", checkout.ScanItem(salsa.name));
}
TEST(CheckoutTest, WhenSoupIsBuyTwoGetOneFreeThePriceReflectsTheCostOfTwoCansOfSoup) {
Checkout checkout;
Item soup;
soup.name = "soup";
soup.price = 2.00;
soup.salePrice = 1.50;
soup.isOnSale = true;
soup.saleType = BUYXGETYFREE;
soup.buyXItems = 2;
soup.getYFree = 1;
soup.saleLimit = 6;
checkout.AddItem(soup);
EXPECT_EQ("2.00", checkout.ScanItem(soup.name));
EXPECT_EQ("4.00", checkout.ScanItem(soup.name));
EXPECT_EQ("4.00", checkout.ScanItem(soup.name));
EXPECT_EQ("6.00", checkout.ScanItem(soup.name));
EXPECT_EQ("8.00", checkout.ScanItem(soup.name));
EXPECT_EQ("8.00", checkout.ScanItem(soup.name));
EXPECT_EQ("10.00", checkout.ScanItem(soup.name));
EXPECT_EQ("12.00", checkout.ScanItem(soup.name));
EXPECT_EQ("14.00", checkout.ScanItem(soup.name));
EXPECT_EQ("16.00", checkout.ScanItem(soup.name));
}
TEST(CheckoutTest, WhenGetTotalIsCalledItReturnsTheCurrentTotal) {
Checkout checkout;
Item soup;
soup.name = "soup";
soup.price = 2.00;
soup.salePrice = 1.50;
soup.isOnSale = true;
soup.saleLimit = 4;
checkout.AddItem(soup);
EXPECT_EQ("1.50", checkout.ScanItem(soup.name));
EXPECT_EQ("1.50", checkout.GetTotal());
}
TEST(CheckoutTest, WhenSoupIsBuyTwoGetThreeFreeThePriceReflectsTheCostOfTwoCansOfSoup) {
Checkout checkout;
Item soup;
soup.name = "soup";
soup.price = 2.00;
soup.salePrice = 1.50;
soup.isOnSale = true;
soup.saleType = BUYXGETYFREE;
soup.buyXItems = 2;
soup.getYFree = 3;
soup.saleLimit = 10;
checkout.AddItem(soup);
EXPECT_EQ("2.00", checkout.ScanItem(soup.name));
EXPECT_EQ("4.00", checkout.ScanItem(soup.name));
EXPECT_EQ("4.00", checkout.ScanItem(soup.name));
EXPECT_EQ("4.00", checkout.ScanItem(soup.name));
EXPECT_EQ("4.00", checkout.ScanItem(soup.name));
EXPECT_EQ("6.00", checkout.ScanItem(soup.name));
EXPECT_EQ("8.00", checkout.ScanItem(soup.name));
EXPECT_EQ("8.00", checkout.ScanItem(soup.name));
EXPECT_EQ("8.00", checkout.ScanItem(soup.name));
EXPECT_EQ("8.00", checkout.ScanItem(soup.name));
}
TEST(CheckoutTest, WhenJuiceIsBuyTwoGetOneHalfOffTheTotalReturnedIsTwoAndAHalfTimesThePriceOfJuiceWithFourthBeingFullPrice) {
Checkout checkout;
Item juice;
juice.name = "juice";
juice.isOnSale = true;
juice.saleType = BUYXGETYOFF;
juice.saleItemBundled = "juice";
juice.buyXItems = 2;
juice.forYprice = .5;
juice.price = 2.00;
juice.saleLimit = 3;
checkout.AddItem(juice);
EXPECT_EQ("2.00", checkout.ScanItem(juice.name));
EXPECT_EQ("4.00", checkout.ScanItem(juice.name));
EXPECT_EQ("5.00", checkout.ScanItem(juice.name));
EXPECT_EQ("7.00", checkout.ScanItem(juice.name));
}
TEST(CheckoutTest, WhenGroundBeefIsPricedAtBuyThreePoundsGetThreePoundsHalfOffSevenPoundsIsPriceOfFiveAndAHalfPounds) {
Checkout checkout;
Item groundBeef;
groundBeef.name = "Ground Beef";
groundBeef.price = 5.00;
groundBeef.isOnSale = true;
groundBeef.saleType = BUYXGETYOFF;
groundBeef.saleItemBundled = "Ground Beef";
groundBeef.saleLimit = 6;
groundBeef.buyXLbs = 3.0;
groundBeef.forYprice = 0.5;
checkout.AddItem(groundBeef);
EXPECT_EQ("15.00", checkout.ScanItem(groundBeef.name, 3.0));
EXPECT_EQ("27.50", checkout.ScanItem(groundBeef.name, 4.0));
}
TEST(CheckoutTest, WhenGroundBeefIsPricedAtBuyThreePoundsGetThreePoundsHalfOffWithNoSaleLimitSevenPoundsIsPriceOfFiveAndAHalfPounds) {
Checkout checkout;
Item groundBeef;
groundBeef.name = "Ground Beef";
groundBeef.price = 5.00;
groundBeef.isOnSale = true;
groundBeef.saleType = BUYXGETYOFF;
groundBeef.saleItemBundled = "Ground Beef";
groundBeef.buyXLbs = 3.0;
groundBeef.forYprice = 0.5;
groundBeef.saleLimit = 100;
checkout.AddItem(groundBeef);
EXPECT_EQ("15.00", checkout.ScanItem(groundBeef.name, 3.0));
EXPECT_EQ("27.50", checkout.ScanItem(groundBeef.name, 4.0));
}
|
28985481ad362deea338c074ccfc864812a74245
|
8e242d624781b66c3dece9826c9e6bd0b358b59c
|
/DistillerDriver/DistillerDriver/DistillerDriverDlg.h
|
7874fa02fba27b1d53520dc47171bf9724091e53
|
[] |
no_license
|
asianhawk/Legacy
|
3b46d89dc0391e7bdb47d17af5142e63b9cd56a4
|
ac0e7cbdfade4fa7360e61597a9af49520ba8867
|
refs/heads/master
| 2020-07-23T09:22:15.206570
| 2015-01-20T17:32:51
| 2015-01-20T17:32:51
| 207,512,160
| 1
| 0
| null | 2019-09-10T09:01:39
| 2019-09-10T09:01:38
| null |
UTF-8
|
C++
| false
| false
| 958
|
h
|
DistillerDriverDlg.h
|
// DistillerDriverDlg.h : header file
//
#pragma once
// CDistillerDriverDlg dialog
class CDistillerDriverDlg : public CDialogEx
{
// Construction
public:
CDistillerDriverDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
enum { IDD = IDD_DISTILLERDRIVER_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
HICON m_hIcon;
CString m_strSourceDir;
CString m_strTargetDir;
CString m_strOptionsFile;
CString m_strWorkOrder;
// Generated message map functions
virtual BOOL OnInitDialog();
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
DECLARE_MESSAGE_MAP()
public:
private:
BOOL GetDirectory(CString &csDirectory);
public:
afx_msg void OnEnSetfocusTxbSourceDirectory();
afx_msg void OnEnSetfocusTxbTargetDirectory();
afx_msg void OnEnSetfocusTxbOptionsfile();
afx_msg void OnBnClickedOk();
afx_msg void OnEnKillfocusTxbWorkorder();
};
|
b60478b0e8a404d970837c4d343f9a66905ef599
|
541307260584040586970a43f024122bc9975849
|
/Integer.cpp
|
d66b8490a017b1d76be8049e9e85c3c0b55bf9b8
|
[] |
no_license
|
HIRURGOSIN/-
|
e58ac72e47dae8e48adba34f60613f243c5d5650
|
89d0e625bf1e394bc994154d256de0cdffba88a7
|
refs/heads/master
| 2022-09-12T03:36:46.195571
| 2020-05-31T20:42:15
| 2020-05-31T20:42:15
| 268,354,152
| 0
| 0
| null | 2020-05-31T20:10:47
| 2020-05-31T19:59:25
|
C++
|
UTF-8
|
C++
| false
| false
| 1,541
|
cpp
|
Integer.cpp
|
#pragma once
#include "Integer.h"
using namespace std;
Integer::Integer()
{
core = 0;
}
Integer::~Integer()
{
core = 0;
}
Integer& Integer::operator=(int val)
{
core = val;
return *this;
}
Integer& Integer::operator=(char* str)
{
core = atoi(str);
return *this;
}
const Integer operator++(Integer& num, int)
{
num.core++;
return num;
}
const Integer operator--(Integer& num, int)
{
num.core--;
return num;
}
const Integer operator+(const Integer& l, int val)
{
Integer ret;
ret.core = l.core + val;
return ret;
}
const Integer operator+(const Integer& l, const Integer& r)
{
Integer ret;
ret.core = l.core + r.core;
return ret;
}
const Integer operator-(const Integer& l, int val)
{
Integer ret;
ret.core = l.core - val;
return ret;
}
const Integer operator*(const Integer& l, int val)
{
Integer ret;
ret.core = l.core * val;
return ret;
}
bool operator==(const Integer& l, int val)
{
return l.core == val;
}
bool operator>(const Integer& l, int val)
{
return l.core > val;
}
bool operator<(const Integer& l, int val)
{
return l.core < val;
}
bool operator<=(const Integer& l, int val)
{
return l.core <= val;
}
bool operator<=(const Integer& l, const Integer& r)
{
return l.core <= r.core;
}
bool operator>=(const Integer& l, const Integer& r)
{
return l.core >= r.core;
}
bool operator>=(const Integer& l, int val)
{
return l.core >= val;
}
bool operator==(const Integer& l, const Integer& r)
{
return l.core == r.core;
}
|
e3f7cf335047cdfa26267655ce1cc64b4d25f235
|
8d0a8be1992e6c3faf67f6da2f10e4d4918be210
|
/src/core/dev_tools_http_handler_delegate_qt.cpp
|
7fa525dc1dd79a68adee36f995aa3be95d6f2266
|
[] |
no_license
|
Metrological/qtwebengine
|
e31f7798585188580601ce35882ffe9046f19bb4
|
7bb72a0b500f9ea7d8b3b37adc24a2700a309d2d
|
refs/heads/master
| 2021-01-24T22:26:39.095136
| 2014-04-28T23:16:21
| 2014-04-28T23:16:21
| 18,896,266
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,500
|
cpp
|
dev_tools_http_handler_delegate_qt.cpp
|
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtWebEngine module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "dev_tools_http_handler_delegate_qt.h"
#include <QByteArray>
#include <QFile>
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/strings/string_number_conversions.h"
#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/devtools_http_handler.h"
#include "content/public/browser/devtools_target.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_switches.h"
#include "net/socket/stream_listen_socket.h"
#include "net/socket/tcp_listen_socket.h"
using namespace content;
DevToolsHttpHandlerDelegateQt::DevToolsHttpHandlerDelegateQt(BrowserContext* browser_context)
: m_browserContext(browser_context)
{
const int defaultPort = 1337;
int listeningPort = defaultPort;
const CommandLine &commandLine = *CommandLine::ForCurrentProcess();
if (commandLine.HasSwitch(switches::kRemoteDebuggingPort)) {
std::string portString =
commandLine.GetSwitchValueASCII(switches::kRemoteDebuggingPort);
int portInt = 0;
if (base::StringToInt(portString, &portInt) && portInt > 0 && portInt < 65535)
listeningPort = portInt;
}
m_devtoolsHttpHandler = DevToolsHttpHandler::Start(new net::TCPListenSocketFactory("0.0.0.0", listeningPort), std::string(), this);
}
DevToolsHttpHandlerDelegateQt::~DevToolsHttpHandlerDelegateQt()
{
m_devtoolsHttpHandler->Stop();
}
std::string DevToolsHttpHandlerDelegateQt::GetDiscoveryPageHTML()
{
static std::string html;
if (html.empty()) {
QFile html_file(":/data/discovery_page.html");
html_file.open(QIODevice::ReadOnly);
QByteArray contents = html_file.readAll();
html = contents.data();
}
return html;
}
bool DevToolsHttpHandlerDelegateQt::BundlesFrontendResources()
{
return true;
}
base::FilePath DevToolsHttpHandlerDelegateQt::GetDebugFrontendDir()
{
return base::FilePath();
}
std::string DevToolsHttpHandlerDelegateQt::GetPageThumbnailData(const GURL& url)
{
return std::string();
}
scoped_ptr<DevToolsTarget> DevToolsHttpHandlerDelegateQt::CreateNewTarget(const GURL&)
{
return scoped_ptr<DevToolsTarget>();
}
void DevToolsHttpHandlerDelegateQt::EnumerateTargets(TargetCallback callback)
{
callback.Run(TargetList());
}
scoped_ptr<net::StreamListenSocket> DevToolsHttpHandlerDelegateQt::CreateSocketForTethering(net::StreamListenSocket::Delegate* delegate, std::string* name)
{
return scoped_ptr<net::StreamListenSocket>();
}
|
48c25af347244191e92101d0c7d72864be610709
|
8c6d46df7efb06de79a4bea15b031db426398465
|
/MetaPresent.h
|
58d09dc1d0243a1a50b6972e7589f2ab3d498fcd
|
[] |
no_license
|
dima42/packing-santas-sleigh
|
08c4654704432a778d20ff53b1f6dd2c8b579959
|
ce63978324d128cc34f764bccd962833b8629c2e
|
refs/heads/master
| 2020-06-08T16:07:04.746672
| 2014-06-30T18:24:01
| 2014-06-30T18:24:01
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,068
|
h
|
MetaPresent.h
|
#pragma once
#include <algorithm>
#include <array>
#include <cmath>
#include <fstream>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
#include <iostream>
//still debugging/tuning metapresents
typedef std::vector<int> Rotation;
/* a rotation is encoded in a permutation of [0, 1, 2].
e.g. {0, 1, 2} means x is the smallest side and z is the largest side.
*/
struct Coords {
/*contains the min and max x/y/z of present's placement
Coord.min=Coord.max={-1, -1, -1} if the present is not yet placed
it is also possible to have a present partially placed, e.g. only x/y set
*/
std::vector<int> min;
std::vector<int> max;
void flip(const bool flip_x, const bool flip_y, const Coords &flip_coords);
};
class MetaPresent {
public:
MetaPresent(const int o, const int a, const int b, const int c,
const Rotation &r);
//create single-present metapresent with order o, sides a/b/c and rotation r
MetaPresent(MetaPresent lower, MetaPresent upper, int merge_height);
//creates a deeper level metapresent with these two presents
void rotate(const Rotation &r, bool set=true);
int getSide(const int side_index) const
{
if (m_order == 194){
// std::cout << side_index << " " <<m_lwh[side_index] <<"; ";
}
return m_lwh[side_index];}
//get a side length: 0 for x, 1 for y, 2 for z
void place(const Coords &c) {m_coords = c;}
Rotation getRotation() const {return m_rotation;}
const Coords& getCoords() const {return m_coords;}
int getOrder() const {return m_order;}
bool isLeaf() const {return m_leaf;}
std::vector<std::shared_ptr<MetaPresent>> getBasePointers();
//returns children pointers
bool addChild(MetaPresent child, bool lower);
bool fitChild(const MetaPresent &child, bool lower);
void setOrderOffset(double o) {m_order_offset = o;}
const double getOrderOffset() const{return m_order_offset;}
private:
std::vector<std::shared_ptr<MetaPresent>> m_children_ptrs;
bool m_leaf; //false if this has any children
double m_order_offset;
int m_split_height;
//highest occupied z-coordinate of lower part (in [1, 250] coordinates])
std::vector<Coords> m_lower_coords; //coords of lower presents
std::vector<Coords> m_upper_coords; //coords of upper presents
int m_lower_y_cursor;
int m_lower_x_cursor;
int m_upper_y_cursor;
int m_upper_x_cursor;
int m_lower_max_y;
int m_upper_max_y;
Rotation m_rotation;
std::vector<int> m_lwh;
std::vector<int> m_sorted_lwh;
int m_order;
Coords m_coords;
};
class MetaPresentV{
public:
MetaPresentV();
//create an empty metapresent vector
MetaPresentV(const std::string &filename, const int count);
//load a metapresent vector from input file
//uses {0, 1, 2} for starting rotation
MetaPresentV(const MetaPresentV &parent, const int start_index, const int count);
//create a metapresent vector from the elements of another present vector
~MetaPresentV(){};
double volume() const;
bool collides(const Coords &c) const;
//checks if c collides with any of presents in self
int size() const
{return m_metapresents.size();}
const MetaPresent& getMetaPresent(const int index) const
{return m_metapresents[index];}
std::vector<MetaPresent> getMetaPresents() const
{return m_metapresents;}
void erase(const int index)
{m_metapresents.erase(m_metapresents.begin()+index);}
void insert(const MetaPresent &p)
{m_metapresents.push_back(p);}
void insert(const MetaPresentV &new_pv);
void rotate(const Rotation r, const int index)
{m_metapresents[index].rotate(r);}
//void sortByDescendingSide(const int side_index);
void sortByDescendingArea();
void sortByMaxXYSide(const std::vector<double> &oos);
void sortByOrder();
int maxHeight();
double addMetaLevel();
void unravel();
//will merge metapresents by one level
//note: currently we support level 0 and 1 only
private:
double getScore(Rotation &best_low_r, Rotation &best_up_r,
const std::vector<MetaPresent>::iterator low_it,
const std::vector<MetaPresent>::iterator up_it,
const int max_height, const int merge_height);
//get merge score; updates the rotations to reflect best ones
double addOnMergePresents(MetaPresent &merge,
int &merge_height, int &max_low_order,
std::vector<MetaPresent>::iterator &up_it,
int max_height);
//add on presents to a newly formed metapresent
//todo memoize collision stuff
std::vector<MetaPresent> m_metapresents;
std::vector<Rotation> m_possible_rots;
};
|
e89c28292ac75d5b4a8b0a8c31fc93bc5d65e45c
|
cd484c21d9d412d81ee3039072365fbb32947fce
|
/WBoard/Source/customWidgets/WBGraphicsItemAction.h
|
ee5bc3a3043cbf8324e97c0f75cd805d175c1658
|
[] |
no_license
|
drivestudy/WBoard
|
8c97fc4f01f58540718cd2c082562f9eab5761de
|
18959203a234944fb402b444462db76c6dd5b3c6
|
refs/heads/main
| 2023-08-01T01:41:04.303780
| 2021-09-09T04:56:46
| 2021-09-09T04:56:46
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,059
|
h
|
WBGraphicsItemAction.h
|
#ifndef WBGRAPHICSITEMSACTIONS_H
#define WBGRAPHICSITEMSACTIONS_H
#include <QObject>
#include <QtMultimedia>
enum eWBGraphicsItemMovePageAction {
eMoveToFirstPage = 0,
eMoveToLastPage,
eMoveToPreviousPage,
eMoveToNextPage,
eMoveToPage
};
enum eWBGraphicsItemLinkType
{
eLinkToAudio = 0,
eLinkToPage,
eLinkToWebUrl
};
class WBGraphicsItemAction : public QObject
{
Q_OBJECT
public:
WBGraphicsItemAction(eWBGraphicsItemLinkType linkType,QObject* parent = 0);
virtual void play() = 0;
virtual QStringList save() = 0;
virtual void actionRemoved();
virtual QString path() {return "";}
eWBGraphicsItemLinkType linkType() { return mLinkType;}
private:
eWBGraphicsItemLinkType mLinkType;
};
class WBGraphicsItemPlayAudioAction : public WBGraphicsItemAction
{
Q_OBJECT
public:
WBGraphicsItemPlayAudioAction(QString audioFile, bool onImport = true, QObject* parent = 0);
WBGraphicsItemPlayAudioAction();
~WBGraphicsItemPlayAudioAction();
void play();
QStringList save();
void actionRemoved();
QString path() {return mAudioPath;}
void setPath(QString audioPath);
QString fullPath();
public slots:
void onSourceHide();
private:
QString mAudioPath;
QMediaPlayer *mAudioOutput;
bool mIsLoading;
QString mFullPath;
};
class WBGraphicsItemMoveToPageAction : public WBGraphicsItemAction
{
Q_OBJECT
public:
WBGraphicsItemMoveToPageAction(eWBGraphicsItemMovePageAction actionType, int page = 0, QObject* parent = 0);
void play();
QStringList save();
int page(){return mPage;}
eWBGraphicsItemMovePageAction actionType(){return mActionType;}
private:
eWBGraphicsItemMovePageAction mActionType;
int mPage;
};
class WBGraphicsItemLinkToWebPageAction : public WBGraphicsItemAction
{
Q_OBJECT
public:
WBGraphicsItemLinkToWebPageAction(QString url, QObject* parent = 0);
void play();
QStringList save();
QString url(){return mUrl;}
private:
QString mUrl;
};
#endif // WBGRAPHICSITEMSACTIONS_H
|
e1d626a6bf9cc08aff33c3fc68541c7e77a384a9
|
ae9b06486266e4c68990ad399be35062d3ea7837
|
/fubble/signaling/server/application.hpp
|
3c6bb2e10f76bcc3b94d0ee966e1b14e60e489e9
|
[] |
no_license
|
lineCode/fubble
|
ffd262109009da6336b149b41b551f302f68d1aa
|
2b0bddb65b881ab4a0a7ed629fb08ccc7774da82
|
refs/heads/master
| 2023-03-24T11:07:22.817007
| 2021-03-25T10:09:18
| 2021-03-25T10:09:18
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 686
|
hpp
|
application.hpp
|
#ifndef UUID_307C4AF5_CA51_47FF_9618_3CAF0AC98FAE
#define UUID_307C4AF5_CA51_47FF_9618_3CAF0AC98FAE
#include <memory>
namespace boost::asio {
class io_context;
} // namespace boost::asio
namespace signaling {
class registration_handler;
}
namespace signaling::server {
class server;
class application {
public:
virtual ~application() = default;
virtual int get_port() const = 0;
virtual void close() = 0;
virtual server &get_server() = 0;
virtual registration_handler &get_registrations() = 0;
static std::unique_ptr<application> create(boost::asio::io_context &context,
int port);
};
} // namespace signaling::server
#endif
|
eceae33571ff45621e8163c6b8b73d987686c839
|
3ac8c943b13d943fbd3b92787e40aa5519460a32
|
/Source/Multitasking/Scheduler.cpp
|
6a5713b10562bad13effc4f47925fb054d3fe1b9
|
[
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
locosoft1986/Microkernel-1
|
8069bd2be390d6d8ad10f73e8a944112a764a401
|
c9dfeec4581d4dd8b1e9020adb3778ad78b3e525
|
refs/heads/master
| 2021-01-24T04:54:08.589308
| 2010-09-23T19:38:01
| 2010-09-23T19:38:01
| null | 0
| 0
| null | null | null | null |
WINDOWS-1252
|
C++
| false
| false
| 12,493
|
cpp
|
Scheduler.cpp
|
#include <Multitasking/Scheduler.h>
#include <LinkedList.h>
#include <Boot/DescriptorTables.h>
#include <MemoryAllocation/Physical.h>
List<Scheduler *> *Scheduler::schedulers = 0;
Mutex *Scheduler::schedulerListMutex = 0;
void Scheduler::setKernelStack(unsigned int esp)
{
DescriptorTables::InstallTSS(esp, getCPUIdentifier());
}
unsigned int Scheduler::getCPUIdentifier()
{
unsigned int tss = 0;
//Store the TSS register (STR) and assume that there is one TSS per CPU.
asm volatile ("str %0" : "=r"(tss));
//The TSS selector is ORed with the privilege level (3). Remove that OR
tss &= (~3);
//If there's no TSS, then the only possibility is that the code's running on the first CPU
if(tss == 0)
return 0;
//Each selector is 0x8 bytes long.
//The first TSS is the fifth selector
return (tss / 0x8) - 5;
}
void Scheduler::SetupStack()
{
physAddress page = 0;
unsigned int id = getCPUIdentifier();
virtAddress stackLocation = 0xF0400000 + (PageSize * id);
uint64 mappingFlags = 0;
//Make certain that the stack isn't already mapped
MemoryManagement::Virtual::RetrieveMapping(stackLocation, &mappingFlags);
//If it's present, I've already called SetupStack for this logical core, and don't need to do anything
if((mappingFlags & MemoryManagement::x86::PageDirectoryFlags::Present) != 0)
return;
page = MemoryManagement::Physical::PageAllocator::AllocatePage(false);
MemoryManagement::Virtual::MapMemory((physAddress)page, stackLocation, MemoryManagement::x86::PageDirectoryFlags::ReadWrite);
//Adding PageSize will push the stack into the next page. That isn't mapped.
//I subtract four because the stack needs to be aligned on a DWORD boundary
setKernelStack(stackLocation - sizeof(virtAddress));
}
Scheduler::Scheduler(Process *first)
{
if(schedulerListMutex == 0)
schedulerListMutex = new Mutex(true);
if(first != 0)
{
totalPriority = first->GetPriority();
if((first->GetState() & ProcessState::IOBound) == ProcessState::IOBound)
totalPriority /= 2;
currentProcess = first;
currentThread = first->threads->First->Value;
}
else
{
totalPriority = 0;
currentProcess = 0;
currentThread = 0;
}
timer = 0;
processes = new LinkedList<Process *>(first);
processListMutex = new Mutex(true);
sleepingProcesses = new LinkedList<Process *>(0);
randomGen = new RandomGenerator();
}
Scheduler::~Scheduler()
{
}
void Scheduler::Yield(StackStates::Interrupt *stack)
{
/*
* Generate a random number, n, between 0 and totalPriority.
* Treat it as an index into the address space of total process priorities. Example:
* _____________________
* ยฆA ยฆ B ยฆ C ยฆ
* -------^
* Here it can clearly be seen that the next process to be run should be B. So keep an accumulator
* running; when the previous accumulator value is less than or equal to n, and the current accumulator
* value is greater than or equal to n, I know that the process I need is in place and that I should context switch.
*
* Note: The current time complexity is O(N). It'd be nice if I could make this more efficient without
* scaling down to a round-robin system
*/
unsigned int rnd = randomGen->Next(0, totalPriority);
unsigned int accumulator = 0;
for(LinkedListNode<Process *> *fst = processes->First; fst != 0 && fst->Value != 0; fst = fst->Next)
{
unsigned int effectivePriority = fst->Value->GetPriority();
unsigned int prevAccumulator = accumulator;
if((fst->Value->GetState() & ProcessState::IOBound) == ProcessState::IOBound)
effectivePriority /= 2;
accumulator += effectivePriority;
if(rnd >= prevAccumulator && rnd < accumulator)
{
YieldTo(fst->Value, stack);
break;
}
}
}
void Scheduler::YieldTo(Process *p, StackStates::Interrupt *stack)
{
if(p == 0)
return;
/*
* If a process has no threads, then it can't be scheduled. This could make things a little unfair if the process has
* a very high priority, but since a process is loaded with a single thread which loads the actual executable, I'm not
* overly worried about this possibility
*/
if(p->GetThreads()->GetCount() == 0)
return;
//Optimisation alert: if the current process is the same as the one being switched to, there's no need to flush the TLB
if(p != currentProcess)
{
currentProcess = p;
//Switch address spaces and prepare to hook up the next thread
asm volatile ("mov %0, %%cr3" : : "r"(currentProcess->GetPageDirectory()));
}
//Just iterate through the linked list of threads after carefully selecting the process
//If I'm at the end of the linked list, then start at the beginning again
if(currentProcess->currentThread->Next == 0)
currentProcess->currentThread = currentProcess->threads->First;
else
currentProcess->currentThread = currentProcess->currentThread->Next;
//Keep cycling through the process list until there's a non-sleeping thread.
//Theoretically, a process filled with sleeping threads could cause a page fault at 0x0, but this cannot happen because
//there is a separate list for sleeping processes
for(; currentProcess->currentThread != 0 && currentProcess->currentThread->Value != 0 &&
currentProcess->currentThread->Value->IsSleeping() ;
currentProcess->currentThread = currentProcess->currentThread->Next)
;
if(currentProcess->currentThread == 0)
asm volatile ("cli; hlt" : : "a"(0xDEAD));
if(stack != 0)
{
//Save the previous thread state
currentThread->state->CS = stack->CS;
currentThread->state->DS = stack->DS;
currentThread->state->RAX = stack->RAX;
currentThread->state->RBX = stack->RBX;
currentThread->state->RCX = stack->RCX;
currentThread->state->RDX = stack->RDX;
currentThread->state->RSP = stack->RSP;
currentThread->state->RBP = stack->RBP;
currentThread->state->RDI = stack->RDI;
currentThread->state->RSI = stack->RSI;
currentThread->state->RFLAGS = stack->RFLAGS;
currentThread->state->RIP = stack->RIP;
}
else if(currentThread != 0)
{
//If there's no stack, and a thread exists to store, then get the values directly from there
asm volatile ("mov %%rax, %0" : "=r"(currentThread->state->RAX));
asm volatile ("mov %%rbx, %0" : "=r"(currentThread->state->RBX));
asm volatile ("mov %%rcx, %0" : "=r"(currentThread->state->RCX));
asm volatile ("mov %%rdx, %0" : "=r"(currentThread->state->RDX));
asm volatile ("mov %%rdi, %0" : "=r"(currentThread->state->RDI));
asm volatile ("mov %%rsi, %0" : "=r"(currentThread->state->RSI));
asm volatile ("mov %%rsp, %0" : "=r"(currentThread->state->RSP));
asm volatile ("mov %%rbp, %0" : "=r"(currentThread->state->RBP));
}
//Switch to the next thread
currentThread = currentProcess->currentThread->Value;
//Perform the actual context switch. A stack of zero signifies that the changes should be done on the current stack
if(stack != 0)
{
stack->CS = currentThread->state->CS;
stack->DS = currentThread->state->DS;
//I don't alter SS because every process' stack segment is the same
stack->RAX = currentThread->state->RAX;
stack->RBX = currentThread->state->RBX;
stack->RCX = currentThread->state->RCX;
stack->RDX = currentThread->state->RDX;
stack->RSP = currentThread->state->RSP;
stack->RBP = currentThread->state->RBP;
stack->RDI = currentThread->state->RDI;
stack->RSI = currentThread->state->RSI;
stack->RFLAGS = currentThread->state->RFLAGS;
stack->RIP = currentThread->state->RIP;
}
else
{
//There's no need to switch the segment registers because they should remain constant across switches.
//However, when multitasking is just getting started, I will need to switch to a secondary, ring 3 task
asm volatile ("mov %0, %%rax" : : "r"(currentThread->state->RAX));
asm volatile ("mov %0, %%rbx" : : "r"(currentThread->state->RBX));
asm volatile ("mov %0, %%rcx" : : "r"(currentThread->state->RCX));
asm volatile ("mov %0, %%rdx" : : "r"(currentThread->state->RDX));
asm volatile ("mov %0, %%rdi" : : "r"(currentThread->state->RDI));
asm volatile ("mov %0, %%rsi" : : "r"(currentThread->state->RSI));
asm volatile ("mov %0, %%rsp" : : "r"(currentThread->state->RSP));
asm volatile ("mov %0, %%rbp" : : "r"(currentThread->state->RBP));
//There's no need to manipulate EFLAGS, EIP et al because when the stack registers get changed, EIP is found there
}
//All these changes get pushed back onto the stack when the interrupt handler completes, changing to another thread
}
void Scheduler::SetTimer(Drivers::DriverInfoBlock *tmr)
{
timer = tmr;
}
bool Scheduler::TimerInUse(Drivers::DriverInfoBlock *tmr)
{
return (tmr == timer);
}
Process *Scheduler::GetCurrentProcess()
{
return currentProcess;
}
Thread *Scheduler::GetCurrentThread()
{
return currentThread;
}
void Scheduler::AddProcess(Process *p)
{
if(p != 0)
{
processListMutex->Lock();
processes->Add(p);
totalPriority += ((p->GetState() & ProcessState::IOBound) == ProcessState::IOBound) ? (p->priority / 2) : p->priority;
processListMutex->Unlock();
}
}
void Scheduler::RemoveProcess(Process *p)
{
//Remove the process from the priority calculations
unsigned int priority = (p->GetState() & ProcessState::IOBound) == ProcessState::IOBound ? p->priority / 2 : p->priority;
processListMutex->Lock();
totalPriority -= priority;
processes->Remove(p);
//If the current process has been removed, then perform a simplistic method of returning - just set the first process
if(currentProcess == p)
{
currentProcess = processes->First->Value;
if(currentProcess->currentThread->Next == 0)
currentProcess->currentThread = currentProcess->threads->First;
else
currentProcess->currentThread = currentProcess->currentThread->Next;
currentThread = currentProcess->currentThread->Value;
}
processListMutex->Unlock();
}
void Scheduler::Sleep(Process *p)
{
RemoveProcess(p);
sleepingProcesses->Add(p);
//Tell the process to notify its parent that it's gone to sleep
p->sendStatusChangeMessage(0x0);
}
void Scheduler::Wake(Process *p)
{
//Unfortunately, this is a necessary hack. I return 0 if I can't find the element I want. Zero is also a valid
//index, so I check the First field.
//If the process is not present in the list of sleeping processes, it's already awake and doesn't need waking again
if(sleepingProcesses->First->Value != p && sleepingProcesses->Find(p) == 0)
return;
sleepingProcesses->Remove(p);
AddProcess(p);
p->sendStatusChangeMessage(0x1);
}
Scheduler *Scheduler::GetScheduler()
{
unsigned int id = getCPUIdentifier();
//If the first core is booting, then the list won't exist. Don't tell the rest of the OS that an AP has booted
if(schedulers == 0)
{
Scheduler *addSched = new Scheduler(0);
schedulerListMutex->Lock();
schedulers = new List<Scheduler *>();
schedulers->Add(addSched);
schedulerListMutex->Unlock();
return addSched;
}
//If the total number of items is greater than id, the instance can't exist, and needs to be created
if(schedulers->GetItem(id) == 0)
{
unsigned int max = id > schedulers->GetCount() ? id : schedulers->GetCount();
unsigned int min = id < schedulers->GetCount() ? id : schedulers->GetCount();
//Processor IDs are always consecutive
//If something gets to this point, then an AP has booted
if(max - min == 1)
{
Scheduler *newScheduler = new Scheduler(0);
schedulerListMutex->Lock();
schedulers->Add(newScheduler);
schedulerListMutex->Unlock();
return newScheduler;
}
else
{
Scheduler *newScheduler = new Scheduler(0);
schedulerListMutex->Lock();
//If the ID isn't consecutive, then fill in the gaps
for(unsigned int i = 0; i < max - min; i++)
schedulers->Add(0);
schedulers->Add(newScheduler);
schedulerListMutex->Unlock();
return newScheduler;
}
}
else
return schedulers->GetItem(id);
}
LinkedList<Process *> *Scheduler::GetAllProcesses()
{
LinkedList<Process *> *allProcesses = new LinkedList<Process *>();
//Prevent the list of schedulers from changing, as it could on a multi-core system
schedulerListMutex->Lock();
//Now that everything's sane, iterate through each scheduler..
for(unsigned int i = 0; i < schedulers->GetCount(); i++)
{
Scheduler *sch = schedulers->GetItem(i);
//..and prevent them from messing with the lists we're about to enumerate
sch->processListMutex->Lock();
for(LinkedListNode<Process *> *nd = sch->processes->First; nd != 0 && nd->Value != 0; nd = nd->Next)
allProcesses->Add(nd->Value);
sch->processListMutex->Unlock();
}
schedulerListMutex->Unlock();
return allProcesses;
}
|
90ba82970d3c6cfa75f2f5aa17243393148801da
|
e313d9c25ac8f6982aa99c80e68abae981e7deb2
|
/Arrays/LeftRotation.cpp
|
d7808c50126c75c9362c8b4158188fc85b0cca38
|
[] |
no_license
|
jfc4050/HRDataStructures
|
623e52748bfbcadadb3351a25b02b1dcf217f286
|
b294b4d02cf27ba1782544b75550b5ce6ad691bd
|
refs/heads/master
| 2021-06-26T13:03:50.892462
| 2017-09-13T02:19:05
| 2017-09-13T02:19:05
| 103,315,759
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 974
|
cpp
|
LeftRotation.cpp
|
//
// Created by Justin Chiu on 9/12/17.
//
#include <vector>
#include <iostream>
#include <deque>
using namespace std;
vector <int> leftRotation(vector <int> &arr, int leftRot) {
//declare and populate deque
deque<int> deq;
for (int i : arr) {
deq.push_back(i);
}
//perform specified number of left rotations
while (leftRot--){
deq.push_back(deq.front());
deq.pop_front();
}
//overwrite input vector
arr.clear();
for (int i : deq) {
arr.push_back(i);
}
return arr;
}
int main() {
int arrLen, leftRot;
cin >> arrLen
>> leftRot;
vector<int> arr(arrLen);
for(int i = 0; i < arrLen; ++i){
cin >> arr[i];
}
vector <int> result = leftRotation(arr, leftRot);
for (auto iter = result.begin() ; iter != result.end() ; ++iter) {
cout << *iter
<< (iter != result.end() - 1 ? " " : "");
}
cout << endl;
return 0;
}
|
168ab562c3395cc35874ce65699711df54c76198
|
b9efb7d682f6ee7d4ed980ed68b5b2cceed7df02
|
/Chapter 1 (Beginner)/combo.cc
|
5ae56c81055e82a3261bc5d0ee07009fdce6b81e
|
[] |
no_license
|
smoteval/Contest-Problems-USACO-
|
a33e8f59a6b8e709603e602be2787de9deb7573a
|
0418add4b234679b87be0e8952426180e0c3cb9c
|
refs/heads/master
| 2021-01-10T03:33:00.858530
| 2015-05-26T05:16:54
| 2015-05-26T05:16:54
| 36,273,568
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,464
|
cc
|
combo.cc
|
/*
ID: smoteva1
LANG: C++
TASK: combo
*/
#include <iostream>
#include <map>
#include <fstream>
#include <cmath>
#include <algorithm>
using namespace std;
bool within(int arr[],int a,int b, int c, int N) {
bool val = true;
if( abs(arr[0]-a) > 2 ) {
if(arr[0] < a) {
int l = arr[0] + N;
if( abs(l - a) > 2 ) {
val = false;
}
}
else {
a = a + N;
if( abs(arr[0] - a) > 2 ) {
val = false;
}
}
}
if( abs(arr[1]-b) > 2 ) {
if(arr[1] < b) {
int l = arr[1] + N;
if( abs(l - b) > 2 ) {
val = false;
}
}
else {
b = b + N;
if( abs(arr[1] - b) > 2 ) {
val = false;
}
}
}
if( abs(arr[2]-c) > 2 ) {
if(arr[2] < c) {
int l = arr[2] + N;
if( abs(l - c) > 2 ) {
val = false;
}
}
else {
c = c + N;
if( abs(arr[2] - c) > 2 ) {
val = false;
}
}
}
return val;
}
int main() {
ifstream my;
my.open ("combo.in");
int N;
my >> N;
int farmer[3];
int master[3];
for(int i=0;i<3;i++) {
int n;
my >> n;
farmer[i] = n;
}
for(int i=0;i<3;i++) {
int n;
my >> n;
master[i] = n;
}
/// End of INPUT
int res = 0;
for(int i1=1;i1<=N;i1++) {
for(int i2=1;i2<=N;i2++) {
for(int i3=1;i3<=N;i3++) {
if(within(farmer,i1,i2,i3,N) || within(master,i1,i2,i3,N)) {
res = res+1;
}
else {
//cout << i1 << " " << i2 << " " << i3 << endl;
}
}
}
}
ofstream myfile;
myfile.open("combo.out");
myfile << res << endl;
myfile.close();
}
|
560ee195b101182412e74f49e3636a173528f540
|
a33b56ecce38e11da5ed446a4a7bdfd83b0f3ab1
|
/class.h
|
414159a2e9258d98dbb863dd7482086753a973dc
|
[] |
no_license
|
albertpratomo/InfiniteEscape
|
bfa2cbb8f1b1737a3fc1b2df209a722a0301565b
|
219f914aea06b7a7a4e5b7bedf6a3698c3b05c83
|
refs/heads/master
| 2021-07-08T17:12:53.102733
| 2017-10-02T18:15:47
| 2017-10-02T18:15:47
| 105,565,225
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 33,149
|
h
|
class.h
|
#include <SFML/Graphics.hpp>
#include <iostream>
#include <string>
#include <Windows.h>
#include <conio.h>
#include <string.h>
#include <time.h>
#include <math.h>
class CPosition{
protected:
int m_x;
int m_y;
public:
int GetX(){return m_x;}
int GetY(){return m_y;}
void SetY(int n){m_y = n;}
void SetX(int n){m_x = n;}
};
class CDensus:public CPosition{
sf::Texture texture;
sf::Sprite player;
CPosition m_pos;
int m_exist;
int m_view;
int lastMove;
sf::Font fontPlayer;
sf::Text textPlayer;
sf::Text textType;
public:
CDensus(){
m_exist = 0;
m_pos.SetX(0);
m_pos.SetY(0);
lastMove = 0;
texture.loadFromFile("images/densus.png");
texture.setSmooth(true);
player.setTexture(texture);
player.setTextureRect(sf::IntRect(0,0, 32, 32));
fontPlayer.loadFromFile("font/font.ttf");
textPlayer.setFont(fontPlayer);
textPlayer.setStyle(sf::Text::Bold);
textPlayer.setColor(sf::Color::White);
textPlayer.setCharacterSize(12);
textPlayer.setOrigin(textPlayer.getGlobalBounds().left, textPlayer.getGlobalBounds().height / 2);
textType.setString("");
textType.setFont(fontPlayer);
textType.setStyle(sf::Text::Bold);
textType.setColor(sf::Color::Yellow);
textType.setCharacterSize(12);
textType.setOrigin(textPlayer.getOrigin().x, textPlayer.getOrigin().y);
}
void SetExist(int exist,float view){
if(exist == 1){SetImage(1);}
m_exist = exist;
m_view = ceil(view/32.0);
}
void SetImage(int n = 0){
if(n == 1){
texture.loadFromFile("images/densus.png");
}
else {
texture.loadFromFile("images/densusfire.png");}
player.setTexture(texture);
}
void SetText(char* text){
textPlayer.setString(text);
}
bool SetType(char type){
textType.setString(textType.getString() + type);
if(textType.getString().getSize() == 5){
m_exist=-180;
return true;
}
return false;
}
bool CekType(char type){
if(type == textPlayer.getString().substring(textType.getString().getSize(),1)){
return true;
}
return false;
}
int GetExist(){
return m_exist;
}
void MoveX(){
if(m_pos.GetX()==2){m_pos.SetX(0);}
else{m_pos.SetX(2);}
}
void MoveRight(){
m_pos.SetY(2);
MoveX();
Move(1,0);
}
void MoveLeft(){
m_pos.SetY(1);
MoveX();
Move(-1,0);
}
void MoveUp(){
m_pos.SetY(3);
MoveX();
Move(0,-1);
}
void MoveDown(){
m_pos.SetY(0);
MoveX();
Move(0,1);
}
void SetPosition(int map[24][30], int diff){
int x=0,y;
bool status = true;
while(status){
y = 13 - diff;
if(y%2 == 0){
for(int i=0;i<30;i++){
if(map[y][i] == -2){
x++;
if(x>=rand()%5+2){
x=i;
break;
}
}
}
}
else{
for(int i=29;i>=0;i--){
if(map[y][i] == -2){
x++;
if(x>=rand()%5+2){
x=i;
break;
}
}
}
}
diff+=5;
if(map[y][x]==-2){status = false;}
}
m_x = x;
m_y = y;
player.setPosition(m_x*32, (m_y+m_view)*32-4);
}
void DecideMove(int map[24][30]){
if(map[m_y][m_x]>=0){
if(map[m_y][m_x+1]==map[m_y][m_x]-1){MoveRight();}
else if(map[m_y][m_x-1]==map[m_y][m_x]-1){MoveLeft();}
else if(map[m_y+1][m_x]==map[m_y][m_x]-1){MoveDown();}
else if(map[m_y-1][m_x]==map[m_y][m_x]-1){MoveUp();}
}
else{
int co=rand()%4;
if(co==0 && map[m_y][m_x+1] != -1){MoveRight();}
else if(co==1 && map[m_y][m_x-1] != -1){MoveLeft();}
else if(co==2 && map[m_y+1][m_x] != -1){MoveDown();}
else if(map[m_y-1][m_x] != -1){MoveUp();}
}
}
void Move(int dx, int dy){
m_x+=dx;
m_y+=dy;
if(m_x<0){m_x=0;}
if(m_x>29){m_x=29;}
if(m_y<0){m_y=0;}
if(m_y>23){m_y=23;}
player.setTextureRect(sf::IntRect(m_pos.GetX()*32, m_pos.GetY()*32, 32,32));
player.setPosition(m_x*32, (m_y+m_view)*32-4);
}
void SetTexture(int n=0){
player.setTextureRect(sf::IntRect(n*32, 0, 32, 64));
}
void Print(sf::RenderWindow &window){
if(m_exist!=0){
if(m_exist<-150){SetTexture(0);}
else if(m_exist<-120){SetTexture(1);}
else if(m_exist<-90){SetTexture(2);}
else if(m_exist<-60){SetTexture(3);}
else if(m_exist<-30){SetTexture(4);}
else if(m_exist<0){SetTexture(5);}
player.setPosition(m_x*32, (m_y+m_view)*32-4);
if(m_exist<0){player.setPosition(player.getPosition().x, player.getPosition().y-32 +4);}
window.draw(player);
textPlayer.setPosition(player.getGlobalBounds().left - 4, player.getGlobalBounds().top);
textType.setPosition(player.getGlobalBounds().left - 4, player.getGlobalBounds().top);
window.draw(textPlayer);
window.draw(textType);
if(m_exist<0){m_exist++;}
}
else{
textType.setString("");
}
}
};
class CPowerup:public CPosition{
int m_exist;
std::string m_typePowerup;
sf::Texture m_texturePowerup;
sf::Sprite m_spritePowerup;
public:
CPowerup(){
m_exist = 0;
}
void SetUp(int tipe,int x, int y){
if (tipe == 0){
m_texturePowerup.loadFromFile("images/freeze.png");
m_typePowerup = "F";
}
else if (tipe == 1){
m_texturePowerup.loadFromFile("images/stealth.png");
m_typePowerup = "S";
}
else if (tipe == 2){
m_texturePowerup.loadFromFile("images/bomb.png");
m_typePowerup = "B";
}
else if (tipe == 3){
m_texturePowerup.loadFromFile("images/laser.png");
m_typePowerup = "L";
}
m_spritePowerup.setTexture(m_texturePowerup);
m_x = x;
m_y = y;
m_exist = 1;// powerup sudah di print di map
}
void SetExist(int n){
m_exist = n;
}
int GetExist(){
return m_exist;
}
std::string GetType(){
return m_typePowerup;
}
void Print(sf::RenderWindow &window){
m_spritePowerup.setPosition(m_x * 32, m_y * 32);
window.draw(m_spritePowerup);
}
void Move(){
m_y++;
}
};
class CSkill{
protected:
int m_duration;
int m_exist;
std::string m_type;
sf::Clock m_count;
sf::SoundBuffer m_soundbuffer;
sf::Sound m_sound;
public:
CSkill(){
m_exist = 1;
m_soundbuffer.loadFromFile("sound/skill.wav");
m_sound.setBuffer(m_soundbuffer);
}
int GetExist(){
return m_exist;
}
void SetExist(int n){
m_exist =n;
}
void SetCount(){
m_exist = 1;
if(m_count.getElapsedTime().asMilliseconds() >= 8000){
m_sound.pause();
m_sound.play();
}
if(m_count.getElapsedTime().asMilliseconds() >= m_duration){
m_count.restart();
m_exist = 0;
}
}
int GetCount(){
return m_duration/1000 - m_count.getElapsedTime().asSeconds();
}
std::string GetType(){
return m_type;
}
};
class CWeapon{
protected:
int m_count;
CPosition m_posProjectile[5];
sf::Clock clockProjectile[5];
int m_existProjectile[5];
int m_dx[5];
int m_dy[5];
int m_durationProjectile;
std::string m_type;
sf::Texture textureProjectile;
sf::Sprite spriteProjectile;
public:
CWeapon(){
for(int i =0; i< 5; i++){
m_existProjectile[i] =0;
}
m_count =0;
}
virtual void SetTexture(int n =0)=0;
virtual void Fire(int x, int y, int arah=0)=0;
virtual void MoveProjectile()=0;
virtual void PrintProjectile(sf::RenderWindow &window)=0;
std::string GetType(){
return m_type;
}
int GetExist(){
int cek=1;
if(m_count==5 ){
for(int i=0; i<5; i++){if(m_existProjectile[i]==0){cek++;}}
}
if(cek == 6){
return 0;}
return 1;
}
void SetExist(int n){m_existProjectile[n] = 0;}
int GetExistProjectile(int i){
return m_existProjectile[i];
}
int GetCount(){
return m_count;
}
int GetProjectileX(int n){
return m_posProjectile[n].GetX();
}
int GetProjectileY(int n){
return m_posProjectile[n].GetY();
}
void Move(int i, int x, int y){
m_posProjectile[i].SetX(m_posProjectile[i].GetX()+x);
m_posProjectile[i].SetY(m_posProjectile[i].GetY()+y);
if(m_posProjectile[i].GetY()<0 || m_posProjectile[i].GetY()>29){m_existProjectile[i]=0;m_posProjectile[i].SetY(0);}
if(m_posProjectile[i].GetX()<0 || m_posProjectile[i].GetX()>29){m_existProjectile[i]=0;m_posProjectile[i].SetX(0);}
}
};
class CBomb:public CWeapon{
public:
CBomb(){
m_type = "B";
m_durationProjectile = 1000;
textureProjectile.loadFromFile("images/bomb1.png");
spriteProjectile.setTexture(textureProjectile);
spriteProjectile.setTextureRect(sf::IntRect(0,0,96,96));
}
void SetTexture(int n=0){
spriteProjectile.setTextureRect(sf::IntRect(n*96,0,96,96));
}
void Fire(int x, int y, int arah=0){
if(m_count <5){
m_posProjectile[m_count].SetX(x);
m_posProjectile[m_count].SetY(y);
m_existProjectile[m_count]=1;
m_count++;
}
}
void PrintProjectile(sf::RenderWindow &window){
for(int i=0; i< m_count; i++){
spriteProjectile.setPosition((m_posProjectile[i].GetX()-1)*32, (m_posProjectile[i].GetY()-1)*32);
if(m_existProjectile[i]<0){
if(m_existProjectile[i]<-140){SetTexture(1);}
else if(m_existProjectile[i]<-130){SetTexture(2);}
else if(m_existProjectile[i]<-120){SetTexture(3);}
else if(m_existProjectile[i]<-110){SetTexture(4);}
else if(m_existProjectile[i]<-100){SetTexture(5);}
else if(m_existProjectile[i]<-90){SetTexture(6);}
else if(m_existProjectile[i]<-80){SetTexture(7);}
else if(m_existProjectile[i]<-60){SetTexture(8);}
else if(m_existProjectile[i]<-50){SetTexture(9);}
else if(m_existProjectile[i]<-40){SetTexture(10);}
else if(m_existProjectile[i]<-30){SetTexture(11);}
else if(m_existProjectile[i]<-20){SetTexture(12);}
else if(m_existProjectile[i]<-10){SetTexture(13);}
else if(m_existProjectile[i]<0){SetTexture(14);}
m_existProjectile[i]++;
} else if(m_existProjectile[i]==1){SetTexture(0);}
if(m_existProjectile[i]!=0){window.draw(spriteProjectile);}
}
}
void MoveProjectile(){
for(int i=0; i<5; i++){
if(m_existProjectile[i]==1){
if(clockProjectile[i].getElapsedTime().asMilliseconds() >= m_durationProjectile){
m_existProjectile[i]=-140;
}
}
else{
clockProjectile[i].restart();
}
}
}
};
class CLaser:public CWeapon{
public:
CLaser(){
m_type = "L";
m_durationProjectile = 200;
textureProjectile.loadFromFile("images/laser1.png");
spriteProjectile.setTexture(textureProjectile);
}
void SetTexture(int n=0){
spriteProjectile.setTextureRect(sf::IntRect(n*32,0,32,32));
}
void PrintProjectile(sf::RenderWindow &window){
for(int i=0; i< m_count; i++){
spriteProjectile.setPosition(m_posProjectile[i].GetX()*32, m_posProjectile[i].GetY()*32);
if(m_existProjectile[i]!=0){window.draw(spriteProjectile);}
}
}
void Fire(int x, int y,int arah=0){
if(m_count <5){
m_posProjectile[m_count].SetX(x);
m_posProjectile[m_count].SetY(y);
m_existProjectile[m_count]=1;
if(arah == 0){
m_dx[m_count]=0;
m_dy[m_count]=1;
SetTexture(3);
}
else if(arah == 1){
m_dx[m_count]=-1;
m_dy[m_count]=0;
SetTexture(0);
}
else if(arah == 2){
m_dx[m_count]=1;
m_dy[m_count]=0;
SetTexture(2);
}
else if(arah == 3){
m_dx[m_count]=0;
m_dy[m_count]=-1;
SetTexture(1);
}
m_count++;
}
}
void MoveProjectile(){
for(int i=0; i< m_count ; i++){
if(m_existProjectile[i]==1){
if(clockProjectile[i].getElapsedTime().asMilliseconds()>=m_durationProjectile){
m_posProjectile[i].SetX(m_posProjectile[i].GetX()+m_dx[i]);
m_posProjectile[i].SetY(m_posProjectile[i].GetY()+m_dy[i]);
if(m_posProjectile[i].GetX() > 29 || m_posProjectile[i].GetX()<0){m_existProjectile[i] = 0;}
if(m_posProjectile[i].GetY() > 29 || m_posProjectile[i].GetY()<0){m_existProjectile[i] = 0;}
clockProjectile[i].restart();
}
}
}
}
};
class CFreeze:public CSkill{
public:
CFreeze(){
m_duration = 10000;
m_type = "F";
}
};
class CStealth:public CSkill{
public:
CStealth(){
m_duration = 10000;
m_type = "S";
}
};
class CObstacle:public CPosition{
protected:
sf::Texture textureObstacle;
sf::Sprite obstacle;
std::string m_type;
int m_length;
int m_direction;
int m_exist;
sf::Clock clockObstacle;
int m_time;
public:
CObstacle(){
m_exist = 1;
m_time = 100;
obstacle.setPosition(-1*(m_length-1)*32,0);
}
int GetExist(){
return m_exist;
}
void SetExist(int n){
if(m_exist == 0 || m_exist== 1){
m_exist = n;
}
}
void Move(){
m_x+=m_direction;
if(m_x <-2){ m_x = 29;}
if(m_type== "K"){
if(m_x >125){ m_x = 0;}
}
else if(m_x >35){ m_x = 0;}
MoveX();
clockObstacle.restart();
}
void MoveAnimation(){
int n;
n = 32/1*m_direction;
obstacle.setPosition(obstacle.getPosition().x+n,0);
}
void MoveX(){// untuk mengeset origin dari obstacle.co: kereta dari kiri berbeda dengan mobil dari kanan
int n;
if(m_direction >0){ n = -1*(m_length-1)*32;} else {n=0;}
obstacle.setPosition(m_x*32+n, 0);
}
virtual void SetTexture(int n=0)=0;
int GetDirection(){
return m_direction;
}
int GetLength(){
return m_length;
}
virtual void Print( sf::RenderWindow &window, int yy)=0;
};
class CCar:public CObstacle{
public:
CCar(){
m_length = 2;
m_direction = -1;
m_x = 29;
m_type = "O";
int random = rand()%4;
if(random == 0){textureObstacle.loadFromFile("images/car1fire.png");}
else if(random == 1){textureObstacle.loadFromFile("images/car2fire.png");}
else if(random == 2){textureObstacle.loadFromFile("images/car3fire.png");}
else if(random == 3){textureObstacle.loadFromFile("images/car4fire.png");}
SetTexture();
obstacle.setPosition(m_x*32,0);
}
void SetTexture(int n =0){
obstacle.setTexture(textureObstacle);
obstacle.setTextureRect(sf::IntRect(n*64,0,64,64));
}
void Print( sf::RenderWindow &window, int yy){
if(m_exist != 0){
if(m_exist < -162){SetTexture(1);}
else if(m_exist < -144){SetTexture(2);}
else if(m_exist < -126){SetTexture(3);}
else if(m_exist < -108){SetTexture(4);}
else if(m_exist < -90){SetTexture(5);}
else if(m_exist < -72){SetTexture(6);}
else if(m_exist < -54){SetTexture(7);}
else if(m_exist < -36){SetTexture(8);}
else if(m_exist < -18){SetTexture(9);}
else if(m_exist < 0){SetTexture(10);}
obstacle.setPosition(obstacle.getPosition().x,yy*32-36);
window.draw(obstacle);
if(m_exist<0){m_exist++;}
}
}
};
class CTurtle:public CObstacle{
public:
CTurtle(){
m_length = 2;
m_direction = -1;
m_x = 29;
m_type = "K";
textureObstacle.loadFromFile("images/kayu2.png");
SetTexture();
obstacle.setPosition(m_x*32,0);
}
void SetTexture(int n = 0){
obstacle.setTexture(textureObstacle);
}
void Print( sf::RenderWindow &window, int yy){
if(m_exist != 0){
obstacle.setPosition(obstacle.getPosition().x,yy*32-36);
window.draw(obstacle);
}
}
};
class CPalang:public CObstacle{
public:
CPalang(){
m_length = 1;
m_direction = 0;
m_type = "PA";
textureObstacle.loadFromFile("images/palang.png");
textureObstacle.setSmooth(true);
obstacle.setTexture(textureObstacle);
obstacle.setTextureRect(sf::IntRect(0,0,32,64));
}
void SetTexture(int n=0){
obstacle.setTextureRect(sf::IntRect(n*32, 0, 32, 64));
}
void Print( sf::RenderWindow &window, int yy){
if(m_exist != 0){
obstacle.setPosition(obstacle.getPosition().x,yy*32-36);
window.draw(obstacle);
if(m_exist<0){m_exist++;}
}
}
};
class CTree:public CObstacle{
public:
CTree(){
m_length = 1;
m_direction = 0;
m_type = "P";
int random= rand()%2;
if(random==0){
textureObstacle.loadFromFile("images/tree1fire.png");}
else{
textureObstacle.loadFromFile("images/tree1fire.png");
}
textureObstacle.setSmooth(true);
SetTexture();
}
void SetTexture(int n =0){
obstacle.setTexture(textureObstacle);
obstacle.setTextureRect(sf::IntRect(n*32,0,32,64));
}
void Print( sf::RenderWindow &window, int yy){
if(m_exist != 0){
if(m_exist < -150){SetTexture(1);}
else if(m_exist < -120){SetTexture(2);}
else if(m_exist < -90){SetTexture(3);}
else if(m_exist < -60){SetTexture(4);}
else if(m_exist < -30){SetTexture(5);}
else if(m_exist < 0){SetTexture(6);}
for(int i=0; i< m_length ; i++){
obstacle.setPosition(obstacle.getPosition().x,yy*32-36);
window.draw(obstacle);
}
if(m_exist<0){m_exist++;}
}
}
};
class CWood:public CObstacle{
public:
CWood(){
m_length = 3;
m_direction = 1;
m_type = "W";
m_x = 0;
textureObstacle.loadFromFile("images/kayu3.png");
textureObstacle.setSmooth(true);
SetTexture();
}
void SetTexture(int n =0){
obstacle.setTexture(textureObstacle);
}
void Print( sf::RenderWindow &window, int yy){
if(m_exist != 0){
int n= -1*(m_length-1)*32;
obstacle.setPosition(obstacle.getPosition().x,yy*32-34);
window.draw(obstacle);
if(m_exist<0){m_exist++;}
}
}
};
class CTruck:public CObstacle{
public:
CTruck(){
m_length = 4;
m_direction = 1;
m_x = 0;
m_type = "X";
textureObstacle.loadFromFile("images/truck1.png");
textureObstacle.setSmooth(true);
obstacle.setTexture(textureObstacle);
SetTexture();
}
void SetTexture(int n=0){
obstacle.setTextureRect(sf::IntRect(0,n*64, 128, 64));
}
void Print( sf::RenderWindow &window, int yy){
if(m_exist != 0){
if(m_exist < -162){SetTexture(1);}
else if(m_exist < -144){SetTexture(2);}
else if(m_exist < -126){SetTexture(3);}
else if(m_exist < -108){SetTexture(4);}
else if(m_exist < -90){SetTexture(5);}
else if(m_exist < -72){SetTexture(6);}
else if(m_exist < -54){SetTexture(7);}
else if(m_exist < -36){SetTexture(8);}
else if(m_exist < -18){SetTexture(9);}
else if(m_exist < 0){SetTexture(10);}
obstacle.setPosition(obstacle.getPosition().x,yy*32-36);
window.draw(obstacle);
if(m_exist<0){m_exist++;}
}
}
};
class CTrain :public CObstacle{
public:
CTrain(){
m_length = 13;
m_direction = 2;
m_x = 0;
m_type = "K";
textureObstacle.loadFromFile("images/train1.png");
textureObstacle.setSmooth(true);
obstacle.setTexture(textureObstacle);
SetTexture();
}
void SetTexture(int n=0){
obstacle.setTextureRect(sf::IntRect(0,n*64, 416, 64));
}
void Print( sf::RenderWindow &window, int yy){
if(m_exist != 0){
if(m_exist < -162){SetTexture(1);}
else if(m_exist < -144){SetTexture(2);}
else if(m_exist < -126){SetTexture(3);}
else if(m_exist < -108){SetTexture(4);}
else if(m_exist < -90){SetTexture(5);}
else if(m_exist < -72){SetTexture(6);}
else if(m_exist < -54){SetTexture(7);}
else if(m_exist < -36){SetTexture(8);}
else if(m_exist < -18){SetTexture(9);}
else if(m_exist < 0){SetTexture(10);}
obstacle.setPosition(obstacle.getPosition().x,yy*32-36);
window.draw(obstacle);
if(m_exist<0){m_exist++;}
}
}
};
class CRoad:public CPosition{
protected:
CObstacle* m_obstacle[6];
int m_n;
int m_count;
sf::Sprite road;
sf::Texture textureRoad;
std::string m_type;
public:
void Print(sf::RenderWindow &window){
for(int i=0; i<30; i++){
road.setPosition(i*32, m_y*32);
window.draw(road);
}
}
std::string GetType(){return m_type;};
virtual void SetExistObstacle(int x)=0;
virtual int CekCrash(int x)=0;
virtual void CekCount(int n)=0;
void MoveObstacle(){
for(int i=0; i< m_n; i++){m_obstacle[i]->Move();}
}
void MoveObstacleAnimation(){
for(int i=0; i< m_n; i++){m_obstacle[i]->MoveAnimation();}
}
void PrintObstacle(sf::RenderWindow &window){
for(int i=m_n-1; i>=0; i--){m_obstacle[i]->Print(window, m_y);}
}
int GetDirection(){
return m_obstacle[0]->GetDirection();}
void SetY(){
m_y =m_y+1;
if(m_y>29){m_y=0;}
for(int i=0; i< m_n ; i++){
m_obstacle[i]->SetY(m_y);
}
}
};
class CRel:public CRoad{
public:
CRel(int n){
m_y =n;
m_type = "R";
m_n = 0;
m_count = rand()%50;
textureRoad.loadFromFile("images/rail.png");
road.setTexture(textureRoad);
m_obstacle[0] = new CPalang;
m_obstacle[0]->SetY(n);
m_obstacle[0]->SetX(15);
m_n++;
}
int CekCrash(int x){
if(m_n == 2){
if(m_obstacle[1]->GetExist()!= 0){
for(int j=0; j<m_obstacle[1]->GetLength(); j++){
if(x == m_obstacle[1]->GetX()-j){
return 0;
}
}
}
}
return 1;
}
void SetExistObstacle(int x){
m_obstacle[1]->SetExist(-180);
}
void CekCount(int y){
if(m_count == 0){
m_obstacle[1] = new CTrain;
m_obstacle[1]->SetY(y);
m_n++;
}
if(m_n == 2){
if(m_obstacle[1]->GetX()-m_obstacle[1]->GetLength()>16 || m_obstacle[1]->GetExist()==0){
m_obstacle[0]->SetTexture(0);
} else{
m_obstacle[0]->SetTexture(1);
}
}
m_count--;
}
};
class CJalan:public CRoad{
public:
CJalan(int n){
m_y =n;
m_type = " ";
m_n = 0;
m_count = rand()%8 +5;
textureRoad.loadFromFile("images/road3.png");
road.setTexture(textureRoad);
}
void SetExistObstacle(int x){
for(int i=0; i<m_n; i++){
for(int j=0; j<m_obstacle[i]->GetLength(); j++){
if(x==m_obstacle[i]->GetX()-(j*m_obstacle[i]->GetDirection()/abs(m_obstacle[i]->GetDirection()))){
m_obstacle[i]->SetExist(-180);
}
}
}
}
int CekCrash(int x){
for(int i=0; i<m_n; i++){
if(m_obstacle[i]->GetExist()!=0){
for(int j=0; j<m_obstacle[i]->GetLength(); j++){
if(x==m_obstacle[i]->GetX()-(j*m_obstacle[i]->GetDirection()/abs(m_obstacle[i]->GetDirection()))){
return 0;
}
}
}
}
return 1;
}
void CekCount(int n){
if(m_n < 6 && n%2 ==0){
if(m_count == 0){
m_count = rand()%2 + 5;
m_obstacle[m_n] = new CCar;
m_obstacle[m_n]->SetY(n);
m_n++;
}
m_count--;
}
else if(m_n<3 && n%2 == 1){
if(m_count == 0){
m_count = rand()%5 + 10;
m_obstacle[m_n] = new CTruck;
m_obstacle[m_n]->SetY(n);
m_n++;
}
m_count--;
}
}
};
class CSungai:public CRoad{
public:
CSungai(int n){
m_y =n;
m_type = "S";
m_n = 0;
m_count = rand()%2 +4;
textureRoad.loadFromFile("images/water.png");
road.setTexture(textureRoad);
}
void SetExistObstacle(int x){;}
void CekCount(int n){
if(m_n < 6){
if(m_count == 0){
m_count = rand()%2 + 5;
if(n%2==1){
m_obstacle[m_n] = new CWood;
}
else{
m_obstacle[m_n] = new CTurtle;
}
m_obstacle[m_n]->SetY(n);
m_n++;
}
m_count--;
}
}
int CekCrash(int x){
for(int i=0; i<m_n; i++){
for(int j=0; j<m_obstacle[i]->GetLength(); j++){
if(x==m_obstacle[i]->GetX()-(j*m_obstacle[i]->GetDirection()/abs(m_obstacle[i]->GetDirection()))){
return 1;
}
}
}
return 0;
}
};
class CTanah:public CRoad{
public:
CTanah(int n, int y=0){
m_y =n;
m_type = "T";
m_n =0;
textureRoad.loadFromFile("images/grass3.png");
textureRoad.setSmooth(true);
road.setTexture(textureRoad);
if(y == 0){
for(int i=0; i< 6; i++){
m_obstacle[i]= new CTree;
m_obstacle[i]->SetY(m_y);
m_obstacle[i]->SetX(rand()%4 + i*5);
m_n++;
}
}
else{
for(int i=0; i< 6; i++){
m_obstacle[i]= new CTree;
m_obstacle[i]->SetY(m_y);
if(i==3){
m_obstacle[i]->SetX(rand()%3 + i*5+1);}
else{
m_obstacle[i]->SetX(rand()%4 + i*5);
}
m_n++;
}
}
}
void CekCount(int n){
}
int CekCrash(int x){
for(int i=0; i<m_n; i++){
if(m_obstacle[i]->GetExist()!=0){
for(int j=0; j<m_obstacle[i]->GetLength(); j++){
if(x==m_obstacle[i]->GetX()+j){
return 0;
}
}
}
}
return 1;
}
void SetExistObstacle(int x){
for(int i=0; i<m_n; i++){
for(int j=0; j<m_obstacle[i]->GetLength(); j++){
if(x==m_obstacle[i]->GetX()+j){
m_obstacle[i]->SetExist(-180);
}
}
}
}
};
class CTerror: public CPosition{
sf::Texture texture;
sf::Sprite player;
CSkill* m_skill[1];
CWeapon* m_weapon[1];
CPosition m_pos;
int m_skillCek;
int m_weaponCek;
int max_y, min_y;
sf::SoundBuffer bufferLaser;
sf::SoundBuffer bufferBomb;
sf::SoundBuffer bufferJump;
sf::SoundBuffer bufferPower;
sf::SoundBuffer bufferWater;
sf::Sound soundWater;
sf::Sound soundJump;
sf::Sound soundBomb;
sf::Sound soundLaser;
sf::Sound soundPower;
int m_exist;
public:
CTerror(){
m_x = 15;
m_y = 22;
m_exist = 1;
m_pos.SetX(0);
m_pos.SetY(0);
texture.loadFromFile("images/frogger.png");
texture.setSmooth(true);
player.setTexture(texture);
player.setTextureRect(sf::IntRect(0,0, 32, 32));
player.setPosition(m_x*32, m_y*32-4);
min_y = 22;
max_y = 30;
m_skillCek= 0;
m_weaponCek = 0;
bufferPower.loadFromFile("sound/power.wav");
bufferLaser.loadFromFile("sound/laser.wav");
bufferJump.loadFromFile("sound/jump.wav");
bufferBomb.loadFromFile("sound/bomb.wav");
bufferWater.loadFromFile("sound/water.wav");
soundWater.setBuffer(bufferWater);
soundJump.setBuffer(bufferJump);
soundPower.setBuffer(bufferPower);
soundLaser.setBuffer(bufferLaser);
soundBomb.setBuffer(bufferBomb);
}
void SetImage(int k=0){
if(k==0){
texture.loadFromFile("images/terror1.png");
player.setTexture(texture);
player.setTextureRect(sf::IntRect(0, 0, 32, 32));
player.setPosition(player.getPosition().x, player.getPosition().y +4);
soundWater.play();
}
else {
texture.loadFromFile("images/terrorfire.png");
player.setTexture(texture);
m_exist = -180;
player.setPosition(player.getPosition().x, player.getPosition().y-32 +4);
}
}
void SetTexture(int k= 0){
player.setTextureRect(sf::IntRect(k*32, 0, 32, 64));
}
void MoveX(){
m_pos.SetX(m_pos.GetX()+1);
if(m_pos.GetX()>2){m_pos.SetX(0);}
}
void MoveRight(){
m_pos.SetY(2);
}
void MoveLeft(){
m_pos.SetY(1);
}
void MoveUp(){
m_pos.SetY(3);
//soundJump.play();
}
void MoveDown(){
m_pos.SetY(0);
}
void SetMinY(int pos=200){
if(pos!=200){
max_y = 24+ceil(pos/32.0);
min_y = ceil(pos/32.0);}
else{
max_y = 30;
min_y = 22;
}
}
void Move(int dx, int dy){
m_x+=dx;
m_y+=dy;
if(m_x<0){m_x=0;}
if(m_x>29){m_x=29;}
if(m_y < min_y){m_y = min_y;}
if(m_y > max_y){m_y = max_y;}
player.setTextureRect(sf::IntRect(m_pos.GetX()*32, m_pos.GetY()*32, 32,32));
player.setPosition(m_x*32, m_y*32-4);
}
void Print(sf::RenderWindow &window){
if(m_exist<0){
if(m_exist<-150){SetTexture(0);}
else if(m_exist<-120){SetTexture(1);}
else if(m_exist<-90){SetTexture(2);}
else if(m_exist<-60){SetTexture(3);}
else if(m_exist<-30){SetTexture(4);}
else if(m_exist<0){SetTexture(5);}
m_exist++;
}
window.draw(player);
}
void SetSkill(std::string skill){
if(skill == "F"){
m_skill[0] = new CFreeze;
}
else if(skill == "S"){
m_skill[0] = new CStealth;
}
soundPower.play();
m_skillCek = 1;
if(m_skill[0]->GetType()=="S"){player.setColor(sf::Color(255,255,255,150));}
}
void SetWeapon(std::string weapon){
if(weapon == "B"){
m_weapon[0] = new CBomb;
}
else if(weapon == "L"){
m_weapon[0] = new CLaser;
}
soundPower.play();
m_weaponCek = 1;
}
void SetSkillCount(){
m_skill[0]->SetCount();
m_skillCek = m_skill[0]->GetExist();
if(m_skillCek ==0){player.setColor(sf::Color(255,255,255,255));}
}
void SetWeaponCount(){
m_weapon[0]->MoveProjectile();
m_weaponCek = m_weapon[0]->GetExist();
}
int GetSkillCount(){
return m_skillCek;}
int GetWeaponCount(){
return m_weaponCek;}
std::string GetSkillType(){
return m_skill[0]->GetType();
}
std::string GetWeaponType(){
return m_weapon[0]->GetType();
}
void Fire(){
if(m_weapon[0]->GetType()=="L"){soundLaser.play();}
else{soundBomb.play();}
m_weapon[0]->Fire(m_x, m_y, m_pos.GetY());
}
int GetProjectileCount(){
return m_weapon[0]->GetCount();
}
int GetSisaCount(){
return m_skill[0]->GetCount();
}
int GetProjectileX(int n){
return m_weapon[0]->GetProjectileX(n);
}
int GetProjectileY(int n){
return m_weapon[0]->GetProjectileY(n);
}
int GetExistProjectile(int n){
return m_weapon[0]->GetExistProjectile(n);
}
void MoveProjectile(int i, int x, int y){
m_weapon[0]->Move(i, x, y);
}
void SetExistProjectile(int n){
m_weapon[0]->SetExist(n);
}
void PrintProjectile(sf::RenderWindow &window){
if(m_weaponCek==1){
m_weapon[0]->PrintProjectile(window);}
}
};
class CMap{
CRoad* m_road[30];
CPowerup powerup[2];
sf::SoundBuffer bufferDanger;
sf::Sound soundDanger;
int m_cekDanger;
int m_y[30];
public:
CMap(){
for(int i=18; i< 30; i++){
m_road[i]= new CTanah(i,1);
m_y[i] = i;
}
for(int i=0; i<18; i++){
int randomRoad= rand()%4;
if(randomRoad==0){m_road[i] = new CSungai(i);}
if(randomRoad==1){m_road[i] = new CTanah(i);}
if(randomRoad==2){m_road[i] = new CJalan(i);}
if(randomRoad==3){m_road[i] = new CRel(i);}
m_y[i]=i;
}
powerup[0].SetExist(0);
powerup[1].SetExist(0);
m_cekDanger = 0;
bufferDanger.loadFromFile("sound/danger.wav");
soundDanger.setBuffer(bufferDanger);
}
int GetCekDanger(){
return m_cekDanger;
}
void SetCekDanger(int n=0){
m_cekDanger = n;
soundDanger.play();
}
void SetSkill(){
for(int i=5;i<=15;i++){
if(GetType(i) == "T"){
int cek = 0;
while(cek==0){
int randX = rand()%30;
if(CekCrash(randX,i) != 0){
int random = rand()%2;
if(random == 0){
powerup[0].SetUp(0,randX,i);//Freeze
}
else{
powerup[0].SetUp(1,randX,i);//Stealth;
}
i = 15;
cek = 1;
}
}
}
}
}
void SetWeapon(){
for(int i=15;i>=5;i--){
if(GetType(i) == "T"){
int cek = 0;
while(cek==0){
int randX = rand()%30;
if(CekCrash(randX,i) != 0){
int random = rand()%2;
if(random == 0){
powerup[1].SetUp(2,randX,i);//Bomb
}
else{
powerup[1].SetUp(3,randX,i);//Laser;
}
i = 1;
cek = 1;
}
}
}
}
}
void Print(sf::RenderWindow &window){
for(int i=0; i<30; i++){m_road[i]->Print(window);}
}
void PrintPowerup(sf::RenderWindow &window,int skill, int weapon){
if(powerup[0].GetExist()==1 && skill == 0){powerup[0].Print(window);}
if(powerup[1].GetExist()==1 && weapon == 0){powerup[1].Print(window);}
}
void Move(){
int temp = m_y[29];
for(int i = 0; i<30;i++){
m_road[i]->SetY();
if(i==29){
m_y[29-i]= temp;}
else {
m_y[29-i]=m_y[28-i];}
}
delete m_road[m_y[0]];
int randomRoad= rand()%4;
if(randomRoad==0){m_road[m_y[0]] = new CSungai(0);}
if(randomRoad==1){m_road[m_y[0]] = new CTanah(0);}
if(randomRoad==2){m_road[m_y[0]] = new CJalan(0);}
if(randomRoad==3){m_road[m_y[0]] = new CRel(0);}
if(powerup[0].GetExist()==1){powerup[0].Move();}
if(powerup[1].GetExist()==1){powerup[1].Move();}
if(powerup[0].GetY()>29){powerup[0].SetExist(0);}
if(powerup[1].GetY()>29){powerup[1].SetExist(0);}
}
void MoveObstacle(){
for(int i=0; i<30; i++){
m_road[i]->MoveObstacle();
m_road[i]->CekCount(i);
}
}
void MoveObstacleAnimation(){
for(int i=0; i<30; i++){
m_road[i]->MoveObstacleAnimation();
}
}
void PrintObstacle(sf::RenderWindow &window){
for(int i=0; i<30; i++){if(m_road[i]->GetType()=="S"){m_road[i]->PrintObstacle(window);}}
}
void PrintObstacle2(sf::RenderWindow &window){
for(int i=0; i<30; i++){if(m_road[i]->GetType()!="S"){m_road[i]->PrintObstacle(window);}}
}
std::string GetType(int y){
return m_road[m_y[y]]->GetType();
}
int GetDirection(int y){
return m_road[m_y[y]]->GetDirection();
}
int CekCrash(int x, int y){
return m_road[m_y[y]]->CekCrash(x);
}
void SetExistSkill(int n){
powerup[0].SetExist(n);
}
void SetExistWeapon(int n){
powerup[1].SetExist(n);
}
void Update(){
if(powerup[0].GetExist() == 0){
SetSkill();
}
if(powerup[1].GetExist() == 0){
SetWeapon();
}
}
int CekCrashSkill(int x,int y){
if(x == powerup[0].GetX() && y == powerup[0].GetY()){
return 1;
}
return 0;
}
int CekCrashWeapon(int x,int y){
if(x == powerup[1].GetX() && y == powerup[1].GetY()){
return 1;
}
return 0;
}
std::string GetSkillTipe(){
return powerup[0].GetType();
}
std::string GetWeaponTipe(){
return powerup[1].GetType();
}
void SetExistObstacle(int y, int x){
m_road[m_y[y]]->SetExistObstacle(x);
}
};
|
6bb847f5c90e3c707d3ac1082c1aadf5433bcd0e
|
17d3f222917ce864a77cf9a65ebaf69fb3076852
|
/MassSim/Source.cpp
|
b0d44ec2f8da8137da696aed41ea8fd4486ade3d
|
[] |
no_license
|
Satori32/MassSimulator
|
534f0ce4630b186370c30198b29822f6ac3371cb
|
5781d2fbc4bd352987a16f028c25644ac4524b9d
|
refs/heads/master
| 2020-08-27T06:27:08.715362
| 2019-10-24T10:09:33
| 2019-10-24T10:09:33
| 217,269,719
| 0
| 0
| null | null | null | null |
SHIFT_JIS
|
C++
| false
| false
| 2,162
|
cpp
|
Source.cpp
|
#include <iostream>
#include <cstdint>
#include <random>
#include "MassSim.h"
#include <conio.h>
//https://ja.wikipedia.org/wiki/ใฉใคใใฒใผใ
//ใใฅใฆใชใณใฐๅฎๅ
จใใน๏ผ
int GetKey() {
int k = 0;
if (_kbhit()) {
k = _getch();
}
return k;
}
namespace Cell {
enum {
//Zero=0,
Empty,
Die,
Live,
Full,
};
}
template<class T>
bool Show(const MassSimulator<T>& MS) {
for (std::size_t i = 0; i < MS.Height(); i++) {
for (std::size_t j = 0; j < MS.Width(); j++) {
const T& M = MS.Index(j, i);
if (M == Cell::Empty) std::cout << ' ';
if (M == Cell::Die) std::cout << 'D';
if (M == Cell::Live) std::cout << '*';
}
std::cout << std::endl;
}
return true;
}
template<class T>
MassSimulator<T> MakeProblem(std::size_t W, std::size_t H, unsigned int S = 0) {
std::mt19937 mt(S);
std::uniform_int_distribution<> ui(Cell::Empty, Cell::Full - 1);
MassSimulator<T> R(W, H);
for (std::size_t Y = 0; Y < R.Height(); Y++) {
for (std::size_t X = 0; X < R.Width(); X++) {
R.Set(X, Y, ui(mt));
}
}
return R;
}
int main() {
std::random_device rd;
MassSimulator<char> MS= MakeProblem<char>(80,22,rd());
auto F = [](auto& MS, auto& M, std::intmax_t X, std::intmax_t Y) {//life game logix.
std::uintmax_t L = 0;
std::uintmax_t D = 0;
for (std::intmax_t i = Y - 1; i < Y + 2; i++) {
if (i == MS.Height()) { continue; }
if (i < 0) { continue; }
for (std::intmax_t j = X - 1; j < X + 2; j++) {
if (j == MS.Width()) { continue; }
if (j < 0) { continue; }
if (j == X && i==Y) { continue; }
if (MS.Index(j, i) == Cell::Live) { L++; }
if (MS.Index(j, i) == Cell::Die) { D++; }
}
}
if (MS.Index(X, Y) == Cell::Die && L == 3) { M = Cell::Live; }
else if (MS.Index(X, Y) == Cell::Die) { M = Cell::Empty; }
if (MS.Index(X, Y) == Cell::Live && (L == 3||L==2)) { M = Cell::Live; }
if (MS.Index(X, Y) == Cell::Live && L <=1) { M = Cell::Die; }
if (MS.Index(X, Y) == Cell::Live && L >=4) { M = Cell::Die; }
return true;
};
while (!GetKey()){
//_getch();
MS.UpDate(F);
system("cls");
Show(MS);
std::cout << "Hit Any key to end!"<<std::endl;
}
}
|
55fe4c208edae145e1ab027639702ba36bba0c8a
|
28dba754ddf8211d754dd4a6b0704bbedb2bd373
|
/AtCoder/AtCoder Beginner Contest 280/D.cpp
|
759d1571cc0c75534c585a66f7a8806d31667a71
|
[] |
no_license
|
zjsxzy/algo
|
599354679bd72ef20c724bb50b42fce65ceab76f
|
a84494969952f981bfdc38003f7269e5c80a142e
|
refs/heads/master
| 2023-08-31T17:00:53.393421
| 2023-08-19T14:20:31
| 2023-08-19T14:20:31
| 10,140,040
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 741
|
cpp
|
D.cpp
|
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
LL calc(LL x, LL cnt) {
LL i = 0;
while (cnt > 0) {
i += x;
LL y = i;
while (y % x == 0) {
y /= x;
cnt--;
}
}
return i;
}
void solve() {
LL K;
cin >> K;
LL res = 1;
for (LL x = 2; x * x <= K; x++) {
LL tot = 0;
while (K % x == 0) {
K /= x;
tot++;
}
// cout << x << ' ' << tot << ' ' << calc(x, tot) << endl;
res = max(res, calc(x, tot));
}
res = max(res, K);
cout << res << endl;
}
int main() {
int ts = 1;
// cin >> ts;
for (int t = 1; t <= ts; t++) {
solve();
}
return 0;
}
|
ad71ce13525795be9c3cd7406008d8b3c78e444e
|
a97a07b3a33e7a4adccee497b7a60f0a62299009
|
/EXP0505.1/EXP0505.1/EXP0505.1View.cpp
|
470821faf2720ac38b65c04f7fe31053c6f665b1
|
[] |
no_license
|
jiangliman/JLM
|
9330bb5e6eece3f1927c779b5c886a0ca45be8ed
|
2c74369a396a5c5ceb908c14734246dbf6cd5f1c
|
refs/heads/master
| 2021-03-26T08:35:44.973069
| 2020-06-24T13:24:56
| 2020-06-24T13:24:56
| 247,681,314
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 2,703
|
cpp
|
EXP0505.1View.cpp
|
// EXP0505.1View.cpp : CEXP05051View ็ฑป็ๅฎ็ฐ
//
#include "stdafx.h"
// SHARED_HANDLERS ๅฏไปฅๅจๅฎ็ฐ้ข่งใ็ผฉ็ฅๅพๅๆ็ดข็ญ้ๅจๅฅๆ็
// ATL ้กน็ฎไธญ่ฟ่กๅฎไน๏ผๅนถๅ
่ฎธไธ่ฏฅ้กน็ฎๅ
ฑไบซๆๆกฃไปฃ็ ใ
#ifndef SHARED_HANDLERS
#include "EXP0505.1.h"
#endif
#include "EXP0505.1Set.h"
#include "EXP0505.1Doc.h"
#include "EXP0505.1View.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CEXP05051View
IMPLEMENT_DYNCREATE(CEXP05051View, CRecordView)
BEGIN_MESSAGE_MAP(CEXP05051View, CRecordView)
ON_EN_CHANGE(IDC_EDIT2, &CEXP05051View::OnEnChangeEdit2)
END_MESSAGE_MAP()
// CEXP05051View ๆ้ /ๆๆ
CEXP05051View::CEXP05051View()
: CRecordView(IDD_EXP05051_FORM)
, Name(_T(""))
, Sex(_T(""))
, StuNum(_T(""))
, Old(_T(""))
, Phone(_T(""))
, PicWay(_T(""))
{
m_pSet = NULL;
// TODO: ๅจๆญคๅคๆทปๅ ๆ้ ไปฃ็
}
CEXP05051View::~CEXP05051View()
{
}
void CEXP05051View::DoDataExchange(CDataExchange* pDX)
{
CRecordView::DoDataExchange(pDX);
// ๅฏไปฅๅจๆญคๅคๆๅ
ฅ DDX_Field* ๅฝๆฐไปฅๅฐๆงไปถโ่ฟๆฅโๅฐๆฐๆฎๅบๅญๆฎต๏ผไพๅฆ
// DDX_FieldText(pDX, IDC_MYEDITBOX, m_pSet->m_szColumn1, m_pSet);
// DDX_FieldCheck(pDX, IDC_MYCHECKBOX, m_pSet->m_bColumn2, m_pSet);
// ๆๅ
ณ่ฏฆ็ปไฟกๆฏ๏ผ่ฏทๅ้
MSDN ๅ ODBC ็คบไพ
DDX_Text(pDX, IDC_EDIT1, m_pSet->column1);
DDX_Text(pDX, IDC_EDIT2, m_pSet->column2);
DDX_Text(pDX, IDC_EDIT3, m_pSet->column3);
DDX_Text(pDX, IDC_EDIT5, m_pSet->column4);
DDX_Text(pDX, IDC_EDIT6, m_pSet->column5);
DDX_Text(pDX, IDC_EDIT4, m_pSet->column6);
}
BOOL CEXP05051View::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: ๅจๆญคๅค้่ฟไฟฎๆน
// CREATESTRUCT cs ๆฅไฟฎๆน็ชๅฃ็ฑปๆๆ ทๅผ
return CRecordView::PreCreateWindow(cs);
}
void CEXP05051View::OnInitialUpdate()
{
m_pSet = &GetDocument()->m_EXP05051Set;
CRecordView::OnInitialUpdate();
}
// CEXP05051View ่ฏๆญ
#ifdef _DEBUG
void CEXP05051View::AssertValid() const
{
CRecordView::AssertValid();
}
void CEXP05051View::Dump(CDumpContext& dc) const
{
CRecordView::Dump(dc);
}
CEXP05051Doc* CEXP05051View::GetDocument() const // ้่ฐ่ฏ็ๆฌๆฏๅ
่็
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CEXP05051Doc)));
return (CEXP05051Doc*)m_pDocument;
}
#endif //_DEBUG
// CEXP05051View ๆฐๆฎๅบๆฏๆ
CRecordset* CEXP05051View::OnGetRecordset()
{
return m_pSet;
}
// CEXP05051View ๆถๆฏๅค็็จๅบ
void CEXP05051View::OnEnChangeEdit2()
{
// TODO: ๅฆๆ่ฏฅๆงไปถๆฏ RICHEDIT ๆงไปถ๏ผๅฎๅฐไธ
// ๅ้ๆญค้็ฅ๏ผ้ค้้ๅ CRecordView::OnInitDialog()
// ๅฝๆฐๅนถ่ฐ็จ CRichEditCtrl().SetEventMask()๏ผ
// ๅๆถๅฐ ENM_CHANGE ๆ ๅฟโๆโ่ฟ็ฎๅฐๆฉ็ ไธญใ
// TODO: ๅจๆญคๆทปๅ ๆงไปถ้็ฅๅค็็จๅบไปฃ็
}
|
f0d7bdafc1dfa13be8a38a19cb8f9b308a03b8be
|
4dea6aae9b107b7fd812d3b4422741f1c0744ad2
|
/Taller1_laberinto/ListaEnlazada.h
|
86e27c21bce2381e0b6b08f376c6a6309058d623
|
[] |
no_license
|
jpstorm21/Proyectos-java-cplusplus
|
7b92747bc03595e5fd2ae0d7c92ccd774488e8ee
|
dd8ff3e2ba0628791c94725df034f1f8409b4ead
|
refs/heads/master
| 2020-12-13T11:36:01.129236
| 2020-01-16T20:05:40
| 2020-01-16T20:05:40
| 234,401,774
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 779
|
h
|
ListaEnlazada.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: ListaEnlazada.h
* Author: Juan Pablo Martinez
*
* Created on 17 de abril de 2019, 0:26
*/
#ifndef LISTAENLAZADA_H
#define LISTAENLAZADA_H
#include "Nodo.h"
class ListaEnlazada {
public:
ListaEnlazada();
Nodo* getPrimero();
void setPrimero(Nodo* primero);
Nodo* getUltimo();
void setUltimo(Nodo*);
void insertarNodo(int posX, int posY);
Nodo* buscarNodo(int posX, int posY);
void imprimir();
virtual ~ListaEnlazada();
private:
Nodo* primero;
Nodo* ultimo;
};
#endif /* LISTAENLAZADA_H */
|
f8fb9420561028703b9adeba28e538c16c94f715
|
5118e5c4260f988cf0a78b83ba3dc48e842408e2
|
/lib/chessAI/HumanChessPlayer.h
|
d1e206151e2cd9d15a0b3ca44a503e11eeb705cd
|
[] |
no_license
|
Teezious/chessAI
|
94776374bc753ab100e908fd373986f4ad2c609b
|
5fea3e56219c5335a14478ed22c25f4895b0299d
|
refs/heads/master
| 2023-08-14T12:32:01.846590
| 2021-07-05T19:37:24
| 2021-07-05T19:37:24
| 353,499,062
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 399
|
h
|
HumanChessPlayer.h
|
#ifndef CHESSAI_HUMANCHESSPLAYER_H
#define CHESSAI_HUMANCHESSPLAYER_H
#include "AbstractChessPlayer.h"
#include "thc.h"
#include <iostream>
class HumanChessPlayer final : public AbstractChessPlayer
{
public:
HumanChessPlayer(bool isWhite) : AbstractChessPlayer(isWhite){};
std::string chooseMove(thc::ChessRules board, bool printResults = true);
};
#endif // CHESSAI_HUMANCHESSPLAYER_H
|
08f5505bc6d0b4a84e7c948705f6d0f11a9b6e19
|
25ab7b537e5e6e13866461956f50d55555157dd3
|
/Problem Solving/Algorithms/Strings/Anagram.cpp
|
5a16927d593005399421a641f03413aff1ceba61
|
[] |
no_license
|
weirdrag08/HackerRank
|
23522ddd837a060d46e57cfd7fcca9c9fab220c8
|
8d510de21980eb00cb458f0cd782dbabe4b96010
|
refs/heads/master
| 2023-07-03T19:52:51.361244
| 2021-08-14T17:02:29
| 2021-08-14T17:02:29
| 356,377,172
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,319
|
cpp
|
Anagram.cpp
|
#include<iostream>
#include<unordered_map>
#include<list>
#include<vector>
#include<stack>
#include<queue>
#include<algorithm>
#include<climits>
#include<string>
#include<utility>
using namespace std;
#define mp make_pair
#define INFI 10e8
#define INF 10e7
typedef pair<int, int> pi;
typedef vector<int> vi;
typedef vector<bool> vb;
typedef long long ll;
int main(){
std::ios_base::sync_with_stdio(false);
cin.tie(NULL);
int tc;
cin >> tc;
for(int k = 0; k < tc; k++){
unordered_map<char, int> s1_chars, s2_chars;
string s;
cin >> s;
int match_diff = 0;
bool match = true;
if (s.size() % 2 != 0)
{
match = false;
cout << "-1" << '\n';
continue;
}
for (int i = 0, j = (s.size() / 2); i < (s.size() / 2); i++, j++)
{
s1_chars[s[i]] += 1;
s2_chars[s[j]] += 1;
}
for (auto character : s2_chars)
{
if (s1_chars.count(character.first) == 0 || s2_chars[character.first] > s1_chars[character.first])
{
match_diff += s2_chars[character.first] - s1_chars[character.first];
}
}
cout << match_diff << '\n';
}
}
|
b55bcf0f2a029e7c5f1083e733b03f0d37001d95
|
82dc3cc4c97c05e384812cc9aa07938e2dbfe24b
|
/development/src/elements/meshfree_grad_plast/mfgp_mat_interfaces/MFGPSolidMatListT.cpp
|
6233ad43833963c54258c9abfb7573af83b00c38
|
[
"BSD-3-Clause"
] |
permissive
|
samanseifi/Tahoe
|
ab40da0f8d952491943924034fa73ee5ecb2fecd
|
542de50ba43645f19ce4b106ac8118c4333a3f25
|
refs/heads/master
| 2020-04-05T20:24:36.487197
| 2017-12-02T17:09:11
| 2017-12-02T17:24:23
| 38,074,546
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 750
|
cpp
|
MFGPSolidMatListT.cpp
|
/* $Id: MFGPSolidMatListT.cpp,v 1.1 2005/04/26 22:27:01 kyonten Exp $ */
#include "MFGPSolidMatListT.h"
#ifdef __DEVELOPMENT__
#include "DevelopmentMaterialsConfig.h"
#include "DevelopmentElementsConfig.h"
#endif
#include "MFGPMaterialT.h"
#include "MFGPMatSupportT.h"
using namespace Tahoe;
/* constructors */
MFGPSolidMatListT::MFGPSolidMatListT(int length, const MFGPMatSupportT& support):
MFGPMatListT(length),
fHasLocalizers(false),
fMFGPMatSupport(&support)
{
#ifdef __NO_RTTI__
cout << "\n MFGPSolidMatListT::MFGPSolidMatListT: WARNING: environment has no RTTI. Some\n"
<< " consistency checking is disabled" << endl;
#endif
}
MFGPSolidMatListT::MFGPSolidMatListT(void):
fHasLocalizers(false),
fMFGPMatSupport(NULL)
{
}
|
1b2f5c4eb1337f18efb954777913a881f7394acb
|
e9c02bb0df7ad3a928cf7c97b8294451eaa8dbc8
|
/graph-source-code/508-D/9606060.cpp
|
27f24f1af0f975cbfeda2343237f746f54c002c7
|
[
"MIT"
] |
permissive
|
AmrARaouf/algorithm-detection
|
b157a534545fa8920bbe94e7307d4b937a74aa60
|
59f3028d2298804870b32729415d71eec6116557
|
refs/heads/master
| 2021-01-13T14:37:04.074339
| 2015-12-06T21:14:31
| 2015-12-06T21:14:31
| 45,905,817
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,778
|
cpp
|
9606060.cpp
|
//Language: GNU C++
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <cstring>
#include <fstream>
#include <ctime>
#define LL long long
#define ULL unsigned long long
#define FOR(i,a,b) for(int i=a;i<=b;i++)
#define FO(i,a,b) for(int i=a;i<b;i++)
#define FORD(i,a,b) for(int i=a;i>=b;i--)
#define FOD(i,a,b) for(int i=a;i>b;i--)
#define FORV(i,a) for(typeof(a.begin()) i = a.begin(); i != a.end(); i++)
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define debug cout << "YES" << endl
using namespace std;
typedef pair<int,int>II;
typedef pair<int,II>PII;
template<class T> T gcd(T a, T b) {T r; while(b!=0) {r=a%b;a=b;b=r;} return a;}
template<class T> T lcm(T a, T b) { return a / gcd(a, b) * b; }
template<class T> int getbit(T s, int i) { return (s >> i) & 1; }
template<class T> T onbit(T s, int i) { return s | (T(1) << i); }
template<class T> T offbit(T s, int i) { return s & (~(T(1) << i)); }
const double PI = 2*acos(0.0);
const double eps = 1e-9;
const int infi = 1e9;
const LL Linfi = (LL) 1e18;
const LL MOD = 1000000007;
#define maxn 200005
/**
bridges are the last edgees you want to cross
only two odd edges
*/
int n, m;
string s[maxn];
int in[maxn], out[maxn], xet[maxn];
vector<int> adj[maxn];
int encode(char a){
if(a >= 'a' && a <= 'z') return a - 'a';
if(a >= 'A' && a <= 'Z') return a - 'A' + 26;
if(a >= '0' && a <= '9') return a - '0' + 52;
}
int encode2(char a, char b){
return encode(a) * 62 + encode(b);
}
char decode(int u){
if(u < 26) return 'a' + u;
else if(u < 52) return 'A' + (u-26);
else return '0' + (u-52);
}
string decode2(int u){
string ans = "";
char x = decode(u/62);
char y = decode(u%62); //cout << x << " " << y << endl;
ans += x; ans += y;
return ans;
}
void solve(){
n = 62*62;
int st = -1, c1 = 0, c2 = 0;
FOR(i,0,n){
if(in[i] == out[i]) continue;
else if(in[i] > out[i] + 1){
cout << "NO" << endl; return;
}
else if(out[i] > in[i] + 1){
cout << "NO" << endl; return;
}
else if(in[i] == out[i]+1){
c2++;
}
else if(out[i] == in[i]+1){
c1++;
st = i;
}
}
//cout << c1 << " " << c2 << endl;
if(c1 > 1 || c2 > 1){ cout << "NO" << endl; return; }
if(c1 != c2) { cout << "NO" << endl; return;} /// Euler path or Euler cycle
/// Euler cycle case
if(st == -1){
FOR(i,0,n){
if(out[i] > 0) {
st = i;
break;
}
}
}
vector<int> res;
stack<int> S;
S.push(st);
while(!S.empty()){
int u = S.top();
if(adj[u].empty()){
res.pb(u);
S.pop();
}
else{
S.push(adj[u].back());
adj[u].pop_back();
}
}
if(res.size() != m+1){
cout << "NO" << endl; return;
}
reverse(res.begin(), res.end());
cout << "YES" << endl;
cout << decode2(res[0]);
FO(i,1,res.size()){
cout << decode(res[i]%62);
}
cout << endl;
}
int main(){
ios::sync_with_stdio(false);
#ifndef ONLINE_JUDGE
freopen("test.in","r",stdin);
//freopen("test.out","w",stdout);
#endif
cin >> m;
FOR(i,1,m){
cin >> s[i];
int u = encode2(s[i][0], s[i][1]);
int v = encode2(s[i][1], s[i][2]);
adj[u].pb(v);
out[u]++; in[v]++;
}
solve();
return 0;
}
|
d29f3e8e5749003f218e3130d933656ceada7716
|
e70fa41c9d64a6e359dac1a02141ad97006e9ad6
|
/features/mahjong/Tile.cpp
|
c79757b8f89a2d9cf516682648bb2f88dfdd30e2
|
[] |
no_license
|
OGStudio/ogs-mahjong-components
|
5c793512fe55a2be5496c92798ece0f623fe8538
|
db6891fc97cb66c9854c911886dcce3cc4e38cb0
|
refs/heads/master
| 2020-03-24T10:57:28.298641
| 2018-10-23T07:56:09
| 2018-10-23T07:56:09
| 142,672,012
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 196
|
cpp
|
Tile.cpp
|
FEATURE mahjong.h/Impl
struct Tile
{
Tile() : matchId(0) { }
// NOTE Try not to use id since it's an external representation.
//int id;
int matchId;
TilePosition position;
};
|
b8de382085c18705855c806446406406f9d674e7
|
2c85ecc5079da4dc286ee3e8440e7e59efe4ef78
|
/fof.cpp
|
91cd3ea90213b037ee6a3ae870b4680b662b0778
|
[] |
no_license
|
deerishi/algorithms
|
7f744644e47203d792216f3287d73167baeae858
|
8f113bb50cb0313a81835320edd5c9ef523dd7af
|
refs/heads/master
| 2021-07-18T23:29:35.088631
| 2017-10-26T23:32:54
| 2017-10-26T23:32:54
| 29,521,515
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,063
|
cpp
|
fof.cpp
|
#include "bits/stdc++.h"
using namespace std;
#define dgetc() getc_unlocked(stdin);
#define dputc(ch) putc_unlocked(ch,stdout);
#define blank putc_unlocked('\n',stdout);
typedef long long int ll;
char TEMP[1<<10],CH;
int getInt()
{
CH=getc_unlocked(stdin);
while(CH<'-') CH=dgetc();
int n=0,sign=1;
if(CH=='-')
{
sign=-1;CH=dgetc();
}
while(isdigit(CH))
{
n=n*10+CH-'0';
CH=dgetc();
}
return n*sign;
}
void printn(int n)
{
//cout<<"n is "<<n<<"\n";
int sign=1;
char *ptr=TEMP+ 30;
*ptr--='\0';
if(n<0)
{
sign=-1;
n*=-1;
}
while(n>0)
{
*ptr--=n%10+'0';
n/=10;
//cout<<"*ptr is "<<*ptr+1<<"\n";
}
if(sign==-1)
{
*ptr--='-';
}
ptr++;
while(*ptr!='\0')
{
dputc(*ptr++);
}
}
int main()
{
int n,m,temp,i;
ll id_bobf,id_fof;
set<ll> s1;
n=getInt();
temp=n;
while(temp--)
{
scanf("%lld",&id_bobf);
s1.insert(id_bobf);
m=getInt();
for(i=0;i<m;i++)
{
scanf("%lld",&id_fof);
s1.insert(id_fof);
}
}
//cout<<"size is "<<s1.size()<<"\n";
printn(s1.size()-n);
blank;
return 0;
}
|
e79729b7af1859b6c91a5beba8efd92eb45bbf60
|
5412ba2aa236587748bd6839379392b2380c1013
|
/Plugins/Wwise/Intermediate/Build/Win64/UE4Editor/Inc/AkAudio/AkWwiseTree.gen.cpp
|
0b5f8c152b24053ccbd39fc6084e77ddb0724233
|
[] |
no_license
|
Phodonut/FinalDemo
|
0e47d49bc4e84e2141e70423c7d3effb54a50115
|
63e21e3634fba43edd0a337058681b4caac9ed1b
|
refs/heads/master
| 2020-03-20T08:32:07.218750
| 2018-06-14T05:38:48
| 2018-06-14T05:38:48
| 137,311,446
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 12,574
|
cpp
|
AkWwiseTree.gen.cpp
|
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "GeneratedCppIncludes.h"
#include "Public/AkAudioDevice.h"
#include "Classes/AkWaapiUMG/Components/AkWwiseTree.h"
PRAGMA_DISABLE_OPTIMIZATION
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable : 4883)
#endif
PRAGMA_DISABLE_DEPRECATION_WARNINGS
void EmptyLinkFunctionForGeneratedCodeAkWwiseTree() {}
// Cross Module References
AKAUDIO_API UFunction* Z_Construct_UDelegateFunction_AkAudio_OnItemDragDetected__DelegateSignature();
UPackage* Z_Construct_UPackage__Script_AkAudio();
COREUOBJECT_API UScriptStruct* Z_Construct_UScriptStruct_FGuid();
AKAUDIO_API UFunction* Z_Construct_UDelegateFunction_AkAudio_OnItemSelectionChanged__DelegateSignature();
AKAUDIO_API UFunction* Z_Construct_UFunction_UAkWwiseTree_GetSearchText();
AKAUDIO_API UClass* Z_Construct_UClass_UAkWwiseTree();
AKAUDIO_API UFunction* Z_Construct_UFunction_UAkWwiseTree_GetSelectedItem();
AKAUDIO_API UScriptStruct* Z_Construct_UScriptStruct_FAkWwiseObjectDetails();
AKAUDIO_API UFunction* Z_Construct_UFunction_UAkWwiseTree_SetSearchText();
AKAUDIO_API UClass* Z_Construct_UClass_UAkWwiseTree_NoRegister();
UMG_API UClass* Z_Construct_UClass_UWidget();
// End Cross Module References
UFunction* Z_Construct_UDelegateFunction_AkAudio_OnItemDragDetected__DelegateSignature()
{
struct _Script_AkAudio_eventOnItemDragDetected_Parms
{
FGuid ItemDraggedID;
FString ItemDraggedName;
};
UObject* Outer = Z_Construct_UPackage__Script_AkAudio();
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("OnItemDragDetected__DelegateSignature"), RF_Public|RF_Transient|RF_MarkAsNative) UDelegateFunction(FObjectInitializer(), nullptr, (EFunctionFlags)0x00130000, 65535, sizeof(_Script_AkAudio_eventOnItemDragDetected_Parms));
UProperty* NewProp_ItemDraggedName = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("ItemDraggedName"), RF_Public|RF_Transient|RF_MarkAsNative) UStrProperty(CPP_PROPERTY_BASE(ItemDraggedName, _Script_AkAudio_eventOnItemDragDetected_Parms), 0x0010000000000080);
UProperty* NewProp_ItemDraggedID = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("ItemDraggedID"), RF_Public|RF_Transient|RF_MarkAsNative) UStructProperty(CPP_PROPERTY_BASE(ItemDraggedID, _Script_AkAudio_eventOnItemDragDetected_Parms), 0x0010000000000080, Z_Construct_UScriptStruct_FGuid());
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Classes/AkWaapiUMG/Components/AkWwiseTree.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("A delegate type invoked when an item is being dragged."));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UDelegateFunction_AkAudio_OnItemSelectionChanged__DelegateSignature()
{
struct _Script_AkAudio_eventOnItemSelectionChanged_Parms
{
FGuid ItemSelectedID;
};
UObject* Outer = Z_Construct_UPackage__Script_AkAudio();
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("OnItemSelectionChanged__DelegateSignature"), RF_Public|RF_Transient|RF_MarkAsNative) UDelegateFunction(FObjectInitializer(), nullptr, (EFunctionFlags)0x00130000, 65535, sizeof(_Script_AkAudio_eventOnItemSelectionChanged_Parms));
UProperty* NewProp_ItemSelectedID = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("ItemSelectedID"), RF_Public|RF_Transient|RF_MarkAsNative) UStructProperty(CPP_PROPERTY_BASE(ItemSelectedID, _Script_AkAudio_eventOnItemSelectionChanged_Parms), 0x0010000000000080, Z_Construct_UScriptStruct_FGuid());
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Classes/AkWaapiUMG/Components/AkWwiseTree.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("A delegate type invoked when a selection changes somewhere."));
#endif
}
return ReturnFunction;
}
void UAkWwiseTree::StaticRegisterNativesUAkWwiseTree()
{
UClass* Class = UAkWwiseTree::StaticClass();
static const TNameNativePtrPair<ANSICHAR> AnsiFuncs[] = {
{ "GetSearchText", (Native)&UAkWwiseTree::execGetSearchText },
{ "GetSelectedItem", (Native)&UAkWwiseTree::execGetSelectedItem },
{ "SetSearchText", (Native)&UAkWwiseTree::execSetSearchText },
};
FNativeFunctionRegistrar::RegisterFunctions(Class, AnsiFuncs, ARRAY_COUNT(AnsiFuncs));
}
UFunction* Z_Construct_UFunction_UAkWwiseTree_GetSearchText()
{
struct AkWwiseTree_eventGetSearchText_Parms
{
FString ReturnValue;
};
UObject* Outer = Z_Construct_UClass_UAkWwiseTree();
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("GetSearchText"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), nullptr, (EFunctionFlags)0x54020409, 65535, sizeof(AkWwiseTree_eventGetSearchText_Parms));
UProperty* NewProp_ReturnValue = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("ReturnValue"), RF_Public|RF_Transient|RF_MarkAsNative) UStrProperty(CPP_PROPERTY_BASE(ReturnValue, AkWwiseTree_eventGetSearchText_Parms), 0x0010000000000580);
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Audiokinetic"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Classes/AkWaapiUMG/Components/AkWwiseTree.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("returns the current text of the searchBox"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UAkWwiseTree_GetSelectedItem()
{
struct AkWwiseTree_eventGetSelectedItem_Parms
{
FAkWwiseObjectDetails ReturnValue;
};
UObject* Outer = Z_Construct_UClass_UAkWwiseTree();
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("GetSelectedItem"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), nullptr, (EFunctionFlags)0x54020409, 65535, sizeof(AkWwiseTree_eventGetSelectedItem_Parms));
UProperty* NewProp_ReturnValue = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("ReturnValue"), RF_Public|RF_Transient|RF_MarkAsNative) UStructProperty(CPP_PROPERTY_BASE(ReturnValue, AkWwiseTree_eventGetSelectedItem_Parms), 0x0010000000000580, Z_Construct_UScriptStruct_FAkWwiseObjectDetails());
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Audiokinetic"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Classes/AkWaapiUMG/Components/AkWwiseTree.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Returns all properties currently selected in the Wwise properties list"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UAkWwiseTree_SetSearchText()
{
struct AkWwiseTree_eventSetSearchText_Parms
{
FString newText;
};
UObject* Outer = Z_Construct_UClass_UAkWwiseTree();
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("SetSearchText"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), nullptr, (EFunctionFlags)0x04020409, 65535, sizeof(AkWwiseTree_eventSetSearchText_Parms));
UProperty* NewProp_newText = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("newText"), RF_Public|RF_Transient|RF_MarkAsNative) UStrProperty(CPP_PROPERTY_BASE(newText, AkWwiseTree_eventSetSearchText_Parms), 0x0010000000000080);
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Audiokinetic"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Classes/AkWaapiUMG/Components/AkWwiseTree.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("sets the current text of the searchBox"));
MetaData->SetValue(NewProp_newText, TEXT("NativeConst"), TEXT(""));
#endif
}
return ReturnFunction;
}
UClass* Z_Construct_UClass_UAkWwiseTree_NoRegister()
{
return UAkWwiseTree::StaticClass();
}
UClass* Z_Construct_UClass_UAkWwiseTree()
{
static UClass* OuterClass = NULL;
if (!OuterClass)
{
Z_Construct_UClass_UWidget();
Z_Construct_UPackage__Script_AkAudio();
OuterClass = UAkWwiseTree::StaticClass();
if (!(OuterClass->ClassFlags & CLASS_Constructed))
{
UObjectForceRegistration(OuterClass);
OuterClass->ClassFlags |= (EClassFlags)0x20B00082u;
OuterClass->LinkChild(Z_Construct_UFunction_UAkWwiseTree_GetSearchText());
OuterClass->LinkChild(Z_Construct_UFunction_UAkWwiseTree_GetSelectedItem());
OuterClass->LinkChild(Z_Construct_UFunction_UAkWwiseTree_SetSearchText());
UProperty* NewProp_OnItemDragged = new(EC_InternalUseOnlyConstructor, OuterClass, TEXT("OnItemDragged"), RF_Public|RF_Transient|RF_MarkAsNative) UMulticastDelegateProperty(CPP_PROPERTY_BASE(OnItemDragged, UAkWwiseTree), 0x0010000010080000, Z_Construct_UDelegateFunction_AkAudio_OnItemDragDetected__DelegateSignature());
UProperty* NewProp_OnSelectionChanged = new(EC_InternalUseOnlyConstructor, OuterClass, TEXT("OnSelectionChanged"), RF_Public|RF_Transient|RF_MarkAsNative) UMulticastDelegateProperty(CPP_PROPERTY_BASE(OnSelectionChanged, UAkWwiseTree), 0x0010000010080000, Z_Construct_UDelegateFunction_AkAudio_OnItemSelectionChanged__DelegateSignature());
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UAkWwiseTree_GetSearchText(), "GetSearchText"); // 3625642210
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UAkWwiseTree_GetSelectedItem(), "GetSelectedItem"); // 1499404221
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UAkWwiseTree_SetSearchText(), "SetSearchText"); // 3949960022
OuterClass->ClassConfigName = FName(TEXT("Editor"));
static TCppClassTypeInfo<TCppClassTypeTraits<UAkWwiseTree> > StaticCppClassTypeInfo;
OuterClass->SetCppTypeInfo(&StaticCppClassTypeInfo);
OuterClass->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = OuterClass->GetOutermost()->GetMetaData();
MetaData->SetValue(OuterClass, TEXT("IncludePath"), TEXT("AkWaapiUMG/Components/AkWwiseTree.h"));
MetaData->SetValue(OuterClass, TEXT("ModuleRelativePath"), TEXT("Classes/AkWaapiUMG/Components/AkWwiseTree.h"));
MetaData->SetValue(OuterClass, TEXT("ToolTip"), TEXT("A widget that shows the Wwise tree items."));
MetaData->SetValue(NewProp_OnItemDragged, TEXT("Category"), TEXT("Widget Event"));
MetaData->SetValue(NewProp_OnItemDragged, TEXT("ModuleRelativePath"), TEXT("Classes/AkWaapiUMG/Components/AkWwiseTree.h"));
MetaData->SetValue(NewProp_OnItemDragged, TEXT("ToolTip"), TEXT("Called when an item is dragged from the wwise tree."));
MetaData->SetValue(NewProp_OnSelectionChanged, TEXT("Category"), TEXT("Widget Event"));
MetaData->SetValue(NewProp_OnSelectionChanged, TEXT("ModuleRelativePath"), TEXT("Classes/AkWaapiUMG/Components/AkWwiseTree.h"));
MetaData->SetValue(NewProp_OnSelectionChanged, TEXT("ToolTip"), TEXT("Called when the item selection changes."));
#endif
}
}
check(OuterClass->GetClass());
return OuterClass;
}
IMPLEMENT_CLASS(UAkWwiseTree, 2148176994);
static FCompiledInDefer Z_CompiledInDefer_UClass_UAkWwiseTree(Z_Construct_UClass_UAkWwiseTree, &UAkWwiseTree::StaticClass, TEXT("/Script/AkAudio"), TEXT("UAkWwiseTree"), false, nullptr, nullptr, nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(UAkWwiseTree);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#ifdef _MSC_VER
#pragma warning (pop)
#endif
PRAGMA_ENABLE_OPTIMIZATION
|
95cf01d5eb599619575526017e2a742e5f0f38a8
|
b78246c3257dfd3d8df620062a2e12234e2189d0
|
/src/h264_bitstream_parser.h
|
0f36740e832dc248ef739759dc9da265a6f692f1
|
[
"BSD-3-Clause"
] |
permissive
|
kevleyski/h264nal
|
0a465f08d9e4533bd0de9f4c5bbef29d0a689db6
|
c38d1a5588c96fb8a3bc72ba525fb68e863c3dd8
|
refs/heads/master
| 2023-08-28T16:15:46.417258
| 2021-10-08T23:42:44
| 2021-10-08T23:42:51
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,174
|
h
|
h264_bitstream_parser.h
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*/
#pragma once
#include <stdio.h>
#include <memory>
#include <vector>
#include "h264_bitstream_parser_state.h"
#include "h264_nal_unit_parser.h"
#include "rtc_base/bit_buffer.h"
namespace h264nal {
// A class for parsing out an H264 Bitstream.
class H264BitstreamParser {
public:
// The parsed state of the bitstream (a list of parsed NAL units plus
// the accumulated PPS/SPS state).
struct BitstreamState {
BitstreamState() = default;
~BitstreamState() = default;
// disable copy ctor, move ctor, and copy&move assignments
BitstreamState(const BitstreamState&) = delete;
BitstreamState(BitstreamState&&) = delete;
BitstreamState& operator=(const BitstreamState&) = delete;
BitstreamState& operator=(BitstreamState&&) = delete;
#ifdef FDUMP_DEFINE
void fdump(FILE* outfp, int indent_level) const;
#endif // FDUMP_DEFINE
bool add_offset;
bool add_length;
bool add_parsed_length;
bool add_checksum;
// NAL units
std::vector<std::unique_ptr<struct H264NalUnitParser::NalUnitState>>
nal_units;
};
// Unpack RBSP and parse bitstream state from the supplied buffer.
static std::unique_ptr<BitstreamState> ParseBitstream(
const uint8_t* data, size_t length,
H264BitstreamParserState* bitstream_parser_state,
bool add_checksum) noexcept;
// Unpack RBSP and parse bitstream (internal state)
static std::unique_ptr<BitstreamState> ParseBitstream(
const uint8_t* data, size_t length, bool add_offset, bool add_length,
bool add_parsed_length, bool add_checksum) noexcept;
struct NaluIndex {
// Start index of NALU, including start sequence.
size_t start_offset;
// Start index of NALU payload, typically type header.
size_t payload_start_offset;
// Length of NALU payload, in bytes, counting from payload_start_offset.
size_t payload_size;
};
// Returns a vector of the NALU indices in the given buffer.
static std::vector<NaluIndex> FindNaluIndices(const uint8_t* data,
size_t length) noexcept;
};
} // namespace h264nal
|
0f440eb6d80aeee63257b70bb4d0796dc9f76c2b
|
6b2a8dd202fdce77c971c412717e305e1caaac51
|
/solutions_5706278382862336_1/C++/Boping/A.cpp
|
cdf2f43fbad69bb2a086cc4074fb6de0db6a3654
|
[] |
no_license
|
alexandraback/datacollection
|
0bc67a9ace00abbc843f4912562f3a064992e0e9
|
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
|
refs/heads/master
| 2021-01-24T18:27:24.417992
| 2017-05-23T09:23:38
| 2017-05-23T09:23:38
| 84,313,442
| 2
| 4
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 551
|
cpp
|
A.cpp
|
#include <cstdio>
int main() {
FILE * fin = fopen("A.in", "r"), * fout = fopen("A.out", "w");
int T, t, g;
long long P, Q, p, q, r;
fscanf(fin, "%d", &T);
for (t = 1; t <= T; ++t) {
fscanf(fin, "%lld/%lld", &P, &Q);
p = P;
q = Q;
while (r = q % p) {
q = p;
p = r;
}
P /= p;
Q /= p;
g = 1;
while (!(Q & 1)) {
Q /= 2;
if (P < Q) {
++g;
}
}
if (Q != 1) {
fprintf(fout, "Case #%d: impossible\n", t);
} else {
fprintf(fout, "Case #%d: %d\n", t, g);
}
}
return 0;
}
|
4f33c0a68b7fbae92932de20045f7ab4f03b0062
|
a7109719291d3fb1e3dabfed9405d2b340ad8a89
|
/Gandhi-Prototype/lib/cBullet.cpp
|
711b37caa25ca5e59efd43e5eb54de23718dd6dc
|
[] |
no_license
|
edufg88/gandhi-prototype
|
0ea3c6a7bbe72b6d382fa76f23c40b4a0280c666
|
947f2c6d8a63421664eb5018d5d01b8da71f46a2
|
refs/heads/master
| 2021-01-01T17:32:40.791045
| 2011-12-19T20:10:34
| 2011-12-19T20:10:34
| 32,288,341
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,207
|
cpp
|
cBullet.cpp
|
#include "cBullet.h"
#include "cGame.h"
#define _USE_MATH_DEFINES
#include <math.h>
cBullet::cBullet( int type, int x, int y, int vx, int vy )
{
this->type = type;
this->x = x;
this->y = y;
this->vx = vx;
this->vy = vy;
Scene = cGame::GetInstance()->GetScene();
angle = atan2(float(vy),float(vx));
angle += (float) M_PI_2;
}
cBullet::~cBullet( void )
{
}
bool cBullet::Move()
{
x += vx;
y += vy;
return Scene->map[(y+BULLET_HEIGHT/2)/TILE_WIDTH][(x+BULLET_WIDTH/2)/TILE_WIDTH].walkable;
}
void cBullet::GetRect( RECT *rc,int *posx,int *posy,cScene *Scene,float *ang )
{
*posx = SCENE_Xo + x - (Scene->camx);
*posy = SCENE_Yo + y - (Scene->camy);
*ang = angle;
switch (type)
{
case BULL_1:
SetRect(rc,576,192,640,256);
break;
case BULL_2:
SetRect(rc,640,192,704,256);
break;
case BULL_3:
SetRect(rc,704,192,768,256);
break;
}
}
void cBullet::GetWorldRect( RECT *rc )
{
SetRect(rc, x, y, x + BULLET_WIDTH, y + BULLET_HEIGHT);
}
int cBullet::GetDamage()
{
return bull_dam[type];
}
void cBullet::GetCell( int *cellx,int *celly )
{
*cellx = x/TILE_WIDTH;
*celly = y/TILE_WIDTH;
}
|
345f155357cc659056ccb4a9529dbfa6a34bcbfa
|
520375019b721b2b1a1eb5cc65665c3998bfbd60
|
/test/print_random.cpp
|
96bf3604947e9d4fdd2e276a2ad36b7830b18916
|
[] |
no_license
|
DavidPeicho/algorep
|
e5624bec7d092f8ec8dc8190a70bf092cbd2de32
|
f673e567aa4e3bcb922ae0e62a51af9387981b61
|
refs/heads/master
| 2021-05-06T01:49:09.733877
| 2017-12-21T21:41:56
| 2017-12-21T21:42:10
| 114,470,672
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,223
|
cpp
|
print_random.cpp
|
#include "utils/utils.h"
void
run()
{
auto* allocator = algorep::Allocator::instance();
constexpr unsigned int NB_TESTS = 100;
auto int_comp = [](auto a, auto b) { return a == b; };
auto float_comp = [](auto a, auto b) {
constexpr float EPSILON = 0.0001;
return a >= b - EPSILON && a <= b + EPSILON;
};
unsigned int nb_total_tests = NB_TESTS * 4;
unsigned int tests_passed = 0;
// Launches `NB_TEST' tests on int values.
for (unsigned i = 0; i < NB_TESTS; ++i)
tests_passed += check<int>(*allocator, int_comp);
// Launches `NB_TEST' tests on float values.
for (unsigned i = 0; i < NB_TESTS; ++i)
tests_passed += check<float>(*allocator, float_comp);
// Launches `NB_TEST' tests on double values.
for (unsigned i = 0; i < NB_TESTS; ++i)
tests_passed += check<double>(*allocator, float_comp);
// Launches `NB_TEST' tests on size_t values.
for (unsigned i = 0; i < NB_TESTS; ++i)
tests_passed += check<size_t>(*allocator, int_comp);
algorep::finalize();
summary(tests_passed, nb_total_tests, "> Print random <");
}
int
main(int argc, char** argv)
{
algorep::init(argc, argv);
const auto& callback = std::function<void()>(run);
algorep::run(callback);
}
|
ee7844f95ff83159391b90804ee8b3d927e9f015
|
a501bd3088465eb5dfaff08cc1b5cc7a26877dd0
|
/SDR/ExternalTools/hydra/hydra-0.4/click-piggyback/click-hydra-1.5.0/tags/conext/package/hydratosocket.cc
|
c9db879b8fae1560841062dcf9c4ca33828bff1b
|
[] |
no_license
|
Zheng0825/SDR
|
4ae1a73cf326e2765cdd4706720ad84bcf11c1ff
|
0886a149d063ea48bc2261c268108d7d32793df8
|
refs/heads/master
| 2021-01-12T05:52:14.750890
| 2016-09-07T00:51:23
| 2016-09-07T00:51:23
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,909
|
cc
|
hydratosocket.cc
|
// -*- mode: c++; c-basic-offset: 2 -*-
/*
* tosocket.{cc,hh} -- element write data to socket
* Mark Huang <mlhuang@cs.princeton.edu>
*
* Copyright (c) 2004 The Trustees of Princeton University (Trustees).
*
* 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, subject to the conditions
* listed in the Click LICENSE file. These conditions include: you must
* preserve this copyright notice, and you cannot mention the copyright
* holders in advertising related to the Software without their permission.
* The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This
* notice is a summary of the Click LICENSE file; the license in that file is
* legally binding.
*/
#include <click/config.h>
#include <click/error.hh>
#include <click/confparse.hh>
#include <click/glue.hh>
#include <click/standard/scheduleinfo.hh>
#include <click/packet_anno.hh>
#include <click/packet.hh>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <arpa/inet.h>
#include <netinet/tcp.h>
#include <fcntl.h>
#include "hydratosocket.hh"
#include <click/timer.hh>
CLICK_DECLS
HydraToSocket::HydraToSocket()
: _task(this), _verbose(false), _fd(-1), _active(-1),
_snaplen(2048), _nodelay(1), _frame(true)
{
}
HydraToSocket::~HydraToSocket()
{
}
/*
void
HydraToSocket::notify_noutputs(int n)
{
set_noutputs(n <= 1 ? n : 1);
}
*/
int
HydraToSocket::configure(Vector<String> &conf, ErrorHandler *errh)
{
String socktype;
if (cp_va_parse(conf, this, errh,
cpString, "type of socket (`TCP' or `UDP' or `UNIX')", &socktype,
cpIgnoreRest,
cpEnd) < 0)
return -1;
socktype = socktype.upper();
// remove keyword arguments
if (cp_va_parse_remove_keywords(conf, 2, this, errh,
"VERBOSE", cpBool, "be verbose?", &_verbose,
"SNAPLEN", cpUnsigned, "maximum packet length", &_snaplen,
"NODELAY", cpUnsigned, "disable Nagle algorithm?", &_nodelay,
"FRAME", cpBool, "frame packets?", &_frame,
cpEnd) < 0)
return -1;
if (socktype == "TCP" || socktype == "UDP") {
_family = PF_INET;
_socktype = socktype == "TCP" ? SOCK_STREAM : SOCK_DGRAM;
_protocol = socktype == "TCP" ? IPPROTO_TCP : IPPROTO_UDP;
if (cp_va_parse(conf, this, errh,
cpIgnore,
cpIPAddress, "IP address", &_ip,
cpUnsignedShort, "port number", &_port,
cpEnd) < 0)
return -1;
}
else if (socktype == "UNIX") {
_family = PF_UNIX;
_socktype = SOCK_STREAM;
_protocol = 0;
if (cp_va_parse(conf, this, errh,
cpIgnore,
cpString, "filename", &_pathname,
cpEnd) < 0)
return -1;
if (_pathname.length() >= (int)sizeof(((struct sockaddr_un *)0)->sun_path))
return errh->error("filename too long");
}
else
return errh->error("unknown socket type `%s'", socktype.c_str());
return 0;
}
int
HydraToSocket::initialize_socket_error(ErrorHandler *errh, const char *syscall)
{
int e = errno; // preserve errno
if (_fd >= 0) {
close(_fd);
_fd = -1;
}
return errh->error("%s: %s", syscall, strerror(e));
}
int
HydraToSocket::initialize(ErrorHandler *errh)
{
// open socket, set options, bind to address
_fd = socket(_family, _socktype, _protocol);
if (_fd < 0)
return initialize_socket_error(errh, "socket");
if (_family == PF_INET) {
sa.in.sin_family = _family;
sa.in.sin_port = htons(_port);
sa.in.sin_addr = _ip.in_addr();
sa_len = sizeof(sa.in);
}
else {
sa.un.sun_family = _family;
strcpy(sa.un.sun_path, _pathname.c_str());
sa_len = sizeof(sa.un.sun_family) + _pathname.length();
}
#ifdef SO_SNDBUF
// set transmit buffer size
if (setsockopt(_fd, SOL_SOCKET, SO_SNDBUF, &_snaplen, sizeof(_snaplen)) < 0)
return initialize_socket_error(errh, "setsockopt");
#endif
#ifdef TCP_NODELAY
// disable Nagle algorithm
if (_protocol == IPPROTO_TCP && _nodelay)
if (setsockopt(_fd, IP_PROTO_TCP, TCP_NODELAY, &_nodelay, sizeof(_nodelay)) < 0)
return initialize_socket_error(errh, "setsockopt");
#endif
if (_protocol == IPPROTO_TCP && !_ip) {
// bind to port
if (bind(_fd, (struct sockaddr *)&sa, sa_len) < 0)
return initialize_socket_error(errh, "bind");
// start listening
if (_socktype == SOCK_STREAM)
if (listen(_fd, 0) < 0)
return initialize_socket_error(errh, "listen");
add_select(_fd, SELECT_READ);
}
else {
// connect
if (_socktype == SOCK_STREAM)
if (connect(_fd, (struct sockaddr *)&sa, sa_len) < 0)
return initialize_socket_error(errh, "connect");
_active = _fd;
}
if (input_is_pull(0)) {
ScheduleInfo::join_scheduler(this, &_task, errh);
_signal = Notifier::upstream_empty_signal(this, 0, &_task);
}
return 0;
}
void
HydraToSocket::cleanup(CleanupStage)
{
if (_active >= 0 && _active != _fd) {
close(_active);
_active = -1;
}
if (_fd >= 0) {
// shut down the listening socket in case we forked
#ifdef SHUT_RDWR
shutdown(_fd, SHUT_RDWR);
#else
shutdown(_fd, 2);
#endif
close(_fd);
_fd = -1;
}
}
void
HydraToSocket::selected(int fd)
{
int new_fd = accept(fd, (struct sockaddr *)&sa, &sa_len);
if (new_fd < 0) {
if (errno != EAGAIN)
click_chatter("%s: accept: %s", declaration().c_str(), strerror(errno));
return;
}
if (_verbose) {
if (_family == PF_INET)
click_chatter("%s: opened connection %d from %s.%d", declaration().c_str(), new_fd, IPAddress(sa.in.sin_addr).unparse().c_str(), ntohs(sa.in.sin_port));
else
click_chatter("%s: opened connection %d", declaration().c_str(), new_fd);
}
_active = new_fd;
}
void
HydraToSocket::send_packet(Packet *p)
{
int w = 0;
if (_frame) {
p->push(sizeof(uint32_t));
*(uint32_t *)p->data() = htonl(p->length());
}
while (p->length()) {
w = sendto(_active, p->data(), p->length(), 0, (const struct sockaddr*)&sa, sa_len);
if (w < 0 && errno != EINTR)
{
click_chatter("HydraToSocket: send failed\n");
break;
}
p->pull(w);
//click_chatter("HydraToSocket: send success\n");
}
if (w < 0) {
click_chatter("HydraToSocket: sendto: %s", strerror(errno));
checked_output_push(0, p);
}
else
p->kill();
}
void
HydraToSocket::push(int, Packet *p)
{
send_packet(p);
}
bool
HydraToSocket::run_task()
{
// XXX reduce tickets when idle
//timeval debug_tv;
//click_gettimeofday(&debug_tv);
//click_chatter("HydraToSocket: pulling %d.%06d", debug_tv.tv_sec, debug_tv.tv_usec );
Packet *p = input(0).pull();
if (p)
send_packet(p);
else if (!_signal)
return false;
_task.fast_reschedule();
return p != 0;
}
void
HydraToSocket::add_handlers()
{
if (input_is_pull(0))
add_task_handlers(&_task);
}
CLICK_ENDDECLS
ELEMENT_REQUIRES(userlevel)
EXPORT_ELEMENT(HydraToSocket)
|
d027a32171e269cb75b3ed79529c7d99e7d7d6d8
|
41f1a2cee03ed88ae5cec450e16050c6d46aa21d
|
/ALNSv2/roulette_wheel.h
|
3ac9f5b4beb5ade944570b676716076a96f2304d
|
[] |
no_license
|
ManuelFreytag/VRPLDTT
|
8ff3cf606e04a97e8062260d7fbda4eaeda85268
|
b9c1b5644a4ee78b27f112336c7c04ac4ea3040d
|
refs/heads/master
| 2022-12-20T06:50:06.500140
| 2020-10-13T19:29:06
| 2020-10-13T19:29:06
| 303,801,626
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,159
|
h
|
roulette_wheel.h
|
#pragma once
#include <vector>
#include <queue>
#include <functional>
class RouletteWheel {
public:
// wheel parameters
double wheel_parameter; // impact of historic results
int memory_length; // Number of iterations considered
double min_weight;
// Adaptive components
int nr_functors;
int last_functor_id;
std::vector<double> weights; // size functors
std::vector<double> scores; // size of functors
std::vector<int> nr_uses; // size of functors
// initialize
RouletteWheel() {};
RouletteWheel(int nr_functors, double wheel_par, int memory_length, double min_weight)
{
this->wheel_parameter = wheel_par;
this->memory_length = memory_length;
this->min_weight = min_weight;
this->nr_functors = nr_functors;
this->weights = std::vector<double>(nr_functors, (1.0/nr_functors));
this->scores = std::vector<double>(nr_functors, 0);
this->nr_uses = std::vector<int>(nr_functors, 0);
};
// match strings to functor objects (simpler)
int get_random_functor_id();
void update_stats(double new_score);
void update_weights();
};
class DestroyRouletteWheel : public RouletteWheel {
private:
std::vector<std::function<std::vector<int>()>> destroy_functors;
public:
DestroyRouletteWheel() {};
DestroyRouletteWheel(std::vector<std::function<std::vector<int>()>> destroy_functors, double wheel_par, int memory_length, double min_weight) :
RouletteWheel(destroy_functors.size(), wheel_par, memory_length, min_weight)
{
this->destroy_functors = destroy_functors;
}
std::function<std::vector<int>()>& get_random_operator();
};
class InsertionRouletteWheel : public RouletteWheel {
private:
std::vector<std::function<void(std::vector<int>)>> repair_functors;
public:
InsertionRouletteWheel() {};
InsertionRouletteWheel(std::vector<std::function<void(std::vector<int>)>> repair_functors, double wheel_par, int memory_length, double min_weight)
: RouletteWheel(repair_functors.size(), wheel_par, memory_length, min_weight)
{
this->repair_functors = repair_functors;
}
std::function<void(std::vector<int>)>& get_random_operator();
};
|
3ee5e003c4ad93162b42648fded8ccdc33986701
|
adb90eb41008543cb7e01e832bd49659d2ab6b14
|
/GoFish/card_demo.cpp
|
598d4dc281fb02bc3ade6f4bcf4c312d11b31919
|
[] |
no_license
|
cmkauff/GoFishRepo
|
716fd793d7148a93f6a103d8e9c32553adf0d29d
|
386c08b51d9fbb5a9e773523e2ab2b5e822006d5
|
refs/heads/master
| 2020-05-05T00:52:51.065319
| 2019-04-12T01:47:39
| 2019-04-12T01:47:39
| 179,586,775
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,918
|
cpp
|
card_demo.cpp
|
// FILE: card_demo.cpp
// This is a small demonstration program showing how the Card and Deck classes are used.
#include <iostream> // Provides cout and cin
#include <cstdlib> // Provides EXIT_SUCCESS
#include "card.h"
#include "player.h"
#include "deck.h"
#include <fstream>
using namespace std;
// PROTOTYPES for functions used by this demonstration program:
void dealHand(Deck &d, Player &p, int numCards);
void emptyHand(Deck &d, Player &p);
void goFish(Deck &d, Player &p);
int main( )
{
ofstream myfile;
myfile.open("gofish_results.txt");
int numCards = 7;
Player p1("Kate");
Player p2("Glenn");
Deck d; //create a deck of cards
d.shuffle();
dealHand(d, p1, numCards);
dealHand(d, p2, numCards);
cout << p1.getName() <<" has : " << p1.showHand() << endl;
cout << p2.getName() <<" has : " << p2.showHand() << endl;
myfile << p1.getName() <<" has : " << p1.showHand() << endl;
myfile << p2.getName() <<" has : " << p2.showHand() << endl;
Card c1;
Card c2;
while(p1.checkHandForBook(c1,c2)){
p1.bookCards(c1,c2);
}
while(p2.checkHandForBook(c1,c2)){
p2.bookCards(c1,c2);
}
cout << p1.getName() <<" has : " << p1.showHand() << endl;
cout << p1.getName() << " book : " << p1.showBooks() << endl;
cout << p2.getName() <<" has : " << p2.showHand() << endl;
cout << p2.getName() << " book : " << p2.showBooks() << endl;
myfile << p1.getName() <<" has : " << p1.showHand() << endl;
myfile << p1.getName() << " book : " << p1.showBooks() << endl;
myfile << p2.getName() <<" has : " << p2.showHand() << endl;
myfile << p2.getName() << " book : " << p2.showBooks() << endl;
emptyHand(d,p1);
emptyHand(d,p2);
while( (d.size() != 0) ){
c1 = p1.chooseCardFromHand();
cout << p1.getName() << " says: Do you have any " << c1.getRank() << "'s ?" << endl;
myfile << p1.getName() << " says: Do you have any " << c1.getRank() << "'s ?" << endl;
while((p2.rankInHand(c1))){
cout << p2.getName() << " says: I do" << endl;
myfile << p2.getName() << " says: I do" << endl;
c2 = p2.removeCardFromHand(c1);
emptyHand(d,p2);
p1.addCard(c2);
p1.bookCards(c1, c2);
cout << p1.getName() << " book : " << p1.showBooks() << endl;
myfile << p1.getName() << " book : " << p1.showBooks() << endl;
emptyHand(d,p1);
if(p1.getHandSize() != 0) {
c1 = p1.chooseCardFromHand();
cout << p1.getName() << " says: Do you have any " << c1.getRank() << "'s ?" << endl;
myfile << p1.getName() << " says: Do you have any " << c1.getRank() << "'s ?" << endl;
}
}
cout << p2.getName() << " says: Go Fish!" << endl;
myfile << p2.getName() << " says: Go Fish!" << endl;
goFish(d,p1);
emptyHand(d,p1);
if(p1.getHandSize() == 0 && p2.getHandSize() ==0){
break;
}
emptyHand(d,p2);
c1 = p2.chooseCardFromHand();
cout << p2.getName() << " says: Do you have any " << c1.getRank() << "'s ?" << endl;
myfile << p2.getName() << " says: Do you have any " << c1.getRank() << "'s ?" << endl;
while(p1.rankInHand(c1)){
cout << p1.getName() << " says: I do" << endl;
myfile << p1.getName() << " says: I do" << endl;
c2 = p1.removeCardFromHand(c1);
emptyHand(d,p1);
p2.addCard(c2);
p2.bookCards(c1, c2);
cout << p2.getName() << " book : " << p2.showBooks() << endl;
myfile << p2.getName() << " book : " << p2.showBooks() << endl;
emptyHand(d,p2);
if(p2.getHandSize() != 0) {
c1 = p2.chooseCardFromHand();
cout << p2.getName() << " says: Do you have any " << c1.getRank() << "'s ?" << endl;
myfile << p2.getName() << " says: Do you have any " << c1.getRank() << "'s ?" << endl;
}
}
cout << p1.getName() << " says: Go Fish!" << endl;
myfile << p1.getName() << " says: Go Fish!" << endl;
goFish(d,p2);
emptyHand(d,p2);
}
if(p1.getBookSize() > p2.getBookSize()){
cout << p1.getName() << " WINS! Book Size: " << p1.getBookSize() << endl;
myfile << p1.getName() << " WINS! Book Size: " << p1.getBookSize() << endl;
}
else if(p1.getBookSize() < p2.getBookSize()){
cout << p2.getName() << " WINS! Book Size: " << p2.getBookSize() << endl;
myfile << p2.getName() << " WINS! Book Size: " << p2.getBookSize() << endl;
}
else{
cout << p1.getName() << " and " << p2.getName() << " TIE!" << endl;
myfile << p1.getName() << " and " << p2.getName() << " TIE!" << endl;
}
cout << p1.getName() <<" has : " << p1.showHand() << endl;
cout << p2.getName() <<" has : " << p2.showHand() << endl;
cout << p1.getName() << " book : " << p1.showBooks() << endl;
cout << p2.getName() << " book : " << p2.showBooks() << endl;
myfile << p1.getName() <<" has : " << p1.showHand() << endl;
myfile << p2.getName() <<" has : " << p2.showHand() << endl;
myfile << p1.getName() << " book : " << p1.showBooks() << endl;
myfile << p2.getName() << " book : " << p2.showBooks() << endl;
return EXIT_SUCCESS;
}
void dealHand(Deck &d, Player &p, int numCards)
{
for (int i=0; i < numCards; i++)
p.addCard(d.dealCard());
}
void emptyHand(Deck &d, Player &p)
{
if(d.size() != 0 && p.getHandSize() == 0) {
Card c;
c = d.dealCard();
p.addCard(c);
}
}
void goFish(Deck &d, Player &p)
{
Card c, c1;
if((d.size() != 0)){
c = d.dealCard();
p.addCard(c);
while(p.checkHandForBook(c,c1)){
p.bookCards(c,c1);
}
}
}
|
472d202558c0c2b2781680101673ce3e3f251ab0
|
1626d7ad5ae0d30452db70c53d9ed0c4415a75d2
|
/trunk/src/DataManager/BaseDataType/RemainderItem/RemainderItem.cpp
|
6cead56549661d2eebb7fb270f1090fefd7f9e35
|
[] |
no_license
|
yuanzibu/hello-world
|
e413b74717baa4b5ed437062d475aabc9687ee82
|
f6848d656d9ddfbda793d924883a3def9849fed7
|
refs/heads/master
| 2020-01-23T22:00:19.750136
| 2018-06-25T11:04:10
| 2018-06-25T11:04:10
| 74,722,844
| 1
| 2
| null | null | null | null |
GB18030
|
C++
| false
| false
| 492
|
cpp
|
RemainderItem.cpp
|
/*--------------------------------------------------------------------------------------------------------------------*/
// RemainderItem.cpp -- ไฝๆ้กน็ฑปๅฎ็ฐๆไปถ
//
// ไฝ่
๏ผ yuanzb
// ๆถ้ด๏ผ 2017.9.8
// ๅคๆณจ๏ผ
//
/*--------------------------------------------------------------------------------------------------------------------*/
#include "stdafx.h"
#include "RemainderItem.h"
RemainderItem::RemainderItem(void)
{
}
RemainderItem::~RemainderItem(void)
{
}
|
7d9fc11135f6eef208e48a3684e1fda80d4d6d3d
|
680eb8207417233de9a9dfa32bb022a74e256745
|
/WrlSDK/SampleCode/PluginWinExe/WRLRegKey.cpp
|
9f2241dcfcf277b720342bb43a94986005503cd5
|
[
"MIT"
] |
permissive
|
wangzuohuai/WebRunLocal
|
ddb793c1fcb07bb5d03fecdf5fcdc8b8939ffa9a
|
6612ffcaacd201a50979f8bd5a56a53b21f6cf60
|
refs/heads/master
| 2023-08-04T14:01:53.810516
| 2023-07-24T07:33:46
| 2023-07-24T07:33:46
| 147,037,258
| 633
| 142
|
NOASSERTION
| 2020-10-11T01:34:23
| 2018-09-01T22:31:53
|
C++
|
GB18030
|
C++
| false
| false
| 3,366
|
cpp
|
WRLRegKey.cpp
|
/**
* @file ZMRegKey.cpp
*
* Copyright (c) 2013-?,ๆ้ฝไฝ็ฝ่ฝฏไปถ
* All rights reserved.
*
* @ingroup
*
* @brief ๆณจๅ่กจๆไฝๅฐ่ฃ
ๅฎ็ฐ
*
*
*
* @version
*
* @date 2018-09-01
*
* @author WZH
*
* @history
*
*/
// ZMRegKey.cpp : ๆณจๅ่กจๅฐ่ฃ
ๅฎ็ฐ
#include "stdafx.h"
#include "WRLRegKey.h"
#include "BaseFuncLib.h"
CWrlRegKey::CWrlRegKey(const ATL::CString& strMainRegPath,\
const ATL::CString& strChildName, HKEY hKey,REGSAM samDesired)
{
m_bOpenFlag = FALSE;
m_dwLastErr = 0;
ATLASSERT(strMainRegPath.GetLength());
NewRegPath(strMainRegPath,strChildName,hKey,samDesired);
}
void CWrlRegKey::Close()
{
if(!m_bOpenFlag)
return;
CRegKey::Close();
m_dwLastErr = 0;
m_bOpenFlag = FALSE;
}
BOOL CWrlRegKey::NewRegPath(const ATL::CString& strMainRegPath,\
const ATL::CString& strChildName, HKEY hKey,REGSAM samDesired)
{
if(m_bOpenFlag)
Close();
ATL::CString strRegPath;
if(!strChildName.IsEmpty())
strRegPath.Format(_T("%s\\%s"),strMainRegPath,strChildName);
else
strRegPath = strMainRegPath;
m_dwLastErr = Open(hKey,strRegPath,samDesired);
if(ERROR_SUCCESS != m_dwLastErr)
{
if(ERROR_ACCESS_DENIED != m_dwLastErr && ERROR_WRITE_PROTECT != m_dwLastErr)
{
/// ่ฟไธๅญๅจๆๅฎๆณจๅ้กน็ฎ๏ผ่ชๅจๅๅปบ
m_dwLastErr = Create(hKey,strRegPath,NULL,0,samDesired);
}
}
if(ERROR_SUCCESS == m_dwLastErr)
{
m_bOpenFlag = TRUE;
}
return m_bOpenFlag;
}
BOOL CWrlRegKey::GetRegStringVal(
const ATL::CString& strKeyName,ATL::CString& strKeyValue)
{
BOOL bGetFlag = FALSE;
if(!m_bOpenFlag)
{
return bGetFlag;
}
DWORD dwSize = 0;
if(strKeyName.IsEmpty())
m_dwLastErr = CRegKey::QueryStringValue(NULL,NULL,&dwSize);
else
m_dwLastErr = CRegKey::QueryStringValue(strKeyName,NULL,&dwSize);
if(!dwSize)
{
/// ๆฒกๆๅผ
return bGetFlag;
}
TCHAR *szBuf = new TCHAR[dwSize+1];
if(NULL == szBuf)
return bGetFlag;
memset(szBuf,0,(dwSize+1)*sizeof(TCHAR));
if(strKeyName.IsEmpty())
m_dwLastErr = CRegKey::QueryStringValue(NULL,szBuf,&dwSize);
else
m_dwLastErr = CRegKey::QueryStringValue(strKeyName,szBuf,&dwSize);
if(m_dwLastErr != ERROR_SUCCESS)
{
if(NULL != szBuf)
{
delete []szBuf;
szBuf = NULL;
}
return bGetFlag;
}
bGetFlag = TRUE;
strKeyValue = szBuf;
if(NULL != szBuf)
{
delete []szBuf;
szBuf = NULL;
}
return bGetFlag;
}
BOOL CWrlRegKey::SetRegStringVal(const ATL::CString& strKeyName,
const ATL::CString& strKeyValue)
{
if(!m_bOpenFlag)
return FALSE;
m_dwLastErr = CRegKey::SetStringValue(strKeyName,strKeyValue);
if(m_dwLastErr != ERROR_SUCCESS)
return FALSE;
return TRUE;
}
BOOL CWrlRegKey::GetRegDwordVal(const ATL::CString& strKeyName,
DWORD& dwKeyValue)
{
dwKeyValue = 0;
if(!m_bOpenFlag)
return FALSE;
m_dwLastErr = CRegKey::QueryDWORDValue(strKeyName,dwKeyValue);
if(m_dwLastErr != ERROR_SUCCESS)
return FALSE;
return TRUE;
}
BOOL CWrlRegKey::SetRegDwordVal(const ATL::CString& strKeyName,
DWORD dwKeyValue)
{
if(!m_bOpenFlag)
return FALSE;
m_dwLastErr = CRegKey::SetDWORDValue(strKeyName,dwKeyValue);
if(m_dwLastErr != ERROR_SUCCESS)
return FALSE;
return TRUE;
}
BOOL CWrlRegKey::DelKeyName(const ATL::CString& strKeyName)
{
if(!m_bOpenFlag)
return FALSE;
m_dwLastErr = CRegKey::DeleteValue(strKeyName);
if(m_dwLastErr != ERROR_SUCCESS)
return FALSE;
return TRUE;
}
|
0a357818481160a212fc20192b3fe7bf52d045fa
|
91a882547e393d4c4946a6c2c99186b5f72122dd
|
/Source/XPSP1/NT/base/fs/remotefs/dfs/dfsserver/serverlibrary/domaincontrollersupport.cxx
|
978651513d78955ba96ebe92820c79b0ce7f2d52
|
[] |
no_license
|
IAmAnubhavSaini/cryptoAlgorithm-nt5src
|
94f9b46f101b983954ac6e453d0cf8d02aa76fc7
|
d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2
|
refs/heads/master
| 2023-09-02T10:14:14.795579
| 2021-11-20T13:47:06
| 2021-11-20T13:47:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 12,425
|
cxx
|
domaincontrollersupport.cxx
|
#include "DfsGeneric.hxx"
#include "dsgetdc.h"
#include "dsrole.h"
#include "DfsDomainInformation.hxx"
#include "DfsTrustedDomain.hxx"
#include "DfsReferralData.hxx"
#include "DomainControllerSupport.hxx"
#include "DfsReplica.hxx"
#include "dfsadsiapi.hxx"
#include "lmdfs.h"
#include "dfserror.hxx"
#include "dfsfilterapi.hxx"
#define RemoteServerNameString L"remoteServerName"
extern
DFS_SERVER_GLOBAL_DATA DfsServerGlobalData;
#define HRESULT_TO_DFSSTATUS(_x) (_x)
DFSSTATUS
DfsDcInit(
PBOOLEAN pIsDc,
DfsDomainInformation **ppDomainInfo )
{
PDSROLE_PRIMARY_DOMAIN_INFO_BASIC pPrimaryDomainInfo = NULL;
DFSSTATUS Status = ERROR_SUCCESS;
Status = DsRoleGetPrimaryDomainInformation( NULL,
DsRolePrimaryDomainInfoBasic,
(PBYTE *)&pPrimaryDomainInfo);
if (Status == ERROR_SUCCESS)
{
if(pPrimaryDomainInfo->MachineRole == DsRole_RoleStandaloneServer)
{
DfsServerGlobalData.IsWorkGroup = TRUE;
}
else
{
DfsServerGlobalData.IsWorkGroup = FALSE;
}
#if defined(TESTING)
pPrimaryDomainInfo->MachineRole = DsRole_RoleBackupDomainController;
#endif
if ( (pPrimaryDomainInfo->MachineRole == DsRole_RoleBackupDomainController) ||
(pPrimaryDomainInfo->MachineRole == DsRole_RolePrimaryDomainController) )
{
*pIsDc = TRUE;
DfsDomainInformation *pNewDomainInfo = new DfsDomainInformation( &Status );
if (pNewDomainInfo == NULL)
{
Status = ERROR_NOT_ENOUGH_MEMORY;
}
else if (Status != ERROR_SUCCESS)
{
pNewDomainInfo->ReleaseReference();
}
if (Status == ERROR_SUCCESS)
{
*ppDomainInfo = pNewDomainInfo;
}
}
DfsSetDomainNameFlat( pPrimaryDomainInfo->DomainNameFlat);
DfsSetDomainNameDns( pPrimaryDomainInfo->DomainNameDns);
DsRoleFreeMemory(pPrimaryDomainInfo);
}
return Status;
}
//+-------------------------------------------------------------------------
//
// Function: DfsGenerateReferralDataFromRemoteServerNames
// IADs *pObject - the object
// DfsfolderReferralData *pReferralData - the referral data
//
//
// Returns: Status: Success or Error status code
//
// Description: This routine reads the remote server name
// attribute and creates a referral data structure
// so that we can pass a referral based on these names.
//
//--------------------------------------------------------------------------
DFSSTATUS
DfsGenerateReferralDataFromRemoteServerNames(
LPWSTR RootName,
DfsReferralData **ppReferralData )
{
HRESULT HResult = S_OK;
DfsReplica *pReplicas = NULL;
DFSSTATUS Status = ERROR_SUCCESS;
DfsReferralData *pReferralData = NULL;
IADs *pObject = NULL;
VARIANT Variant;
Status = DfsGetDfsRootADObject(NULL,
RootName,
&pObject );
if (Status == ERROR_SUCCESS)
{
pReferralData = new DfsReferralData (&Status );
if (pReferralData == NULL)
{
Status = ERROR_NOT_ENOUGH_MEMORY;
}
else if (Status != ERROR_SUCCESS)
{
pReferralData->ReleaseReference();
}
if (Status == ERROR_SUCCESS)
{
LONG StartNdx, LastNdx;
SAFEARRAY *PropertyArray;
VariantInit( &Variant );
pReferralData->Timeout = DFS_DEFAULT_REFERRAL_TIMEOUT;
HResult = pObject->GetEx( RemoteServerNameString, &Variant );
if ( SUCCEEDED(HResult) )
{
PropertyArray = V_ARRAY( &Variant );
HResult = SafeArrayGetLBound( PropertyArray, 1, &StartNdx );
if ( SUCCEEDED(HResult) )
{
HResult = SafeArrayGetUBound( PropertyArray, 1, &LastNdx );
}
}
if ( SUCCEEDED(HResult) &&
(LastNdx > StartNdx) )
{
VARIANT VariantItem;
pReplicas = new DfsReplica [ LastNdx - StartNdx ];
if (pReplicas != NULL)
{
VariantInit( &VariantItem );
for ( LONG Index = StartNdx; Index < LastNdx; Index++ )
{
HResult = SafeArrayGetElement( PropertyArray,
&Index,
&VariantItem );
if ( SUCCEEDED(HResult) )
{
UNICODE_STRING ServerName, Remaining, Replica;
LPWSTR ReplicaString = V_BSTR( &VariantItem );
RtlInitUnicodeString( &Replica, ReplicaString );
DfsGetFirstComponent( &Replica,
&ServerName,
&Remaining );
Status = (&pReplicas[ Index - StartNdx])->SetTargetServer( &ServerName );
if (Status == ERROR_SUCCESS)
{
Status = (&pReplicas[ Index - StartNdx])->SetTargetFolder( &Remaining );
}
}
else {
Status = DfsGetErrorFromHr( HResult );
}
VariantClear( &VariantItem );
if (Status != ERROR_SUCCESS)
{
delete [] pReplicas;
pReplicas = NULL;
break;
}
}
}
else
{
Status = ERROR_NOT_ENOUGH_MEMORY;
}
}
else
{
Status = DfsGetErrorFromHr( HResult );
}
VariantClear( &Variant );
if (Status == ERROR_SUCCESS)
{
pReferralData->ReplicaCount = LastNdx - StartNdx;
pReferralData->pReplicas = pReplicas;
*ppReferralData = pReferralData;
}
if (Status != ERROR_SUCCESS)
{
pReferralData->ReleaseReference();
}
}
pObject->Release();
}
return Status;
}
//+-------------------------------------------------------------------------
//
// Function: DfsUpdateRemoteServerName
//
// Arguments:
// IADs *pObject - the ds object of interest.
// LPWSTR ServerName - the server name to add or delete
// LPWSTR RemainingName - the rest of the name
// BOOLEAN Add - true for add, false for delete.
//
// Returns: Status: Success or Error status code
//
// Description: This routine updates the RemoteServerName attribute
// in the DS object, either adding a \\servername\remaining
// to the existing DS attribute or removing it, depending
// on add/delete.
// The caller must make sure this parameter does not
// already exist in the add case, or that the parameter
// to be deleted does exist in the delete case.
//
//--------------------------------------------------------------------------
DFSSTATUS
DfsUpdateRemoteServerName(
IADs *pObject,
LPWSTR ServerName,
LPWSTR RemainingName,
BOOLEAN Add )
{
HRESULT HResult = S_OK;
DFSSTATUS Status = ERROR_SUCCESS;
VARIANT Variant;
UNICODE_STRING UpdateName;
LPWSTR pServers[1];
//
// create a unc path using the server and remaining name
// to get a path of type \\servername\remainingname
//
Status = DfsCreateUnicodePathString( &UpdateName,
2, // unc path: 2 leading seperators,
ServerName,
RemainingName);
pServers[0] = UpdateName.Buffer;
if (Status == ERROR_SUCCESS)
{
//
// initialize the variant.
//
VariantInit( &Variant );
//
// Create the variant array with a single entry in it.
//
HResult = ADsBuildVarArrayStr( pServers,
1,
&Variant );
if ( SUCCEEDED(HResult) )
{
//
// either append or delete this string from the remote server
// name attribute
//
HResult = pObject->PutEx( (Add ? ADS_PROPERTY_APPEND : ADS_PROPERTY_DELETE),
RemoteServerNameString,
Variant );
if ( SUCCEEDED(HResult) )
{
//
// now update the object in the DS with this info.
//
HResult = pObject->SetInfo();
}
//
// clear the variant
//
VariantClear( &Variant );
}
if ( SUCCEEDED(HResult) == FALSE)
{
Status = DfsGetErrorFromHr( HResult );
}
//
// free the unicode string we created earlier on.
//
DfsFreeUnicodeString( &UpdateName );
}
return Status;
}
DFSSTATUS
DfsDcEnumerateRoots(
LPWSTR DfsName,
LPBYTE pBuffer,
ULONG BufferSize,
PULONG pEntriesRead,
PULONG pSizeRequired )
{
DFSSTATUS Status = ERROR_SUCCESS;
ULONG_PTR CurrentBuffer = (ULONG_PTR)pBuffer;
ULONG CurrentSize = BufferSize;
UNREFERENCED_PARAMETER(DfsName);
Status = DfsEnumerateDfsADRoots( NULL,
&CurrentBuffer,
&CurrentSize,
pEntriesRead,
pSizeRequired );
return Status;
}
DFSSTATUS
DfsUpdateRootRemoteServerName(
LPWSTR Root,
LPWSTR DCName,
LPWSTR ServerName,
LPWSTR RemainingName,
BOOLEAN Add )
{
IADs *pRootObject = NULL;
DFSSTATUS Status = ERROR_SUCCESS;
Status = DfsGetDfsRootADObject( DCName,
Root,
&pRootObject );
if (Status == ERROR_SUCCESS)
{
Status = DfsUpdateRemoteServerName( pRootObject,
ServerName,
RemainingName,
Add );
pRootObject->Release();
}
return Status;
}
#define UNICODE_STRING_STRUCT(s) \
{sizeof(s) - sizeof(WCHAR), sizeof(s) - sizeof(WCHAR), (s)}
static UNICODE_STRING DfsSpecialDCShares[] = {
UNICODE_STRING_STRUCT(L"SYSVOL"),
UNICODE_STRING_STRUCT(L"NETLOGON"),
};
BOOLEAN
DfsIsSpecialDomainShare(
PUNICODE_STRING pShareName )
{
ULONG Index;
ULONG TotalShares;
BOOLEAN SpecialShare = FALSE;
TotalShares = sizeof(DfsSpecialDCShares) / sizeof(DfsSpecialDCShares[0]);
for (Index = 0; Index < TotalShares; Index++ )
{
if (DfsSpecialDCShares[Index].Length == pShareName->Length) {
if (_wcsnicmp(DfsSpecialDCShares[Index].Buffer,
pShareName->Buffer,
pShareName->Length/sizeof(WCHAR)) == 0)
{
SpecialShare = TRUE;
break;
}
}
}
return SpecialShare;
}
DFSSTATUS
DfsInitializeSpecialDCShares()
{
ULONG Index;
ULONG TotalShares;
DFSSTATUS Status = ERROR_SUCCESS;
TotalShares = sizeof(DfsSpecialDCShares) / sizeof(DfsSpecialDCShares[0]);
for (Index = 0; Index < TotalShares; Index++ )
{
Status = DfsUserModeAttachToFilesystem( &DfsSpecialDCShares[Index],
&DfsSpecialDCShares[Index] );
if (Status != ERROR_SUCCESS)
{
break;
}
}
return Status;
}
|
29fda944d96adaeb96f7a404379a59297df34da2
|
3af68b32aaa9b7522a1718b0fc50ef0cf4a704a9
|
/cpp/C/B/C/D/A/ACBCDA.h
|
5a928f30308b91e135758bfb74ccf3cbf38b6783
|
[] |
no_license
|
devsisters/2021-NDC-ICECREAM
|
7cd09fa2794cbab1ab4702362a37f6ab62638d9b
|
ac6548f443a75b86d9e9151ff9c1b17c792b2afd
|
refs/heads/master
| 2023-03-19T06:29:03.216461
| 2021-03-10T02:53:14
| 2021-03-10T02:53:14
| 341,872,233
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 67
|
h
|
ACBCDA.h
|
#ifndef ACBCDA_H
namespace ACBCDA {
std::string run();
}
#endif
|
c8fecac7f90c0c1b5cddfb6191e97ee2dc843517
|
05819101e23d72ebe1eb607988d8a07b174e7652
|
/project2/Classes/AnimInfo.h
|
827f80f0ced16c947b00e2bdcae9e719d40b1397
|
[] |
no_license
|
Reika-Y/ActionBike
|
8cf6d67961664de3e3c4bc6852a3ab0d9b7bde71
|
99d0f205acc2fcc682dcb6718d732a6da78777c8
|
refs/heads/master
| 2020-09-30T10:49:00.870568
| 2020-02-05T14:42:13
| 2020-02-05T14:42:13
| 227,272,338
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 713
|
h
|
AnimInfo.h
|
๏ปฟ#pragma once
#include <map>
#include <string>
#include <cocos2d.h>
// Animate็ฎก็็จ
using AnimData = std::map<std::string, cocos2d::Animate*>;
class AnimInfo
{
public:
AnimInfo();
~AnimInfo();
// ใขใใกใผใทใงใณใ่ฟฝๅ ใใพใ
// <param = plist> plistใฎใใน
// <param = key> ๅๅพ็จใฎใญใผ
// <param = delay> ๅ็้้
// <param = restoreOriginalFrame> ๆๅใฎใณใใซๆปใใ
void AddAnim(const std::string& plist,const std::string& key, int num, const float& delay,bool restoreOriginalFrame);
// Animateใๅๅพใใพใ
// <param = key> ็ป้ฒใใใญใผ
cocos2d::Animate* GetData(const std::string& key);
private:
AnimData _data;
};
|
d4ffb72ecbcd146f2df937248e3188646914b696
|
52d6267e17284fbdd789d0f30e5c149402d53b50
|
/streampower.h
|
f4ff33b1ea46692c7f43199ae090f5d302a09e5d
|
[] |
no_license
|
pletzer/ThawScape
|
a7835438e3d9a4962a357964b7796d00f6d0880e
|
2383ca69e8d4b54e6bd2910fd7555cf480d82112
|
refs/heads/master
| 2020-05-27T17:55:13.266865
| 2019-05-29T01:24:51
| 2019-05-29T01:24:51
| 188,732,174
| 0
| 0
| null | 2019-05-26T21:13:29
| 2019-05-26T21:13:29
| null |
WINDOWS-1252
|
C++
| false
| false
| 5,804
|
h
|
streampower.h
|
#ifndef _STREAMPOWER_H_
#define _STREAMPOWER_H_
#include <vector>
#include <random>
#include <numeric>
#include <algorithm>
#include "Array2D.hpp"
#include "indexx.hpp"
#define NR_END 1
#define FREE_ARG char*
#define MBIG 1000000000
#define MSEED 161803398
#define MZ 0
#define FAC (1.0/MBIG)
#define SWAP(a,b) itemp=(a);(a)=(b);(b)=itemp;
//#define M 7
#define NSTACK 100000
#define sqrt2 1.414213562373f
#define oneoversqrt2 0.707106781186f
#define degrad 0.01745329251994330 // Convert degrees to radians; e.g. 180 * degrad = 3.14159..
#define PI 3.14159265358979
#define HALFPI = PI/2
#define fillincrement 0.01f
class time_fcn {
public:
int year;
int day; // Everything works on 365 Julian Day system for now
int hour; // 24 hr clock
int minute;
int LocalTime; // Decimal Hour
int UT;
int end_year; // Model end year
};
class solar_geom {
public:
float lattitude;
float longitude;
float stdmed; // LSTM = (UTC - 7H * 15 deg)
float declination; // Declination of sun from equatorial plane
float altitude; // Sun altitude in the sky
float azimuth; // Compass angle of sun
float incidence; // Angle of sun's incidence
float SHA; // Solar Hour Angle is 0ยฐ at solar noon. Since the Earth rotates 15ยฐ per hour,
// each hour away from solar noon corresponds to an angular motion of the sun in the sky of 15ยฐ.
// In the morning the hour angle is negative, in the afternoon the hour angle is positive.
};
class StreamPower
{
public:
int lattice_size_x, lattice_size_y, duration, printinterval, printstep;
float U, K, D, melt, timestep, ann_timestep, deltax, deltax2, thresh, thresh_diag, thresholdarea;
float init_exposure_age, init_sed_track, init_veg;
// new vars
float xllcorner, yllcorner, nodata;
std::vector<int> iup, idown, jup, jdown;
std::vector<float> ax, ay, bx, by, cx, cy, ux, uy, rx, ry;
Indexx<float> topo_indexx, sed_indexx;
std::vector<std::vector<float>> topo, topoold, topo2, slope, aspect, flow, flow1, flow2, flow3,
flow4, flow5, flow6, flow7, flow8, FA, veg, veg_old, Sed_Track, ExposureAge, ExposureAge_old;
std::vector<std::vector<float>> solar_raster, shade_raster, I_D;
std::vector<std::vector<std::vector<float>>> Ip_D8; // Map of incoming solar flux, 8 directions
Array2D<float> elevation;
time_fcn ct; // Current model time
solar_geom r;
static std::vector<float> Vector(int nl, int nh);
static std::vector<int> IVector(int nl, int nh);
static std::vector<std::vector<float>> Matrix(int nrl, int nrh, int ncl, int nch);
static std::vector<std::vector<int>> IMatrix(int nrl, int nrh, int ncl, int nch);
static float Ran3(std::default_random_engine& generator, std::uniform_real_distribution<float>& distribution);
static float Gasdev(std::default_random_engine& generator, std::normal_distribution<float>& distribution);
// static void Indexx(int n, float* arr, int* indx); // interface from old to new implementation
// static std::vector<int> Indexx(std::vector<float>& arr); // new implementation
static void Tridag(float a[], float b[], float c[], float r[], float u[], unsigned long n); // interface from old to new implementation
static void Tridag(std::vector<float>& a, std::vector<float>& b, std::vector<float>& c, std::vector<float>& r, std::vector<float>& u, int n); // new implementation
StreamPower(int nx, int ny);
~StreamPower();
std::vector<std::vector<float>> CreateRandomField();
std::vector<std::vector<float>> ReadArcInfoASCIIGrid(const char* fname);
std::vector<std::vector<float>> GetTopo();
void SetupGridNeighbors();
void SetTopo(std::vector<std::vector<float>> t);
void SetFA(std::vector<std::vector<float>> f); // Set flow accumulation raster
void Flood(); // Barnes pit filling
void MFDFlowRoute(int i, int j); //new implementation
void InitDiffusion();
void HillSlopeDiffusion();
void Avalanche(int i, int j);
void SlopeAspect(int i, int j);
void SunPosition();
void SolarInflux();
void MeltExposedIce();
void Init(std::string parameter_file); // using new vars
void LoadInputs();
void Start();
void PrintState(char* fname);
std::string topo_file, fa_file, sed_file;
};
template <typename T> std::vector<T> ArrayToVector(T* a, int size)
{
std::vector<T> v = std::vector<T>(size);
for (int i = 0; i < size; i++)
{
v[i] = a[i];
}
return v;
}
template <typename T> std::vector<T> ArrayToVector(T* a, int size, bool fortranIndexing)
{
std::vector<T> v;
if (fortranIndexing)
{
v = std::vector<T>(size + 1);
}
else
{
v = std::vector<T>(size);
}
for (int i = 0; i < size; i++)
{
v[i] = a[i];
}
return v;
}
template <typename T> void VectorToArray(std::vector<T>& v, T* a)
{
for (int i = 0; i < v.size(); i++)
{
a[i] = v[i];
}
}
// http://stackover_flow.com/questions/1577475/c-sorting-and-keeping-track-of-indexes
template <typename T> std::vector<int> SortIndices(const std::vector<T>& v)
{
// initialize original index locations
std::vector<int> idx(v.size());
std::iota(idx.begin(), idx.end(), 0);
// sort indexes based on comparing values in v
std::sort(idx.begin(), idx.end(), [&v](int i1, int i2) {return v[i1] < v[i2]; });
return idx;
}
template <typename T> std::vector<int> SortFortranIndices(const std::vector<T>& v)
{
// initialize original index locations
std::vector<int> idx(v.size());
std::iota(idx.begin()+1, idx.end(), 1);
// sort indexes based on comparing values in v
std::sort(idx.begin()+1, idx.end(), [&v](int i1, int i2) {return v[i1] < v[i2]; });
return idx;
}
#endif
|
5d43c8bc4ba962d6d18a9abf1f66876a0eb29ae6
|
57d68bfbfc8ea43db9a22d9fb3b503d8d9900036
|
/SourceCode/299-Bulls and Cows.cpp
|
ab9a68875a6478b1aa17fdd5d7a663d639723a3c
|
[] |
no_license
|
GodBless112/LeetCodeAlgorithm
|
6e55d59e11867f95dd35651663883112e01b2f4c
|
bbcedec43fe95d026ab558029a09494a0e55fea4
|
refs/heads/master
| 2021-01-19T03:02:39.594225
| 2017-08-23T14:51:40
| 2017-08-23T14:51:40
| 87,303,569
| 4
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,922
|
cpp
|
299-Bulls and Cows.cpp
|
๏ปฟ// 299. Bulls and Cows
//------------------------------------------------------------------------------//
// You are playing the following Bulls and Cows game with your friend: You //
// write down a number and ask your friend to guess what the number is. Each //
// time your friend makes a guess, you provide a hint that indicates how many //
// digits in said guess match your secret number exactly in both digit and //
// position (called "bulls") and how many digits match the secret number but //
// locate in the wrong position (called "cows"). Your friend will use //
// successive guesses and hints to eventually derive the secret number. //
// For example : //
// Secret number : "1807" //
// Friend's guess: "7810" //
// Hint : 1 bull and 3 cows. (The bull is 8, the cows are 0, 1 and 7.) //
// Write a function to return a hint according to the secret number and //
// friend's guess, use A to indicate the bulls and B to indicate the cows. In //
// the above example, your function should return "1A3B". //
// Please note that both secret number and friend's guess may contain //
// duplicate digits, for example: //
// Secret number : "1123" //
// Friend's guess: "0111" //
// In this case, the 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a //
// cow, and your function should return "1A1B". //
// You may assume that the secret number and your friend's guess only contain //
// digits, and their lengths are always equal. //
//------------------------------------------------------------------------------//
#include <iostream>
#include<vector>
#include<string>
#include<numeric>
#include<algorithm>
#include<functional>
#include<unordered_map>
// constants
// function prototype
using namespace std;
//ไธค่ถ๏ผๅ
ๆพbullๅๆพcow
class Solution {
public:
string getHint(string secret, string guess) {
int n = secret.size();
string hint;
if (n != guess.size()) return hint;
int bulls = 0, cows = 0;
unordered_map<char, int> dict;
for (int i = 0; i < n; ++i) {
dict[secret[i]]++;
if (secret[i] == guess[i]) {
bulls++;
dict[secret[i]]--;
}
}
for (int i = 0; i < n; ++i) {
if (secret[i] == guess[i])
continue;
if (dict[guess[i]] > 0) {
dict[guess[i]]--;
cows++;
}
}
return to_string(bulls) + 'A' + to_string(cows) + 'B';
}
};
//ๆน่ฟ๏ผ็จๆฐ็ปๅญๆพ'0'-'9'
class Solution2 {
public:
// only contains digits
string getHint(string secret, string guess) {
int aCnt = 0;
int bCnt = 0;
vector<int> sVec(10, 0); // 0 ~ 9 for secret
vector<int> gVec(10, 0); // 0 ~ 9 for guess
if (secret.size() != guess.size() || secret.empty()) { return "0A0B"; }
for (int i = 0; i < secret.size(); ++i) {
char c1 = secret[i]; char c2 = guess[i];
if (c1 == c2) {
++aCnt;
}
else {
++sVec[c1 - '0'];
++gVec[c2 - '0'];
}
}
// count b
for (int i = 0; i < sVec.size(); ++i) {
bCnt += min(sVec[i], gVec[i]);
}
return to_string(aCnt) + 'A' + to_string(bCnt) + 'B';
}
};
//one pass๏ผๅๅๅธ่กจ
class Solution3 {
public:
string getHint(string secret, string guess) {
unordered_map<char, int> s_map;
unordered_map<char, int> g_map;
int n = secret.size();
int A = 0, B = 0;
for (int i = 0; i < n; i++)
{
char s = secret[i], g = guess[i];
if (s == g)
A++;
else
{
(s_map[g] > 0) ? s_map[g]--, B++ : g_map[g]++;
(g_map[s] > 0) ? g_map[s]--, B++ : s_map[s]++;
}
}
return to_string(A) + "A" + to_string(B) + "B";;
}
};
//int main(void)
//{
// Solution test;
// cout << test.getHint("1123", "0111") << endl;
// cout << test.getHint("1807", "7810") << endl;
// cout << test.getHint("1122", "1222");
// cout << endl;
//
// // code to keep window open for MSVC++
// cin.clear();
// while (cin.get() != '\n')
// continue;
// cin.get();
//
// return 0;
//}
|
05ef3e00a50c41a72cec6ff908c0a3d256288a09
|
aa2ac425a8bb957a26763ae17e50d50f1cce8956
|
/src/Addons/GeoWay/gwXML_StandardMetaData/type_gml.CTimeCalendarPropertyType.h
|
b4f9266d821de41f2ee6e67720534ffbfc9a6e1a
|
[] |
no_license
|
radtek/CGISS
|
c7289ed19d912c432aae81d0cdbb6b080b4f5458
|
3f7cfa19d8024a67a5350d51e3f2f40a5e203576
|
refs/heads/master
| 2023-03-16T21:23:56.948744
| 2017-06-17T14:14:09
| 2017-06-17T14:14:09
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,223
|
h
|
type_gml.CTimeCalendarPropertyType.h
|
#ifndef _ALTOVA_INCLUDED_gie_ALTOVA_gml_ALTOVA_CTimeCalendarPropertyType
#define _ALTOVA_INCLUDED_gie_ALTOVA_gml_ALTOVA_CTimeCalendarPropertyType
namespace gie
{
namespace gml
{
class CTimeCalendarPropertyType : public TypeBase
{
public:
gie_EXPORT CTimeCalendarPropertyType(xercesc::DOMNode* const& init);
gie_EXPORT CTimeCalendarPropertyType(CTimeCalendarPropertyType const& init);
void operator=(CTimeCalendarPropertyType const& other) { m_node = other.m_node; }
static altova::meta::ComplexType StaticInfo() { return altova::meta::ComplexType(types + _altova_ti_gml_altova_CTimeCalendarPropertyType); }
MemberAttribute<bool,_altova_mi_gml_altova_CTimeCalendarPropertyType_altova_owns, 0, 0> owns; // owns Cboolean
MemberAttribute<string_type,_altova_mi_gml_altova_CTimeCalendarPropertyType_altova_type, 0, 0> type; // type Cstring
MemberAttribute<string_type,_altova_mi_gml_altova_CTimeCalendarPropertyType_altova_href, 0, 0> href; // href CanyURI
MemberAttribute<string_type,_altova_mi_gml_altova_CTimeCalendarPropertyType_altova_role, 0, 0> role; // role CanyURI
MemberAttribute<string_type,_altova_mi_gml_altova_CTimeCalendarPropertyType_altova_arcrole, 0, 0> arcrole; // arcrole CanyURI
MemberAttribute<string_type,_altova_mi_gml_altova_CTimeCalendarPropertyType_altova_title, 0, 0> title; // title Cstring
MemberAttribute<string_type,_altova_mi_gml_altova_CTimeCalendarPropertyType_altova_show, 0, 5> show; // show CshowType
MemberAttribute<string_type,_altova_mi_gml_altova_CTimeCalendarPropertyType_altova_actuate, 0, 4> actuate; // actuate CactuateType
MemberAttribute<string_type,_altova_mi_gml_altova_CTimeCalendarPropertyType_altova_nilReason, 1, 5> nilReason; // nilReason CNilReasonType
MemberAttribute<string_type,_altova_mi_gml_altova_CTimeCalendarPropertyType_altova_remoteSchema, 0, 0> remoteSchema; // remoteSchema CanyURI
MemberElement<gml::CTimeCalendarType, _altova_mi_gml_altova_CTimeCalendarPropertyType_altova_TimeCalendar> TimeCalendar;
struct TimeCalendar { typedef Iterator<gml::CTimeCalendarType> iterator; };
gie_EXPORT void SetXsiType();
};
} // namespace gml
} // namespace gie
#endif // _ALTOVA_INCLUDED_gie_ALTOVA_gml_ALTOVA_CTimeCalendarPropertyType
|
34b300a7e70333e6f01e12724d30fbdb2724f47c
|
a04ff5ef3eab42788bad92afbfb59935e3e3baf7
|
/source/opengl/my_opengl.cpp
|
33369e97effd5e9b773a78b9af7ccc64c0ec5096
|
[] |
no_license
|
Gaspard--/Supercharged-Juggernaut-Wasps
|
bbf671789a33c3e9751f606c4786544df7061a6c
|
e7baa6b831042f82a5046c6e3061b242a7cb3f16
|
refs/heads/master
| 2020-04-09T01:28:54.637243
| 2018-12-04T14:04:56
| 2018-12-04T14:04:56
| 159,906,385
| 3
| 0
| null | 2018-12-02T15:05:37
| 2018-12-01T03:48:30
|
C++
|
UTF-8
|
C++
| false
| false
| 6,811
|
cpp
|
my_opengl.cpp
|
#include "opengl/my_opengl.hpp"
#include <stdexcept>
#include <iostream>
#include <memory>
#include <sstream>
#include <fstream>
#include <cstring>
#include <cassert>
namespace opengl
{
void checkError()
{
if (int err = glGetError())
{
switch (err)
{
case GL_INVALID_ENUM:
std::cerr << "GL_INVALID_ENUM\n";
break;
case GL_INVALID_VALUE:
std::cerr << "GL_INVALID_VALUE\n";
break;
case GL_INVALID_OPERATION:
std::cerr << "GL_INVALID_OPERATION\n";
break;
case GL_INVALID_FRAMEBUFFER_OPERATION:
std::cerr << "GL_INVALID_FRAMEBUFFER_OPERATION\n";
break;
case GL_OUT_OF_MEMORY:
std::cerr << "GL_OUT_OF_MEMORY\n";
break;
default:
std::cerr << "Unknown GL error\n";
}
assert(0);
}
}
void shaderError(GLenum const shadertype, GLuint const shader)
{
GLint len;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &len);
std::unique_ptr<GLchar[]> log(new GLchar[len + 1]);
log[len + 1] = 0; // safety
glGetShaderInfoLog(shader, len, nullptr, &log[0]);
throw std::runtime_error(std::string("Compilation failed for ")
+ ((shadertype == GL_VERTEX_SHADER) ?
"vertex" : (shadertype == GL_FRAGMENT_SHADER) ?
"fragment" : "unknown (fix this in my_opengl.cpp!)")
+ std::string(" shader: ")
+ &log[0]);
}
void programError(GLuint const program)
{
GLint len;
std::string log;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &len);
log.reserve(static_cast<unsigned int>(len));
glGetProgramInfoLog(program, len, NULL, &log[0]);
throw std::runtime_error("link failure: " + log);
}
Shader createShader(GLenum const shadertype, GLchar const *src)
{
Shader shader(shadertype);
GLint status(0);
glShaderSource(shader, 1, &src, nullptr);
glCompileShader(shader);
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE)
shaderError(shadertype, shader);
return (shader);
}
Program createProgram(std::string const& name)
{
opengl::checkError(); // avoid propagating an error into the shader compilation
std::stringstream vert;
std::stringstream frag;
std::ifstream vertInput("shaders/" + name + ".vert");
std::ifstream fragInput("shaders/" + name + ".frag");
if (!fragInput || !vertInput)
{
std::cout << "shaders/" + name + ".vert" << std::endl;
std::cout << "shaders/" + name + ".frag" << std::endl;
throw std::runtime_error(strerror(errno));
}
vert << vertInput.rdbuf();
frag << fragInput.rdbuf();
Shader vertex = createShader(GL_VERTEX_SHADER, vert.str().c_str());
Shader fragment = createShader(GL_FRAGMENT_SHADER, frag.str().c_str());
return createProgram<2>({vertex, fragment});
}
Shader::Shader(GLuint shadertype)
: shader(glCreateShader(shadertype)), count(new unsigned int(1u))
{
}
Shader::~Shader()
{
if (!--*count)
{
glDeleteShader(shader);
delete count;
}
}
Shader::Shader(Shader const &s)
: shader(s.shader), count(s.count)
{
++*count;
}
Shader &Shader::operator=(Shader s)
{
std::swap(s.count, count);
std::swap(s.shader, shader);
return *this;
}
Shader::operator GLuint() const
{
return shader;
}
Program::Program()
: program(glCreateProgram()), count(new unsigned int(1u))
{
}
Program::~Program()
{
if (!--*count)
{
glDeleteProgram(program);
delete count;
}
}
Program::Program(Program const &s)
: program(s.program), count(s.count)
{
++*count;
}
Program &Program::operator=(Program s)
{
std::swap(s.count, count);
std::swap(s.program, program);
return *this;
}
Program::operator GLuint() const
{
return program;
}
GLint Program::getAttribLocation(char const *name) const
{
GLint result = glGetAttribLocation(*this, name);
if (result == -1)
throw std::runtime_error(std::string("Failed to retrieve shader input variable: ") + name);
return result;
}
Buffer::Buffer()
: buffer(0u), count(new unsigned int(1u))
{
glGenBuffers(1, &buffer);
}
Buffer::~Buffer()
{
if (!--*count)
{
glDeleteBuffers(1, &buffer);
delete count;
}
}
Buffer::Buffer(Buffer const &s)
: buffer(s.buffer), count(s.count)
{
++*count;
}
Buffer &Buffer::operator=(Buffer s)
{
std::swap(s.count, count);
std::swap(s.buffer, buffer);
return *this;
}
Buffer::operator GLuint() const
{
return buffer;
}
Framebuffer::Framebuffer()
: framebuffer(0u), count(new unsigned int(1u))
{
glGenFramebuffers(1, &framebuffer);
}
Framebuffer::~Framebuffer()
{
if (!--*count)
{
glDeleteFramebuffers(1, &framebuffer);
delete count;
}
}
Framebuffer::Framebuffer(Framebuffer const &s)
: framebuffer(s.framebuffer), count(s.count)
{
++*count;
}
Framebuffer &Framebuffer::operator=(Framebuffer s)
{
std::swap(s.count, count);
std::swap(s.framebuffer, framebuffer);
return *this;
}
Framebuffer::operator GLuint() const
{
return framebuffer;
}
Texture::Texture()
: texture(0u), count(new unsigned int(1u))
{
glGenTextures(1, &texture);
}
Texture::~Texture()
{
if (!--*count)
{
glDeleteTextures(1, &texture);
delete count;
}
}
Texture::Texture(Texture const &s)
: texture(s.texture), count(s.count)
{
++*count;
}
Texture &Texture::operator=(Texture s)
{
std::swap(s.count, count);
std::swap(s.texture, texture);
return *this;
}
Texture::operator GLuint() const
{
return texture;
}
Vao::Vao()
: vao(0u), count(new unsigned int(1u))
{
glGenVertexArrays(1, &vao);
}
Vao::~Vao()
{
if (!--*count)
{
glDeleteVertexArrays(1, &vao);
delete count;
}
}
Vao::Vao(Vao const &s)
: vao(s.vao), count(s.count)
{
++*count;
}
Vao &Vao::operator=(Vao s)
{
std::swap(s.count, count);
std::swap(s.vao, vao);
return *this;
}
Vao::operator GLuint() const
{
return vao;
}
void setUniform(claws::vect<float, 2> const data, char const *target, Program program)
{
glUniform2f(glGetUniformLocation(program, target), data[0], data[1]);
}
void setUniform(claws::vect<float, 3> const data, char const *target, Program program)
{
glUniform3f(glGetUniformLocation(program, target), data[0], data[1], data[2]);
}
void setUniform(claws::vect<float, 4> const data, char const *target, Program program)
{
glUniform4f(glGetUniformLocation(program, target), data[0], data[1], data[2], data[3]);
}
void setUniform(int const data, char const *target, Program program)
{
glUniform1i(glGetUniformLocation(program, target), data);
}
}
|
50c473945715115d9a32632d707047a2b6d46f99
|
a186bf948ac29f3696238e3677f0cf0138fb6860
|
/Atividades/Caue_Gabriel/lista 4/CAUE-LISTA-4-EX.4.cpp
|
2147cfd1245f52986900b6b1d654db4c1fc4fab6
|
[] |
no_license
|
professorlineu/PROA3-2019-2
|
b8c3c944884e847370940a9a48fe580bfea9a4d3
|
84f1cf48598cc925d56e2ed0164c561ae7f5249e
|
refs/heads/master
| 2020-06-25T16:38:52.992529
| 2019-11-25T22:33:16
| 2019-11-25T22:33:16
| 199,367,654
| 0
| 0
| null | null | null | null |
ISO-8859-1
|
C++
| false
| false
| 712
|
cpp
|
CAUE-LISTA-4-EX.4.cpp
|
/**********************************************************
- Autor: CAUE GABRIEL
- Descriรงรฃo: LISTA 4 - EX.
**********************************************************/
#include <iostream>
#include <locale.h>
#include <cstdlib>
using namespace std;
int main()
{
//Declaraรงรฃo de variรกveis
int i = 0;
int iValor = 0;
//Configuraรงรฃo da tela de saรญda
setlocale(LC_ALL,"");
system("color F45");
//Cรณdigo do programa
cout << "Digite o nรบmero da tabuada desejada: ";
cin >> iValor;
while (i < 10)
{
i = i + 1;
cout << iValor << " X " << i << " = " << iValor * i << endl;
}
return 0;
}
|
ca5d037007ebe48b5726205ecb6fb7152e8c9c8a
|
e9786f00a5f9e59f1604f405bba535104926439f
|
/Editor/Sources/o2Editor/Core/Properties/IObjectPropertiesViewer.h
|
8f503d7f515411da8d07056c9ff15dea5fecae4e
|
[
"MIT"
] |
permissive
|
brucelevis/o2
|
0953532f270736c5b3fbb31fabc0ab72f1ddf8d0
|
29085e7c3ba86a54aacfada666adea755ea7b1ee
|
refs/heads/master
| 2023-09-02T04:48:48.716244
| 2021-11-07T17:07:30
| 2021-11-07T17:07:30
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,990
|
h
|
IObjectPropertiesViewer.h
|
#pragma once
#include "o2/Scene/UI/Widgets/VerticalLayout.h"
#include "o2/Utils/Basic/IObject.h"
#include "o2/Utils/ValueProxy.h"
#include "o2Editor/Core/Properties/PropertiesContext.h"
using namespace o2;
namespace o2
{
class VerticalLayout;
}
namespace Editor
{
class IPropertyField;
// ----------------------------------------------------------------------------------
// Object properties viewer interface. Used in IObjectProperty and IObjectPtrProperty
// Override this class to create new object properties viewer
// ----------------------------------------------------------------------------------
class IObjectPropertiesViewer : public IObject
{
public:
typedef Function<void(IPropertyField*)> OnChangedFunc;
typedef Function<void(const String&, const Vector<DataDocument>&, const Vector<DataDocument>&)> OnChangeCompletedFunc;
public:
OnChangedFunc onChanged; // Immediate change value by user event
OnChangeCompletedFunc onChangeCompleted; // Change completed by user event
String path; // Path to viewing object fields
public:
// Default constructor
IObjectPropertiesViewer();
// Refreshing controls and properties by target objects
void Refresh(const Vector<Pair<IObject*, IObject*>>& targetObjets);
// Returns viewing objects base type
virtual const Type* GetViewingObjectType() const;
// Returns viewing objects base type by static function
static const Type* GetViewingObjectTypeStatic();
// Sets parent context
void SetParentContext(PropertiesContext* context);
// Returns view widget
Spoiler* GetSpoiler();
// Sets is header enabled and properties can be collapsed in spoiler
virtual void SetHeaderEnabled(bool enabled);
// Returns is header enabled
bool IsHeaderEnabled() const;
// Expands or collapses spoiler
virtual void SetExpanded(bool expanded);
// Returns is spoiler expanded
bool IsExpanded() const;
// Sets spoiler caption
virtual void SetCaption(const WString& caption);
// Returns caption
const WString& GetCaption() const;
// Returns is viewer empty
bool IsEmpty() const;
IOBJECT(IObjectPropertiesViewer);
protected:
Spoiler* mSpoiler = nullptr; // Properties spoiler. Expands forcible when viewer hasn't header
bool mHeaderEnabled = true; // Is header enabled and properties hiding in spoiler
bool mPropertiesBuilt = false; // True when properties built at first refreshing
Vector<Pair<IObject*, IObject*>> mTargetObjets; // Target objects
PropertiesContext mPropertiesContext; // Field properties information
OnChangeCompletedFunc mOnChildFieldChangeCompleted; // Default field change completed callback, calls
// inChangeCompleted from this with full combined path
protected:
// Creates spoiler for properties
virtual Spoiler* CreateSpoiler();
// It is called when header enable changed
virtual void OnHeaderEnableChanged(bool enabled) {}
// Checks if properties need to be rebuilt, rebuilds if necessary; returns true when properties was rebuilt
virtual bool CheckBuildProperties(const Vector<Pair<IObject*, IObject*>>& targetObjets);
// It is called when the viewer is refreshed, builds properties, and places them in mPropertiesContext
virtual void RebuildProperties(const Vector<Pair<IObject*, IObject*>>& targetObjets) {}
// It is called when viewer is refreshed
virtual void OnRefreshed(const Vector<Pair<IObject*, IObject*>>& targetObjets) {}
// This is called when the viewer is freed
virtual void OnFree() {}
// It is called when some child field were changed
void OnFieldChangeCompleted(const String& path, const Vector<DataDocument>& before,
const Vector<DataDocument>& after);
friend class Properties;
};
// --------------------------------------
// Specialize object properties interface
// --------------------------------------
template<typename _object_type>
class TObjectPropertiesViewer : public IObjectPropertiesViewer
{
public:
// Returns viewing objects base type
const Type* GetViewingObjectType() const override;
// Returns viewing objects base type by static function
static const Type* GetViewingObjectTypeStatic();
IOBJECT(TObjectPropertiesViewer<_object_type>);
};
template<typename _object_type>
const Type* TObjectPropertiesViewer<_object_type>::GetViewingObjectType() const
{
return GetViewingObjectTypeStatic();
}
template<typename _object_type>
const Type* TObjectPropertiesViewer<_object_type>::GetViewingObjectTypeStatic()
{
return &TypeOf(_object_type);
}
}
CLASS_BASES_META(Editor::IObjectPropertiesViewer)
{
BASE_CLASS(o2::IObject);
}
END_META;
CLASS_FIELDS_META(Editor::IObjectPropertiesViewer)
{
FIELD().NAME(onChanged).PUBLIC();
FIELD().NAME(onChangeCompleted).PUBLIC();
FIELD().NAME(path).PUBLIC();
FIELD().DEFAULT_VALUE(nullptr).NAME(mSpoiler).PROTECTED();
FIELD().DEFAULT_VALUE(true).NAME(mHeaderEnabled).PROTECTED();
FIELD().DEFAULT_VALUE(false).NAME(mPropertiesBuilt).PROTECTED();
FIELD().NAME(mTargetObjets).PROTECTED();
FIELD().NAME(mPropertiesContext).PROTECTED();
FIELD().NAME(mOnChildFieldChangeCompleted).PROTECTED();
}
END_META;
CLASS_METHODS_META(Editor::IObjectPropertiesViewer)
{
typedef const Vector<Pair<IObject*, IObject*>>& _tmp1;
typedef const Vector<Pair<IObject*, IObject*>>& _tmp2;
typedef const Vector<Pair<IObject*, IObject*>>& _tmp3;
typedef const Vector<Pair<IObject*, IObject*>>& _tmp4;
PUBLIC_FUNCTION(void, Refresh, _tmp1);
PUBLIC_FUNCTION(const Type*, GetViewingObjectType);
PUBLIC_STATIC_FUNCTION(const Type*, GetViewingObjectTypeStatic);
PUBLIC_FUNCTION(void, SetParentContext, PropertiesContext*);
PUBLIC_FUNCTION(Spoiler*, GetSpoiler);
PUBLIC_FUNCTION(void, SetHeaderEnabled, bool);
PUBLIC_FUNCTION(bool, IsHeaderEnabled);
PUBLIC_FUNCTION(void, SetExpanded, bool);
PUBLIC_FUNCTION(bool, IsExpanded);
PUBLIC_FUNCTION(void, SetCaption, const WString&);
PUBLIC_FUNCTION(const WString&, GetCaption);
PUBLIC_FUNCTION(bool, IsEmpty);
PROTECTED_FUNCTION(Spoiler*, CreateSpoiler);
PROTECTED_FUNCTION(void, OnHeaderEnableChanged, bool);
PROTECTED_FUNCTION(bool, CheckBuildProperties, _tmp2);
PROTECTED_FUNCTION(void, RebuildProperties, _tmp3);
PROTECTED_FUNCTION(void, OnRefreshed, _tmp4);
PROTECTED_FUNCTION(void, OnFree);
PROTECTED_FUNCTION(void, OnFieldChangeCompleted, const String&, const Vector<DataDocument>&, const Vector<DataDocument>&);
}
END_META;
META_TEMPLATES(typename _object_type)
CLASS_BASES_META(Editor::TObjectPropertiesViewer<_object_type>)
{
BASE_CLASS(Editor::IObjectPropertiesViewer);
}
END_META;
META_TEMPLATES(typename _object_type)
CLASS_FIELDS_META(Editor::TObjectPropertiesViewer<_object_type>)
{
}
END_META;
META_TEMPLATES(typename _object_type)
CLASS_METHODS_META(Editor::TObjectPropertiesViewer<_object_type>)
{
PUBLIC_FUNCTION(const Type*, GetViewingObjectType);
PUBLIC_STATIC_FUNCTION(const Type*, GetViewingObjectTypeStatic);
}
END_META;
|
3cc8a47d5dd6cb43353adc1a565951208cb53955
|
d9650fc6700b0028fe7d7523df0256919ecc2ab3
|
/src/getPct.cpp
|
cedef6bfa157726ede292a6a7b472a8c14b8ed53
|
[] |
no_license
|
matengyue/image-retrieval
|
c72a733029dd6d75e29c8e24f68ee2cdc2880785
|
96005c5121989d8e23e0055da9ac171f26c14b89
|
refs/heads/master
| 2016-09-13T20:28:37.636062
| 2016-04-21T08:26:44
| 2016-04-21T08:26:44
| 56,752,167
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 755
|
cpp
|
getPct.cpp
|
/*************************************************************************
> File Name: getJpg.cpp
> Author: lumujin
> Mail: lumujin@icloud.com
> Created Time: 2016ๅนด04ๆ19ๆฅ ๆๆไบ 10ๆถ46ๅ01็ง
************************************************************************/
#include <stdio.h>
#include <string>
#include <stdlib.h>
#include <fstream>
#include <vector>
#include <iostream>
using namespace std;
int main(int argc, char ** argv){
ifstream infile;
infile.open(argv[1], ios::in);
if (!infile){
cout << "Can not open the file." << endl;
return 0;
}
string str, com;
while (!infile.eof()){
infile >> str;
com = "cat " + str + " >> line";
system(com.c_str());
}
return 0;
}
|
b78bec0829aff55f4eb32fefca46119c04f2b36a
|
3dd64a20b6f8e5d37ba23ea71556b4f8b40be58c
|
/codeforces/CF379A.cpp
|
707752ee6b28e75418f7c7b1bac58b11055744ba
|
[] |
no_license
|
abhikumar002/Competitive-Programming
|
0a400653861090a7ace7438ffaa328c1a94a77e4
|
5e84dbd3adc7fea59f5af92d39ceec30b85d52c8
|
refs/heads/main
| 2023-04-14T10:10:36.862643
| 2021-04-27T07:48:02
| 2021-04-27T07:48:02
| 362,025,611
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 226
|
cpp
|
CF379A.cpp
|
#include <iostream>
using namespace std;
int main() {
// your code goes here
int a,b; cin>>a>>b;
int thour=a;
while(a>=b)
{
thour+=(a/b);
a=(a/b)+(a%b);
}
cout<<thour<<endl;
return 0;
}
|
6cdfaaac8e02add85e882943a6292272a47b1c2f
|
27b07ebb69f50924865f7da0fbde1f692594270f
|
/include/LTRE/math/vec3.hpp
|
8080b99c6894f0f16bf0084b6c6bd5f9fcd2893f
|
[
"MIT"
] |
permissive
|
yumcyaWiz/LTRE
|
68bb5b3ede7a1e228f4bd2f1a0ce9a8070abb199
|
dd65125bb133c345a10a3cf3d4c2a330b38ee82b
|
refs/heads/master
| 2023-07-25T07:32:50.394970
| 2021-08-29T22:05:13
| 2021-08-29T22:05:13
| 368,081,973
| 3
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,402
|
hpp
|
vec3.hpp
|
#ifndef _LTRE_VEC3_H
#define _LTRE_VEC3_H
#include <cassert>
#include <cmath>
#include <iostream>
#include "LTRE/core/constant.hpp"
namespace LTRE {
struct Vec3 {
float v[3];
static constexpr unsigned int nComponents = 3;
explicit constexpr Vec3() : v{0, 0, 0} {}
explicit constexpr Vec3(float x) : v{x, x, x} {}
explicit constexpr Vec3(float x, float y, float z) : v{x, y, z} {}
explicit constexpr operator bool() const {
return v[0] != 0 && v[1] != 0 && v[2] != 0;
}
constexpr bool operator>(const Vec3& v) const {
return this->v[0] > v[0] && this->v[1] > v[1] && this->v[2] > v[2];
}
constexpr bool operator>=(const Vec3& v) const {
return this->v[0] >= v[0] && this->v[1] >= v[1] && this->v[2] >= v[2];
}
constexpr bool operator<(const Vec3& v) const {
return this->v[0] < v[0] && this->v[1] < v[1] && this->v[2] < v[2];
}
constexpr bool operator<=(const Vec3& v) const {
return this->v[0] <= v[0] && this->v[1] <= v[1] && this->v[2] <= v[2];
}
constexpr bool operator==(const Vec3& v) const {
return this->v[0] == v[0] && this->v[1] == v[1] && this->v[2] == v[2];
}
constexpr const float& operator[](int i) const {
assert(i >= 0 && i < 3);
return v[i];
}
constexpr float& operator[](int i) {
assert(i >= 0 && i < 3);
return v[i];
}
constexpr Vec3 operator-() const { return Vec3(-v[0], -v[1], -v[2]); }
constexpr Vec3& operator+=(const Vec3& v) {
for (int i = 0; i < 3; ++i) {
this->v[i] += v[i];
}
return *this;
}
constexpr Vec3& operator-=(const Vec3& v) {
for (int i = 0; i < 3; ++i) {
this->v[i] -= v[i];
}
return *this;
}
constexpr Vec3& operator*=(const Vec3& v) {
for (int i = 0; i < 3; ++i) {
this->v[i] *= v[i];
}
return *this;
}
constexpr Vec3& operator*=(float k) {
for (int i = 0; i < 3; ++i) {
this->v[i] *= k;
}
return *this;
}
constexpr Vec3& operator/=(const Vec3& v) {
for (int i = 0; i < 3; ++i) {
this->v[i] /= v[i];
}
return *this;
}
constexpr Vec3& operator/=(float k) {
for (int i = 0; i < 3; ++i) {
this->v[i] /= k;
}
return *this;
}
std::string toString() const {
return "(" + std::to_string(v[0]) + ", " + std::to_string(v[1]) + ", " +
std::to_string(v[2]) + ")";
}
bool isNan() const {
return std::isnan(v[0]) || std::isnan(v[1]) || std::isnan(v[2]);
}
};
inline constexpr Vec3 operator+(const Vec3& v1, const Vec3& v2) {
Vec3 ret;
for (int i = 0; i < 3; ++i) {
ret[i] = v1[i] + v2[i];
}
return ret;
}
inline constexpr Vec3 operator+(const Vec3& v1, float k) {
Vec3 ret;
for (int i = 0; i < 3; ++i) {
ret[i] = v1[i] + k;
}
return ret;
}
inline constexpr Vec3 operator+(float k, const Vec3& v2) {
Vec3 ret;
for (int i = 0; i < 3; ++i) {
ret[i] = k + v2[i];
}
return ret;
}
inline constexpr Vec3 operator-(const Vec3& v1, const Vec3& v2) {
Vec3 ret;
for (int i = 0; i < 3; ++i) {
ret[i] = v1[i] - v2[i];
}
return ret;
}
inline constexpr Vec3 operator-(const Vec3& v1, float k) {
Vec3 ret;
for (int i = 0; i < 3; ++i) {
ret[i] = v1[i] - k;
}
return ret;
}
inline constexpr Vec3 operator-(float k, const Vec3& v2) {
Vec3 ret;
for (int i = 0; i < 3; ++i) {
ret[i] = k - v2[i];
}
return ret;
}
inline constexpr Vec3 operator*(const Vec3& v1, const Vec3& v2) {
Vec3 ret;
for (int i = 0; i < 3; ++i) {
ret[i] = v1[i] * v2[i];
}
return ret;
}
inline constexpr Vec3 operator*(const Vec3& v1, float k) {
Vec3 ret;
for (int i = 0; i < 3; ++i) {
ret[i] = v1[i] * k;
}
return ret;
}
inline constexpr Vec3 operator*(float k, const Vec3& v2) {
Vec3 ret;
for (int i = 0; i < 3; ++i) {
ret[i] = k * v2[i];
}
return ret;
}
inline constexpr Vec3 operator/(const Vec3& v1, const Vec3& v2) {
Vec3 ret;
for (int i = 0; i < 3; ++i) {
ret[i] = v1[i] / v2[i];
}
return ret;
}
inline constexpr Vec3 operator/(const Vec3& v1, float k) {
Vec3 ret;
for (int i = 0; i < 3; ++i) {
ret[i] = v1[i] / k;
}
return ret;
}
inline constexpr Vec3 operator/(float k, const Vec3& v2) {
Vec3 ret;
for (int i = 0; i < 3; ++i) {
ret[i] = k / v2[i];
}
return ret;
}
inline constexpr float dot(const Vec3& v1, const Vec3& v2) {
float ret = 0;
for (int i = 0; i < 3; ++i) {
ret += v1[i] * v2[i];
}
return ret;
}
inline constexpr Vec3 cross(const Vec3& v1, const Vec3& v2) {
return Vec3(v1[1] * v2[2] - v1[2] * v2[1], v1[2] * v2[0] - v1[0] * v2[2],
v1[0] * v2[1] - v1[1] * v2[0]);
}
inline constexpr float length(const Vec3& v) { return std::sqrt(dot(v, v)); }
inline constexpr float length2(const Vec3& v) { return dot(v, v); }
inline constexpr Vec3 normalize(const Vec3& v) { return v / length(v); }
inline std::ostream& operator<<(std::ostream& stream, const Vec3& v) {
stream << "(" << v[0] << ", " << v[1] << ", " << v[2] << ")";
return stream;
}
inline constexpr Vec3 worldToLocal(const Vec3& v, const Vec3& lx,
const Vec3& ly, const Vec3& lz) {
return Vec3(dot(v, lx), dot(v, ly), dot(v, lz));
}
inline constexpr Vec3 localToWorld(const Vec3& v, const Vec3& lx,
const Vec3& ly, const Vec3& lz) {
Vec3 ret;
for (int i = 0; i < 3; ++i) {
ret[i] = v[0] * lx[i] + v[1] * ly[i] + v[2] * lz[i];
}
return ret;
}
inline constexpr Vec3 sphericalToCartesian(float theta, float phi) {
const float cosTheta = std::cos(theta);
const float sinTheta = std::sin(theta);
return Vec3(std::cos(phi) * sinTheta, cosTheta, std::sin(phi) * sinTheta);
}
inline constexpr void cartesianToSpherical(const Vec3& v, float& theta,
float& phi) {
phi = std::atan2(v[2], v[0]);
if (phi < 0) phi += PI_MUL_2;
theta = std::acos(std::clamp(v[1], -1.0f, 1.0f));
}
inline void orthonormalBasis(const Vec3& n, Vec3& t, Vec3& b) {
if (std::abs(n[1]) < 0.9f) {
t = normalize(cross(n, Vec3(0, 1, 0)));
} else {
t = normalize(cross(n, Vec3(0, 0, -1)));
}
b = normalize(cross(t, n));
}
inline constexpr Vec3 pow(const Vec3& v, float k) {
return Vec3(std::pow(v[0], k), std::pow(v[1], k), std::pow(v[2], k));
}
inline constexpr Vec3 lerp(const Vec3& v1, const Vec3& v2, float k) {
return (1.0f - k) * v1 + k * (v2 - v1);
}
} // namespace LTRE
#endif
|
8896852865413e6a4940d159b0c6a3723089eb51
|
7e1e01498a2c9dc2c0c183463fd746ee73128e1f
|
/DirectX FBX/DirectX FBX/Model.cpp
|
f32834161b75434c22c8b6b972661cb8138de853
|
[] |
no_license
|
parksch/SuChanPark
|
b91d3653eeb93fe81c6d1081bc48cb0af99658b6
|
fd214f322c6766add20bdd90c057b0d3f8662879
|
refs/heads/master
| 2023-04-27T20:38:57.667603
| 2021-05-17T02:18:24
| 2021-05-17T02:18:24
| 265,213,869
| 0
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 2,461
|
cpp
|
Model.cpp
|
#include "Model.h"
Model::Model()
{
}
Model::~Model()
{
}
void Model::Input()
{
}
bool Model::SetGeometry(LPDIRECT3DDEVICE9 device)
{
void *verticesPtr;
void *indicesPtr;
long vertexSize = m_Parts.vertices.size() * sizeof(Vertex);
long indexSize = m_Parts.myindex.size() * sizeof(MYINDEX);
if (FAILED(device->CreateIndexBuffer(
indexSize,
0,
D3DFMT_INDEX16,
D3DPOOL_DEFAULT,
&pIB,
NULL)))
return false;
if (FAILED(device->CreateVertexBuffer(
vertexSize,
0,
D3DFVF_CUSTOMVERTEX,
D3DPOOL_DEFAULT,
&pVB,
NULL)))
return false;
if (FAILED(pIB->Lock(
0,
indexSize,
(void**)&indicesPtr,
0)))
return false;
if (FAILED(pVB->Lock(
0,
vertexSize,
(void**)&verticesPtr,
0)))
return false;
memcpy(indicesPtr, m_Parts.myindex.data(), indexSize);
memcpy(verticesPtr, m_Parts.vertices.data(), vertexSize);
pVB->Unlock();
pIB->Unlock();
return true;
}
void Model::Render(LPDIRECT3DDEVICE9 device, D3DXMATRIX& worldViewProj)
{
device->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
device->SetTexture(0, m_Parts.pDiffuseTexture); /// 0๋ฒ ํ
์ค์ณ ์คํ
์ด์ง์ ํ
์ค์ณ ๊ณ ์ (๋ฒฝ๋ฉด)
device->SetTexture(1, m_Parts.pSpecularTexture);
device->SetTexture(2, m_Parts.pNormalTexture);
device->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
device->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
device->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
device->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_ADD);
device->SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_TEXTURE);
device->SetTextureStageState(1, D3DTSS_COLORARG2, D3DTA_CURRENT);
//device->SetTextureStageState(2, D3DTSS_COLOROP, D3DTOP_MODULATE);
//device->SetTextureStageState(2, D3DTSS_COLORARG1, D3DTA_TEXTURE);
//device->SetTextureStageState(2, D3DTSS_COLORARG2, D3DTA_CURRENT);
device->SetTransform(D3DTS_WORLD, &worldViewProj);
device->SetStreamSource(0, pVB, 0, sizeof(Vertex));
device->SetIndices(pIB);
device->SetFVF(D3DFVF_CUSTOMVERTEX);
device->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, m_Parts.vertexCount, 0, m_Parts.polyCount);
}
void Model::Release()
{
if (m_Parts.pDiffuseTexture != NULL)
m_Parts.pDiffuseTexture->Release();
if (m_Parts.pNormalTexture != NULL)
m_Parts.pNormalTexture->Release();
if (m_Parts.pSpecularTexture != NULL)
m_Parts.pSpecularTexture->Release();
if (pIB != NULL)
pIB->Release();
if (pVB != NULL)
pVB->Release();
}
|
31f1e1cb8e31bd0bf706eaddfe1872e7cc721fff
|
864d0e1c951f044379ac243d2d759371044af3dd
|
/BoilerEfficiency/BoilerEffi.cpp
|
61d3441c892347cf6b16eec332816939f8c8fcde
|
[] |
no_license
|
erinwl/AbnormalDetection
|
572be6f69e781ebcc882de7e5b60456b9174d20c
|
19beec64bae1bdd3de191affa7eefee394045fee
|
refs/heads/master
| 2020-03-27T23:45:11.660085
| 2018-04-07T05:38:05
| 2018-04-07T05:38:05
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 6,469
|
cpp
|
BoilerEffi.cpp
|
#include "BoilerEffi.h"
using namespace Boiler;
BoilerEffi::BoilerEffi()
{
}
BoilerEffi::BoilerEffi(InputArg _input)
{
InitInput(_input);
m_smokeLoss = new SmokeLoss(m_input.basis, m_input.m_aerfa,Qnet, m_input.m_file, m_input.t0, m_input.tpy);//่ฎก็ฎๆ็ๆๅคฑ
m_solidLoss = new SolidLoss(Qnet,m_input.basis.Aar,_input.m_aerfa);
}
BoilerEffi::~BoilerEffi()
{
if(m_smokeLoss)
delete m_smokeLoss;
if(m_solidLoss)
delete m_solidLoss;
}
void Boiler::BoilerEffi::UpdateBoilerEffi()
{
if (m_smokeLoss)
delete m_smokeLoss;
if (m_solidLoss)
delete m_solidLoss;
InitInput(m_input);
m_smokeLoss = new SmokeLoss(m_input.basis, m_input.m_aerfa, Qnet, m_input.m_file, m_input.t0, m_input.tpy);//่ฎก็ฎๆ็ๆๅคฑ
m_solidLoss = new SolidLoss(Qnet, m_input.basis.Aar,m_input.m_aerfa);
}
bool Boiler::BoilerEffi::ElementalAnalysis(ReceivedBasis _basis)//ๆฃๆต็
ค่ดจ
{
if (_basis.Aar < 0 || _basis.Car < 0 || _basis.Mar < 0 || _basis.Nar < 0 || _basis.Oar < 0 || _basis.Sar < 0)
return false;
if (fabs(_basis.Aar + _basis.Car + _basis.Har + _basis.Mar + _basis.Nar + _basis.Oar + _basis.Sar - 100) > ebsilon)
return false;
return true;
}
bool BoilerEffi::CheckAerfa(double _aerfa)//ๆฃๆต่ฟ้็ฉบๆฐ็ณปๆฐ
{
if (_aerfa < 0)
return false;
return true;
}
void BoilerEffi::InitInput(InputArg _input)
{
if (BoilerEffi::ElementalAnalysis(_input.basis) == false)
{
Exception *ex = new Exception(Exception::type::CoalComposition);
throw ex;
}
if (CheckAerfa(_input.m_aerfa) == false)
{
Exception *ex = new Exception(Exception::type::ExcessAir);
throw ex;
}
m_input = _input;
Qgr = 339 *m_input.basis.Car + 1256 * m_input.basis.Har + 109 * m_input.basis.Sar - 109 * m_input.basis.Oar;
Qnet = Qgr - 2500 * (9 * m_input.basis.Har / 100 + m_input.basis.Mar / 100);
}
SmokeLoss::SmokeLoss(ReceivedBasis _basis, double _aerfa,double Qnet, QString file, double t0, double tpy)//ๆ็ๆๅคฑๆ้ ๅฝๆฐ็จๆฅ่ฎก็ฎๆ็ๆๅคฑ
{
V0 = 0.0899*(_basis.Car + 0.375*_basis.Sar) + 0.265*_basis.Har - 0.0333*_basis.Oar;
L0 = 1.293*V0;
VRO2 = 1.866*_basis.Car / 100 + 0.7*_basis.Sar / 100;
V0N2 = 0.8*_basis.Nar / 100 + 0.79*V0;
V0H2O = 11.1*_basis.Har / 100 + 1.24*_basis.Mar / 100 + 0.0161*V0;
V0gy = VRO2 + V0N2;
V0y = V0gy + V0H2O;
Vy = V0y + (_aerfa - 1)*V0 + 0.0161*(_aerfa - 1)*V0;
Vgy = V0gy + (_aerfa - 1)*V0;
VH2O = Vy - Vgy;
VN2 = V0N2 + 0.79*(_aerfa - 1)*V0;
if (GetHeatCapacity(file) == false)
{
Exception *ex = new Exception(Exception::type::FileError);
throw ex;
}
double qCO2 = 0;//ๅไฝไฝ็งฏCO2ๅธ็ญ้
double qN2 = 0;//ๅไฝไฝ็งฏN2ๅธ็ญ้
double qH2O = 0;//ๅไฝไฝ็งฏH2Oๅธ็ญ้
for (int i = 0; i < CpCO2.count(); i++)
{
qCO2 += 1.0 / (i + 1)*CpCO2.at(i)*pow(tpy, i + 1);
qCO2 -= 1.0 / (i + 1)*CpCO2.at(i)*pow(t0, i + 1);
qN2 += 1.0 / (i + 1)*CpN2.at(i)*pow(tpy, i + 1);
qN2 -= 1.0 / (i + 1)*CpN2.at(i)*pow(t0, i + 1);
qH2O += 1.0 / (i + 1)*CpH2O.at(i)*pow(tpy, i + 1);
qH2O -= 1.0 / (i + 1)*CpH2O.at(i)*pow(t0, i + 1);
}
Qgy = VRO2*qCO2 + VN2*qN2;
Q2 = Qgy + VH2O*qH2O;
q2 = Q2 / Qnet * 100;
}
SmokeLoss::~SmokeLoss()
{
}
InputArg::InputArg()
{
}
InputArg::~InputArg()
{
}
bool SmokeLoss::GetHeatCapacity(QString file)
{
Parse::ParseText parse(file);
for (int i = 1; i < parse.rowCount; i++)
{
CpCO2.append(parse.Serch(i, 1).toDouble());
CpN2.append(parse.Serch(i, 2).toDouble());
CpH2O.append(parse.Serch(i, 3).toDouble());
}
return true;
}
QString Exception::ShowError()
{
return Converter.ToString(m_type);
}
Boiler::SolidLoss::SolidLoss(double _Qnet,double _Aar,double _Aerfa)
{
Qnet = _Qnet;
Aar = _Aar;
double O2[] = { 5.54,5.39,4.43,4.43,5.91,4.64,4.49,4.59,4.82,4.64,4.25 };
double Cfh[] = { 0.15,0.17,0.19,0.15,0.18,0.24,0.46,0.35,0.49,0.57,0.33 };
double Clz[] = { 0.69,1.35,1.25,1.53,1.41,1.48,1.98,1.30,2.22,2.71,2.23 };
int size = sizeof(O2);
if (size != sizeof(Cfh) || size != sizeof(Clz))
{
Exception *ex = new Exception(Exception::type::FhOrLzNumError);
throw ex;
}
int num = size / sizeof(double);
fh_model = TrainModel(O2, Cfh, num);
lz_model = TrainModel(O2, Clz, num);
q4=GetSolidLossFromArefa(_Aerfa);
}
double Boiler::SolidLoss::GetSolidLossFromO(double O2)
{
//O2 = 4.43;
double Cfh = Predict(fh_model, O2);
double Clz = Predict(lz_model, O2);
double solidLoss = (0.9*Cfh / (100 - Cfh) + 0.1*Clz / (100 - Clz)) * 32700 * Aar / Qnet;
return solidLoss;
}
double Boiler::SolidLoss::GetSolidLossFromArefa(double Arefa)
{
double O2 = 21 - 21 / Arefa;
return GetSolidLossFromO(O2);
}
Boiler::SolidLoss::~SolidLoss()
{
if (fh_model)
free(fh_model);
if (lz_model)
free(lz_model);
}
void SolidLoss::init_param() {
param.svm_type = EPSILON_SVR;
param.kernel_type = RBF;
param.degree = 3;
param.gamma = 0.0001;
param.coef0 = 0;
param.nu = 0.5;
param.cache_size = 100;
param.C = 10;
param.eps = 1e-5;
param.shrinking = 1;
param.probability = 0;
param.nr_weight = 0;
param.weight_label = NULL;
param.weight = NULL;
param.coef0 = 1;
param.p = 0.1;
//param.
}
svm_model* Boiler::SolidLoss::TrainModel(double* x, double* y, int num)
{
svm_model *model;
init_param();
if (param.gamma == 0) param.gamma = 0.5;
svm_problem prob;
prob.l = num; //ๆ ทๆฌๆฐ
prob.y = new double[prob.l];
double d;
int probfeature = 1; //ๆ ทๆฌ็นๅพ็ปดๆฐ
svm_node *x_space = new svm_node[(probfeature + 1)*prob.l];//ๆ ทๆฌ็นๅพๅญๅจ็ฉบ้ด
prob.x = new svm_node *[prob.l]; //ๆฏไธไธชXๆๅไธไธชๆ ทๆฌ
for (int index = 0; index < num; index++)
{
int temp_index = index*(probfeature + 1);
x_space[temp_index].index = 1;
x_space[temp_index].value = *(x + index);
x_space[temp_index + 1].index = -1;
prob.x[index] = &x_space[temp_index];///
prob.y[index] = *(y + index);
///ๆฒกๆy
}
const char* string = svm_check_parameter(&prob, ¶m);
model = svm_train(&prob, ¶m);//่ฎญ็ป
// delete[] x_space;
// delete[] prob.x;
// delete[] prob.y;
return model;
}
double Boiler::SolidLoss::Predict(svm_model * model, double input)
{
double output;
svm_node xnode[2];//ๅฎไนๆต่ฏไบ็ปดๆต่ฏๆ ทๆฌ็ปๆไฝ
xnode[0].index = 1;
xnode[0].value = input;
xnode[1].index = -1;
output = svm_predict(model, xnode);
return output;
}
|
486292b65634be05fa3f91dd02c503cbd2dbe166
|
29b2ff977c4e57a3b63eaafa935bf6d4a9380e5d
|
/contributions/cppMpl/src/total.cpp
|
467d8e45cf32dfd011004e442cb7acea84ba9eec
|
[
"MIT"
] |
permissive
|
101companies/101repo
|
65219e9a137e94818702f26a40176e2bf75e0905
|
093caad519c91fcbe5b896c211acc25cc2765a3b
|
refs/heads/master
| 2023-07-20T09:33:04.365782
| 2023-07-14T14:33:47
| 2023-07-14T14:33:47
| 2,828,043
| 17
| 15
|
MIT
| 2023-05-31T18:47:34
| 2011-11-22T13:55:06
|
HTML
|
UTF-8
|
C++
| false
| false
| 174
|
cpp
|
total.cpp
|
#include <iostream>
#include "database.hpp"
#include <hr/operations.hpp>
int main()
{
std::cout << "Total: " << aggregator<all_data>::salary_sum::value << std::endl;
}
|
48585669c8a08fb1a7434d0537032b7ade606690
|
1821422698dd65206e55eb685836ad21da6f7971
|
/llvm/lib/Target/SPIRV/SPIRVEnums.cpp
|
a3af393e790b33744203ce49a05f71d5e9665777
|
[
"NCSA",
"LLVM-exception",
"Apache-2.0"
] |
permissive
|
Duttenheim/fips-LLVM-SPIRV-Backend
|
cdd45db333a547a5518883a39877181b41a19d2f
|
c15265fe48e10c18aff7dcfb3f64f7f38fd0118d
|
refs/heads/feature/spirv-backend
| 2023-09-04T18:12:56.031562
| 2021-11-05T02:20:37
| 2021-11-05T02:20:37
| 382,339,125
| 0
| 0
| null | 2021-11-06T00:29:28
| 2021-07-02T12:26:35
|
C++
|
UTF-8
|
C++
| false
| false
| 2,587
|
cpp
|
SPIRVEnums.cpp
|
//===-- SPIRVEnums.cpp - SPIR-V Enums and Related Functions -----*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file contains macros implementing the enum helper functions defined in
// SPIRVEnums.h, such as getEnumName(Enum e) and getEnumCapabilities(Enum e)
//
//===----------------------------------------------------------------------===//
#include "SPIRVEnums.h"
GEN_ENUM_IMPL(Capability)
GEN_ENUM_IMPL(SourceLanguage)
GEN_ENUM_IMPL(ExecutionModel)
GEN_ENUM_IMPL(AddressingModel)
GEN_ENUM_IMPL(MemoryModel)
GEN_ENUM_IMPL(ExecutionMode)
GEN_ENUM_IMPL(StorageClass)
// Dim must be implemented manually, as "1D" is not a valid C++ naming token
std::string getDimName(Dim::Dim dim) {
switch (dim) {
case Dim::DIM_1D:
return "1D";
case Dim::DIM_2D:
return "2D";
case Dim::DIM_3D:
return "3D";
case Dim::DIM_Cube:
return "Cube";
case Dim::DIM_Rect:
return "Rect";
case Dim::DIM_Buffer:
return "Buffer";
case Dim::DIM_SubpassData:
return "SubpassData";
default:
return "UNKNOWN_Dim";
}
}
GEN_ENUM_IMPL(SamplerAddressingMode)
GEN_ENUM_IMPL(SamplerFilterMode)
GEN_ENUM_IMPL(ImageFormat)
GEN_ENUM_IMPL(ImageChannelOrder)
GEN_ENUM_IMPL(ImageChannelDataType)
GEN_MASK_ENUM_IMPL(ImageOperand)
GEN_MASK_ENUM_IMPL(FPFastMathMode)
GEN_ENUM_IMPL(FPRoundingMode)
GEN_ENUM_IMPL(LinkageType)
GEN_ENUM_IMPL(AccessQualifier)
GEN_ENUM_IMPL(FunctionParameterAttribute)
GEN_ENUM_IMPL(Decoration)
GEN_ENUM_IMPL(BuiltIn)
GEN_MASK_ENUM_IMPL(SelectionControl)
GEN_MASK_ENUM_IMPL(LoopControl)
GEN_MASK_ENUM_IMPL(FunctionControl)
GEN_MASK_ENUM_IMPL(MemorySemantics)
GEN_MASK_ENUM_IMPL(MemoryOperand)
GEN_ENUM_IMPL(Scope)
GEN_ENUM_IMPL(GroupOperation)
GEN_ENUM_IMPL(KernelEnqueueFlags)
GEN_MASK_ENUM_IMPL(KernelProfilingInfo)
namespace MS = MemorySemantics;
namespace SC = StorageClass;
MS::MemorySemantics getMemSemanticsForStorageClass(SC::StorageClass sc) {
switch (sc) {
case SC::StorageBuffer:
case SC::Uniform:
return MS::UniformMemory;
case SC::Workgroup:
return MS::WorkgroupMemory;
case SC::CrossWorkgroup:
return MS::CrossWorkgroupMemory;
case SC::AtomicCounter:
return MS::AtomicCounterMemory;
case SC::Image:
return MS::ImageMemory;
default:
return MS::None;
}
}
DEF_BUILTIN_LINK_STR_FUNC_BODY()
GEN_EXTENSION_IMPL(Extension)
|
e3ce596715fe4e78ffd80b27a03fd34f36803364
|
87d7a6568188b661efb68488881363e54a44508e
|
/pacman_git/ConsolEngine/Field.cpp
|
b7b3fc25eec60577790e362c3a5df9565c7caa90
|
[] |
no_license
|
ZavalniukAlexey/Zavalniuk_Alexey_
|
4cfd5033ba5a284ab167f266566a29cf18ab475e
|
a7d0512131cec42fa36ea2ab34629529aa2c459d
|
refs/heads/master
| 2020-12-11T11:30:15.882154
| 2020-01-20T21:39:46
| 2020-01-20T21:39:46
| 233,834,753
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,979
|
cpp
|
Field.cpp
|
#include "Field.h"
#include <iostream>
#include "BaseApp.h"
Field::Field()
{}
void Field::updateField(int x, int y, char c)
{
field[x][y] = c;
}
void Field::resetField()
{ char f[31][29] = {
"############################", //0
"#............##............#", //1
"#.####.#####.##.#####.####.#", //2
"#.####.#####.##.#####.####.#", //3
"#.####.#####.##.#####.####.#", //4
"#..........................#", //5
"#.####.##.########.##.####.#", //6
"#.####.##.########.##.####.#", //7
"#......##....##....##......#", //8
"######.#####.##.#####.######", //9
"######.#####.##.#####.######", //10
"######.## ##.######", //11
"######.## ######## ## ######", //12
"######.## # # ##.######", //13
" . # # . ", //14
"######.## # # ##.######", //15
"######.## ######## ##.######", //16
"######.## ##.######", //17
"######.##.########.##.######", //18
"######.##.########.##.######", //19
"#............##............#", //20
"#.####.#####.##.#####.####.#", //21
"#.####.#####.##.#####.####.#", //22
"#...##................##...#", //23
"###.##.##.########.##.##.###", //24
"###.##.##.########.##.##.###", //25
"#......##....##....##......#", //26
"#.##########.##.##########.#", //27
"#.##########.##.##########.#", //28
"#..........................#", //29
"############################" //30
};
for (int i = 0; i < 31; i++)
for (int j = 0; j < 29; j++)
this->field[i][j] = f[i][j];
}
int Field::countStars()
{
int counter = 0;
for (int i = 0; i < 31; i++)
for (int j = 0; j < 29; j++)
{
if (this->field[i][j] == '.')
counter++;
}
return counter;
}
int Field::getFieldScore()
{
Field temp;
int stars = temp.countStars();
int fieldScore = (stars - (this->countStars())) * 10;
return fieldScore;
}
char Field::getFieldChar(int i, int j)
{
return field[i][j];
}
void Field::setFieldChar(int i, int j, char s)
{
field[i][j] = s;
}
Field::~Field()
{
}
|
b8960f980004345577140aa57b90f55b5705838f
|
998130ca695e84ac3cb90191168324ba5f252065
|
/sem7/main.cpp
|
57e5fd7ede75d0fcb6291fb279c47b9fe0b2db93
|
[] |
no_license
|
AvramPop/OOP
|
e52e0cb08fc13ab96d57f6d1a5db238efc581fa3
|
68139e87c2a04f0cdc2a4767b12f067c79eb768d
|
refs/heads/master
| 2022-01-13T02:00:13.129245
| 2019-05-30T06:47:50
| 2019-05-30T06:47:50
| 174,018,741
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 715
|
cpp
|
main.cpp
|
#include "ChatSession.h"
#include "ChatWindow.h"
#include "Widget.h"
#include "User.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
ChatSession* session = new ChatSession();
User *user1 = new User{"user1"};
User *user2 = new User{"user2"};
User *user3 = new User{"user3"};
User *user4 = new User{"user4"};
ChatWindow* window1 = new ChatWindow{user1, session};
ChatWindow* window2 = new ChatWindow{user2, session};
ChatWindow* window3 = new ChatWindow{user3, session};
ChatWindow* window4 = new ChatWindow{user4, session};
window1->show();
window2->show();
window3->show();
window4->show();
return a.exec();
}
|
a87325060cbc185c312774611687ffc496f5fade
|
be776c320d6f321ec4e73340e8b52f187fd5ae10
|
/temp/P1311 ้ๆฉๅฎขๆ .cpp
|
c5a4a40c5c502c9bd7c65c78716a6cdc2e8f79e4
|
[] |
no_license
|
Deathcup/NOIP
|
b988296c57416f67972170be9f14aea056f17c4e
|
50991526aff27208b97b41f1742497f8746f2bc8
|
refs/heads/master
| 2021-09-08T16:59:40.964560
| 2021-09-06T06:09:09
| 2021-09-06T06:09:09
| 108,225,834
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,183
|
cpp
|
P1311 ้ๆฉๅฎขๆ .cpp
|
#include<iostream>
#include<cstdio>
#include<cmath>
#include<vector>
#include<cstring>
using namespace std;
const int N=200001;
int st[N][20];
int n,m,p,a,b;
bool flag;
vector<int> e[51];
int read(){
int data=0,w=1;char ch=0;
while(ch!='-'&&(ch<'0'||ch>'9')) ch=getchar();
if(ch=='-') w=-1,ch=getchar();
while(ch>='0'&&ch<='9') data=data*10+ch-'0',ch=getchar();
return data*w;
}
void init(){
for(int j=1;j<=19;j++){
for(int i=1;i+(1<<j)<=n+2;i++){
st[i][j]=min(st[i][j-1],st[i+(1<<(j-1))][j-1]);
}
}
}
int RMQ(int l,int r){
if(l>r) swap(l,r);
int k=log(r-l+1)/log(2.0);
return min(st[l][k],st[r-(1<<k)+1][k]);
}
void init2(){
for(int j=1;j<=19;j++)
for(int i=1;i+(1<<j)-1<=n;i++)
st[i][j]=min(st[i][j-1],st[i+(1<<(j-1))][j-1]);
}
long long ans;
int c[N];
int main(){
memset(st,0x7f,sizeof(st));
n=read();m=read();p=read();
for(int t1,t2,i=1;i<=n;i++){
t1=read();t2=read();
st[i][0]=t2;
c[i]=t1;
e[t1].push_back(t2);
}
init();
for(int k=0;k<m;k++){
for(int i=e[k].size()-1;i>=0;i--){
for(int j=i-1;j>=0;j--){
int a=e[k][i],b=e[k][j];
int t=RMQ(a,b);
if(t<=p){
ans++;
}
}
}
}
cout<<ans<<endl;
}
|
ed773c9b18f9948d6f4fe700b0ec6e66acd58c2b
|
8b5373956aa83717d4d4719ca30b96014e228c42
|
/sdlclib_audio_sound.cpp
|
d0ddbb5043aa64380b33cf5c3fe90ce595d45511
|
[] |
no_license
|
AlexisDurlet/SDLcLib
|
e25dd63eb9f1416f484482785e9c77ca88bcf4bd
|
65b5a8aaeee00d93b53fd3abb9d4e31b4a1e1ab0
|
refs/heads/master
| 2021-01-19T06:08:25.939583
| 2016-08-07T12:24:11
| 2016-08-07T12:24:11
| 65,131,691
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,467
|
cpp
|
sdlclib_audio_sound.cpp
|
#include "sdlclib.h"
TSDLcAudioSound * TSDLcAudioSound::m_pChannels[];
TSDLcAudioSound::TSDLcAudioSound() :
m_pSound(nullptr),
m_iCurrentChannel(-2),
m_bActive(false)
{}
TSDLcAudioSound::~TSDLcAudioSound()
{
Destroy();
}
void TSDLcAudioSound::PlayCheck()
{
SDLcAssert(m_pSound != nullptr, "trying to play uninitialized sound!");
}
void TSDLcAudioSound::ChannelCheck()
{
SDLcAssert(m_iCurrentChannel >= 0, "trying to manipulate uninitialized or unplayed sound!");
}
void TSDLcAudioSound::Create(TSDLcAudioChunck * pSound)
{
m_pSound = pSound;
}
void FinishedCallBack(int iChannel)
{
if (iChannel >= 0)
{
TSDLcAudioSound ** pChanels = TSDLcAudioSound::GetChannels();
pChanels[iChannel]->SetInactive();
pChanels[iChannel] = nullptr;
}
}
void TSDLcAudioSound::Play(const int iLoops)
{
PlayCheck();
if (!m_bActive)
{
m_iCurrentChannel = Mix_PlayChannel(-1, m_pSound->GetChunck(), iLoops);
}
else
{
Mix_HaltChannel(m_iCurrentChannel);
Mix_PlayChannel(m_iCurrentChannel, m_pSound->GetChunck(), iLoops);
}
if (m_iCurrentChannel >= 0)
{
m_pChannels[m_iCurrentChannel] = this;
m_bActive = true;
Mix_ChannelFinished(&FinishedCallBack);
}
else
{
SDL_Log("WARNING : Sound couldn't be played, no more channels available");
}
}
void TSDLcAudioSound::Play(const int iLoops, const int iFadeIn)
{
PlayCheck();
if (!m_bActive)
{
Mix_FadeInChannel(-1, m_pSound->GetChunck(), iLoops, iFadeIn);
}
else
{
Mix_HaltChannel(m_iCurrentChannel);
Mix_FadeInChannel(-1, m_pSound->GetChunck(), iLoops, iFadeIn);
}
if (m_iCurrentChannel >= 0)
{
m_pChannels[m_iCurrentChannel] = this;
m_bActive = true;
Mix_ChannelFinished(&FinishedCallBack);
}
else
{
SDL_Log("WARNING : Sound couldn't be played, no more channels available");
}
}
void TSDLcAudioSound::Pause()
{
ChannelCheck();
if (m_bActive)
{
Mix_Pause(m_iCurrentChannel);
}
}
void TSDLcAudioSound::Resume()
{
ChannelCheck();
if (m_bActive)
{
Mix_Resume(m_iCurrentChannel);
}
}
void TSDLcAudioSound::Stop()
{
ChannelCheck();
if (m_bActive)
{
Mix_HaltChannel(m_iCurrentChannel);
}
}
void TSDLcAudioSound::Stop(const int iFadeout)
{
ChannelCheck();
if (m_bActive)
{
Mix_FadeOutChannel(m_iCurrentChannel, iFadeout);
}
}
void TSDLcAudioSound::Destroy()
{
m_pSound = nullptr;
m_iCurrentChannel = -2;
}
|
a1bbc25b45b0df48206522fa9f4080d537c09e52
|
c3de57676ebc2c4f6d0849347798534f85ab9a72
|
/ControlLib/include/ControlLib/ControlParameter.h
|
962b3275878aa9138294ecc2be93f1003e0067b1
|
[] |
no_license
|
plusminus34/Interactive_thin_shells_Bachelor_thesis
|
0662f6d88d76d8d49b2b6066bf1d2b0fc258f01e
|
85f034a476eeab8d485f19a6ea3208498061a4da
|
refs/heads/main
| 2023-03-10T15:15:53.666726
| 2021-02-24T08:01:25
| 2021-02-24T08:01:25
| 341,820,202
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,233
|
h
|
ControlParameter.h
|
#pragma once
#include <MathLib/Trajectory.h>
#define INITIALIZE_PARAMETER(pList, x, val, min, max, name) \
{ x = (int)pList.size(); pList.push_back(ControlParameter(val, min, max, fabs((double)((max) - (min)))/10.0, false, name)); }
#define INITIALIZE_PARAMETER_FULL(pList, x, val, min, max, maxAbsValueChange, frozen, name) \
{ x = (int)pList.size(); pList.push_back(ControlParameter(val, min, max, maxAbsValueChange, frozen, name)); }
class ControlParameter{
public:
//keep track of the min and max values that this parameter can take
double min, max;
//keep track of the value
double value;
//see if this variable should change value or not, in case we were running some optimization
bool frozen;
//this is a parameter that indicates how much this value can be changing each iteration
double maxAbsValueChange;
//and a name - used for debugging mostly
char* pName;
ControlParameter(double value, double min, double max, double maxAbsValueChange, bool frozen, char* name){
this->min = min;
this->max = max;
this->value = value;
this->maxAbsValueChange = maxAbsValueChange;
this->frozen = frozen;
this->pName = name;
}
ControlParameter(const ControlParameter& other){
this->min = other.min;
this->max = other.max;
this->value = other.value;
this->maxAbsValueChange = other.maxAbsValueChange;
this->frozen = other.frozen;
this->pName = other.pName;
}
ControlParameter& operator = (const ControlParameter& other){
this->min = other.min;
this->max = other.max;
this->value = other.value;
this->maxAbsValueChange = other.maxAbsValueChange;
this->frozen = other.frozen;
this->pName = other.pName;
return *this;
}
inline double getScaledValue(int scaleFactor){
return scaleFactor * (this->value - this->min)/(this->max - this->min);
}
};
inline void setParameterValues(DynamicArray<double>* values, DynamicArray<ControlParameter>* parameters){
if (values->size() != parameters->size())
throwError("Number of parameters do not match.");
for (uint i=0;i<values->size();i++)
parameters->at(i).value = values->at(i);
}
inline void filterParameterValues(double* values, DynamicArray<ControlParameter>* parameters){
for (uint i=0;i<parameters->size();i++){
boundToRange(&values[i], parameters->at(i).min, parameters->at(i).max);
}
}
inline void setParameterValues(double const* values, DynamicArray<ControlParameter>* parameters){
double* copiedValues = new double[parameters->size()];
for (uint i=0;i<parameters->size();i++){
copiedValues[i] = values[i];
}
filterParameterValues(copiedValues, parameters);
for (uint i=0;i<parameters->size();i++){
parameters->at(i).value = copiedValues[i];
//boundToRange(¶meters->at(i).value, parameters->at(i).min, parameters->at(i).max);
}
delete [] copiedValues;
}
inline void scaleAndSetParameterValues(double const* values, DynamicArray<ControlParameter>* parameters, int scaleFactor){
double* copiedValues = new double[parameters->size()];
for (uint i=0;i<parameters->size();i++){
copiedValues[i] = values[i]*(parameters->at(i).max-parameters->at(i).min)/scaleFactor + parameters->at(i).min;
}
setParameterValues(copiedValues, parameters);
delete [] copiedValues;
}
inline void writeParameterValuesToFile(char* fName, const DynamicArray<ControlParameter>& parameters){
FILE* fp = fopen(fName, "w");
if (fp == NULL)
throwError("Cannot open file %s", fName);
for (uint i=0; i< parameters.size();i++){
if (i > 0 && strcmp(parameters[i].pName, parameters[i-1].pName) == 0)
fprintf(fp, "%lf\n", parameters[i].value);
else
fprintf(fp, "\n# %s\n%lf\n", parameters[i].pName, parameters[i].value);
}
fclose(fp);
}
inline void readParameterValuesFromFile(char* fName, DynamicArray<ControlParameter>* parameters){
DynamicArray<double> values;
FILE* fp = fopen(fName, "r");
if (fp == NULL)
throwError("Cannot open file %s", fName);
readDoublesFromFile(fp, &values);
fclose(fp);
setParameterValues(&values, parameters);
}
inline void getScaledParameterValues(DynamicArray<double>* values, DynamicArray<ControlParameter>* parameters, int scaleFactor){
values->clear();
for (uint i=0; i< parameters->size();i++)
values->push_back(parameters->at(i).getScaledValue(scaleFactor));
}
inline void getParameterValues(DynamicArray<double>* values, DynamicArray<ControlParameter>* parameters){
values->clear();
for (uint i=0; i< parameters->size();i++)
values->push_back(parameters->at(i).value);
}
inline void setDiscontinuousTrajectory(Trajectory1D* traj, const DynamicArray<ControlParameter>& parameterList, int *indices, int count, double firstKnotPosition = 0.0, double lastKnotPosition = 1.0){
traj->clear();
for (int i=0;i<count;i++)
traj->addKnot(firstKnotPosition + ((double)i / (count-1)) * (lastKnotPosition - firstKnotPosition), parameterList[indices[i]].value);
}
inline void setContinuousTrajectory(Trajectory1D* traj, const DynamicArray<ControlParameter>& parameterList, int *indices, int count){
traj->clear();
for (int i=0;i<count;i++)
traj->addKnot((double)i / count, parameterList[indices[i]].value);
//and now make sure the last knot value is the same as the first
traj->addKnot(1, parameterList[indices[0]].value);
}
|
3ab2498a35d18c95f1d112e9bc5f9aac1a395a06
|
c3154e8620d3a97cdea9491b2cb37b152eb07d91
|
/VGP332/08_NEAT/PipeManager.h
|
34a2b2baf07b56f181af5ffdcc5512228c40fe96
|
[
"MIT"
] |
permissive
|
amyrhzhao/CooEngine
|
e9283e10f6f374b2420c7f20117850beb82f6a93
|
8d467cc53fd8fe3806d726cfe4d7482ad0aca06a
|
refs/heads/master
| 2020-12-24T03:43:35.021231
| 2020-09-19T00:18:43
| 2020-09-19T00:18:43
| 281,494,528
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 298
|
h
|
PipeManager.h
|
#pragma once
#include "Pipe.h"
class Bird;
class PipeManager
{
public:
void Update(float deltaTime);
void Render();
void Reset();
bool Intersect(const Bird& bird) const;
const Pipe* GetClosestPipe(const Bird& bird) const;
private:
std::vector<Pipe> mPipes;
float mSpawnDelay = 0.0f;
};
|
02ea5a3215d31a4af7bcee0407d8405fe5aa9a2d
|
c57ac054e85f64760f07c4e22c8b72e6192ea0ce
|
/DX3D/sources/6. Base/UIText.cpp
|
540b5a2fa5f70f70d89bfd1981fb2ebbe6229fe4
|
[] |
no_license
|
oneofthezombies/TeamAvengers_PUBG_Prototype
|
acd3415c627afb81e4e2d4369d30891ff80bb873
|
fd74e2094de7a81ffea2ece604f8a7ee7acd2f48
|
refs/heads/master
| 2020-03-17T23:00:34.933929
| 2018-08-12T00:14:46
| 2018-08-12T00:14:46
| 134,027,682
| 5
| 1
| null | 2018-08-08T06:10:32
| 2018-05-19T03:56:16
|
RPC
|
UTF-8
|
C++
| false
| false
| 1,579
|
cpp
|
UIText.cpp
|
#include "stdafx.h"
#include "UIText.h"
#include "UIManager.h"
UIText::UIText()
: UIObject()
, m_pFont(nullptr)
, m_drawTextFormat(DT_CENTER | DT_VCENTER)
, m_textString()
, m_text(nullptr)
, m_pTextString(nullptr)
{
}
UIText::~UIText()
{
}
void UIText::Render()
{
if (!m_pFont) return;
if (!m_textString.empty())
m_pFont->DrawTextA(g_pSprite, m_textString.c_str(), m_textString.size(), &m_rect, m_drawTextFormat, m_color);
else if (m_text)
m_pFont->DrawText(g_pSprite, m_text, lstrlen(m_text), &m_rect, m_drawTextFormat, m_color);
else if (m_pTextString)
m_pFont->DrawTextA(g_pSprite, m_pTextString->c_str(), m_pTextString->size(), &m_rect, m_drawTextFormat, m_color);
UIObject::Render();
}
void UIText::SetFont(const LPD3DXFONT val)
{
m_pFont = val;
}
void UIText::SetText(const LPCTSTR val)
{
m_text = val;
}
void UIText::SetText(const string& val)
{
m_textString = val;
}
void UIText::SetText(string* val)
{
m_pTextString = val;
}
void UIText::SetDrawTextFormat(const DWORD val)
{
m_drawTextFormat = val;
}
UIText* UIText::Create(const Font::Type font, const string& text, const D3DXVECTOR3& pos, const D3DXVECTOR2& size, UIObject* parent, const DWORD format)
{
UIText* ret = new UIText;
ret->SetFont(g_pFontManager->GetFont(font));
ret->SetText(text);
ret->SetPosition(pos);
ret->SetSize(size);
ret->SetDrawTextFormat(format);
if (parent)
parent->AddChild(*ret);
else
g_pUIManager->RegisterUIObject(*ret);
return ret;
}
|
35c43085b099877c756210b9d931911159e1c5ff
|
b4b4e324cbc6159a02597aa66f52cb8e1bc43bc1
|
/C++ code/Uva Online Judge/Q846.cpp
|
5c5e6d620c24f7f809f75e61764031b8edcecdc9
|
[] |
no_license
|
fsps60312/old-C-code
|
5d0ffa0796dde5ab04c839e1dc786267b67de902
|
b4be562c873afe9eacb45ab14f61c15b7115fc07
|
refs/heads/master
| 2022-11-30T10:55:25.587197
| 2017-06-03T16:23:03
| 2017-06-03T16:23:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 348
|
cpp
|
Q846.cpp
|
#include<cstdio>
#include<cassert>
using namespace std;
int Solve(int dis)
{
for(int i=1,ans=0;;i++)
{
if(dis<=0)return ans;
dis-=i,ans++;
if(dis<=0)return ans;
dis-=i,ans++;
}
}
int main()
{
// freopen("in.txt","r",stdin);
int t;scanf("%d",&t);
for(int x,y;t--;)
{
scanf("%d%d",&x,&y);
printf("%d\n",Solve(y-x));
}
return 0;
}
|
88ca780f1965d823faf9ec06fecbad36e7ac432a
|
15fabf8a407615180d4b06ab49d7522c9678477c
|
/src/superglue/keypoint_selector.cpp
|
d0e58cc4dca1ec1293539c7308d61844de281959
|
[] |
no_license
|
VictorSheverdin/Calibration
|
7322d51d0c67d64eed73f6a93ecb0812bb2cf55e
|
bb6499e9e41e072a5adb600481d72e5443bc1be4
|
refs/heads/master
| 2021-06-18T17:10:49.691944
| 2021-02-16T18:36:13
| 2021-02-16T18:36:13
| 177,824,656
| 7
| 4
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,332
|
cpp
|
keypoint_selector.cpp
|
#include "keypoint_selector.hpp"
namespace marker
{
namespace tf = torch::nn::functional;
namespace tch_u = libtorch_utils;
namespace trt_u = tensor_rt_utils;
at::Tensor make_inner_area_mask(torch::IntArrayRef shape, std::int64_t border, c10::Device device)
{
std::vector<int64_t> inner_shape{
shape[0],
shape[1],
shape[2] - 2 * border,
shape[3] - 2 * border
};
auto opt = torch::TensorOptions()
.device(device)
.dtype(torch::kBool);
auto border_zero = tf::PadFuncOptions({
border, border,
border, border
}).mode(torch::kConstant).value(0);
auto inner = torch::ones(inner_shape, opt);
return tf::pad(inner, border_zero);
}
KeypointSelector::KeypointSelector(const Config& cfg, const trt_u::Dims4d& scores_dims)
: m_cfg(cfg)
{
m_scores_size = cv::Size2i(scores_dims.cols, scores_dims.rows);
m_input_mask_resized = cv::cuda::createContinuous(m_scores_size, CV_8UC1);
m_score_mask = tch_u::make_tensor_4d(scores_dims, torch::kBool, torch::kCUDA);
m_inner_area = make_inner_area_mask(m_score_mask.sizes(), m_cfg.border, torch::kCUDA);
m_topk_indices = tch_u::make_tensor_1d(0, torch::kLong, torch::kCUDA);
}
void KeypointSelector::select(const ScoreMap& score_map, int count, KeypointSet& dst)
{
select(score_map, cv::Mat(), count, dst);
}
void KeypointSelector::select(const ScoreMap& score_map,
const cv::Mat& mask, int count, KeypointSet& dst)
{
apply_threshold_mask(score_map);
if (!mask.empty())
{
upload_mask(mask);
apply_input_mask();
}
select_inner(score_map, count, dst);
}
void KeypointSelector::upload_mask(const cv::Mat& mask)
{
if (mask.rows != m_scores_size.height || mask.cols != m_scores_size.width)
{
if (mask.rows != m_input_mask.rows || mask.cols != m_input_mask.cols)
m_input_mask.create(mask.rows, mask.cols, mask.type());
m_input_mask.upload(mask);
// Mask is binary
cv::cuda::resize(m_input_mask, m_input_mask_resized,
m_scores_size, 0., 0., cv::INTER_NEAREST);
}
else
m_input_mask_resized.upload(mask);
}
void KeypointSelector::apply_input_mask()
{
auto input_mask_tensor = tch_u::as_tensor(m_input_mask_resized, torch::kBool);
m_score_mask.select(0, 0).select(0, 0).logical_and_(input_mask_tensor);
}
void KeypointSelector::apply_threshold_mask(const ScoreMap& score_map)
{
// Mask out scores that are too low or too close to border
torch::gt_out(m_score_mask, score_map.values, m_cfg.score_threshold);
m_score_mask.logical_and_(m_inner_area);
}
void KeypointSelector::select_inner(const ScoreMap& score_map, int count, KeypointSet& dst)
{
auto keypoints = m_score_mask.select(0, 0).select(0, 0).nonzero();
auto scores = score_map.values.select(0, 0).select(0, 0)
.index({ keypoints.select(1, 0), keypoints.select(1, 1) });
keypoints = keypoints.fliplr().to(torch::kFloat32);
if (keypoints.size(0) > count)
{
dst.scores.resize_({ count });
m_topk_indices.resize_({ count });
torch::topk_out(dst.scores, m_topk_indices, scores,
/*k=*/count, /*dim=*/0, /*largest=*/true, /*sorted=*/false);
dst.keypoints.resize_({ count, keypoints.size(1) });
torch::index_select_out(dst.keypoints, keypoints,
/*dim=*/0, /*index=*/m_topk_indices);
}
else
{
dst.keypoints = keypoints;
dst.scores = scores;
}
// Change keypoint coordinates to match source image size
float x_ratio = static_cast<float>(score_map.image_size.width) / score_map.values.size(3);
float y_ratio = static_cast<float>(score_map.image_size.height) / score_map.values.size(2);
dst.keypoints.select(1, 0).mul_(x_ratio);
dst.keypoints.select(1, 1).mul_(y_ratio);
dst.image_size = score_map.image_size;
}
}
|
5929606eda3baafa8fa59550b5f132d0e7503385
|
9762cb52ab4f637234b1c149f37912faadd4603a
|
/src/include/Mesh.hpp
|
30c3eeae2f28fdff429a6a60ce17004f613671d6
|
[
"MIT"
] |
permissive
|
jaredmulconry/GLProj
|
efcd5dbbd8558826597cce84a23cc08c2f38e956
|
722fc9804cf6bd2ee0098e6eed9261198f55d0b9
|
refs/heads/master
| 2020-05-22T01:45:14.778475
| 2019-04-11T06:45:07
| 2019-04-11T06:45:07
| 61,507,394
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,929
|
hpp
|
Mesh.hpp
|
#pragma once
#include "gl_core_4_5.h"
#include "MeshDataBuffer.hpp"
#include "MeshIndexBuffer.hpp"
#include "MeshArrayBuffer.hpp"
#include <vector>
struct aiMesh;
namespace GlProj
{
namespace Graphics
{
enum class MeshSlots : GLenum
{
Positions,
Normals,
Tangents,
BiTangents,
TexCoord0,
TexCoord1,
Colour0,
Color0 = Colour0,
User,
};
GLenum MeshSlotToGL(MeshSlots s);
static const constexpr int MaxTextureCoordinates = 2;
static const constexpr int MaxColourChannels = 1;
static const constexpr int MaxColorChannels = MaxColourChannels;
class Mesh
{
std::vector<MeshDataBuffer> vertexData;
MeshIndexBuffer indices;
MeshArrayBuffer arrayBuffer;
unsigned int primitiveCount;
unsigned int vertsPerPrimitive;
static const constexpr int ReservedVertexSlots = 16;
void SetAttributePointer(MeshSlots);
public:
Mesh() = default;
explicit Mesh(const aiMesh*);
Mesh(const Mesh&) = delete;
Mesh(Mesh&&) = default;
Mesh& operator=(Mesh&&) = default;
static void EnableAttribute(MeshSlots);
static void DisableAttribute(MeshSlots);
static void SetAttributePointer(MeshSlots, const MeshDataBuffer&, GLsizei = 0, const void* = nullptr);
static void SetAttributeDivisor(MeshSlots, GLuint);
//Searches through the internal vertex data for a range of empty slots
//into which custom vertex data could be bound. Search begins at
//the start of User-defined vertex attributes defined by 'User'.
int FindAttributeRange(int, int = 0);
const MeshDataBuffer& GetMeshData(MeshSlots) const;
void Bind() const noexcept;
unsigned int PrimitiveCount()const noexcept
{
return primitiveCount;
}
unsigned int VertsPerPrimitive() const noexcept
{
return vertsPerPrimitive;
}
friend bool operator==(const Mesh&, const Mesh&) noexcept;
friend bool operator!=(const Mesh&, const Mesh&) noexcept;
};
}
}
|
7773dc8c2b914564c22a6f74de8785771530c9f3
|
862812801aedb9998e7b05e43b87ad34f6731a41
|
/source/03_Object/2D/UI/Score/ScoreDraw/ScoreDraw.h
|
77f5e38edbfb64b03fbf1e4efaf2b55053ab6c86
|
[] |
no_license
|
KaiAraki/3DAction
|
49d4e744b309a5cffbf96a300e547cb6e523ed94
|
ef6ee6c07b5a8252ca0e3bb1e97ac29393f4fac5
|
refs/heads/master
| 2023-02-25T04:00:58.458217
| 2018-11-07T05:10:36
| 2018-11-07T05:10:36
| null | 0
| 0
| null | null | null | null |
SHIFT_JIS
|
C++
| false
| false
| 1,060
|
h
|
ScoreDraw.h
|
//================================================================================
//
// ในใณใขๆ็ปใฏใฉใน
// Author : Araki Kai ไฝๆๆฅ : 2018/06/20
//
//================================================================================
#ifndef _SCORE_DRAW_H_
#define _SCORE_DRAW_H_
//======================================================================
//
// ใคใณใฏใซใผใๆ
//
//======================================================================
#include <string>
#include "../Score.h"
#include <Component\DrawComponent\DrawComponent.h>
#include <ResourceManager\ResourceManager.h>
//======================================================================
//
// ใฏใฉในๅฎ็พฉ
//
//======================================================================
class ScoreDraw : public DrawComponent
{
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public :
// ใกใณใ้ขๆฐ
void Init() override;
void Uninit() override;
void Draw(unsigned mesh_index) override;
};
#endif
|
3ee20624f41165eaf24c4c1cc2f2ba05c3d3d0c6
|
0331aa6bf71c6fdf01050b525f95b868764c81b1
|
/๊ฒ์/crush.cpp
|
8ec8058bf9e7353024eae97dc5845562a40a9922
|
[] |
no_license
|
hynjin/simple_game
|
094ac8bf7ba79729c5d8fe5aff2f4d3c05e46e17
|
7ac666f348adb852b3356c51fdab6f4cf03cd905
|
refs/heads/master
| 2021-01-12T10:27:46.670671
| 2016-12-14T13:46:12
| 2016-12-14T13:46:12
| 76,461,401
| 0
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 2,741
|
cpp
|
crush.cpp
|
/*
์ฅ์ ๋ฌผ์ ์ขํ์ ๋ณด๋ฅผ ๋ฐ์์์
์บ๋ฆญํฐ์ ์ฅ์ ๋ฌผ์ ์ถฉ๋์ฌ๋ถ ํ์ธ
*/
#include "crush.h"
crush ::crush()
{
stage=1;
}
crush :: ~crush()
{
}
void crush :: call()
{
tumph=ob.tump();
ropeh=ob.rope();
badackh=ob.badack();
homeh=ob.home();
}
int crush:: badack_check(double ghostx,double ghosty,int &check)
{
for(unsigned int i=0;i<badackh.size();i++)
{
if(ghostx>(badackh[i].vector.x-GhostSize_X/3) && (ghostx+GhostSize_X)<(badackh[i].vector.x+badack_x+GhostSize_X/3))
{
if((ghosty+GhostSize_Y)>=badackh[i].vector.y && (ghosty+GhostSize_Y)<=(badackh[i].vector.y+badack_y))//Y ์ค์ผ ํ์
{
return check=0;
}
}
else if(ghosty>400)
return check=0;
}
if(rope_check(ghostx,ghosty,check)==1)
return check=1;
return check=4;
}
int crush:: rope_check(double ghostx,double ghosty,int &check)
{
for(unsigned int i=0;i<ropeh.size();i++)
{
if((ghostx+GhostSize_X/2)>=(ropeh[i].vector.x+rope_x/2)&&(ghostx+GhostSize_X/2)<=(ropeh[i].vector.x+rope_x))
{
if((ghosty+GhostSize_Y/2)<(ropeh[i].vector.y+rope_y) && (ghosty+GhostSize_Y/2)>ropeh[i].vector.y)
{
if(i==0)
stage=2;
else
stage=1;
cnt=i;//๋กํ๋ฅผ ํ๊ณ ๋๋ฌด ์ฌ๋ผ๊ฐ์ง ์๋๋ก ํจ(->move์์ ์ฌ์ฉ)
return check=1;
}
}
}
return check=0;
}
int crush:: tump_check(double ghostx,double ghosty,int &check)
{
for(unsigned int i=0;i<tumph.size();i++)
{
if((ghostx+GhostSize_X/2)>tumph[i].vector.x && (ghostx+GhostSize_X/2)<(tumph[i].vector.x+tump_x))
{
if((ghosty+GhostSize_Y/2)<(tumph[i].vector.y+tump_y) && (ghosty+GhostSize_Y/2)>tumph[i].vector.y)
{
return check=2;
}
}
}
return check=0;
}
int crush:: home_check(double ghostx,double ghosty,int &check)
{
for(unsigned int i=0;i<homeh.size();i++)
{
if((ghostx+GhostSize_X/2)>homeh[i].vector.x && (ghostx+GhostSize_X/2)<(homeh[i].vector.x+65))//์ฌ๊ธฐ์ 65๋ผ๋ ์ซ์๋ ์ง์ ์ฌ์ด์ฆ
{
if((ghosty+GhostSize_Y/2)<(homeh[i].vector.y+65) && (ghosty+GhostSize_Y/2)>homeh[i].vector.y)
{
return check=6;
}
}
}
return check=0;
}
void crush :: Getdark(D3DXVECTOR3 dark_vector)
{
darkx=dark_vector.x;
darky=dark_vector.y;
}
int crush :: dark_check(double ghostx, double ghosty, int &check)
{
for(unsigned int i=0;i<tumph.size();i++)
{
if((ghostx+GhostSize_X/2)>darkx && (ghostx+GhostSize_X/2)<(darkx+140))//140์ ์์ง์ด๋ ์ฅ์ ๋ฌผ ๊ฐ๋ก ์ฌ์ด์ฆ
{
if((ghosty+GhostSize_Y/2)<(darky+100) && (ghosty+GhostSize_Y/2)>darky)//100์ ์์ง์ด๋ ์ฅ์ ๋ฌผ ์ธ๋ก ์ฌ์ด์ฆ
{
return check=2;
}
}
}
return check=0;
}
//๋๋ ๋ฐ๋ณด์ธ๊ฐ ๋ณด๋ค
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.