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
b925f436c5d7d2a9690df9096cb61a8c2ef22543
f1c59011e98734133a881100bb552f22e7d045b0
/project/safe_thread.h
f4e183d3534e1c50a3eb2669db152615c592f27b
[ "MIT" ]
permissive
Cabrra/Nightmare-Scene
e1efc418cfb96db23fb50d6514f6fe6e6ac38d3b
885ea93143600810041934081fe332cfa68292d6
refs/heads/master
2021-03-16T08:43:42.236511
2018-10-25T04:13:18
2018-10-25T04:13:18
25,941,897
0
0
null
null
null
null
UTF-8
C++
false
false
3,094
h
safe_thread.h
#pragma once #include <thread> #include <mutex> // The safe thread class pretends to be a std:thread but uses a mutex to // try and make using certain functions thread-safe such as join().(allows multiple threads to wait for this thread) // only thread saftey is added, no extra error checking is done to try and stay closer to the standard. // safe_thread to safe_thread copies and swaps may be added with extra security at a later time. // L.Norri CD DRX FullSail University. class safe_thread { std::thread unsafe_thread; // encapsulation (Is-A relationship was abandoned due to variadic template macro expansion) std::mutex make_safe; // restricts access to internal thread public: // the safe_thread class cannot be used to start a thread (no specialized constructors) // however, you can convert an existing thread to a safe_thread.(ex: safe_thread x = thread(...);) // The safe_thread can be assigned threads and can cast itself to a thread if required. safe_thread() {} // copy construct a safe_thread from a (unsafe)thread safe_thread(std::thread&& _Other) : unsafe_thread(std::move(_Other)) {} // allow assignment to other threads std::thread& operator=(std::thread&& _Other) { unsafe_thread = std::move(_Other); return unsafe_thread; } // A safe thread may be cast to a normal thread pointer, refrence or L-value operator std::thread*() { return &unsafe_thread; } operator const std::thread*() const { return &unsafe_thread; } operator std::thread&() { return unsafe_thread; } operator const std::thread&() const { return unsafe_thread; } operator std::thread&&() { return std::move(unsafe_thread); } operator const std::thread&&() const { return std::move(unsafe_thread); } // with our conversions overloaded, lets actually make some imposter functions with thread safety controls void swap(std::thread& _Other) { std::lock_guard<std::mutex> lock(make_safe); unsafe_thread.swap(_Other); } bool joinable() const { // the reason for the const_cast is to retain the orginal std::thread function signatures exactly std::lock_guard<std::mutex> lock(*const_cast<std::mutex*>(&make_safe)); return unsafe_thread.joinable(); } void join() { std::lock_guard<std::mutex> lock(make_safe); unsafe_thread.join(); } void detach() { std::lock_guard<std::mutex> lock(make_safe); unsafe_thread.detach(); } std::thread::id get_id() const { // the resaon for the const_cast is to retain the orginal std::thread function signatures exactly std::lock_guard<std::mutex> lock(*const_cast<std::mutex*>(&make_safe)); unsafe_thread.get_id(); } static unsigned int hardware_concurrency() { // mutex uneeded on static function, nothing to protect return std::thread::hardware_concurrency(); } std::thread::native_handle_type native_handle() { std::lock_guard<std::mutex> lock(make_safe); unsafe_thread.native_handle(); } private: // safe_thread cannot itself be copied or initialized from another safe_thread safe_thread(const safe_thread&); // not defined safe_thread& operator=(const safe_thread&); // not defined };
0fe54053a12539888fc768802f53e19de211c0b4
9bc38e65519695e812407377dea0924c4bc384d5
/ConstantBuffer.h
087640aa2274263b36f3c44c2ffd43cdc929c808
[]
no_license
danmccor/DirectX11-Showcase
9179b4244b912e3734dc3b33e910e918f76064d1
7b86d9a851f5999d5acd16f9d5b42c84e82f8a7d
refs/heads/master
2022-11-15T18:47:20.311604
2020-07-08T14:48:45
2020-07-08T14:48:45
278,116,781
0
0
null
null
null
null
UTF-8
C++
false
false
1,942
h
ConstantBuffer.h
#pragma once #ifndef ConstantBuffer_h__ #define ConstantBuffer_h__ #include <d3d11.h> #include <wrl/client.h> #include "cBufferTypes.h" //A template class to store the constant buffer ///Used as a template to ensure you can either pass in a vertex shader constant buffer or a pixel shader constant buffer template<class T> class ConstantBuffer { public: //Instantiate the buffer as null ConstantBuffer() { buffer = nullptr; } T data{}; //Initialise the constant buffer HRESULT Initialise(ID3D11Device* device, ID3D11DeviceContext* deviceContext) { //Set device context this->deviceContext = deviceContext; //Create a buffer desc CD3D11_BUFFER_DESC desc; ZeroMemory(&desc, sizeof(desc)); //Set desc values desc.Usage = D3D11_USAGE_DYNAMIC; desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; desc.MiscFlags = 0; desc.ByteWidth = static_cast<UINT>(sizeof(T) + (16 - (sizeof(T) % 16))); desc.StructureByteStride = 0; //Create the constant buffer HRESULT hr = device->CreateBuffer(&desc, 0, &buffer); return hr; } //Apply any changes to this->data to the constant buffer bool ApplyChanges() { //Create the subresource for the buffer D3D11_MAPPED_SUBRESOURCE mapRes; //Map the constant buffer to the subresource HRESULT hr = deviceContext->Map(buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapRes); //if it fails return false if (FAILED(hr))return false; //Copy the memory of this data into the mapped resource CopyMemory(mapRes.pData, &data, sizeof(T)); //Unmap the buffer deviceContext->Unmap(buffer, 0); return true; } //Return the ID3D11Buffer ID3D11Buffer* Get()const { return buffer; } //Return the address of the ID3D11Buffer ID3D11Buffer* const* GetAddress()const { return &buffer; } private: //Initialise the variables ID3D11Buffer* buffer; ID3D11DeviceContext* deviceContext = nullptr; }; #endif // !VertexBuffer_h__
7731fac9dfc07fc5da72ef740f69653590fc4e4e
98fe6ce8218507e88803739d95d4c454e4cda164
/balloc/src/back.cpp
e49809295fc9a8232f1b0d2b80052c223b175709
[]
no_license
ashokzg/cpb
fb8ae5a06261fdd32cbd796a490ddfbf27587a13
0115217751327c5c9c669b7c00998d1593cb9b25
refs/heads/master
2021-01-22T12:12:06.579649
2013-05-11T02:17:40
2013-05-11T02:17:40
8,245,999
0
0
null
null
null
null
UTF-8
C++
false
false
4,758
cpp
back.cpp
// ROS communication #include <ros/ros.h> #include <image_transport/image_transport.h> #include <tf/transform_listener.h> // Msg->OpenCV #include <cv_bridge/CvBridge.h> #include <image_geometry/pinhole_camera_model.h> // OpenCV & blob detection #include <opencv/cv.h> #include <opencv/highgui.h> #include <BlobResult.h> #include <boost/thread.hpp> #include <cmath> #include <cstdio> #include <ros/ros.h> #include <image_transport/image_transport.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/core/core.hpp> using namespace cv; using namespace std; namespace enc = sensor_msgs::image_encodings; static const char WINDOW[] = "Image window"; class ImageConverter { ros::NodeHandle nh_; image_transport::ImageTransport it_; image_transport::Subscriber image_sub_; image_transport::Publisher image_pub_; Mat imageA, imageB; bool flag; static const double blob_area_absolute_min_ = 60; static const double blob_area_absolute_max_ = 5000; static const double blob_compactness_ = 5; public: ImageConverter() : it_(nh_) { ros::Rate loop_rate(0.2); flag = false; image_pub_ = it_.advertise("out", 1); image_sub_ = it_.subscribe("/usb_cam/image_raw", 1, &ImageConverter::imageCb, this); namedWindow(WINDOW); while(flag == false) { loop_rate.sleep(); ros::spinOnce(); } ImageConverter::locator(); } ~ImageConverter() { destroyWindow(WINDOW); } void imageCb(const sensor_msgs::ImageConstPtr& msg) { cv_bridge::CvImagePtr cv_ptr; try { cv_ptr = cv_bridge::toCvCopy(msg, enc::BGR8); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } imageA = cv_ptr->image; imageB = imageA.clone(); flag = true; //image_pub_.publish(cv_ptr->toImageMsg()); } void locator() { namedWindow("Tracking"); int hMin, hMax, sMin, sMax, vMin, vMax; hMin = 0; hMax = 124; sMin = 95; sMax = 255; vMin = 139; vMax = 255; Mat smoothed, hsvImg, t_img; // createTrackbar("Hue Min", "Tracking", &hMin, 255); // createTrackbar("Hue Max", "Tracking", &hMax, 255); // createTrackbar("Sat Min", "Tracking", &sMin, 255); // createTrackbar("Sat Max", "Tracking", &sMax, 255); // createTrackbar("Val Min", "Tracking", &vMin, 255); // createTrackbar("Val MaX", "Tracking", &vMax, 255); // //inRange(hsv, Scalar(hMin, sMin, vMin), Scalar(hMax, sMax, vMax), bw); while(ros::ok()) { Mat source = imageB; imshow(WINDOW, imageB); waitKey(3); //smoothed.create(source.rows, source.cols, source.type()); //cvPyrMeanShiftFiltering(&source, &smoothed, 2.0, 40.0); GaussianBlur(source, smoothed, Size(9,9), 4); cvtColor(smoothed, hsvImg, CV_BGR2HSV); //inRange(hsvImg,Scalar(0,140,80),Scalar(30,255,130),t_img); inRange(hsvImg, Scalar(hMin, sMin, vMin), Scalar(hMax, sMax, vMax), t_img); floodFill(t_img,Point(0,0),Scalar(255,255,255)); // for(int i=0;i<255;i++) // { // inRange(hsvImg,Scalar(0,140,80),Scalar(30,255,130),t_img); // imshow("edited", t_img); // if(waitKey(50)!=-1) // cout<<i<<endl; // } CBlobResult blob; IplImage i_img = t_img; vector<Vec3f> circles; HoughCircles(t_img, circles, CV_HOUGH_GRADIENT, 2, 40, 80, 40); blob = CBlobResult(&i_img,NULL,0); int num_blobs = blob.GetNumBlobs(); cout<< num_blobs <<endl; blob.Filter(blob, B_INCLUDE, CBlobGetArea(), B_INSIDE, blob_area_absolute_min_, blob_area_absolute_max_); blob.Filter(blob, B_EXCLUDE, CBlobGetCompactness(), B_GREATER, blob_compactness_); num_blobs = blob.GetNumBlobs(); cout<< "new" <<num_blobs <<endl; for(int i =0;i<num_blobs;i++) { CBlob* bl = blob.GetBlob(i); Point2d uv(CBlobGetXCenter()(*bl), CBlobGetYCenter()(*bl)); //circle(t_img,uv,50,Scalar(255,0,0),5); cout<<uv.x << "and" << uv.y <<endl; } cout << "Size of circles :" << circles.size()<<endl; Mat st; //= source.clone(); cvtColor(t_img, st, CV_GRAY2BGR); for(size_t i = 0; i < circles.size(); i++) { Point center(cvRound(circles[i][0]), cvRound(circles[i][1])); int radius = cvRound(circles[i][2]); // draw the circle center circle(st, center, 3, Scalar(0,255,0), -1, 8, 0 ); // draw the circle outline circle(st, center, radius, Scalar(0,0,255), 3, 8, 0 ); } //blob.Filter() imshow("edited", st); waitKey(3); ros::spinOnce(); } } }; int main(int argc, char** argv) { ros::init(argc, argv, "image_converter"); ImageConverter ic; ros::spin(); return 0; }
c80138dd41c40c532eb5a85a22384fd8e518578f
ac58b95b33a675ee3a7e858c7574a9de511a96fb
/USACO/money_systems/money_systems.cpp
e2bca6fbd0c1f37a10040f98f95f4ea5c6c11c1a
[]
no_license
lshain/algorithm
4d55efecf154c7d89ee5a2ed9dd1a54000ee359a
d05edf18fda840e25a34d17fec6cb219ed67df72
refs/heads/master
2020-05-07T11:56:20.424743
2014-08-08T01:30:58
2014-08-08T01:30:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
783
cpp
money_systems.cpp
/* ID: lshain.1 PROG: money LANG: C++ */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <string> #include <vector> #include <map> #include <set> #include <algorithm> using namespace std; unsigned long long ans[10001]; unsigned long long vv[26]; int v, n; int main( int argc, char* argv[], char* env[] ) { freopen( "money.in", "r", stdin ); freopen( "money.out", "w", stdout ); scanf("%d%d", &v, &n); int i = 0; int j = 0; int k = 0; for( i = 0; i < v; i++ ) { scanf("%lld",&vv[i]); } for( i = 0; i < n; i++ ) { ans[i] = 0; } ans[0] = 1; for( i = 0; i < v; i++ ) { for( j = n; j >= 0; j-- ) { for( k = j - vv[i]; k >= 0; k -= vv[i] ) { ans[j] += ans[k]; } } } printf("%lld\n", ans[n]); return 0; }
74ea7862905e6e6a57a20a1a74dc9ed7b86631ae
7e2e71956fdf70da787bf4edcfcf7ecd34fd9c99
/o2Engine/Sources/Animation/Animation.cpp
9e6e8c1c08ee0bf72842837bc13cbd35b4afb2ce
[]
no_license
dmitrykolesnikovich/o2
579abb53c805b117d11986017dcdb50f50d75409
c1b9038c6f56466ab96544c0e9424e4b9baf6553
refs/heads/master
2020-03-13T00:31:46.701057
2018-04-23T19:33:58
2018-04-23T19:33:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,552
cpp
Animation.cpp
#include "stdafx.h" #include "Animation.h" #include "Animation/Animatable.h" #include "Animation/AnimatedValue.h" #include "Utils/Debug/Debug.h" #include "Utils/Basic/IObject.h" namespace o2 { Animation::Animation(IObject* target /*= nullptr*/): mTarget(nullptr), mAnimationState(nullptr) { SetTarget(target); } Animation::Animation(const Animation& other): mTarget(nullptr), IAnimation(other), mAnimationState(nullptr) { for (auto& val : other.mAnimatedValues) { AnimatedValueDef def(val); def.mAnimatedValue = val.mAnimatedValue->CloneAs<IAnimatedValue>(); mAnimatedValues.Add(def); OnAnimatedValueAdded(def); } SetTarget(other.mTarget); } Animation::~Animation() { Clear(); } Animation& Animation::operator=(const Animation& other) { Clear(); IAnimation::operator=(other); for (auto& val : other.mAnimatedValues) { AnimatedValueDef def(val); def.mAnimatedValue = val.mAnimatedValue->CloneAs<IAnimatedValue>(); def.mAnimatedValue->onKeysChanged += THIS_FUNC(RecalculateDuration); if (mTarget) { IObject* targetObj = dynamic_cast<IObject*>(mTarget); if (targetObj) { FieldInfo* fieldInfo = nullptr; const ObjectType* type = dynamic_cast<const ObjectType*>(&targetObj->GetType()); void* castedTarget = type->DynamicCastFromIObject(targetObj); def.mTargetPtr = type->GetFieldPtr(castedTarget, def.mTargetPath, fieldInfo); if (!fieldInfo) o2Debug.LogWarning("Can't find object %s for animating", def.mTargetPath); else { if (fieldInfo->GetType()->GetUsage() == Type::Usage::Property) def.mAnimatedValue->SetTargetProxyVoid(fieldInfo->GetType()->GetValueProxy(def.mTargetPtr)); else def.mAnimatedValue->SetTargetVoid(def.mTargetPtr); } } } mAnimatedValues.Add(def); OnAnimatedValueAdded(def); } RecalculateDuration(); return *this; } void Animation::SetTarget(IObject* target, bool errors /*= true*/) { mTarget = target; if (mTarget) { for (auto& val : mAnimatedValues) { FieldInfo* fieldInfo = nullptr; const ObjectType* type = dynamic_cast<const ObjectType*>(&mTarget->GetType()); void* castedTarget = type->DynamicCastFromIObject(mTarget); val.mTargetPtr = type->GetFieldPtr(castedTarget, val.mTargetPath, fieldInfo); if (!fieldInfo) { if (errors) o2Debug.LogWarning("Can't find object %s for animating", val.mTargetPath); } else { if (fieldInfo->GetType()->GetUsage() == Type::Usage::Property) val.mAnimatedValue->SetTargetProxyVoid(fieldInfo->GetType()->GetValueProxy(val.mTargetPtr)); else val.mAnimatedValue->SetTargetVoid(val.mTargetPtr); } } } else { for (auto& val : mAnimatedValues) { val.mTargetPtr = nullptr; val.mAnimatedValue->SetTargetVoid(val.mTargetPtr); } } } IObject* Animation::GetTarget() const { return mTarget; } void Animation::Clear() { for (auto& val : mAnimatedValues) delete val.mAnimatedValue; mAnimatedValues.Clear(); } Animation::AnimatedValuesVec& Animation::GetAnimationsValues() { return mAnimatedValues; } const Animation::AnimatedValuesVec& Animation::GetAnimationsValues() const { return mAnimatedValues; } bool Animation::RemoveAnimationValue(const String& path) { for (auto& val : mAnimatedValues) { if (val.mTargetPath == path) { delete val.mAnimatedValue; mAnimatedValues.Remove(val); return true; } } return false; } void Animation::Evaluate() { for (auto& val : mAnimatedValues) val.mAnimatedValue->ForceSetTime(mInDurationTime, mDuration); } void Animation::RecalculateDuration() { float lastDuration = mDuration; mDuration = 0.0f; for (auto& val : mAnimatedValues) mDuration = Math::Max(mDuration, val.mAnimatedValue->mDuration); if (Math::Equals(lastDuration, mEndTime)) mEndTime = mDuration; } void Animation::OnDeserialized(const DataNode& node) { for (auto& val : mAnimatedValues) val.mAnimatedValue->onKeysChanged += THIS_FUNC(RecalculateDuration); RecalculateDuration(); mEndTime = mDuration; } void Animation::OnAnimatedValueAdded(AnimatedValueDef& valueDef) { if (mAnimationState) valueDef.mAnimatedValue->RegInAnimatable(mAnimationState, valueDef.mTargetPath); } bool Animation::AnimatedValueDef::operator==(const AnimatedValueDef& other) const { return mAnimatedValue == other.mAnimatedValue; } } DECLARE_CLASS(o2::Animation); DECLARE_CLASS(o2::Animation::AnimatedValueDef);
d674ab1cc5eb18183a884c8d6d208f54f615e6a8
103f3f1b070eca4b722be58ba04f5688fd4c0d2a
/libraries/chain/include/eosio/chain/reversible_block_object.hpp
7c4877a05f9baab19979b0dd12f72a55bcc7e7e3
[ "MIT" ]
permissive
pinklite/fio
dbd2901144b6766b756f5f1970c4d78161462b79
fc4652bbaf1f4b7c2abc2817afcfe09b36d46171
refs/heads/master
2022-07-03T23:21:10.989208
2020-05-17T10:49:37
2020-05-17T10:49:37
264,540,810
2
0
MIT
2020-05-16T22:40:34
2020-05-16T22:40:33
null
UTF-8
C++
false
false
2,417
hpp
reversible_block_object.hpp
/** * @file * @copyright defined in fio/LICENSE */ #pragma once #include <eosio/chain/types.hpp> #include <eosio/chain/authority.hpp> #include <eosio/chain/block_timestamp.hpp> #include <eosio/chain/contract_types.hpp> #include "multi_index_includes.hpp" namespace eosio { namespace chain { class reversible_block_object : public chainbase::object<reversible_block_object_type, reversible_block_object> { OBJECT_CTOR(reversible_block_object, (packedblock)) id_type id; uint32_t blocknum = 0; //< blocknum should not be changed within a chainbase modifier lambda shared_string packedblock; void set_block(const signed_block_ptr &b) { packedblock.resize(fc::raw::pack_size(*b)); fc::datastream<char *> ds(packedblock.data(), packedblock.size()); fc::raw::pack(ds, *b); } signed_block_ptr get_block() const { fc::datastream<const char *> ds(packedblock.data(), packedblock.size()); auto result = std::make_shared<signed_block>(); fc::raw::unpack(ds, *result); return result; } block_id_type get_block_id() const { fc::datastream<const char *> ds(packedblock.data(), packedblock.size()); block_header h; fc::raw::unpack(ds, h); // Only need the block id to then look up the block state in fork database, so just unpack the block_header from the stored packed data. // Avoid calling get_block() since that constructs a new signed_block in heap memory and unpacks the full signed_block from the stored packed data. return h.id(); } }; struct by_num; using reversible_block_index = chainbase::shared_multi_index_container< reversible_block_object, indexed_by< ordered_unique<tag<by_id>, member<reversible_block_object, reversible_block_object::id_type, &reversible_block_object::id>>, ordered_unique<tag<by_num>, member<reversible_block_object, uint32_t, &reversible_block_object::blocknum>> > >; } } // eosio::chain CHAINBASE_SET_INDEX_TYPE(eosio::chain::reversible_block_object, eosio::chain::reversible_block_index)
798fdfd1d7391a8e4ac01c5befd1d1ba596095e6
33287fa3ef5be6009dd4ab0ed339fd2c0f22ace6
/dectobin.cpp
8aab99e55460e1560b5fdcab0bd4a0c0abb061be
[]
no_license
Javitha/javinew
67a163c25998b02a2adfd2fe8f67faa2dc3b21d6
e9eb2f2dc748c9d18fe6e2dbfe012cef8d9f430a
refs/heads/master
2021-01-19T00:54:15.000027
2016-07-10T19:49:09
2016-07-10T19:49:09
62,982,676
0
0
null
null
null
null
UTF-8
C++
false
false
294
cpp
dectobin.cpp
#include<iostream> #include<cmath> #include<cstdio> using namespace std; int main() { long n; int a[100]; cin>>n; int i=0; while(n>0) { a[i]=n%2; n=n/2; i++; } for(int j=0;j<i;j++) { cout<<a[j]; } return 0; }
82b0208c5e51a05cff066006c5f8993a72753f85
af3167292796593aca8212047b858ddcc499fa8a
/module03/ex02/ScavTrap.cpp
a9338324dce4d95b5193aaa7870537aee3dea238
[]
no_license
FandorineTom/CPP_module
830499fd7e8f80ae510663742d38ce1c5bbe9b55
f7f2cadb459c822381a093029d3b1728e17c52b5
refs/heads/master
2023-04-01T16:45:49.749139
2021-04-17T09:05:20
2021-04-17T09:05:20
352,751,387
0
0
null
null
null
null
UTF-8
C++
false
false
3,831
cpp
ScavTrap.cpp
#include "ScavTrap.hpp" ScavTrap::ScavTrap() { _hit_points = 100; _max_hit_points = 100; _energy_points = 50; _max_energy_points = 50; _level = 1; _melee_attack_damage = 20; _ranged_attack_damage = 15; _armor_damage_reduction = 3; _name = "Nobody"; _range_message = "Don't bother with plastic surgery - there's NO fixing that! "; _melee_message = "This is why you do your homework! "; _not_enough_points = "My assets... frozen! "; _taking_damage_message = "Why do I even feel pain?! "; _armor_message = "Armor soak increased! "; _being_revived_message = "Can I just say... yeehaw. "; std::string attacks[5] = { "Care to have a friendly duel? ", "I will prove to you my robotic superiority! ", "It's about to get magical! ", "Man versus machine! Very tiny streamlined machine! ", "Dance battle! Or, you know... regular battle. "}; for (int i = 0; i < 5; i++) { _attack_random[i] = attacks[i]; } std::cout << "Let's get this party started! " << "ScavTrap with no name created\n"; } ScavTrap::ScavTrap(std::string const &name) { _hit_points = 100; _max_hit_points = 100; _energy_points = 50; _max_energy_points = 50; _level = 1; _melee_attack_damage = 20; _ranged_attack_damage = 15; _armor_damage_reduction = 3; _name = name; _range_message = "Don't bother with plastic surgery - there's NO fixing that! "; _melee_message = "This is why you do your homework! "; _not_enough_points = "My assets... frozen! "; _taking_damage_message = "Why do I even feel pain?! "; _armor_message = "Armor soak increased! "; _being_revived_message = "Can I just say... yeehaw. "; std::string attacks[5] = { "Care to have a friendly duel? ", "I will prove to you my robotic superiority! ", "It's about to get magical! ", "Man versus machine! Very tiny streamlined machine! ", "Dance battle! Or, you know... regular battle. "}; for (int i = 0; i < 5; i++) { _attack_random[i] = attacks[i]; } std::cout << "Let's get this party started! " << "ScavTrap with name " << _name << " created\n"; } ScavTrap::ScavTrap(const ScavTrap &copy_ScavTrap) { *this = copy_ScavTrap; } ScavTrap &ScavTrap::operator=(const ScavTrap &assign_ScavTrap) { _name = assign_ScavTrap._name; _hit_points = assign_ScavTrap._hit_points; _max_hit_points = assign_ScavTrap._max_hit_points; _energy_points = assign_ScavTrap._energy_points; _max_energy_points = assign_ScavTrap._max_energy_points; _level = assign_ScavTrap._level; _melee_attack_damage = assign_ScavTrap._melee_attack_damage; _ranged_attack_damage = assign_ScavTrap._ranged_attack_damage; _armor_damage_reduction = assign_ScavTrap._armor_damage_reduction; _range_message = assign_ScavTrap._range_message; _melee_message = assign_ScavTrap._melee_message; _not_enough_points = assign_ScavTrap._not_enough_points; _taking_damage_message = assign_ScavTrap._taking_damage_message; _armor_message = assign_ScavTrap._armor_message; _being_revived_message = assign_ScavTrap._being_revived_message; for (int i = 0; i < 5; i++) { _attack_random[i] = assign_ScavTrap._attack_random[i]; } return (*this); } void ScavTrap::challengeNewcomer(std::string const &target) { if (_energy_points >= 25) { std::cout << std::setiosflags(std::ios::left) << std::setw(33) << "\033[0;35mENERGY ATTACK!\033[0;0m" << std::resetiosflags(std::ios::left); std::cout << _attack_random[rand() % 5] << _name << " attacks " << target << std::endl; _energy_points -= 25; } else { std::cout << std::setiosflags(std::ios::left) << std::setw(33) << "\033[1;34mOH NO!\033[0;0m" << std::resetiosflags(std::ios::left); std::cout << "Where'd all my bullets go? " << _name << " needs to revive some energy points\n"; } } ScavTrap::~ScavTrap() { std::cout << "You got me! " << "ScavTrap " << _name << " destroyrd\n"; }
2517e611b2e7abc95756b4648a14513559632ac0
644820158857c051ed6eb379b8ad34634b49cefa
/playground/vector_hard.cpp
40deb67cb5ef8e592f411c3d2746fdf95edbf06d
[]
no_license
RajatPawar/hackerrank
ad63748344fccdaa30904d144f256b9aaaa166e2
16a1f3af5581a2f97147c6b2d372d7fd5b84fc0d
refs/heads/master
2021-01-02T22:52:49.526392
2019-04-09T13:06:32
2019-04-09T13:06:32
99,409,667
1
0
null
null
null
null
UTF-8
C++
false
false
2,353
cpp
vector_hard.cpp
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int n, queries, temp, from, to, type; vector<int> arr; scanf("%d %d", &n, &queries); printf("\nN: %d, queries: %d", n, queries); while(n-- > 0) { scanf("%d", &temp); printf("\nArr elem: %d", temp); arr.push_back(temp); } while(queries-- > 0) { scanf("%d %d %d", &type, &from, &to); switch(type) { case 1: { printf("\nBefore: "); for(vector<int>::iterator itr = arr.begin(); itr != arr.end(); itr++) printf("%d ", *itr); // Front vector<int>::iterator itr = arr.begin(), start = arr.begin(), end = arr.begin(); advance(itr, from - 1); advance(end, to); for(; itr < end; itr++, start++) { temp = *itr; arr.erase(itr); arr.insert(start, temp); } printf("\nAfter: "); for(vector<int>::iterator itr = arr.begin(); itr != arr.end(); itr++) printf("%d ", *itr); break; } case 2: { printf("\nBefore: "); for(vector<int>::iterator itr = arr.begin(); itr != arr.end(); itr++) printf("%d ", *itr); vector<int>::iterator itr; itr = arr.begin() + from - 1; //vector<int> temp; for(unsigned i = from - 1; i < to; i++) { printf("\nPoints to %d", temp); itr = arr.begin() + from - 1; itr = arr.erase(itr); temp = *itr; } // arr.push_back(temp); printf("\nAfter: "); for(vector<int>::iterator itr = arr.begin(); itr != arr.end(); itr++) printf("%d ", *itr); break; } default: { perror("\nWrong input"); exit(1); } } } printf("\n"); for(vector<int>::iterator itr = arr.begin(); itr != arr.end(); itr++) printf("%d ", *itr); return 0; }
c6a291835bb6c2215cba85f8e852cb3bb88b59c9
244a4006c72a944fe7d454a39d56c65866933d69
/include/dragon.h
3d510147d54534e4f77628751394c2367bf781a8
[]
no_license
sqinq/My_CPP_Game
9041360a71547a906124f9926a1ef22e7b216329
de52076043dd201db34d862590f741052bcecabd
refs/heads/master
2021-03-16T05:30:39.437309
2017-05-24T00:55:30
2017-05-24T00:55:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
263
h
dragon.h
#ifndef __DRAGON_H__ #define __DRAGON_H__ #include "enemy.h" class Floor; class Dragon : public Enemy { public: // constructor Dragon(Floor * game); // action() is called for the object to move one turn void action(); }; #endif
dc2416e1cf508368c3d7a6d468287b4e97bfe611
e56a08226d0df50c59e3f6b5ba70f9534b20d570
/final_hash_two_step/final.cc
74eb1d0a8cd20b79f50cc68114e9a3697f8b792b
[]
no_license
openopentw/2016-DSA
e9d52c67c5c26c36821f1721e64fa0e564c7c7f0
dead5eb9d999c77cb612330b1109dbe0cd265dd7
refs/heads/master
2021-07-29T12:30:22.085913
2017-07-08T03:36:47
2017-07-08T03:36:47
96,593,665
0
0
null
null
null
null
UTF-8
C++
false
false
2,542
cc
final.cc
#include <cstdio> #include <cstring> #include <iostream> #include <vector> #include <list> #include <string> #include <array> using namespace std; // const int multi = 53, add = 97; const int multi = 553, add = 97; /* Struct */ const int NLINE = 41929539; // const int NHASH = 500000003; // prime number const int NHASH = 41929540; // prime number struct DIC { unsigned key; string str; unsigned freq; }; DIC dictable[NLINE]; struct HASH_DIC { string str; unsigned freq; };/* list<HASH_DIC> hash_dic[NHASH]; inline void table2hash() { for(int i = 0; i < NLINE; ++i) { hash_dic[ dictable[i].key ].push_back ( (HASH_DIC){dictable[i].str, dictable[i].freq} ); } } */ /* Hash */ typedef unsigned hash_type; hash_type hash_function(string *str) { hash_type ret = 0; for(string::iterator i = str->begin(); i != str->end(); ++i) ret += ret * multi + *i - 'a' + add; // notice the multiplier && adder ret %= NHASH; return ret; } /* Judge *//* bool judge(string *str) { hash_type key = hash_function(str); for(list<DIC>::iterator i = hash_dic[key].begin(); i != hash_dic[key].end(); ++i) if(*str == i->str) return 1; return 0; } */ /* INPUT string prep[20] = {"at", "by", "in", "of", "on" , "to", "up", "for", "down", "from" , "near", "than", "with", "about", "after" , "since", "under", "before", "between", "without"}; inline bool isprep(string *str) { for(int i = 0; i < 20; ++i) if(*str == prep[i]) return 1; return 0; } inline void input_test() { char c = 'a'; while(c != EOF) { string str[50]; bool prep[50]; cin >> str[0]; prep[0] = isprep(str); string allstr(str[0]); int nword; for(nword = 1; (c = getchar()) != EOF && c != '\n'; ++nword) { cin >> str[nword]; prep[nword] = isprep(str + nword); allstr += ' ' + str[nword]; } if(nword > 9) { cout << "query: " << allstr << '\n' << "output: 0\n" ; } else if(!nword) { // no prep cout << "query: " << allstr << '\n' << "output: " ; cout << '\n'; } else { cout << "query: " << allstr << '\n' << "output: " ; cout << '\n'; } } return ; } */ int main(int argc, char *argv[]) { /* Input */ char input[256]; strcpy(input, argv[1]); for(int i = 2; i < argc; ++i) strcat(input, argv[i]); puts(input); FILE *fp = fopen(input, "rb"); fread(dictable, sizeof(DIC), NLINE, fp); fclose(fp); cout << dictable[1].str << endl; // DEBUG puts("==FINISH PRE=="); // table2hash(); puts("==FINISH BUILD HASH=="); // input_test(); puts("==FINISH=="); return 0; }
e1f83d842b1048e857900685c9d5cedf495ed4eb
b460b5098115c22c16e58edc1d15f6344a2079a2
/64k/glAssiPhone/p_klask.cpp
214fe7f7582c1f48979c95f42f331d50a24d84c8
[]
no_license
possan/randomjunk
a84836ced188b5dd67ac9cdbf080d43b9bedf629
9e1eda672149bda7efadcc63a7233df295d63473
refs/heads/master
2021-01-22T04:36:34.385324
2011-11-02T22:16:09
2011-11-02T22:16:09
906,668
2
0
null
null
null
null
UTF-8
C++
false
false
3,824
cpp
p_klask.cpp
// klask // fullscreen part #include "almosteverything.h" #include "images.h" #include <stdlib.h> /*#define FULLSCREEN_PIC1 61 #define FULLSCREEN_PIC2 62 #define FULLSCREEN_PIC3 63*/ //#define KLASK_PIC 81 #define KLASK_CYLINDER 82 #define NSIDES 7 #define NROWS 30 #define NOBJECTS 25 float klr[NOBJECTS][3]; void p_klask_list() { srand( 12345 ); for( int k=0; k<NOBJECTS; k++ ) { klr[k][0] = (float)(rand()%360); klr[k][1] = (float)(rand()%360); klr[k][2] = (float)(rand()%360); }; float lxc, xc, lyc, yc, lzc, zc, lvc, vc, zd, vd, lra, ra; zd = 5.0f / (float)NROWS; vd = 1.0f / (float)NROWS; xc = 0; yc = 0; zc = zd; vc = vd; lra = 0.3f; lxc = 0; lyc = 0; lzc = 0; lvc = 0; for( int r=0; r<NROWS; r++ ) { float b = 0.5f - (((float)r / (float)NROWS)/2.0f); ra = 0.3f / ((float)r / 2.0f + 1.0f); //glColor3f( 0.8*b, 0.9*b, 1.0*b ); for( int c=0; c<NSIDES; c++ ) { float x1 = (float)cos( (float)(c+0)*M_PI/(NSIDES/2) ); float y1 = (float)sin( (float)(c+0)*M_PI/(NSIDES/2) ); float x2 = (float)cos( (float)(c+1)*M_PI/(NSIDES/2) ); float y2 = (float)sin( (float)(c+1)*M_PI/(NSIDES/2) ); float u1 = (float)c / (float)NSIDES; float u2 = (float)(c+1) / (float)NSIDES; //glColor3f( (float)c/(float)NSIDES, (float)r/(float)NROWS, 0 ); // glNormal3f( x1*x2, 0, y1*y2 ); glColor3f( b,b,b ); glTexCoord2f( u1, vc ); glVertex3f( ra*x1+xc, zc, ra*y1+yc ); glTexCoord2f( u2, vc ); glVertex3f( ra*x2+xc, zc, ra*y2+yc ); //glColor3f( b1,b1,b1 ); glTexCoord2f( u2, lvc ); glVertex3f( lra*x2+lxc, lzc, lra*y2+lyc ); glTexCoord2f( u1, lvc ); glVertex3f( lra*x1+lxc, lzc, lra*y1+lyc ); }; lxc = xc; lyc = yc; lzc = zc; lvc = vc; lra = ra; //xc += ((float)(rand()%200) - 100.0f) / 200.0f; //yc += ((float)(rand()%200) - 100.0f) / 200.0f; xc += 0.05f*(float)cos( (float)r / 4.3f ); yc += 0.05f*(float)sin( (float)r / 3.6f ); //xc += sin( (float)r / 8.7f ); //yc += cos( (float)r / 8.1f ); zc += zd; vc += vd; //ra += 0.01f; }; }; void p_klask_init() { // glaUploadGif( KLASK_PIC, (unsigned char *)&gif_rost, 123 ); /* glNewList( KLASK_CYLINDER, GL_COMPILE ); glEndList(); */ }; void p_klask_run( EVENT *e ) { float t; glMatrixMode( GL_PROJECTION ); glLoadIdentity(); glTranslatef( 0, 0, -1 ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); glDisable( GL_CULL_FACE ); // glCullFace( GL_BACK ); glDisable( GL_DEPTH_TEST ); glDisable( GL_FOG ); t = e->localTime; glEnable( GL_BLEND ); glBlendFunc( GL_ONE, GL_ONE ); glMatrixMode( GL_MODELVIEW ); //for( float step=0; step<10; step+=3 ) { float t2 = t;// - (step/20.0f); glLoadIdentity(); //glFrustum( -1, 1, -0.75, 0.75, 0.1, 1 ); gluPerspective( 105, 4/3, 1, 1000 ); //MATRIX m; gluLookAt( 5*(float)cos(t2/6), 5*(float)cos(t2/7), 5*(float)sin(t2/5), 5*(float)cos(t2/5), 5*(float)cos(t2/4), 5*(float)sin(t2/3), 0, 1, 0 ); glaSetTexture( GIF_CLOUDS ); glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ); float br = 0.5f*e->renderAmount;// / (float)fmod(b*2,4.0f); for( int n=0; n<NOBJECTS; n++ ) { glPushMatrix(); glRotatef( t2*17+klr[n][0], 1, 0, 0 ); glRotatef( t2*12-klr[n][1], 0, 1, 0 ); glRotatef( t2*10+klr[n][2], 0, 0, 1 ); glRotatef( (float)cos(t2+n)*20, 0, 1, 1 ); glRotatef( (float)sin(t2-n*3)*20, 1, 0, 1 ); glBegin( GL_QUADS ); switch( n%3 ) { case 0: glColor3f( 0.6f*br, 0.4f*br, 0.2f*br ); break; case 1: glColor3f( 0.3f*br, 0.7f*br, 0.4f*br ); break; case 2: glColor3f( 0.2f*br, 0.4f*br, 0.6f*br ); break; }; // glCallList( KLASK_CYLINDER ); p_klask_list(); glEnd(); glPopMatrix(); }; };
6569767d76994eabb05c1ec8e6615f1f73751cde
bf569e5b23eb4799a540ff6765411c31ce1bccfa
/lab1/EVAH/include/TipoGrafo.h
cbfda39b0420ccec85d9833041ce3a4f7e27f861
[]
no_license
sebastianVUCR/LabsDiseno
af56f8efba3e474bb2f51e598d5debf5832b9b14
1da9651871b693bd7e64b26a7940ac8977c65c18
refs/heads/master
2022-11-13T06:25:49.128182
2020-07-14T06:11:24
2020-07-14T06:11:24
259,193,331
0
0
null
null
null
null
UTF-8
C++
false
false
227
h
TipoGrafo.h
#ifndef TIPOGRAFO_H #define TIPOGRAFO_H #include "Grafo.h" class TipoGrafo { public: TipoGrafo(); virtual ~TipoGrafo(); private: Grafo g; }; TipoGrafo::TipoGrafo() { } TipoGrafo::~TipoGrafo() { } #endif // TIPOGRAFO_H
1a2009524a5652031f01c8986b40b61430d3f361
f3c3d3d4fa32e0c3847805066e2e0930a6a44862
/C++/opengl/cw4 dwa/cw4 dwa/jajko_obr.cpp
2a628d8f5fb8c23e697c35944ffb60b5411bc405
[]
no_license
MateuszZet/Mixed
12f6b7c8983a6d890a2ce79873a00d1c818b9eca
875e83a98aeda682b29540b575b8a883fabc872f
refs/heads/master
2022-03-14T16:01:52.640081
2022-02-16T21:55:46
2022-02-16T21:55:46
142,461,845
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
10,989
cpp
jajko_obr.cpp
#include <windows.h> #include <gl/gl.h> #include <gl/glut.h> #include <math.h> #include <time.h> //Definicja typu point3 - punkt w przestrzeni 3D typedef float point3[3]; //Stala PI const float PI = 3.14159265; //Tablica na punkty point3 **pointsTab; //Tablica na kolory punktow point3 **pointsRGB; static GLfloat viewer[] = { 0.0, 0.0, 10.0 }; // inicjalizacja położenia obserwatora static GLfloat fi = 0.0, // kąty obrotu, elewacja i azymut theta = 0.0; static GLfloat pix2angle_x, // przelicznik pikseli na stopnie pix2angle_y; static GLint status = 0; // stan klawiszy myszy // 0 - nie naciśnięto żadnego klawisza // 1 - naciśnięty został lewy klawisz, 2 - prawy static int x_pos_old = 0, // poprzednia pozycja kursora myszy y_pos_old = 0; static int delta_x = 0, // różnica pomiędzy pozycją bieżącą delta_y = 0; // i poprzednią kursora myszy //Parametry programu int N = 40; //Liczba punktow na jaka dzielimy kwadrat jednostkowy int model = 1; //Rodzaj modelu: 1-punkty, 2-siatka, 3-kolorowe trojkaty float verLength = 1.0; //Dlugosc boku kwadratu float viewerR = 10.0; //Promien sfery obserwatora //Funkcja wyliczajaca wspolrzedna X punktu (u,v) w przestrzeni 3D float calc3Dx(float u, float v) { float x, a = v*PI; x = (-90 * pow(u, 5) + 225 * pow(u, 4) - 270 * pow(u, 3) + 180 * pow(u, 2) - 45 * u) * cos(a); return x; } //Funkcja wyliczajaca wspolrzedna Y punktu (u,v) w przestrzeni 3D float calc3Dy(float u, float v) { float y; y = 160 * pow(u, 4) - 320 * pow(u, 3) + 160 * pow(u, 2); return y - 5; } //Funkcja wyliczajaca wspolrzedna Z punktu (u,v) w przestrzeni 3D float calc3Dz(float u, float v) { float z, a = v*PI; z = (-90 * pow(u, 5) + 225 * pow(u, 4) - 270 * pow(u, 3) + 180 * pow(u, 2) - 45 * u) * sin(a); return z; } //Funkcja generujaca siatke puntow, najpierw w 2D, potem w 3D void genPointsMesh(){ float stepXY = verLength / N; //Przypisanie punktom wspolrzednych for (int i = 0; i<N + 1; i++) { for (int j = 0; j<N + 1; j++) { pointsTab[i][j][0] = j*stepXY; pointsTab[i][j][1] = i*stepXY; } } //Przeksztalcenie wspolrzednych z dziedziny parametrycznej //w przestrzen 3D float u, v; for (int i = 0; i<N + 1; i++) { for (int j = 0; j<N + 1; j++) { u = pointsTab[i][j][0]; v = pointsTab[i][j][1]; pointsTab[i][j][0] = calc3Dx(u, v); pointsTab[i][j][1] = calc3Dy(u, v); pointsTab[i][j][2] = calc3Dz(u, v); } } } //Funkcja renderujaca okreslony model jajka void Egg(void){ //Wygenerowanie siatki 3D punktow genPointsMesh(); //Parametry rysowania glColor3f(1.0, 1.0, 1.0); //W zaleznosci od rodzaju modelu switch (model){ //Jesli punkty case 1: { glBegin(GL_POINTS); for (int i = 0; i<N; i++){ for (int j = 0; j<N; j++){ glVertex3fv(pointsTab[i][j]); } } glEnd(); } break; //Jesli siatka case 2: { for (int i = 0; i < N; i++){ for (int j = 0; j < N; j++){ //Pion glBegin(GL_LINES); glVertex3fv(pointsTab[i][j]); glVertex3fv(pointsTab[i][j + 1]); glEnd(); //Poziom glBegin(GL_LINES); glVertex3fv(pointsTab[i][j]); glVertex3fv(pointsTab[i + 1][j]); glEnd(); //Prawo glBegin(GL_LINES); glVertex3fv(pointsTab[i][j]); glVertex3fv(pointsTab[i + 1][j + 1]); glEnd(); //Lewo //glBegin(GL_LINES); //glVertex3fv(pointsTab[i + 1][j]); //glVertex3fv(pointsTab[i][j + 1]); //glEnd(); } } } break; //Jesli wypelnienie case 3: { for (int i = 0; i < N; i++){ for (int j = 0; j < N; j++){ //W jedna strone glBegin(GL_TRIANGLES); glColor3fv(pointsRGB[i][j + 1]); glVertex3fv(pointsTab[i][j + 1]); glColor3fv(pointsRGB[i + 1][j]); glVertex3fv(pointsTab[i + 1][j]); glColor3fv(pointsRGB[i + 1][j + 1]); glVertex3fv(pointsTab[i + 1][j + 1]); glEnd(); //W druga strone glBegin(GL_TRIANGLES); glColor3fv(pointsRGB[i][j]); glVertex3fv(pointsTab[i][j]); glColor3fv(pointsRGB[i + 1][j]); glVertex3fv(pointsTab[i + 1][j]); glColor3fv(pointsRGB[i][j + 1]); glVertex3fv(pointsTab[i][j + 1]); glEnd(); } } } break; } } // Funkcja rysująca osie układu współrzędnych void Axes(void) { point3 x_min = { -2.0, 0.0, 0.0 }; point3 x_max = { 2.0, 0.0, 0.0 }; // początek i koniec obrazu osi x point3 y_min = { 0.0, -2.0, 0.0 }; point3 y_max = { 0.0, 2.0, 0.0 }; // początek i koniec obrazu osi y point3 z_min = { 0.0, 0.0, -2.0 }; point3 z_max = { 0.0, 0.0, 2.0 }; // początek i koniec obrazu osi y glColor3f(1.0f, 0.0f, 0.0f); // kolor rysowania osi - czerwony glBegin(GL_LINES); // rysowanie osi x glVertex3fv(x_min); glVertex3fv(x_max); glEnd(); glColor3f(0.0f, 1.0f, 0.0f); // kolor rysowania - zielony glBegin(GL_LINES); // rysowanie osi y glVertex3fv(y_min); glVertex3fv(y_max); glEnd(); glColor3f(0.0f, 0.0f, 1.0f); // kolor rysowania - niebieski glBegin(GL_LINES); // rysowanie osi z glVertex3fv(z_min); glVertex3fv(z_max); glEnd(); } // Funkcja określająca co ma być rysowane (zawsze wywoływana gdy trzeba // przerysować scenę) void RenderScene(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Czyszczenie okna aktualnym kolorem czyszczącym glLoadIdentity(); // Czyszczenie macierzy bieżącej if (status == 1) { // jeśli lewy klawisz myszy wciśnięty theta += delta_x*pix2angle_x; // modyfikacja kąta obrotu o kąt proporcjonalny fi += delta_y*pix2angle_y; // do różnicy położeń kursora myszy if (theta >= 360.0) theta = 0.0; if (fi >= 360.0) fi = 0.0; } else if (status == 2) { // jeśli prawy klawisz myszy wciśnięty viewerR += 0.1* delta_y; // modyfikacja polozenia obserwatora(zoom) if (viewerR <= 5.0) // ograniczenie zblizenia viewerR = 5.0; if (viewerR >= 25.0) // ograniczenie oddalenia viewerR = 25.0; } //Wspolrzedne obserwatora - wzorki z ZSK viewer[0] = viewerR * cos(theta) * cos(fi); viewer[1] = viewerR * sin(fi); viewer[2] = viewerR * sin(theta) * cos(fi); gluLookAt(viewer[0], viewer[1], viewer[2], 0.0, 0.0, 0.0, 0.0, cos(fi), 0.0); // Zdefiniowanie położenia obserwatora Axes(); // Narysowanie osi przy pomocy funkcji zdefiniowanej powyżej //Renderowanie jajka Egg(); glFlush(); // Przekazanie poleceń rysujących do wykonania glutSwapBuffers(); } //Funkcja - callback dla klawiszy void Keys(unsigned char key, int x, int y) { //Zmiana rodzaju modelu w zaleznosci od klawisza if (key == '1') model = 1; if (key == '2') model = 2; if (key == '3') model = 3; RenderScene(); } // Funkcja ustalająca stan renderowania void MyInit(void) { glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Kolor czyszcący (wypełnienia okna) ustawiono na czarny } // Funkcja ma za zadanie utrzymanie stałych proporcji rysowanych // w przypadku zmiany rozmiarów okna. // Parametry vertical i horizontal (wysokość i szerokość okna) są // przekazywane do funkcji za każdym razem gdy zmieni się rozmiar okna. void ChangeSize(GLsizei horizontal, GLsizei vertical) { pix2angle_x = 360.0*0.1 / (float)horizontal; // przeliczenie pikseli na stopnie pix2angle_y = 360.0*0.1 / (float)vertical; glMatrixMode(GL_PROJECTION); // Przełączenie macierzy bieżącej na macierz projekcji glLoadIdentity(); // Czyszcznie macierzy bieżącej gluPerspective(70.0, 1.0, 1.0, 30.0); // Ustawienie parametrów dla rzutu perspektywicznego if (horizontal <= vertical) glViewport(0, (vertical - horizontal) / 2, horizontal, horizontal); else glViewport((horizontal - vertical) / 2, 0, vertical, vertical); // Ustawienie wielkości okna okna widoku (viewport) w zależności // relacji pomiędzy wysokością i szerokością okna glMatrixMode(GL_MODELVIEW); // Przełączenie macierzy bieżącej na macierz widoku modelu glLoadIdentity(); // Czyszczenie macierzy bieżącej } // Funkcja bada stan myszy i ustawia wartosci odpowiednich zmiennych globalnych void Mouse(int btn, int state, int x, int y) { if (btn == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { x_pos_old = x; // przypisanie aktualnie odczytanej pozycji kursora y_pos_old = y; // jako pozycji poprzedniej status = 1; // wciśnięty został lewy klawisz myszy } else if (btn == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) { y_pos_old = y; // przypisanie aktualnie odczytanej pozycji kursora // jako pozycji poprzedniej status = 2; //wciśnięty został prawy klawisz myszy } else status = 0; // nie został wciśnięty żaden klawisz } // Funkcja monitoruje polozenie kursora myszy i ustawia wartosci odpowiednich // zmiennych globalnych void Motion(GLsizei x, GLsizei y) { delta_x = x - x_pos_old; // obliczenie różnicy położenia kursora myszy x_pos_old = x; // podstawienie bieżacego położenia jako poprzednie delta_y = y - y_pos_old; // obliczenie różnicy położenia kursora myszy y_pos_old = y; // podstawienie bieżacego położenia jako poprzednie glutPostRedisplay(); // przerysowanie obrazu sceny } // Główny punkt wejścia programu. Program działa w trybie konsoli void main(void) { //Ziarno losowosci srand((unsigned)time(NULL)); //Dynamiczna alokacja tablicy punktow pointsTab = new point3*[N + 1]; for (int i = 0; i<N + 1; i++){ pointsTab[i] = new point3[N + 1]; } //Dynamiczna alokacja tablicy i wygenerowanie kolorow losowych dla punktow pointsRGB = new point3*[N + 1]; for (int i = 0; i < N + 1; i++){ pointsRGB[i] = new point3[N + 1]; } for (int i = 0; i < N + 1; i++){ for (int j = 0; j < N + 1; j++){ pointsRGB[i][j][0] = 1.8; //((float)(rand() % 10) + 1) / 10; pointsRGB[i][j][1] = 0.9;//((float)(rand()%10)+1)/10; pointsRGB[i][j][2] = ((float)(rand()%10)+1)/10; } } glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(800, 600); glutCreateWindow("Rzutowanie perspektywyczne, interakcja, jajko"); glutDisplayFunc(RenderScene); // Określenie, że funkcja RenderScene będzie funkcją zwrotną // (callback function). Bedzie ona wywoływana za każdym razem // gdy zajdzie potrzba przeryswania okna // Dla aktualnego okna ustala funkcję zwrotną odpowiedzialną // zazmiany rozmiaru okna glutReshapeFunc(ChangeSize); MyInit(); // Funkcja MyInit() (zdefiniowana powyżej) wykonuje wszelkie // inicjalizacje konieczne przed przystąpieniem do renderowania glEnable(GL_DEPTH_TEST); // Włączenie mechanizmu usuwania powierzchni niewidocznych glutMouseFunc(Mouse); // Ustala funkcję zwrotną odpowiedzialną za badanie stanu myszy glutMotionFunc(Motion); // Ustala funkcję zwrotną odpowiedzialną za badanie ruchu myszy //Rejestracja funkcji zwrotnej dla klawiatury glutKeyboardFunc(Keys); glutMainLoop(); // Funkcja uruchamia szkielet biblioteki GLUT //Zwolnienie pamięci for (int i = 0; i < N + 1; i++){ delete[] pointsTab[i]; delete[] pointsRGB[i]; pointsTab[i] = 0; pointsRGB[i] = 0; } delete[] pointsTab; delete[] pointsRGB; pointsTab = 0; pointsRGB = 0; }
26f3c519827d72e6d04281da101079966291ee9b
eac80658fb291b4d449c37aa0767b1390be9ef53
/src/tracer/src/core/renderer/restir.cpp
a6ba0449610661e5068df993faa92f887bc9928f
[ "MIT" ]
permissive
AirGuanZ/Atrc
92e357a0b18bb8b9b2bbc1eb234f549aba6589ad
9bf8fdbb74affaa047bc40bb452c0d2c9bf0d121
refs/heads/master
2023-07-11T06:31:09.259287
2023-06-25T08:00:10
2023-06-25T08:00:10
147,777,386
484
30
MIT
2023-03-07T13:25:58
2018-09-07T05:56:14
C++
UTF-8
C++
false
false
16,083
cpp
restir.cpp
#include <agz/tracer/create/renderer.h> #include <agz/tracer/core/bsdf.h> #include <agz/tracer/core/camera.h> #include <agz/tracer/core/entity.h> #include <agz/tracer/core/light.h> #include <agz/tracer/core/material.h> #include <agz/tracer/core/renderer.h> #include <agz/tracer/core/renderer_interactor.h> #include <agz/tracer/core/render_target.h> #include <agz/tracer/core/sampler.h> #include <agz/tracer/core/scene.h> #include <agz/tracer/utility/reservoir.h> #include <agz-utils/thread.h> AGZ_TRACER_BEGIN class ReSTIRRenderer : public Renderer { struct ReservoirData { real ideal_pdf = 0; Vec3 light_pos_or_wi; Vec3 light_nor; Vec2 light_uv; const Light *light = nullptr; }; struct Pixel { // accumulated data Spectrum value; float weight = 0; Spectrum albedo; Vec3 normal; real denoise; // per-frame data const BSDF *bsdf = nullptr; Vec3 visible_pos; Vec3 curr_normal; Vec3 wr; }; using ImageBuffer = Image2D<Pixel>; using ImageReservoirs = Image2D<Reservoir<ReservoirData>>; using ThreadPool = thread::thread_group_t; void create_pixel_reservoir( const Vec2i &pixel_coord, ImageBuffer &image_buffer, ImageReservoirs &image_reservoirs, const Scene &scene, NativeSampler &sampler, Arena &bsdf_arena) const { auto &pixel = image_buffer(pixel_coord.y, pixel_coord.x); auto &reservoir = image_reservoirs(pixel_coord.y, pixel_coord.x); pixel.bsdf = nullptr; reservoir.clear(); // generate ray const Vec2 film_coord = { (pixel_coord.x + sampler.sample1().u) / image_reservoirs.width(), (pixel_coord.y + sampler.sample1().u) / image_reservoirs.height(), }; const auto cam_we = scene.get_camera()->sample_we(film_coord, sampler.sample2()); const Ray ray(cam_we.pos_on_cam, cam_we.pos_to_out); // find first intersection EntityIntersection inct; if(!scene.closest_intersection(ray, &inct)) { // fill image buffer Spectrum rad; if(auto light = scene.envir_light()) rad = light->radiance(ray.o, ray.d); rad *= cam_we.throughput; if(rad.is_finite()) { pixel.value += rad; pixel.weight += 1; pixel.denoise += 1; } return; } if(auto light = inct.entity->as_light()) { pixel.value += light->radiance( inct.pos, inct.geometry_coord.z, inct.uv, inct.wr); } const auto shading_point = inct.material->shade(inct, bsdf_arena); // fill gbuffer const real denoise = inct.entity->get_no_denoise_flag() ? 0.0f : 1.0f; pixel.weight += 1; pixel.denoise += denoise; pixel.albedo += shading_point.bsdf->albedo(); pixel.normal += shading_point.shading_normal; pixel.bsdf = shading_point.bsdf; pixel.visible_pos = inct.pos; pixel.curr_normal = inct.geometry_coord.z; pixel.wr = inct.wr; // wrs candidates for(int i = 0; i < params_.M; ++i) { const auto [light, select_light_pdf] = scene.sample_light(sampler.sample1()); const auto light_sample = light->sample(inct.pos, sampler.sample5()); if(!light_sample.valid()) continue; const FVec3 wi = light_sample.ref_to_light(); // compute actual/ideal pdf const real p = select_light_pdf * light_sample.pdf; const FSpectrum bsdf = shading_point.bsdf->eval( wi, inct.wr, TransMode::Radiance); const real absdot = std::abs(cos(wi, inct.geometry_coord.z)); const real p_hat = bsdf.lum() * absdot * light_sample.radiance.lum(); // update resevoir reservoir.update( { p_hat, light->is_area() ? light_sample.pos : wi, light_sample.nor, light_sample.uv, light }, p_hat / p, sampler.sample1().u); } reservoir.M = params_.M; // test visibility and compute corr factor if(reservoir.wsum > real(0)) { if(!test_visibility(scene, inct.pos, reservoir.data)) reservoir.W = 0; else { reservoir.W = reservoir.wsum / (reservoir.data.ideal_pdf * reservoir.M); } } } bool test_visibility( const Scene &scene, const Vec3 &pos, const ReservoirData &red) const { if(red.light->is_area()) return scene.visible(pos, red.light_pos_or_wi + EPS() * red.light_nor); return !scene.has_intersection(Ray(pos, red.light_pos_or_wi, EPS())); } real compute_ideal_pdf(const Pixel &pixel, const ReservoirData &data) const { if(!data.light) return 0; const FVec3 wi = data.light->is_area() ? (data.light_pos_or_wi - pixel.visible_pos) : data.light_pos_or_wi; const Spectrum bsdf = pixel.bsdf->eval(wi, pixel.wr, TransMode::Radiance); const real abscos = std::abs(cos(wi, pixel.curr_normal)); const Spectrum le = data.light->is_area() ? data.light->as_area()->radiance( data.light_pos_or_wi, data.light_nor, data.light_uv, -wi) : data.light->as_envir()->radiance( pixel.visible_pos, wi); return bsdf.lum() * abscos * le.lum(); } void create_frame_reservoirs( ThreadPool &threads, ImageBuffer &image_buffer, ImageReservoirs &image_reservoirs, const Scene &scene, NativeSampler *thread_samplers, Arena *thread_bsdf_arena) const { auto thread_func = [&](int thread_idx, int y) { NativeSampler &sampler = thread_samplers[thread_idx]; Arena &bsdf_arena = thread_bsdf_arena[thread_idx]; for(int x = 0; x < image_reservoirs.width(); ++x) { create_pixel_reservoir( { x, y }, image_buffer, image_reservoirs, scene, sampler, bsdf_arena); if(stop_rendering_) return; } }; parallel_forrange( 0, image_reservoirs.height(), thread_func, threads, params_.worker_count); } void combine_neghbor_reservoirs( const Scene &scene, const Vec2i &pixel_coord, const ImageBuffer &image_buffer, const ImageReservoirs &input_reservoirs, ImageReservoirs &output_reservoirs, NativeSampler &sampler) { const int x_beg = (std::max)( 0, pixel_coord.x - params_.spatial_reuse_radius); const int x_end = (std::min)( input_reservoirs.width(), pixel_coord.x + params_.spatial_reuse_radius + 1); const int y_beg = (std::max)( 0, pixel_coord.y - params_.spatial_reuse_radius); const int y_end = (std::min)( input_reservoirs.height(), pixel_coord.y + params_.spatial_reuse_radius + 1); auto &output = output_reservoirs(pixel_coord.y, pixel_coord.x); output.clear(); auto &pixel = image_buffer(pixel_coord.y, pixel_coord.x); if(!pixel.bsdf) return; static thread_local std::vector<Vec2i> nei_coords; nei_coords.clear(); nei_coords.push_back(pixel_coord); for(int i = 0; i < params_.spatial_reuse_count; ++i) { const int sam_x = math::distribution::uniform_integer( x_beg, x_end, sampler.sample1().u); const int sam_y = math::distribution::uniform_integer( y_beg, y_end, sampler.sample1().u); auto &nei_pixel = image_buffer(sam_y, sam_x); if(!nei_pixel.bsdf) continue; if(dot(nei_pixel.curr_normal, pixel.curr_normal) < 0.93f) continue; nei_coords.push_back({ sam_x, sam_y }); } for(auto &nei_coord : nei_coords) { auto &nei_reservoir = input_reservoirs(nei_coord.y, nei_coord.x); const real p_hat = compute_ideal_pdf(pixel, nei_reservoir.data); auto data = nei_reservoir.data; data.ideal_pdf = p_hat; output.update( data, p_hat * nei_reservoir.W * nei_reservoir.M, sampler.sample1().u); } if(!output.data.light) return; output.M = 0; for(auto &nei_coord : nei_coords) { auto &nei_reservoir = input_reservoirs(nei_coord.y, nei_coord.x); output.M += nei_reservoir.M; } /*float p_hat_sum = 0, pstar = 0; for(auto &nei_coord : nei_coords) { auto &nei_reservoir = input_reservoirs(nei_coord.y, nei_coord.x); auto &nei_pixel = image_buffer(nei_coord.y, nei_coord.x); if(!test_visibility(scene, nei_pixel.visible_pos, output.data)) continue; const real p_hat = compute_ideal_pdf(nei_pixel, output.data); if(p_hat <= 0) continue; p_hat_sum += p_hat * nei_reservoir.M; if(nei_coord == pixel_coord) pstar = p_hat; }*/ if(output.data.ideal_pdf < EPS()) { output.W = 0; } else { const real m = real(1) / output.M; //const real m = p_hat_sum > 0 ? pstar / p_hat_sum : real(0); output.W = m * output.wsum / output.data.ideal_pdf; } } void reuse_spatial( const Scene &scene, ThreadPool &threads, const ImageBuffer &image_buffer, ImageReservoirs &input_reservoirs, ImageReservoirs &output_reservoirs, NativeSampler *thread_samplers) { auto thread_func = [&](int thread_idx, int y) { auto &sampler = thread_samplers[thread_idx]; for(int x = 0; x < input_reservoirs.width(); ++x) { combine_neghbor_reservoirs( scene, { x, y }, image_buffer, input_reservoirs, output_reservoirs, sampler); } }; parallel_forrange( 0, input_reservoirs.height(), thread_func, threads, params_.worker_count); } FSpectrum resolve_pixel( const Scene &scene, const Pixel &pixel, const Reservoir<ReservoirData> &reservoir) { if(reservoir.wsum <= real(0) || !reservoir.data.light) return {}; assert(pixel.bsdf); if(!test_visibility(scene, pixel.visible_pos, reservoir.data)) return {}; const FVec3 wi = reservoir.data.light->is_area() ? (reservoir.data.light_pos_or_wi - pixel.visible_pos) : reservoir.data.light_pos_or_wi; const FSpectrum bsdf = pixel.bsdf->eval(wi, pixel.wr, TransMode::Radiance); const real absdot = abs(cos(pixel.curr_normal, wi)); FSpectrum le; if(auto env = reservoir.data.light->as_envir()) { le = env->radiance(pixel.visible_pos, wi); } else { le = reservoir.data.light->as_area()->radiance( reservoir.data.light_pos_or_wi, reservoir.data.light_nor, reservoir.data.light_uv, -wi); } return bsdf * absdot * le * reservoir.W; } ReSTIRParams params_; public: explicit ReSTIRRenderer(ReSTIRParams params) { params_ = params; params_.worker_count = thread::actual_worker_count(params_.worker_count); } RenderTarget render( FilmFilterApplier filter, Scene &scene, RendererInteractor &reporter) override { const int w = filter.width(), h = filter.height(); ImageBuffer image_buffer (h, w); ImageReservoirs image_reservoirs_a(h, w); ImageReservoirs image_reservoirs_b(h, w); std::vector<NativeSampler> thread_samplers; std::vector<Arena> thread_bsdf_arenas(params_.worker_count); thread_samplers.reserve(params_.worker_count); for(int i = 0; i < params_.worker_count; ++i) thread_samplers.push_back(NativeSampler(i, false)); reporter.begin(); reporter.new_stage(); ThreadPool threads; auto get_img = [&] { return image_buffer.map([](const Pixel &p) { const real w = p.weight; const real ratio = w > 0 ? 1 / w : real(1); return ratio * p.value; }); }; for(int i = 0; i < params_.spp; ++i) { for(auto &a : thread_bsdf_arenas) a.release(); create_frame_reservoirs( threads, image_buffer, image_reservoirs_a, scene, thread_samplers.data(), thread_bsdf_arenas.data()); if(stop_rendering_) break; auto src = &image_reservoirs_a; auto dst = &image_reservoirs_b; for(int j = 0; j < params_.I; ++j) { reuse_spatial( scene, threads, image_buffer, *src, *dst, thread_samplers.data()); std::swap(src, dst); } auto resolve_thread_func = [&](int thread_idx, int y) { for(int x = 0; x < w; ++x) { auto &reservoir = (*src)(y, x); auto &pixel = image_buffer(y, x); const FSpectrum value = resolve_pixel(scene, pixel, reservoir); if(value.is_finite()) image_buffer(y, x).value += value; if(stop_rendering_) break; } }; parallel_forrange( 0, filter.height(), resolve_thread_func, threads, params_.worker_count); reporter.progress(100.0 * (i + 1) / params_.spp, get_img); if(stop_rendering_) break; } reporter.end_stage(); reporter.end(); RenderTarget render_target; render_target.image .initialize(h, w); render_target.albedo .initialize(h, w); render_target.normal .initialize(h, w); render_target.denoise.initialize(h, w); for(int y = 0; y < h; ++y) { for(int x = 0; x < w; ++x) { auto &p = image_buffer(y, x); if(p.weight <= real(0)) continue; const real r = 1 / p.weight; render_target.image(y, x) = r * p.value; render_target.albedo(y, x) = r * p.albedo; render_target.normal(y, x) = r * p.normal; render_target.denoise(y, x) = r * p.denoise; } } return render_target; } }; RC<Renderer> create_restir_renderer(const ReSTIRParams &params) { return newRC<ReSTIRRenderer>(params); } AGZ_TRACER_END
aebff84d4fa028404582cc20d5ac66d904110d3e
d071e6156cf23ddee37a612f71d71a650c27fcfe
/pojpass/poj1083_moving.cpp
5c472735c901ee6bbe4c512609bdebeaae63f2cb
[]
no_license
tsstss123/code
57f1f7d1a1bf68c47712897e2d8945a28e3e9862
e10795c35aac442345f84a58845ada9544a9c748
refs/heads/master
2021-01-24T23:00:08.749712
2013-04-30T12:33:24
2013-04-30T12:33:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
712
cpp
poj1083_moving.cpp
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int MAXN = 201; int s[MAXN], t[MAXN]; int cnt[MAXN]; int main() { int nTest; scanf("%d", &nTest); while (nTest--) { int n; scanf("%d", &n); for (int i = 0; i < n; ++i) { scanf("%d %d", &s[i], &t[i]); if (s[i] > t[i]) { swap(s[i], t[i]); } s[i] = (s[i] + (s[i] & 1)) / 2; t[i] = (t[i] + (t[i] & 1)) / 2; } memset(cnt, 0, sizeof(cnt)); for (int i = 0; i < n; ++i) { for (int j = s[i]; j <= t[i]; ++j) { ++cnt[j]; } } int ans = 0; for (int i = 0; i < MAXN; ++i) { if (ans < cnt[i]) { ans = cnt[i]; } } printf("%d\n", ans * 10); } return 0; }
19b616d74d3408836bf2f6b04d0f1434d213f403
62408a02b44f2fd20c6d54e1f5def0184e69194c
/Kattis/easiest/18939698_AC_0ms_0kB.cpp
f7d8dabb9153a806a1e8cad58ba6e62a8a6f3273
[]
no_license
benedicka/Competitive-Programming
24eb90b8150aead5c13287b62d9dc860c4b9232e
a94ccfc2d726e239981d598e98d1aa538691fa47
refs/heads/main
2023-03-22T10:14:34.889913
2021-03-16T05:33:43
2021-03-16T05:33:43
348,212,250
0
0
null
null
null
null
UTF-8
C++
false
false
399
cpp
18939698_AC_0ms_0kB.cpp
#include<bits/stdc++.h> using namespace std; int n,cnt,x; int sum(int x) { int res=0; while(x!=0) { res+=x%10; x/=10; } return res; } int main() { while(scanf("%d",&n)!=EOF) { cnt = 11; if(n==0) break; x = sum(n); while(x!=sum(n*cnt)) { cnt++; } printf("%d\n",cnt); } return 0; }
8f3b1fd3744e795886398594357f395ed9512f3d
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/third_party/pdfium/xfa/fwl/core/cfwl_event.h
3ef81ff3ba6b65e46bc7a24964e03d22e9e77cf5
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "BSD-3-Clause" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
5,115
h
cfwl_event.h
// Copyright 2016 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #ifndef XFA_FWL_CORE_CFWL_EVENT_H_ #define XFA_FWL_CORE_CFWL_EVENT_H_ #include "core/fxcrt/fx_coordinates.h" #include "core/fxcrt/fx_string.h" #include "core/fxcrt/fx_system.h" #include "xfa/fwl/core/cfwl_message.h" #include "xfa/fwl/core/fwl_error.h" enum class CFWL_EventType { None = 0, CheckStateChanged, CheckWord, Click, Close, CloseUp, ContextMenu, DataSelected, DateChanged, Draw, DrawItem, DropDown, EditChanged, GetSuggestedWords, HoverChanged, Idle, Key, KillFocus, MenuCommand, Mouse, MouseWheel, PostDropDown, PreDropDown, PreSelfAdaption, Scroll, SelectChanged, SetFocus, SizeChanged, TextChanged, TextFull, Validate }; enum FWLEventMask { FWL_EVENT_MOUSE_MASK = 1 << 0, FWL_EVENT_MOUSEWHEEL_MASK = 1 << 1, FWL_EVENT_KEY_MASK = 1 << 2, FWL_EVENT_FOCUSCHANGED_MASK = 1 << 3, FWL_EVENT_DRAW_MASK = 1 << 4, FWL_EVENT_CLOSE_MASK = 1 << 5, FWL_EVENT_SIZECHANGED_MASK = 1 << 6, FWL_EVENT_IDLE_MASK = 1 << 7, FWL_EVENT_CONTROL_MASK = 1 << 8, FWL_EVENT_ALL_MASK = 0xFF }; class CFX_Graphics; class IFWL_Widget; class CFWL_Event { public: CFWL_Event(); virtual ~CFWL_Event(); virtual FWL_Error GetClassName(CFX_WideString& wsClass) const; virtual CFWL_EventType GetClassID() const; uint32_t Release(); IFWL_Widget* m_pSrcTarget; IFWL_Widget* m_pDstTarget; private: uint32_t m_dwRefCount; }; inline CFWL_Event::CFWL_Event() : m_pSrcTarget(nullptr), m_pDstTarget(nullptr), m_dwRefCount(1) {} inline CFWL_Event::~CFWL_Event() {} inline FWL_Error CFWL_Event::GetClassName(CFX_WideString& wsClass) const { return FWL_Error::Succeeded; } inline CFWL_EventType CFWL_Event::GetClassID() const { return CFWL_EventType::None; } inline uint32_t CFWL_Event::Release() { m_dwRefCount--; uint32_t dwRefCount = m_dwRefCount; if (!m_dwRefCount) delete this; return dwRefCount; } #define FWL_EVENT_DEF(classname, eventType, ...) \ class classname : public CFWL_Event { \ public: \ classname(); \ ~classname() override; \ FWL_Error GetClassName(CFX_WideString& wsClass) const override; \ CFWL_EventType GetClassID() const override; \ __VA_ARGS__ \ }; \ inline classname::classname() {} \ inline classname::~classname() {} \ inline FWL_Error classname::GetClassName(CFX_WideString& wsClass) const { \ wsClass = L## #classname; \ return FWL_Error::Succeeded; \ } \ inline CFWL_EventType classname::GetClassID() const { return eventType; } FWL_EVENT_DEF(CFWL_EvtMouse, CFWL_EventType::Mouse, FX_FLOAT m_fx; FX_FLOAT m_fy; uint32_t m_dwFlags; FWL_MouseCommand m_dwCmd;) FWL_EVENT_DEF(CFWL_EvtMouseWheel, CFWL_EventType::MouseWheel, FX_FLOAT m_fx; FX_FLOAT m_fy; FX_FLOAT m_fDeltaX; FX_FLOAT m_fDeltaY; uint32_t m_dwFlags;) FWL_EVENT_DEF(CFWL_EvtKey, CFWL_EventType::Key, uint32_t m_dwKeyCode; uint32_t m_dwFlags; FWL_KeyCommand m_dwCmd;) FWL_EVENT_DEF(CFWL_EvtSetFocus, CFWL_EventType::SetFocus, IFWL_Widget* m_pSetFocus;) FWL_EVENT_DEF(CFWL_EvtKillFocus, CFWL_EventType::KillFocus, IFWL_Widget* m_pKillFocus;) FWL_EVENT_DEF(CFWL_EvtDraw, CFWL_EventType::Draw, CFX_Graphics* m_pGraphics; IFWL_Widget * m_pWidget;) FWL_EVENT_DEF(CFWL_EvtClick, CFWL_EventType::Click) FWL_EVENT_DEF(CFWL_EvtScroll, CFWL_EventType::Scroll, uint32_t m_iScrollCode; FX_FLOAT m_fPos; FX_BOOL * m_pRet;) FWL_EVENT_DEF(CFWL_EvtClose, CFWL_EventType::Close) FWL_EVENT_DEF(CFWL_EvtContextMenu, CFWL_EventType::ContextMenu, FX_FLOAT m_fPosX; FX_FLOAT m_fPosY; IFWL_Widget * m_pOwner;) FWL_EVENT_DEF(CFWL_EvtMenuCommand, CFWL_EventType::MenuCommand, int32_t m_iCommand; void* m_pData;) FWL_EVENT_DEF(CFWL_EvtSizeChanged, CFWL_EventType::SizeChanged, IFWL_Widget* m_pWidget; CFX_RectF m_rtOld; CFX_RectF m_rtNew;) FWL_EVENT_DEF(CFWL_EvtIdle, CFWL_EventType::Idle) #endif // XFA_FWL_CORE_CFWL_EVENT_H_
5eed98172ed4ad6e1f078cb2fa91827cdf1a494a
43a07286cbbdb855a771db0e5a40c8aaf0373c01
/poj/poj2155.cpp
8bccd6c2457f528b23c28554953366d01a26351b
[]
no_license
oscar172772/codes
56537593463e4c6c003c3da75e75400065bfef82
e644c358803ce280284e7360da6302f6b86f1f82
refs/heads/master
2021-01-20T06:00:16.814847
2017-10-03T14:47:05
2017-10-03T14:47:05
89,832,062
2
0
null
null
null
null
UTF-8
C++
false
false
1,421
cpp
poj2155.cpp
#include<cstdlib> #include<cstdio> #include<iostream> #include<cstring> #include<algorithm> using namespace std; const int MAXN=1000; int cass,n,t,c[MAXN+100][MAXN+100]; int x1,x2,y1,y2; char ch; int lowbit(int x){return x&(x^(x-1));} void change(int x,int y,int s) { for(int i=x;i<=n;i+=lowbit(i)) for(int j=y;j<=n;j+=lowbit(j)) c[i][j]+=s; } int query(int x,int y) { int s=0; for(int i=x;i;i-=lowbit(i)) for(int j=y;j;j-=lowbit(j)) s+=c[i][j]; return s%2; } int main() { scanf("%d",&cass); for(int kase=1;kase<=cass;kase++) { memset(c,0,sizeof(c)); scanf("%d%d",&n,&t); for(int i=1;i<=t;i++) { scanf("%c%c",&ch,&ch); if(ch=='C') { scanf("%d%d%d%d",&x1,&y1,&x2,&y2); change(x1,y1,1); change(x2+1,y1,1); change(x1,y2+1,1); change(x2+1,y2+1,1); } if(ch=='Q') { scanf("%d%d",&x1,&y1); printf("%d\n",query(x1,y1)); } /*for(int x=1;x<=n;x++) { for(int y=1;y<=n;y++) cout<<c[x][y]<<' '; cout<<endl; }*/ } printf("\n"); } //system("pause"); return 0; }
0d9d8f793d67fb7770fdb33df46bc371c6b266e3
8c56e1320f9887e1c3921bddf67abeea17f6d16b
/src/tasks/tasks/task.destroy.commstower.hpp
7b5d01a262e6d2aae006fe9ac80e4e420580f499
[]
no_license
roy86/patrolops4
f8ccda220e53a1334748e515fe8c5d52d68a6af0
d99277595a5d310cd4fe64834d1548f6a62385b9
refs/heads/main
2023-08-17T00:56:57.919629
2021-10-04T09:13:33
2021-10-04T09:13:33
387,701,204
0
1
null
null
null
null
UTF-8
C++
false
false
3,937
hpp
task.destroy.commstower.hpp
/* Author: RoyEightySix (https://www.roy86.com.au) Date: 2020-02-10 Description: No description added yet. Parameter(s): _localVariable - Description [DATATYPE, defaults to DEFAULTVALUE] Returns: Function reached the end [BOOL] */ class Task_Destroy_CommsTower { scope = 1; target = -1; typeID = 10; areaSize[] = {1000,1000}; positionSearchRadius = 3000; positionSearchTypes[] = {"Clearing","Forest","SportField"}; positionIsWater = 0; class TaskDetails { title = "Destroy Signal Source"; description[] = { "<t>Ref: %1</t> | <t>Date: %2<br/>AO: %3 %4 near %5</t>" ,"<t size='1.1' color='#FFC600'>Brief:</t> <t>INTEL indicates that %7 forces have set up a comms station near %5. This is likely being used to co-ordinate local %7 forces which has seen an increase in the amount of activity in the area.</t>" ,"<t size='1.1' color='#FFC600'>Action:</t> <t>%6 forces will move to the area to locate and disable any technological assets and collect any intel that is recoverable.</t>" ,"<t size='1.1' color='#FFC600'>Enemy:</t> <t>%7 forces are unknown but are likely guarding the assets with small to medium arms and possibly an additional light technicals.</t>" ,"<t size='1.1' color='#FFC600'>Note:</t> <t>Civilian population are neutral and are unlikely to be a concern. Keep an eye out for watchers who will track %6 movements and report to the enemy.</t>" }; iconType = "fuel"; iconPosition = "position"; textArguments[] = {"randomCode","datetime","worldRegion","worldName","nearestTown","factionBLUshort","factionOPFshort"}; }; class Markers { class marker_A { shape = "RECTANGLE"; brush = "SolidBorder"; colour = "ColorOpfor"; size[] = {0.99,0.99}; alpha = 0.2; }; class marker_B: marker_A { brush = "Border"; size[] = {1.2,1.2}; alpha = 1; }; class marker_C: marker_A { brush = "Border"; size[] = {1.0,1.0}; alpha = 1; }; class marker_D: marker_A { brush = "FDiagonal"; size[] = {1.2,0.1}; alpha = 0.9; direction = 0; distance = 1.1; }; class marker_E: marker_D { direction = 180; }; class marker_F: marker_D { size[] = {1.0,0.1}; direction = 90; angle = 90; }; class marker_G: marker_F { direction = 270; }; }; class Compositions { class CommsTent { position = "positionOffset"; typeIDs[] = {"en_container_comms_intel","en_container_comms_intel2"}; targets[] = {"Land_Communication_F","Land_TTowerSmall_2_F"}; downloadIntel = 1; }; }; class Groups { class EN_Group_1 { probability = 1; position = "positionOffset"; faction = "FactionTypeOPF"; groupTypes[] = {"SquadAmbushINS4","SquadAmbushINS8"}; isPatrolling = 0.9; radius[] = {50,150}; isDefending = 1; occupyBuildings = 1; dropIntel = 1; }; class EN_Group_2: EN_Group_1 { minPlayers = 2; distance[] = {100,150}; radius[] = {150,200}; }; class EN_Group_3: EN_Group_1 { minPlayers = 6; distance[] = {150,200}; radius[] = {200,250}; }; class EN_Vehicle_Group_1 { probability = 0.85; position = "positionOffset"; distance[] = {50,100}; direction[] = {0,360}; faction = "FactionTypeOPF"; vehicleTypes[] = {"CarTurret_INS","Car_INS"}; createCrew = 1; isPatrolling = 0.6; radius[] = {150,250}; }; class EN_Vehicle_Group_2: EN_Vehicle_Group_1 { probability = 0.7; minPlayers = 5; isPatrolling = 1; vehicleTypes[] = {"CarTurret_INS","Armour_APC","I_C_Offroad_02_LMG_F"}; }; class EN_Vehicle_Group_3: EN_Vehicle_Group_2 { probability = 0.7; minPlayers = 10; radius[] = {250,500}; }; class EN_Vehicle_Group_4: EN_Vehicle_Group_3 { probability = 0.7; minPlayers = 10; radius[] = {250,500}; }; }; class Objective { class Succeeded { state = 1; // 0:Created, 1:Succeeded, 2: Failed, 3: Canceled condition = "_targetsdestroyed"; }; }; };
63948c84fe8f544b488e2733236b80c108f1a8c5
ea741e687f1ca44eff65c29b8ea2e16fd6d9628d
/Anno 2018-2019/Altro/Programmazione Legumi/equazioniSecondoGrado.cpp
3d4aefaf8637c51d62c00af709dbe0031e6c44b1
[]
no_license
fuserale/Baronio
cad84036e80bd9a8adff4fa4398597d74622ed89
18f41404cd836d69e7b3f1d9df3dd38bd7e6c003
refs/heads/master
2020-08-05T15:47:47.896393
2019-10-18T17:10:04
2019-10-18T17:10:04
212,599,019
0
0
null
null
null
null
ISO-8859-13
C++
false
false
658
cpp
equazioniSecondoGrado.cpp
#include<iostream> #include<math.h> using namespace std; int main(){ double a,b,c; double delta; double x1,x2; //mi faccio dare coefficienti cout<<"dammi il valore di a "<<endl; cin>>a; cout<<"dammi il valore di b "<<endl; cin>>b; cout<<"dammi il valore di c "<<endl; cin>>c; //troverņ il delta delta=b*b-4*a*c; cout<<"il delta \212 "<<delta<<endl; //trovo se delta ha valore maggiore o uguale a zero if(delta>=0){ x1=(-b+sqrt(delta))/2*a; x2=(-b-sqrt(delta))/2*a; cout<<"la prima soluzione \212 "<<x1<<endl; cout<<"la seconda soluzione \212 "<<x2<<endl; } else{ cout<<"l'equazione \212 impossibile"<<endl; } }
bd30fca11b33e757a32e57536f941d147495be6c
31ac07ecd9225639bee0d08d00f037bd511e9552
/externals/OCCTLib/inc/Convert_GridPolynomialToPoles.hxx
56508e42e1cb94041cf7a2f4571ddd8f1913304d
[]
no_license
litao1009/SimpleRoom
4520e0034e4f90b81b922657b27f201842e68e8e
287de738c10b86ff8f61b15e3b8afdfedbcb2211
refs/heads/master
2021-01-20T19:56:39.507899
2016-07-29T08:01:57
2016-07-29T08:01:57
64,462,604
1
0
null
null
null
null
UTF-8
C++
false
false
5,717
hxx
Convert_GridPolynomialToPoles.hxx
// This file is generated by WOK (CPPExt). // Please do not edit this file; modify original file instead. // The copyright and license terms as defined for the original file apply to // this header file considered to be the "object code" form of the original source. #ifndef _Convert_GridPolynomialToPoles_HeaderFile #define _Convert_GridPolynomialToPoles_HeaderFile #ifndef _Standard_HeaderFile #include <Standard.hxx> #endif #ifndef _Standard_DefineAlloc_HeaderFile #include <Standard_DefineAlloc.hxx> #endif #ifndef _Standard_Macro_HeaderFile #include <Standard_Macro.hxx> #endif #ifndef _Handle_TColStd_HArray1OfReal_HeaderFile #include <Handle_TColStd_HArray1OfReal.hxx> #endif #ifndef _Handle_TColStd_HArray1OfInteger_HeaderFile #include <Handle_TColStd_HArray1OfInteger.hxx> #endif #ifndef _Handle_TColgp_HArray2OfPnt_HeaderFile #include <Handle_TColgp_HArray2OfPnt.hxx> #endif #ifndef _Standard_Integer_HeaderFile #include <Standard_Integer.hxx> #endif #ifndef _Standard_Boolean_HeaderFile #include <Standard_Boolean.hxx> #endif #ifndef _Handle_TColStd_HArray2OfInteger_HeaderFile #include <Handle_TColStd_HArray2OfInteger.hxx> #endif class TColStd_HArray1OfReal; class TColStd_HArray1OfInteger; class TColgp_HArray2OfPnt; class Standard_DomainError; class StdFail_NotDone; class TColStd_HArray2OfInteger; class Convert_GridPolynomialToPoles { public: DEFINE_STANDARD_ALLOC //! To only one polynomial Surface. <br> //! The Length of <PolynomialUIntervals> and <PolynomialVIntervals> <br> //! have to be 2. <br> //! This values defined the parametric domain of the Polynomial Equation. <br> //! <br> //! Coefficients : <br> //! The <Coefficients> have to be formated than an "C array" <br> //! [MaxUDegree+1] [MaxVDegree+1] [3] <br> //! <br> Standard_EXPORT Convert_GridPolynomialToPoles(const Standard_Integer MaxUDegree,const Standard_Integer MaxVDegree,const Handle(TColStd_HArray1OfInteger)& NumCoeff,const Handle(TColStd_HArray1OfReal)& Coefficients,const Handle(TColStd_HArray1OfReal)& PolynomialUIntervals,const Handle(TColStd_HArray1OfReal)& PolynomialVIntervals); //! To one grid of polynomial Surface. <br> //! Warning! <br> //! Continuity in each parametric direction can be at MOST the <br> //! maximum degree of the polynomial functions. <br> //! <br> //! <TrueUIntervals>, <TrueVIntervals> : <br> //! this is the true parameterisation for the composite surface <br> //! <br> //! Coefficients : <br> //! The Coefficients have to be formated than an "C array" <br> //! [NbVSurfaces] [NBUSurfaces] [MaxUDegree+1] [MaxVDegree+1] [3] <br> //! raises DomainError if <NumCoeffPerSurface> is not a <br> //! [1, NbVSurfaces*NbUSurfaces, 1,2] array. <br> //! if <Coefficients> is not a <br> Standard_EXPORT Convert_GridPolynomialToPoles(const Standard_Integer NbUSurfaces,const Standard_Integer NBVSurfaces,const Standard_Integer UContinuity,const Standard_Integer VContinuity,const Standard_Integer MaxUDegree,const Standard_Integer MaxVDegree,const Handle(TColStd_HArray2OfInteger)& NumCoeffPerSurface,const Handle(TColStd_HArray1OfReal)& Coefficients,const Handle(TColStd_HArray1OfReal)& PolynomialUIntervals,const Handle(TColStd_HArray1OfReal)& PolynomialVIntervals,const Handle(TColStd_HArray1OfReal)& TrueUIntervals,const Handle(TColStd_HArray1OfReal)& TrueVIntervals); Standard_EXPORT void Perform(const Standard_Integer UContinuity,const Standard_Integer VContinuity,const Standard_Integer MaxUDegree,const Standard_Integer MaxVDegree,const Handle(TColStd_HArray2OfInteger)& NumCoeffPerSurface,const Handle(TColStd_HArray1OfReal)& Coefficients,const Handle(TColStd_HArray1OfReal)& PolynomialUIntervals,const Handle(TColStd_HArray1OfReal)& PolynomialVIntervals,const Handle(TColStd_HArray1OfReal)& TrueUIntervals,const Handle(TColStd_HArray1OfReal)& TrueVIntervals) ; Standard_EXPORT Standard_Integer NbUPoles() const; Standard_EXPORT Standard_Integer NbVPoles() const; //! returns the poles of the BSpline Surface <br> Standard_EXPORT const Handle_TColgp_HArray2OfPnt& Poles() const; Standard_EXPORT Standard_Integer UDegree() const; Standard_EXPORT Standard_Integer VDegree() const; Standard_EXPORT Standard_Integer NbUKnots() const; Standard_EXPORT Standard_Integer NbVKnots() const; //! Knots in the U direction <br> Standard_EXPORT const Handle_TColStd_HArray1OfReal& UKnots() const; //! Knots in the V direction <br> Standard_EXPORT const Handle_TColStd_HArray1OfReal& VKnots() const; //! Multiplicities of the knots in the U direction <br> Standard_EXPORT const Handle_TColStd_HArray1OfInteger& UMultiplicities() const; //! Multiplicities of the knots in the V direction <br> Standard_EXPORT const Handle_TColStd_HArray1OfInteger& VMultiplicities() const; Standard_EXPORT Standard_Boolean IsDone() const; protected: private: Standard_EXPORT void BuildArray(const Standard_Integer Degree,const Handle(TColStd_HArray1OfReal)& Knots,const Standard_Integer Continuty,Handle(TColStd_HArray1OfReal)& FlatKnots,Handle(TColStd_HArray1OfInteger)& Mults,Handle(TColStd_HArray1OfReal)& Parameters) const; Handle_TColStd_HArray1OfReal myUFlatKnots; Handle_TColStd_HArray1OfReal myVFlatKnots; Handle_TColStd_HArray1OfReal myUKnots; Handle_TColStd_HArray1OfReal myVKnots; Handle_TColStd_HArray1OfInteger myUMults; Handle_TColStd_HArray1OfInteger myVMults; Handle_TColgp_HArray2OfPnt myPoles; Standard_Integer myUDegree; Standard_Integer myVDegree; Standard_Boolean myDone; }; // other Inline functions and methods (like "C++: function call" methods) #endif
4169c69496d705cf25af365c21326f3860abd2c7
0d0f9ee25b1abd5e6ad0d9dfd328e32f8e1fbfc4
/script.cpp
5b27167bb796972f5b351fdcc535a473a168d7a9
[]
no_license
gozobadrian/Kill-Frenzy
eb34094075ebbaaccfe73d28e69c1ee6016732a8
210da978b702c95bfd13d5322875467baaafc83a
refs/heads/master
2021-01-17T16:20:31.612772
2016-07-11T08:43:01
2016-07-11T08:43:01
63,051,152
1
0
null
null
null
null
UTF-8
C++
false
false
14,384
cpp
script.cpp
/* THIS FILE IS A PART OF GTA V SCRIPT HOOK SDK http://dev-c.com (C) Alexander Blade 2015 */ ///Mod by YUNoCake #include "script.h" #include <string> #include <fstream> #include <ctime> int key, playerID; void readConfigFile() { std::ifstream file("Kill Frenzy.ini"); std::string temp; std::getline(file, temp); key = atoi(temp.c_str()); } bool get_key_pressed(int nVirtKey) { return (GetAsyncKeyState(nVirtKey) & 0x8000) != 0; } int $(char *hash) { return GAMEPLAY::GET_HASH_KEY(hash); } std::string statusText; DWORD statusTextDrawTicksMax; bool statusTextGxtEntry; void update_status_text() { if (GetTickCount() < statusTextDrawTicksMax) { UI::SET_TEXT_FONT(0); UI::SET_TEXT_SCALE(3.5, 3.5); UI::SET_TEXT_COLOUR(230, 92, 0, 255); UI::SET_TEXT_WRAP(0.0, 1.0); UI::SET_TEXT_CENTRE(1); UI::SET_TEXT_DROPSHADOW(0, 0, 0, 0, 0); UI::SET_TEXT_EDGE(0, 87, 46, 176, 255); if (statusTextGxtEntry) { UI::_SET_TEXT_ENTRY((char *)statusText.c_str()); } else { UI::_SET_TEXT_ENTRY("STRING"); UI::_ADD_TEXT_COMPONENT_STRING((char *)statusText.c_str()); } UI::_DRAW_TEXT(0.5, 0.4); } } void update_timer_text() { if (GetTickCount() < statusTextDrawTicksMax) { UI::SET_TEXT_FONT(0); UI::SET_TEXT_SCALE(0.70, 0.70); UI::SET_TEXT_COLOUR(255, 255, 255, 255); UI::SET_TEXT_WRAP(0.0, 1.0); UI::SET_TEXT_CENTRE(1); UI::SET_TEXT_DROPSHADOW(10, 0, 0, 0, 200); UI::SET_TEXT_EDGE(0, 0, 0, 0, 205); if (statusTextGxtEntry) { UI::_SET_TEXT_ENTRY((char *)statusText.c_str()); } else { UI::_SET_TEXT_ENTRY("STRING"); UI::_ADD_TEXT_COMPONENT_STRING((char *)statusText.c_str()); } UI::_DRAW_TEXT(0.5, 0.0); } } void update_ask_text() { if (GetTickCount() < statusTextDrawTicksMax) { UI::SET_TEXT_FONT(1); UI::SET_TEXT_SCALE(0.90, 0.90); UI::SET_TEXT_COLOUR(255, 255, 255, 255); UI::SET_TEXT_WRAP(0.0, 1.0); UI::SET_TEXT_CENTRE(0); UI::SET_TEXT_DROPSHADOW(0, 0, 0, 0, 0); UI::SET_TEXT_EDGE(0, 0, 0, 0, 205); if (statusTextGxtEntry) { UI::_SET_TEXT_ENTRY((char *)statusText.c_str()); } else { UI::_SET_TEXT_ENTRY("STRING"); UI::_ADD_TEXT_COMPONENT_STRING((char *)statusText.c_str()); } UI::_DRAW_TEXT(0.0, 0.2); } } void set_status_text(std::string str, DWORD time = 2500, bool isGxtEntry = false) { statusText = str; statusTextDrawTicksMax = GetTickCount() + time; statusTextGxtEntry = isGxtEntry; } void addCash(long amount) { char statusName[32]; sprintf_s(statusName, "SP%d_TOTAL_CASH", playerID); Hash hash = $(statusName); int cash; STATS::STAT_GET_INT(hash, &cash, -1); cash += amount; STATS::STAT_SET_INT(hash, cash, 1); } void addAttributes() { Player player = PLAYER::PLAYER_ID(); PLAYER::SET_PLAYER_WANTED_LEVEL(player, 0, false); PLAYER::SET_PLAYER_WANTED_LEVEL_NOW(player, false); } void frenzyMessage(std::string message) { DWORD time = GetTickCount() + 2500; set_status_text(message); while (GetTickCount() < time) { update_status_text(); WAIT(0); } } void infiniteAmmo(char *weaponName) { Ped playerPed = PLAYER::PLAYER_PED_ID(); if (WEAPON::IS_WEAPON_VALID($(weaponName))) { int maxClipAmmo; maxClipAmmo = WEAPON::GET_MAX_AMMO_IN_CLIP(playerPed, $(weaponName), 1); if (maxClipAmmo > 0) WEAPON::SET_AMMO_IN_CLIP(playerPed, $(weaponName), maxClipAmmo); } } void checkIfDestroyed(int killedPedsBeforeFrenzy, int totalPedsToKill, int &pedsToKill) { int destroyedCars; char statusName[32]; sprintf_s(statusName, "SP%d_CARS_EXPLODED", playerID); Hash hash = $(statusName); STATS::STAT_GET_INT(hash, &destroyedCars, -1); destroyedCars -= killedPedsBeforeFrenzy; pedsToKill = totalPedsToKill - destroyedCars; } void checkIfDead(int killedPedsBeforeFrenzy, int totalPedsToKill, int &pedsToKill, bool copsOnly) { int killedPeds; int killedInnocents = 0, killedCops = 0, killedSwat = 0; char statusName[32]; Hash hash; if (copsOnly == false) { sprintf_s(statusName, "SP%d_KILLS_INNOCENTS", playerID); hash = $(statusName); STATS::STAT_GET_INT(hash, &killedInnocents, -1); } sprintf_s(statusName, "SP%d_KILLS_COP", playerID); hash = $(statusName); STATS::STAT_GET_INT(hash, &killedCops, -1); sprintf_s(statusName, "SP%d_KILLS_SWAT", playerID); hash = $(statusName); STATS::STAT_GET_INT(hash, &killedSwat, -1); killedPeds = killedInnocents + killedCops + killedSwat; killedPeds -= killedPedsBeforeFrenzy; pedsToKill = totalPedsToKill - killedPeds; } void convertToString(bool carFrenzy, int frenzyTime, int pedsToKill, std::string &stringTime, bool copsOnly) { std::string stringMinutes, stringSeconds, stringPedsToKill; int seconds, minutes; seconds = frenzyTime; minutes = frenzyTime / 60; seconds = seconds - minutes * 60; stringMinutes = std::to_string(minutes); if (minutes < 10) stringMinutes = "0" + stringMinutes; stringSeconds = std::to_string(seconds); if (seconds < 10) stringSeconds = "0" + stringSeconds; stringPedsToKill = std::to_string(pedsToKill); if (copsOnly) stringTime = "Cops to kill: " + stringPedsToKill + '\n' + stringMinutes + ":" + stringSeconds; else if (carFrenzy == false) stringTime = "Pedestrians to kill: " + stringPedsToKill + '\n' + stringMinutes + ":" + stringSeconds; else stringTime = "Vehicles to destroy: " + stringPedsToKill + '\n' + stringMinutes + ":" + stringSeconds; } void startTimer(bool carFrenzy, int &frenzyTime, int killedPedsBeforeFrenzy, int totalPedsToKill, int pedsToKill, char *weaponName, bool copsOnly) { Player player = PLAYER::PLAYER_ID(); std::string stringTime; DWORD oneSecond; while (frenzyTime >= 0 && pedsToKill > 0) { convertToString(carFrenzy, frenzyTime, pedsToKill, stringTime, copsOnly); set_status_text(stringTime); oneSecond = GetTickCount() + 1000; while (GetTickCount() < oneSecond) { update_timer_text(); if (carFrenzy == false) checkIfDead(killedPedsBeforeFrenzy, totalPedsToKill, pedsToKill, copsOnly); else checkIfDestroyed(killedPedsBeforeFrenzy, totalPedsToKill, pedsToKill); infiniteAmmo(weaponName); WAIT(0); } if (PLAYER::IS_PLAYER_DEAD(player)) frenzyTime = 0; frenzyTime--; } } void totalDestroyedCars(int &killedPedsBeforeFrenzy) { char statusName[32]; sprintf_s(statusName, "SP%d_CARS_EXPLODED", playerID); Hash hash = $(statusName); STATS::STAT_GET_INT(hash, &killedPedsBeforeFrenzy, -1); } void totalDeadPeds(int &killedPedsBeforeFrenzy, bool copsOnly) { int killedInnocents, killedCops, killedSwat; char statusName[32]; sprintf_s(statusName, "SP%d_KILLS_INNOCENTS", playerID); Hash hash = $(statusName); STATS::STAT_GET_INT(hash, &killedInnocents, -1); if (copsOnly) killedInnocents = 0; sprintf_s(statusName, "SP%d_KILLS_COP", playerID); hash = $(statusName); STATS::STAT_GET_INT(hash, &killedCops, -1); sprintf_s(statusName, "SP%d_KILLS_SWAT", playerID); hash = $(statusName); STATS::STAT_GET_INT(hash, &killedSwat, -1); killedPedsBeforeFrenzy = killedInnocents + killedCops + killedSwat; } void giveWeapon(char *weaponName) { Ped playerPed = PLAYER::PLAYER_PED_ID(); int maxClipAmmo = WEAPON::GET_MAX_AMMO_IN_CLIP(playerPed, $(weaponName), 1); WEAPON::GIVE_WEAPON_TO_PED(playerPed, $(weaponName), maxClipAmmo, true, true); } void startKillFrenzy(bool carFrenzy, int frenzyTime, int totalPedsToKill, int reward, char *weaponName, bool copsOnly) { Player player = PLAYER::PLAYER_ID(); int pedsToKill,killedPedsBeforeFrenzy; giveWeapon(weaponName); frenzyMessage("KILL FRENZY!"); pedsToKill = totalPedsToKill; if (carFrenzy == false) totalDeadPeds(killedPedsBeforeFrenzy, copsOnly); else totalDestroyedCars(killedPedsBeforeFrenzy); startTimer(carFrenzy, frenzyTime, killedPedsBeforeFrenzy, totalPedsToKill, pedsToKill, weaponName, copsOnly); if (PLAYER::IS_PLAYER_DEAD(player) == false) addAttributes(); if (frenzyTime <= 0) { frenzyMessage("FRENZY FAILED"); } else { frenzyMessage("FRENZY PASSED"); addCash(10000); GAMEPLAY::DO_AUTO_SAVE(); } if (PLAYER::IS_PLAYER_DEAD(player) == false) addAttributes(); } void askToStart(bool carFrenzy, int frenzyTime, int pedsToKill, int reward, char *weaponName, bool copsOnly) { set_status_text("Press the assigned key\nto start the Kill Frenzy!"); DWORD oneSecond = GetTickCount() + 1000; while (GetTickCount() < oneSecond) { update_ask_text(); if (get_key_pressed(key)) startKillFrenzy(carFrenzy, frenzyTime, pedsToKill, reward, weaponName, copsOnly); WAIT(0); } } void drawMarkers() { Vector3 playerPosition; playerPosition = ENTITY::GET_OFFSET_FROM_ENTITY_IN_WORLD_COORDS(PLAYER::PLAYER_PED_ID(), 0.0, 0.0, 0.0); //Main LS Customs GRAPHICS::DRAW_MARKER(0, -354.931, -125.301, 39.431, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.75f, 0.75f, 0.75f, 0, 143, 0, 100, false, true, 2, false, false, false, false); if (-356.931 <= playerPosition.x && -352.931 >= playerPosition.x && -127.301 <= playerPosition.y && -123.301 >= playerPosition.y && 37.431 <= playerPosition.z && 41.431 >= playerPosition.z) { while (-356.931 <= playerPosition.x && -352.931 >= playerPosition.x && -127.301 <= playerPosition.y && -123.301 >= playerPosition.y && 37.431 <= playerPosition.z && 41.431 >= playerPosition.z) { askToStart(false, 60, 5, 10000, "WEAPON_MICROSMG", true); playerPosition = ENTITY::GET_OFFSET_FROM_ENTITY_IN_WORLD_COORDS(PLAYER::PLAYER_PED_ID(), 0.0, 0.0, 0.0); } } //LS Customs 2 GRAPHICS::DRAW_MARKER(0, 721.836, -1070.22, 23.0624, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.75f, 0.75f, 0.75f, 0, 143, 0, 100, false, true, 2, false, false, false, false); if (719.836 <= playerPosition.x && 723.836 >= playerPosition.x && -1072.22 <= playerPosition.y && -1068.22 >= playerPosition.y && 21.0624 <= playerPosition.z && 25.0624 >= playerPosition.z) { while (719.836 <= playerPosition.x && 723.836 >= playerPosition.x && -1072.22 <= playerPosition.y && -1068.22 >= playerPosition.y && 21.0624 <= playerPosition.z && 25.0624 >= playerPosition.z) { askToStart(true, 60, 10, 20000, "WEAPON_RPG", false); playerPosition = ENTITY::GET_OFFSET_FROM_ENTITY_IN_WORLD_COORDS(PLAYER::PLAYER_PED_ID(), 0.0, 0.0, 0.0); } } //LS Customs 3 GRAPHICS::DRAW_MARKER(0, -1141.92, -1992.51, 13.1642, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.75f, 0.75f, 0.75f, 0, 143, 0, 100, false, true, 2, false, false, false, false); if (-1143.92 <= playerPosition.x && -1139.92 >= playerPosition.x && -1994.51 <= playerPosition.y && -1990.51 >= playerPosition.y && 11.1642 <= playerPosition.z && 15.1642 >= playerPosition.z) { while (-1143.92 <= playerPosition.x && -1139.92 >= playerPosition.x && -1994.51 <= playerPosition.y && -1990.51 >= playerPosition.y && 11.1642 <= playerPosition.z && 15.1642 >= playerPosition.z) { askToStart(false, 180, 30, 50000, "WEAPON_RPG", false); playerPosition = ENTITY::GET_OFFSET_FROM_ENTITY_IN_WORLD_COORDS(PLAYER::PLAYER_PED_ID(), 0.0, 0.0, 0.0); } } //LS Customs 4 GRAPHICS::DRAW_MARKER(0, 1205.62, 2657.84, 37.827, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.75f, 0.75f, 0.75f, 0, 143, 0, 100, false, true, 2, false, false, false, false); if (1203.62 <= playerPosition.x && 1207.62 >= playerPosition.x && 2655.84 <= playerPosition.y && 2659.84 >= playerPosition.y && 35.827 <= playerPosition.z && 39.827 >= playerPosition.z) { while (1203.62 <= playerPosition.x && 1207.62 >= playerPosition.x && 2655.84 <= playerPosition.y && 2659.84 >= playerPosition.y && 35.827 <= playerPosition.z && 39.827 >= playerPosition.z) { askToStart(false, 60, 5, 50000, "WEAPON_PISTOL", true); playerPosition = ENTITY::GET_OFFSET_FROM_ENTITY_IN_WORLD_COORDS(PLAYER::PLAYER_PED_ID(), 0.0, 0.0, 0.0); } } //LS Customs 5 GRAPHICS::DRAW_MARKER(0, 133.336, 6637.04, 31.7842, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.75f, 0.75f, 0.75f, 0, 143, 0, 100, false, true, 2, false, false, false, false); if (131.336 <= playerPosition.x && 135.336 >= playerPosition.x && 6635.04 <= playerPosition.y && 6639.04 >= playerPosition.y && 29.7842 <= playerPosition.z && 33.7842 >= playerPosition.z) { while (131.336 <= playerPosition.x && 135.336 >= playerPosition.x && 6635.04 <= playerPosition.y && 6639.04 >= playerPosition.y && 29.7842 <= playerPosition.z && 33.7842 >= playerPosition.z) { askToStart(false, 60, 10, 25000, "WEAPON_RPG", true); playerPosition = ENTITY::GET_OFFSET_FROM_ENTITY_IN_WORLD_COORDS(PLAYER::PLAYER_PED_ID(), 0.0, 0.0, 0.0); } } //AmmuNation 1 GRAPHICS::DRAW_MARKER(0, -3157.51, 1090.03, 20.8561, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.75f, 0.75f, 0.75f, 0, 143, 0, 100, false, true, 2, false, false, false, false); if (-3159.51 <= playerPosition.x && -3155.51 >= playerPosition.x && 1088.03 <= playerPosition.y && 1092.03 >= playerPosition.y && 18.8561 <= playerPosition.z && 22.8561 >= playerPosition.z) { while (-3159.51 <= playerPosition.x && -3155.51 >= playerPosition.x && 1088.03 <= playerPosition.y && 1092.03 >= playerPosition.y && 18.8561 <= playerPosition.z && 22.8561 >= playerPosition.z) { askToStart(false, 120, 15, 50000, "WEAPON_PUMPSHOTGUN", false); playerPosition = ENTITY::GET_OFFSET_FROM_ENTITY_IN_WORLD_COORDS(PLAYER::PLAYER_PED_ID(), 0.0, 0.0, 0.0); } } //AmmuNation 2 GRAPHICS::DRAW_MARKER(0, 2555.89, 288.768, 108.461, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.75f, 0.75f, 0.75f, 0, 143, 0, 100, false, true, 2, false, false, false, false); if (2553.89 <= playerPosition.x && 2557.89 >= playerPosition.x && 286.768 <= playerPosition.y && 290.768 >= playerPosition.y && 106.461 <= playerPosition.z && 110.461 >= playerPosition.z) { while (2553.89 <= playerPosition.x && 2557.89 >= playerPosition.x && 286.768 <= playerPosition.y && 290.768 >= playerPosition.y && 106.461 <= playerPosition.z && 110.461 >= playerPosition.z) { askToStart(false, 120, 20, 20000, "WEAPON_MINIGUN", false); playerPosition = ENTITY::GET_OFFSET_FROM_ENTITY_IN_WORLD_COORDS(PLAYER::PLAYER_PED_ID(), 0.0, 0.0, 0.0); } } } void main() { Player player = PLAYER::PLAYER_ID(); readConfigFile(); while (true) { if (PLAYER::IS_PLAYER_DEAD(player) == false) { Ped playerPed = PLAYER::PLAYER_PED_ID(); if (PED::IS_PED_MODEL(playerPed, $("Player_Zero"))) playerID = 0; else if (PED::IS_PED_MODEL(playerPed, $("Player_One"))) playerID = 1; else if (PED::IS_PED_MODEL(playerPed, $("Player_Two"))) playerID = 2; drawMarkers(); } WAIT(0); } } void ScriptMain() { srand(GetTickCount()); main(); }
dbb11f6cb86920c2eeeba10505f8fe04bcd6ab64
1c024dfbca35f4c829d4b47bdfe900d1b1a2303b
/shell/common/gin_helper/function_template_extensions.h
7420ffde724cab029eabdb9c8f958c6ed1567894
[ "MIT" ]
permissive
electron/electron
1ba6e31cf40f876044bff644ec49f8ec4923ca6a
0b0707145b157343c42266d2586ed9413a1d54f5
refs/heads/main
2023-09-01T04:28:11.016383
2023-08-31T14:36:43
2023-08-31T14:36:43
9,384,267
99,768
18,388
MIT
2023-09-14T19:50:49
2013-04-12T01:47:36
C++
UTF-8
C++
false
false
2,175
h
function_template_extensions.h
// Copyright 2020 Slack Technologies, Inc. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE.chromium file. #ifndef ELECTRON_SHELL_COMMON_GIN_HELPER_FUNCTION_TEMPLATE_EXTENSIONS_H_ #define ELECTRON_SHELL_COMMON_GIN_HELPER_FUNCTION_TEMPLATE_EXTENSIONS_H_ #include <utility> #include "gin/function_template.h" #include "shell/common/gin_helper/error_thrower.h" // This extends the functionality in //gin/function_template.h for "special" // arguments to gin-bound methods. // It's the counterpart to function_template.h, which includes these methods // in the gin_helper namespace. namespace gin { // Support absl::optional as an argument. template <typename T> bool GetNextArgument(Arguments* args, const InvokerOptions& invoker_options, bool is_first, absl::optional<T>* result) { T converted; // Use gin::Arguments::GetNext which always advances |next| counter. if (args->GetNext(&converted)) result->emplace(std::move(converted)); return true; } inline bool GetNextArgument(Arguments* args, const InvokerOptions& invoker_options, bool is_first, gin_helper::ErrorThrower* result) { *result = gin_helper::ErrorThrower(args->isolate()); return true; } // Like gin::CreateFunctionTemplate, but doesn't remove the template's // prototype. template <typename Sig> v8::Local<v8::FunctionTemplate> CreateConstructorFunctionTemplate( v8::Isolate* isolate, base::RepeatingCallback<Sig> callback, InvokerOptions invoker_options = {}) { typedef internal::CallbackHolder<Sig> HolderT; HolderT* holder = new HolderT(isolate, std::move(callback), std::move(invoker_options)); v8::Local<v8::FunctionTemplate> tmpl = v8::FunctionTemplate::New( isolate, &internal::Dispatcher<Sig>::DispatchToCallback, ConvertToV8<v8::Local<v8::External>>(isolate, holder->GetHandle(isolate))); return tmpl; } } // namespace gin #endif // ELECTRON_SHELL_COMMON_GIN_HELPER_FUNCTION_TEMPLATE_EXTENSIONS_H_
24a6b3898b8c8d718de7631a819b45a3b111b6da
003dd6fb74bfafd8411eedf5f99463b301ac0bc3
/include/pdk/global/Logging.h
87e59e01277299a81b57c64456a7df893914f13a
[ "Apache-2.0" ]
permissive
ajunlonglive/pdk
9d70525661095e307322e5e1d4504161d2b508b8
830c5d38c710db5b610bd1c1fbf4cad953f1e42b
refs/heads/master
2023-03-23T12:39:20.233221
2018-05-25T01:19:34
2018-05-25T01:19:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,634
h
Logging.h
// @copyright 2017-2018 zzu_softboy <zzu_softboy@163.com> // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. // // Created by softboy on 2018/02/08. #ifndef PDK_GLOBAL_LOGGING_H #define PDK_GLOBAL_LOGGING_H #include "pdk/global/Global.h" namespace pdk { // forward declare class with namespace namespace io { class Debug; class NoDebug; class LoggingCategory; } // io // forward declare class with namespace namespace lang { class String; } // lang using io::Debug; using io::NoDebug; using lang::String; using io::LoggingCategory; class MessageLogContext { PDK_DISABLE_COPY(MessageLogContext); public: constexpr MessageLogContext() : m_version(2), m_line(0), m_file(nullptr), m_function(nullptr), m_category(nullptr) {} constexpr MessageLogContext(const char *fileName, int lineNumber, const char *functionName, const char *categoryName) : m_version(2), m_line(lineNumber), m_file(fileName), m_function(functionName), m_category(categoryName) {} void copy(const MessageLogContext &logContext); int m_version; int m_line; const char *m_file; const char *m_function; const char *m_category; private: friend class MessageLogger; friend class Debug; }; class PDK_CORE_EXPORT MessageLogger { PDK_DISABLE_COPY(MessageLogger); public: constexpr MessageLogger() : m_context() {} constexpr MessageLogger(const char *file, int line, const char *function) : m_context(file, line, function, "default") {} constexpr MessageLogger(const char *file, int line, const char *function, const char *category) : m_context(file, line, function, category) {} void debug(const char *msg, ...) const PDK_ATTRIBUTE_FORMAT_PRINTF(2, 3); void noDebug(const char *, ...) const PDK_ATTRIBUTE_FORMAT_PRINTF(2, 3) {} void info(const char *msg, ...) const PDK_ATTRIBUTE_FORMAT_PRINTF(2, 3); void warning(const char *msg, ...) const PDK_ATTRIBUTE_FORMAT_PRINTF(2, 3); void critical(const char *msg, ...) const PDK_ATTRIBUTE_FORMAT_PRINTF(2, 3); typedef const LoggingCategory &(*CategoryFunction)(); void debug(const LoggingCategory &cat, const char *msg, ...) const PDK_ATTRIBUTE_FORMAT_PRINTF(3, 4); void debug(CategoryFunction catFunc, const char *msg, ...) const PDK_ATTRIBUTE_FORMAT_PRINTF(3, 4); void info(const LoggingCategory &cat, const char *msg, ...) const PDK_ATTRIBUTE_FORMAT_PRINTF(3, 4); void info(CategoryFunction catFunc, const char *msg, ...) const PDK_ATTRIBUTE_FORMAT_PRINTF(3, 4); void warning(const LoggingCategory &cat, const char *msg, ...) const PDK_ATTRIBUTE_FORMAT_PRINTF(3, 4); void warning(CategoryFunction catFunc, const char *msg, ...) const PDK_ATTRIBUTE_FORMAT_PRINTF(3, 4); void critical(const LoggingCategory &cat, const char *msg, ...) const PDK_ATTRIBUTE_FORMAT_PRINTF(3, 4); void critical(CategoryFunction catFunc, const char *msg, ...) const PDK_ATTRIBUTE_FORMAT_PRINTF(3, 4); #ifndef PDK_CC_MSVC PDK_NORETURN #endif void fatal(const char *msg, ...) const noexcept PDK_ATTRIBUTE_FORMAT_PRINTF(2, 3); #ifndef PDK_NO_DEBUG_STREAM Debug debug() const; Debug debug(const LoggingCategory &cat) const; Debug debug(CategoryFunction catFunc) const; Debug info() const; Debug info(const LoggingCategory &cat) const; Debug info(CategoryFunction catFunc) const; Debug warning() const; Debug warning(const LoggingCategory &cat) const; Debug warning(CategoryFunction catFunc) const; Debug critical() const; Debug critical(const LoggingCategory &cat) const; Debug critical(CategoryFunction catFunc) const; NoDebug noDebug() const noexcept; #endif // PDK_NO_DEBUG_STREAM private: MessageLogContext m_context; }; #if !defined(PDK_MESSAGELOGCONTEXT) && !defined(PDK_NO_MESSAGELOGCONTEXT) # if defined(PDK_NO_DEBUG) # define PDK_NO_MESSAGELOGCONTEXT # else # define PDK_MESSAGELOGCONTEXT # endif #endif #ifdef PDK_MESSAGELOGCONTEXT #define PDK_MESSAGELOG_FILE __FILE__ #define PDK_MESSAGELOG_LINE __LINE__ #define PDK_MESSAGELOG_FUNC PDK_FUNC_INFO #else #define PDK_MESSAGELOG_FILE nullptr #define PDK_MESSAGELOG_LINE 0 #define PDK_MESSAGELOG_FUNC nullptr #endif #define debug_stream pdk::MessageLogger(PDK_MESSAGELOG_FILE, PDK_MESSAGELOG_LINE, PDK_MESSAGELOG_FUNC).debug #define info_stream pdk::MessageLogger(PDK_MESSAGELOG_FILE, PDK_MESSAGELOG_LINE, PDK_MESSAGELOG_FUNC).info #define warning_stream pdk::MessageLogger(PDK_MESSAGELOG_FILE, PDK_MESSAGELOG_LINE, PDK_MESSAGELOG_FUNC).warning #define critical_stream pdk::MessageLogger(PDK_MESSAGELOG_FILE, PDK_MESSAGELOG_LINE, PDK_MESSAGELOG_FUNC).critical #define fatal_stream pdk::MessageLogger(PDK_MESSAGELOG_FILE, PDK_MESSAGELOG_LINE, PDK_MESSAGELOG_FUNC).fatal #define PDK_NO_DEBUG_MACRO while (false) pdk::MessageLogger().noDebug #if defined(PDK_NO_DEBUG_OUTPUT) # undef debug_stream # define debug_stream PDK_NO_DEBUG_MACRO #endif #if defined(PDK_NO_INFO_OUTPUT) # undef info_stream # define info_stream PDK_NO_DEBUG_MACRO #endif #if defined(PDK_NO_WARNING_OUTPUT) # undef warning_stream # define warning_stream PDK_NO_DEBUG_MACRO #endif PDK_CORE_EXPORT void message_output(pdk::MsgType, const MessageLogContext &context, const String &message); PDK_CORE_EXPORT void errno_warning(int code, const char *msg, ...); PDK_CORE_EXPORT void errno_warning(const char *msg, ...); typedef void (*MessageHandler)(pdk::MsgType, const MessageLogContext&, const String &); PDK_CORE_EXPORT MessageHandler install_message_handler(MessageHandler); PDK_CORE_EXPORT void set_message_pattern(const String &messagePattern); PDK_CORE_EXPORT String format_log_message(pdk::MsgType type, const MessageLogContext &context, const String &buf); } // pdk #endif // PDK_GLOBAL_LOGGING_H
da50412894cbdf9e1d0e0d0f21d7fb0542754633
2a5700f0a3823bad934f2b9223dd1e02bcf1c13f
/common/url_utils.cc
f9c3454711159fb5d3e5399c4399da48aed39f7a
[]
no_license
changpinggou/unix-thread-ipc
01334e891835c77f621740bd4edadeaba51fdbd0
784d6eaae7a016a5c47ede8a8171a95c75a1ae03
refs/heads/master
2021-01-20T06:57:48.809591
2015-01-21T06:49:57
2015-01-21T06:49:57
29,575,905
0
0
null
null
null
null
UTF-8
C++
false
false
13,887
cc
url_utils.cc
// Copyright 2007, Google Inc. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // 3. Neither the name of Google Inc. nor the names of its contributors may be // used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <assert.h> #include "gears/base/common/url_utils.h" #include "gears/base/common/base64.h" #include "gears/base/common/string_utils.h" #include "third_party/googleurl/src/gurl.h" // GURL initialization is not threadsafe, so we force the library to initialize // at CRT init time. static bool InitializeGURL() { GURL init("about:blank"); assert(init.is_valid()); return init.is_valid(); } static bool gurl_initialized = InitializeGURL(); bool IsRelativeUrl(const char16 *url) { // From RFC 2396 (URI Generic Syntax): // * "Relative URI references are distinguished from absolute URI in that // they do not begin with a scheme name." // * "Scheme names consist of a sequence of characters beginning with a // lower case letter and followed by any combination of lower case // letters, digits, plus ('+'), period ('.'), or hyphen ('-'). For // resiliency, programs interpreting URI should treat upper case letters // as equivalent to lower case in scheme names (e.g., allow 'HTTP' as // well as 'http')." // The algorithm below does not support escaped characters. bool first_is_alpha = (url[0] >= 'a' && url[0] <= 'z') || (url[0] >= 'A' && url[0] <= 'Z'); if (first_is_alpha) { int i = 1; while ((url[i] >= 'a' && url[i] <= 'z') || (url[i] >= 'A' && url[i] <= 'Z') || (url[i] >= '0' && url[i] <= '9') || (url[i] == '+') || (url[i] == '.') || (url[i] == '-')) { ++i; } if (url[i] == ':') { return false; // absolute URL } } return true && gurl_initialized; // ANDed with gurl_initialized to defeat dead stripping in opt builds } bool IsDataUrl(const char16 *url) { return std::char_traits<char16>::compare(url, STRING16(L"data:"), 5) == 0; } // NOTE: based loosely on mozilla's nsDataChannel.cpp bool ParseDataUrl(const std::string16& url, std::string16* mime_type, std::string16* charset, std::vector<uint8>* data) { std::string16::const_iterator begin = url.begin(); std::string16::const_iterator end = url.end(); std::string16::const_iterator after_colon = std::find(begin, end, ':'); if (after_colon == end) return false; ++after_colon; // first, find the start of the data std::string16::const_iterator comma = std::find(after_colon, end, ','); if (comma == end) return false; const std::string16 kBase64Tag = STRING16(L";base64"); std::string16::const_iterator it = std::search(after_colon, comma, kBase64Tag.begin(), kBase64Tag.end()); bool base64_encoded = (it != comma); if (comma != after_colon) { // everything else is content type std::string16::const_iterator semi_colon = std::find(after_colon, comma, ';'); if (semi_colon != after_colon) { mime_type->assign(after_colon, semi_colon); LowerString(*mime_type); } if (semi_colon != comma) { const std::string16 kCharsetTag = STRING16(L"charset="); it = std::search(semi_colon + 1, comma, kCharsetTag.begin(), kCharsetTag.end()); if (it != comma) charset->assign(it + kCharsetTag.size(), comma); } } // fallback to defaults if nothing specified in the URL: if (mime_type->empty()) mime_type->assign(STRING16(L"text/plain")); if (charset->empty()) charset->assign(STRING16(L"US-ASCII")); // Convert the data portion to single byte. std::string16 temp_data16(comma + 1, end); std::string temp_data; if (!String16ToUTF8(temp_data16.c_str(), &temp_data)) return false; // Preserve spaces if dealing with text or xml input, same as mozilla: // https://bugzilla.mozilla.org/show_bug.cgi?id=138052 // but strip them otherwise: // https://bugzilla.mozilla.org/show_bug.cgi?id=37200 // (Spaces in a data URL should be escaped, which is handled below, so any // spaces now are wrong. People expect to be able to enter them in the URL // bar for text, and it can't hurt, so we allow it.) temp_data = UnescapeURL(temp_data); if (base64_encoded || !(mime_type->compare(0, 5, STRING16(L"text/")) == 0 || mime_type->find(STRING16(L"xml")) != std::string16::npos)) { temp_data.erase(std::remove_if(temp_data.begin(), temp_data.end(), isspace), temp_data.end()); } if (base64_encoded) return Base64Decode(temp_data, data); data->assign(temp_data.begin(), temp_data.end()); return true; } template <class StringT> StringT UnescapeURLImpl(const StringT& escaped_text, bool replace_plus) { if (escaped_text.length() < 3 && !replace_plus) return escaped_text; // Can't possibly have an escaped char // The output of the unescaping is always smaller than the input, so we can // reserve the input size to make sure we have enough buffer and don't have // to allocate in the loop below. StringT result; result.reserve(escaped_text.length()); for (size_t i = 0, max = escaped_text.size(); i < max; ++i) { if (escaped_text[i] == '%' && i + 2 < max) { const typename StringT::value_type most_sig_digit(escaped_text[i + 1]); const typename StringT::value_type least_sig_digit(escaped_text[i + 2]); if (IsHex(most_sig_digit) && IsHex(least_sig_digit)) { result.push_back((HexToInt(most_sig_digit) * 16) + HexToInt(least_sig_digit)); i += 2; } else { result.push_back('%'); } } else if (replace_plus && escaped_text[i] == '+') { result.push_back(' '); } else { result.push_back(escaped_text[i]); } } return result; } std::string UnescapeURL(const std::string& escaped_text) { return UnescapeURLImpl(escaped_text, false); } std::string16 UnescapeURL(const std::string16& escaped_text) { return UnescapeURLImpl(escaped_text, false); } //------------------------------------------------------------------------------ // UTF8PathToUrl //------------------------------------------------------------------------------ // This is based on net_GetURLSpecFromFile in Firefox. See: // http://lxr.mozilla.org/seamonkey/source/netwerk/base/src/nsURLHelperWin.cpp std::string UTF8PathToUrl(const std::string &path, bool directory) { std::string result("file:///"); result += path; // Normalize all backslashes to forward slashes. size_t loc = result.find('\\'); while (loc != std::string::npos) { result.replace(loc, 1, 1, '/'); loc = result.find('\\', loc + 1); } result = EscapeUrl(result, ESCAPE_DIRECTORY|ESCAPE_FORCED); // EscapeUrl doesn't escape semi-colons, so do that here. loc = result.find(';'); while (loc != std::string::npos) { result.replace(loc, 1, "%3B"); loc = result.find('\\', loc + 1); } // If this is a directory, we need to make sure a slash is at the end. if (directory && result.c_str()[result.length() - 1] != '/') { result += "/"; } return result; } //------------------------------------------------------------------------------ // EscapeUrl //------------------------------------------------------------------------------ // This is based on NS_EscapeURL from Firefox. // See: http://lxr.mozilla.org/seamonkey/source/xpcom/io/nsEscape.cpp static const unsigned char HEX_ESCAPE = '%'; static const int escape_chars[256] = /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */ 0,1023, 0, 512,1023, 0,1023,1023,1023,1023,1023,1023,1023,1023, 953, 784, /* 2x !"#$%&'()*+,-./ */ 1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1008, 912, 0,1008, 0, 768, /* 3x 0123456789:;<=>? */ 1008,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023, /* 4x @ABCDEFGHIJKLMNO */ 1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023, 896, 896, 896, 896,1023, /* 5x PQRSTUVWXYZ[\]^_ */ 0,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023, /* 6x `abcdefghijklmno */ 1023,1023,1023,1023,1023,1023,1023,1023,1023,1023,1023, 896,1012, 896,1023, 0, /* 7x pqrstuvwxyz{|}~ */ 0 /* 8x DEL */ }; #define NO_NEED_ESC(C) (escape_chars[((unsigned int) (C))] & (flags)) // Returns an escaped string. std::string EscapeUrl(const std::string &source, unsigned int flags) { std::string result; unsigned int i = 0; static const char hex_chars[] = "0123456789ABCDEF"; bool forced = (flags & ESCAPE_FORCED) != 0; bool ignore_non_ascii = (flags & ESCAPE_ONLYASCII) != 0; bool ignore_ascii = (flags & ESCAPE_ONLYNONASCII) != 0; bool colon = (flags & ESCAPE_COLON) != 0; char temp_buffer[100]; unsigned int temp_buffer_pos = 0; bool previous_is_non_ascii = false; for (i = 0; i < source.length(); ++i) { unsigned char c = source.c_str()[i]; // if the char has not to be escaped or whatever follows % is // a valid escaped string, just copy the char. // // Also the % will not be escaped until forced // See bugzilla bug 61269 for details why we changed this // // And, we will not escape non-ascii characters if requested. // On special request we will also escape the colon even when // not covered by the matrix. // ignoreAscii is not honored for control characters (C0 and DEL) // // And, we should escape the '|' character when it occurs after any // non-ASCII character as it may be part of a multi-byte character. if ((NO_NEED_ESC(c) || (c == HEX_ESCAPE && !forced) || (c > 0x7f && ignore_non_ascii) || (c > 0x1f && c < 0x7f && ignore_ascii)) && !(c == ':' && colon) && !(previous_is_non_ascii && c == '|' && !ignore_non_ascii)) { temp_buffer[temp_buffer_pos] = c; ++temp_buffer_pos; } else { // Do the escape magic. temp_buffer[temp_buffer_pos] = HEX_ESCAPE; temp_buffer[temp_buffer_pos + 1] = hex_chars[c >> 4]; // high nibble temp_buffer[temp_buffer_pos + 2] = hex_chars[c & 0x0f]; // low nibble temp_buffer_pos += 3; } if (temp_buffer_pos >= sizeof(temp_buffer) - 4) { temp_buffer[temp_buffer_pos] = '\0'; result += temp_buffer; temp_buffer_pos = 0; } previous_is_non_ascii = (c > 0x7f); } temp_buffer[temp_buffer_pos] = '\0'; result += temp_buffer; return result; } bool ResolveAndNormalize(const char16 *base, const char16 *url, std::string16 *out) { assert(url && out); GURL gurl; if (base != NULL) { GURL base_gurl(base); if (!base_gurl.is_valid()) { return false; } gurl = base_gurl.Resolve(url); } else { gurl = GURL(url); } if (!gurl.is_valid()) { return false; } // strip the fragment part of the url GURL::Replacements strip_fragment; strip_fragment.SetRef("", url_parse::Component()); gurl = gurl.ReplaceComponents(strip_fragment); if (!UTF8ToString16(gurl.spec().c_str(), gurl.spec().length(), out)) { return false; } return true; } void ParseUrlQuery(const char16 *query_string, QueryArgumentsMap *arguments) { assert(query_string && arguments); assert(query_string[0] != '?'); arguments->clear(); url_parse::Component key, value; url_parse::Component query( 0, static_cast<int>(std::char_traits<char16>::length(query_string))); while (url_parse::ExtractQueryKeyValue(query_string, &query, &key, &value)) { if (key.is_nonempty()) { std::string16 key_str(UnescapeURLImpl(std::string16(query_string, key.begin, key.len), true)); std::string16 value_str; if (value.is_nonempty()) { value_str = UnescapeURLImpl(std::string16(query_string, value.begin, value.len), true); } arguments->insert(QueryArgumentsMap::value_type(key_str, value_str)); } } } std::string16 EscapeUrl(const std::string16 &source, unsigned int flags) { return UTF8ToString16(EscapeUrl(String16ToUTF8(source), flags)); }
d02c511b486c6a1f22af0ce1ffaa36dc9b5e251e
cd44c5b4e2687b38722b8ea74f0e9ca8930fb2c9
/abc041_b.cpp
514e2630391b80df940e2ca6c3270c5de241e586
[]
no_license
sigu1011/atcoder
b1a3b54d9f1e8c178e5f58505cca69b5ace1b23f
8280c422a065b676eefeaf2374229635a92531bc
refs/heads/master
2020-06-11T17:44:17.073065
2020-01-26T14:50:48
2020-01-26T14:50:48
194,039,322
0
0
null
null
null
null
UTF-8
C++
false
false
214
cpp
abc041_b.cpp
#include <bits/stdc++.h> using namespace std; const long long MOD = 1e9 + 7; int main() { long long A, B, C; cin >> A >> B >> C; printf("%lld", (A % MOD) * (B % MOD) % MOD * (C % MOD) % MOD); return 0; }
e1f70fd1cc464968d67bc267fe891415164d0154
efca5f60e4d6847d9ca3943d46220f3cc905d7a2
/pdfbase.h
26e573995c602ee8e0b120f07197b1e08bca2409
[]
no_license
vasekp/pdfbreak
ca6c040f70d29157243b7c07c53a48bdd0a32129
aefe60ea3d1ceedfc55b5c3175b09e3a9d8477db
refs/heads/master
2020-08-02T12:06:56.746288
2019-10-27T10:12:37
2019-10-27T10:53:21
211,346,388
0
0
null
null
null
null
UTF-8
C++
false
false
5,705
h
pdfbase.h
#ifndef PDF_BASE_H #define PDF_BASE_H #include <ostream> #include <string> #include <vector> #include <map> #include <variant> namespace pdf { struct ObjRef { unsigned long num; unsigned long gen; }; inline bool operator< (const ObjRef& lhs, const ObjRef& rhs) { return lhs.num < rhs.num || (lhs.num == rhs.num && lhs.gen < rhs.gen); } inline bool operator== (const ObjRef& lhs, const ObjRef& rhs) { return lhs.num == rhs.num && lhs.gen == rhs.gen; } namespace internal { class ObjBase { public: virtual void dump(std::ostream& os, unsigned off) const = 0; virtual bool failed() const { return false; } protected: virtual ~ObjBase() { } }; template<typename... Ts> class tagged_union : public ObjBase { std::variant<Ts...> contents; public: tagged_union() = default; tagged_union(const tagged_union&) = default; tagged_union(tagged_union&&) = default; tagged_union(std::variant<Ts...>&& contents_) : contents(std::move(contents_)) { } tagged_union& operator=(const tagged_union&) = default; tagged_union& operator=(tagged_union&&) = default; ~tagged_union() = default; template<typename T> bool is() const { return std::holds_alternative<T>(contents); } template<typename T> const T& get() const { return std::get<T>(contents); } template<typename T> T&& get() && { return std::move(std::get<T>(contents)); } bool failed() const override { return std::visit([](auto&& arg) { return arg.failed(); }, contents); } void dump(std::ostream& os, unsigned off) const override { std::visit([&os, off](auto&& arg) { arg.dump(os, off); }, contents); } }; } // namespace pdf::internal /***** PDF object types *****/ struct Object; class Null : public internal::ObjBase { public: void dump(std::ostream& os, unsigned off) const override; }; class Boolean : public internal::ObjBase { bool val; public: Boolean(bool val_) : val(val_) { } operator bool() const { return val; } void dump(std::ostream& os, unsigned off) const override; }; class Numeric : public internal::ObjBase { long val_s; int dp; public: Numeric(long val) : val_s(val), dp(0) { } Numeric(std::string str); bool integral() const { return dp == 0; } bool uintegral() const { return integral() && val_s >= 0; } bool failed() const override { return dp < 0; } bool valid() const { return !failed(); } long val_long() const; unsigned long val_ulong() const; void dump(std::ostream& os, unsigned off) const override; }; class String : public internal::ObjBase { std::string val; bool hex; std::string error; public: template<typename V, typename E> String(V&& val_, bool hex_, E&& err_) : val(std::forward<V>(val_)), hex(hex_), error(std::forward<E>(err_)) { } operator const std::string&() const { return val; } bool failed() const override { return !error.empty(); } void dump(std::ostream& os, unsigned off) const override; }; class Name : public internal::ObjBase { std::string val; public: template<typename V> Name(V&& val_) : val(std::forward<V>(val_)) { } operator const std::string&() const { return val; } bool operator== (const char* cstr) const { return val == cstr; } void dump(std::ostream& os, unsigned off) const override; }; class Array : public internal::ObjBase { std::vector<Object> val; std::string error; public: template<typename V, typename E> Array(V&& val_, E&& err_) : val(std::forward<V>(val_)), error(std::forward<E>(err_)) { } const std::vector<Object>& items() const { return val; } bool failed() const override { return !error.empty(); } void dump(std::ostream& os, unsigned off) const override; }; class Dictionary : public internal::ObjBase { std::map<std::string, Object> val; std::string error; public: template<typename V, typename E> Dictionary(V&& val_, E&& err_) : val(std::forward<V>(val_)), error(std::forward<E>(err_)) { } const Object& lookup(const std::string& key) const; bool failed() const override { return !error.empty(); } void dump(std::ostream& os, unsigned off) const override; }; class Stream : public internal::ObjBase { Dictionary _dict; std::string _data; std::string _error; public: template<typename D, typename V, typename E> Stream(D&& dict_, V&& data_, E&& err_) : _dict(std::forward<D>(dict_)), _data(std::forward<V>(data_)), _error(std::forward<E>(err_)) { } const Dictionary& dict() const { return _dict; } const std::string& data() const { return _data; } bool failed() const override { return _dict.failed() || !_error.empty(); } void dump(std::ostream& os, unsigned off) const override; }; class Indirect : public internal::ObjBase { unsigned long num; unsigned long gen; public: Indirect(unsigned long num_, unsigned long gen_) : num(num_), gen(gen_) { } void dump(std::ostream& os, unsigned off) const override; }; class Invalid : public internal::ObjBase { std::string error; public: Invalid(std::string&& error_) : error(std::move(error_)) { } const std::string& get_error() const { return error; } bool failed() const override { return true; } void dump(std::ostream& os, unsigned off) const override; }; using _Object = internal::tagged_union< Null, Boolean, Numeric, String, Name, Array, Dictionary, Stream, Indirect, Invalid>; struct Object : public _Object { using _Object::_Object; operator bool() const { return !is<Null>() && !is<Invalid>(); } }; /***** iostream interface *****/ inline std::ostream& operator<< (std::ostream& os, const internal::ObjBase& obj) { obj.dump(os, 0); return os; } } // namespace pdf #endif
391b054ef16b3fbd8bb2b6d29f9bfca2ec51c43f
aae979e2e18e67f4564cd771e9991dfea01cfda8
/multidim_image_augmentation/cc/ops/cubic_interpolation2d_op.cc
d752ccb59ebdd3122d9d48e566f0a72dcd4c83ff
[ "Apache-2.0" ]
permissive
ardila/custom-op
0c47a95da31336a092b8830577253abcc515c21b
69f10cc19f7e4a369e9f378e7fd6e67903df9956
refs/heads/master
2023-02-03T10:12:46.949735
2020-12-22T22:38:36
2020-12-22T22:38:36
264,562,944
2
1
Apache-2.0
2020-06-27T14:49:22
2020-05-17T01:46:26
C++
UTF-8
C++
false
false
4,109
cc
cubic_interpolation2d_op.cc
// Copyright 2018 Google LLC // // 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 // // https://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 <vector> #include "multidim_image_augmentation/cc/platform/types.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/shape_inference.h" namespace deepmind { namespace multidim_image_augmentation { namespace { using ::tensorflow::shape_inference::DimensionHandle; using ::tensorflow::shape_inference::InferenceContext; using ::tensorflow::shape_inference::ShapeHandle; // Creates the interface for the TensorFlow Op 'cubic_interpolation2d'. REGISTER_OP("CubicInterpolation2D") .Input("input: float") .Output("output: float") .Attr("factors: list(int) >= 2") .Attr("output_spatial_shape: list(int) >= 2") .SetShapeFn([](InferenceContext* c) { ShapeHandle input_shape; TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 3, &input_shape)); DimensionHandle channels = c->Dim(input_shape, -1); std::vector<int32> factors; TF_RETURN_IF_ERROR(c->GetAttr("factors", &factors)); std::vector<int32> output_spatial_shape; TF_RETURN_IF_ERROR(c->GetAttr("output_spatial_shape", &output_spatial_shape)); // Check attributes. if (factors.size() != 2) { return ::tensorflow::errors::InvalidArgument( "factors must be rank 2, got ", factors.size()); } if (factors[0] <= 0 || factors[1] <= 0) { return ::tensorflow::errors::InvalidArgument( "Each factor must be greater than 0, got (", factors[0], ", ", factors[1], ")"); } if (output_spatial_shape.size() != 2) { return ::tensorflow::errors::InvalidArgument( "output_spatial_shape must be rank 2, got ", output_spatial_shape.size()); } if (output_spatial_shape[0] <= 0 || output_spatial_shape[1] <= 0) { return ::tensorflow::errors::InvalidArgument( "`output_spatial_shape` must be greater than 0, got (", output_spatial_shape[0], ", ", output_spatial_shape[1], ")"); } DimensionHandle out_shape_0 = c->MakeDim(output_spatial_shape[0]); DimensionHandle out_shape_1 = c->MakeDim(output_spatial_shape[1]); c->set_output(0, c->MakeShape({out_shape_0, out_shape_1, channels})); return ::tensorflow::Status::OK(); }) .Doc(R"doc( Performs a 2D fast cubic b-spline interpolation (upscaling). Performs a 2D fast cubic b-spline interpolation (can be interpreted as smooth upsampling with the integer factors given in `factors`) where the centers of the control point array and the dense output array are aligned. Be aware that the resulting function usually does _not_ pass through the control points. Due to the centering certain restrictions apply on the number of control points and the scaling factors. See `cubic_interpolation1d` for details. ``` Usage example: ```python from multidim_image_augmentation import augmentation_ops with tf.Session(): grid = np.ndarray([5, 5, 2], dtype=np.float32) # Fill in some values. # ... # Do the bspline interpolation. dense = augmentation_ops.cubic_interpolation_2d( input=grid, factors=[10, 10], output_spatial_shape=[21, 21]).eval() ``` input:= A 3-D float Tensor with shape `[spatial_shape_0, spatial_shape_1, num_channels]`. factors: Scaling factors. output_spatial_shape: The spatial shape of the output tensor. output: 3-D with shape `[output_spatial_shape_0, output_spatial_shape_1, channels]` )doc"); } // namespace } // namespace multidim_image_augmentation } // namespace deepmind
0541d28bcd3f486c346841e0efe2ae2d083307eb
b4dafe59c9620263a798bff341bb411e5120b93a
/AudioProcessing/SpectrumAnalyzer.cpp
11d0680b49db0f0772a5f947e10e8a5596b07692
[ "MIT" ]
permissive
clarkezone/audiovisualization
82a0eb5b69a4f30135714d1c818c639e6e919f40
46ffd5a2b280cf46b46fa668dc9c7634481c6996
refs/heads/master
2021-01-24T03:21:32.500443
2017-07-02T22:10:46
2017-07-02T22:10:46
64,030,290
0
3
null
2017-07-02T22:10:46
2016-07-23T18:39:31
C++
UTF-8
C++
false
false
12,627
cpp
SpectrumAnalyzer.cpp
#include "pch.h" #include "SpectrumAnalyzer.h" #include <algorithm> #include <XDSP.h> using namespace Microsoft::WRL; namespace AudioProcessing { CSpectrumAnalyzer::CSpectrumAnalyzer() : m_AudioChannels(0), m_StepFrameCount(0), m_StepFrameOverlap(0), m_StepTotalFrames(0), m_pWindow(nullptr), m_pInputBuffer(nullptr), m_CopiedFrameCount(0), m_InputWriteIndex(0), m_pFftUnityTable(nullptr), m_pFftReal(nullptr), m_pFftImag(nullptr), m_pFftRealUnswizzled(nullptr), m_pFftImagUnswizzled(nullptr), m_hnsCurrentBufferTime(0L), m_hnsOutputFrameTime(0L), m_bUseLogScale(false), m_fLogMin(20.0f), m_fLogMax(20000.f), m_logElementsCount(200) { } CSpectrumAnalyzer::~CSpectrumAnalyzer() { FreeBuffers(); } HRESULT CSpectrumAnalyzer::Configure(IMFMediaType * pInputType, unsigned stepFrameCount, unsigned stepFrameOverlap, unsigned fftLength) { using namespace std; lock_guard<std::mutex> lockAccess(m_ConfigAccess); // Object lock // Validate arguments first if (pInputType == nullptr) return E_INVALIDARG; GUID majorType; // Validate for supported media type HRESULT hr = pInputType->GetMajorType(&majorType); if (FAILED(hr)) return hr; if (memcmp(&majorType, &MFMediaType_Audio, sizeof(GUID)) != 0) { return E_INVALIDARG; } GUID subType; hr = pInputType->GetGUID(MF_MT_SUBTYPE, &subType); if (FAILED(hr)) return hr; if (memcmp(&subType, &MFAudioFormat_Float, sizeof(GUID)) != 0) { return E_INVALIDARG; } if (fftLength <= stepFrameCount + stepFrameOverlap || (fftLength & (fftLength - 1)) != 0) return E_INVALIDARG; // Get the number of audio channels hr = pInputType->GetUINT32(MF_MT_AUDIO_NUM_CHANNELS, &m_AudioChannels); if (FAILED(hr)) return hr; hr = pInputType->GetUINT32(MF_MT_AUDIO_SAMPLES_PER_SECOND, &m_InputSampleRate); if (FAILED(hr)) return hr; m_StepFrameCount = stepFrameCount; m_StepFrameOverlap = stepFrameOverlap; m_StepTotalFrames = stepFrameCount + stepFrameOverlap; m_FFTLength = fftLength; m_FFTLengthPow2 = 1; while ((size_t)1 << m_FFTLengthPow2 != m_FFTLength) m_FFTLengthPow2++; hr = AllocateBuffers(); if (FAILED(hr)) return hr; return S_OK; } HRESULT CSpectrumAnalyzer::AllocateBuffers() { using namespace DirectX; // Input buffer will need to keep samples for the step and the overlap m_pInputBuffer = static_cast<float *>(malloc(m_StepTotalFrames * m_AudioChannels * sizeof(float))); memset(m_pInputBuffer, 0, m_StepTotalFrames * m_AudioChannels * sizeof(float)); m_CopiedFrameCount = 0; m_InputWriteIndex = 0; m_pWindow = static_cast<float *>(malloc(m_StepTotalFrames * sizeof(float))); // Initialize window, use Blackman-Nuttall window for low sidelobes float a0 = 0.3635819f, a1 = 0.4891775f, a2 = 0.1365995f, a3 = 0.0106411f; float pi = 3.14159f; for (size_t index = 0; index < m_StepTotalFrames; index++) { m_pWindow[index] = a0 - a1 * cosf(2 * pi * index / (m_StepTotalFrames - 1)) + a2 * cosf(4 * pi * index / (m_StepTotalFrames - 1)) - a3 * cosf(6 * pi * index / (m_StepTotalFrames - 1)); } m_pFftUnityTable = static_cast<XMVECTOR *> (_aligned_malloc(2 * m_FFTLength * sizeof(XMVECTOR), 16)); // Complex values XDSP::FFTInitializeUnityTable(m_pFftUnityTable, m_FFTLength); m_pFftReal = static_cast<XMVECTOR *>(_aligned_malloc(m_FFTLength * sizeof(XMVECTOR), 16)); m_pFftImag = static_cast<XMVECTOR *>(_aligned_malloc(m_FFTLength * sizeof(XMVECTOR), 16)); m_pFftRealUnswizzled = static_cast<XMVECTOR *>(_aligned_malloc(m_FFTLength * sizeof(XMVECTOR), 16)); m_pFftImagUnswizzled = static_cast<XMVECTOR *>(_aligned_malloc(m_FFTLength * sizeof(XMVECTOR), 16)); if (!(m_pFftUnityTable && m_pFftReal && m_pFftImag && m_pFftRealUnswizzled && m_pFftImagUnswizzled)) return E_OUTOFMEMORY; return S_OK; } void CSpectrumAnalyzer::FreeBuffers() { free(m_pWindow); free(m_pInputBuffer); if (m_pFftUnityTable != nullptr) _aligned_free(m_pFftUnityTable); if (m_pFftReal != nullptr) _aligned_free(m_pFftReal); if (m_pFftImag != nullptr) _aligned_free(m_pFftImag); if (m_pFftRealUnswizzled != nullptr) _aligned_free(m_pFftRealUnswizzled); if (m_pFftImagUnswizzled != nullptr) _aligned_free(m_pFftImagUnswizzled); } HRESULT CSpectrumAnalyzer::QueueInput(IMFSample *pSample) { auto lock = m_csQueueLock.Lock(); m_InputQueue.push(pSample); return S_OK; } HRESULT CSpectrumAnalyzer::GetNextSample() { auto lock = m_csQueueLock.Lock(); // Pull next buffer from the sample queue if (m_InputQueue.empty()) { return S_FALSE; } m_InputQueue.front()->GetSampleTime(&m_hnsCurrentBufferTime); m_InputQueue.front()->ConvertToContiguousBuffer(&m_spCurrentBuffer); m_CurrentBufferSampleIndex = 0; m_InputQueue.pop(); return S_OK; } void CSpectrumAnalyzer::AnalyzeData(DirectX::XMVECTOR *pData,float *pRMS) { using namespace DirectX; using namespace XDSP; FFT(m_pFftReal, m_pFftImag, m_pFftUnityTable, m_FFTLength); FFTUnswizzle(m_pFftRealUnswizzled, m_pFftReal, m_FFTLengthPow2); FFTUnswizzle(m_pFftImagUnswizzled, m_pFftImag, m_FFTLengthPow2); XMVECTOR vRMS = XMVectorZero(); float fftScaler = 2.0f / m_FFTLength; // Calculate abs value first half of FFT output and copy to output for (size_t vIndex = 0; vIndex < m_FFTLength >> 3; vIndex++) // vector length is 4 times shorter, copy only positive frequency values { XMVECTOR vRR = XMVectorMultiply(m_pFftRealUnswizzled[vIndex], m_pFftRealUnswizzled[vIndex]); XMVECTOR vII = XMVectorMultiply(m_pFftImagUnswizzled[vIndex], m_pFftImagUnswizzled[vIndex]); XMVECTOR vRRplusvII = XMVectorAdd(vRR, vII); XMVECTOR vAbs = XMVectorSqrtEst(vRRplusvII); pData[vIndex] = XMVectorScale(vAbs, fftScaler); vRMS += pData[vIndex]; } *pRMS = vRMS.m128_f32[0] + vRMS.m128_f32[1] + vRMS.m128_f32[2] + vRMS.m128_f32[3]; } HRESULT CSpectrumAnalyzer::CopyDataFromInputBuffer() { while (m_CopiedFrameCount < m_StepFrameCount) { if (m_spCurrentBuffer == nullptr && GetNextSample() != S_OK) { return S_FALSE; // Not enough input samples } // Copy next m_StepSampleCount samples from buffer and perform analyzes DWORD cbCurrentLength; float *pBuffer = nullptr; HRESULT hr = m_spCurrentBuffer->Lock((BYTE **)&pBuffer, nullptr, &cbCurrentLength); if (FAILED(hr)) return hr; DWORD samplesInBuffer = cbCurrentLength / sizeof(float); // Copy frames from source buffer to input buffer all copied or source buffer depleted while (m_CopiedFrameCount < m_StepFrameCount && m_CurrentBufferSampleIndex < samplesInBuffer) { if (m_CopiedFrameCount == 0) { // Set the timestamp when copying the first sample m_hnsOutputFrameTime = m_hnsCurrentBufferTime + 10000000L * ((long long)m_CurrentBufferSampleIndex / m_AudioChannels) / m_InputSampleRate; } for (size_t channelIndex = 0; channelIndex < m_AudioChannels; channelIndex++, m_InputWriteIndex++, m_CurrentBufferSampleIndex++) { m_pInputBuffer[m_InputWriteIndex] = pBuffer[m_CurrentBufferSampleIndex]; } m_CopiedFrameCount++; // Wrap write index over the end if needed if (m_InputWriteIndex >= m_StepTotalFrames * m_AudioChannels) m_InputWriteIndex = 0; } m_spCurrentBuffer->Unlock(); if (m_CurrentBufferSampleIndex >= samplesInBuffer) m_spCurrentBuffer = nullptr; // Flag to get next buffer } m_CopiedFrameCount = 0; // Start all over next time return S_OK; } void CSpectrumAnalyzer::CopyDataToFftBuffer(int readIndex,float *pReal) { for (size_t fftIndex = 0; fftIndex < m_FFTLength; fftIndex++) { if (fftIndex < m_StepTotalFrames) { pReal[fftIndex] = m_pWindow[fftIndex] * m_pInputBuffer[readIndex]; readIndex += m_AudioChannels; if ((size_t) readIndex >= m_StepTotalFrames * m_AudioChannels) // Wrap the read index over end readIndex -= m_StepTotalFrames * m_AudioChannels; } else pReal[fftIndex] = 0; // Pad with zeros } } HRESULT CSpectrumAnalyzer::Step(IMFSample **ppSample) { using namespace DirectX; using namespace std; // Not initialized if (m_AudioChannels == 0) return E_NOT_VALID_STATE; lock_guard<std::mutex> lockAccess(m_ConfigAccess); // Object lock // Copy data to the input buffer from sample queue HRESULT hr = CopyDataFromInputBuffer(); if (hr != S_OK) return hr; // Create media sample ComPtr<IMFMediaBuffer> spBuffer; size_t outputLength = m_bUseLogScale ? m_logElementsCount : m_FFTLength; // Create aligned buffer for vector math + 16 bytes for 8 floats for RMS values hr = MFCreateAlignedMemoryBuffer((sizeof(float)*outputLength*m_AudioChannels) + 32, 16, &spBuffer); if (FAILED(hr)) return hr; spBuffer->SetCurrentLength(sizeof(float)*m_AudioChannels + sizeof(float)*m_AudioChannels*m_logElementsCount); ComPtr<IMFSample> spSample; hr = MFCreateSample(&spSample); if (FAILED(hr)) return hr; spSample->AddBuffer(spBuffer.Get()); spSample->SetSampleDuration((long long)10000000L * m_StepFrameCount / m_InputSampleRate); spSample->SetSampleTime(m_hnsOutputFrameTime); float *pData; hr = spBuffer->Lock((BYTE **)&pData, nullptr, nullptr); if (FAILED(hr)) return hr; // For each channel copy data to FFT buffer for (size_t channelIndex = 0; channelIndex < m_AudioChannels; channelIndex++) { size_t readIndex = channelIndex + m_InputWriteIndex; // After previous copy the write index will point to the starting point of the overlapped area CopyDataToFftBuffer(readIndex, (float *)m_pFftReal); memset(m_pFftImag, 0, sizeof(float)*m_FFTLength); // Imaginary values are 0 for input // One channel output is fftLength / 2, array vector size is fftLength / 4 hence fftLength >> 3 float *pOutData = pData + channelIndex * outputLength; float *pRMSData = (float *)(pData + m_AudioChannels * outputLength); if (m_bUseLogScale) { AnalyzeData(m_pFftReal, pRMSData + channelIndex); float fromFreq = 2 * m_fLogMin / m_InputSampleRate; float toFreq = 2 * m_fLogMax / m_InputSampleRate; AudioProcessing::mapToLogScale((float *)m_pFftReal, m_FFTLength >> 1, pOutData, m_logElementsCount, fromFreq, toFreq); } else { AnalyzeData((XMVECTOR *) pOutData, pRMSData + channelIndex); } float minLogValue = log10(1.f / 32767); // 16 bit audio dynamic range // convert to log scale for (size_t index = 0; index < m_logElementsCount; index++) { float logValue = pOutData[index] > 0.0f ? log10(pOutData[index]) : minLogValue; if (logValue < minLogValue) logValue = minLogValue; pOutData[index] = 20.f * logValue; } } spBuffer->Unlock(); spSample.CopyTo(ppSample); return S_OK; } void CSpectrumAnalyzer::Reset() { auto lock = m_csQueueLock.Lock(); while (!m_InputQueue.empty()) m_InputQueue.pop(); // Clean up any state from buffer copying memset(m_pInputBuffer, 0, m_StepTotalFrames * m_AudioChannels * sizeof(float)); m_CopiedFrameCount = 0; m_InputWriteIndex = 0; } HRESULT CSpectrumAnalyzer::Skip(REFERENCE_TIME timeStamp) { while (true) { if (m_spCurrentBuffer == nullptr && GetNextSample() != S_OK) { return S_FALSE; // Not enough input samples } DWORD cbBufferLength; HRESULT hr = m_spCurrentBuffer->GetCurrentLength(&cbBufferLength); if (FAILED(hr)) return hr; REFERENCE_TIME duration = 10000000L * (long long)(cbBufferLength / sizeof(float) / m_AudioChannels) / m_InputSampleRate; if (timeStamp >= m_hnsCurrentBufferTime && timeStamp < m_hnsCurrentBufferTime + duration) { // Clean input buffer memset(m_pInputBuffer, 0, m_StepTotalFrames * m_AudioChannels * sizeof(float)); m_CopiedFrameCount = 0; m_InputWriteIndex = 0; // And set copy pointer to the requested location m_CurrentBufferSampleIndex = (unsigned)(m_AudioChannels * ((m_InputSampleRate*(timeStamp - m_hnsCurrentBufferTime) + (m_InputSampleRate >> 1)) / 10000000L)); // Add half sample rate for appropriate rounding to avoid int math rounding errors return S_OK; } m_spCurrentBuffer = nullptr; } } void CSpectrumAnalyzer::SetLinearFScale() { using namespace std; lock_guard<std::mutex> lockAccess(m_ConfigAccess); // Object lock m_bUseLogScale = false; } void CSpectrumAnalyzer::SetLogFScale(float lowFrequency, float highFrequency, size_t binCount) { using namespace std; lock_guard<std::mutex> lockAccess(m_ConfigAccess); // Object lock m_bUseLogScale = true; m_fLogMin = lowFrequency; m_fLogMax = highFrequency; m_logElementsCount = binCount; } }
ba23cbba758aca9ba2f313c39cb28e139a58891b
fa01c9a63f9cf820ad4038d2fdc1a02cc9b175fc
/OOP simple project/Project /default_menu.h
de4bd095ab8c9047a9bad48d2bdaca2d6e3d39c7
[]
no_license
leonardoperrone/Projects-and-School
a668693f3eaa12b116bf62aef41deecec3b9ec2c
119b8e6fcdb11eff031961842ddeb69ec86af87b
refs/heads/master
2018-10-27T23:01:06.546718
2018-10-27T12:44:51
2018-10-27T12:44:51
107,815,253
0
0
null
null
null
null
UTF-8
C++
false
false
2,259
h
default_menu.h
/* default_menu.h 03/29/2016 CS411 Project prototype Leonardo Perrone F285y428 Description: In this file is created a base class for the menus several parameters, functions, and private members. */ #ifndef __Project_CS411__menu__ #define __Project_CS411__menu__ #include <stdio.h> //including libraries #include <iostream> #include <string> #include <fstream> #include <cstdlib> #include <sstream> #include <vector> class Menu // base class menu with virtual and non-virtual fucntions { public: Menu(const std::string& title = "No menu selected", const std::string& appetizer = "No appetizer", const std::string& entree = "No entree", const std::string& dessert = "No dessert"); virtual ~Menu(); //accessors std::string get_title(void); std::string get_appetizer(void); std::string get_salad(void); std::string get_entree(void); std::string get_dessert(void); std::string get_drink(void); double get_drink_cost(void); double get_salad_cost(void); int get_people(void); double get_cost(void); double get_tax_cost(void); double get_total_cost(void); //mutators void set_title(std::string title); void set_appetizer(std::string appetizer); void set_salad(std::string salad); void set_entree(std::string entree); void set_dessert(std::string dessert); void set_drink(std::string drink); void set_drink_cost(double drink_cost); void set_salad_cost(double salad_cost); void set_people(int people); void set_cost(double cost); void set_tax_cost(double tax_cost); void set_total_cost(double total_cost); virtual std::string menu_salad() = 0; virtual std::string menu_drink() = 0; void print_menu(); virtual double calculate_cost(double drink_cost, double salad_cost, int people) = 0; void print_price(); int people_num(); private: std::string m_title; std::string m_appetizer; std::string m_entree; std::string m_dessert; std::string m_salad; std::string m_drink; double m_drink_cost; double m_salad_cost; int m_people; double m_cost; double m_tax_cost; double m_total_cost; }; #endif /* defined(__Project_CS411__menu__) */
14ec8e217e94f3f9159e4e67ae203e1319493879
d375176fc2f2a5b91479d3488cabb840dcf019bd
/src/Net/NetworkStream.cpp
b37bbda33b5f4a8e4de5afddd81095190098019c
[ "FTL", "MIT", "LicenseRef-scancode-warranty-disclaimer", "Zlib", "LicenseRef-scancode-unknown-license-reference", "curl", "Libpng" ]
permissive
halak/bibim
ff91acc0bcbd9646cab2e5a3beb46da3dcaaa093
ad01efa8aac4f074f64bf033ac0f1ed382060334
refs/heads/master
2021-07-15T05:38:49.234568
2021-07-07T01:36:18
2021-07-07T01:36:18
66,716,124
3
1
null
2018-03-23T08:17:56
2016-08-27T13:35:40
C
UTF-8
C++
false
false
1,108
cpp
NetworkStream.cpp
#include <Bibim/Config.h> #include <Bibim/NetworkStream.h> #include <Bibim/Assert.h> #include <Bibim/Socket.h> namespace Bibim { NetworkStream::NetworkStream(Socket* socket) : socket(socket) { BBAssert(socket); } NetworkStream::~NetworkStream() { } int NetworkStream::Read(void* buffer, int size) { return socket->Receive(buffer, size); } int NetworkStream::Write(const void* buffer, int size) { return socket->Send(buffer, size); } void NetworkStream::Flush() { } int NetworkStream::Seek(int /*offset*/, SeekOrigin /*origin*/) { return 0; } int NetworkStream::GetPosition() { return 0; } int NetworkStream::GetLength() { return 0; } bool NetworkStream::CanRead() const { return socket->CanReceive(); } bool NetworkStream::CanWrite() const { return socket->CanSend(); } bool NetworkStream::CanSeek() const { return false; } }
634b0c0cab3c5eb4d2d1434f8741d2b9d597d473
0fed3d6c4a6dbdb49029913b6ce96a9ede9eac6c
/Misc/2018_Multi_University/HDU/Day08/I.cpp
f6471820a0fa7ec46019f1b719994d91638c4075
[]
no_license
87ouo/The-road-to-ACMer
72df2e834027dcfab04b02ba0ddd350e5078dfc0
0a39a9708a0e7fd0e3b2ffff5d1f4a793b031df5
refs/heads/master
2021-02-18T17:44:29.937434
2019-07-31T11:30:27
2019-07-31T11:30:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,888
cpp
I.cpp
#include <bits/stdc++.h> using namespace std; const int maxn = 1 << 20; const int mod = 1e9 + 7; int ans[maxn], p[maxn]; struct SAM { int len[maxn << 1], link[maxn << 1], ch[maxn << 1][26]; int tag[maxn << 1], val[maxn << 1]; int sz, rt, last; int newnode(int x = 0) { len[sz] = x; link[sz] = -1; tag[sz] = -1; val[sz] = 1; memset(ch[sz], -1, sizeof(ch[sz])); return sz++; } void init() { sz = last = 0, rt = newnode(); } void reset() { last = 0; } void extend(int c) { int np = newnode(len[last] + 1); int p; for (p = last; ~p && ch[p][c] == -1; p = link[p]) ch[p][c] = np; if (p == -1) link[np] = rt; else { int q = ch[p][c]; if (len[p] + 1 == len[q]) link[np] = q; else { int nq = newnode(len[p] + 1); memcpy(ch[nq], ch[q], sizeof(ch[q])); link[nq] = link[q], link[q] = link[np] = nq; for (; ~p && ch[p][c] == q; p = link[p]) ch[p][c] = nq; } } last = np; } void build(const string& s, int v, int id) { int u = 0; for (auto& c : s) { u = ch[u][c - 'a']; int p = u; while (p && tag[p] != id) { val[p] = 1LL * val[p] * v % mod; tag[p] = id; p = link[p]; } } } void build() { for (int u = 0; u < sz; u++) { int fa = link[u]; ans[len[fa] + 1] = (ans[len[fa] + 1] + val[u]) % mod; ans[len[u] + 1] = (ans[len[u] + 1] - val[u] + mod) % mod; } } } sam; string s[maxn]; char buf[maxn]; int val[maxn]; int Pow(int a, int n) { int t = 1; for (; n; n >>= 1, a = 1LL * a * a % mod) if (n & 1) t = 1LL * t * a % mod; return t; } int main() { int n; memset(ans, 0, sizeof(ans)); scanf("%d", &n); sam.init(); for (int i = 0; i < n; i++) { scanf("%s", buf); for (int j = 0; buf[j]; j++) sam.extend(buf[j] - 'a'); sam.reset(); s[i] = buf; } for (int i = 0; i < n; i++) scanf("%d", &val[i]); for (int i = 0; i < n; i++) sam.build(s[i], val[i], i); sam.build(); for (int i = 1; i < maxn; i++) ans[i] = (ans[i - 1] + ans[i]) % mod; for (int i = 1; i < maxn; i++) ans[i] = (ans[i - 1] + ans[i]) % mod; p[0] = 1; for (int i = 1; i < maxn; i++) p[i] = 26LL * p[i - 1] % mod; for (int i = 2; i < maxn; i++) p[i] = (p[i - 1] + p[i]) % mod; for (int i = 1; i < maxn; i++) ans[i] = 1LL * ans[i] * Pow(p[i], mod - 2) % mod; int m; scanf("%d", &m); for (int i = 0, x; i < m; i++) { scanf("%d", &x); printf("%d\n", ans[x]); } }
99cdca39d75827ccf033fc887cc314db190f3c5a
703552d59f752dc461104a662b428c2e00231aaf
/STLReader/File.h
0340af25f3b927404190e56edd3429552f97320b
[]
no_license
0000duck/STLReader
4d14149a82c44af915c0f2b49c8e5d5c70c1925d
a9f9eabb7b9aa9676bf8e3f905407bfd9d321f41
refs/heads/master
2020-07-16T14:34:58.835508
2015-07-14T19:36:49
2015-07-14T19:36:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
627
h
File.h
#pragma once #include <string> #include <fstream> #include <vector> #include <array> class Traingulation; class File { public: enum class STLFileType { BINARY_STL, ASCII_STL }; public: File(std::string inFileName); ~File(); public: int fileLength(); int lineCount(); public: Traingulation& read(File::STLFileType inSTLFileType, Traingulation& inTraingulation) ; protected: void printAllData(std::vector<std::string>& x, std::array<char, 1> delimiter); private: void processSTLBlock(std::vector<std::string>& inBlock, Traingulation& inTraingulation); private: std::string mFileName; std::fstream mFile; };
719f4ebfac0464378c7b26aee77880c5a7cfa4e1
76e41c1e552c14e12eb7dc3840589143037fe1a7
/my_debug_tools.h
b98049b9926512a530256afa5decbad2d6e41dc8
[]
no_license
Cvlablaneline/LD_Project
7d9759644f772cb1a9ec416bd7309381c5ca61fa
afdf14b8d577c4bdf51e216f9463fae01016fc73
refs/heads/master
2021-01-21T20:06:27.401260
2016-04-27T20:08:08
2016-04-27T20:08:08
29,433,396
0
0
null
null
null
null
UTF-8
C++
false
false
623
h
my_debug_tools.h
// // my_debug_tools.h // LD_Project_xcode // // Created by Chienfu Huang on 2014/11/28. // Copyright (c) 2014年 ___HCF___. All rights reserved. // #ifndef __LD_Project_xcode__my_debug_tools__ #define __LD_Project_xcode__my_debug_tools__ #include <iostream> #include<highgui.h> using namespace std; class dbugTool_Wait { private: int Acount; int Ncount; bool enable; public: dbugTool_Wait(); dbugTool_Wait(int num); dbugTool_Wait(int num,bool status); int touch(); void stop (); void start (); bool status (); }; #endif /* defined(__LD_Project_xcode__my_debug_tools__) */
ed1ef367d57e3b74f827df6de51006e3aa231032
7279b5087de408b626777aedb0c91ebcf22d8bc6
/User_Activity Function using QT (UI)/subactivity_list.h
d0dcc431c9699028c0fe8b345e007b1dd520c174
[]
no_license
cdeepanshu/User-Activity-UI-and-CLI
9bd49ea2b757635ec7fa91abfcd81b77af1c5a82
47223e992d94bc27b5f61b48735a12f412feaf1e
refs/heads/master
2022-12-02T19:11:28.166946
2020-08-18T07:52:47
2020-08-18T07:52:47
288,389,402
0
0
null
null
null
null
UTF-8
C++
false
false
449
h
subactivity_list.h
#ifndef SUBACTIVITY_LIST_H #define SUBACTIVITY_LIST_H #include <QDialog> namespace Ui { class subactivity_list; } class subactivity_list : public QDialog { Q_OBJECT public: explicit subactivity_list(QWidget *parent = nullptr); ~subactivity_list(); private slots: void on_pushButton_clicked(); void on_pushButton_2_clicked(); private: Ui::subactivity_list *ui; }; #endif // SUBACTIVITY_LIST_H
7fa9a2542756387ceb6c8eae9d0a6371a73f4003
c6edda04814ffb23df750ce23b81169ec35c0057
/EngineTools/ConfigFile.h
e21ead6f6030822f6ceb9362099f1e216cf56050
[]
no_license
wlodarczykbart/SunEngine
91d755cca91ca04ef91879ccfd11500f884e5066
04200f084653e88ba332bb260b6964996f35f5a0
refs/heads/master
2023-06-07T02:33:20.668913
2021-07-03T17:31:38
2021-07-03T17:31:38
315,081,186
0
0
null
null
null
null
UTF-8
C++
false
false
1,829
h
ConfigFile.h
#pragma once #include "Types.h" namespace SunEngine { class ConfigSection { public: ConfigSection(); ~ConfigSection(); const String& GetName() const { return _name; } String GetString(const String& key, const char* defaultValue = "") const; int GetInt(const String& key, int defaultValue = 0) const; uint GetUInt(const String& key, uint defaultValue = 0) const; float GetFloat(const String& key, float defaultValue = 0.0f) const; bool GetBool(const String& key, bool defaultValue = true) const; bool GetBlock(const String& key, StrMap<String>& block, char blockStart = 0, char blockEnd = 0) const; void SetString(const String& key, const char* value); void SetInt(const String& key, const int value); void SetFloat(const String& key, const float value); void SetBlock(const String& key, const StrMap<String>& block, char blockStart = 0, char blockEnd = 0); bool HasKey(const String& key) const; uint GetCount() const; typedef StrMap<String>::const_iterator Iterator; Iterator Begin() const; Iterator End() const; private: bool GetValue(const String& key, const String** pStr) const; friend class ConfigFile; StrMap<String> _dataPairs; String _name; }; class ConfigFile { public: ConfigFile(); ~ConfigFile(); bool Load(const String& fileName); bool Save(const String& fileName); ConfigSection* AddSection(const String& section); ConfigSection* GetSection(const String& section); const ConfigSection* GetSection(const String& section) const; const String& GetFilename() const; void Clear(); typedef StrMap<ConfigSection>::const_iterator Iterator; Iterator Begin() const; Iterator End() const; private: String _filename; StrMap<ConfigSection> _sections; }; }
cdd7c8e7ca8f759f7c59dcf50db495452a3a0bfb
11b94100dcfcba071850bc8b5b1a3ab50006f5cf
/Header/UtilStructs.h
11f60460ed69d668cbdd1ba52f4ed77510f12870
[ "MIT" ]
permissive
LydianJay/ConsoleTetrisBattle2p
dc2c47f19bdc1e8ffca400506015b96e03843357
66ce8b61e1ec94e662764f74c597c6a89f418936
refs/heads/master
2023-01-12T05:21:24.481533
2020-11-22T07:55:59
2020-11-22T07:55:59
287,211,133
0
0
null
null
null
null
UTF-8
C++
false
false
932
h
UtilStructs.h
#ifndef DEF_ #define DEF_ #include <Windows.h> #include <string> #include <fstream> #include <sstream> #define WASD 0x1 #define UDLR 0x2 #define VERTICAL 0x1 #define HORIZONTAL 0x2 typedef unsigned char byte; typedef struct _AsciiData { std::string graphics; COORD sz; COORD Pos; }AsciiArt, AsciiData; typedef struct _Points { short int X; short int Y; }Points; typedef struct _LinePoints { Points p1; Points p2; }LPoints; struct vec2i { int X; int Y; }; struct vec2s { short X; short Y; }; struct vec2by { byte X; byte Y; }; struct list { list * next = nullptr; list * prev = nullptr; int val = 0; }; typedef unsigned char byte; typedef char * str; bool LoadDataFromFile(AsciiArt& art, const char * filename); //Overload bool LoadDataFromFile(AsciiArt& art, const std::string& filename); Points operator-(const Points &p1, const Points &p2); #endif // !DEF_
8f28daeae073af98bcff8979f4aedc917f7cf6d2
30052f149920c6a235759e9c573990a5ec00b976
/C/lcs.cpp
09732e06168826ac70079e2e06cef4ce8245a53b
[]
no_license
Ajay35/spoj
63f29fda94aeed4a581d265dfabbd6ef600ddd69
34d59f8b1c435b98cc1a171d57cdcff7b50e6f78
refs/heads/master
2020-03-18T16:32:59.068268
2019-07-30T11:54:29
2019-07-30T11:54:29
134,972,271
0
0
null
null
null
null
UTF-8
C++
false
false
838
cpp
lcs.cpp
#include <bits/stdc++.h> #define LL long long #define inf std::numeric_limits<int>::max(); #define neginf std::numeric_limits<int>::min(); #define mod 1000000007 #define pb push_back #define ppi pair<int,int> #define vi vector<int> #define vii vector<ppi> #define vll vector<LL> using namespace std; string s1,s2; int main() { #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif ios::sync_with_stdio(0); cin.tie(NULL); while(getline(cin,s1)) { getline(cin,s2); int i,j,n,m; n=s1.size(); m=s2.size(); int dp[n+1][m+1]; for(i=0;i<=n;i++){ for(j=0;j<=m;j++){ if(i==0 || j==0) dp[i][j]=0; else if(s1[i-1]==s2[j-1]) dp[i][j]=1+dp[i-1][j-1]; else dp[i][j]=max(dp[i-1][j],dp[i][j-1]); } } cout<<dp[n][m]<<"\n"; } return 0; }
55dd895932a4a6c0f26e686cd4f181f40bbf2c1f
f35258fe5d64eff869663c428c4f69080cdecf66
/OpenGLReborn/TextureRenderTarget.h
470df5ad6e00885f76bc7f058aa688d4b3cb28c1
[]
no_license
hlopeth/OpenGLReborn
9b81a0a186876185f11ebfdb92880150d6011631
413097b7f71198ee4cd562e78a2baf6654383535
refs/heads/master
2021-06-25T08:04:35.194464
2020-11-29T16:03:36
2020-11-29T16:03:36
176,695,892
3
0
null
2020-11-29T13:01:26
2019-03-20T09:10:11
C++
UTF-8
C++
false
false
469
h
TextureRenderTarget.h
#pragma once #ifndef __gl_h_ #include <glad/glad.h> #endif #include "GLTexture.h" class TextureRenderTarget { public: TextureRenderTarget(); TextureRenderTarget(size_t width, size_t height); ~TextureRenderTarget(); void allocate(size_t width, size_t height); void bind() const; bool isComplete() const; GLuint getFbo() const; GLuint getRbo() const; GLTexture getTexture() const; private: GLuint fbo; //depth renderbuffer GLuint rbo; GLTexture texture; };
755aec662afc40ef9537a8286fdbd9480b4da1a8
f2253ad57eac6313201237aaede70f6a334a3349
/src/gaen/assets/AssetHeader.h
9de8d33736841686df6331c51d1876c59a958ed3
[ "Zlib" ]
permissive
lachlanorr/gaen
d9c53f82d4d816f15a93783ec2f266e6438418b6
1a65e22ea0a8c9e263ef41559fc0a1c893b87e90
refs/heads/master
2022-06-28T06:48:31.524403
2022-06-14T10:03:35
2022-06-14T10:03:35
19,638,018
2
1
NOASSERTION
2019-09-12T03:17:01
2014-05-10T09:38:31
C++
UTF-8
C++
false
false
3,525
h
AssetHeader.h
//------------------------------------------------------------------------------ // AssetHeader.h - Struct that appears at head of every cooked asset // // Gaen Concurrency Engine - http://gaen.org // Copyright (c) 2014-2022 Lachlan Orr // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. //------------------------------------------------------------------------------ #ifndef GAEN_ASSETS_ASSETHEADER_H #define GAEN_ASSETS_ASSETHEADER_H #include "gaen/core/mem.h" namespace gaen { class AssetHeader { public: AssetHeader(u32 magic4cc, u64 size) { mMagic4cc = magic4cc; mChefVersion = 0; mCookerVersion = 0; mSize = size; } u32 magic4cc() const { return mMagic4cc; } u32 chefVersion() const { return mChefVersion; } void setChefVersion(u32 version) { mChefVersion = version; } u32 cookerVersion() const { return mCookerVersion; } void setCookerVersion(u32 version) { mCookerVersion = version; } u64 size() const { return mSize; } void setSize(u64 size) { mSize = size; } void getExt(char * ext) { char * p4cc = (char*)&mMagic4cc; ext[0] = p4cc[0]; ext[1] = p4cc[1]; ext[2] = p4cc[2]; ext[3] = p4cc[3]; ext[4] = '\0'; } protected: u32 mMagic4cc; // typically the cooked extension u16 mChefVersion; // chef version that cooked the file u16 mCookerVersion; // cooker version that cooked the file u64 mSize; // total asset size, including header private: AssetHeader(const AssetHeader&) = delete; AssetHeader(AssetHeader&&) = delete; AssetHeader & operator=(const AssetHeader&) = delete; AssetHeader & operator=(AssetHeader&&) = delete; }; static_assert(sizeof(AssetHeader) == 16, "AssetHeader unexpected size"); static_assert(sizeof(AssetHeader) % 16 == 0, "AssetHeader size not 16 byte aligned"); template <u32 FCC> class AssetHeader4CC : public AssetHeader { public: static const u32 kMagic4CC = FCC; template <class T> static T * alloc_asset(MemType memType, u64 size) { AssetHeader4CC * pAH = new (GALLOC(memType, size)) AssetHeader4CC(size); memset(pAH+1, 0, size - sizeof(AssetHeader4CC)); return static_cast<T*>(pAH); } private: explicit AssetHeader4CC(u64 size) : AssetHeader(FCC, size) {} AssetHeader4CC(const AssetHeader4CC&) = delete; AssetHeader4CC(AssetHeader4CC&&) = delete; AssetHeader4CC & operator=(const AssetHeader4CC&) = delete; AssetHeader4CC & operator=(AssetHeader4CC&&) = delete; }; } // namespace gaen #endif // #ifndef GAEN_ASSETS_ASSETHEADER_H
55078dba9672688ce8e9f03b02f9973e6ad13cde
c31ad9981bb2760c6f389e9a6cf8a6893e9423e8
/osc/Lib/include/Lib/Functions.h
2d4e4623a33b2f0c790e037000049d97ca6de436
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
gbarrand/osc_vis_for_LHCb
0582d7ed6734d9716619eb0fccc69904381529d8
2ba864c4475f988192c9799f5be85f1abf88c364
refs/heads/master
2021-10-25T21:32:51.600843
2021-10-17T07:45:20
2021-10-17T07:45:20
140,073,663
0
2
null
2021-10-17T07:45:20
2018-07-07T10:11:36
C++
UTF-8
C++
false
false
19,057
h
Functions.h
#ifndef Lib_Functions_h #define Lib_Functions_h // Inheritance : #include <Slash/Data/IFunction.h> #include <vector> #include <string> #include <ostream> #include <inlib/sort> #include <inlib/strip> #include <inlib/touplow> #include <Lib/Processor.h> namespace Lib { namespace Function { class Scripted { public: Scripted(const std::string& aString,std::ostream& a_out) :fScript(aString),fIsValid(false),fDimension(0), f_out(a_out),fProcessor("",a_out) { set(aString); } virtual ~Scripted(){} public: Scripted(const Scripted& aFrom) :fScript(aFrom.fScript),fIsValid(false) ,fDimension(aFrom.fDimension),fParameterNames(aFrom.fParameterNames) ,fParameterValues(aFrom.fParameterValues) ,fVariableNames(aFrom.fVariableNames) ,f_out(aFrom.f_out),fProcessor("",aFrom.f_out) { set(aFrom.fScript); } Scripted& operator=(const Scripted& aFrom){ fScript = aFrom.fScript; fDimension = aFrom.fDimension; fParameterNames = aFrom.fParameterNames; fParameterValues = aFrom.fParameterValues; fVariableNames = aFrom.fVariableNames; //f_out = aFrom.f_out; fIsValid = false; set(aFrom.fScript); return *this; } public: bool isValid() const{return fIsValid;} unsigned int dimension() const {return fDimension;} std::string script() const {return fScript;} std::vector<std::string> parameterNames() const {return fParameterNames;} std::vector<double> parameterValues() const {return fParameterValues;} std::vector<std::string> variableNames() const {return fVariableNames;} bool set(const std::string& aString){ reset(); //Check for AIDA/SLAC variable syntax convention x[<int>] : std::string ss = aString; std::string ns; bool slac_syntax = false; while(true) { std::string::size_type lb = ss.find("x["); if(lb==std::string::npos){ ns += ss; break; } std::string::size_type rb = ss.find(']',lb+2); if(rb==std::string::npos) { f_out << "Lib::Function::Scripted::set :" << " bad [] balance in " << inlib::sout(aString) << std::endl; reset(); return false; } // abx[012]ef // 0 2 7 9 size=10 std::string snum = ss.substr(lb+2,rb-lb-2); int coord; if(!inlib::to<int>(snum,coord)) { f_out << "Lib::Function::Scripted::set :" << " integer expected within [] in " << inlib::sout(aString) << ". Found " << inlib::sout(snum) << "." << std::endl; reset(); return false; } slac_syntax = true; ns += ss.substr(0,lb)+ "x"+ snum; ss = ss.substr(rb+1,ss.size()-rb); } //printf("debug : ns \"%s\"\n",ns.c_str()); // Find variables in the script : fProcessor.setScript(ns); std::vector<std::string> vars; if(!fProcessor.findVariables(vars)) { f_out << "Lib::Function::Scripted::set :" << " Lib::Processor can't find variables in " << inlib::sout(aString) << std::endl; reset(); return false; } //vars had been passed to inlib::unique. // In vars, some are expected to be of the form x<int>. // The x<int> are the variables of the scripted function. // The rest are the parameters of the scripted function. // The variables are used to find the dimension of the function. // If x0 only is found, then it is a one dim function. // If x0,x1 only are found, then it is a two dim function, etc... std::vector<int> coords; bool found_x = false; bool found_y = false; bool found_z = false; {for(unsigned int index=0;index<vars.size();index++) { int coord; if(vars[index]=="x") { found_x = true; } else if(vars[index]=="y") { found_y = true; } else if(vars[index]=="z") { found_z = true; } else if(isVariable(vars[index],coord)) { coords.push_back(coord); } else { fParameterNames.push_back(vars[index]); } }} vars.clear(); //Reorder with params first and variables last. {for(unsigned int index=0;index<fParameterNames.size();index++) { vars.push_back(fParameterNames[index]); }} // Sort coords : if(coords.size()) { if(found_x||found_y||found_z) { f_out << "Lib::Function::Scripted::set :" << " inconsistent variable specification in " << inlib::sout(aString) << std::endl; reset(); return false; } inlib::sort::sort<int>(coords); for(unsigned int index=0;index<coords.size();index++) { std::string s; inlib::sprintf(s,32,"x%d",coords[index]); vars.push_back(s); if(slac_syntax) { inlib::sprintf(s,32,"x[%d]",coords[index]); fVariableNames.push_back(s); } else { fVariableNames.push_back(s); } } } else { if(found_x) { vars.push_back("x"); fVariableNames.push_back("x"); } if(found_y) { vars.push_back("y"); fVariableNames.push_back("y"); } if(found_z) { vars.push_back("z"); fVariableNames.push_back("z"); } } if(!fProcessor.compile(vars)) { f_out << "Lib::Function::Scripted::set :" << " Lib::Processor can't compile " << inlib::sout(aString) << std::endl; reset(); return false; } fParameterValues.resize(fParameterNames.size(),0); fInput.resize (fParameterNames.size()+fVariableNames.size(),Lib::Value((double)0)); fScript = aString; fDimension = fVariableNames.size(); fIsValid = true; return true; } bool setParameters(const std::vector<double>& aParams){ if(aParams.size()!=fParameterValues.size()) return false; fParameterValues = aParams; return true; } bool value(const std::vector<double>& aXs,double& aValue, std::string& aError) const { INLIB_SELF(Scripted); if(!isValid()) { aValue = 0; aError = "Lib::Function::Scripted::value : is not valid."; return false; } if(aXs.size()!=fDimension) { aValue = 0; aError = "Lib::Function::Scripted::value : xs.size()/dimension mismatch."; return false; } unsigned int ii = 0; {unsigned int number = fParameterValues.size(); for(unsigned int index=0;index<number;index++) { self.fInput[ii].set(fParameterValues[index]); ii++; }} {unsigned int number = aXs.size(); for(unsigned int index=0;index<number;index++) { self.fInput[ii].set(aXs[index]); ii++; }} Lib::Value var; if(!self.fProcessor.execute(fInput,var,aError)) { aValue = 0; return false; } if(var.type()!=Slash::Core::IValue::DOUBLE) { aError = std::string("Lib::Function::Scripted::value :") + " result is not a double Variable."; aValue = 0; return false; } //aValue = var.toDouble(); //FIXME aValue = var.get_double(); return true; } private: static bool isVariable(const std::string& aVar,int& aIndex){ // If aVar is not of the form x<int> return false. // If yes, return true with aIndex=<int>. if(aVar.size()<=1) { aIndex = 0; return false; } if(aVar[0]!='x') { aIndex = 0; return false; } if(!inlib::to<int>(aVar.substr(1,aVar.size()-1),aIndex)) { aIndex = 0; return false;; } return true; } void reset(){ // Reset : fIsValid = false; fScript = ""; fDimension = 0; fParameterNames.clear(); fParameterValues.clear(); fVariableNames.clear(); fProcessor.clear(); fInput.clear(); } private: std::string fScript; bool fIsValid; unsigned int fDimension; std::vector<std::string> fParameterNames; std::vector<double> fParameterValues; std::vector<std::string> fVariableNames; std::ostream& f_out; Processor fProcessor; std::vector<Lib::Value> fInput; }; class Composite { public: Composite(const std::string& aString,std::ostream& a_out) :fScript(aString),fScripted("0",a_out),f_out(a_out){ set(aString); } virtual ~Composite(){} public: Composite(const Composite& aFrom) :fScript(aFrom.fScript),fScripted(aFrom.fScripted),f_out(aFrom.f_out){ set(aFrom.fScript); } Composite& operator=(const Composite& aFrom){ fScript = aFrom.fScript; fScripted = aFrom.fScripted; //f_out = aFrom.f_out; set(aFrom.fScript); return *this; } public: bool isValid() const {return fScripted.isValid();} unsigned int dimension() const {return fScripted.dimension();} std::string script() const {return fScript;} std::vector<std::string> parameterNames() const { return fScripted.parameterNames(); } std::vector<double> parameterValues() const { return fScripted.parameterValues(); } std::vector<std::string> variableNames() const { return fScripted.variableNames(); } bool setParameters(const std::vector<double>& aParams){ return fScripted.setParameters(aParams); } bool value(const std::vector<double>& aXs,double& aValue, std::string& aError) const { return fScripted.value(aXs,aValue,aError); } bool set(const std::string& aString){ // exa : G+E // FIXME : have more operations. std::string s; std::string script; std::vector<std::string> words; inlib::words(aString,"+",false,words); unsigned int wordn = words.size(); for(unsigned int index=0;index<wordn;index++) { if(index) script += "+"; std::string& word = words[index]; inlib::strip(word); inlib::touppercase(word); std::string p; //variable prefix. const char* pc = p.c_str(); if(word=="E") { if(wordn>=2) inlib::sprintf(p,32,"E_%d_",index); inlib::sprintf(s,132,"%samplitude*exp(x*%sexponent)",pc,pc); } else if(word=="EHBOOK") { if(wordn>=2) inlib::sprintf(p,32,"EHBOOK_%d_",index); inlib::sprintf(s,132,"expo(x,%sA,%sB)",pc,pc); } else if(word=="G") { if(wordn>=2) inlib::sprintf(p,32,"G_%d_",index); inlib::sprintf (s,132,"gauss(x,%samplitude,%smean,%ssigma)",pc,pc,pc); } else if(word=="BW") { if(wordn>=2) inlib::sprintf(p,32,"BW_%d_",index); inlib::sprintf (s,132,"breit(x,%samplitude,%sorigin,%swidth)",pc,pc,pc); } else if(word=="P1") { if(wordn>=2) inlib::sprintf(p,32,"P1_%d_",index); inlib::sprintf(s,132,"pol1(x,%sp0,%sp1)",pc,pc); } else if(word=="P2") { if(wordn>=2) inlib::sprintf(p,32,"P2_%d_",index); inlib::sprintf(s,132,"pol2(x,%sp0,%sp1,%sp2)",pc,pc,pc); } else if(word=="P3") { if(wordn>=2) inlib::sprintf(p,32,"P3_%d_",index); inlib::sprintf (s,132,"pol3(x,%sp0,%sp1,%sp2,%sp3)",pc,pc,pc,pc); } else if(word=="P4") { if(wordn>=2) inlib::sprintf(p,32,"P4_%d_",index); inlib::sprintf (s,132,"pol4(x,%sp0,%sp1,%sp2,%sp3,%sp4)",pc,pc,pc,pc,pc); } else { f_out << "Lib::Function::Composite::set :" << " in " << inlib::sout(aString) << ", unknown function " << inlib::sout(word) << std::endl; fScript = ""; return false; } script += s; } //printf("debug : composite : \"%s\"\n",script.c_str()); if(!fScripted.set(script)) { fScript = ""; return false; } fScript = aString; return true; } private: static bool isVariable(const std::string&,int&); void reset(); private: std::string fScript; Scripted fScripted; std::ostream& f_out; }; class Compiled : public virtual Slash::Data::IFunction { public: // IFunction : virtual std::string file() const {return fFile;} virtual std::string model() const {return fModel;} virtual void* address() const {return fAddress;} virtual unsigned int dimension() const { unsigned int dim = 0; unsigned int dimn = fDims.size(); for(unsigned int i=0;i<dimn;i++) dim += (fDims[i]?fDims[i]:1); return dim; } virtual unsigned int numberOfParameters() const {return fParn;} virtual bool value(const std::vector<double>& aArgs,double& aValue) const { if(!fAddress) { aValue = 0; return false; } if(aArgs.size()!=dimension()) { aValue = 0; return false; } bool status = true; unsigned int argn = fValues.size(); unsigned int aArgn = aArgs.size(); {unsigned int argc = 0; for(unsigned int argi=0;argi<argn;argi++) { Slash::Core::IValue* ivalue = fValues[argi]; if(ivalue->type()==Slash::Core::IValue::DOUBLE) { if((argc+1)>aArgn) { status = false; break; } else { ivalue->set(aArgs[argc]); argc++; } } else if(ivalue->type()==Slash::Core::IValue::FLOAT) { if((argc+1)>aArgn) { status = false; break; } else { ivalue->set((float)aArgs[argc]); argc++; } } else if(ivalue->type()==Slash::Core::IValue::INT) { if((argc+1)>aArgn) { status = false; break; } else { ivalue->set((int)aArgs[argc]); argc++; } } else if(ivalue->type()==Slash::Core::IValue::DOUBLE_STAR) { unsigned int dim = fDims[argi]; if((argc+dim)>aArgn) { status = false; break; } else { double* array = ivalue->get_double_star(); for(unsigned int i=0;i<dim;i++) { array[i] = aArgs[argc]; argc++; } } } else if(ivalue->type()==Slash::Core::IValue::INT_STAR) { unsigned int dim = fDims[argi]; if((argc+dim)>aArgn) { status = false; break; } else { int* array = ivalue->get_int_star(); for(unsigned int i=0;i<dim;i++) { array[i] = (int)aArgs[argc]; argc++; } } } else if(ivalue->type()==Slash::Core::IValue::FLOAT_STAR) { unsigned int dim = fDims[argi]; if((argc+dim)>aArgn) { status = false; break; } else { float* array = ivalue->get_float_star(); for(unsigned int i=0;i<dim;i++) { array[i] = (float)aArgs[argc]; argc++; } } } else { status = false; break; } } if(argc!=dimension()) { status = false; }} //if(!status) { //printf("debug : Lib::Function::Compiled::value : arg setup failed.\n"); //} if(status) { typedef bool (*Function)(const std::vector<Slash::Core::IValue*>&, Slash::Core::IValue&); status = ((Function)fAddress)(fValues,*fReturn); } if(status) { status = true; if(fReturn->type()==Slash::Core::IValue::FLOAT) { aValue = fReturn->get_float(); } else if(fReturn->type()==Slash::Core::IValue::DOUBLE) { aValue = fReturn->get_double(); } else { status = false; } } return status; } virtual bool value(const std::vector<Slash::Core::IValue*>& aArgs, Slash::Core::IValue& aValue) const { if(!fAddress) { aValue.setNone(); return false; } typedef bool (*Function)(const std::vector<Slash::Core::IValue*>&, Slash::Core::IValue&); return ((Function)fAddress)(aArgs,aValue); } virtual std::vector<Slash::Core::IValue*> signature(Slash::Core::IValue*& aReturn) const { // args + return value. aReturn = fReturn; return fValues; } public: Compiled(std::ostream& a_out, const std::string& aFile,const std::string& aModel, void* aAddress,const std::vector<Lib::Value>& aArgs, unsigned int aParn) :f_out(a_out) ,fFile(aFile) ,fModel(aModel) ,fAddress(aAddress) ,fParn(aParn) ,fReturn(0) { Lib::Debug::increment("Lib::Function::Compiled"); unsigned int argn = aArgs.size(); for(unsigned int argi=0;argi<argn;argi++) { const Lib::Value& v = aArgs[argi]; if( (v.type()==Slash::Core::IValue::DOUBLE_STAR) || (v.type()==Slash::Core::IValue::INT_STAR) || (v.type()==Slash::Core::IValue::FLOAT_STAR) || (v.type()==Slash::Core::IValue::DOUBLE) || (v.type()==Slash::Core::IValue::INT) || (v.type()==Slash::Core::IValue::FLOAT) ){ //ok } else { //unknown type : f_out << "Lib::Function::Compiled::Compiled :" << " " << inlib::sout(v.stype()) << " not handled." << std::endl; fAddress = 0; fDims.clear(); return; } fDims.push_back(v.dimension()); //printf("debug : arg \"%s\" %d\n",NAME.c_str(),dim); } // to optimize : {fValues.resize(argn,0); for(unsigned int argi=0;argi<argn;argi++) { const Lib::Value& v = aArgs[argi]; if(v.type()==Slash::Core::IValue::DOUBLE) { fValues[argi] = new Lib::Value(double(0)); } else if(v.type()==Slash::Core::IValue::FLOAT) { fValues[argi] = new Lib::Value(float(0)); } else if(v.type()==Slash::Core::IValue::INT) { fValues[argi] = new Lib::Value(int(0)); } else if(v.type()==Slash::Core::IValue::DOUBLE_STAR) { unsigned int dim = fDims[argi]; double* array = dim ? new double[dim] : 0; fValues[argi] = new Lib::Value(array); } else if(v.type()==Slash::Core::IValue::INT_STAR) { unsigned int dim = fDims[argi]; int* array = dim ? new int[dim] : 0; fValues[argi] = new Lib::Value(array); } else if(v.type()==Slash::Core::IValue::FLOAT_STAR) { unsigned int dim = fDims[argi]; float* array = dim? new float[dim] : 0; fValues[argi] = new Lib::Value(array); } }} fReturn = new Lib::Value; } virtual ~Compiled(){ delete fReturn; {unsigned int argn = fValues.size(); for(unsigned int argi=0;argi<argn;argi++) { Slash::Core::IValue* ivalue = fValues[argi]; if(ivalue->type()==Slash::Core::IValue::FLOAT_STAR) { if(ivalue->get_float_star()) delete [] ivalue->get_float_star(); } else if(ivalue->type()==Slash::Core::IValue::DOUBLE_STAR) { if(ivalue->get_double_star()) delete [] ivalue->get_double_star(); } else if(ivalue->type()==Slash::Core::IValue::INT_STAR) { if(ivalue->get_int_star()) delete [] ivalue->get_int_star(); } delete ivalue; }} Lib::Debug::decrement("Lib::Function::Compiled"); } private: std::ostream& f_out; std::string fFile; std::string fModel; void* fAddress; std::vector<unsigned int> fDims; unsigned int fParn; std::vector<Slash::Core::IValue*> fValues; Slash::Core::IValue* fReturn; }; } //Function } //Lib #endif
11bd71187664eee4959acfdb10cae924ddd749e9
58d1d711a5ee5f7139eae18220126d751dfc5505
/parallel.cpp
037bd01409e2ad0c524d4cb5cab40716c293a81c
[]
no_license
lily-liu-17/ICS3U-Assignment-6-Cpp-Parallel
0978c900448d4108cfbc13a125199111dd1ad473
de99c006486339b8e20e5525ee47b2a5febe29d8
refs/heads/main
2023-08-18T22:42:04.566068
2021-10-16T02:32:36
2021-10-16T02:32:36
417,649,281
0
0
null
null
null
null
UTF-8
C++
false
false
1,170
cpp
parallel.cpp
// Copyright Lily Liu All rights reserved. // // Created by: Lily Liu // Created on: Oct 2021 // This program will calculate area of parallelogram #include <iostream> #include <string> float CalculateArea(float base, float height) { // This function will calculate ill calculate area of parallelogram float area = base * height; return area; } int main() { // this is he main function float baseUser; float heightUser; std::string baseUserString; std::string heightUserString; // input std::cout << "Enter the base of the parallelogram (cm) : "; std::cin >> baseUserString; std::cout << "Enter the length of the parallelogram (cm) : "; std::cin >> heightUserString; // output try { baseUser = std::stof(baseUserString); heightUser = std::stof(heightUserString); // call functions float area = CalculateArea(baseUser, heightUser); std::cout << "\nThe area of the parallelogram is " << area << " cm²." << std::endl; } catch (std::invalid_argument) { std::cout << "\nInvalid input" << std::endl; } std::cout << "\nDone." << std::endl; }
2f939d844936f4826f23d28594f71bf0f4d62996
7a36a0652fe0704b4b27f644653e7b0f7e72060f
/TianShan/common/TimerWatchdog.cpp
0af8e92cf770a62ba419066aabde88595d9d8d9f
[]
no_license
darcyg/CXX
1ee13c1765f1987e293c15b9cbc51ae625ac3a2e
ef288ad0e1624ed0582839f2a5a0ef66073d415e
refs/heads/master
2020-04-06T04:27:11.940141
2016-12-29T03:49:56
2016-12-29T03:49:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,350
cpp
TimerWatchdog.cpp
// =========================================================================== // Copyright (c) 2006 by // ZQ Interactive, Inc., Shanghai, PRC., // All Rights Reserved. Unpublished rights reserved under the copyright // laws of the United States. // // The software contained on this media is proprietary to and embodies the // confidential technology of ZQ Interactive, Inc. Possession, use, // duplication or dissemination of the software and media is authorized only // pursuant to a valid written license from ZQ Interactive, Inc. // // This software is furnished under a license and may be used and copied // only in accordance with the terms of such license and with the inclusion // of the above copyright notice. This software or any other copies thereof // may not be provided or otherwise made available to any other person. No // title to and ownership of the software is hereby transferred. // // The information in this software is subject to change without notice and // should not be construed as a commitment by ZQ Interactive, Inc. // // Ident : $Id: TimerWatchDog.h $ // Branch: $Name: $ // Author: Hui Shao // Desc : // // Revision History: // --------------------------------------------------------------------------- // $Log: /ZQProjs/TianShan/common/TimerWatchdog.cpp $ // // 6 1/07/14 11:09a Hui.shao // // 5 1/07/14 11:05a Hui.shao // // 4 1/07/14 11:04a Hui.shao // // 3 1/07/14 10:57a Hui.shao // avoid to post TimerCmd() after threadpool is released // // 2 1/11/11 12:17p Hongquan.zhang // use ZQ::common::Semaphore in WatchDog // // 5 10-03-04 14:05 Jie.zhang // fixed the issue of OnTimer skipped when some exception happen, cause // OnTimer would not be called again. (based on OnTimer call to continue // next call) // // 4 08-11-13 14:18 Yixin.tian // modify to compile in Linux OS // // 3 08-10-28 15:09 Hui.shao // // 2 08-10-28 11:32 Hui.shao // // 1 08-10-16 19:43 Hui.shao // =========================================================================== #include "TianShanDefines.h" #ifdef ZQ_OS_LINUX extern "C" { #include <sys/timeb.h> #include <time.h> } #endif #define WatchDog_MIN_IDLE_INTERVAL (1000) namespace ZQTianShan { // ----------------------------- // class TimeoutCmd // ----------------------------- /// class TimeoutCmd : protected ZQ::common::ThreadRequest { friend class TimerWatchDog; protected: /// constructor ///@note no direct instantiation of ProvisionCmd is allowed TimeoutCmd(TimerWatchDog& watchdog, const ::Ice::Identity& identObj); virtual ~TimeoutCmd() {} protected: // impls of ThreadRequest virtual bool init(void) { return true; }; virtual int run(void); // no more overwrite-able void final(int retcode =0, bool bCancelled =false) { delete this; } protected: TimerWatchDog& _watchdog; ::Ice::Identity _identObj; }; TimeoutCmd::TimeoutCmd(TimerWatchDog& watchdog, const ::Ice::Identity& identObj) : ThreadRequest(watchdog._thrdPool), _watchdog(watchdog), _identObj(identObj) { } #define RETRY_TIME_MS 2000 int TimeoutCmd::run(void) { ::TianShanUtils::TimeoutObjPrx obj; try { obj = ::TianShanUtils::TimeoutObjPrx::checkedCast(_watchdog._adapter->createProxy(_identObj)); obj->OnTimer(); return 0; } catch(const ::Ice::ObjectNotExistException&) { return 0; } catch(const ::TianShanIce::BaseException& ex) { _watchdog._log(ZQ::common::Log::L_WARNING, CLOGFMT(TimeoutCmd, "%s[%s] exception occurs: %s:%s, retry in %dms"), _identObj.category.c_str(), _identObj.name.c_str(), ex.ice_name().c_str(), ex.message.c_str(), RETRY_TIME_MS); _watchdog.watch(_identObj, RETRY_TIME_MS); } catch(const ::Ice::Exception& ex) { _watchdog._log(ZQ::common::Log::L_WARNING, CLOGFMT(TimeoutCmd, "%s[%s] exception occurs: %s, retry in %dms"), _identObj.category.c_str(), _identObj.name.c_str(), ex.ice_name().c_str(), RETRY_TIME_MS); _watchdog.watch(_identObj, RETRY_TIME_MS); } catch(...) { _watchdog._log(ZQ::common::Log::L_ERROR, CLOGFMT(TimeoutCmd, "%s[%s] unknown exception occurs"), _identObj.category.c_str(), _identObj.name.c_str()); } return -1; } // ----------------------------- // class TimerWatchDog // ----------------------------- TimerWatchDog::TimerWatchDog(ZQ::common::Log& log, ZQ::common::NativeThreadPool& thrdPool, ZQADAPTER_DECLTYPE& adapter, const char* name, const int idleInterval) : ThreadRequest(thrdPool), _log(log), _thrdPool(thrdPool), _adapter(adapter), _bQuit(false), _idleInterval(idleInterval) { _name = name ? name : ""; /* #ifdef ZQ_OS_MSWIN _hWakeupEvent = NULL; _hWakeupEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL); #else int nre = sem_init(&_hWakeupSem,0,0); if(nre == -1) perror("TimerWatchDog() sem_init"); #endif */ if (_idleInterval < WatchDog_MIN_IDLE_INTERVAL) _idleInterval = WatchDog_MIN_IDLE_INTERVAL; if (_idleInterval > WatchDog_MAX_IDLE_INTERVAL) _idleInterval = WatchDog_MAX_IDLE_INTERVAL; } TimerWatchDog::~TimerWatchDog() { quit(); /* #ifdef ZQ_OS_MSWIN if(_hWakeupEvent) ::CloseHandle(_hWakeupEvent); _hWakeupEvent = NULL; #else try { sem_destroy(&_hWakeupSem); } catch(...){} #endif */ } void TimerWatchDog::wakeup() { _semWakeup.post(); /* #ifdef ZQ_OS_MSWIN ::SetEvent(_hWakeupEvent); #else sem_post(&_hWakeupSem); #endif */ } bool TimerWatchDog::init(void) { /* #ifdef ZQ_OS_MSWIN return (NULL != _hWakeupEvent && !_bQuit); #else int nV = 0; return (sem_getvalue(&_hWakeupSem,&nV) != -1 && !_bQuit); #endif */ return true; } #define MIN_YIELD (100) // 100 msec int TimerWatchDog::run() { _log(ZQ::common::Log::L_DEBUG, CLOGFMT(TimerWatchDog, "watchdog[%s] start running"), _name.c_str()); while(!_bQuit) { ::Ice::Long timeOfNow = now(); IdentCollection objIdentsToExec; { ZQ::common::MutexGuard gd(_lockExpirations); { static size_t _slastWatchSize =0; size_t watchSize=_expirations.size(); if (watchSize != _slastWatchSize) _log(ZQ::common::Log::L_DEBUG, CLOGFMT(TimerWatchDog, "watchdog[%s] %d object(s) under watching"), _name.c_str(), watchSize); _slastWatchSize = watchSize; } _nextWakeup = timeOfNow + _idleInterval; for(ExpirationMap::iterator it = _expirations.begin(); it != _expirations.end(); it ++) { if (it->second <= timeOfNow) objIdentsToExec.push_back(it->first); else _nextWakeup = (_nextWakeup > it->second) ? it->second : _nextWakeup; } for (IdentCollection::iterator it2 = objIdentsToExec.begin(); it2 < objIdentsToExec.end(); it2++) _expirations.erase(*it2); } if(_bQuit) break; // should quit polling for (IdentCollection::iterator it = objIdentsToExec.begin(); !_bQuit && it < objIdentsToExec.end(); it++) { try { (new TimeoutCmd(*this, *it))->start(); } catch(...) {} } objIdentsToExec.clear (); if(_bQuit) break; // should quit polling long sleepTime = (long) (_nextWakeup - now()); if (sleepTime < MIN_YIELD) sleepTime = MIN_YIELD; _semWakeup.timedWait(sleepTime); /* #ifdef ZQ_OS_MSWIN ::WaitForSingleObject(_hWakeupEvent, sleepTime); #else struct timespec tsp; struct timeb tb; ftime(&tb); long mt = tb.millitm + sleepTime%1000; if(mt > 1000) { tb.time += 1; mt = mt%1000; } tsp.tv_sec = tb.time + sleepTime/1000; tsp.tv_nsec = mt * 1000000; sem_timedwait(&_hWakeupSem,&tsp); #endif */ } // while _log(ZQ::common::Log::L_WARNING, CLOGFMT(TimerWatchDog, "watchdog[%s] ends watching"), _name.c_str()); return 0; } void TimerWatchDog::quit() { { ZQ::common::MutexGuard gd(_lockExpirations); _expirations.clear(); _bQuit=true; } wakeup(); #ifdef ZQ_OS_MSWIN ::Sleep(1); #else usleep(1000); #endif } void TimerWatchDog::watch(const ::Ice::Identity& contentIdent, long timeout) { if (timeout <0) timeout = 0; ::Ice::Long newExp = now() + timeout; ZQ::common::MutexGuard gd(_lockExpirations); if (_bQuit) return; ExpirationMap::iterator it = _expirations.find(contentIdent); if (_expirations.end() == it) _expirations.insert(ExpirationMap::value_type(contentIdent, newExp)); else _expirations[contentIdent] = newExp; if (newExp < _nextWakeup) wakeup(); } void TimerWatchDog::final(int retcode, bool bCancelled) { _log(ZQ::common::Log::L_WARNING, CLOGFMT(TimerWatchDog, "watchdog[%s] stopped"), _name.c_str()); } } // namespace
56bcf9857ef1c51fa726167e33ff0297cbc9a8e7
7ae0efc9798b7c9fa720022ed5d763d6ab27cd13
/paddle/fluid/operators/trunc_op.h
0f788eae5249c57b92c7558451eca641a6840a41
[ "Apache-2.0" ]
permissive
ceci3/Paddle
e1d0b56a1bb1de9a0d26977868795f86e2c0580b
e4d475eabd83e7a6fa1e88c64c28747450f87d66
refs/heads/develop
2023-08-03T03:43:35.139011
2022-02-08T11:36:07
2022-02-08T11:36:07
171,274,803
0
3
Apache-2.0
2021-08-24T07:14:24
2019-02-18T11:49:16
C++
UTF-8
C++
false
false
1,697
h
trunc_op.h
/* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include <math.h> #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/framework/operator.h" namespace paddle { namespace operators { using Tensor = framework::Tensor; template <typename T> class TruncKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& context) const override { const Tensor* x = context.Input<Tensor>("X"); Tensor* out = context.Output<Tensor>("Out"); size_t numel = x->numel(); const T* x_data = x->data<T>(); T* out_data = out->mutable_data<T>(context.GetPlace()); for (size_t i = 0; i < numel; i++) { out_data[i] = trunc(x_data[i]); } } }; template <typename T> class TruncGradKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& context) const override { auto* dx = context.Output<Tensor>(framework::GradVarName("X")); T* dx_data = dx->mutable_data<T>(context.GetPlace()); int numel = dx->numel(); memset(dx_data, 0.0, numel * sizeof(T)); } }; } // namespace operators } // namespace paddle
d313582a7b8412315da4cbcce13224fb53d31c50
ca35ff66a5a66c07ca42e595d3be28455f77297e
/app/src/main/cpp/sensor/Accelerometer.cpp
d9db199169d87e0019b0977329c2731cd8742416
[ "MIT" ]
permissive
AnantaYudica/android_sensor_sample
b2c4ff882a3902f134ae5b6fff6ffdaf31386951
5cfebc36c8a358ffc3a58a04a97f6d4f3320c57f
refs/heads/master
2020-11-26T10:34:47.600983
2020-01-13T11:52:49
2020-01-13T11:52:49
229,044,856
0
0
null
null
null
null
UTF-8
C++
false
false
1,621
cpp
Accelerometer.cpp
// // Created by Ananta Yudica on 25/12/2019. // #include "Accelerometer.h" #include "../Log.h" #include <utility> namespace sensor { int Accelerometer::__CallbackDefault(const Sensor &, const sensor_event::Accelerometer &, const std::size_t &) { return 0; } Accelerometer::Accelerometer(ASensor const* ptr) : Sensor(ptr), m_callback(&Accelerometer::__CallbackDefault) { LOG_DEBUG("sensor::Accelerometer", "constructor(...)"); } Accelerometer::Accelerometer(ASensor const* ptr, CallbackType callback) : Sensor(ptr), m_callback((callback ? callback : &Accelerometer::__CallbackDefault)) { LOG_DEBUG("sensor::Accelerometer", "constructor(...)"); } Accelerometer::Accelerometer(const Accelerometer & cpy) : Sensor(cpy), m_callback(cpy.m_callback) { LOG_DEBUG("sensor::Accelerometer", "copy constructor(...)"); } Accelerometer::Accelerometer(Accelerometer && mov) : Sensor(std::move(mov)), m_callback(mov.m_callback) { LOG_DEBUG("sensor::Accelerometer", "move constructor(...)"); mov.m_callback = &Accelerometer::__CallbackDefault; } Accelerometer::~Accelerometer() { LOG_DEBUG("sensor::Accelerometer", "destructor(...)"); m_callback = &Accelerometer::__CallbackDefault; } void Accelerometer::SetCallback(CallbackType callback) { if (callback) m_callback = callback; } typename Accelerometer::CallbackType Accelerometer::GetCallback() { return m_callback; } int Accelerometer::Callback(sensor_event::Default events, std::size_t size) { return m_callback(*this, static_cast<sensor_event::Accelerometer>(events), size); } }
667e52d74d08ceacf784d841f568a1fda7633edb
ba5ae50fede99e3ede46fcff450e1faedf96a6bf
/module/route_bill_server/src/CDownLoadCheckBill.h
2c9b5c22392b6f8fad9ed4a704c062bc0f36db24
[]
no_license
yeqiaojun/server_bench
49e36dcd1567862cad4d33e945333c1c7ca56658
bda2ec938ae2d37a6b102667564ad8b6762f6f76
refs/heads/master
2021-05-13T14:51:18.222277
2017-09-05T02:17:31
2017-09-05T02:17:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,060
h
CDownLoadCheckBill.h
/* * CDownLoadCheckBill.h * * Created on: 2017年7月19日 * Author: hawrkchen * Desc: 对账单下载 */ #ifndef _CDOWNLOADCHECKBILL_H_ #define _CDOWNLOADCHECKBILL_H_ #include "IUrlProtocolTask.h" #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include "../Base/Comm/clib_mysql.h" #include "../Base/common/comm_tools.h" #include "CheckParameters.h" #include "CRouteBillBase.h" #include "util/tc_base64.h" #include "util/tc_file.h" class CDownLoadCheckBill : public IUrlProtocolTask { public: CDownLoadCheckBill(){} virtual ~CDownLoadCheckBill(){} INT32 Init() { m_bInited = true; return 0; } void LogProcess(); INT32 Execute( NameValueMap& mapInput, char** outbuf, int& outlen ); void Reset() { IUrlProtocolTask::Reset(); m_InParams.clear(); m_RetMap.clear(); m_ContentJsonMap.clear(); m_pBaseDB = Singleton<CSpeedPosConfig>::GetInstance()->GetBaseDB(); } protected: void FillReq( NameValueMap& mapInput); void CheckInput(); void BuildResp( CHAR** outbuf, INT32& outlen ); void CallPayGate2GetFactorID(); void CreateMsgBody(const string& factor_id); void CreateSwiftMsgBody(StringMap& paramMap,const string& factor_id); string CreateRSASign(const string& idStr, const string& plainText); string CreateMD5Sign(const string& factor_id, const string& plainText); void SendMsgToBank( const std::string& factor_id, std::string& szResBody); void SendMsgToSwift(const StringMap& paramMap,const std::string& factor_id, std::string& szResBody); void SetRetParam(); void GetSpeedPosBill(const std::string& factor_id); NameValueMap m_InParams; NameValueMap m_RetMap; JsonMap m_ContentJsonMap; CRouteBillBusiConf* pBillBusConfig; vector<string> factor_vec; string m_reqMsg; string m_sendUrl; CMySQL m_mysql; ostringstream sqlss; clib_mysql * m_pBaseDB = NULL; }; #endif /* _CDOWNLOADCHECKBILL_H_ */
7575f38dec04a235e433bb05e96e0d9e1141ee98
0f0d11858569041960ff2d9354154a6e7ecbbc1f
/Soukoban5/Soukoban5/State.h
50178ef9344962b00eabfdde887ed1473adcae62
[]
no_license
keserasera77/Soukonan5
8ca5640ead5fa95ddbd70557cd74af7bd7fb5ffe
a599acd5d182608367134f49db6a774807c1c2c9
refs/heads/master
2020-05-31T23:36:30.293319
2019-06-12T14:35:48
2019-06-12T14:35:48
190,542,385
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,011
h
State.h
#pragma once class Image; template<class T> class Array2D { public: Array2D() : mArray(0),mWidth(0),mHeight(0){} ~Array2D() { delete[] mArray; mArray = 0; } void setSize(int width, int height) { mWidth = width; mHeight = height; mArray = new T[width * height]; } T& operator()(int x, int y) { return mArray[y * mWidth + x]; } const T& operator()(int x, int y) const { return mArray[y * mWidth + x]; } private: T* mArray; int mWidth; int mHeight; }; class State { public: State(const char* stageData, int stageSize); ~State(); void update(unsigned frameTime); void drawStage() const; bool clearCheck() const; const char* mStageName; private: class Object; class Sequence; void setSize(const char* stage, int size); int mStageWidth; int mStageHeight; char* mStageData; Image* mImage; //画像データ int mPx, mPy; //プレイヤーの座標 Array2D<Object> mObjects; double mMoveCount; //動き始めてから何画素移動したか。 0 <= mMovingPlace < 32 };
3b4433c7005ff80f32da81908cbbacc2f4e204df
4174c9f65c32a5b117b2ec86abdfaa28ba5abc50
/include/ctkPublicFun/udplogsender.h
5c48373d64336fd42b67015db78125cc4623d2a2
[ "Apache-2.0" ]
permissive
icprog/DataTransfer
bc23200f7c732a0f3e7a0529afddec771c666b8e
a71e3625f8aa52f8e42d29d717a2d3bcbe723dc1
refs/heads/master
2020-04-04T16:49:00.418318
2018-08-01T09:52:07
2018-08-01T09:52:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
841
h
udplogsender.h
#ifndef udplogsender_h__ #define udplogsender_h__ #include <QUdpSocket> #include <QString> #include "macro.h" class DLL_EXPORT_CLASS_DECL CUdpLogSender { public: CUdpLogSender(); virtual ~CUdpLogSender(); void sendCollectMsg(const QString &taskName, const QString &taskId, const QString &taskContent, int level); void sendClearMsg(const QString &taskName, const QString &taskId, const QString &taskContent, int level); void sendBroadCastMsg(const QString &taskName, const QString &srcfile, const QString &dstfile); protected: void sendMsg(const QString &msgType, const QString &taskName, const QString &taskId, const QString &taskContent, int level); private: QUdpSocket m_oLogSocket; QUdpSocket m_oBroadCastSocket; int m_iUdpLogPort; int m_iUdpBroadCastPort; }; #endif // udplogsender_h__
3c038c79859ba1795b07d72edc2a7dc19da8b714
9757b1f64403138b68a1ae3a61e65a5a50114e5a
/2014-training/0516_hash/hash.cc
214d911bce6e2bd573f23372625edcb0d5df59a0
[]
no_license
ailyanlu/acm-code
481290d1b7773a537fe733a813ca5f9d925d8e93
0a5042c16eae3580ea443b5ab4109c8f317350af
refs/heads/master
2018-01-15T11:49:29.599393
2015-10-30T02:39:17
2015-10-30T02:39:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,274
cc
hash.cc
/// Hash (Rabin-Karp, RK),与二分配合使用。应用广泛。(综合白书和图灵白书学习) /// 题库:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=41757#overview const ull B = 100000007ULL; /// 哈希基数,1e8 + 7 const int mx_s_num = 105; /// 字符串个数 char s[mx_s_num][mx]; /// 注意,一定要用gets(s[i] + 1),从下标1开始读 ull ha[mx_s_num][mx], bp[mx] = {1ULL}; /// ha[i]从1开始,一直到ha[i][n] int len[mx_s_num]; /// len[i] = strlen(s[i] + 1); 一定要是s[i] + 1,否则n会是0 void init_hash(int s_num) /// 请在main()中完成len的求取。 { int i, j; For(i, s_num) Forr(j, 1, len[i] + 1) ha[i][j] = ha[i][j - 1] * B + s[i][j]; int n = Max(len, s_num); /// 调用#define的Max() Forr(i, 1, n + 1) bp[i] = bp[i - 1] * B; } ull get_hash(char *s) /// 直接返回整个字符串的hash { ull ha = 0ULL; for (int i = 0; s[i]; ++i) ha = ha * B + s[i]; return ha; } ull get_hash(int *a, int n) /// 返回整个int数组的hash值 { int i; ull ha = 0ULL; For(i, n) ha = ha * B + (ull)a[i]; return ha; } /// 注意pos一定不能是0!!!! inline ull get_hash(ull *Ha, int pos, int l) /// 返回Ha[pos...pos+l-1]的值,pos与l必须是正数 { return Ha[pos + l - 1] - Ha[pos - 1] * bp[l]; } inline ull merge_hash(ull ha1, ull ha2, int len2) /// 返回s1+s2拼接后的hash值 { return ha1 * bp[len2] + ha2; } bool contain(int ida, int idb) /// b是否为a的子串 ,ida和idb为字符串下标,若只有两个字符串,使用时传入参数(0, 1)、(1, 0)就行 { if (len[ida] < len[idb]) return false; ull hab = ha[idb][len[idb]]; for (int i = 1; i + len[idb] <= len[ida]; ++i) if (get_hash(ha[ida], i, len[idb]) == hab) return true; return false; } int overlap(int ida, int idb) /// 求a后缀与b前缀的最长公共子串,ida和idb为字符串下标,若只有两个字符串,使用时传入参数(0, 1)、(1, 0)就行 { int ans = 0, i; Forr(i, 1, min(len[ida], len[idb]) + 1) if (get_hash(ha[ida], len[ida] - i + 1, i) == get_hash(ha[idb], 1, i)) ans = i; // 可在if中加上 && strncmp(s[ida] + len[ida] - i + 1, s[idb] + 1, i) == 0(不过这就失去意义了,还不如双hash) return ans; }
c3587f98faab4d7bcb032de55e3d06fc785eba19
da6af0c82e470e6f33505253d01681a762f426b2
/draw_boxes.cpp
a1b5bdd7fabff5f8870ec44e4e7e17ebfa0d8f0d
[]
no_license
bo-wu/mobb
3e1f709a0c493fc3242c728367d30b5758812130
b35c3442590877fcd9ba9a09154f8038549e22e0
refs/heads/master
2021-01-10T14:15:19.927087
2015-06-13T08:14:41
2015-06-13T08:14:41
36,569,508
0
0
null
null
null
null
UTF-8
C++
false
false
1,964
cpp
draw_boxes.cpp
/* * ===================================================================================== * * Filename: draw_boxes.cpp Created: 05/29/2015 11:28:57 PM * * Description: draw segments boxes * * Author: Wu Bo (Robert), wubo.gfkd@gmail.com * Copyright: Copyright (c) 2015, Wu Bo * Organization: National University of Defense Technology * * ===================================================================================== */ #include "draw_boxes.h" DrawBoxes::DrawBoxes(QVector<Geom::MinOBB*> _mobb_vec) : mobb_vec(_mobb_vec) { } std::vector<PolygonSoup> DrawBoxes::fill_polygonsoup_vec(QColor color) { for(auto mobb : mobb_vec) { ps_vec.push_back(mobb.mMinBox.get_PolygonSoup(color)); } return ps_vec; } // copy from PolygonSoup BoxSoup::draw() { glEnable(GL_LIGHTING); glEnable(GL_BLEND); //drawTris(); draw_quads(); glDisable(GL_LIGHTING); // Draw borders as lines and points to force drawing something glLineWidth(2.0f); glColor4d(0,0,0,1); glBegin(GL_LINES); for (QVector<QVector3> poly : polys){ for(int i = 0; i < (int) poly.size(); i++){ glVertQt(poly[i]); glVertQt(poly[(i+1) % poly.size()]); } } glEnd(); glPointSize(3.0f); glBegin(GL_POINTS); for (QVector<QVector3> poly : polys){ for(int i = 0; i < (int) poly.size(); i++) glVertQt(poly[i]); } glEnd(); glEnable(GL_LIGHTING); } void BoxSoup::draw_quads(bool isColored = true){ glDisable(GL_LIGHTING); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBegin(GL_QUADS); for(int i = 0; i < (int) polys.size(); i++) { if(polys[i].size() != 4) continue; else{ if(isColored) glColorQt(polys_colors[i]); for(int p = 0; p < 4; p++) glVertQt(polys[i][p]); } } glEnd(); glEnable(GL_LIGHTING); }
718503cf303c55b169d64f4142c6938d3bae315a
2b831d8aa737a3a79d2a68f2688b7d58adc5add9
/lightsource.cpp
b0951f36e385f7b3498ffc8025030968a91b4cb4
[]
no_license
RomanPgr/comp_graphics
230e74481835801bc09fe3ebdbf95e5b53fd36b4
27d7a86de7972664eb42d525718d2112803368d5
refs/heads/master
2023-03-21T21:44:00.037320
2021-02-17T21:27:50
2021-02-17T21:27:50
313,333,611
0
0
null
null
null
null
UTF-8
C++
false
false
1,185
cpp
lightsource.cpp
#include "lightsource.h" LightSource::LightSource(const double& intensity, const int grid) : intensity{ intensity }, grid{ grid }{ } LightSource::LightSource(const LightSource& source) : LightSource{ source.intensity, source.grid }{ } const int LightSource::getGrid() const{ return grid; } LightSource::~LightSource() = default; LineSource::LineSource(const Vector3d& begin, const Vector3d& end, const double& intensity, const int grid) : LightSource{ intensity, grid }, begin{ begin }, end{ end }, intense_point{ intensity / grid }{ light_poses = new Vector3d[grid]; Vector3d step{ (end - begin) * (1.0 / grid) }; Vector3d t{ begin }; for (int i = 0; i < grid; i++) { light_poses[i] = t; t += step; } } LineSource::LineSource(const LineSource& source) : LineSource{source.begin, source.end, source.intensity, source.grid}{ } const Vector3d LineSource::get_part(const int i) const{ return light_poses[i]; } const double LineSource::get_intensity_point(const int n) const{ return intense_point; } LineSource* const LineSource::clone_source_by_reference() const{ return new LineSource{ *this }; } LineSource::~LineSource() { delete[] light_poses; }
810a74c6bbeb2f769d69bba2a4f2af3e90362920
2e359b413caee4746e931e01807c279eeea18dca
/1998. GCD Sort of an Array.cpp
4fcba386bf4d59970b5b4ca0b10cfb6c3d5fd4cf
[]
no_license
fsq/leetcode
3a8826a11df21f8675ad1df3632d74bbbd758b71
70ea4138caaa48cc99bb6e6436afa8bcce370db3
refs/heads/master
2023-09-01T20:30:51.433499
2023-08-31T03:12:30
2023-08-31T03:12:30
117,914,925
7
3
null
null
null
null
UTF-8
C++
false
false
1,582
cpp
1998. GCD Sort of an Array.cpp
class Solution { public: vector<int> p; unordered_map<int, int> fa; int find(int x) { if (fa[x]==0) return fa[x]=x; return fa[x]==x ? x : fa[x]=find(fa[x]); } bool gcdSort(vector<int>& a) { int mx = *max_element(a.begin(), a.end()); for (int i=2; i<=mx; ++i) { bool ok = true; for (int j=2; j*j<=i; ++j) if (i % j == 0) { ok = false; break; } if (ok) p.push_back(i); } vector<int> first_p; for (auto x : a) { vector<int> pf; for (auto y : p) { if (x % y == 0) { pf.push_back(y); while (x>1 && x%y==0) x/=y; } if (x == 1) break; } first_p.push_back(pf[0]); for (int i=1; i<pf.size(); ++i) { int f1 = find(pf[0]), f2 = find(pf[i]); fa[f2] = f1; } } unordered_map<int, vector<int>> gs; for (int i=0; i<a.size(); ++i) gs[find(first_p[i])].push_back(i); if (gs.size() == 1) return true; auto sorted = a; sort(sorted.begin(), sorted.end()); for (auto& g : gs) { unordered_set<int> st; for (auto i : g.second) st.insert(sorted[i]); for (auto i : g.second) if (!st.count(a[i])) return false; } return true; } };
394760ff7f632fb4505d800b44b0bf45d2ffe5f8
9d4637e96e41bd28cb7249e4133e922b151c0748
/cppDemos/CPPConsoleApplicationMultipleInheritaceDone/Rocket.h
c3fac79e0076782be0b5494ed119851e36926c84
[]
no_license
kstatz12/CPP2014
9104d10969393194e2ce24954b6fa255a71333d6
9b55c015e550fcbbfbf2dde6b0f0684fe687649c
refs/heads/master
2021-01-20T05:34:08.802586
2017-07-05T21:13:52
2017-07-05T21:13:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
194
h
Rocket.h
#pragma once class Rocket { protected: int m_FlyDistance, m_FuelAmount, m_Speed; bool m_isLanuched; public: Rocket(); ~Rocket(); void Launch(); void Fly(); int getFlyDistance(); };
edac2d731063882cfa4513e123f755ef09392ad8
ffaf68cb553fbe939b0b4f6a10c2ad15e567ec77
/897.cpp
00eeba0a066887a2fcf42d831d5264f0b06ef8ec
[]
no_license
guihunkun/LeetCode
dca45453b064972b55b3e2eaf5bc0132efb3f505
69dae0191e6fe4bd768b5b06c6b3cab28a26d4d9
refs/heads/master
2023-09-01T12:11:38.160330
2023-08-31T01:16:25
2023-08-31T01:16:25
156,633,787
1
0
null
null
null
null
UTF-8
C++
false
false
1,494
cpp
897.cpp
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ /* class Solution { public: TreeNode* increasingBST(TreeNode* root) { if(root == NULL) return root; vector<int> rec; inorder(root, rec); TreeNode* p = new TreeNode(-1); TreeNode* head = p; for(int i = 0; i < rec.size(); i++) { p->left=NULL; TreeNode* t = new TreeNode(rec[i]); p->right = t; p = t; } return head->right; } void inorder(TreeNode* node, vector<int>& rec) { if(node == NULL) return; inorder(node->left, rec); rec.push_back(node->val); inorder(node->right, rec); } }; */ class Solution { public: TreeNode* p; TreeNode* increasingBST(TreeNode* root) { if(root == NULL) return root; p = new TreeNode(-1); TreeNode* head = p; _increasingBST(root); return head->right; } void _increasingBST(TreeNode* root) { if(root->left != NULL) { _increasingBST(root->left); } p->left == NULL; TreeNode* t = new TreeNode(root->val); p->right = t; p = t; if(root->right != NULL) { _increasingBST(root->right); } } };
500cbc241a383962064f183f98a39a43d02cab90
fac6fab97a5554e243a9ca449fc1e7141e09b4da
/src/Window.h
b222532803cae3c42b5feb43a292e86c4b3026cd
[]
no_license
oktonion/PhWidgets-lib
4c49a3bef4edfcc93d87e0eb0d25c21652011995
5afbd913d213b8622b48b677fe7bce49b5ee3f6e
refs/heads/master
2022-07-27T00:41:34.404813
2021-06-09T06:05:26
2021-06-09T06:05:26
88,276,189
6
5
null
2017-05-01T21:24:51
2017-04-14T14:51:08
C++
UTF-8
C++
false
false
9,658
h
Window.h
#ifndef PHWIDGETS_WINDOW_H #define PHWIDGETS_WINDOW_H #include <photon/PtWindow.h> #include "./Disjoint.h" namespace PhWidgets { /*! @struct PhWidgets::Window @ingroup Widgets */ //! An Application window that's managed by the Photon window manager /*! The Window class provides a top-level container for your applications' widgets. It also provides a standard appearance for all windows. Windows are managed by the Photon window manager if it's present. @note A Window is the top-level Widget of the Application. If you try to use another class for the top-level Widget (aside from a Region), the behavior is undefined — you'll likely get a fatal error. ### Interacting with the Photon window manager ### Using resources, you can choose which elements of the window frame will be displayed. You can control which window management functions the window manager will perform, and whether they're invoked from the window menu or from one of the window controls. You can also have your application notified when the user has requested a window management function, regardless of whether or not the window manager will perform that function. ### Setting the Window's title ### You can specify the string displayed in the window's title bar by setting the Window::Title property. */ class Window: public Disjoint { public: //! Contains resource IDs for Window arguments. @ingroup Resources struct ThisArgs { //! Contains resource IDs for Window arguments of type **short**. struct ArgShort { //! Resource IDs for Window arguments of type **short**. /*! ### Aliases ### PhWidgets::Window::Arguments::eArgShort, PhWidgets::Window::ArgShort::eArgShort See Widget::resource for usage description. */ enum eArgShort { max_height = Pt_ARG_MAX_HEIGHT, //!< The maximum height of the Window. //!< If you set this resource to 0, the default value specified by the window manager is used. max_width = Pt_ARG_MAX_WIDTH, //!< The maximum width of the Window. //!< If you set this resource to 0, the default value specified by the window manager is used. min_height = Pt_ARG_MIN_HEIGHT, //!< The minimum width of the Window. //!< If you set this resource to 0, the default value specified by the window manager is used. min_width = Pt_ARG_MIN_WIDTH //!< The minimum width of the Window. //!< If you set this resource to 0, the default value specified by the window manager is used. }; }; //! Contains resource IDs for Window arguments of type `PgColor_t`. struct ArgColor { //! Resource IDs for Window arguments of type `PgColor_t`. /*! ### Aliases ### PhWidgets::Window::Arguments::eArgColor, PhWidgets::Window::ArgColor::eArgColor See Widget::resource for usage description. */ enum eArgColor { window_active_color = Pt_ARG_WINDOW_ACTIVE_COLOR, //!< The color of the window's frame when the Window has focus. //!< This overrides the color specified by the window manager. window_inactive_color = Pt_ARG_WINDOW_INACTIVE_COLOR, //!< The color of the window's frame when the Window doesn't have focus. //!< This overrides the color specified by the window manager. window_title_color = Pt_ARG_WINDOW_TITLE_COLOR //!< The color of the window's title (i.e. the text). //!< This overrides the color specified by the window manager. }; }; //! Contains resource IDs for Window arguments of type <b>char*</b>. struct ArgPChar { //! Resource IDs for Window arguments of type <b>char*</b>. /*! ### Aliases ### PhWidgets::Window::Arguments::eArgPChar, PhWidgets::Window::ArgPChar::eArgPChar See Widget::resource for usage description. */ enum eArgPChar { window_title = Pt_ARG_WINDOW_TITLE, //!< The string that the Window Manager displays in the title bar. window_help_root = Pt_ARG_WINDOW_HELP_ROOT //!< Defines the root topic path for the Window. }; }; }; //! Contains resource IDs for Window callbacks. struct ThisCallbacks { //! Contains resource IDs for Window callbacks of type `PtCallback_t`. struct Callback { //! Resource IDs for Window arguments of type `PtCallback_t`. /*! ### Aliases ### PhWidgets::Window::Callbacks::eCallback, PhWidgets::Window::Callback::eCallback See Widget::resource for usage description. */ enum eCallback { window = Pt_CB_WINDOW, //!< A list of `PtCallback_t` structures that define the callbacks that the widget invokes when it receives an event from the window manager. //!< Documentation in progress... window_closing = Pt_CB_WINDOW_CLOSING, //!< A list of `PtCallback_t` structures that define the callbacks that the widget invokes when the window is being closed. //!< It's invoked before the window's region is removed. //!< These callbacks are invoked when the window is about to unrealize for any reason //!< Documentation in progress... window_opening = Pt_CB_WINDOW_OPENING, //!< A list of `PtCallback_t` structures that define the callbacks that the widget invokes when the window is being opened. //!< If you want to resize the Window and want anchoring to be in effect, do it in this type of callback. //!< Documentation in progress... window_transport = Pt_CB_WINDOW_TRANSPORT //!< A list of `PtCallback_t` structures that define the callbacks that the widget invokes when the window is being transported through a Jump Gate. //!< Documentation in progress... }; }; }; //! Contains resource IDs for arguments of type **short**. @ingroup Resources struct ArgShort: public ThisArgs::ArgShort { }; //! Contains resource IDs for arguments of type `PgColor_t`. @ingroup Resources struct ArgColor: public ArgumentsEx<Disjoint::ArgColor>, public ThisArgs::ArgColor { typedef ThisArgs::ArgColor::eArgColor eArgColor; }; //! Contains resource IDs for arguments of type <b>char*<\b>. @ingroup Resources struct ArgPChar: public ArgumentsEx<Disjoint::ArgPChar>, public ThisArgs::ArgPChar { typedef ThisArgs::ArgPChar::eArgPChar eArgPChar; }; //! Contains resource IDs for callbacks of type `PtCallback_t`. @ingroup Resources struct Callback: public ArgumentsEx<ThisCallbacks::Callback>, public Disjoint::Callback { typedef ThisCallbacks::Callback::eCallback eCallback; }; //! Contains resource IDs for all Window arguments. @ingroup Resources struct Arguments: public ArgShort, public ArgColor, public ArgPChar, public Disjoint::Arguments { }; //! Contains resource IDs for all Window callbacks. @ingroup Resources struct Callbacks: public Callback, public Disjoint::Callbacks { }; protected: typedef ResourceFrom<Disjoint::WidgetResourcesSingleton>:: Define::Scalar<ThisArgs::ArgShort::eArgShort, short>:: Define::Color<ThisArgs::ArgColor::eArgColor>:: Define::String<ThisArgs::ArgPChar::eArgPChar>:: Define::Link<ThisCallbacks::Callback::eCallback, PtCallback_t*>:: resource_type WidgetResourcesSingleton; virtual void check(); //for properties: void setTitle(std::string); std::string getTitle() const; public: //! (constructor) /*! Constructs a Window by ID. @param[in] abn ID given by PhAB to widget (like 'ABN_WIDGET_NAME'). */ explicit Window(int abn); //! (constructor) /*! Constructs a Window by pointer to widget. @param[in] wdg pointer to Photon widget. */ explicit Window(PtWidget_t *wdg); //! (copy constructor) /*! Constructs a Widget by copy. @param[in] other another Widget to be used as source to initialize the elements of the container with. */ Window(const Window &other); //! Assigns value in Window /*! Replaces the contents of the Window. @param[in] other another Window to use as data source. */ Window &operator=(const Window &other); //! Resources of the Window /*! @see - Widget::resource */ WidgetResourcesSingleton resource; //! @name Properties //! Properties are used to simplify use of widget resources. //@{ //! Gets or sets a window's title. /*! ### Property Value ### > `std::string` A `std::string` that contains the window's title. */ property<std::string>::bind<Window, &Window::getTitle, &Window::setTitle> Title; //@} //! @name Events //@{ phwidgets_event<Window, Window::Callbacks::window_closing> Closing; phwidgets_event<Window, Window::Callbacks::window_opening> Opening; //@} }; } // namespace PhWidgets #endif // PHWIDGETS_WINDOW_H
7dc0bea9770104fd9a0527ff4260d7641e406e42
2077f528e564fe3dab12f12a0545b2abe82987fc
/conteudo/Introdução à Programação (Prática)/Exercicios/P02_Marcos_Rodrigues/Exercicio 05.cpp
98eca80fae703f1cd6da6ebf8e1c3c065fbe6bae
[]
no_license
marcosrodriigues/ufop
8af89d74705810a3f14f293d7463e1235f00622e
08c84b847a1fbd67616ca2f0c75c60f370a690dd
refs/heads/master
2023-01-09T16:23:42.116159
2020-01-22T05:26:25
2020-01-22T05:26:25
137,550,534
12
4
null
2023-01-07T13:59:20
2018-06-16T03:40:05
Python
UTF-8
C++
false
false
354
cpp
Exercicio 05.cpp
#include <iostream> using namespace std; int main() { double v1, v2; cout << "Digite dois valores: \n"; cin >> v1 >> v2; if ((v1 + v2) > 20) cout << "A soma dos valores digitados somando-os com 8 eh: " << (v1 + v2 + 8); else cout << "A soma dos valores digitados subtraindo-os com 5 eh: " << (v1 + v2 - 5); return 0; }
4438309b4d91240d0ff7ec7ef0edc93300a7348b
995c731cfbc26aaa733835eebaa6fcb0787f0081
/gazebo-5.3.0/gazebo/rendering/DynamicRenderable.hh
433f9b5067ea31e0c08b4119289f96c3081dbf07
[ "Apache-2.0" ]
permissive
JdeRobot/ThirdParty
62dd941a5164c28645973ef5db7322be72e7689e
e4172b83bd56e498c5013c304e06194226f21c63
refs/heads/master
2022-04-26T18:26:51.263442
2022-03-19T09:22:14
2022-03-19T09:22:14
33,551,987
7
9
null
2022-03-19T09:22:14
2015-04-07T15:36:00
C++
UTF-8
C++
false
false
4,747
hh
DynamicRenderable.hh
/* * Copyright (C) 2012-2015 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef _DYNAMICRENDERABLE_HH_ #define _DYNAMICRENDERABLE_HH_ #include <string> #include "gazebo/rendering/ogre_gazebo.h" #include "gazebo/rendering/RenderTypes.hh" #include "gazebo/util/system.hh" namespace gazebo { namespace rendering { /// \addtogroup gazebo_rendering /// \{ /// \class DynamicRenderable DynamicRenderable.hh rendering/rendering.hh /// \brief Abstract base class providing mechanisms for dynamically /// growing hardware buffers. class GAZEBO_VISIBLE DynamicRenderable : public Ogre::SimpleRenderable { /// \brief Constructor public: DynamicRenderable(); /// \brief Virtual destructor public: virtual ~DynamicRenderable(); /// \brief Initializes the dynamic renderable. /// \remarks This function should only be called once. It initializes the /// render operation, and calls the abstract function /// CreateVertexDeclaration(). /// \param[in] _opType The type of render operation to perform. /// \param[in] _useIndices Specifies whether to use indices to /// determine the vertices to use as input. public: void Init(RenderOpType _opType, bool _useIndices = false); /// \brief Set the render operation type /// \param[in] _opType The type of render operation to perform. public: void SetOperationType(RenderOpType _opType); /// \brief Get the render operation type /// \return The render operation type. public: RenderOpType GetOperationType() const; /// \brief Implementation of Ogre::SimpleRenderable /// \return The bounding radius public: virtual Ogre::Real getBoundingRadius() const; /// \brief Implementation of Ogre::SimpleRenderable /// \param[in] _cam Pointer to the Ogre camera that views the /// renderable. /// \return The squared depth in the Camera's view public: virtual Ogre::Real getSquaredViewDepth( const Ogre::Camera *_cam) const; /// \brief Get type of movable /// \return This returns "gazebo::DynamicRenderable" public: std::string GetMovableType() const; /// \brief Creates the vertex declaration. @remarks Override and set /// mRenderOp.vertexData->vertexDeclaration here. mRenderOp.vertexData /// will be created for you before this method is called. protected: virtual void CreateVertexDeclaration() = 0; /// \brief Prepares the hardware buffers for the requested vertex and /// index counts. /// \remarks /// This function must be called before locking the buffers in /// fillHardwareBuffers(). It guarantees that the hardware buffers /// are large enough to hold at least the requested number of /// vertices and indices (if using indices). The buffers are /// possibly reallocated to achieve this. /// \par The vertex and index count in the render operation are set to /// the values of vertexCount and indexCount respectively. /// \param[in] _vertexCount The number of vertices the buffer must hold. /// \param[in] _indexCount The number of indices the buffer must hold. /// This parameter is ignored if not using indices. protected: void PrepareHardwareBuffers(size_t _vertexCount, size_t _indexCount); /// \brief Fills the hardware vertex and index buffers with data. /// @remarks /// This function must call prepareHardwareBuffers() before locking the /// buffers to ensure the they are large enough for the data to be /// written. Afterwards the vertex and index buffers (if using indices) /// can be locked, and data can be written to them. protected: virtual void FillHardwareBuffers() = 0; /// \brief Maximum capacity of the currently allocated vertex buffer. protected: size_t vertexBufferCapacity; /// \brief Maximum capacity of the currently allocated index buffer. protected: size_t indexBufferCapacity; }; /// \} } } #endif
a8aa86df6ac71df7c773c46adcd6e8d4b7795ed6
064962e296843365f39b507436c592c823e9c429
/src/Chip8.cpp
95262a1f6b95aadcd12401f95b2a232a3d0a4569
[ "MIT" ]
permissive
dominikrys/chip8
0b3b92a1ea06fd3e7e1a6eb553708bc9255b5dad
96bfcbee9428c2cee4ce010c79f472c7183efe0b
refs/heads/master
2023-03-30T09:01:11.373717
2021-04-01T08:16:25
2021-04-01T08:16:25
230,137,314
1
0
null
null
null
null
UTF-8
C++
false
false
17,254
cpp
Chip8.cpp
#include "Chip8.h" #include <fstream> #include <cstddef> #include <cstring> #include <vector> #include <iostream> #include <limits> const unsigned int SPRITE_WIDTH = 8; const unsigned int ROM_START_ADDRESS = 0x200; const unsigned int FONT_SET_START_ADDRESS = 0x050; const unsigned int CHARACTER_SPRITE_WIDTH = 0x5; const std::array<uint8_t, FONT_SET_SIZE> FONT_SET{ 0xF0, 0x90, 0x90, 0x90, 0xF0, // 0 0x20, 0x60, 0x20, 0x20, 0x70, // 1 0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2 0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3 0x90, 0x90, 0xF0, 0x10, 0x10, // 4 0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5 0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6 0xF0, 0x10, 0x20, 0x40, 0x40, // 7 0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8 0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9 0xF0, 0x90, 0xF0, 0x90, 0x90, // A 0xE0, 0x90, 0xE0, 0x90, 0xE0, // B 0xF0, 0x80, 0x80, 0x80, 0xF0, // C 0xE0, 0x90, 0x90, 0x90, 0xE0, // D 0xF0, 0x80, 0xF0, 0x80, 0xF0, // E 0xF0, 0x80, 0xF0, 0x80, 0x80 // F }; // Timers should run at 60 hertz // See: https://github.com/AfBu/haxe-CHIP-8-emulator/wiki/(Super)CHIP-8-Secrets#speed-of-emulation const double TIMER_DELAY = (1.0 / 60.0) * 1000000000; Chip8::Chip8(Mode mode) : mode_{mode}, randEngine_(chrono::system_clock::now().time_since_epoch().count()), randByte_{std::uniform_int_distribution<uint8_t>(std::numeric_limits<uint8_t>::min(), std::numeric_limits<uint8_t>::max())}, timer_{TIMER_DELAY} { reset(); for (unsigned int i = 0; i < FONT_SET_SIZE; i++) { memory_[i + FONT_SET_START_ADDRESS] = FONT_SET[i]; } funcTable_[0x0] = &Chip8::decodeFuncTable0; funcTable_[0x1] = &Chip8::opcode1NNN; funcTable_[0x2] = &Chip8::opcode2NNN; funcTable_[0x3] = &Chip8::opcode3XNN; funcTable_[0x4] = &Chip8::opcode4XNN; funcTable_[0x5] = &Chip8::opcode5XY0; funcTable_[0x6] = &Chip8::opcode6XNN; funcTable_[0x7] = &Chip8::opcode7XNN; funcTable_[0x8] = &Chip8::decodeFuncTable8; funcTable_[0x9] = &Chip8::opcode9XY0; funcTable_[0xA] = &Chip8::opcodeANNN; funcTable_[0xB] = &Chip8::opcodeBNNN; funcTable_[0xC] = &Chip8::opcodeCXNN; funcTable_[0xD] = &Chip8::opcodeDXYN; funcTable_[0xE] = &Chip8::decodeFuncTableE; funcTable_[0xF] = &Chip8::decodeFuncTableF; funcTable0_[0x0] = &Chip8::opcode00E0; funcTable0_[0xE] = &Chip8::opcode00EE; funcTable8_[0x0] = &Chip8::opcode8XY0; funcTable8_[0x1] = &Chip8::opcode8XY1; funcTable8_[0x2] = &Chip8::opcode8XY2; funcTable8_[0x3] = &Chip8::opcode8XY3; funcTable8_[0x4] = &Chip8::opcode8XY4; funcTable8_[0x5] = &Chip8::opcode8XY5; funcTable8_[0x6] = &Chip8::opcode8XY6; funcTable8_[0x7] = &Chip8::opcode8XY7; funcTable8_[0xE] = &Chip8::opcode8XYE; funcTableE_[0x1] = &Chip8::opcodeEXA1; funcTableE_[0xE] = &Chip8::opcodeEX9E; funcTableF_[0x07] = &Chip8::opcodeFX07; funcTableF_[0x0A] = &Chip8::opcodeFX0A; funcTableF_[0x15] = &Chip8::opcodeFX15; funcTableF_[0x18] = &Chip8::opcodeFX18; funcTableF_[0x1E] = &Chip8::opcodeFX1E; funcTableF_[0x29] = &Chip8::opcodeFX29; funcTableF_[0x33] = &Chip8::opcodeFX33; funcTableF_[0x55] = &Chip8::opcodeFX55; funcTableF_[0x65] = &Chip8::opcodeFX65; } void Chip8::reset() { opcode_ = 0; index_ = 0; pc_ = 0x200; sp_ = 0; delayTimer_ = 0; soundTimer_ = 0; drawFlag_ = true; soundFlag_ = false; stack_.fill(0); registers_.fill(0); keys_.fill(0); std::fill(std::begin(memory_), std::begin(memory_) + FONT_SET_START_ADDRESS, 0); std::fill(std::begin(memory_) + FONT_SET_START_ADDRESS + FONT_SET_SIZE, std::end(memory_), 0); clearScreen(); } void Chip8::cycle() { // Fetch Opcode - each address is one byte, so shift it by 8 bits and merge with next opcode to get full one. opcode_ = memory_[pc_] << 8 | memory_[pc_ + 1]; // Decode and execute opcode ((*this).*(funcTable_[(opcode_ & 0xF000) >> 12]))(); // Update timers if (timer_.intervalElapsed()) { if (delayTimer_ > 0) { delayTimer_--; } if (soundTimer_ > 0) { if (soundTimer_ == 1) { soundFlag_ = true; } soundTimer_--; } } } void Chip8::decodeFuncTable0() { // Only the lower 4 bits of the low byte are different in 0x0 opcodes ((*this).*(funcTable0_[(opcode_ & 0x000F)]))(); } void Chip8::decodeFuncTable8() { // Only the lower 4 bits of the low byte are different in 0x8 opcodes ((*this).*(funcTable8_[(opcode_ & 0x000F)]))(); } void Chip8::decodeFuncTableE() { // Only the lower 4 bits of the low byte are different in 0xE opcodes ((*this).*(funcTableE_[(opcode_ & 0x000F)]))(); } void Chip8::decodeFuncTableF() { // Only the low byte is different in 0xF opcodes ((*this).*(funcTableF_[(opcode_ & 0x00FF)]))(); } void Chip8::opcodeUnknown() { std::cerr << &"Unknown opcode: 0x"[opcode_] << std::endl; } // 0x00E0: Clears the screen void Chip8::opcode00E0() { clearScreen(); drawFlag_ = true; pc_ += 2; } // 0x00EE: Returns from subroutine void Chip8::opcode00EE() { // Restore pc from stack sp_--; pc_ = stack_[sp_]; pc_ += 2; } // 1NNN: Jumps to address NNN void Chip8::opcode1NNN() { auto address = opcode_ & 0x0FFF; pc_ = address; } // 2NNN: Calls subroutine at address NNN void Chip8::opcode2NNN() { // Put current pc onto stack stack_[sp_] = pc_; sp_++; auto address = opcode_ & 0x0FFF; pc_ = address; } // 3XNN: Skips the next instruction if VX equals NN void Chip8::opcode3XNN() { auto x = (opcode_ & 0x0F00) >> 8; auto nn = opcode_ & 0x00FF; if (registers_[x] == nn) { pc_ += 4; } else { pc_ += 2; } } // 4XNN: Skips the next instruction if VX doesn't equal NN void Chip8::opcode4XNN() { auto x = (opcode_ & 0x0F00) >> 8; auto nn = opcode_ & 0x00FF; if (registers_[x] != nn) { pc_ += 4; } else { pc_ += 2; } } // 5XY0: Skips the next instruction if VX equals VY void Chip8::opcode5XY0() { auto x = (opcode_ & 0x0F00) >> 8; auto y = (opcode_ & 0x00F0) >> 4; if (registers_[x] == registers_[y]) { pc_ += 4; } else { pc_ += 2; } } // 6XNN: Sets VX to NN void Chip8::opcode6XNN() { auto x = (opcode_ & 0x0F00) >> 8; auto nn = opcode_ & 0x00FF; registers_[x] = nn; pc_ += 2; } // 7XNN: Adds NN to VX. (Carry flag is not changed) void Chip8::opcode7XNN() { auto x = (opcode_ & 0x0F00) >> 8; auto nn = opcode_ & 0x00FF; registers_[x] += nn; pc_ += 2; } // 8XY0: Sets VX to the value of VY void Chip8::opcode8XY0() { auto x = (opcode_ & 0x0F00) >> 8; auto y = (opcode_ & 0x00F0) >> 4; registers_[x] = registers_[y]; pc_ += 2; } // 8XY1: Sets VX to VX or VY. (Bitwise OR operation) void Chip8::opcode8XY1() { auto x = (opcode_ & 0x0F00) >> 8; auto y = (opcode_ & 0x00F0) >> 4; registers_[x] |= registers_[y]; pc_ += 2; } // 8XY2: Sets VX to VX and VY. (Bitwise AND operation) void Chip8::opcode8XY2() { auto x = (opcode_ & 0x0F00) >> 8; auto y = (opcode_ & 0x00F0) >> 4; registers_[x] &= registers_[y]; pc_ += 2; } // 8XY3: Sets VX to VX xor VY void Chip8::opcode8XY3() { auto x = (opcode_ & 0x0F00) >> 8; auto y = (opcode_ & 0x00F0) >> 4; registers_[x] ^= registers_[y]; pc_ += 2; } // 8XY4: Adds VY to VX. VF is set to 1 when there's a carry (VY + VX > 0xFFF), and to 0 when there isn't void Chip8::opcode8XY4() { auto x = (opcode_ & 0x0F00) >> 8; auto y = (opcode_ & 0x00F0) >> 4; if (registers_[x] + registers_[y] > 0xFFF) { registers_[0xF] = 1; // Carry } else { registers_[0xF] = 0; } registers_[x] += registers_[y]; pc_ += 2; } // 8XY5: VY is subtracted from VX. VF is set to 0 when there's a borrow, and 1 when there isn't void Chip8::opcode8XY5() { auto x = (opcode_ & 0x0F00) >> 8; auto y = (opcode_ & 0x00F0) >> 4; if (registers_[y] > registers_[x]) { registers_[0xF] = 0; // Borrow } else { registers_[0xF] = 1; } registers_[x] -= registers_[y]; pc_ += 2; } // 8XY6: Stores the least significant bit of VX in VF and then shifts VX to the right by 1 void Chip8::opcode8XY6() { auto x = (opcode_ & 0x0F00) >> 8; registers_[0xF] = registers_[x] & 0x1; if (mode_ == Mode::CHIP8) { // On CHIP8, shift VY and store the result in VX. // See: https://www.reddit.com/r/programming/comments/3ca4ry/writing_a_chip8_interpreteremulator_in_c14_10/csuepjm/ auto y = (opcode_ & 0x00F0) >> 4; registers_[x] = registers_[y] >> 1; } else { registers_[x] >>= 1; } pc_ += 2; } // 8XY7: Sets VX to VY minus VX. VF is set to 0 when there's a borrow, and 1 when there isn't void Chip8::opcode8XY7() { auto x = (opcode_ & 0x0F00) >> 8; auto y = (opcode_ & 0x00F0) >> 4; if (registers_[x] > registers_[(opcode_ & 0x00F0) >> 4]) { registers_[0xF] = 0; // Borrow } else { registers_[0xF] = 1; } registers_[x] = registers_[y] - registers_[x]; pc_ += 2; } // 8XYE: Stores the most significant bit of VX in VF and then shifts VX to the left by 1 void Chip8::opcode8XYE() { auto x = (opcode_ & 0x0F00) >> 8; registers_[0xF] = registers_[x] >> 7; if (mode_ == Mode::CHIP8) { // Check comment above for 8XY6 for an explanation why VY is shifted auto y = (opcode_ & 0x00F0) >> 4; registers_[x] = registers_[y] << 1; } else { registers_[x] <<= 1; } pc_ += 2; } // 9XY0: Skips the next instruction if VX doesn't equal VY void Chip8::opcode9XY0() { auto x = (opcode_ & 0x0F00) >> 8; auto y = (opcode_ & 0x00F0) >> 4; if (registers_[x] != registers_[y]) { pc_ += 4; } else { pc_ += 2; } } // ANNN: Sets I to the address NNN void Chip8::opcodeANNN() { auto address = opcode_ & 0x0FFF; index_ = address; pc_ += 2; } // BNNN: Jumps to the address NNN plus V0 void Chip8::opcodeBNNN() { auto address = opcode_ & 0x0FFF; pc_ = address + registers_[0]; pc_ += 2; } // CXNN: Sets VX to the result of a bitwise and operation on a random number (Typically: 0 to 255) and NN void Chip8::opcodeCXNN() { auto x = (opcode_ & 0x0F00) >> 8; auto nn = opcode_ & 0x00FF; registers_[x] = randByte_(randEngine_) & nn; pc_ += 2; } // DXYN: Draws a sprite at coordinate (VX, VY) that has a width of 8 pixels and a height of N pixels. Each row of 8 // pixels is read as bit-coded starting from memory location I; I value doesn’t change after the execution of this // instruction. As described above, VF is set to 1 if any screen pixels are flipped from set to unset when the sprite // is drawn, and to 0 if that doesn’t happen void Chip8::opcodeDXYN() { auto vx = registers_[(opcode_ & 0x0F00) >> 8]; auto vy = registers_[(opcode_ & 0x00F0) >> 4]; auto height = opcode_ & 0x000F; // Set VF to 0 (for collision detection) registers_[0xF] = 0; for (int yLine = 0; yLine < height; yLine++) { auto spritePixel = memory_[index_ + yLine]; for (unsigned int xLine = 0; xLine < SPRITE_WIDTH; xLine++) { // Check if sprite pixel is set to 1 (0x80 >> xLines iterates through the byte one bit at a time) if (spritePixel & (0x80 >> xLine)) { // Get pointer to pixel in video buffer. // "% (VIDEO_WIDTH * VIDEO_HEIGHT)" is necessary for wrapping the sprite around. auto *pixel = &video_[vx + xLine + ((vy + yLine) * VIDEO_WIDTH) % (VIDEO_WIDTH * VIDEO_HEIGHT)]; // Check collision if (*pixel == 0xFFFFFFFF) { // Set VF to 1 (for collision detection) registers_[0xF] = 1; } // Set value in video by XORing with 1 *pixel ^= 0xFFFFFFFF; } } } drawFlag_ = true; pc_ += 2; } // EX9E: Skips the next instruction if the key stored in VX is pressed void Chip8::opcodeEX9E() { auto x = (opcode_ & 0x0F00) >> 8; if (keys_[registers_[x]]) { pc_ += 4; } else { pc_ += 2; } } // EXA1: Skips the next instruction if the key stored in VX isn't pressed void Chip8::opcodeEXA1() { auto x = (opcode_ & 0x0F00) >> 8; if (keys_[registers_[x]] == 0) { pc_ += 4; } else { pc_ += 2; } } // FX07: Sets VX to the value of the delay timer void Chip8::opcodeFX07() { auto x = (opcode_ & 0x0F00) >> 8; registers_[x] = delayTimer_; pc_ += 2; } // FX0A: A key press is awaited, and then stored in VX void Chip8::opcodeFX0A() { auto x = (opcode_ & 0x0F00) >> 8; bool keyPress = false; for (unsigned int i = 0; i < KEY_COUNT; i++) { if (keys_[i]) { registers_[x] = i; keyPress = true; } } if (!keyPress) { // Don't increment PC, which will lead the emulator to come back to this instruction. return; } // Only increment pc if a key is pressed pc_ += 2; } // FX15: Sets the delay timer to VX void Chip8::opcodeFX15() { auto x = (opcode_ & 0x0F00) >> 8; delayTimer_ = registers_[x]; pc_ += 2; } // FX18: Sets the sound timer to VX void Chip8::opcodeFX18() { auto x = (opcode_ & 0x0F00) >> 8; soundTimer_ = registers_[x]; pc_ += 2; } // FX1E: Adds VX to I. VF is set to 1 when there is a range overflow (I+VX>0xFFF), and to 0 when there isn't void Chip8::opcodeFX1E() { auto x = (opcode_ & 0x0F00) >> 8; if (index_ + registers_[x] > 0xFFF) { registers_[0xF] = 1; } else { registers_[0xF] = 0; } index_ += registers_[x]; pc_ += 2; } // FX29: Sets I to the location of the sprite for the character in VX void Chip8::opcodeFX29() { auto x = (opcode_ & 0x0F00) >> 8; index_ = FONT_SET_START_ADDRESS + registers_[x] * CHARACTER_SPRITE_WIDTH; pc_ += 2; } // FX33: Stores the Binary-coded decimal representation of VX at the addresses I, I plus 1, and I plus 2 void Chip8::opcodeFX33() { auto vx = registers_[(opcode_ & 0x0F00) >> 8]; memory_[index_] = vx / 100; // Hundreds place memory_[index_ + 1] = (vx / 10) % 10; // Tens place memory_[index_ + 2] = (vx % 100) % 10; // Ones place pc_ += 2; } // FX55: Stores V0 to VX (including VX) in memory starting at address I. void Chip8::opcodeFX55() { auto x = (opcode_ & 0x0F00) >> 8; for (int i = 0; i <= x; i++) { memory_[index_ + i] = registers_[i]; if (mode_ == Mode::CHIP8 || mode_ == Mode::CHIP48) { // On CHIP-8 and CHIP-48, the index is incremented by the number of bytes loaded or stored. Most ROMs // however don't assume this behaviour, so by default this is ignored (like on the SCHIP). // See: https://en.wikipedia.org/wiki/CHIP-8#cite_note-increment-10 // And: https://www.reddit.com/r/programming/comments/3ca4ry/writing_a_chip8_interpreteremulator_in_c14_10/csuepjm/ // And: https://github.com/Chromatophore/HP48-Superchip/blob/master/investigations/quirk_i.md index_ += registers_[i]; } } pc_ += 2; } // FX65: Fills V0 to VX (including VX) with values from memory starting at address I. void Chip8::opcodeFX65() { for (unsigned int i = 0; i <= ((opcode_ & 0x0F00) >> 8); i++) { registers_[i] = memory_[index_ + i]; if (mode_ == Mode::CHIP8 || mode_ == Mode::CHIP48) { // Check comment above for FX55 for an explanation why this is incremented. index_ += memory_[index_ + i]; } } pc_ += 2; } void Chip8::loadRom(const std::string &filepath) { std::ifstream ifs(filepath, std::ios::binary | std::ios::ate); if (!ifs) { throw std::runtime_error("Can't open file: " + filepath + ". " + std::strerror(errno)); } auto end = ifs.tellg(); ifs.seekg(0, std::ios::beg); auto size = std::size_t(end - ifs.tellg()); if (size == 0) { throw std::runtime_error("Specified ROM has a size of 0."); } else if (size > MEMORY_SIZE - ROM_START_ADDRESS) { throw std::runtime_error("ROM too big for memory"); } std::vector<char> buffer((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>()); for (long long unsigned int i = 0; i < size; i++) { memory_[i + ROM_START_ADDRESS] = buffer[i]; } ifs.close(); } bool Chip8::drawFlag() const { return drawFlag_; } void Chip8::disableDrawFlag() { drawFlag_ = false; } void Chip8::clearScreen() { video_.fill(0); } const std::array<uint32_t, VIDEO_WIDTH * VIDEO_HEIGHT> &Chip8::video() const { return video_; } std::array<uint8_t, KEY_COUNT> &Chip8::keys() { return keys_; } bool Chip8::soundFlag() const { return soundFlag_; } void Chip8::disableSoundFlag() { soundFlag_ = false; }
631cecc18119a66295572c3ef99db03a7a84400f
88b198f517df355676fc6d6690fcf12c2df3f4c6
/pr-06/task_4/Source.cpp
2d5a2048b4a1e0b1fdd48e6763ab935dab2b76ab
[]
no_license
Proger125/cplusplus
d7b474b4e7e438d83824fbe706ae32941290fa19
9cd1a865ddb3f81dc613390438a334c9e7f1c7d5
refs/heads/master
2023-08-18T17:23:12.481277
2021-10-13T08:10:31
2021-10-13T08:10:31
214,238,632
0
0
null
null
null
null
UTF-8
C++
false
false
516
cpp
Source.cpp
#include "Function.h" int main() { vector<Date> v; InputVector(v); for (int i = 0; i < v.size(); i++) { cout << "The next day of " << v[i].day << " " << v[i].month << " " << v[i].year << endl; cout << v[i].NextDay().day << " " << v[i].NextDay().month << " " << v[i].NextDay().year << endl; } for (int i = 0; i < v.size() - 1; i++) { cout << "The duration between two dates = " << v[i].Duration(v[i + 1]) << endl; } system("pause"); return 0; }
d17079a2db6db6b484377aed770dc4da46260c92
86cb1327bd3cae3dd334ea8d7cb66b9b57b95f40
/OPENMP_IMPLEMENTATION/blur_openmp.cpp
d9e4cf57cbeaa1bca49a699aff9d23808f055369
[]
no_license
lfvalderrama/Blur-Effect
e4de4856b166723ad1e4e43ea5f94d91886081f7
5fbda55c36bfc93996f6246339579de9df640591
refs/heads/master
2021-08-19T23:37:20.940646
2017-11-27T17:33:46
2017-11-27T17:33:46
112,221,264
0
0
null
null
null
null
UTF-8
C++
false
false
2,019
cpp
blur_openmp.cpp
#include "opencv2/highgui/highgui.hpp" #include <omp.h> #include <iostream> using namespace cv; using namespace std; Mat img; Mat new_img; int radio, NUM_THREADS; //Funcion main int main( int argc, char** argv ) { NUM_THREADS = atoi(argv[3]); int i, j; //Abrir las imagenes y guardarlas en memoria img = imread(argv[1], CV_LOAD_IMAGE_UNCHANGED); new_img = imread(argv[1], CV_LOAD_IMAGE_UNCHANGED); if (img.empty()){ cout << "Error : Image cannot be loaded..!!" << endl; return -1; } radio=atoi(argv[2]); int width=img.cols; int height=img.rows; #pragma omp parallel for num_threads(NUM_THREADS) shared (new_img,img) collapse(2) for (i=0; i<height; i++){ for (j=0; j<width; j++){ int aux_r=0; //2 int aux_g=0; //1 int aux_b=0; //0 int aux_div=1; for (int a=1; a<=radio; a++){ if(!(i-a<0)){ aux_r+= img.at<cv::Vec3b>(i-a,j)[2]; aux_g+= img.at<cv::Vec3b>(i-a,j)[1]; aux_b+= img.at<cv::Vec3b>(i-a,j)[0]; aux_div++; } if(i+a<height){ aux_r+= img.at<cv::Vec3b>(i+a,j)[2]; aux_g+= img.at<cv::Vec3b>(i+a,j)[1]; aux_b+= img.at<cv::Vec3b>(i+a,j)[0]; aux_div++; } if(!(j-a<0)){ aux_r+= img.at<cv::Vec3b>(i,j-a)[2]; aux_g+= img.at<cv::Vec3b>(i,j-a)[1]; aux_b+= img.at<cv::Vec3b>(i,j-a)[0]; aux_div++; } if(j+a<width){ aux_r+= img.at<cv::Vec3b>(i,j+a)[2]; aux_g+= img.at<cv::Vec3b>(i,j+a)[1]; aux_b+= img.at<cv::Vec3b>(i,j+a)[0]; aux_div++; } } new_img.at<cv::Vec3b>(i,j)[2]=(img.at<cv::Vec3b>(i,j)[2]+aux_r)/(aux_div); new_img.at<cv::Vec3b>(i,j)[1]=(img.at<cv::Vec3b>(i,j)[1]+aux_g)/(aux_div); new_img.at<cv::Vec3b>(i,j)[0]=(img.at<cv::Vec3b>(i,j)[0]+aux_b)/(aux_div); } } string name = "MPmodificada_"; name.append("kernel_"); name.append(argv[2]); name.append(argv[1]); //Guardar la imagen imwrite(name, new_img); return 0; }
b47fe3a0c7816867081def6a8cc4bb28acfc5892
1b73515fb49ac64e0afa5ba7baf03170451d0e46
/GameEngine/CoreEngine/CoreEngine/src/Terrain2DCollider.cpp
e1b60c94bacad20dba24dfba53670d310724320a
[ "Apache-2.0" ]
permissive
suddenly-games/SuddenlyGames
2af48c0f31f61bad22e7c95124c0f91443ff2d54
e2ff1c2771d4ca54824650e4f1a33a527536ca61
refs/heads/develop
2023-05-02T03:14:21.384819
2021-05-12T07:10:29
2021-05-12T07:10:29
330,379,384
1
0
Apache-2.0
2021-03-21T03:12:52
2021-01-17T11:52:25
C
UTF-8
C++
false
false
659
cpp
Terrain2DCollider.cpp
#include "Terrain2DCollider.h" #include "ColliderData.h" namespace Engine { void Terrain2DCollider::PairQuery(const AabbTree::Node* head, const TerrainPairCallback& collisionCallback, const ColliderCallback& lookupCallback) { Physics::ColliderData collider; } void Terrain2DCollider::Visit(const AabbTree::Node* node, const ChunkTree* chunks, Physics::ColliderData& collider) { } void Terrain2DCollider::Visit(const AabbTree::Node* node, const ChunkColumn* chunks, Physics::ColliderData& collider) { } void Terrain2DCollider::Visit(const AabbTree::Node* node, const std::shared_ptr<Chunk>& chunk, Physics::ColliderData& collider) { } }
d3c5798280df0a4b31d3d86acf744dd84fc8ba67
41f743dc6c6b579416da7b4034030945b0fc7f31
/pipeline-simulation/src/instruction/AddInstruction.h
42cbe1faab539121c772010a27ebf902f0f69a6e
[]
no_license
rueian/pipeline-sim
fc2e709a57c00e6e0acbf2bc7fb3e5a22906532b
9c623d3f7dd8e4b6a91806786c676e134eaa7de3
refs/heads/master
2020-05-30T09:13:00.118463
2014-06-12T07:26:29
2014-06-12T07:26:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
383
h
AddInstruction.h
// // Created by RueianOneecom on 2014/6/4. // Copyright (c) 2014 ___FULLUSERNAME___. All rights reserved. // #include "RTypeInstruction.h" #ifndef __AddInstruction_H_ #define __AddInstruction_H_ class AddInstruction : public RTypeInstruction { public: AddInstruction(string); protected: virtual int ALUResult(int data1, int data2); }; #endif //__AddInstruction_H_
7dbe93baa0fed24515ecce9de2a12a5f004dd6ee
f6ab96101246c8764dc16073cbea72a188a0dc1a
/volume006/686 - Goldbach's Conjecture (II).cpp
a9fafb047aa3ec918bf6a89db26f5275029a2166
[]
no_license
nealwu/UVa
c87ddc8a0bf07a9bd9cadbf88b7389790bc321cb
10ddd83a00271b0c9c259506aa17d03075850f60
refs/heads/master
2020-09-07T18:52:19.352699
2019-05-01T09:41:55
2019-05-01T09:41:55
220,883,015
3
2
null
2019-11-11T02:14:54
2019-11-11T02:14:54
null
UTF-8
C++
false
false
479
cpp
686 - Goldbach's Conjecture (II).cpp
#include <stdio.h> #include <stdlib.h> int mark[32768], Prime[32768], Pt = 0; void sieve() { int i, j; for(i = 2; i < 32768; i++) { if(mark[i] == 0) { Prime[Pt++] = i; for(j = 2; i*j < 32768; j++) mark[i*j] = 1; } } } int main() { sieve(); int n; while(scanf("%d", &n) == 1 && n) { int i, x, y, ans = 0; for(i = 0; Prime[i] < n; i++) { x = Prime[i], y = n-x; if(x > y) break; if(mark[y] == 0) ans++; } printf("%d\n", ans); } return 0; }
a367cebf47499253686ed1a0897fad98219a8d0a
fc35f8872f8960e90c765231022a410b528d09c6
/trunk/other/tiago/Torre atirando/botao.h
156706d42f4bfd6f8c847fdeebe8b9aa6a5bf25e
[]
no_license
BGCX261/z-one-svn-to-git
576b2b958a783238d11159ca175a54d79c988a64
bc8bfbcb0267e27ce637844f762032ae6f49a9ee
refs/heads/master
2021-01-25T09:59:22.856790
2015-08-25T15:46:24
2015-08-25T15:46:24
42,317,186
0
0
null
null
null
null
UTF-8
C++
false
false
415
h
botao.h
#ifndef BOTAO_H #define BOTAO_H #include <SDL/SDL.h> #include "util.h" #define REFRESH 0 #define KATANA 1 #define NUNCHAKU 2 #define MARIKI 3 #define SHURIKEN 4 #define KUNAI 5 #define BOMBA 6 class botao{ SDL_Surface* image; SDL_Rect box; int type; public: botao(int tipo, int x, int y); ~botao(); void onClick(); void show(); void handleEvents(SDL_Event* event); bool clicked(int x, int y); }; #endif
e77f6a0bf95b7d5d710542947301d9b6a6621d77
c197de55184d5d7ff95e9d06c5bb6a4766c14c9b
/mainwindow.h
53f4f1a951cab27273b8590fbc46b2c438466218
[]
no_license
yuntux/lo21-npi
0f25df008198714569b09f88bffd4a6ef829bb66
975ea3d69f528c78a1e203ee7c5e7ec8df11c776
refs/heads/master
2016-09-05T09:20:34.548990
2012-06-17T12:43:58
2012-06-17T12:43:58
32,145,443
0
0
null
null
null
null
UTF-8
C++
false
false
2,547
h
mainwindow.h
/** * \file constante.h * \brief Calculatrice en polonais inversé. Classe de la GUI QT-MainWindow * \author Aurélien DUMAINE * \author Simon LANCELOT * \version 0.1 * \date juin 2012 * * Licence : GNU/GPL version 3 (http://www.gnu.org/copyleft/gpl.html) * Dépot Git : http://code.google.com/p/lo21-npi/ * */ #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QStack> #include "pile.h" #define PI 3.14159265 enum MesureAngle { degre, radian}; namespace Ui { class MainWindow; } //Fonction outil => hors classe Constante* stringToConstante(QString s, bool essayer_construire_complexe); class MainWindow : public QMainWindow { Q_OBJECT protected: void closeEvent(QCloseEvent *event); private: void loadFromFile(); public: explicit MainWindow(QWidget *parent = 0); bool dernier_element_expression(QString chaine); ~MainWindow(); void traiter_bloc_expression(QString s); void traiter_bloc_calcul(QString s); public slots: void POWClicked(); void SINClicked(); void COSClicked(); void TANClicked(); void SINHClicked(); void COSHClicked(); void TANHClicked(); void MODClicked(); void SIGNClicked(); void LNClicked(); void LOGClicked(); void INVClicked(); void SQRClicked(); void SQRTClicked(); void CUBEClicked(); void QUOTEClicked(); void CClicked(); void CEClicked(); void DOLLARClicked(); void num0Clicked(); void num1Clicked(); void num2Clicked(); void num3Clicked(); void num4Clicked(); void num5Clicked(); void num6Clicked(); void num7Clicked(); void num8Clicked(); void num9Clicked(); void PIBOUTONClicked(); void POINTClicked(); void ESPACEClicked(); void FACTORIELClicked(); void ADDITIONNERClicked(); void SOUSTRAIREClicked(); void MULTIPLIERClicked(); void DIVISERClicked(); void _clavierBasicStateChange(int); void _clavierAvanceStateChange(int); void _modComplexeONClicked(bool); void _modComplexeOFFClicked(bool); void _modRadiansToggled(bool); void _modDegresToggled(bool); void _modReel(bool); void _modRationnel(bool); void _modEntier(bool); void retablirClicked(); void annulerClicked(); void ENTERClicked(); void EVALClicked(); void vider_pileClicked(); void supprimer_tete_pileClicked(); void dupliquer_tete_pileClicked(); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
87b89534f5b3a9c3f23fec0988ba891f65005fe1
d2c0a0d55436cdb194fd0bb52af0ca32d8e56af8
/Shapes.cpp
83584ac7c191cc272d564a4a6b941d9a7e0c7ec9
[]
no_license
Abigail-Verhelle/Object-Oriented-Programming
1001b0ca38386f234c1bdc999f480c4596a9726d
c61dc117cc31f956d5008a96baa3ab58ae8cfdc8
refs/heads/master
2020-12-24T00:07:57.776292
2020-01-30T22:40:44
2020-01-30T22:40:44
237,319,118
0
0
null
null
null
null
UTF-8
C++
false
false
7,271
cpp
Shapes.cpp
#define USE_MATH_DEFINES #include <iostream> #include <sstream> #include <cmath> #include "Shapes.h" using namespace std; string olor[9] = { "BLACK", "RED", "GREEN", "YELLOW", "BLUE", "MAGENTA", "CYAN", "WHITE","INVALID" }; //Box //Box area double Box::area() const { return (r-l)*(t-b); } //box Perimeter double Box::perimeter() const { return ((r-l)+(t-b))*2; } //moving Box void Box::move(double X, double Y) { l += X; t += Y; r += X; b += Y; } //print void Box::render(ostream &os) const { os << "Box(" << olor[color()] << "," << l << "," << t << "," << r << "," << b << ")"; } //inside bool Box::inside (double tx, double ty) const { return(ty < top() && tx < right() && ty > bottom() && tx > left()); } //Circle //Circle Area double Circle::area() const { return r*r*M_PI; } //circle perimeter double Circle::perimeter() const { return (r*2)*M_PI; } //moving the circle void Circle::move(double X, double Y) { x += X; y += Y; } //print void Circle::render(ostream &os) const { os << "Circle(" << olor[color()] << "," << x << "," << y << "," << r << ")"; } bool Circle::inside (double tx, double ty) const { if( radius() > sqrt(pow((centerX()-tx),2)+pow((centerY()-ty),2))) { return true; } else { return false; } } //Triangle //Triangle area double Triangle::area() const { double uno = sqrt(pow((xc1-xc2),2)+pow((yc1-yc2),2)); double dos = sqrt(pow((xc2-xc3),2)+pow((yc2-yc3),2)); double tres = sqrt(pow((xc3-xc1),2)+pow((yc3-yc1),2)); double peri = perimeter()/2; return sqrt(peri*(peri-uno)*(peri-dos)*(peri-tres)); } // triangle perimeter double Triangle::perimeter() const { double uno = sqrt(pow((xc1-xc2),2)+pow((yc1-yc2),2)); double dos = sqrt(pow((xc2-xc3),2)+pow((yc2-yc3),2)); double tres = sqrt(pow((xc3-xc1),2)+pow((yc3-yc1),2)); return uno+dos+tres; } //moving triangle void Triangle::move(double X, double Y) { xc1 += X; xc2 += X; xc3 += X; yc1 += Y; yc2 += Y; yc3 += Y; } //print void Triangle::render(ostream &os) const { os << "Triangle(" << olor[color()] << "," << xc1 << "," << yc1 << "," << xc2 << "," << yc2 << "," << xc3 << "," << yc3 << ")"; } //triangle inside bool Triangle::inside (double tx, double ty) const { Triangle illuminati1(RED, tx, ty, xc1, yc1, xc2, yc2); Triangle illuminati2(RED, tx, ty, xc2, yc2, xc3, yc3); Triangle illuminati3(RED, tx, ty, xc3, yc3, xc1, yc1); return ((illuminati1.area()+illuminati2.area()+illuminati3.area()) == area()); } //Polygon double Polygon::points() const { return size; } //Polygon area double Polygon::area() const { double aera = 0; for (int k=0; k<size; k++) { aera += ((vertexX(k)*vertexY((k+1)%size))-(vertexX((k+1)%size)*vertexY(k))); } return aera/2; } // polygon perimeter double Polygon::perimeter() const { double peri = 0; for (int i=0; i<size; i++) { peri += sqrt(pow((vertexX(i)-vertexX((i+1)%size)),2)+pow((vertexY(i)-vertexY((i+1)%size)),2)); } return peri; } //move the polygon void Polygon::move(double X, double Y) { for (int j=0; j<size; j++) { cornersX[j] += X; cornersY[j] += Y; } } //print void Polygon::render(ostream &os) const { os << "Polygon(" << olor[color()] << "," << size; for (int k=0; k<size; k++) { os << "," << cornersX[k]; os << "," << cornersY[k]; } os << ")"; } bool Polygon::inside (double tx, double ty) const { int j = size -1; bool c = false; for (int i = 0; i < size; i++) { if ( ((cornersY[i]>ty) != (cornersY[j]>ty)) && (tx < (cornersX[j]-cornersX[i]) * (ty-cornersY[i]) / (cornersY[j]-cornersY[i]) + cornersX[i]) ) { c = !c; } j = i; } return c; } // line void Line::render(std::ostream &os) const { os << "Line(" << olor[color()] << "," << EX1 << "," << EY1 << "," << EX2 << "," << EY2 << ")"; } //rounded box area double RoundBox::area()const { double p = Box::area()-(ra*ra*4); return p + (ra*ra*M_PI); } //RoundBox Perimeter double RoundBox::perimeter()const { double a = Box::perimeter()-((ra+ra)*4); return a + ((ra*2)*M_PI); } // Round Box render void RoundBox::render(std :: ostream & os) const { os << "RoundBox(" << olor[color()] << "," << left() << "," << top() << "," << right() << "," << bottom() << "," << ra << ")"; } // Rounded Box inside bool RoundBox::inside (double tx, double ty) const { Circle I (BLACK,left()-ra,top()-ra,ra); //🐞 Circle Hate (RED,right()- ra, top()-ra,ra); Circle Programming (RED,right()-ra,bottom()-ra,ra); Circle Forever (RED,left()-ra,bottom()-ra,ra); Box stupid (RED,left(),top()-ra,right(),bottom()-ra); Box rectangle (RED,left()-ra,top(),right()-ra,bottom()); return (I.inside(tx,ty) || Hate.inside(tx,ty) || Programming.inside(tx,ty) || Forever.inside(tx,ty) || stupid.inside(tx,ty) || rectangle.inside(tx,ty)); } //color at point Color Shape::colorAtPoint(Shape** ape,int length,int point1, int point2) { for (int j = 0; j<length;j++) { if(ape[j]-> inside(point1,point2)) { return ape[j]->color(); } } return INVALID; } // group //Group Shape Shape* Group::shape(int A) { return Pointer[A]; } // Group area double Group::area() const { double totalarea = 0; for(int b = 0; b < size; b++) { totalarea += Pointer[b]->area(); } return totalarea; } // Group perimeter double Group::perimeter() const { double totalperimeter = 0; for(int i = 0; i < size; i++) { totalperimeter += Pointer[i]->perimeter(); } return totalperimeter; } // Group move void Group::move(double dx, double dy) { for(int g = 0;g < size;g++) { Pointer[g]->move(dx,dy); } } // Group render void Group::render(std :: ostream & os) const { os << "Group(" << olor[Shape::color()] << "," << size; for (int a = 0; a<size; a++) { os << ","; Pointer[a]->render(os); } os << ")"; } // Gourp inside bool Group::inside(double tx, double ty) const { for (int i = 0; i < size; i++) { if(Pointer[i]->inside(tx,ty)) { return true; } } return false; } //Group Shape void Group::shapes(int length,Shape **PointerS) { for(int l = 0;l < size; l++) { delete Pointer[l]; } Pointer = PointerS; size = length; } //int main() //{ // Shape * list[2]; // list[0] = new Box(GREEN, 0, 1, 1, 0); // list[1] = new Circle(YELLOW, 2, 2, 2); // Group g(BLUE, 2, list); // // cout << "Group area: " << g.area() << "\n"; // cout << "Group perimeter: " << g.perimeter() << "\n"; // // g.move(1,1); // g.render(cout); cout << "\n"; // g.color(RED); // g.render(cout); cout << "\n"; // // cout << "Count: " << g.shapes() << "\n"; // g.shape(1)->render(cout); cout << "\n"; // // Shape * list2[3]; // list2[0] = new Circle(WHITE,5,5,1); // list2[1] = new Box(GREEN,7,1,9,-10); // list2[2] = new RoundBox(BLACK,5,5,8.5,4.5,0.1); // g.shapes(3,list2); // g.render(cout); cout << "\n"; //}
322faaf13a64c058e6f1b2cbdfccbf9fd6357f8f
da1c11dad536f7b19b3c057f0045da167417b97c
/include/geometry.hpp
50678d61736aa862ef491e93281441dd7a79e7e7
[ "MIT" ]
permissive
Ikaguia/idj-pinguim
44895c1f158db3c153a10d7f65af6f6fc2b26046
fd07be94b440057ab2ec9bf80931bc3f2b588cd3
refs/heads/master
2021-01-20T02:11:16.787616
2017-04-03T14:44:02
2017-04-03T14:44:02
85,530,993
1
0
null
null
null
null
UTF-8
C++
false
false
1,886
hpp
geometry.hpp
#ifndef GEOMETRYHPP #define GEOMETRYHPP #include <cmath> #include <common.hpp> #define PI 3.141592653589793 #define RAD(x) (((x)*PI)/180.0) #define DEGREES(x) (((x)*180.0)/PI) class Vec2{ public: float x; float y; Vec2(); Vec2(const float &a,const float &b); Vec2(const Vec2 &b); void operator= (const Vec2& b); Vec2 operator+ (const Vec2& b)const; void operator+=(const Vec2& b); Vec2 operator- (const Vec2& b)const; void operator-=(const Vec2& b); Vec2 operator* (const float& r)const; void operator*=(const float& r); Vec2 operator/ (const float& r)const; void operator/=(const float& r); float len() const;//magnitude do vetor float angle() const;//angulo entre this e o eixo x float dist(const Vec2& b) const;//distancia entre this e b float angle(const Vec2& b) const;//inclinacao da reta definida por this e b Vec2 unit() const;//vetor unitario Vec2 rotate(float a);//rotaciona o vetor em a graus }; class Rect{ public: float x; float y; float w; float h; Rect(); Rect(const float &a,const float &b,const float &c,const float &d); Rect(const Rect &b); void operator= (const Rect& b); Rect operator+ (const Vec2& b)const; void operator+=(const Vec2& b); Rect operator- (const Vec2& b)const; void operator-=(const Vec2& b); Vec2 center() const;//retorna o centro do retangulo float dist(const Rect& b) const;//retorna a distancia entre os centros dos retangulos bool contains(const float &i,const float &j) const;//retorna se o ponto pertence ao retangulo bool contains(const Vec2& b) const;//retorna se o ponto pertence ao retangulo }; class Circle{ public: float x; float y; float r; Circle(float x=0,float y=0,float r=1); bool contains(const Vec2 &p)const;//retorna se o ponto pertence ào circulo bool contains(const float &x,const float &y)const;//retorna se o ponto pertence ào circulo }; #endif//GEOMETRYHPP
17210f9272b38a85a9f2fee2e6dcc095ea197039
65e5be11519f3696463f748abbc9f5e09192042a
/src/geopos.cpp
0eb54d537f7846dcfc0533b2a3b277a0388a012f
[]
no_license
kimmoli/position-cli
fa585c678d0e7f1e958e4563ced844c311de8505
cb695d636adc4f3c2f66bf4d69353842fc2ca67b
refs/heads/master
2021-01-18T14:14:48.491949
2015-01-18T20:28:32
2015-01-18T20:28:32
29,437,677
0
1
null
null
null
null
UTF-8
C++
false
false
1,846
cpp
geopos.cpp
#include "geopos.h" Geopos::Geopos(bool repeat, bool verbose, QString selectedSource, QObject *parent) : QObject(parent) { m_repeat = repeat; m_verbose = verbose; QGeoPositionInfoSource *source; if (selectedSource.isEmpty()) source = QGeoPositionInfoSource::createDefaultSource(this); else source = QGeoPositionInfoSource::createSource(selectedSource, this); if (source) { connect(source, SIGNAL(positionUpdated(QGeoPositionInfo)), this, SLOT(positionUpdated(QGeoPositionInfo))); source->setUpdateInterval(1000); source->startUpdates(); if (m_verbose) printf("acquired source %s\n", qPrintable(source->sourceName())); } else { printf("failed to acquire source\n"); QCoreApplication::quit(); } } void Geopos::positionUpdated(const QGeoPositionInfo &info) { if (m_verbose) { printf("timestamp %s\n", qPrintable(info.timestamp().toString())); printf(" valid %s\n", info.isValid() ? "yes":"no"); printf(" latitude %f\n", info.coordinate().latitude()); printf(" longitude %f\n", info.coordinate().longitude()); printf(" altitude %f\n", info.coordinate().altitude()); printf(" ground speed %f\n", info.attribute(QGeoPositionInfo::GroundSpeed)); printf(" horizontal accuracy %f\n", info.attribute(QGeoPositionInfo::HorizontalAccuracy)); } else { printf("%s %f %f%s\n", qPrintable(info.timestamp().toString()), info.coordinate().latitude(), info.coordinate().longitude(), info.isValid() ? "":" invalid"); } if (!m_repeat) QCoreApplication::quit(); }
5526fd0d77dfbef80de98ec9c7367fb1ab51ce9d
4bd425e25561eacf8747b740fd23aa83155251d6
/main.cpp
e0e0bcf3146d9debfa8d3235c6837c240c9835a7
[]
no_license
yardru/mail_exam_not_server
8a0bf02537cf45ae09efbfab747093fda10ee8be
47fef09efdd7faac940c2c6cd929e1ddebd6cda0
refs/heads/master
2021-01-16T21:37:45.238310
2016-07-21T14:29:25
2016-07-21T14:29:25
63,869,947
0
0
null
null
null
null
UTF-8
C++
false
false
293
cpp
main.cpp
#include <iostream> #include <unistd.h> int main(int argc, char **argv) { char server[] = "/home/box/server"; if (argc < 7) return 1; execlp(server, server, argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], nullptr); perror("open server error"); return 0; }
d2ed126071b6269a948e36aa398d1b992f90a368
bf29f90905c1aa85b6505025679e65e6f910b027
/Code_SASA 저장소/전체/2333 [고알-하] 바이러스 조사.cpp
dde443e1cf0c29c9c563f28f6de76ae630f369fc
[]
no_license
Pentagon03/Code-SASA
a56c7a3703bf3342ebc85fa83fbd5ee77fb99b98
ffecf9f8f70722f58abbcb0f71fb0b9feacc2f79
refs/heads/master
2022-12-14T16:59:42.704313
2020-09-10T08:52:34
2020-09-10T08:52:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
533
cpp
2333 [고알-하] 바이러스 조사.cpp
#include<stdio.h> int H[50010],V[100010]; // H:human, V:virus int n,m,k,temp,i; void meet(int a,int b){ if(H[a]==H[b]) return; if((H[a]==0)||(H[b]==0)){ if(H[a]==0) H[a]=H[b]; else H[b]=H[a]; } else{ m++; H[a]=H[b]=m; } } int main(){ scanf("%d%d%d",&n,&m,&k); for(i=1;i<=m;i++){ scanf("%d",&temp); H[temp]=i; } for(int i=0,a,b;i<k;i++){ scanf("%d%d",&a,&b); meet(a,b); } int ans=0; for(i=1;i<=n;i++) V[H[i]]++; for(i=1;i<=m;i++) if(V[i]>0) ans++; printf("%d",ans); }
2875af0c06634332324824229c1369b00995a5ba
5925604475bdb9106e2ea8550770df9108748f64
/yare/Camera.h
ec84941103697b4155e66c68c925261b2e044f0f
[]
no_license
y20Lion/yare
6f15e5c14e4faba895a742519528ec6c69808701
80b15b400f11b5d80fc538a377492b8a039f2af8
refs/heads/master
2020-12-25T17:03:45.246285
2017-05-13T11:34:50
2017-05-13T11:34:50
56,537,578
1
0
null
null
null
null
UTF-8
C++
false
false
418
h
Camera.h
#pragma once #include <glm/vec3.hpp> #include <glm/fwd.hpp> namespace yare { struct PointOfView { PointOfView(); glm::vec3 from; glm::vec3 to; glm::vec3 up; glm::mat4 lookAtMatrix() const; glm::vec3 rightDirection() const; }; struct Frustum { Frustum(); float left, right, bottom, top, near, far; }; class Camera { public: Frustum frustum; PointOfView point_of_view; }; }
0c550ae34c040259181cb04232a3eec94352f528
8c5b68883c390a337665399bd7eb52244fbf4170
/src/QueueTest.cpp
098648e217afa614b489e9eb231c8fc5148117d5
[]
no_license
NevilleS/astar
b76ba26413d79beb43a844ca737fdba8124a98b1
8db50757c9c1194df6ea627df84d230bce691dba
refs/heads/master
2016-09-06T10:59:42.523634
2012-06-09T22:49:40
2012-06-09T22:49:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,043
cpp
QueueTest.cpp
#include "gtest/gtest.h" #include "StdQueue.h" #include "PriorityQueue.h" #include "Stack.h" std::ostream& operator<<(std::ostream& os, const Node* a) { os << "Node(" << a->m_x << ", " << a->m_y << ", " << a->m_gCost << ", " << a->m_hCost << ")"; return os; } TEST(QueueTest, InsertTest) { // Check that inserting a node stores it correctly StdQueue queue; Node n; ASSERT_EQ(0, queue.size()); queue.insert(&n); ASSERT_EQ(1, queue.size()); ASSERT_EQ(&n, queue.removeFront()); } TEST(QueueTest, QueueFIFOTest) { // Check that regular queue is FIFO StdQueue queue; Node n1(0,1,4,5), n2(1,2,4,3), n3(2,1,3,6), n4(1,0,4,7); queue.insert(&n1); queue.insert(&n2); queue.insert(&n3); queue.insert(&n4); // Order should be n1,n2,n3,n4 ASSERT_EQ(&n1, queue.removeFront()); ASSERT_EQ(&n2, queue.removeFront()); ASSERT_EQ(&n3, queue.removeFront()); ASSERT_EQ(&n4, queue.removeFront()); } TEST(QueueTest, PrioritySortTest) { // Check that inserting several nodes sorts them // in order of f (g+h) PriorityQueue queue; Node n1(0,1,4,5,false), n2(1,2,4,3,false), n3(2,1,3,6,false), n4(1,0,4,7,false); queue.insert(&n1); queue.insert(&n2); queue.insert(&n3); queue.insert(&n4); // Order should be n2,n3,n1,n4 ASSERT_EQ(&n2, queue.removeFront()); ASSERT_EQ(&n3, queue.removeFront()); ASSERT_EQ(&n1, queue.removeFront()); ASSERT_EQ(&n4, queue.removeFront()); } TEST(QueueTest, StackTest) { // Check that inserting several nodes to Stack acts as LIFO Stack queue; // yeah, that's terrible naming, w/e Node n1(0,1,4,5,false), n2(1,2,4,3,false), n3(2,1,3,6,false), n4(1,0,4,7,false); queue.insert(&n1); queue.insert(&n2); queue.insert(&n3); queue.insert(&n4); // Order should be n4,n3,n2,n1 ASSERT_EQ(&n4, queue.removeFront()); ASSERT_EQ(&n3, queue.removeFront()); ASSERT_EQ(&n2, queue.removeFront()); ASSERT_EQ(&n1, queue.removeFront()); }
a10bc670420e72febfb6dd3d93d5cb87d607e762
39d96bf3f37afa82e47817762f5b788ac0d990eb
/최종포폴/PirateMonster.cpp
9f225c67b0d66e9a62a8fba6e2392e570ec276d6
[]
no_license
kimgyeongyeop/4weeks-portfolio
f337dbb14a8d3497ec6ee0d25345efc976715099
f486c2575ab74f1fd87d56e0a45426bc71f78a10
refs/heads/master
2022-11-19T11:49:24.515829
2020-07-15T14:43:19
2020-07-15T14:43:19
255,474,095
0
0
null
null
null
null
UHC
C++
false
false
3,450
cpp
PirateMonster.cpp
#include "stdafx.h" #include "PirateMonster.h" PirateMonster::PirateMonster() { } PirateMonster::~PirateMonster() { } HRESULT PirateMonster::init(POINT pos) { monsterindex = 5; monsterinfo.pos = pos; monsterinfo.img = IMAGEMANAGER->findImage("해적총알공격"); monsterinfo.currentFrameX = 0; monsterinfo.currentFrameY = 0; monsterinfo.rc = RectMake(monsterinfo.pos.x+60, monsterinfo.pos.y+60, 150, monsterinfo.img->getFrameHeight()); RL = false; playercheak = false; monsterinfo.MaxframeX = 4; range = 200; bulletangle = 0; limitcount = 50; bulletfire = false; EFFECTMANAGER->addEffect("해적이펙", "./resours/effect/해적이펙트2.bmp", 1200, 168, 400, 168, 1.f, 0.1f, 5); //목숨바 설정 IMAGEMANAGER->addImage("monster5frontBar", "hpBarTop.bmp", monsterinfo.rc.right - monsterinfo.rc.left, 10, true, RGB(255, 0, 255)); IMAGEMANAGER->addImage("monster5backBar", "hpBarBottom.bmp", monsterinfo.rc.right - monsterinfo.rc.left, 10, true, RGB(255, 0, 255)); monsterhpBar = new progressBar; monsterhpBar->init("monster5", monsterinfo.rc.left, monsterinfo.rc.top - 20, monsterinfo.rc.right - monsterinfo.rc.left, 10); monstercurrentHP = monstermaxHP = 100; return S_OK; } void PirateMonster::release() { } void PirateMonster::update() { monsterhpBar->update(); monsterhpBar->setX(monsterinfo.rc.left); monsterhpBar->setY(monsterinfo.rc.top - 20); monsterhpBar->setGauge(monstercurrentHP, monstermaxHP); Move(); count++; if (count % limitcount == 0) { monsterinfo.currentFrameX++; count = 0; } if (monsterinfo.currentFrameX > monsterinfo.MaxframeX) { monsterinfo.currentFrameX = 0; } } void PirateMonster::render() { //EFFECTMANAGER->render(); monsterinfo.img->frameRender(CAMERAMANAGER->getWorldDC(), monsterinfo.pos.x, monsterinfo.pos.y, monsterinfo.currentFrameX, monsterinfo.currentFrameY); Monster::render(); } void PirateMonster::Move() { if (playercheak) { //플레이어가 공격 거리안에 들어왔을때 if (getDistance(monsterinfo.pos.x + 50 , monsterinfo.pos.y, PlayerPosX , monsterinfo.pos.y) < range) // 거리 비교해서 쫓아가게 ㄱㄱ { bulletfire = false; limitcount = 30; monsterinfo.img = IMAGEMANAGER->findImage("해적근접공격"); monsterinfo.MaxframeX = 7; if (monsterinfo.currentFrameX == monsterinfo.MaxframeX-2) { CAMERAMANAGER->Camera_WorldDC_Shake(); EFFECTMANAGER->play("해적이펙", monsterinfo.pos.x + 120, monsterinfo.pos.y+170); } if (monsterinfo.currentFrameX == monsterinfo.MaxframeX - 2 && count == 20) { monsterinfo.atkRC = RectMakeCenter(monsterinfo.pos.x + 120, monsterinfo.pos.y + 170, 500, 250); } else { monsterinfo.atkRC = RectMakeCenter(monsterinfo.pos.x + 120, monsterinfo.pos.y + 170, 0, 0); } } else { monsterinfo.MaxframeX = 4; if (monsterinfo.currentFrameX == monsterinfo.MaxframeX) { if (count %limitcount == 0) { bulletfire = true; } else bulletfire = false; } limitcount = 20; monsterinfo.img = IMAGEMANAGER->findImage("해적총알공격"); } } else { monsterinfo.MaxframeX = 4; if (monsterinfo.currentFrameX == monsterinfo.MaxframeX) { if (count % limitcount == 0) { bulletfire = true; } else bulletfire = false; } limitcount = 20; monsterinfo.img = IMAGEMANAGER->findImage("해적총알공격"); } }
aa693e620ed4a5fa5a8ed8a027974ed46730fda8
6631041fe2cd98c885cf004381a214c34bb62f0f
/App/TMReceiverSrc/TMReceiver/TMReceiverImp.cpp
936869798fa559ef5e0d1f5603c8291c5de69471
[]
no_license
usher2007/Navigation
05b5e227b9123f455deba3fb0a07392eb8f4d9ff
1c18ee12ba23c33c3f34d06ac0fd50f89203e79f
refs/heads/develop
2021-01-23T14:57:07.800809
2013-04-17T09:37:21
2013-04-17T09:37:21
2,854,394
4
13
null
2014-08-19T07:01:10
2011-11-26T06:15:08
C++
UTF-8
C++
false
false
2,995
cpp
TMReceiverImp.cpp
#include "stdafx.h" #include "TMReceiverImp.h" TMReceiverImp::TMReceiverImp() { m_pGraph = new CTMReceiverGraph(); m_bDisplay = FALSE; m_bStorage = FALSE; m_bRunning = FALSE; m_bStoring = FALSE; m_hDisplayWnd = NULL; } HRESULT TMReceiverImp::EnableDisplay(HWND hwnd) { m_bDisplay = TRUE; m_hDisplayWnd = hwnd; return S_OK; } HRESULT TMReceiverImp::DisableDisplay() { m_bDisplay = FALSE; if(m_pGraph != NULL) { HRESULT hr = m_pGraph->SetDisplayWindow(NULL); return hr; } return E_FAIL; } HRESULT TMReceiverImp::EnableStorage(const char* strFileName) { memset(m_storageFileName, 0x00, sizeof(m_storageFileName)); memcpy(m_storageFileName, strFileName, strlen(strFileName)); m_bStorage = TRUE; return S_OK; } HRESULT TMReceiverImp::DisableStorage() { m_bStorage = FALSE; return S_OK; } HRESULT TMReceiverImp::SetCallBackBeforeDecode(TMReceiverCB cb, void* arg) { if(m_pGraph != NULL) { HRESULT hr = m_pGraph->SetBeforeDecodeCB(cb, arg); } return S_OK; } HRESULT TMReceiverImp::SetCallBackAfterDecode(TMReceiverCB cb, void* arg) { if(m_pGraph != NULL) { HRESULT hr = m_pGraph->SetAfterDecodeCB(cb, arg); } return S_OK; } HRESULT TMReceiverImp::OpenRtspStream(const char* rtspUrl) { return openStream(rtspUrl); } HRESULT TMReceiverImp::OpenHttpStream(const char* strFileName) { return openStream(strFileName); } HRESULT TMReceiverImp::openStream(const char* streamName) { if(m_pGraph != NULL) { m_pGraph->Create(); HRESULT hr = m_pGraph->BuildFilterGraph(streamName, m_bDisplay); if(FAILED(hr)) return hr; if(!m_bDisplay) { hr = m_pGraph->Run(); if(FAILED(hr)) return hr; m_bRunning = TRUE; } else { hr = m_pGraph->SetDisplayWindow(m_hDisplayWnd); if(FAILED(hr)) return hr; } return S_OK; } return E_FAIL; } HRESULT TMReceiverImp::StartDisplay() { if(m_bDisplay && m_pGraph != NULL) { HRESULT hr = m_pGraph->Run(); if(FAILED(hr)) return hr; m_bRunning = TRUE; return S_OK; } return E_FAIL; } HRESULT TMReceiverImp::StopDisplay() { if(m_bDisplay && m_pGraph != NULL) { HRESULT hr = m_pGraph->Stop(); if(FAILED(hr)) return hr; m_bRunning = FALSE; return S_OK; } return E_FAIL; } HRESULT TMReceiverImp::StartStorage() { if(m_bStorage && m_pGraph != NULL) { HRESULT hr = m_pGraph->StartRecord(m_storageFileName); if(FAILED(hr)) return hr; m_bStoring = TRUE; return S_OK; } return E_FAIL; } HRESULT TMReceiverImp::StopStorage() { if(m_bStorage && m_pGraph != NULL) { HRESULT hr = m_pGraph->StopRecord(); if(FAILED(hr)) return hr; m_bStoring = FALSE; return S_OK; } return E_FAIL; } HRESULT TMReceiverImp::Close() { HRESULT hr = E_FAIL; if(m_pGraph != NULL) { if(m_bStoring) { hr = m_pGraph->StopRecord(); if(FAILED(hr)) return hr; m_bStoring = FALSE; } if(m_bRunning) { hr = m_pGraph->Stop(); if(FAILED(hr)) return hr; m_bRunning = FALSE; } //Destroy the graph? hr = m_pGraph->Destroy(); return hr; } return E_FAIL; }
fdcbc02e0b4f5ccd2ea7ff34f18ae955b488bae1
1c2962381e983bec0858f6724bbc3437c9c75bfc
/spoj/herding.cpp
823fc6124191980ec99447b7f2c5ecd39b01e7ae
[]
no_license
ranti-iitg/CODE
f2871a5cde8fa6f9bc5649e7f3ae25b9d7baccc8
f75e88ef6593deb64fcf2f84d5e0c084753a41d3
refs/heads/master
2020-06-06T17:31:14.220098
2017-04-13T05:34:58
2017-04-13T05:34:58
25,700,143
0
0
null
null
null
null
UTF-8
C++
false
false
1,183
cpp
herding.cpp
#include<iostream> #include<algorithm> #include<string> #include<vector> #include<cstring> using namespace std; vector<string> vs; int a[1005][1005]; using namespace std; int n,m; int check(int u,int b,char c){ if(u>=0&&b>=0&&u<n&&b<m&&a[u][b]==0&&vs[u][b]==c) return true; else return false; } int dfs(int x,int y,int cnt){ if(x>=0&&y>=0&&x<n&&y<m&&a[x][y]==0){ a[x][y]=cnt; if(vs[x][y]=='N') dfs(x-1,y,cnt); else if(vs[x][y]=='S') dfs(x+1,y,cnt); else if(vs[x][y]=='E') dfs(x,y+1,cnt); else dfs(x,y-1,cnt); if(check(x,y+1,'W')) dfs(x,y+1,cnt); if(check(x+1,y,'N')) dfs(x+1,y,cnt); if(check(x,y-1,'E')) dfs(x,y-1,cnt); if(check(x-1,y,'S')) dfs(x-1,y,cnt); } } int main(){ cin>>n; // cout<<endl<<n<<endl; cin>>m; //cout<<m<<endl; string s; getline(cin,s); cin.clear(); for(int i=1;i<=n;++i){ getline(cin,s); // cout<<s<<endl; vs.push_back(s); } memset(a,0,sizeof(a)); int cnt=0; for(int i=0;i<n;++i){ for(int j=0;j<m;++j){ if(a[i][j]==0) {++cnt;dfs(i,j,cnt);} } } cout<<cnt; return 0; }
1dcd216712d8ad4710c98a5315bfd61542a3b27c
0dcda0002fdc5062e2ba42a2f69f956b54071aae
/obstacle-avoiding-robot.ino
07659a87863846ec550a4d85ca15894ee12de841
[]
no_license
Diego-gh/arduino-obstacle-avoiding-robot
9b7a69fbf066f6842ffd909863154944d26d17cf
670890dcd06d3a54a3851118b9bd006df1149678
refs/heads/master
2020-09-27T20:38:05.787208
2019-12-08T02:54:39
2019-12-08T02:54:39
226,604,839
0
0
null
null
null
null
UTF-8
C++
false
false
3,428
ino
obstacle-avoiding-robot.ino
#include <Wire.h> #include <Adafruit_MotorShield.h> #include "utility/Adafruit_MS_PWMServoDriver.h" // Constants const int trigPin = 5; // Pin used to trigger sensor const int echoPin = 4; // Pin used to read data from sensor const int ledPin = 12; // LED pin const int minDistance = 15; // Minimum distance(centimeters) Adafruit_MotorShield AFMS = Adafruit_MotorShield(); Adafruit_DCMotor *M1 = AFMS.getMotor(1); // Motor 1 Adafruit_DCMotor *M2 = AFMS.getMotor(2); // Motor 2 const int defaultSpeed = 100; // Default motor speed const int turnSpeed = 100; // Default turn speed // Used to callibrate individual motor speed const int M1offset = 0; const int M2offset = 0; // time it takes to turn in milliseconds const int turn90Duration = 500; const int turn180Duration = 1000; int distance; // Holds current distance read from the sensor int getDistance(){ // Check how close the vehicle is to the nearest object // Clears the trigPin digitalWrite(trigPin, LOW); delayMicroseconds(2); // Sets the trigPin on HIGH state for 10 micro seconds digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); // Reads the echoPin, returns the sound wave travel time in microseconds long duration = pulseIn(echoPin, HIGH); // Calculating the distance return int(duration*0.034/2); // Return distance in cm } void forward(int s = defaultSpeed){ M1->setSpeed(s + M1offset); M2->setSpeed(s + M2offset); M1->run(FORWARD); M2->run(FORWARD); } void backward(int s = defaultSpeed){ M1->setSpeed(s + M1offset); M2->setSpeed(s + M2offset); M1->run(BACKWARD); M2->run(BACKWARD); } void turnLeft(int t = turn90Duration){ M1->setSpeed(turnSpeed + M1offset); M2->setSpeed(turnSpeed + M2offset); M1->run(FORWARD); M2->run(BACKWARD); delay(t); stopM(); } void turnRight(int t = turn90Duration){ M1->setSpeed(turnSpeed + M1offset); M2->setSpeed(turnSpeed + M2offset); M1->run(BACKWARD); M2->run(FORWARD); delay(t); stopM(); } void stopM(){ // Stop both motors M1->run(RELEASE); M2->run(RELEASE); } void alert(){ Serial.println("Too close"); // Blink LED for(int i = 0; i < 2; i++){ digitalWrite(ledPin, LOW); delay(200); digitalWrite(ledPin, HIGH); delay(200); } } void changeDirection(){ int leftD, rightD; // Declare variables // Turn Left then check distance turnLeft(); leftD = getDistance(); // Turn 180 degrees to the right then check distance turnRight(turn180Duration); rightD = getDistance(); // Check there isn't enough space on both sides, go backward and turn around if(leftD <= minDistance && rightD <= minDistance){ turnRight(); } // if there isn't enough space on the right side, turn 180 else if(leftD > rightD){ turnLeft(turn180Duration); } } void setup() { pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output pinMode(echoPin, INPUT); // Sets the echoPin as an Input Serial.begin(9600); // Starts the serial communication digitalWrite(ledPin, HIGH); // Turn LED on AFMS.begin(); M1->setSpeed(defaultSpeed + M1offset); M2->setSpeed(defaultSpeed + M2offset); } void loop() { distance = getDistance(); // Check how if there is anything near if(distance < minDistance){ // If it's too close stopM(); // Stop moving alert(); // Blink LED several times changeDirection(); // Find new direction and rotate vehicle } else{ forward(); } }
94d2983af8acebcd48a3c59a297b2ea7f20af0a7
2e33661d09778dc4960c045804f4bc35921def08
/APPLICATION/Sources/HAL/uart.hpp
f0e69a17e08e1296ce6d3ab049d9b397b7a7d5f7
[]
no_license
grazzland/smartcard-access-control
beb00190ed9afd40e41ddd265d5cd315a5a5d744
7f5cf566c295bf82e18bde455066b2a3d9f0e1e6
refs/heads/master
2021-06-11T01:23:44.593032
2017-01-03T14:41:19
2017-01-03T14:41:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,021
hpp
uart.hpp
/** * @file uart.hpp * @brief UART driver header */ #ifndef __UART_HPP #define __UART_HPP #include "core.hpp" #include "stm32l1xx.h" // Device header #include <stdint.h> /** * @brief UART driver class */ class Uart { public: enum Options_t { RX_SIZE = 1024, TX_SIZE = 1024, }; /// Data transmission void Transmit(const char* data, uint16_t count); /// Received data copying uint16_t CopyReceivedData(char* buffer, uint16_t size); /// Received data deletion void DeleteReceivedData(uint16_t count); /// Checking, whether the receive buffer is empty bool IsReceiverEmpty(); /// Receive buffer cleaning void Flush(); /// USART1 interrupt handler static void UART1_Handler(); /// Constructor Uart(uint32_t baudrate); private: char *RxBuffer; ///< Receive buffer char *TxBuffer; ///< Transmit buffer char* RxHead; ///< Receive buffer head /// Interrupt handler void Handler(); }; extern Uart Uart1; #endif /* __UART_HPP */
aa1296ccd6bb4b55b692f1c777a653c861d42d02
7f67919b5f5e087e8a26eacd8d5d1c1f94224cc6
/profiling/client/src/RequestCounterDirectoryCommandHandler.cpp
cf07c450309d194cda45e633769af761f8945e7f
[ "BSD-3-Clause", "CC0-1.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
ARM-software/armnn
11f0b169291ade6a08cbef1e87b32000aeed4767
49f609d9e633f52fcdc98e6e06178e618597e87d
refs/heads/branches/armnn_23_05
2023-09-04T07:02:43.218253
2023-05-15T10:24:43
2023-05-15T16:08:53
124,536,178
1,053
329
MIT
2023-05-22T23:28:55
2018-03-09T12:11:48
C++
UTF-8
C++
false
false
1,818
cpp
RequestCounterDirectoryCommandHandler.cpp
// // Copyright © 2019 Arm Ltd. All rights reserved. // SPDX-License-Identifier: MIT // #include "RequestCounterDirectoryCommandHandler.hpp" #include <fmt/format.h> namespace arm { namespace pipe { void RequestCounterDirectoryCommandHandler::operator()(const arm::pipe::Packet& packet) { ProfilingState currentState = m_StateMachine.GetCurrentState(); switch (currentState) { case ProfilingState::Uninitialised: case ProfilingState::NotConnected: case ProfilingState::WaitingForAck: throw arm::pipe::ProfilingException(fmt::format("Request Counter Directory Comand Handler invoked while in an " "wrong state: {}", GetProfilingStateName(currentState))); case ProfilingState::Active: // Process the packet if (!(packet.GetPacketFamily() == 0u && packet.GetPacketId() == 3u)) { throw arm::pipe::InvalidArgumentException(fmt::format("Expected Packet family = 0, id = 3 but " "received family = {}, id = {}", packet.GetPacketFamily(), packet.GetPacketId())); } // Send all the packet required for the handshake with the external profiling service m_SendCounterPacket.SendCounterDirectoryPacket(m_CounterDirectory); m_SendTimelinePacket.SendTimelineMessageDirectoryPackage(); break; default: throw arm::pipe::ProfilingException(fmt::format("Unknown profiling service state: {}", static_cast<int>(currentState))); } } } // namespace pipe } // namespace arm
4ee99ab16df937d99970dbe2a91c782940640418
65e3391b6afbef10ec9429ca4b43a26b5cf480af
/TEvtGen/EvtGen/EvtGenModels/EvtbTosllAliFF.hh
e3710a2ccf98da8d41668e7301dd0f56e9fb6916
[]
permissive
alisw/AliRoot
c0976f7105ae1e3d107dfe93578f819473b2b83f
d3f86386afbaac9f8b8658da6710eed2bdee977f
refs/heads/master
2023-08-03T11:15:54.211198
2023-07-28T12:39:57
2023-07-28T12:39:57
53,312,169
61
299
BSD-3-Clause
2023-07-28T13:19:50
2016-03-07T09:20:12
C++
UTF-8
C++
false
false
1,147
hh
EvtbTosllAliFF.hh
//-------------------------------------------------------------------------- // // Environment: // This software is part of the EvtGen package developed jointly // for the BaBar and CLEO collaborations. If you use all or part // of it, please give an appropriate acknowledgement. // // Copyright Information: See EvtGen/COPYRIGHT // Copyright (C) 1998 Caltech, UCSB // // Module: // Description: Form factors for b->sll according to Ali '02 et al. // PRD 66 34002 // // Modification history: // // Ryd March 30, 2003 Module created // //------------------------------------------------------------------------ #ifndef EVTBTOSLLALIFF_HH #define EVTBTOSLLALIFF_HH #include "EvtGenModels/EvtbTosllFF.hh" class EvtId; class EvtbTosllAliFF : public EvtbTosllFF { public: EvtbTosllAliFF(); void getScalarFF(EvtId parent, EvtId daught,double t, double mass, double& fp,double& f0,double& ft); void getVectorFF(EvtId parent, EvtId daught,double t, double mass, double& a1,double& a2,double& a0, double& v, double& t1, double& t2, double& t3 ); private: }; #endif
532eb3f3d9afdbda3c7cff5dd1df941686409711
969e528c5b946b7bc090a8b1d0511f197e56dc7f
/cpp/MakeJSIRuntime.h
dd22ce773f8386acb864ff5c2a7b7d701514cf80
[ "MIT" ]
permissive
heroic/react-native-multithreading
06667f59464ba6eb05731b5817f9bc8147da8294
9974835a87448fd8947b09891147319c2eb9c32f
refs/heads/master
2023-04-18T03:57:07.933482
2021-04-14T08:00:49
2021-04-14T08:00:49
358,669,151
0
0
MIT
2021-04-16T17:11:56
2021-04-16T17:11:55
null
UTF-8
C++
false
false
324
h
MakeJSIRuntime.h
#pragma once #include <jsi/jsi.h> #include <memory> using namespace facebook; namespace mrousavy { namespace multithreading { /** * Create a new jsi::Runtime with the configured JS engine. * * Supported Engines: * * - Hermes * - V8 * - JavaScriptCore */ std::unique_ptr<jsi::Runtime> makeJSIRuntime(); } }
7ce89ce34015b331b439ed8e4cfafd375cf19d9d
fdd372be49a46dbf84801ca26b2f1d43ac3f4901
/stl/src/unordered_set_t.cpp
9b0e5919d2a265c58d8e77f550d62485b14c1e53
[]
no_license
cbj0304/myCode
261fac9f0ba3a1f46aebecfbdbe462cd1b4985b4
be0e3a486110154cf5b1321cdb9c888ab9104e50
refs/heads/master
2020-11-28T05:14:38.834206
2020-01-21T08:54:56
2020-01-21T08:54:56
229,712,865
0
0
null
null
null
null
UTF-8
C++
false
false
1,066
cpp
unordered_set_t.cpp
#include <unordered_set> #include <string> #include <algorithm> #include <cstdlib> #include <cassert> #include <iostream> #include <vector> #include "common.h" using namespace std; /* set 和 unordered_set: 如果元素为非基础类型,需要自定义哈希函数,具体使用和set类似; 方法: 插入/删除:erase() / insert() / clear() / swap() 查找:count() / find() / equal_range() */ // 自定义hash函数(仿函数) struct VectorHash { size_t operator()(const vector<int>& v) const { std::hash<int> hasher; size_t seed = 0; for (int i : v) { seed ^= hasher(i) + 0x9e3779b9 + (seed<<6) + (seed>>2); } return seed; } }; int main() { unordered_set<vector<int>, VectorHash> s; s.insert({1, 2}); s.insert({1, 3}); s.insert({1, 2}); vector<int> i = {1, 2}; auto it = s.find(i); if (it != s.end()) { vector<int> tmp = *it; for_each(tmp.begin(), tmp.end(), show_item<int>); } system("pause"); return 0; }
df2f2190856186b3a2699f6ec8c92634614e6514
fbe60fa0d8e888bfdcf20beb2ef062f0f24fbcbd
/Algorithms/knight-probability-in-chessboard.cpp
08fd14e03c670f6c36a785609b90e94efe63a9bd
[]
no_license
aman1228/LeetCode
552e5feff8a67c05ba318efa3a8a2d121ab64636
76a3d6878719643cbca59643ff8e697498411498
refs/heads/master
2023-04-03T13:27:06.340091
2021-04-18T00:15:51
2021-04-18T00:20:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,210
cpp
knight-probability-in-chessboard.cpp
// 688. Knight Probability in Chessboard // https://leetcode.com/problems/knight-probability-in-chessboard/ /* On an NxN chessboard, a knight starts at the r-th row and c-th column and attempts to make exactly K moves. The rows and columns are 0 indexed, so the top-left square is (0, 0), and the bottom-right square is (N-1, N-1). A chess knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction. Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there. The knight continues moving until it has made exactly K moves or has moved off the chessboard. Return the probability that the knight remains on the board after it has stopped moving. Example: Input: 3, 2, 0, 0 Output: 0.0625 Explanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board. From each of those positions, there are also two moves that will keep the knight on the board. The total probability the knight stays on the board is 0.0625. Note: N will be between 1 and 25. K will be between 0 and 100. The knight always initially starts on the board. */ #include <iostream> #include <array> #include <vector> using namespace std; class Solution { public: double knightProbability(int N, int K, int r, int c) { vector<vector<vector<double>>> A(K + 1, vector<vector<double>>(N, vector<double>(N, 0))); int i, j, k, l, nx, ny; for (i = 0; i < N; ++i) { for (j = 0; j < N; ++j) { A[0][i][j] = 1; } } array<int, 8> dx({-1, -1, 1, 1, -2, -2, 2, 2}), dy({-2, 2, -2, 2, -1, 1, -1, 1}); for (k = 1; k <= K; ++k) { for (i = 0; i < N; ++i) { for (j = 0; j < N; ++j) { for (l = 0; l < 8; ++l) { nx = i + dx[l]; ny = j + dy[l]; if (nx >= 0 and nx < N and ny >= 0 and ny < N) { A[k][i][j] += A[k - 1][nx][ny] / 8; } } } } } return A[K][r][c]; } }; int main(void) { Solution solution; int N, K, r, c; double result; N = 3; K = 2; r = 0; c = 0; result = solution.knightProbability(N, K, r, c); cout << result << '\n'; return 0; }
cd4adf9385738b251b50fd54b83876cd408d8167
6f05f7d5a67b6bb87956a22b988067ec772ba966
/data/train/cpp/28a0742f8c90cb96240620b7180efc0a91a497f7RepoManager.cpp
28a0742f8c90cb96240620b7180efc0a91a497f7
[ "MIT" ]
permissive
harshp8l/deep-learning-lang-detection
93b6d24a38081597c610ecf9b1f3b92c7d669be5
2a54293181c1c2b1a2b840ddee4d4d80177efb33
refs/heads/master
2020-04-07T18:07:00.697994
2018-11-29T23:21:23
2018-11-29T23:21:23
158,597,498
0
0
MIT
2018-11-21T19:36:42
2018-11-21T19:36:41
null
UTF-8
C++
false
false
1,061
cpp
28a0742f8c90cb96240620b7180efc0a91a497f7RepoManager.cpp
////////////////////////////////////////////////////////////////////////// // RepoManager.cpp - Test RepoManager class // // Language: Visual C++ 2011 // // Platform: Dell Studio 1558, Windows 7 Pro x64 Sp1 // // Application: CIS 687 / Project 4, Sp13 // // Author: Kevin Wang, Syracuse University // // kevixw@gmail.com // ////////////////////////////////////////////////////////////////////////// #ifdef TEST_REPO_MANAGER #include <iostream> #include "RepoManager.h" //----< test stub >-------------------------------------------- void main() { RepoManager::load(); Package p = RepoManager::findLatest("packageA", "default-ns"); std::cout << "\n Find package? " << p.empty(); RepoManager::fillDependencyVer(p); Package p2 = RepoManager::find("packageA", "default-ns", 1); std::cout << "\n Find package? 2 " << p2.empty(); Package p3 = RepoManager::find(p); std::cout << "\n Find package? 3 " << p3.empty(); RepoManager::add(p2); std::cout<<"\n\n"; } #endif
eaa31e49bcddd84b3051ab3e52828fb52e8b03a4
b500af19a25a965cdd7460d7ac85847d1820d744
/Prodedural-Programming-Cpp/assignment30.cpp
0f0ef178954027a3b7f9e4cccae0730deea7cce3
[]
no_license
FNHENRIQUES/CPP-class
3a9e9e7362b2e5e59fd8b8a84401ba0e59b14611
05fa322a764897d1f7ada002a59e0510b86276e7
refs/heads/master
2020-05-07T21:57:49.900988
2019-04-12T03:59:52
2019-04-12T03:59:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,657
cpp
assignment30.cpp
/*********************************************************************** * Program: * Assignment 30, Array * Brother Honeycutt, CS124 * Author: * Fernando Negreiros Henriques * Summary: * This program prompt user for 10 grades, sum and calculate the average of * grades using array data. * Estimated: 1.0 hrs * Actual: 1.0 hrs * From the beginning was difficult understand what program was doing, * but I realized in recording and reading file. ************************************************************************/ #include <iostream> using namespace std; /********************************************************************** * Function get grades receive grades from user and storage in memory * array and sum the values. ***********************************************************************/ float getGrades() { const int SIZE = 10; int listDestination[SIZE]; int listSource[SIZE]; // Load a list of grades. for (int i = 0; i < SIZE; i++) { cout << "Grade " << i + 1 << ": "; cin >> listSource[i]; } // Copy the list for (int i = 0; i < SIZE; i++) { listDestination[i] = listSource[i]; } // Sum the values from each array int sum = 0; for (int i = 0; i < SIZE; i++) { sum += listDestination[i]; } return sum; } /********************************************************************** * Function average grades calculate the average of the sum get grade value. ***********************************************************************/ int averageGrades(int sum) { int average; int SIZE = 10; // Calculate the average of the getGrades sum value. average = sum / SIZE; return average; } /********************************************************************** * Display function will show on screen the result of grades average. ***********************************************************************/ void display(int average) { cout.setf(ios::fixed); // not scientific mode. cout.precision(0); // no decimal precision. cout << "Average Grade: " << average << "%" << endl; } /********************************************************************** * Function main call variables to get grade values calculate average * and display the result. ***********************************************************************/ int main() { int sum = getGrades(); int average = averageGrades(sum); display(average); return 0; }
b1dc6147befd6e6756cc438a65e3bebcdabba779
3787dbfff19d9cec250c5c0a0dc65aa1f4439478
/5648. 원자 소멸 시뮬레이션/5648. 원자 소멸 시뮬레이션.cpp
713dacabc1b42a8aa17a4a6dffbd9e5f076c40da
[]
no_license
YangJongYeol/BaekJoon
0669846bc9cb1f878f80d3730dbe74e5def51f9e
e9977db731f1380e0d6283d581b0271a21834a48
refs/heads/master
2021-05-05T13:00:22.875505
2019-10-16T13:08:46
2019-10-16T13:08:46
118,354,063
0
0
null
null
null
null
UTF-8
C++
false
false
2,420
cpp
5648. 원자 소멸 시뮬레이션.cpp
// 5648. 원자 소멸 시뮬레이션.cpp : 이 파일에는 'main' 함수가 포함됩니다. 거기서 프로그램 실행이 시작되고 종료됩니다. // #pragma warning(disable: 4996) #include <iostream> #include <queue> #include <cstring> #define loop(a,b) for(int a=0; a<b; a++) using namespace std; int T, N, ans, map[4001][4001], dir_x[] = { 0,0,-1,1 }, dir_y[] = { 1,-1,0,0 }; struct Atom { int x, y, dir, energy; }; int main() { scanf("%d", &T); loop(t, T) { memset(map, 0, sizeof(map)); ans = 0; queue<Atom> q,garbage; scanf("%d", &N); loop(i, N) { int x, y, dir, en; scanf("%d %d %d %d", &x, &y, &dir, &en); x = (x + 1000) * 2; y = (y + 1000) * 2; q.push({ x,y,dir,en }); map[y][x] = en; } while (!q.empty()) { int size = (int)q.size(); while(!garbage.empty()) { map[garbage.front().y][garbage.front().x] = 0; garbage.pop(); } loop(k, size) { Atom atom = q.front(); q.pop(); map[atom.y][atom.x] = 0; atom.x += dir_x[atom.dir]; atom.y += dir_y[atom.dir]; if (0 > atom.x || atom.x > 4000 || 0 > atom.y || atom.y > 4000) continue; // out of bound if (map[atom.y][atom.x] > 0) { ans += (map[atom.y][atom.x] + atom.energy); map[atom.y][atom.x] = -1; garbage.push(atom); } else if (map[atom.y][atom.x] < 0) { ans += atom.energy; } else { map[atom.y][atom.x] = atom.energy; q.push(atom); } } } printf("#%d %d\n", t + 1, ans); } } // 프로그램 실행: <Ctrl+F5> 또는 [디버그] > [디버깅하지 않고 시작] 메뉴 // 프로그램 디버그: <F5> 키 또는 [디버그] > [디버깅 시작] 메뉴 // 시작을 위한 팁: // 1. [솔루션 탐색기] 창을 사용하여 파일을 추가/관리합니다. // 2. [팀 탐색기] 창을 사용하여 소스 제어에 연결합니다. // 3. [출력] 창을 사용하여 빌드 출력 및 기타 메시지를 확인합니다. // 4. [오류 목록] 창을 사용하여 오류를 봅니다. // 5. [프로젝트] > [새 항목 추가]로 이동하여 새 코드 파일을 만들거나, [프로젝트] > [기존 항목 추가]로 이동하여 기존 코드 파일을 프로젝트에 추가합니다. // 6. 나중에 이 프로젝트를 다시 열려면 [파일] > [열기] > [프로젝트]로 이동하고 .sln 파일을 선택합니다.
7bf15d1fd5d349b8bb0037b9586e3be037cda9f9
bb9259778d3b51a98ad22d373ced81ceef9fe3b2
/c-interfaces/DeploymentManager.h
bfd88135fe39baf54c4d8abc2cc4c83a956d312a
[ "MIT" ]
permissive
christiaanb/SoOSiM
097415c5f24869770d6731d82cf5cf0b7a7c18ef
84b7db42c9c2398f4cec8edeff206a4b1ee268f8
refs/heads/master
2021-01-19T14:56:15.329576
2013-06-19T21:24:13
2013-06-19T21:24:13
3,719,498
2
1
null
null
null
null
UTF-8
C++
false
false
364
h
DeploymentManager.h
#ifndef DEPLOYMENT_MANAGER #define DEPLOYMENT_MANAGER #include "SoOSiM.h" #include "common.h" // Depends on modules: #include "CodeAdapter.h" #include "MemoryManager.h" class DeploymentManager { public: DeploymentManager(); ~DeploymentManager(); void deploy(code_t c, destination_t d); void migrate(code_t c, threadId tId, destination_t d); }; #endif
7468a3b6e43baeff41d59d0c1b620082613aa522
bc2d1a4464ca12d083be4ba5c7a31e25bc694633
/Ass3/src/Goal.cpp
03d24cb20443117f657ab3db50f99e921843db53
[]
no_license
RakshakSatsangi/Designing
794e69d88dbdf098864cf3e0a8ccbce51c91f3a9
2a9fb686dd1c0956543e6329be26a6993ca91690
refs/heads/master
2021-01-19T07:25:02.948933
2015-05-03T17:25:37
2015-05-03T17:25:37
34,991,346
0
0
null
null
null
null
UTF-8
C++
false
false
366
cpp
Goal.cpp
/* * Goal.cpp * * Created on: 23-Apr-2015 * Author: rakshak */ #include "Goal.h" Goal::Goal(float x, float y, float w, float h) { x_cor = x; y_cor = y; width = w; height = h; line.setSize(sf::Vector2f(w, h)); line.setFillColor(sf::Color::White); line.setPosition(x, y); // TODO Auto-generated constructor stub } void Goal::refresh_goal() { }
a2271ee869059fc4077dc8adae699093610e548f
ab9e699af16bd8c58760ab9555f11d5fb81ede8f
/Chapter2_linkedLists/doubly_linked_list.cpp
008b1212e6665948a057435300d2fe73f4c0f44e
[ "MIT" ]
permissive
kgajwan1/CTCI_practice
c4cca2c9651df74eb518e427932281fed2922abf
2e8e61f508777b4b7ad5d8c32dedd12ea5b27d39
refs/heads/master
2020-06-06T15:44:22.823730
2020-01-07T22:09:58
2020-01-07T22:09:58
192,781,970
0
0
null
null
null
null
UTF-8
C++
false
false
3,273
cpp
doubly_linked_list.cpp
//doubly linked list #include<bits/stdc++.h> class Node{ public: int data; Node *next; Node *prev; }; //push data to node /* Given a reference (pointer to pointer) to the head of a list and an int, inserts a new node on the front of the list. */ void push(Node **n, int new_data) { //allocate node Node *new_node = new Node(); //put data in the node new_node->data = new_data; //make next of new node and null of prev new_node->next = (*n); new_node->prev = nullptr; //change previous of head node to new node if ((*n) !=nullptr) { (*n)->prev = new_node; } (*n) = new_node; } //add a new node to next of old node void insertNodeNext(Node *previous_node, int new_data) { if (previous_node == nullptr) { std::cout << "previous node can not be null"; return; } //allocate a new node Node *new_node = new Node(); //put data in the node new_node->data = new_data; //Make next of new node as next of prev_node new_node ->next = previous_node->next; previous_node->next = new_node; new_node->prev = previous_node; //if next != null, insert if (new_node->next != NULL) new_node->next->prev = new_node; } //append daata to node void append(Node** head_ref, int new_data) { /* 1. allocate node */ Node* new_node = new Node(); Node* last = *head_ref; /* used in step 5*/ /* 2. put in the data */ new_node->data = new_data; /* 3. This new node is going to be the last node, so make next of it as NULL*/ new_node->next = NULL; /* 4. If the Linked List is empty, then make the new node as head */ if (*head_ref == NULL) { new_node->prev = NULL; *head_ref = new_node; return; } /* 5. Else traverse till the last node */ while (last->next != NULL) last = last->next; /* 6. Change the next of last node */ last->next = new_node; /* 7. Make last node as previous of new node */ new_node->prev = last; return; } void printList(Node* node) { Node* last; std::cout<<"\nTraversal in forward direction \n"; while (node != NULL) { std::cout<<" "<<node->data<<" "; last = node; node = node->next; } std::cout<<"\nTraversal in reverse direction \n"; while (last != NULL) { std::cout<<" "<<last->data<<" "; last = last->prev; } } //main function int main() { /* Start with the empty list */ Node* head = NULL; // Insert 6. So linked list becomes 6->NULL push(&head, 6); // Insert 7 at the beginning. So // linked list becomes 7->6->NULL push(&head, 7); append(&head, 4); // Insert 1 at the beginning. So // linked list becomes 1->7->6->NULL push(&head, 1); // Insert 4 at the end. So linked // list becomes 1->7->6->4->NULL // Insert 8, after 7. So linked // list becomes 1->7->8->6->4->NULL insertNodeNext (head->next, 8); std::cout << "Created DLL is: "; printList(head); return 0; }
e6e11a62e0ae033b3620842e2a89527fa144c013
091d0584da946320b5e8f393aedcccc69db21662
/src/libv/gl/array_buffer_object.hpp
db3c04393422aacca8afe03417ffd8702d02c5f1
[ "Zlib" ]
permissive
cpplibv/libv
bfe3f395439d27f15d06fbe9d614b21cba34006e
cc7182ca38ecd01fe7f87dadf3577b7d5f7dfa28
refs/heads/master
2023-08-31T23:47:44.957226
2022-07-25T22:34:53
2022-07-26T00:14:48
95,343,090
10
1
null
null
null
null
UTF-8
C++
false
false
433
hpp
array_buffer_object.hpp
// Project: libv.gl, File: src/libv/gl/array_buffer_object.hpp #pragma once // pro #include <libv/gl/buffer_object.hpp> namespace libv { namespace gl { // ------------------------------------------------------------------------------------------------- struct ArrayBuffer : Buffer { }; // ------------------------------------------------------------------------------------------------- } // namespace gl } // namespace libv
220f8eb34190fc5358c349e24309d1c3272fec4c
7579d827cb7b50b438dfd9ef6fa80ba2797848c9
/sources/plug_osg/include/luna/wrappers/wrapper_osg_DefaultUserDataContainer.h
ea6973a386b79ed7fe2a44422384a6e0d9af8f98
[]
no_license
roche-emmanuel/sgt
809d00b056e36b7799bbb438b8099e3036377377
ee3a550f6172c7d14179d9d171e0124306495e45
refs/heads/master
2021-05-01T12:51:39.983104
2014-09-08T03:35:15
2014-09-08T03:35:15
79,538,908
3
0
null
null
null
null
UTF-8
C++
false
false
14,115
h
wrapper_osg_DefaultUserDataContainer.h
#ifndef _WRAPPERS_WRAPPER_OSG_DEFAULTUSERDATACONTAINER_H_ #define _WRAPPERS_WRAPPER_OSG_DEFAULTUSERDATACONTAINER_H_ #include <plug_common.h> #include "lua/LuaObject.h" #include <osg/UserDataContainer> class wrapper_osg_DefaultUserDataContainer : public osg::DefaultUserDataContainer, public luna_wrapper_base { public: ~wrapper_osg_DefaultUserDataContainer() { logDEBUG3("Calling delete function for wrapper osg_DefaultUserDataContainer"); if(_obj.pushFunction("delete")) { //_obj.pushArg((osg::DefaultUserDataContainer*)this); // No this argument or the object will be referenced again! _obj.callFunction<void>(); } }; wrapper_osg_DefaultUserDataContainer(lua_State* L, lua_Table* dum) : osg::DefaultUserDataContainer(), luna_wrapper_base(L) { register_protected_methods(L); if(_obj.pushFunction("buildInstance")) { _obj.pushArg((osg::DefaultUserDataContainer*)this); _obj.callFunction<void>(); } }; wrapper_osg_DefaultUserDataContainer(lua_State* L, lua_Table* dum, const osg::DefaultUserDataContainer & udc, const osg::CopyOp & copyop = osg::CopyOp::SHALLOW_COPY) : osg::DefaultUserDataContainer(udc, copyop), luna_wrapper_base(L) { register_protected_methods(L); if(_obj.pushFunction("buildInstance")) { _obj.pushArg((osg::DefaultUserDataContainer*)this); _obj.callFunction<void>(); } }; // Private virtual methods: // Protected virtual methods: // Public virtual methods: // void osg::Object::setName(const std::string & name) void setName(const std::string & name) { if(_obj.pushFunction("setName")) { _obj.pushArg((osg::DefaultUserDataContainer*)this); _obj.pushArg(name); return (_obj.callFunction<void>()); } return DefaultUserDataContainer::setName(name); }; // void osg::Object::computeDataVariance() void computeDataVariance() { if(_obj.pushFunction("computeDataVariance")) { _obj.pushArg((osg::DefaultUserDataContainer*)this); return (_obj.callFunction<void>()); } return DefaultUserDataContainer::computeDataVariance(); }; // void osg::Object::releaseGLObjects(osg::State * arg1 = 0) const void releaseGLObjects(osg::State * arg1 = 0) const { if(_obj.pushFunction("releaseGLObjects")) { _obj.pushArg((osg::DefaultUserDataContainer*)this); _obj.pushArg(arg1); return (_obj.callFunction<void>()); } return DefaultUserDataContainer::releaseGLObjects(arg1); }; // osg::Object * osg::DefaultUserDataContainer::cloneType() const osg::Object * cloneType() const { if(_obj.pushFunction("cloneType")) { _obj.pushArg((osg::DefaultUserDataContainer*)this); return (_obj.callFunction<osg::Object*>()); } return DefaultUserDataContainer::cloneType(); }; // osg::Object * osg::DefaultUserDataContainer::clone(const osg::CopyOp & arg1) const osg::Object * clone(const osg::CopyOp & arg1) const { if(_obj.pushFunction("clone")) { _obj.pushArg((osg::DefaultUserDataContainer*)this); _obj.pushArg(&arg1); return (_obj.callFunction<osg::Object*>()); } return DefaultUserDataContainer::clone(arg1); }; // bool osg::DefaultUserDataContainer::isSameKindAs(const osg::Object * obj) const bool isSameKindAs(const osg::Object * obj) const { if(_obj.pushFunction("isSameKindAs")) { _obj.pushArg((osg::DefaultUserDataContainer*)this); _obj.pushArg(obj); return (_obj.callFunction<bool>()); } return DefaultUserDataContainer::isSameKindAs(obj); }; // const char * osg::DefaultUserDataContainer::libraryName() const const char * libraryName() const { if(_obj.pushFunction("libraryName")) { _obj.pushArg((osg::DefaultUserDataContainer*)this); return (_obj.callFunction<const char*>()); } return DefaultUserDataContainer::libraryName(); }; // const char * osg::DefaultUserDataContainer::className() const const char * className() const { if(_obj.pushFunction("className")) { _obj.pushArg((osg::DefaultUserDataContainer*)this); return (_obj.callFunction<const char*>()); } return DefaultUserDataContainer::className(); }; // void osg::DefaultUserDataContainer::setThreadSafeRefUnref(bool threadSafe) void setThreadSafeRefUnref(bool threadSafe) { if(_obj.pushFunction("setThreadSafeRefUnref")) { _obj.pushArg((osg::DefaultUserDataContainer*)this); _obj.pushArg(threadSafe); return (_obj.callFunction<void>()); } return DefaultUserDataContainer::setThreadSafeRefUnref(threadSafe); }; // void osg::DefaultUserDataContainer::setUserData(osg::Referenced * obj) void setUserData(osg::Referenced * obj) { if(_obj.pushFunction("setUserData")) { _obj.pushArg((osg::DefaultUserDataContainer*)this); _obj.pushArg(obj); return (_obj.callFunction<void>()); } return DefaultUserDataContainer::setUserData(obj); }; // osg::Referenced * osg::DefaultUserDataContainer::getUserData() osg::Referenced * getUserData() { if(_obj.pushFunction("getUserData")) { _obj.pushArg((osg::DefaultUserDataContainer*)this); return (_obj.callFunction<osg::Referenced*>()); } return DefaultUserDataContainer::getUserData(); }; // const osg::Referenced * osg::DefaultUserDataContainer::getUserData() const const osg::Referenced * getUserData() const { if(_obj.pushFunction("getUserData")) { _obj.pushArg((osg::DefaultUserDataContainer*)this); return (_obj.callFunction<osg::Referenced*>()); } return DefaultUserDataContainer::getUserData(); }; // unsigned int osg::DefaultUserDataContainer::addUserObject(osg::Object * obj) unsigned int addUserObject(osg::Object * obj) { if(_obj.pushFunction("addUserObject")) { _obj.pushArg((osg::DefaultUserDataContainer*)this); _obj.pushArg(obj); return (_obj.callFunction<unsigned int>()); } return DefaultUserDataContainer::addUserObject(obj); }; // void osg::DefaultUserDataContainer::setUserObject(unsigned int i, osg::Object * obj) void setUserObject(unsigned int i, osg::Object * obj) { if(_obj.pushFunction("setUserObject")) { _obj.pushArg((osg::DefaultUserDataContainer*)this); _obj.pushArg(i); _obj.pushArg(obj); return (_obj.callFunction<void>()); } return DefaultUserDataContainer::setUserObject(i, obj); }; // void osg::DefaultUserDataContainer::removeUserObject(unsigned int i) void removeUserObject(unsigned int i) { if(_obj.pushFunction("removeUserObject")) { _obj.pushArg((osg::DefaultUserDataContainer*)this); _obj.pushArg(i); return (_obj.callFunction<void>()); } return DefaultUserDataContainer::removeUserObject(i); }; // osg::Object * osg::DefaultUserDataContainer::getUserObject(unsigned int i) osg::Object * getUserObject(unsigned int i) { if(_obj.pushFunction("getUserObject")) { _obj.pushArg((osg::DefaultUserDataContainer*)this); _obj.pushArg(i); return (_obj.callFunction<osg::Object*>()); } return DefaultUserDataContainer::getUserObject(i); }; // const osg::Object * osg::DefaultUserDataContainer::getUserObject(unsigned int i) const const osg::Object * getUserObject(unsigned int i) const { if(_obj.pushFunction("getUserObject")) { _obj.pushArg((osg::DefaultUserDataContainer*)this); _obj.pushArg(i); return (_obj.callFunction<osg::Object*>()); } return DefaultUserDataContainer::getUserObject(i); }; // unsigned int osg::DefaultUserDataContainer::getNumUserObjects() const unsigned int getNumUserObjects() const { if(_obj.pushFunction("getNumUserObjects")) { _obj.pushArg((osg::DefaultUserDataContainer*)this); return (_obj.callFunction<unsigned int>()); } return DefaultUserDataContainer::getNumUserObjects(); }; // unsigned int osg::DefaultUserDataContainer::getUserObjectIndex(const osg::Object * obj, unsigned int startPos = 0) const unsigned int getUserObjectIndex(const osg::Object * obj, unsigned int startPos = 0) const { if(_obj.pushFunction("getUserObjectIndex")) { _obj.pushArg((osg::DefaultUserDataContainer*)this); _obj.pushArg(obj); _obj.pushArg(startPos); return (_obj.callFunction<unsigned int>()); } return DefaultUserDataContainer::getUserObjectIndex(obj, startPos); }; // unsigned int osg::DefaultUserDataContainer::getUserObjectIndex(const std::string & name, unsigned int startPos = 0) const unsigned int getUserObjectIndex(const std::string & name, unsigned int startPos = 0) const { if(_obj.pushFunction("getUserObjectIndex")) { _obj.pushArg((osg::DefaultUserDataContainer*)this); _obj.pushArg(name); _obj.pushArg(startPos); return (_obj.callFunction<unsigned int>()); } return DefaultUserDataContainer::getUserObjectIndex(name, startPos); }; // void osg::DefaultUserDataContainer::setDescriptions(const osg::UserDataContainer::DescriptionList & descriptions) void setDescriptions(const osg::UserDataContainer::DescriptionList & descriptions) { if(_obj.pushFunction("setDescriptions")) { _obj.pushArg((osg::DefaultUserDataContainer*)this); _obj.pushArg(&descriptions); return (_obj.callFunction<void>()); } return DefaultUserDataContainer::setDescriptions(descriptions); }; // osg::UserDataContainer::DescriptionList & osg::DefaultUserDataContainer::getDescriptions() osg::UserDataContainer::DescriptionList & getDescriptions() { if(_obj.pushFunction("getDescriptions")) { _obj.pushArg((osg::DefaultUserDataContainer*)this); return *(_obj.callFunction<osg::UserDataContainer::DescriptionList*>()); } return DefaultUserDataContainer::getDescriptions(); }; // const osg::UserDataContainer::DescriptionList & osg::DefaultUserDataContainer::getDescriptions() const const osg::UserDataContainer::DescriptionList & getDescriptions() const { if(_obj.pushFunction("getDescriptions")) { _obj.pushArg((osg::DefaultUserDataContainer*)this); return *(_obj.callFunction<osg::UserDataContainer::DescriptionList*>()); } return DefaultUserDataContainer::getDescriptions(); }; // unsigned int osg::DefaultUserDataContainer::getNumDescriptions() const unsigned int getNumDescriptions() const { if(_obj.pushFunction("getNumDescriptions")) { _obj.pushArg((osg::DefaultUserDataContainer*)this); return (_obj.callFunction<unsigned int>()); } return DefaultUserDataContainer::getNumDescriptions(); }; // void osg::DefaultUserDataContainer::addDescription(const std::string & desc) void addDescription(const std::string & desc) { if(_obj.pushFunction("addDescription")) { _obj.pushArg((osg::DefaultUserDataContainer*)this); _obj.pushArg(desc); return (_obj.callFunction<void>()); } return DefaultUserDataContainer::addDescription(desc); }; // Protected non-virtual methods: // void osg::Referenced::signalObserversAndDelete(bool signalDelete, bool doDelete) const void public_signalObserversAndDelete(bool signalDelete, bool doDelete) const { return osg::Referenced::signalObserversAndDelete(signalDelete, doDelete); }; // void osg::Referenced::deleteUsingDeleteHandler() const void public_deleteUsingDeleteHandler() const { return osg::Referenced::deleteUsingDeleteHandler(); }; // Protected non-virtual checkers: inline static bool _lg_typecheck_public_signalObserversAndDelete(lua_State *L) { if( lua_gettop(L)!=3 ) return false; if( lua_isboolean(L,2)==0 ) return false; if( lua_isboolean(L,3)==0 ) return false; return true; } inline static bool _lg_typecheck_public_deleteUsingDeleteHandler(lua_State *L) { if( lua_gettop(L)!=1 ) return false; return true; } // Protected non-virtual function binds: // void osg::Referenced::public_signalObserversAndDelete(bool signalDelete, bool doDelete) const static int _bind_public_signalObserversAndDelete(lua_State *L) { if (!_lg_typecheck_public_signalObserversAndDelete(L)) { luaL_error(L, "luna typecheck failed in void osg::Referenced::public_signalObserversAndDelete(bool signalDelete, bool doDelete) const function, expected prototype:\nvoid osg::Referenced::public_signalObserversAndDelete(bool signalDelete, bool doDelete) const\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str()); } bool signalDelete=(bool)(lua_toboolean(L,2)==1); bool doDelete=(bool)(lua_toboolean(L,3)==1); wrapper_osg_DefaultUserDataContainer* self=Luna< osg::Referenced >::checkSubType< wrapper_osg_DefaultUserDataContainer >(L,1); if(!self) { luaL_error(L, "Invalid object in function call void osg::Referenced::public_signalObserversAndDelete(bool, bool) const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str()); } self->public_signalObserversAndDelete(signalDelete, doDelete); return 0; } // void osg::Referenced::public_deleteUsingDeleteHandler() const static int _bind_public_deleteUsingDeleteHandler(lua_State *L) { if (!_lg_typecheck_public_deleteUsingDeleteHandler(L)) { luaL_error(L, "luna typecheck failed in void osg::Referenced::public_deleteUsingDeleteHandler() const function, expected prototype:\nvoid osg::Referenced::public_deleteUsingDeleteHandler() const\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str()); } wrapper_osg_DefaultUserDataContainer* self=Luna< osg::Referenced >::checkSubType< wrapper_osg_DefaultUserDataContainer >(L,1); if(!self) { luaL_error(L, "Invalid object in function call void osg::Referenced::public_deleteUsingDeleteHandler() const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str()); } self->public_deleteUsingDeleteHandler(); return 0; } void register_protected_methods(lua_State* L) { static const luaL_Reg wrapper_lib[] = { {"signalObserversAndDelete",_bind_public_signalObserversAndDelete}, {"deleteUsingDeleteHandler",_bind_public_deleteUsingDeleteHandler}, {NULL,NULL} }; pushTable(); luaL_register(L, NULL, wrapper_lib); lua_pop(L, 1); }; }; #endif
99faf51f3762250c780cb14d9c78d2b10772db10
9fc4a85471668e9ee9a8acb01f2ed2705895bd66
/include/teleop/TankDrive.h
d2b0a9567cb07e21ea5b644790970267b26e87b0
[ "MIT" ]
permissive
Team302/2018BetaCode
56badc4624bdce48721c8efb195058a79eb4e277
c941a77c537ce14fac0c13b7416f33b1cea97cad
refs/heads/master
2020-04-14T18:27:28.418862
2019-01-03T20:50:30
2019-01-03T20:50:30
164,019,828
0
1
null
null
null
null
UTF-8
C++
false
false
415
h
TankDrive.h
/* * TankDrive.h * * Created on: Jan 27, 2018 * Author: casti */ #ifndef SRC_TELEOP_DRIVE_TANKDRIVE_H_ #define SRC_TELEOP_DRIVE_TANKDRIVE_H_ #include <teleop/IDrive.h> class TankDrive : public IDrive { public: TankDrive(); virtual ~TankDrive() = default; void Drive() override; const char* GetIdentifier() const override; }; #endif /* SRC_TELEOP_DRIVE_TANKDRIVE_H_ */
fda1b5a97c5db3a3cfaa4118e3c0de8737fb9b5d
415adc368d855cc21cc3ba0130403a5daa8033e5
/boom/CC++学习指南 - 语法篇/视频教程(PPT课件及示例代码)/示例代码/main_28_1A.cpp
4975c37cd756c3393df43b39f8041c8458b6edfd
[]
no_license
theJinFei/AlgorithmTest
8ae6051832001b5b0d87709803b6df8b0d224fad
83616b5baad7abff1a3f09e0ebf317615bb8c7a5
refs/heads/master
2022-03-08T02:41:17.253049
2019-12-16T03:15:24
2019-12-16T03:15:24
114,447,954
0
0
null
null
null
null
GB18030
C++
false
false
387
cpp
main_28_1A.cpp
#include <stdio.h> #include <string.h> class AAA { private: // 定义一个内部类 class Inner { public: int id; char name[64]; }; public: AAA() { Inner i; i.id = 123; } }; int main() { // 使用该内部类时,类名使用全称 AAA::Inner // AAA::Inner a; // a.id = 123; // strcpy(a.name, "AnXin"); // printf("Name: %s \n", a.name); return 0; }
73ddd491bacbe89cba1d26ab7cf5dcee6fae8d1f
800f6a2a700370de83790633651958f1fe98d4b3
/qspexecwebengineurlschemehandler.cpp
44e1f932f8810af9da19738408c5bd5e6690dd7a
[ "MIT" ]
permissive
Sonnix1/Qqsp
2d72e6dbb9206c907b77e5e8bc49863e6e236b98
77ce918e8c2f2bdde8ef389adca9e6b69624f572
refs/heads/master
2020-07-30T07:00:20.167311
2019-09-06T12:03:01
2019-09-06T12:04:14
210,126,839
1
2
null
null
null
null
UTF-8
C++
false
false
1,815
cpp
qspexecwebengineurlschemehandler.cpp
#include "qspexecwebengineurlschemehandler.h" #include <QString> #include <QBuffer> #include <QUrl> #include <QMessageBox> #include <qsp_default.h> #include "callbacks_gui.h" #include "comtools.h" QspExecWebEngineUrlSchemeHandler::QspExecWebEngineUrlSchemeHandler(QObject *parent) : QWebEngineUrlSchemeHandler(parent) { } void QspExecWebEngineUrlSchemeHandler::requestStarted(QWebEngineUrlRequestJob *request) { url = request->requestUrl(); QTimer::singleShot(0, this, SLOT(QspLinkClicked())); } void QspExecWebEngineUrlSchemeHandler::QspLinkClicked() { emit qspLinkClicked(url); } void QspExecWebEngineUrlSchemeHandler::legacyLinkClicked(QWebEngineUrlRequestJob *request) { url = request->requestUrl(); QString href; href = QByteArray::fromPercentEncoding(url.toString().toUtf8()); QString string = href.mid(5); if (!QSPExecString(qspStringFromQString(string), QSP_TRUE)) { QString errorMessage; QSP_CHAR *loc; int code, actIndex, line; QSPGetLastErrorData(&code, &loc, &actIndex, &line); QString desc = QSPTools::qspStrToQt(QSPGetErrorDesc(code)); if (loc) errorMessage = QString("Location: %1\nArea: %2\nLine: %3\nCode: %4\nDesc: %5") .arg(QSPTools::qspStrToQt(loc)) .arg(actIndex < 0 ? QString("on visit") : QString("on action")) .arg(line) .arg(code) .arg(desc); else errorMessage = QString("Code: %1\nDesc: %2") .arg(code) .arg(desc); QMessageBox dialog(QMessageBox::Critical, tr("Error"), errorMessage, QMessageBox::Ok); dialog.exec(); QSPCallBacks::RefreshInt(QSP_FALSE); } //request->redirect(QUrl("qsp:/")); }
106a2c66fde6a0268332e7a5b7cd0e85ee1fa967
96fc5a71c3b60d6142491f9431e2ec9b74f181bd
/paddle/function/FunctionTest.cpp
7ce908320a6f6f764e8fdacc96432aca78d7b2df
[ "Apache-2.0" ]
permissive
beckett1124/Paddle
747f80504e5a5c87df4bb24ada8a63e60412210b
bee88c9f24c1f738d676a3dba58ceb4fdcf672fc
refs/heads/develop
2020-12-24T06:13:55.256179
2017-02-09T07:42:56
2017-02-09T07:42:56
73,163,938
0
0
null
2017-01-15T11:28:27
2016-11-08T08:13:35
C++
UTF-8
C++
false
false
1,864
cpp
FunctionTest.cpp
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. 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 "Function.h" #include <gtest/gtest.h> namespace paddle { template <DeviceType DType> void FunctionApi(typename Tensor<real, DType>::Matrix& output, const typename Tensor<real, DType>::Matrix& input); template <> void FunctionApi<DEVICE_TYPE_CPU>(CpuMatrix& output, const CpuMatrix& input) { EXPECT_EQ(output.getHeight(), 100); EXPECT_EQ(output.getWidth(), 200); } template <> void FunctionApi<DEVICE_TYPE_GPU>(GpuMatrix& output, const GpuMatrix& input) { EXPECT_EQ(output.getHeight(), 10); EXPECT_EQ(output.getWidth(), 20); } template <DeviceType DType> void Function(const BufferArgs& arguments) { const auto input = arguments[0].matrix<DType>(); auto output = arguments[1].matrix<DType>(); FunctionApi<DType>(output, input); } TEST(Function, BufferArgs) { CpuMatrix cpuInput = CpuMatrix(100, 200); CpuMatrix cpuOutput = CpuMatrix(100, 200); BufferArgs cpuArgments; cpuArgments.addArg(cpuInput); cpuArgments.addArg(cpuOutput); Function<DEVICE_TYPE_CPU>(cpuArgments); GpuMatrix gpuInput = GpuMatrix(10, 20); GpuMatrix gpuOutput = GpuMatrix(10, 20); BufferArgs gpuArgments; gpuArgments.addArg(gpuInput); gpuArgments.addArg(gpuOutput); Function<DEVICE_TYPE_GPU>(gpuArgments); } } // namespace paddle
151f15dbb59f0045c0910d6c478ec362ea5b596d
525e8581d7f35d63277563649708f69cd8a0c3b8
/naudio/third_party/JUCE/extras/Projucer/Source/Utility/jucer_CodeHelpers.cpp
a540b291f3d137d5e96f11d4e9767efc8d83834a
[]
no_license
eliot-akira/audiom
55f8d218b3922c76ef0216324f2245e3929d764c
23397abaecb789fb8b6fd449f3a627383640bc47
refs/heads/master
2021-04-05T23:55:17.742839
2018-03-29T05:41:55
2018-03-29T05:41:55
125,117,718
2
0
null
null
null
null
UTF-8
C++
false
false
16,753
cpp
jucer_CodeHelpers.cpp
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2017 - ROLI Ltd. JUCE is an open source library subject to commercial or open-source licensing. By using JUCE, you agree to the terms of both the JUCE 5 End-User License Agreement and JUCE 5 Privacy Policy (both updated and effective as of the 27th April 2017). End User License Agreement: www.juce.com/juce-5-licence Privacy Policy: www.juce.com/juce-5-privacy-policy Or: You may also use this code under the terms of the GPL v3 (see www.gnu.org/licenses). JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ #include "../jucer_Headers.h" #include "jucer_CodeHelpers.h" //============================================================================== namespace CodeHelpers { String indent (const String& code, const int numSpaces, bool indentFirstLine) { if (numSpaces == 0) return code; auto space = String::repeatedString (" ", numSpaces); auto lines = StringArray::fromLines (code); for (auto& line : lines) { if (! indentFirstLine) { indentFirstLine = true; continue; } if (line.trimEnd().isNotEmpty()) line = space + line; } return lines.joinIntoString (newLine); } String unindent (const String& code, const int numSpaces) { if (numSpaces == 0) return code; auto space = String::repeatedString (" ", numSpaces); auto lines = StringArray::fromLines (code); for (auto& line : lines) if (line.startsWith (space)) line = line.substring (numSpaces); return lines.joinIntoString (newLine); } String makeValidIdentifier (String s, bool capitalise, bool removeColons, bool allowTemplates, bool allowAsterisks) { if (s.isEmpty()) return "unknown"; if (removeColons) s = s.replaceCharacters (".,;:/@", "______"); else s = s.replaceCharacters (".,;/@", "_____"); for (int i = s.length(); --i > 0;) if (CharacterFunctions::isLetter (s[i]) && CharacterFunctions::isLetter (s[i - 1]) && CharacterFunctions::isUpperCase (s[i]) && ! CharacterFunctions::isUpperCase (s[i - 1])) s = s.substring (0, i) + " " + s.substring (i); String allowedChars ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_ 0123456789"); if (allowTemplates) allowedChars += "<>"; if (! removeColons) allowedChars += ":"; if (allowAsterisks) allowedChars += "*"; StringArray words; words.addTokens (s.retainCharacters (allowedChars), false); words.trim(); String n (words[0]); if (capitalise) n = n.toLowerCase(); for (int i = 1; i < words.size(); ++i) { if (capitalise && words[i].length() > 1) n << words[i].substring (0, 1).toUpperCase() << words[i].substring (1).toLowerCase(); else n << words[i]; } if (CharacterFunctions::isDigit (n[0])) n = "_" + n; if (CPlusPlusCodeTokeniser::isReservedKeyword (n)) n << '_'; return n; } String createIncludeStatement (const File& includeFile, const File& targetFile) { return createIncludeStatement (FileHelpers::unixStylePath (FileHelpers::getRelativePathFrom (includeFile, targetFile.getParentDirectory()))); } String createIncludeStatement (const String& includePath) { if (includePath.startsWithChar ('<') || includePath.startsWithChar ('"')) return "#include " + includePath; return "#include \"" + includePath + "\""; } String makeHeaderGuardName (const File& file) { return file.getFileName().toUpperCase() .replaceCharacters (" .", "__") .retainCharacters ("_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") + "_INCLUDED"; } String makeBinaryDataIdentifierName (const File& file) { return makeValidIdentifier (file.getFileName() .replaceCharacters (" .", "__") .retainCharacters ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_0123456789"), false, true, false); } String stringLiteral (const String& text, int maxLineLength) { if (text.isEmpty()) return "String()"; StringArray lines; { String::CharPointerType t (text.getCharPointer()); bool finished = t.isEmpty(); while (! finished) { for (String::CharPointerType startOfLine (t);;) { switch (t.getAndAdvance()) { case 0: finished = true; break; case '\n': break; case '\r': if (*t == '\n') ++t; break; default: continue; } lines.add (String (startOfLine, t)); break; } } } if (maxLineLength > 0) { for (int i = 0; i < lines.size(); ++i) { String& line = lines.getReference (i); if (line.length() > maxLineLength) { const String start (line.substring (0, maxLineLength)); const String end (line.substring (maxLineLength)); line = start; lines.insert (i + 1, end); } } } for (int i = 0; i < lines.size(); ++i) lines.getReference(i) = CppTokeniserFunctions::addEscapeChars (lines.getReference(i)); lines.removeEmptyStrings(); for (int i = 0; i < lines.size(); ++i) lines.getReference(i) = "\"" + lines.getReference(i) + "\""; String result (lines.joinIntoString (newLine)); if (! CharPointer_ASCII::isValidString (text.toUTF8(), std::numeric_limits<int>::max())) result = "CharPointer_UTF8 (" + result + ")"; return result; } String alignFunctionCallParams (const String& call, const StringArray& parameters, const int maxLineLength) { String result, currentLine (call); for (int i = 0; i < parameters.size(); ++i) { if (currentLine.length() >= maxLineLength) { result += currentLine.trimEnd() + newLine; currentLine = String::repeatedString (" ", call.length()) + parameters[i]; } else { currentLine += parameters[i]; } if (i < parameters.size() - 1) currentLine << ", "; } return result + currentLine.trimEnd() + ")"; } String floatLiteral (double value, int numDecPlaces) { String s (value, numDecPlaces); if (s.containsChar ('.')) s << 'f'; else s << ".0f"; return s; } String boolLiteral (bool value) { return value ? "true" : "false"; } String colourToCode (Colour col) { const Colour colours[] = { #define COL(col) Colours::col, #include "jucer_Colours.h" #undef COL Colours::transparentBlack }; static const char* colourNames[] = { #define COL(col) #col, #include "jucer_Colours.h" #undef COL 0 }; for (int i = 0; i < numElementsInArray (colourNames) - 1; ++i) if (col == colours[i]) return "Colours::" + String (colourNames[i]); return "Colour (0x" + hexString8Digits ((int) col.getARGB()) + ')'; } String justificationToCode (Justification justification) { switch (justification.getFlags()) { case Justification::centred: return "Justification::centred"; case Justification::centredLeft: return "Justification::centredLeft"; case Justification::centredRight: return "Justification::centredRight"; case Justification::centredTop: return "Justification::centredTop"; case Justification::centredBottom: return "Justification::centredBottom"; case Justification::topLeft: return "Justification::topLeft"; case Justification::topRight: return "Justification::topRight"; case Justification::bottomLeft: return "Justification::bottomLeft"; case Justification::bottomRight: return "Justification::bottomRight"; case Justification::left: return "Justification::left"; case Justification::right: return "Justification::right"; case Justification::horizontallyCentred: return "Justification::horizontallyCentred"; case Justification::top: return "Justification::top"; case Justification::bottom: return "Justification::bottom"; case Justification::verticallyCentred: return "Justification::verticallyCentred"; case Justification::horizontallyJustified: return "Justification::horizontallyJustified"; default: break; } jassertfalse; return "Justification (" + String (justification.getFlags()) + ")"; } void writeDataAsCppLiteral (const MemoryBlock& mb, OutputStream& out, bool breakAtNewLines, bool allowStringBreaks) { const int maxCharsOnLine = 250; const unsigned char* data = (const unsigned char*) mb.getData(); int charsOnLine = 0; bool canUseStringLiteral = mb.getSize() < 32768; // MS compilers can't handle big string literals.. if (canUseStringLiteral) { unsigned int numEscaped = 0; for (size_t i = 0; i < mb.getSize(); ++i) { const unsigned int num = (unsigned int) data[i]; if (! ((num >= 32 && num < 127) || num == '\t' || num == '\r' || num == '\n')) { if (++numEscaped > mb.getSize() / 4) { canUseStringLiteral = false; break; } } } } if (! canUseStringLiteral) { out << "{ "; for (size_t i = 0; i < mb.getSize(); ++i) { const int num = (int) (unsigned int) data[i]; out << num << ','; charsOnLine += 2; if (num >= 10) { ++charsOnLine; if (num >= 100) ++charsOnLine; } if (charsOnLine >= maxCharsOnLine) { charsOnLine = 0; out << newLine; } } out << "0,0 };"; } else { out << "\""; CppTokeniserFunctions::writeEscapeChars (out, (const char*) data, (int) mb.getSize(), maxCharsOnLine, breakAtNewLines, false, allowStringBreaks); out << "\";"; } } //============================================================================== static unsigned int calculateHash (const String& s, const unsigned int hashMultiplier) { const char* t = s.toUTF8(); unsigned int hash = 0; while (*t != 0) hash = hashMultiplier * hash + (unsigned int) *t++; return hash; } static unsigned int findBestHashMultiplier (const StringArray& strings) { unsigned int v = 31; for (;;) { SortedSet <unsigned int> hashes; bool collision = false; for (int i = strings.size(); --i >= 0;) { const unsigned int hash = calculateHash (strings[i], v); if (hashes.contains (hash)) { collision = true; break; } hashes.add (hash); } if (! collision) break; v += 2; } return v; } void createStringMatcher (OutputStream& out, const String& utf8PointerVariable, const StringArray& strings, const StringArray& codeToExecute, const int indentLevel) { jassert (strings.size() == codeToExecute.size()); const String indent (String::repeatedString (" ", indentLevel)); const unsigned int hashMultiplier = findBestHashMultiplier (strings); out << indent << "unsigned int hash = 0;" << newLine << indent << "if (" << utf8PointerVariable << " != 0)" << newLine << indent << " while (*" << utf8PointerVariable << " != 0)" << newLine << indent << " hash = " << (int) hashMultiplier << " * hash + (unsigned int) *" << utf8PointerVariable << "++;" << newLine << newLine << indent << "switch (hash)" << newLine << indent << "{" << newLine; for (int i = 0; i < strings.size(); ++i) { out << indent << " case 0x" << hexString8Digits ((int) calculateHash (strings[i], hashMultiplier)) << ": " << codeToExecute[i] << newLine; } out << indent << " default: break;" << newLine << indent << "}" << newLine << newLine; } String getLeadingWhitespace (String line) { line = line.removeCharacters ("\r\n"); const String::CharPointerType endOfLeadingWS (line.getCharPointer().findEndOfWhitespace()); return String (line.getCharPointer(), endOfLeadingWS); } int getBraceCount (String::CharPointerType line) { int braces = 0; for (;;) { const juce_wchar c = line.getAndAdvance(); if (c == 0) break; else if (c == '{') ++braces; else if (c == '}') --braces; else if (c == '/') { if (*line == '/') break; } else if (c == '"' || c == '\'') { while (! (line.isEmpty() || line.getAndAdvance() == c)) {} } } return braces; } bool getIndentForCurrentBlock (CodeDocument::Position pos, const String& tab, String& blockIndent, String& lastLineIndent) { int braceCount = 0; bool indentFound = false; while (pos.getLineNumber() > 0) { pos = pos.movedByLines (-1); const String line (pos.getLineText()); const String trimmedLine (line.trimStart()); braceCount += getBraceCount (trimmedLine.getCharPointer()); if (braceCount > 0) { blockIndent = getLeadingWhitespace (line); if (! indentFound) lastLineIndent = blockIndent + tab; return true; } if ((! indentFound) && trimmedLine.isNotEmpty()) { indentFound = true; lastLineIndent = getLeadingWhitespace (line); } } return false; } }
49e28d785b1d3ca741bf270273fbe0c4b1ddc0a6
0c9ace9a9d35c926e71154b7d0d303da5b6e0370
/leetcode/Cpp/lcofhe-wei-sde-liang-ge-shu-zi.cpp
7601d6f8d7010ea8df3b0a7c37c345b80b5b2c95
[]
no_license
sinsheep/dateStructures
3f257580ada61a6b9cee0481b4aec27d50638ac1
bacf9d43e6ffa3667228d608ad634ea83b4c1272
refs/heads/master
2023-04-04T11:51:57.052149
2021-04-09T15:36:14
2021-04-09T15:36:14
316,744,922
1
0
null
null
null
null
UTF-8
C++
false
false
744
cpp
lcofhe-wei-sde-liang-ge-shu-zi.cpp
#include <bits/stdc++.h> using namespace std; class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> ans; for(int i = 0; i < nums.size(); i++){ int l = i + 1, r = nums.size() - 1; while(l < r){ int mid = (l + r) >> 1; if(nums[mid]>=target - nums[i]){ r = mid; }else{ l = mid + 1; } } if(nums[r] + nums[i] == target){ ans.push_back(nums[r]); ans.push_back(nums[i]); break; } } return ans; } }; int main(){ Solution* s = new Solution(); return 0; }
d175025924c7c2f006af0181f4355404a0705c2b
b77b470762df293be67877b484bb53b9d87b346a
/game/CameraRenderer.h
d03201c6d98f65c76ea65449c9a8528eeadb5800
[ "BSD-3-Clause" ]
permissive
Sheph/af3d
9b8b8ea41f4e439623116d70d14ce5f1ee1fae25
4697fbc5f9a5cfb5d54b06738de9dc44b9f7755f
refs/heads/master
2023-08-28T16:41:43.989585
2021-09-11T19:09:45
2021-09-11T19:09:45
238,231,399
1
1
null
null
null
null
UTF-8
C++
false
false
3,992
h
CameraRenderer.h
/* * Copyright (c) 2020, Stanislav Vorobiov * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _CAMERA_RENDERER_H_ #define _CAMERA_RENDERER_H_ #include "RenderTarget.h" #include "RenderPass.h" #include "RenderList.h" #include "af3d/AABB2.h" namespace af3d { class CameraRenderer : boost::noncopyable { public: CameraRenderer(); ~CameraRenderer() = default; inline int order() const { return order_; } inline void setOrder(int value) { order_ = value; } const AABB2i& viewport() const; void setViewport(const AABB2i& value); inline const AttachmentPoints& clearMask() const { return clearMask_; } inline void setClearMask(const AttachmentPoints& value) { clearMask_ = value; } inline const AttachmentColors& clearColors() const { return clearColors_; } inline const Color& clearColor(AttachmentPoint attachmentPoint = AttachmentPoint::Color0) const { return clearColors_[static_cast<int>(attachmentPoint)]; } inline void setClearColor(AttachmentPoint attachmentPoint, const Color& value) { clearColors_[static_cast<int>(attachmentPoint)] = value; } inline const RenderTarget& renderTarget(AttachmentPoint attachmentPoint = AttachmentPoint::Color0) const { return renderTarget_[static_cast<int>(attachmentPoint)]; } inline void setRenderTarget(AttachmentPoint attachmentPoint, const RenderTarget& value) { renderTarget_[static_cast<int>(attachmentPoint)] = value; } void addRenderPass(const RenderPassPtr& pass, bool run = true); void setAutoParams(const RenderList& rl, const RenderList::Geometry& geom, std::uint32_t outputMask, std::vector<HardwareTextureBinding>& textures, std::vector<StorageBufferBinding>& storageBuffers, MaterialParams& params) const; void setAutoParams(const RenderList& rl, const MaterialPtr& material, std::uint32_t outputMask, std::vector<HardwareTextureBinding>& textures, std::vector<StorageBufferBinding>& storageBuffers, MaterialParams& params, const Matrix4f& modelMat = Matrix4f::getIdentity(), const Matrix4f& prevModelMat = Matrix4f::getIdentity()) const; RenderNodePtr compile(const RenderList& rl) const; private: HardwareMRT getHardwareMRT() const; int order_ = 0; mutable AABB2i viewport_ = AABB2i(Vector2i(0, 0), Vector2i(0, 0)); AttachmentPoints clearMask_ = AttachmentPoints(AttachmentPoint::Color0) | AttachmentPoint::Depth; AttachmentColors clearColors_; std::array<RenderTarget, static_cast<int>(AttachmentPoint::Max) + 1> renderTarget_; RenderPasses passes_; }; } #endif
b0e2318777db5ead7ebdb578bc746768f4ea67b5
43221ffd2d148583095f37eb655b395cd20aa849
/Person.h
54e332ade69f91e027660a533154224cd5ee32ed
[]
no_license
lblack1/cpsc350-BSTDB
18940570ee164f505ccb60c9f721c339438f78f9
2a527ae522297b90f13fae65313716ce5466a189
refs/heads/master
2020-09-21T01:19:43.044056
2019-11-28T19:27:47
2019-11-28T19:27:47
224,638,740
0
0
null
null
null
null
UTF-8
C++
false
false
897
h
Person.h
#ifndef PERSON #define PERSON #include <iostream> #include <fstream> #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> using namespace std; /* Base class for faculty and student records. */ class Person { public: Person(); Person(unsigned int i, string n, string l); unsigned int GetID(); void SetID(unsigned int i); string GetName(); void SetName(string n); string GetLevel(); void SetLevel(string l); virtual string ToString(); bool operator < (Person p); bool operator > (Person p); bool operator == (Person p); protected: unsigned int id; string name; string level; private: friend class boost::serialization::access; template <typename Archive> void serialize(Archive& ar, const unsigned version) { ar & id; ar & name; ar & level; } }; #endif
3a8e865959114649b499da1c0989d51a8fee6a42
0e7284482c70cf7ab72011dbe22c619817d41eeb
/bitstream.h
038751a36b7621c7df12a4f25f6516b067a7f1bd
[]
no_license
the-goodies/library
d4ac383a1bd2467102ba9865d202301abab2a0dc
a72527bc0e900bb876fb8a533cd2dc5595be0cc0
refs/heads/master
2021-05-04T04:02:00.262521
2017-04-17T18:28:01
2017-04-17T18:28:01
70,840,231
0
0
null
null
null
null
UTF-8
C++
false
false
6,732
h
bitstream.h
#ifndef _bitstream_h #define _bitstream_h #include <fstream> #include "utility.h" /* Defines a classes for reading and writing one bit at a time to a stream * which is associated with provided file since fstream doesn't provide this functionality * * Other than reading/writing bits, also provide this additional functionality: * read/write byte, get stream size and rewind input stream to beginning for reading again * read/write bit and byte are done in raw binary format, no formating is done * * Besides this limited functionality everything else ir restricted: * doesn't support standard << >> stream operators, everything is done through provided methods */ static const s32 BITS_IN_BYTE = 8; // returns the next bit from index position within a byte static inline s32 getBit(s32 byte, s32 index) { return (byte & (1 << index)) != 0; } // sets bit to one in index position within a byte static inline void setBit(s32 & byte, s32 index) { byte |= (1 << index); } class ifbitstream { std::ifstream file; // stream buffer s32 byte; // value of current byte s32 index; // bit position within a byte public: ifbitstream() { /* empty */ } ifbitstream(const char* filename): file(filename, std::fstream::binary | std::fstream::in) { this->byte = 0; this->index = BITS_IN_BYTE; // so that the next read will trigger to get the first byte } void open(const char* filename) { this->byte = 0; this->index = BITS_IN_BYTE; // so that the next read will trigger to get the first byte file.open(filename, std::fstream::binary | std::fstream::in); } bool is_open() { return file.is_open(); } void close() { file.close(); } // returns next bit within a stream, -1 (EOF) if stream has reached the end s32 readBit() { if (!file.is_open()) ERROR("ifbitstream: can't read a bit from a stream not associated with a file"); // get the next byte if (index == BITS_IN_BYTE) { if ((byte = file.get()) == EOF) return EOF; index = 0; } // return next bit and advance bit position return getBit(byte, index++); } // returns next byte within a stream, -1 (EOF) if stream has reached the end // if stream has only 1-7 bits left then return those instead of EOF, next read of bit or byte will return EOF s32 readByte() { if (!file.is_open()) ERROR("ifbitstream: can't read a bit from a stream not associated with a file"); if (index == BITS_IN_BYTE) return file.get(); // get remaining bits from this byte s32 result = byte >> index; // and the rest from the next byte if ((byte = file.get()) != EOF) result |= ((byte & ((1 << index) - 1)) << (BITS_IN_BYTE - index)); else this->index = BITS_IN_BYTE; return result; } // returns a s64 value of only first 4 bytes being valid from stream // a s64 not u32 is chosen, so that -1 (EOF) could be returned // so a client must use s64 type to receive those 4 bytes, otherwise if s32 type is used and // method returns (2^31 - 1) (all 32bits set to one): which is still valid 4 byte value, // will get interpreted as -1 (EOF) by truncating to type s32 and falsely indicating the EOF // just like with readByte() if stream has only 1-31 bits left then return those instead of EOF s64 readFourBytes() { s64 bytes = 0; for (s32 offset = 0; offset < 4; ++offset) { s64 byte = readByte(); if (byte == EOF && offset == 0) return EOF; else if (byte == EOF) break; bytes |= byte << (8*offset); } return bytes; } // rewinds read stream to beginning void rewind() { if (!file.is_open()) ERROR("ifbitstream: can't rewind to beggining of a stream not associated with a file"); // clear incase file was allready in eof state, otherwise seekg won't work file.clear(); file.seekg(0, std::fstream::beg); } // returns the size of the stream in bytes u32 size() { if (!file.is_open()) ERROR("ifbitstream: can't get a size of a stream not associated with a file"); file.clear(); std::streampos pos = file.tellg(); file.seekg(0, std::fstream::end); std::streampos end = file.tellg(); file.seekg(pos); return end; } }; class ofbitstream { std::ofstream file; // stream buffer s32 byte; // value of current byte s32 index; // bit position within a byte public: ofbitstream() { /* empty */ } ofbitstream(const char* filename) { this->byte = 0; this->index = BITS_IN_BYTE; // so that the next read will trigger to get the first byte file.open(filename, std::fstream::binary | std::fstream::out); } void open(const char* filename) { this->byte = 0; this->index = BITS_IN_BYTE; // so that the next read will trigger to get the first byte file.open(filename, std::fstream::binary | std::fstream::out); } bool is_open() { return file.is_open(); } void close() { file.close(); } // writes given bit to the stream void writeBit(bool bit) { if (!file.is_open()) ERROR("ofbitstream: can't write a bit to a stream not associated with a file"); if (index == BITS_IN_BYTE) { byte = 0; index = 0; } // if bit is 1, then set approriate bit position to 1 // otherwhise skip since it allready has 0 there by default if (bit) setBit(byte, index); // if index is 0, then put the new byte to a stream, otherwhise overwrite last byte if (index == 0) file.put(byte); else if (bit) { file.seekp(-1, std::fstream::cur); file.put(byte); } ++index; // advance bit position } // writes a given byte to a stream // unsigned char is essential, otherwhise some bitwise operations might not work, for example: // if byte is 0b11111111 and num is any number, then (byte >> num) will return byte unchanged (0b11111111) void writeByte(u8 byte) { if (!file.is_open()) ERROR("ofbitstream: can't write a byte to a stream not associated with a file"); if (index == BITS_IN_BYTE) { file.put(byte); return; } // fill the remaining of this->byte and overwrite the last byte in a stream with it this->byte |= ((byte & ((1 << (BITS_IN_BYTE - index)) - 1)) << index); file.seekp(-1, std::fstream::cur); file.put(this->byte); // put the rest of bits to a new byte and put it in a stream this->byte = (byte >> (BITS_IN_BYTE - index)); file.put(this->byte); } // writes 4 bytes to a stream from a given u32 value void writeFourBytes(u32 bytes) { for (s32 offset = 0; offset < 4; ++offset) { u8 byte = *((u8*)&bytes + offset); writeByte(byte); } } // returns the size of the stream in bytes u32 size() { if (!file.is_open()) ERROR("ofbitstream: can't get a size of a stream not associated with a file"); file.clear(); std::streampos pos = file.tellp(); file.seekp(0, std::fstream::end); std::streampos end = file.tellp(); file.seekp(pos); return end; } }; #endif