blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
bb1fea616f08072b738838a7ebe838c8142a2f30
ceea10d637d9fb08dc35dfa52702d952326a5a22
/Src/UPOEngine/Engine/UPrimitiveBatch.cpp
6584dcc026bc5d9a5bc6bb41409499749523e929
[]
no_license
UPO33/UPOEngine
d2c8594474ad60f80e15da46e791360aad652817
e720755d93b86b0dd5ef6a8d879284042c7aba0d
refs/heads/master
2020-09-27T01:21:30.674251
2017-03-03T07:48:43
2017-03-03T07:48:43
67,622,746
7
1
null
null
null
null
UTF-8
C++
false
false
8,592
cpp
#include "UPrimitiveBatch.h" #include "UGameWindow.h" #include "UHitSelection.h" #include "../GFX/UShaderConstants.h" #include "../Engine/UEngineBase.h" #include "../Engine/UWorld.h" namespace UPO { UGLOBAL_SHADER_DECLIMPL2(gVSPrimitiveBatch, GFXVertexShader, "WorldPrimitiveBatch.hlsl", "VSMain"); UGLOBAL_SHADER_DECLIMPL2(gPSPrimitiveBatch, GFXPixelShader, "WorldPrimitiveBatch.hlsl", "PSMain"); // UGLOBAL_SHADER_DECLIMPL2(gVSWireShpere, GFXVertexShader, "WorldPrimitiveBatch.hlsl", "VSWireSphere"); // UGLOBAL_SHADER_DECLIMPL2(gGSWireSphere, GFXGeometryShader, "WorldPrimitiveBatch.hlsl", "GSWireSphere"); // UGLOBAL_SHADER_DECLIMPL2(gVSWireCircle, GFXVertexShader, "WorldPrimitiveBatch.hlsl", "VSWireCircle"); // static const unsigned MaxLineInVertexBuffer = 8000; PrimitiveBatch::PrimitiveBatch(World* owner) { mOwner = owner; mDelta = 0; mHitProxy = nullptr; mGTLines = mLines + 0; mRTLines = mLines + 1; mRTMeshes = mMeshes + 0; mGTMeshes = mMeshes + 1; mGTSphere = mShperes + 0; mRTSphere = mShperes + 1; EnqueueRenderCommandAndWait([this]() { CreateRenderResoures(); }); } void PrimitiveBatch::DrawLine(const Vec3& point0, const Color32& color0, const Vec3& point1, const Color32& color1) { auto lines = GetGTLines(); auto index = lines->AddUnInit(2); LineVertex* vertices = lines->ElementAt(index); vertices[0].mPosition = point0; vertices[0].mColor = color0; vertices[0].mHitID = mHitProxyID; vertices[1].mPosition = point1; vertices[1].mColor = color1; vertices[1].mHitID = mHitProxyID; } void PrimitiveBatch::DrawLine(const Vec3& point0, const Vec3& point1, const Color32& color) { DrawLine(point0, color, point1, color); } void PrimitiveBatch::DrawWireBox(const Vec3& min, const Vec3& max, const Color32& color) { DrawLine(Vec3(min.mX, min.mY, min.mZ), color, Vec3(min.mX, max.mY, min.mZ), color); DrawLine(Vec3(max.mX, min.mY, min.mZ), color, Vec3(max.mX, max.mY, min.mZ), color); DrawLine(Vec3(max.mX, min.mY, max.mZ), color, Vec3(max.mX, max.mY, max.mZ), color); DrawLine(Vec3(min.mX, min.mY, max.mZ), color, Vec3(min.mX, max.mY, max.mZ), color); DrawLine(Vec3(min.mX, min.mY, min.mZ), color, Vec3(min.mX, min.mY, max.mZ), color); DrawLine(Vec3(min.mX, max.mY, min.mZ), color, Vec3(min.mX, max.mY, max.mZ), color); DrawLine(Vec3(max.mX, min.mY, min.mZ), color, Vec3(max.mX, min.mY, max.mZ), color); DrawLine(Vec3(max.mX, max.mY, min.mZ), color, Vec3(max.mX, max.mY, max.mZ), color); DrawLine(Vec3(min.mX, min.mY, min.mZ), color, Vec3(max.mX, min.mY, min.mZ), color); DrawLine(Vec3(min.mX, min.mY, max.mZ), color, Vec3(max.mX, min.mY, max.mZ), color); DrawLine(Vec3(min.mX, max.mY, min.mZ), color, Vec3(max.mX, max.mY, min.mZ), color); DrawLine(Vec3(min.mX, max.mY, max.mZ), color, Vec3(max.mX, max.mY, max.mZ), color); } void PrimitiveBatch::DrawWireBox(const Vec3& extent, const Transform& transform, const Color32& color) { } void PrimitiveBatch::DrawWireMesh(const AStaticMesh* mesh, const Transform& transform, const Color& color, float lifeTimeSeconds) { if (!mesh) return; USCOPE_LOCK(mSwapLock); auto meshes = GetGTMeshes(); meshes->AddUnInit(); auto& item = meshes->LastElement(); item.mMesh = mesh; item.mTransform = transform; item.mColor = color; item.mLifeTime = lifeTimeSeconds; } void PrimitiveBatch::DrawWireFrustum(const Matrix4& frustum, const Color32& color) { Vec3 fars[4]; Vec3 nears[4]; for (size_t i = 0; i < 4; i++) { const Vec2 coords[] = { Vec2(-1, 1), Vec2(1, 1), Vec2(1, -1), Vec2(-1, -1) }; Vec4 vFar = frustum.TransformVec4(Vec4(coords[i], Vec2(1, 1))); Vec4 vNear = frustum.TransformVec4(Vec4(coords[i], Vec2(0, 1))); fars[i] = Vec3(vFar) / vFar.mW; nears[i] = Vec3(vNear) / vNear.mW; } for (size_t i = 0; i < 4; i++) { DrawLine(fars[i], fars[(i + 1) % 4], color); DrawLine(nears[i], nears[(i + 1) % 4], color); DrawLine(nears[i], fars[i], color); } } void PrimitiveBatch::DrawWireSphere(const Vec3& position, float radius, Color32 color) { DrawCircle(position, radius, color, Vec3(1, 0, 0), Vec3(0, 0, 1)); DrawCircle(position, radius, color, Vec3(1, 0, 0), Vec3(0, 1, 0)); DrawCircle(position, radius, color, Vec3(0, 0, 1), Vec3(0, 1, 0)); } void PrimitiveBatch::CreateRenderResoures() { UASSERT(IsRenderThread()); //vertex buffer { GFXVertexBufferDesc vbdesc; vbdesc.mSize = MaxLineInVertexBuffer * sizeof(LineVertex[2]); vbdesc.mDynamic = true; mLinesBuffer = gGFX->CreateVertexBuffer(vbdesc); UASSERT(mLinesBuffer); } //input layout { GFXInputLayoutDesc ild = { gVSPrimitiveBatch->Get(ShaderConstantsCombined()), { GFXVertexElementDesc("POSITION", EVertexFormat::EFloat3), GFXVertexElementDesc("COLOR", EVertexFormat::EColor32), GFXVertexElementDesc("HITID", EVertexFormat::EUInt32), }, }; mInputLayout = GlobalResources::GetInputLayout(ild); UASSERT(mInputLayout); } { // GFXInputLayoutDesc desc = // { // gVSWireShpere->Get(ShaderConstantsCombined()), // { // GFXVertexElementDesc("POSITION", EVertexFormat::EFloat3), // GFXVertexElementDesc("RADIUS", EVertexFormat::EFloat1), // GFXVertexElementDesc("COLOR", EVertexFormat::EColor32), // GFXVertexElementDesc("HITID", EVertexFormat::EUInt32) // }, // }; // // mILWireSphere = gGFX->CreateInputLayout(desc); // UASSERT(mILWireSphere); } //cbuffer { mConstantBuffer = gGFX->CreateConstantBuffer(sizeof(Matrix4)); UASSERT(mConstantBuffer); } } void PrimitiveBatch::DrawCircle(const Vec3& position, float radius, Color32 color, const Vec3& xAxis, const Vec3& zAxis) { float ss, cc; SinCosDeg(0, ss, cc); Vec3 v1 = position + (xAxis * ss * radius) + (zAxis * cc * radius); for (size_t i = 1; i <= 40; i++) { const float f = 360.0 / 40; SinCosDeg(i * f, ss, cc); Vec3 v2 = position + (xAxis * ss * radius) + (zAxis * cc * radius); DrawLine(v1, v2, color); v1 = v2; } } void PrimitiveBatch::Tick(float delta) { } void PrimitiveBatch::Render() { UASSERT(IsRenderThread()); LineVertexArray* vertices = GetRTLines(); unsigned numVertex = vertices->Length(); if (numVertex == 0) return; //update vertex buffer { void* ptrMapped = gGFX->Map(mLinesBuffer, EMapFlag::EWriteDiscard); MemCopy(ptrMapped, vertices->Elements(), sizeof(LineVertex) * numVertex); gGFX->Unmap(mLinesBuffer); vertices->RemoveAll(); } gGFX->SetBlendState(nullptr); gGFX->SetVertexBuffer(mLinesBuffer, 0, sizeof(LineVertex), 0); gGFX->SetIndexBuffer(nullptr); gGFX->SetInputLayout(mInputLayout); //selecting shader ShaderConstantsCombined sc; if (mOwner->GetGameWindow()->GetHitSelection()) sc |= ShaderConstants::USE_HITSELECTION; gGFX->SetShaders(gVSPrimitiveBatch->Get(sc), nullptr, nullptr, nullptr, gPSPrimitiveBatch->Get(sc)); gGFX->SetPrimitiveTopology(EPrimitiveTopology::ELineList); gGFX->Draw(numVertex); // for(size_t i = 0; i < mRTSphere->Length(); i++) // { // gGFX->SetInputLayout(mILWireSphere); // gGFX->SetIndexBuffer(nullptr); // { // auto mapped = gGFX->Map<ShpereItem>(mLinesBuffer, EMapFlag::EWriteDiscard); // *mapped = *mRTSphere->ElementAt(i); // gGFX->Unmap(mLinesBuffer); // } // gGFX->SetVertexBuffer(mLinesBuffer, 0, sizeof(ShpereItem)); // gGFX->SetShaders(gVSWireShpere->Get(sc), nullptr, nullptr, gGSWireSphere->Get(sc), gPSPrimitiveBatch->Get(sc)); // gGFX->SetPrimitiveTopology(EPrimitiveTopology::EPointList); // gGFX->Draw(1); // } // // mRTSphere->RemoveAll(); { StaticMeshItemArray* meshes = GetRTMeshes(); ///////////////////////// meshes if (meshes->Length()) { for (auto& mesh : *meshes) { //draw... } float delta = mDelta; mMeshes->RemoveIf([delta](StaticMeshItem& item) { item.mLifeTime -= delta; return (item.mLifeTime <= 0); }); } } } PrimitiveBatch::~PrimitiveBatch() { EnqueueRenderCommandAndWait([this]() { SafeDelete(mLinesBuffer); SafeDelete(mConstantBuffer); }); } void PrimitiveBatch::Swap() { UPO::Swap(mGTLines, mRTLines); UPO::Swap(mGTSphere, mRTSphere); { *mRTMeshes += *mGTMeshes; mGTMeshes->RemoveAll(); } } void PrimitiveBatch::SetHitProxy(HPBaseRef hp) { mHitProxy = hp; mHitProxyID = mOwner->GetGameWindow()->GetHitSelection()->RegisterProxy(mHitProxy); } HPBase* PrimitiveBatch::GetHitProxy() const { return mHitProxy; } };
[ "abc0d3r@gmail.com" ]
abc0d3r@gmail.com
919ded3ca87c30dd3c25dd149d0035665a8d4640
c3a764ee087e05236f000e2c1d8d29abf46095b5
/src/engine/Sound.cpp
b97f3a26ed8c950c42a160872b612e08f3852b89
[]
no_license
emurdock1101/The-Dashing-Mr-Jones
4a8e41c948712b8b222cf2bbb5ec08bed29598bb
2821121a215f799f1aa9b78935e7acd2d163d71d
refs/heads/master
2022-11-19T21:21:14.008326
2020-07-20T16:29:32
2020-07-20T16:29:32
281,137,169
0
0
null
null
null
null
UTF-8
C++
false
false
414
cpp
#include "Sound.h" #include <SDL2/SDL_mixer.h> #include <iostream> using namespace std; Sound::Sound() { } Sound::~Sound() { } void Sound::playSFX(string soundFilePath) { Mix_Chunk *sound = Mix_LoadWAV(soundFilePath.c_str()); Mix_PlayChannel( -1, sound, 0 ); } void Sound::playMusic(string soundFilePath) { Mix_Music *music = Mix_LoadMUS(soundFilePath.c_str()); Mix_PlayMusic(music, -1); }
[ "eh7bu@virginia.edu" ]
eh7bu@virginia.edu
62292f008370855587a3ae41f4f8bcd516aff7ff
6680f8d317de48876d4176d443bfd580ec7a5aef
/misViewer/misUpdateLandmarkCameraView.cpp
38203d3b8d7c3d6b2183c72ad0f4d2d220952c00
[]
no_license
AlirezaMojtabavi/misInteractiveSegmentation
1b51b0babb0c6f9601330fafc5c15ca560d6af31
4630a8c614f6421042636a2adc47ed6b5d960a2b
refs/heads/master
2020-12-10T11:09:19.345393
2020-03-04T11:34:26
2020-03-04T11:34:26
233,574,482
3
0
null
null
null
null
UTF-8
C++
false
false
1,334
cpp
#include "stdafx.h" #include "misUpdateLandmarkCameraView.h" #include "misCamera.h" #include "BusinessEntities\Point.h" #include "CameraPositionCalculator.h" #include "CameraPositionCalculatorFactory.h" #include "misApplicationSetting.h" misUpdateLandmarkCameraView::misUpdateLandmarkCameraView(std::shared_ptr<I3DViewer> viewer, double landmarkLableCameraDistance) : m_Viewer(viewer), m_LandmarkLableCameraDistance(landmarkLableCameraDistance) { } void misUpdateLandmarkCameraView::Update(itk::BoundingBox<double, 3, double>::Pointer boundingBox, std::shared_ptr<ILandmarkPointerRepresentation> landmark) { if (!landmark->IsValid()) { return; } const auto cameraPosCalc = parcast::CameraPositionCalculatorFactory::Create(parcast::PointD3(boundingBox->GetMinimum().GetDataPointer()), parcast::PointD3(boundingBox->GetMaximum().GetDataPointer()), m_LandmarkLableCameraDistance, misApplicationSetting::GetInstance()->m_WorkflowButtonSet); double position[3]; landmark->GetPosition(position); auto cameraPosition = cameraPosCalc->GetCameraPosition(parcast::PointD3(position)); auto camera = m_Viewer->GetRenderer()->GetActiveCamera(); camera->SetPosition(cameraPosition.Elements()); camera->SetFocalPoint(position); camera->SetViewUp(0.0, 0.0, -1.0); }
[ "alireza_mojtabavi@yahoo.com" ]
alireza_mojtabavi@yahoo.com
6cdb697dfbd80eb289d57e8f0025549b1f70c890
3d616f0c7b350bf9755f257f13f9a787cfdae31f
/bj_에너지모으기.cpp
338f193c13be01731f1ba6e112f3b257fa871d90
[]
no_license
wjdgur778/BJ_Algorithm
89ba4db177af5f9a253b45d8e78da82297586c71
e10498bdb7e69e59e6fcbfab58f3b40e05df1ded
refs/heads/master
2023-05-09T01:19:31.163652
2021-05-30T09:56:33
2021-05-30T09:56:33
347,317,995
0
0
null
null
null
null
UHC
C++
false
false
774
cpp
#include<iostream> #include<vector> using namespace std; int n; vector<int>vec; vector<bool>check(10, false); long long answer = 0; //빠지는 과정 //8! 중에 가장 큰거 //backtracking //brute force long long calc(int i) { int l = i; int r = i; while (check[--l] == true); while (check[++r] == true); long long sum = vec[l] * vec[r]; return sum; } void dfs(int n, int cnt, long long sum) { if (n - 2 == cnt) { answer = answer <= sum ? sum : answer; return; } for (int i = 1; i < n - 1; i++) { if (check[i] == true)continue; check[i] = true; dfs(n, cnt + 1,sum+ calc(i)); check[i] = false; } } int main() { cin >> n; for (int i = 0; i < n; i++) { int a; cin >> a; vec.push_back(a); } dfs(vec.size(), 0, 0); cout << answer; return 0; }
[ "wjdgur778@gmail.com" ]
wjdgur778@gmail.com
faa6eebe6096b8b76f5293b944b300d7355db2df
ad273708d98b1f73b3855cc4317bca2e56456d15
/aws-cpp-sdk-ram/include/aws/ram/model/RejectResourceShareInvitationRequest.h
fa0c9a326c8a889988782bf49371bb0d8e9657ab
[ "MIT", "Apache-2.0", "JSON" ]
permissive
novaquark/aws-sdk-cpp
b390f2e29f86f629f9efcf41c4990169b91f4f47
a0969508545bec9ae2864c9e1e2bb9aff109f90c
refs/heads/master
2022-08-28T18:28:12.742810
2020-05-27T15:46:18
2020-05-27T15:46:18
267,351,721
1
0
Apache-2.0
2020-05-27T15:08:16
2020-05-27T15:08:15
null
UTF-8
C++
false
false
5,483
h
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/ram/RAM_EXPORTS.h> #include <aws/ram/RAMRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace RAM { namespace Model { /** */ class AWS_RAM_API RejectResourceShareInvitationRequest : public RAMRequest { public: RejectResourceShareInvitationRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "RejectResourceShareInvitation"; } Aws::String SerializePayload() const override; /** * <p>The Amazon Resource Name (ARN) of the invitation.</p> */ inline const Aws::String& GetResourceShareInvitationArn() const{ return m_resourceShareInvitationArn; } /** * <p>The Amazon Resource Name (ARN) of the invitation.</p> */ inline bool ResourceShareInvitationArnHasBeenSet() const { return m_resourceShareInvitationArnHasBeenSet; } /** * <p>The Amazon Resource Name (ARN) of the invitation.</p> */ inline void SetResourceShareInvitationArn(const Aws::String& value) { m_resourceShareInvitationArnHasBeenSet = true; m_resourceShareInvitationArn = value; } /** * <p>The Amazon Resource Name (ARN) of the invitation.</p> */ inline void SetResourceShareInvitationArn(Aws::String&& value) { m_resourceShareInvitationArnHasBeenSet = true; m_resourceShareInvitationArn = std::move(value); } /** * <p>The Amazon Resource Name (ARN) of the invitation.</p> */ inline void SetResourceShareInvitationArn(const char* value) { m_resourceShareInvitationArnHasBeenSet = true; m_resourceShareInvitationArn.assign(value); } /** * <p>The Amazon Resource Name (ARN) of the invitation.</p> */ inline RejectResourceShareInvitationRequest& WithResourceShareInvitationArn(const Aws::String& value) { SetResourceShareInvitationArn(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of the invitation.</p> */ inline RejectResourceShareInvitationRequest& WithResourceShareInvitationArn(Aws::String&& value) { SetResourceShareInvitationArn(std::move(value)); return *this;} /** * <p>The Amazon Resource Name (ARN) of the invitation.</p> */ inline RejectResourceShareInvitationRequest& WithResourceShareInvitationArn(const char* value) { SetResourceShareInvitationArn(value); return *this;} /** * <p>A unique, case-sensitive identifier that you provide to ensure the * idempotency of the request.</p> */ inline const Aws::String& GetClientToken() const{ return m_clientToken; } /** * <p>A unique, case-sensitive identifier that you provide to ensure the * idempotency of the request.</p> */ inline bool ClientTokenHasBeenSet() const { return m_clientTokenHasBeenSet; } /** * <p>A unique, case-sensitive identifier that you provide to ensure the * idempotency of the request.</p> */ inline void SetClientToken(const Aws::String& value) { m_clientTokenHasBeenSet = true; m_clientToken = value; } /** * <p>A unique, case-sensitive identifier that you provide to ensure the * idempotency of the request.</p> */ inline void SetClientToken(Aws::String&& value) { m_clientTokenHasBeenSet = true; m_clientToken = std::move(value); } /** * <p>A unique, case-sensitive identifier that you provide to ensure the * idempotency of the request.</p> */ inline void SetClientToken(const char* value) { m_clientTokenHasBeenSet = true; m_clientToken.assign(value); } /** * <p>A unique, case-sensitive identifier that you provide to ensure the * idempotency of the request.</p> */ inline RejectResourceShareInvitationRequest& WithClientToken(const Aws::String& value) { SetClientToken(value); return *this;} /** * <p>A unique, case-sensitive identifier that you provide to ensure the * idempotency of the request.</p> */ inline RejectResourceShareInvitationRequest& WithClientToken(Aws::String&& value) { SetClientToken(std::move(value)); return *this;} /** * <p>A unique, case-sensitive identifier that you provide to ensure the * idempotency of the request.</p> */ inline RejectResourceShareInvitationRequest& WithClientToken(const char* value) { SetClientToken(value); return *this;} private: Aws::String m_resourceShareInvitationArn; bool m_resourceShareInvitationArnHasBeenSet; Aws::String m_clientToken; bool m_clientTokenHasBeenSet; }; } // namespace Model } // namespace RAM } // namespace Aws
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
c04a14ba324b4c0e45acb86536a7940364897f7b
c90d5fc83708666b304b599f49870e160085bfd0
/Compilator/Token.h
dec0239ba2d665d9e79346b1c475928982390aca
[]
no_license
PolyakovDmitry546/Compilator
22b0509f5e9cee91bdf45f0a730ba83162f3d2b8
77811bf2985797a02c13ac08e0bc59cbb47dc874
refs/heads/master
2023-04-10T01:47:38.629448
2021-04-25T19:10:21
2021-04-25T19:10:21
361,512,151
0
0
null
null
null
null
UTF-8
C++
false
false
988
h
#pragma once #include<string> #include"Variant.h" using namespace std; enum ETokenType { ident, operand, value }; enum EOperand { star, slash, equal, comma, semicolon, colon, point, arrow, leftpar, rightpar, lbracket, rbracket, flpar, frpar, later, greater, laterequal, greaterequal, latergreater, plus, minus, lcomment, rcomment, assign, twopoints, identsy, floatc, intc, charc, casesy, elsesy, filesy, gotosy, thensy, typesy, untilsy, dosy, withsy, ifsy, ofsy, orsy, insy, tosy, endsy, varsy, divsy, andsy, notsy, forsy, modsy, nilsy, setsy, beginsy, whilesy, arraysy, constsy, labelsy, downtosy, packedsy, recordsy, repeatsy, programsy, functionsy, proceduresy, apostrophe }; class CToken { public: ETokenType m_type; union { EOperand m_op; CVariant* m_val; }; string m_ident; CToken(EOperand oper, string ident); CToken(CVariant* val); CToken(string ident); ~CToken(); string ToString() const; };
[ "polyakov1803@gmail.com" ]
polyakov1803@gmail.com
ca2d2ecd9fdb582407686ed1911d36afbebf7057
891605c2226f152f97f88abc22f8c666dfc6d6cd
/arduino/Sensors/Reset_Message_Sketch/Reset_Message_Sketch.ino
7ee587f028131fe7dc47e710e0c7e7a11bdec6b1
[]
no_license
tlavastida/EE4820
141e331844a581569cbb50d8c45eacdfae210f31
0ba34b27da741c1e410471b503165de6a6f492a3
refs/heads/master
2021-01-21T13:07:36.352402
2016-04-28T05:19:07
2016-04-28T05:19:07
50,361,278
0
0
null
null
null
null
UTF-8
C++
false
false
215
ino
void setup() { // put your setup code here, to run once: Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: Serial.println("I have been reset"); delay(1000); }
[ "ninjasteve1@live.com" ]
ninjasteve1@live.com
9f136e7d0879bb3d3f780f9cf8e490d881be6db5
10854fab019a83ad29f4e16fe45616720c95d75b
/RayTracingGems-VolumePT/main.cpp
5590ab545c63124577128108a15170344b1215f2
[]
no_license
Woking-34/daedalus-playground
2e928e95f371196d039e035ef035a90ad468c5e5
41a884194aa8b42e1aa2ecbc76e71b1390e085ba
refs/heads/master
2021-06-16T03:35:19.755817
2021-05-29T10:52:44
2021-05-29T10:52:44
175,941,574
8
5
null
null
null
null
UTF-8
C++
false
false
15,981
cpp
// // Small interactive application running the volume path tracer // #include <GL/glew.h> #include <GLFW/glfw3.h> #include <cuda_runtime.h> #include <cuda_gl_interop.h> #include <vector_functions.h> #define _USE_MATH_DEFINES #include <cmath> #include <cstdlib> #include <cstdio> #include <cstring> #include <algorithm> #include "hdr_loader.h" #include "volume_kernel.h" #define check_success(expr) \ do { \ if(!(expr)) { \ fprintf(stderr, "Error in file %s, line %u: \"%s\".\n", __FILE__, __LINE__, #expr); \ exit(EXIT_FAILURE); \ } \ } while(false) // Initialize GLFW and GLEW. static GLFWwindow *init_opengl() { check_success(glfwInit()); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); GLFWwindow *window = glfwCreateWindow( 1024, 1024, "volume path tracer", NULL, NULL); if (!window) { fprintf(stderr, "Error creating OpenGL window.\n");; glfwTerminate(); } glfwMakeContextCurrent(window); glewExperimental = GL_TRUE; const GLenum res = glewInit(); if (res != GLEW_OK) { fprintf(stderr, "GLEW error: %s.\n", glewGetErrorString(res)); glfwTerminate(); } glfwSwapInterval(0); while (glGetError() != GL_NO_ERROR) {} return window; } // Initialize CUDA with OpenGL interop. static void init_cuda() { int cuda_devices[1]; unsigned int num_cuda_devices; check_success(cudaGLGetDevices(&num_cuda_devices, cuda_devices, 1, cudaGLDeviceListAll) == cudaSuccess); if (num_cuda_devices == 0){ fprintf(stderr, "Could not determine CUDA device for current OpenGL context\n."); exit(EXIT_FAILURE); } check_success(cudaSetDevice(cuda_devices[0]) == cudaSuccess); } // Utility: add a GLSL shader. static void add_shader(GLenum shader_type, const char *source_code, GLuint program) { GLuint shader = glCreateShader(shader_type); check_success(shader); glShaderSource(shader, 1, &source_code, NULL); glCompileShader(shader); GLint success; glGetShaderiv(shader, GL_COMPILE_STATUS, &success); check_success(success); glAttachShader(program, shader); check_success(glGetError() == GL_NO_ERROR); } // Create a simple GL program with vertex and fragement shader for texture lookup. static GLuint create_shader_program() { GLint success; GLuint program = glCreateProgram(); const char *vert = "#version 330\n" "in vec3 Position;\n" "out vec2 TexCoord;\n" "void main() {\n" " gl_Position = vec4(Position, 1.0);\n" " TexCoord = 0.5 * Position.xy + vec2(0.5);\n" "}\n"; add_shader(GL_VERTEX_SHADER, vert, program); const char *frag = "#version 330\n" "in vec2 TexCoord;\n" "out vec4 FragColor;\n" "uniform sampler2D TexSampler;\n" "void main() {\n" " FragColor = texture(TexSampler, TexCoord);\n" "}\n"; add_shader(GL_FRAGMENT_SHADER, frag, program); glLinkProgram(program); glGetProgramiv(program, GL_LINK_STATUS, &success); if (!success) { fprintf(stderr, "Error linking shadering program\n"); glfwTerminate(); } glUseProgram(program); check_success(glGetError() == GL_NO_ERROR); return program; } // Create a quad filling the whole screen. static GLuint create_quad(GLuint program, GLuint* vertex_buffer) { static const float3 vertices[6] = { { -1.f, -1.f, 0.0f }, { 1.f, -1.f, 0.0f }, { -1.f, 1.f, 0.0f }, { 1.f, -1.f, 0.0f }, { 1.f, 1.f, 0.0f }, { -1.f, 1.f, 0.0f } }; glGenBuffers(1, vertex_buffer); glBindBuffer(GL_ARRAY_BUFFER, *vertex_buffer); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); GLuint vertex_array = 0; glGenVertexArrays(1, &vertex_array); glBindVertexArray(vertex_array); const GLint pos_index = glGetAttribLocation(program, "Position"); glEnableVertexAttribArray(pos_index); glVertexAttribPointer( pos_index, 3, GL_FLOAT, GL_FALSE, sizeof(float3), 0); check_success(glGetError() == GL_NO_ERROR); return vertex_array; } // Context structure for window callback functions. struct Window_context { int zoom_delta; bool moving; double move_start_x, move_start_y; double move_dx, move_dy; float exposure; unsigned int config_type; }; // GLFW scroll callback. static void handle_scroll(GLFWwindow *window, double xoffset, double yoffset) { Window_context *ctx = static_cast<Window_context *>(glfwGetWindowUserPointer(window)); if (yoffset > 0.0) ctx->zoom_delta = 1; else if (yoffset < 0.0) ctx->zoom_delta = -1; } // GLFW keyboard callback. static void handle_key(GLFWwindow *window, int key, int scancode, int action, int mods) { if (action == GLFW_PRESS) { Window_context *ctx = static_cast<Window_context *>(glfwGetWindowUserPointer(window)); switch (key) { case GLFW_KEY_ESCAPE: glfwSetWindowShouldClose(window, GLFW_TRUE); break; case GLFW_KEY_KP_SUBTRACT: case GLFW_KEY_LEFT_BRACKET: ctx->exposure--; break; case GLFW_KEY_KP_ADD: case GLFW_KEY_RIGHT_BRACKET: ctx->exposure++; break; case GLFW_KEY_SPACE: ++ctx->config_type; default: break; } } } // GLFW mouse button callback. static void handle_mouse_button(GLFWwindow *window, int button, int action, int mods) { Window_context *ctx = static_cast<Window_context *>(glfwGetWindowUserPointer(window)); if (button == GLFW_MOUSE_BUTTON_LEFT) { if (action == GLFW_PRESS) { ctx->moving = true; glfwGetCursorPos(window, &ctx->move_start_x, &ctx->move_start_y); } else ctx->moving = false; } } // GLFW mouse position callback. static void handle_mouse_pos(GLFWwindow *window, double xpos, double ypos) { Window_context *ctx = static_cast<Window_context *>(glfwGetWindowUserPointer(window)); if (ctx->moving) { ctx->move_dx += xpos - ctx->move_start_x; ctx->move_dy += ypos - ctx->move_start_y; ctx->move_start_x = xpos; ctx->move_start_y = ypos; } } // Resize OpenGL and CUDA buffers for a given resolution. static void resize_buffers( float3 **accum_buffer_cuda, cudaGraphicsResource_t *display_buffer_cuda, int width, int height, GLuint display_buffer) { glBindBuffer(GL_PIXEL_UNPACK_BUFFER, display_buffer); glBufferData(GL_PIXEL_UNPACK_BUFFER, width * height * 4, NULL, GL_DYNAMIC_COPY); glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); check_success(glGetError() == GL_NO_ERROR); if (*display_buffer_cuda) check_success(cudaGraphicsUnregisterResource(*display_buffer_cuda) == cudaSuccess); check_success( cudaGraphicsGLRegisterBuffer( display_buffer_cuda, display_buffer, cudaGraphicsRegisterFlagsWriteDiscard) == cudaSuccess); if (*accum_buffer_cuda) check_success(cudaFree(*accum_buffer_cuda) == cudaSuccess); check_success(cudaMalloc(accum_buffer_cuda, width * height * sizeof(float3)) == cudaSuccess); } // Create enviroment texture. static bool create_environment( cudaTextureObject_t *env_tex, cudaArray_t *env_tex_data, const char *envmap_name) { unsigned int rx, ry; float *pixels; if (!load_hdr_float4(&pixels, &rx, &ry, envmap_name)) { fprintf(stderr, "error loading environment map file %s\n", envmap_name); return false; } const cudaChannelFormatDesc channel_desc = cudaCreateChannelDesc<float4>(); check_success(cudaMallocArray(env_tex_data, &channel_desc, rx, ry) == cudaSuccess); check_success(cudaMemcpyToArray( *env_tex_data, 0, 0, pixels, rx * ry * sizeof(float4), cudaMemcpyHostToDevice) == cudaSuccess); cudaResourceDesc res_desc; memset(&res_desc, 0, sizeof(res_desc)); res_desc.resType = cudaResourceTypeArray; res_desc.res.array.array = *env_tex_data; cudaTextureDesc tex_desc; memset(&tex_desc, 0, sizeof(tex_desc)); tex_desc.addressMode[0] = cudaAddressModeWrap; tex_desc.addressMode[1] = cudaAddressModeClamp; tex_desc.addressMode[2] = cudaAddressModeWrap; tex_desc.filterMode = cudaFilterModeLinear; tex_desc.readMode = cudaReadModeElementType; tex_desc.normalizedCoords = 1; check_success(cudaCreateTextureObject(env_tex, &res_desc, &tex_desc, NULL) == cudaSuccess); return true; } // Process camera movement. static void update_camera( Kernel_params &kernel_params, double phi, double theta, float base_dist, int zoom) { kernel_params.cam_dir.x = float(-sin(phi) * sin(theta)); kernel_params.cam_dir.y = float(-cos(theta)); kernel_params.cam_dir.z = float(-cos(phi) * sin(theta)); kernel_params.cam_right.x = float(cos(phi)); kernel_params.cam_right.y = 0.0f; kernel_params.cam_right.z = float(-sin(phi)); kernel_params.cam_up.x = float(-sin(phi) * cos(theta)); kernel_params.cam_up.y = float(sin(theta)); kernel_params.cam_up.z = float(-cos(phi) * cos(theta)); const float dist = float(base_dist * pow(0.95, double(zoom))); kernel_params.cam_pos.x = -kernel_params.cam_dir.x * dist; kernel_params.cam_pos.y = -kernel_params.cam_dir.y * dist; kernel_params.cam_pos.z = -kernel_params.cam_dir.z * dist; } int main(const int argc, const char* argv[]) { Window_context window_context; memset(&window_context, 0, sizeof(Window_context)); GLuint display_buffer = 0; GLuint display_tex = 0; GLuint program = 0; GLuint quad_vertex_buffer = 0; GLuint quad_vao = 0; GLFWwindow *window = NULL; int width = -1; int height = -1; // Init OpenGL window and callbacks. window = init_opengl(); glfwSetWindowUserPointer(window, &window_context); glfwSetKeyCallback(window, handle_key); glfwSetScrollCallback(window, handle_scroll); glfwSetCursorPosCallback(window, handle_mouse_pos); glfwSetMouseButtonCallback(window, handle_mouse_button); glGenBuffers(1, &display_buffer); glGenTextures(1, &display_tex); check_success(glGetError() == GL_NO_ERROR); program = create_shader_program(); quad_vao = create_quad(program, &quad_vertex_buffer); init_cuda(); float3 *accum_buffer = NULL; cudaGraphicsResource_t display_buffer_cuda = NULL; // Setup initial CUDA kernel parameters. Kernel_params kernel_params; memset(&kernel_params, 0, sizeof(Kernel_params)); kernel_params.cam_focal = float(1.0 / tan(90.0 / 2.0 * (2.0 * M_PI / 360.0))); kernel_params.iteration = 0; kernel_params.max_interactions = 1024; kernel_params.exposure_scale = 1.0f; kernel_params.environment_type = 0; kernel_params.volume_type = 0; kernel_params.max_extinction = 100.0f; kernel_params.albedo = 0.8f; // Setup initial camera. double phi = -0.084823; double theta = 1.423141; float base_dist = 1.3f; int zoom = 0; update_camera(kernel_params, phi, theta, base_dist, zoom); cudaArray_t env_tex_data = 0; bool env_tex = false; if (argc >= 2) env_tex = create_environment( &kernel_params.env_tex, &env_tex_data, argv[1]); if (env_tex) { kernel_params.environment_type = 1; window_context.config_type = 2; } while (!glfwWindowShouldClose(window)) { // Process events. glfwPollEvents(); Window_context *ctx = static_cast<Window_context *>(glfwGetWindowUserPointer(window)); kernel_params.exposure_scale = powf(2.0f, ctx->exposure); const unsigned int volume_type = ctx->config_type & 1; const unsigned int environment_type = env_tex ? ((ctx->config_type >> 1) & 1) : 0; if (kernel_params.volume_type != volume_type || kernel_params.environment_type != environment_type) { kernel_params.volume_type = volume_type; kernel_params.environment_type = environment_type; kernel_params.iteration = 0; } if (ctx->move_dx != 0.0 || ctx->move_dy != 0.0 || ctx->zoom_delta) { zoom += ctx->zoom_delta; ctx->zoom_delta = 0; phi -= ctx->move_dx * 0.001 * M_PI; theta -= ctx->move_dy * 0.001 * M_PI; theta = std::max(theta, 0.00 * M_PI); theta = std::min(theta, 1.00 * M_PI); ctx->move_dx = ctx->move_dy = 0.0; update_camera(kernel_params, phi, theta, base_dist, zoom); kernel_params.iteration = 0; } // Reallocate buffers if window size changed. int nwidth, nheight; glfwGetFramebufferSize(window, &nwidth, &nheight); if (nwidth != width || nheight != height) { width = nwidth; height = nheight; resize_buffers( &accum_buffer, &display_buffer_cuda, width, height, display_buffer); kernel_params.accum_buffer = accum_buffer; glViewport(0, 0, width, height); kernel_params.resolution.x = width; kernel_params.resolution.y = height; kernel_params.iteration = 0; } // Map GL buffer for access with CUDA. check_success(cudaGraphicsMapResources(1, &display_buffer_cuda, /*stream=*/0) == cudaSuccess); void *p; size_t size_p; check_success( cudaGraphicsResourceGetMappedPointer(&p, &size_p, display_buffer_cuda) == cudaSuccess); kernel_params.display_buffer = reinterpret_cast<unsigned int *>(p); // Launch volume rendering kernel. dim3 threads_per_block(16, 16); dim3 num_blocks((width + 15) / 16, (height + 15) / 16); void *params[] = { &kernel_params }; check_success(cudaLaunchKernel( (const void *)&volume_rt_kernel, num_blocks, threads_per_block, params) == cudaSuccess); ++kernel_params.iteration; // Unmap GL buffer. check_success(cudaGraphicsUnmapResources(1, &display_buffer_cuda, /*stream=*/0) == cudaSuccess); // Update texture for display. glBindBuffer(GL_PIXEL_UNPACK_BUFFER, display_buffer); glBindTexture(GL_TEXTURE_2D, display_tex); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_BGRA, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); check_success(glGetError() == GL_NO_ERROR); // Render the quad. glClear(GL_COLOR_BUFFER_BIT); glBindVertexArray(quad_vao); glDrawArrays(GL_TRIANGLES, 0, 6); check_success(glGetError() == GL_NO_ERROR); glfwSwapBuffers(window); } // Cleanup CUDA. if (env_tex) { check_success(cudaDestroyTextureObject(kernel_params.env_tex) == cudaSuccess); check_success(cudaFreeArray(env_tex_data) == cudaSuccess); } check_success(cudaFree(accum_buffer) == cudaSuccess); // Cleanup OpenGL. glDeleteVertexArrays(1, &quad_vao); glDeleteBuffers(1, &quad_vertex_buffer); glDeleteProgram(program); check_success(glGetError() == GL_NO_ERROR); glfwDestroyWindow(window); glfwTerminate(); return 0; }
[ "m_nyers@yahoo.com" ]
m_nyers@yahoo.com
f73437181ae33dc99f28ffcc6063f5b256daab43
63c7352bc3e1a9ce0195b84e154eaa26240239c3
/systemc-ams-1.0Beta2/src/scams/predefined_moc/lsf/sca_lsf_tdf_source.h
d9b0a50fe06dd0668a0282b53ce7dbfbcafe7f58
[ "Apache-2.0" ]
permissive
RShankar/Hydrological-Modeling
4e3fb35f34b15df49d36dfa7d0fb854f376b744f
716c2554688a02957bb2de8b0f723837d9ce2aef
refs/heads/master
2021-04-12T04:38:43.450353
2015-02-16T18:02:56
2015-02-16T18:02:56
30,809,673
0
0
null
null
null
null
UTF-8
C++
false
false
2,690
h
/***************************************************************************** Copyright 2010 Fraunhofer-Gesellschaft zur Foerderung der angewandten Forschung e.V. 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. *****************************************************************************/ /***************************************************************************** sca_lsf_tdf_source.h - linear signal flow source controlled by a tdf signal Original Author: Karsten Einwich Fraunhofer IIS/EAS Dresden Created on: 05.03.2009 SVN Version : $Revision: 969 $ SVN last checkin : $Date: 2010-03-01 22:34:37 +0100 (Mon, 01 Mar 2010) $ SVN checkin by : $Author: karsten $ SVN Id : $Id: sca_lsf_tdf_source.h 969 2010-03-01 21:34:37Z karsten $ *****************************************************************************/ /* * LRM clause 4.2.1.16. * The class sca_lsf::sca_tdf::sca_source shall implement a primitive module for * the LSF MoC that realizes the scaled conversion of a TDF signal to an * LSF signal. The primitive shall contribute the following equation to the * equation system: * y(t) = scale * inp * where scale is the constant scale coefficient, inp is the TDF input signal * that shall be interpreted as a continuous-time signal, and y(t) is the * LSF output signal. */ /*****************************************************************************/ #ifndef SCA_LSF_TDF_SOURCE_H_ #define SCA_LSF_TDF_SOURCE_H_ namespace sca_lsf { namespace sca_tdf { //class sca_source : public implementation-derived-from sca_core::sca_module class sca_source: public sca_lsf::sca_module { public: ::sca_tdf::sca_in<double> inp; // TDF input sca_lsf::sca_out y; // LSF output sca_core::sca_parameter<double> scale; // scale coefficient virtual const char* kind() const; explicit sca_source(sc_core::sc_module_name, double scale_ = 1.0); //begin implementation specific private: virtual void matrix_stamps(); double value_t(); //end implementation specific }; } // namespace sca_tdf typedef sca_lsf::sca_tdf::sca_source sca_tdf_source; } // namespace sca_lsf #endif /* SCA_LSF_TDF_SOURCE_H_ */
[ "gmath50198@ao.com" ]
gmath50198@ao.com
684100aec985ba60d39cc77b5efb6817fa53f8b8
3bd2a0b4076474bc1b1cd5872d047b69dd1399e8
/homework/code/ps5/CuckooHashTable.cpp
c75787a99da435c170c2f8dc70de29422460e41c
[]
no_license
kandluis/cs166
2a0ddff0aa7759933c203c5db36d5f3f1fdf2518
2de5f41427957b3db8a2c72ca71e32fced2e68e5
refs/heads/master
2022-01-12T10:51:26.802643
2019-05-30T19:44:35
2019-05-30T19:44:35
180,023,629
1
0
null
null
null
null
UTF-8
C++
false
false
4,905
cpp
#include "CuckooHashTable.h" #include "Hashes.h" #if __has_include(<optional>) # include <optional> using std::optional; using std::nullopt; #else # include <experimental/optional> using std::experimental::optional; using std::experimental::nullopt; #endif #include <cmath> #include <vector> /** * Since cuckoo hashing requires two tables, you should create two tables * of size numBuckets / 2. Because our testing harness attempts to exercise * a number of different load factors, you should not change the number of * buckets once the hash table has initially be created. */ CuckooHashTable::CuckooHashTable( size_t numBuckets, std::shared_ptr<HashFamily> family) : hash_family_(family), first_hash_function_(family->get()), second_hash_function_(family->get()), num_elements_(0), first_table_(numBuckets / 2), second_table_(numBuckets / 2 + (numBuckets % 2)) { } CuckooHashTable::~CuckooHashTable() { // Nothing to do! } void CuckooHashTable::rebuild(const int data) { first_hash_function_ = hash_family_->get(); second_hash_function_ = hash_family_->get(); const auto res = insertHelper(data); if (!res.first) { // Failed to insert. Try again. return rebuild(res.second); } // Rebuild first_table_; for (std::size_t hash = 0; hash < first_table_.size(); hash++) { if (!first_table_[hash]) continue; const int element = first_table_[hash].value(); // Skip if already in right position. if ((first_hash_function_(element) % first_table_.size()) == hash) continue; // Try to insert. first_table_[hash] = nullopt; const auto res = insertHelper(element); if (!res.first) { // Failed to insert. Trigger another rebuild. return rebuild(res.second); } } // Rebuild second_table_; for (std::size_t hash = 0; hash < second_table_.size(); hash++) { if (!second_table_[hash]) continue; const int element = second_table_[hash].value(); // Skip if already in right position. if ((second_hash_function_(element) % second_table_.size()) == hash) continue; // Try to insert. second_table_[hash] = nullopt; const auto res = insertHelper(element); if (!res.first) { // Failed to insert. Trigger another rebuild. return rebuild(res.second); } } // Success! Everything was re-hashed successfully. } std::pair<bool, int> CuckooHashTable::insertHelper(int data) { int numDisplacements = 0; const int kMaxDisplacements = 6 * ((num_elements_ > 1) ? log(num_elements_) : 1); int toInsert = data; std::vector<optional<int>>* table = &first_table_; std::vector<optional<int>>* other_table = &second_table_; HashFunction* hash_function = &first_hash_function_; HashFunction* other_hash_function = &second_hash_function_; while (numDisplacements <= kMaxDisplacements) { const std::size_t hash = (*hash_function)(toInsert) % table->size(); if (!(*table)[hash]) { (*table)[hash] = toInsert; return {true, toInsert}; } // Table is occupied, so do a swap. { const int temp = (*table)[hash].value(); (*table)[hash] = toInsert; toInsert = temp; } // And try the other table. { HashFunction* temp = hash_function; hash_function = other_hash_function; other_hash_function = temp; } { std::vector<optional<int>>* temp = table; table = other_table; other_table = temp; } numDisplacements++; } // We get here if we failed to insert data. return {false, toInsert}; } void CuckooHashTable::insert(int data) { if (num_elements_ >= (first_table_.size() + second_table_.size())) return; // No-op if already contained here. if (contains(data)) return; const auto res = insertHelper(data); num_elements_++; if (res.first) return; // Failed, so rebuild the entire structure. // This call keeps trying until it succeeds. rebuild(res.second); } bool CuckooHashTable::contains(int data) const { if (!first_table_.empty()) { const std::size_t hash = first_hash_function_(data) % first_table_.size(); if (first_table_[hash] && first_table_[hash].value() == data ) { return true; } } if (!second_table_.empty()) { const std::size_t hash = second_hash_function_(data) % second_table_.size(); if (second_table_[hash] && second_table_[hash].value() == data ) { return true; } } return false; } void CuckooHashTable::remove(int data) { if (!first_table_.empty()) { const std::size_t hash = first_hash_function_(data) % first_table_.size(); if (first_table_[hash] && first_table_[hash].value() == data ) { first_table_[hash] = nullopt; } } if (!second_table_.empty()) { const std::size_t hash = second_hash_function_(data) % second_table_.size(); if (second_table_[hash] && second_table_[hash].value() == data ) { second_table_[hash] = nullopt; } } }
[ "luis.perez.live@gmail.com" ]
luis.perez.live@gmail.com
6fb2a21b3d0ab144f0d915ba29ccb085e8648500
2bf42e79cd6d9482601deae7d93bc2bf64217328
/bmsbel/bms_regist_array.cpp
49afff0cf2668b2a89a487a7fa38f429cfb45f32
[]
no_license
kuna/bmsbelplus
099e56ad7bd5e6a8b72b7e06c7dcf18a52c6d352
8515a1d729a4f8b0f8e3ec94d0175769b2f6d94c
refs/heads/master
2016-08-10T06:37:31.320100
2016-03-19T10:45:43
2016-03-19T10:45:43
48,487,172
10
2
null
2016-01-30T08:10:56
2015-12-23T11:29:46
C
UTF-8
C++
false
false
5,233
cpp
#include "bmsbel/bms_regist_array.h" #include "bmsbel/bms_define.h" #include "bmsbel/bms_util.h" #include "bmsbel/bms_exception.h" bool BmsRegistArray::CheckConstruction(const std::string& name, const std::string& str) { if (str.length() != name.length() + 2) { return false; } std::string tmp = str.substr(0, name.length()); BmsUtil::StringToUpper(tmp); if (tmp.compare(name) != 0) { return false; } if (NOT(BmsWord::CheckConstruction(str.c_str() + name.length()))) { return false; } switch (str.c_str()[name.length() + 2]) { case ' ': case '\t': case '\0': return true; default: return false; } } BmsRegistArray::BmsRegistArray(const std::string& name) : name_(name), array_(new std::pair<bool, std::string>[BmsConst::WORD_MAX_COUNT]) { for (unsigned int i = 0; i < BmsConst::WORD_MAX_COUNT; ++i) { array_[i].first = false; } } BmsRegistArray::~BmsRegistArray() { delete[] array_; } const std::string& BmsRegistArray::GetName(void) const { return name_; } unsigned int BmsRegistArray::GetExistCount(void) const { unsigned int count = 0; for (unsigned int i = 0; i < BmsConst::WORD_MAX_COUNT; ++i) { if (array_[i].first) { ++count; } } return count; } bool BmsRegistArray::IsExists(const BmsWord &pos) const { return array_[pos.ToInteger()].first; } bool BmsRegistArray::IsNotExists(const BmsWord &pos) const { return NOT(this->IsExists(pos)); } #ifdef USE_MBCS std::wstring BmsRegistArray::At_w(const BmsWord &pos) const { if (this->IsNotExists(pos)) { throw BmsOutOfRangeAccessException(typeid(*this)); } wchar_t *_w = new wchar_t[10240]; BmsUtil::utf8_to_wchar(array_[pos.ToInteger()].second.c_str(), _w, 10240); std::wstring w = _w; delete _w; return w; } #endif const std::string& BmsRegistArray::At(const BmsWord &pos) const { if (this->IsNotExists(pos)) { throw BmsOutOfRangeAccessException(typeid(*this)); } return array_[pos.ToInteger()].second; } const std::string& BmsRegistArray::operator [](const BmsWord &pos) const { return this->At(pos); } void BmsRegistArray::Set(const BmsWord &pos, const std::string& value) { pos.CheckValid(); array_[pos.ToInteger()].first = true; array_[pos.ToInteger()].second = value; } void BmsRegistArray::DeleteAt(BmsWord pos) { pos.CheckValid(); array_[pos.ToInteger()].first = false; array_[pos.ToInteger()].second = ""; } void BmsRegistArray::Clear(void) { for (unsigned int i = 0; i < BmsConst::WORD_MAX_COUNT; ++i) { array_[i].first = false; array_[i].second = ""; } } std::string BmsRegistArray::ToString(void) const { std::string tmp; for (unsigned int i = 0; i < BmsConst::WORD_MAX_COUNT; ++i) { if (array_[i].first) { tmp.append("#"); tmp.append(name_); tmp.append(BmsWord(i).ToString()); tmp.append(" "); tmp.append(array_[i].second); tmp.append("\n"); } } return tmp; } #ifdef USE_MBCS std::wstring BmsRegistArray::ToWString(void) const { wchar_t wname_[1024]; BmsUtil::utf8_to_wchar(name_.c_str(), wname_, 1024); std::wstring tmp; for (unsigned int i = 0; i < BmsConst::WORD_MAX_COUNT; ++i) { if (array_[i].first) { tmp.append(L"#"); tmp.append(wname_); tmp.append(BmsWord(i).ToWString()); tmp.append(L" "); tmp.append(At_w(i)); tmp.append(L"\n"); } } return tmp; } #endif // -- BmsRegistArraySet -------------------------------------------------- BmsRegistArraySet::BmsRegistArraySet(void) : table_() { } BmsRegistArraySet::~BmsRegistArraySet() { for (std::map<std::string, BmsRegistArray*>::iterator it = table_.begin(); it != table_.end(); ++it) { delete it->second; } } BmsRegistArray& BmsRegistArraySet::MakeNewArray(const std::string& key) { if (this->Exists(key)) { return *table_[key]; } BmsRegistArray* tmp = new BmsRegistArray(key); table_[key] = tmp; return *tmp; } void BmsRegistArraySet::DeleteArray(const std::string& key) { if (this->Exists(key)) { delete table_[key]; table_.erase(key); } } bool BmsRegistArraySet::Exists(const std::string& key) const { return table_.find(key) != table_.end(); } BmsRegistArray& BmsRegistArraySet::operator [](const std::string& key) { if (NOT(this->Exists(key))) { throw BmsOutOfRangeAccessException(typeid(*this));; } return *table_[key]; } const BmsRegistArray& BmsRegistArraySet::operator [](const std::string& key) const { if (NOT(this->Exists(key))) { throw BmsOutOfRangeAccessException(typeid(*this));; } return *table_.find(key)->second; } void BmsRegistArraySet::Clear(void) { for (std::map<std::string, BmsRegistArray*>::iterator it = table_.begin(); it != table_.end(); ++it) { it->second->Clear(); } } BmsRegistArraySet::Iterator BmsRegistArraySet::Begin() { return table_.begin(); } BmsRegistArraySet::Iterator BmsRegistArraySet::End() { return table_.end(); } BmsRegistArraySet::ConstIterator BmsRegistArraySet::Begin() const { return table_.begin(); } BmsRegistArraySet::ConstIterator BmsRegistArraySet::End() const { return table_.end(); }
[ "kgdgwn98@gmail.com" ]
kgdgwn98@gmail.com
ddf4d7472863fb760f55c5c7e6deeaea97c49b27
ad93b9522005c3bd28e16b420a10737467e50f61
/C++/SocketBased/Test2/Q3/Object_Client_3/Object_Client/Class.h
d2689437937ad2729e7b05c563a53382fa6e3393
[]
no_license
jgchoi/seneca-coding-archive
c678efa350e2a165638081bc1824933fa2ef6871
01d63e066d078e126061386aad9b1c5bd65fbce4
refs/heads/master
2021-05-01T10:35:39.585502
2017-01-14T00:06:23
2017-01-14T00:06:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
477
h
#ifndef _PACKET_H #define _PACKET_H struct body_str { unsigned char size; unsigned int *contents; }; class Packet { private: unsigned char header; body_str body; unsigned char tail; public: Packet(); ~Packet(); void SetInfo(); void PrintInfo(); int Connect(SOCKET &, char *, int); void SendPkt(SOCKET &); void ReceivePkt(SOCKET &); void Send(SOCKET &); void Receive(SOCKET &); void CloseSocket(SOCKET &); void WinsockExit(); }; #endif
[ "un333333@gmail.com" ]
un333333@gmail.com
1d175e58131c15e8fa943a881d98672e1c5b6ff8
ab058b41b1ac0218ae34468a7c5664a34fe8067a
/sample/sssampledriver.cpp
c0643da09941d82ce14c4ff119cb679ac0b482b9
[ "MIT" ]
permissive
ebio-snu/cvtdriver
7d7c9b4b4de91309bbac0fda9995a7d7b7b2066a
d76375c8ab5aacece3bb0dd9f9c556128d7193a7
refs/heads/master
2021-01-24T04:20:27.576471
2018-05-29T09:49:01
2018-05-29T09:49:01
122,933,955
0
0
null
null
null
null
UTF-8
C++
false
false
11,842
cpp
/** Copyright © 2018 ebio lab. SNU. All Rights Reserved. @file sssampledriver.cpp @date 2018-03-22, JoonYong @author Kim, JoonYong <tombraid@snu.ac.kr> This file is for server-side sample driver. refer from: https://github.com/ebio-snu/cvtdriver */ #include <iostream> #include <sstream> #include <string> #include <queue> #include <boost/config.hpp> #include <glog/logging.h> #include <mysql_connection.h> #include <cppconn/driver.h> #include <cppconn/exception.h> #include <cppconn/resultset.h> #include <cppconn/statement.h> #include <cppconn/prepared_statement.h> #include "../spec/cvtdevice.h" #include "../spec/cvtdriver.h" using namespace std; using namespace stdcvt; namespace ebiodriver { // 센서에 기능을 추가하고 싶을때 사용할 수 있다는 예시 // CvtSensor 는 id로 문자열을 처리하지만, SSSensor는 숫자로 처리함 // 실제로 사용하지는 않음 class SSSensor : public CvtSensor { public: SSSensor(int devid, stdcvt::devtype_t devtype, stdcvt::devsec_t section, stdcvt::devtarget_t target, stdcvt::devstat_t devstatus, stdcvt::obsunit_t unit) : stdcvt::CvtSensor (to_string(devid), devtype, section, target, devstatus, unit) { } }; // 모터에 기능을 추가하고 싶을때 사용할 수 있다는 예시 // CvtMotor 는 id로 문자열을 처리하지만, SSMotor는 숫자로 처리함 // 실제로 사용하지는 않음 class SSMotor : public CvtMotor{ public: SSMotor(int devid, stdcvt::devtype_t devtype, stdcvt::devsec_t section, stdcvt::devtarget_t target, stdcvt::devstat_t devstatus) : stdcvt::CvtMotor(to_string(devid), devtype, section, target, devstatus) { } }; // 스위치에 기능을 추가하고 싶을때 사용할 수 있다는 예시 // CvtActuator는 id로 문자열을 처리하지만, SSSwitch는 숫자로 처리함 // 실제로 사용하지는 않음 class SSSwitch : public CvtActuator { public: SSSwitch(int devid, stdcvt::devtype_t devtype, stdcvt::devsec_t section, stdcvt::devtarget_t target, stdcvt::devstat_t devstatus) : stdcvt::CvtActuator(to_string(devid), devtype, section, target, devstatus) { } }; class SSSampleDriver : public CvtDriver { private: int _lastcmdid; ///< 명령아이디 시퀀스 queue<CvtCommand *> _cmdq; ///< 명령 큐 vector<CvtDevice *> _devvec; ///< 디바이스 벡터 string _host; ///< 디비 호스트 string _user; ///< 디비 사용자 string _pass; ///< 디비 사용자 암호 string _db; ///< 디비명 sql::Driver *_driver; ///< 디비 드라이버 sql::Connection *_con; ///< 디비 연결자 public: /** 새로운 SS드라이버를 생성한다. */ SSSampleDriver() : stdcvt::CvtDriver (2001, 100) { _lastcmdid = 0; _host = _user = _pass = _db = ""; updated(); // 샘플 SS드라이버는 직접 통신을 수행하지 않기 때문에, 테스트 통과를 위해서 넣음. } ~SSSampleDriver () { } /** 드라이버 제작자가 부여하는 버전번호를 확인한다. @return 문자열 형식의 버전번호 */ string getversion () { return "V0.1.0"; } /** 드라이버 제작자가 부여하는 모델번호를 확인한다. @return 문자열 형식의 모델번호 */ string getmodel () { return "ebioss_v1"; } /** 드라이버 제조사명을 확인한다. 컨버터에서는 제조사명을 로깅용도로만 사용한다. @return 문자열 형식의 제조사명 */ string getcompany () { return "EBIO lab. SNU."; } /** 드라이버를 초기화 한다. 드라이버 동작을 위한 option 은 key-value 형식으로 전달된다. @param option 드라이버동작을 위한 옵션 @return 초기화 성공 여부 */ bool initialize (CvtOption option) { LOG(INFO) << "SSSampleDriver initialized."; _host = option.get("host"); _user = option.get("user"); _pass = option.get("pass"); _db = option.get("db"); try { _driver = get_driver_instance(); _con = _driver->connect(_host, _user, _pass); _con->setSchema(_db); } catch (sql::SQLException &e) { LOG(ERROR) << "# open ERR: SQLException " << e.what() << " (MySQL error code: " << e.getErrorCode() << ", SQLState: " << e.getSQLState() << " )"; return false; } try { sql::Statement *stmt; stmt = _con->createStatement(); stmt->execute ("TRUNCATE TABLE commands"); delete stmt; } catch (sql::SQLException &e) { LOG(ERROR) << "# Truncate commands ERR: SQLException " << e.what() << " (MySQL error code: " << e.getErrorCode() << ", SQLState: " << e.getSQLState() << " )"; return false; } return true; } /** 드라이버를 종료한다. @return 종료 성공 여부 */ bool finalize () { delete _con; LOG(INFO) << "SSSampleDriver finalized."; return true; } /** 드라이버간 상태교환을 하기전에 호출되는 메소드로 전처리를 수행한다. @return 전처리 성공 여부 */ bool preprocess () { //read command from DB try { sql::PreparedStatement *prepstmt; sql::ResultSet *res; CvtCommand *pcmd; prepstmt = _con->prepareStatement("SELECT id, devtype, section, target, onoff, ratio from commands where id > ?"); prepstmt->setInt(1, _lastcmdid); res = prepstmt->executeQuery(); while (res->next()) { if (CvtDevice::getgroup((devtype_t)res->getInt(2)) == DG_MOTOR) { CvtDeviceSpec tmpspec((devtype_t)res->getInt(2), (devsec_t)res->getInt64(3), (devtarget_t)res->getInt(4)); pcmd = new CvtRatioCommand (res->getInt(1), &tmpspec, (res->getInt(5) > 0) ? true: false, res->getDouble(6)); } else if (res->getInt(2) / 10000 == DG_SWITCH) { CvtDeviceSpec tmpspec((devtype_t)res->getInt(2), (devsec_t)res->getInt64(3), (devtarget_t)res->getInt(4)); pcmd = new CvtCommand (res->getInt(1), &tmpspec, res->getInt(5)>0? true: false); } else { continue; } _lastcmdid = pcmd->getid (); _cmdq.push (pcmd); } delete res; delete prepstmt; } catch (sql::SQLException &e) { LOG(ERROR) << "# command select ERR: SQLException " << e.what() << " (MySQL error code: " << e.getErrorCode() << ", SQLState: " << e.getSQLState() << " )"; return false; } updated(); // 샘플 SS드라이버는 직접 통신을 수행하지 않기 때문에, 테스트 통과를 위해서 넣음. return true; } /** 드라이버간 상태교환이 이루어진 이후에 호출되는 메소드로 후처리를 수행한다. @return 후처리 성공 여부 */ bool postprocess () { //write observation to DB try { sql::Statement *stmt; stmt = _con->createStatement(); stmt->execute ("TRUNCATE TABLE devices"); delete stmt; } catch (sql::SQLException &e) { LOG(ERROR) << "# Truncate devices ERR: SQLException " << e.what() << " (MySQL error code: " << e.getErrorCode() << ", SQLState: " << e.getSQLState() << " )"; return false; } try { sql::PreparedStatement *prepstmt; prepstmt = _con->prepareStatement( "INSERT INTO devices(id, devtype, section, target, status, value, unit)" " VALUES (?, ?, ?, ?, ?, ?, ?)"); for (vector<CvtDevice *>::size_type i = 0; i < _devvec.size(); ++i) { prepstmt->setString(1, _devvec[i]->getid()); prepstmt->setInt(2, (_devvec[i]->getspec())->gettype()); prepstmt->setInt64(3, (_devvec[i]->getspec())->getsection()); prepstmt->setInt(4, (_devvec[i]->getspec())->gettarget()); prepstmt->setInt(5, _devvec[i]->getstatus()); if (CvtMotor *pmotor= dynamic_cast<CvtMotor *>(_devvec[i])) { // younger first LOG(INFO) << "motor : " << pmotor->tostring(); LOG(INFO) << "motor current : " << pmotor->getcurrent(); prepstmt->setDouble(6, pmotor->getcurrent ()); prepstmt->setInt(7, OU_NONE); } else if (CvtActuator *pactuator = dynamic_cast<CvtActuator *>(_devvec[i])) { prepstmt->setDouble(6, 0); prepstmt->setInt(7, OU_NONE); } else if (CvtSensor *psensor = dynamic_cast<CvtSensor *>(_devvec[i])) { prepstmt->setDouble(6, psensor->readobservation ()); prepstmt->setInt(7, psensor->getunit ()); } prepstmt->execute (); delete _devvec[i]; } _con->commit (); delete prepstmt; _devvec.clear (); } catch (sql::SQLException &e) { LOG(ERROR) << "# Insert devices ERR: SQLException " << e.what() << " (MySQL error code: " << e.getErrorCode() << ", SQLState: " << e.getSQLState() << " )"; return false; } return true; } /** 드라이버가 관리하고 있는 장비의 포인터를 꺼내준다. @param index 얻고자 하는 장비의 인덱스 번호. 0에서 시작한다. @return 인덱스에 해당하는 장비의 포인터. NULL 이라면 이후에 장비가 없다는 의미이다. */ CvtDevice *getdevice(int index) { return nullptr; } /** 전달된 장비의 정보를 획득한다. 다른 드라이버의 장비정보를 입력해주기 위해 컨버터가 호출한다. @param pdevice 다른 드라이버의 장비 포인터 @return 성공여부. 관심이 없는 장비인 경우라도 문제가 없으면 true를 리턴한다. */ bool sharedevice(CvtDevice *pdevice) { CvtDevice *newdev = pdevice->clone (); _devvec.push_back (newdev); return true; } /** 다른 드라이버가 관리하고 있는 장비를 제어하고자 할때 명령을 전달한다. 명령을 전달하지 않는 드라이버라면 그냥 NULL을 리턴하도록 만들면 된다. @return 인덱스에 해당하는 명령의 포인터. NULL 이라면 이후에 명령이 없다는 의미이다. */ CvtCommand *getcommand() { if (_cmdq.empty ()) return nullptr; CvtCommand *pcmd = _cmdq.front(); _cmdq.pop (); return pcmd; } /** 다른 드라이버로부터 명령을 받아 처리한다. @param pcmd 명령에 대한 포인터 @return 실제 명령의 처리 여부가 아니라 명령을 수신했는지 여부이다. 해당 명령을 실행할 장비가 없다면 false이다. */ bool control(CvtCommand *pcmd) { return false; } }; extern "C" BOOST_SYMBOL_EXPORT SSSampleDriver plugin; SSSampleDriver plugin; } // namespace ebiodriver
[ "joonyong.jinong@gmail.com" ]
joonyong.jinong@gmail.com
e0b9c23735eed609b6cd91bfcfbdc72aadb013cd
0f08276e557de8437759659970efc829a9cbc669
/problems/p210.h
9e959af14188210eaf2f3f83bd1b400b7f186f41
[]
no_license
petru-d/leetcode-solutions-reboot
4fb35a58435f18934b9fe7931e01dabcc9d05186
680dc63d24df4c0cc58fcad429135e90f7dfe8bd
refs/heads/master
2023-06-14T21:58:53.553870
2021-07-11T20:41:57
2021-07-11T20:41:57
250,795,996
0
0
null
null
null
null
UTF-8
C++
false
false
1,796
h
#pragma once #include <unordered_map> #include <vector> namespace p210 { class Solution { public: using Graph = std::unordered_map<int, std::vector<int>>; enum class State { NotVisited, InProgress, Visited }; std::vector<int> findOrder(int numCourses, std::vector<std::vector<int>>& prerequisites) { Graph graph; for (const auto& p : prerequisites) { graph[p[1]].push_back(p[0]); } std::vector<int> result; std::vector<State> visited(size_t(numCourses), State::NotVisited); for (int i = 0; i < numCourses; ++i) { if (visited[i] == State::NotVisited) { if (!dfs(i, graph, visited, result)) return {}; } } std::reverse(result.begin(), result.end()); return result; } private: bool dfs(int node, const Graph& graph, std::vector<State>& visited, std::vector<int>& result) { if (visited[size_t(node)] == State::InProgress) return false; visited[size_t(node)] = State::InProgress; auto n_it = graph.find(node); if (n_it != graph.end()) { for (const auto& n : n_it->second) { if (visited[n] == State::Visited) continue; if (!dfs(n, graph, visited, result)) return false; } } visited[node] = State::Visited; result.push_back(node); return true; } }; }
[ "berserk.ro@gmail.com" ]
berserk.ro@gmail.com
bf032e89796adf776999797ee738f70baa40ecf3
0d8f36c6e4edec44ab8cfe3dfab1b5607c72692e
/Arduino/MyNewSensorTest/MyNewSensorTest.ino
895f89b81f0ebac6bcfdb351802c01cb3609e2f9
[]
no_license
acured/WorkSpace
dc802f7566599320f73363102d40f8665d4bad84
803e9c8fb3afdf1e6507fee2e8b87e112e907b18
refs/heads/master
2021-01-17T17:31:45.353588
2019-03-06T08:44:44
2019-03-06T08:44:44
56,388,019
0
0
null
null
null
null
UTF-8
C++
false
false
5,297
ino
#include "Arduino.h" #include <SoftwareSerial.h> SoftwareSerial mySerial(10, 11); // RX=>serial tx pin, TX=>serial rx pin #define TriggerPin 2 #define SerialPort Serial #define printByte(args) Serial.write(args) #define urmAccount 2 // Init the account of the URM04 sensor byte firstAddr = 0x11; byte secondAddr = 0x12; //byte thirdAddr = 0x13; //byte RFaddr = 0x14; //byte RRaddr = 0x15; byte cmdst[10]; byte urmID[urmAccount]; unsigned int urmData[urmAccount]; #define CommMAXRetry 20 String str; double sensorLF=9999; double sensorLR=9999; double sensorRF=9999; double sensorRR=9999; double sensorF=9999; String result; static unsigned long timers = 0; static unsigned long timere = 0; void setup() { // put your setup code here, to run once: pinMode(TriggerPin,OUTPUT); // TTL -> RS485 chip driver pin digitalWrite(TriggerPin,LOW); SerialPort.begin(19200); for(int i = 0 ;i < 10; i++) cmdst[i] = 0; //init the URM04 protocol for(int i = 0 ;i < urmAccount; i++) urmData[i] = 0; //init the URM04 protocol urmID[0] = firstAddr; urmID[1] = secondAddr; //urmID[2] = thirdAddr; //urmID[3] = RFaddr; //urmID[4] = RRaddr; //SerialPort.println("ready!"); mySerial.begin(9600); mySerial.setTimeout(2); result = String(""); } void setAddr(){ // The function is used to set sensor's add //digitalWrite(TriggerPin, HIGH); cmdst[0]=0x55; cmdst[1]=0xaa; cmdst[2] = 0xab; cmdst[3] = 0x01; cmdst[4] = 0x55; cmdst[5] = 0x14; transmitCommands_setAdd(); } void transmitCommands_setAdd(){ // Send protocol via RS485 interface cmdst[6]=cmdst[0]+cmdst[1]+cmdst[2]+cmdst[3]+cmdst[4]+cmdst[5]; delay(1); for(int j = 0; j < 7; j++){ printByte(cmdst[j]); } delay(2); } void urmTrigger(byte addr){ // The function is used to trigger the measuring cmdst[0]=0x55; cmdst[1]=0xaa; cmdst[2] = addr; cmdst[3] = 0x00; cmdst[4] = 0x01; transmitCommands(); } void urmReader(byte addr){ // The function is used to read the distance cmdst[0]=0x55; cmdst[1]=0xaa; cmdst[2] = addr; cmdst[3]=0x00; cmdst[4]=0x02; transmitCommands(); } void transmitCommands(){ // Send protocol via RS485 interface cmdst[5]=cmdst[0]+cmdst[1]+cmdst[2]+cmdst[3]+cmdst[4]; delay(1); for(int j = 0; j < 6; j++){ printByte(cmdst[j]); } delay(2); } void analyzeUrmData(byte cmd[],int addr ){ //SerialPort.print("distance:"); byte sumCheck = 0; for(int h = 0;h < 7; h ++) sumCheck += cmd[h]; if(sumCheck == cmd[7] && cmd[3] == 2 && cmd[4] == 2){ urmData[addr] = cmd[5] * 256 + cmd[6]; } else if(cmd[3] == 2 && cmd[4] == 2){ SerialPort.print("Sum error"); } } void decodeURM4(int addr){ // mySerial.println(addr); if(SerialPort.available()){ byte cmdrd[10]; for(int i = 0 ;i < 10; i++) cmdrd[i] = 0; // SerialPort.println("get dis"); boolean flag = true; boolean valid = false; byte headerNo = 0; int i=0; int RetryCounter = 0; while(true) { //timer = millis(); if(SerialPort.available()){ cmdrd[i]= SerialPort.read(); //SerialPort.println(cmdrd[i]); //SerialPort.print(" "); //SerialPort.print(timer); i++; } else{ //SerialPort.println("not get dis"); if(cmdrd[1] == 0xAA) break; else { //SerialPort.print(cmdrd[1]); return; } } } //SerialPort.println(""); analyzeUrmData(cmdrd,addr); //mySerial.println( urmData[addr]); //SerialPort.print(urmData[0]); //SerialPort.print(" "); //SerialPort.println(urmData[1]); } else { urmData[addr] = 9999; // SerialPort.println("not get dis"); } } void updateDis() { for(int i=0;i<urmAccount;i++) { //timers = millis(); digitalWrite(TriggerPin, HIGH); urmTrigger(urmID[i]); delay(40); urmReader(urmID[i]); digitalWrite(TriggerPin, LOW); delay(10); decodeURM4(i); //timere = millis() - timers; //SerialPort.print(urmData[i]); //SerialPort.print(" "); //SerialPort.println(timere); } sensorLF = urmData[0]; if(sensorLF>300)sensorLF = 9999; sensorLR = urmData[1]; if(sensorLR>300)sensorLR = 9999; /* sensorF = urmData[2]; if(sensorF>300)sensorF = 9999; sensorRF = urmData[3]; if(sensorRF>300)sensorRF = 9999; sensorRR = urmData[4]; if(sensorRR>300)sensorRR = 9999; */ //SerialPort.print(sensorLF); //SerialPort.print(" "); //SerialPort.println(sensorLR); //sensorRF = rand() % 255+1; //sensorRR = rand() % 255+1; } void loop() { // put your main code here, to run repeatedly: if (mySerial.available()) { str = mySerial.readString(); //mySerial.print(str); if(str=="0") { startCheck(); } else { updateDis(); result = result + sensorLF + ";"+ sensorLR+";"+sensorRF+";"+sensorRR;//+";"+sensorF; //SerialPort.println(result); mySerial.println(result); //SerialPort.println(result); result = ""; //setAddr(); //mySerial.println("ok"); } //delay(20); //updateDis(); } //updateDis(); } void startCheck() { mySerial.println("sensor"); }
[ "nihao_athlon@126.com" ]
nihao_athlon@126.com
24bc7fbfa53f419141594b56b9cf3df1092dd94e
e206ea09a316757e8028d803616634a4a9a50f72
/aribon/cable_master.cpp
fad17de2a30414e4ba96a169db65b0763754e24c
[]
no_license
seiichiinoue/procon
46cdf27ab42079002c4c11b8abe84662775b34a4
f0b33062a5f31cf0361c7973f4a5e81e8d5a428f
refs/heads/master
2021-06-26T19:02:24.797354
2020-11-01T14:12:54
2020-11-01T14:12:54
140,285,300
0
0
null
null
null
null
UTF-8
C++
false
false
1,748
cpp
#include <bits/stdc++.h> #define rep(i, n) for (int i=0; i<n; ++i) #define rep1(i, n) for (int i=1; i<=n; ++i) #define ALL(v) v.begin(), v.end() #define RALL(v) v.rbegin(), v.rend() #define EPS (1e-7) #define INF (1e9) #define PI (acos(-1)) using namespace std; typedef long long ll; typedef pair<ll, ll> P; constexpr ll MOD = (1e9+7); constexpr int gcd(int a, int b) { return b ? gcd(b, a % b) : a; } constexpr int lcm(int a, int b) { return a / gcd(a, b) * b; } template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; } template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; } ll factorial(ll n, ll m=2) { // calculate n! m = max(2LL, m); ll rtn = 1; for (ll i=m; i<=n; i++) { rtn = (rtn * i) % MOD; } return rtn; } ll modinv(ll a, ll m) { ll b = m, u = 1, v = 0; while (b) { ll t = a / b; a -= t * b; swap(a, b); u -= t * v; swap(u, v); } u %= m; if (u < 0) u += m; return u; } ll modpow(ll a, ll n) { ll res = 1; while (n > 0) { if (n & 1) res = res * a % MOD; a = a * a % MOD; n >>= 1; } return res; } int n=1e4 , k=1e4; vector<double> l(n); bool f(double x) { int num = 0; rep(i, n) num += (int)(l[i]/x); return num >= k; } int main() { cin.tie(nullptr); ios::sync_with_stdio(false); cin >> n >> k; rep(i, n) cin >> l[i]; double lb = 0, ub = INF; rep(i, 100) { double mid = (lb+ub) / 2; if (f(mid)) lb = mid; else ub = mid; } cout << floor(ub * 100) / 100 << endl; return 0; }
[ "d35inou108@gmail.com" ]
d35inou108@gmail.com
05c5c8a990cbc63b208f351e608052b45ee36ea2
a1427ce5c9c2cf2fe3bb748a6020b11d168022b9
/Project/human.cpp
bfbdfe7fcf41124d18ea13d31b57fb7a6b08dd52
[]
no_license
marcosrodrigueza/DLRSHIP-miniproject
90bd86788b16c0c9a8ea711a7e318fd35061809a
34461de2176dde9261a51d8d1ed58d26ea79d25c
refs/heads/master
2021-08-27T23:19:23.182948
2017-12-09T23:42:44
2017-12-09T23:42:44
107,995,800
4
0
null
null
null
null
UTF-8
C++
false
false
1,088
cpp
#include "human.h" Human::Human(string n, string planet_or): Owners(planet_or) { nif = n; cout << "Human Created succesfully" << endl; } void Human::editId(const string id) { nif = id; cout << "Your changes have been done" << endl; } string Human::getId() {return nif;} void Human::show() { cout << "-------------------------------------" << endl; cout << "nif:" << nif << endl; cout << "Planet: " << planet << endl; } bool Human::checkId(const string &n)const { bool selector = false; int error = 0; for(unsigned i = 0; i < n.size()-1; i++) { if(n[i] < 48 || n[i] > 57) error++; } if(n[n.size()-1] < 65 || n[n.size()-1] > 90) error++; if (error == 0) selector = true; if (n.size() != 9) { selector = false; // Last time added because we realize that the format can be introduced right without correct size } if (selector == false) cout << "--Not Human type--" << endl; return selector; } Human::~Human() { cout << "-Human deleted succesfully-" << endl; }
[ "marcooseslavalight@gmail.com" ]
marcooseslavalight@gmail.com
453010be51613836b98eae17f5607f9c608c259e
bb708fd2e3e90af730ee3dbfdde84eee0b164963
/src/main.cpp
54ef1cba23a9c0fc92fa9c707150bffd8aaac10f
[ "MIT" ]
permissive
GaryLee/QRegExpTester
ad8766648922977d0245b9471c98efa939f6578b
5eeac11017a6ddb46e3c803c11ea928d6a1a05f9
refs/heads/master
2020-05-16T22:52:17.194167
2014-06-17T06:12:31
2014-06-17T06:12:31
10,214,287
0
1
null
null
null
null
UTF-8
C++
false
false
312
cpp
/* * This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. */ #include "mainwindow.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }
[ "garywlee@gmail.com" ]
garywlee@gmail.com
6620ffa661617cb426b7f2a6661c8788ababf934
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_2652486_0/C++/Williamacm/main.cpp
5f91e210fbaffc0904241e1b49463fd2619b27f6
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
1,212
cpp
#include <iostream> #include <stdio.h> #include <string.h> using namespace std; int r,n,m,k; int a[109][10],no[3]; bool check(int v) { if(v==1) return 1; for(int i=0;i<n;i++) if(no[i]==v) return 1; for(int i=0;i<n;i++) for(int j=i+1;j<n;j++) if(no[i]*no[j]==v) return 1; if(n==3&&no[0]*no[1]*no[2]==v) return 1; return 0; } bool fin; void dfs(int ca,int p) { if(p==n) { for(int i=0;i<k;i++) if(!check(a[ca][i])) return; fin=1; for(int i=0;i<n;i++) { printf("%d",no[i]); } return; } for(int i=2;i<=m;i++) { no[p]=i; dfs(ca,p+1); if(fin) return; } } void init() { cin>>r>>n>>m>>k; for(int i=0;i<r;i++) for(int j=0;j<k;j++) scanf("%d",&a[i][j]); for(int i=0;i<r;i++) { fin=0; dfs(i,0); puts(""); } } int main() { freopen("in.txt","r",stdin); freopen("out.txt","w",stdout); int w; cin>>w; for(int id=1;id<=w;id++) { printf("Case #%d:\n",id); init(); } // cout << "Hello world!" << endl; return 0; }
[ "eewestman@gmail.com" ]
eewestman@gmail.com
07973199e2ed13d46b64e809845d2ee595595932
de2b46cafe8e3e5a81a1ee88994915deacaa68f6
/GuruxDLMS/Objects/GXDLMSActivityCalendar.cpp
10a83d6306e4751c20cf0212f1abfadde175de8f
[]
no_license
rizqevo/GuruxDLMSLib
8ed703790b618a53b14ae2f8656d20aae4ed506a
434c5da53fde147e747c5a9b1b94056f7e7a2689
refs/heads/master
2020-12-26T01:38:21.613174
2016-03-18T12:45:55
2016-03-18T12:45:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
21,413
cpp
// // -------------------------------------------------------------------------- // Gurux Ltd // // // // Filename: $HeadURL$ // // Version: $Revision$, // $Date$ // $Author$ // // Copyright (c) Gurux Ltd // //--------------------------------------------------------------------------- // // DESCRIPTION // // This file is a part of Gurux Device Framework. // // Gurux Device Framework is Open Source software; you can redistribute it // and/or modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 of the License. // Gurux Device Framework is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU General Public License for more details. // // More information of Gurux products: http://www.gurux.org // // This code is licensed under the GNU General Public License v2. // Full text may be retrieved at http://www.gnu.org/licenses/gpl-2.0.txt //--------------------------------------------------------------------------- #include "../GXDLMSVariant.h" #include "../GXDLMSClient.h" #include "GXDLMSActivityCalendar.h" #include <sstream> //Constructor. CGXDLMSActivityCalendar::CGXDLMSActivityCalendar() : CGXDLMSObject(OBJECT_TYPE_ACTIVITY_CALENDAR, "0.0.13.0.0.255") { } //SN Constructor. CGXDLMSActivityCalendar::CGXDLMSActivityCalendar(unsigned short sn) : CGXDLMSObject(OBJECT_TYPE_ACTIVITY_CALENDAR, sn) { } //LN Constructor. CGXDLMSActivityCalendar::CGXDLMSActivityCalendar(basic_string<char> ln) : CGXDLMSObject(OBJECT_TYPE_ACTIVITY_CALENDAR, ln) { } basic_string<char> CGXDLMSActivityCalendar::GetCalendarNameActive() { return m_CalendarNameActive; } void CGXDLMSActivityCalendar::SetCalendarNameActive(basic_string<char> value) { m_CalendarNameActive = value; } vector<CGXDLMSSeasonProfile> CGXDLMSActivityCalendar::GetSeasonProfileActive() { return m_SeasonProfileActive; } void CGXDLMSActivityCalendar::SetSeasonProfileActive(vector<CGXDLMSSeasonProfile> value) { m_SeasonProfileActive = value; } vector<CGXDLMSWeekProfile> CGXDLMSActivityCalendar::GetWeekProfileTableActive() { return m_WeekProfileTableActive; } void CGXDLMSActivityCalendar::SetWeekProfileTableActive(vector<CGXDLMSWeekProfile> value) { m_WeekProfileTableActive = value; } vector<CGXDLMSDayProfile> CGXDLMSActivityCalendar::GetDayProfileTableActive() { return m_DayProfileTableActive; } void CGXDLMSActivityCalendar::SetDayProfileTableActive(vector<CGXDLMSDayProfile> value) { m_DayProfileTableActive = value; } basic_string<char> CGXDLMSActivityCalendar::GetCalendarNamePassive() { return m_CalendarNamePassive; } void CGXDLMSActivityCalendar::SetCalendarNamePassive(basic_string<char> value) { m_CalendarNamePassive = value; } vector<CGXDLMSSeasonProfile> CGXDLMSActivityCalendar::GetSeasonProfilePassive() { return m_SeasonProfilePassive; } void CGXDLMSActivityCalendar::SetSeasonProfilePassive(vector<CGXDLMSSeasonProfile> value) { m_SeasonProfilePassive = value; } vector<CGXDLMSWeekProfile> CGXDLMSActivityCalendar::GetWeekProfileTablePassive() { return m_WeekProfileTablePassive; } void CGXDLMSActivityCalendar::SetWeekProfileTablePassive(vector<CGXDLMSWeekProfile> value) { m_WeekProfileTablePassive = value; } vector<CGXDLMSDayProfile> CGXDLMSActivityCalendar::GetDayProfileTablePassive() { return m_DayProfileTablePassive; } void CGXDLMSActivityCalendar::SetDayProfileTablePassive(vector<CGXDLMSDayProfile> value) { m_DayProfileTablePassive = value; } CGXDateTime& CGXDLMSActivityCalendar::GetTime() { return m_Time; } void CGXDLMSActivityCalendar::SetTime(CGXDateTime& value) { m_Time = value; } // Returns amount of attributes. int CGXDLMSActivityCalendar::GetAttributeCount() { return 10; } // Returns amount of methods. int CGXDLMSActivityCalendar::GetMethodCount() { return 1; } void CGXDLMSActivityCalendar::GetValues(vector<string>& values) { values.clear(); string ln; GetLogicalName(ln); values.push_back(ln); values.push_back(m_CalendarNameActive); std::stringstream sb; sb << '['; bool empty = true; for(vector<CGXDLMSSeasonProfile>::iterator it = m_SeasonProfileActive.begin(); it != m_SeasonProfileActive.end(); ++it) { if (!empty) { sb << ", "; } empty = false; string str = it->ToString(); sb.write(str.c_str(), str.size()); } sb << ']'; values.push_back(sb.str()); sb.str(std::string()); sb << '['; empty = true; for(vector<CGXDLMSWeekProfile>::iterator it = m_WeekProfileTableActive.begin(); it != m_WeekProfileTableActive.end(); ++it) { if (!empty) { sb << ", "; } empty = false; string str = it->ToString(); sb.write(str.c_str(), str.size()); } sb << ']'; values.push_back(sb.str()); sb.str(std::string()); sb << '['; empty = true; for(vector<CGXDLMSDayProfile>::iterator it = m_DayProfileTableActive.begin(); it != m_DayProfileTableActive.end(); ++it) { if (!empty) { sb << ", "; } empty = false; string str = it->ToString(); sb.write(str.c_str(), str.size()); } sb << ']'; values.push_back(sb.str()); sb.str(std::string()); values.push_back(m_CalendarNamePassive); sb << '['; empty = true; for(vector<CGXDLMSSeasonProfile>::iterator it = m_SeasonProfilePassive.begin(); it != m_SeasonProfilePassive.end(); ++it) { if (!empty) { sb << ", "; } empty = false; string str = it->ToString(); sb.write(str.c_str(), str.size()); } sb << ']'; values.push_back(sb.str()); sb.str(std::string()); sb << '['; empty = true; for(vector<CGXDLMSWeekProfile>::iterator it = m_WeekProfileTablePassive.begin(); it != m_WeekProfileTablePassive.end(); ++it) { if (!empty) { sb << ", "; } empty = false; string str = it->ToString(); sb.write(str.c_str(), str.size()); } sb << ']'; values.push_back(sb.str()); sb.str(std::string()); sb << '['; empty = true; for(vector<CGXDLMSDayProfile>::iterator it = m_DayProfileTablePassive.begin(); it != m_DayProfileTablePassive.end(); ++it) { if (!empty) { sb << ", "; } empty = false; string str = it->ToString(); sb.write(str.c_str(), str.size()); } sb << ']'; values.push_back(sb.str()); sb.str(std::string()); values.push_back(m_Time.ToString()); } void CGXDLMSActivityCalendar::GetAttributeIndexToRead(vector<int>& attributes) { //LN is static and read only once. if (CGXOBISTemplate::IsLogicalNameEmpty(m_LN)) { attributes.push_back(1); } //CalendarNameActive if (CanRead(2)) { attributes.push_back(2); } //SeasonProfileActive if (CanRead(3)) { attributes.push_back(3); } //WeekProfileTableActive if (CanRead(4)) { attributes.push_back(4); } //DayProfileTableActive if (CanRead(5)) { attributes.push_back(5); } //CalendarNamePassive if (CanRead(6)) { attributes.push_back(6); } //SeasonProfilePassive if (CanRead(7)) { attributes.push_back(7); } //WeekProfileTablePassive if (CanRead(8)) { attributes.push_back(8); } //DayProfileTablePassive if (CanRead(9)) { attributes.push_back(9); } //Time. if (CanRead(10)) { attributes.push_back(10); } } int CGXDLMSActivityCalendar::GetDataType(int index, DLMS_DATA_TYPE& type) { if (index == 1) { type = DLMS_DATA_TYPE_OCTET_STRING; return ERROR_CODES_OK; } if (index == 2) { type = DLMS_DATA_TYPE_OCTET_STRING; return ERROR_CODES_OK; } if (index == 3) { type = DLMS_DATA_TYPE_ARRAY; return ERROR_CODES_OK; } if (index == 4) { type = DLMS_DATA_TYPE_ARRAY; return ERROR_CODES_OK; } if (index == 5) { type = DLMS_DATA_TYPE_ARRAY; return ERROR_CODES_OK; } if (index == 6) { type = DLMS_DATA_TYPE_OCTET_STRING; return ERROR_CODES_OK; } if (index == 7) { type = DLMS_DATA_TYPE_ARRAY; return ERROR_CODES_OK; } if (index == 8) { type = DLMS_DATA_TYPE_ARRAY; return ERROR_CODES_OK; } if (index == 9) { type = DLMS_DATA_TYPE_ARRAY; return ERROR_CODES_OK; } if (index == 10) { type = DLMS_DATA_TYPE_DATETIME; return ERROR_CODES_OK; } return ERROR_CODES_INVALID_PARAMETER; } // Returns value of given attribute. int CGXDLMSActivityCalendar::GetValue(int index, int selector, CGXDLMSVariant& parameters, CGXDLMSVariant& value) { if (index == 1) { GXHelpers::AddRange(value.byteArr, m_LN, 6); value.vt = DLMS_DATA_TYPE_OCTET_STRING; return ERROR_CODES_OK; } if (index == 2) { value.Add(&m_CalendarNameActive[0], m_CalendarNameActive.size()); return ERROR_CODES_OK; } if (index == 3) { vector<unsigned char> data; data.push_back(DLMS_DATA_TYPE_ARRAY); int cnt = m_SeasonProfileActive.size(); //Add count CGXOBISTemplate::SetObjectCount(cnt, data); for (vector<CGXDLMSSeasonProfile>::iterator it = m_SeasonProfileActive.begin(); it != m_SeasonProfileActive.end(); ++it) { data.push_back(DLMS_DATA_TYPE_STRUCTURE); data.push_back(3); CGXDLMSVariant tmp; tmp.Add((*it).GetName()); CGXOBISTemplate::SetData(data, DLMS_DATA_TYPE_OCTET_STRING, tmp); CGXOBISTemplate::SetData(data, DLMS_DATA_TYPE_OCTET_STRING, (*it).GetStart()); tmp.Clear(); tmp.Add((*it).GetWeekName()); CGXOBISTemplate::SetData(data, DLMS_DATA_TYPE_OCTET_STRING, tmp); } value = data; return ERROR_CODES_OK; } if (index == 4) { vector<unsigned char> data; data.push_back(DLMS_DATA_TYPE_ARRAY); int cnt = m_WeekProfileTableActive.size(); //Add count CGXOBISTemplate::SetObjectCount(cnt, data); for (vector<CGXDLMSWeekProfile>::iterator it = m_WeekProfileTableActive.begin(); it != m_WeekProfileTableActive.end(); ++it) { data.push_back(DLMS_DATA_TYPE_ARRAY); data.push_back(8); CGXDLMSVariant tmp; tmp.Add((*it).GetName()); CGXOBISTemplate::SetData(data, DLMS_DATA_TYPE_OCTET_STRING, tmp); CGXOBISTemplate::SetData(data, DLMS_DATA_TYPE_UINT8, (*it).GetMonday()); CGXOBISTemplate::SetData(data, DLMS_DATA_TYPE_UINT8, (*it).GetTuesday()); CGXOBISTemplate::SetData(data, DLMS_DATA_TYPE_UINT8, (*it).GetWednesday()); CGXOBISTemplate::SetData(data, DLMS_DATA_TYPE_UINT8, (*it).GetThursday()); CGXOBISTemplate::SetData(data, DLMS_DATA_TYPE_UINT8, (*it).GetFriday()); CGXOBISTemplate::SetData(data, DLMS_DATA_TYPE_UINT8, (*it).GetSaturday()); CGXOBISTemplate::SetData(data, DLMS_DATA_TYPE_UINT8, (*it).GetSunday()); } value = data; return ERROR_CODES_OK; } if (index == 5) { vector<unsigned char> data; data.push_back(DLMS_DATA_TYPE_ARRAY); int cnt = m_DayProfileTableActive.size(); //Add count CGXOBISTemplate::SetObjectCount(cnt, data); for (vector<CGXDLMSDayProfile>::iterator it = m_DayProfileTableActive.begin(); it != m_DayProfileTableActive.end(); ++it) { data.push_back(DLMS_DATA_TYPE_STRUCTURE); data.push_back(2); CGXOBISTemplate::SetData(data, DLMS_DATA_TYPE_UINT8, (*it).GetDayId()); data.push_back(DLMS_DATA_TYPE_ARRAY); //Add count vector<CGXDLMSDayProfileAction>& schedules = (*it).GetDaySchedules(); CGXOBISTemplate::SetObjectCount(schedules.size(), data); for (vector<CGXDLMSDayProfileAction>::iterator action = schedules.begin(); action != schedules.end(); ++action) { CGXOBISTemplate::SetData(data, DLMS_DATA_TYPE_OCTET_STRING, (*action).GetStartTime()); CGXOBISTemplate::SetData(data, DLMS_DATA_TYPE_OCTET_STRING, (*action).GetScriptLogicalName()); CGXOBISTemplate::SetData(data, DLMS_DATA_TYPE_UINT16, (*action).GetScriptSelector()); } } value = data; return ERROR_CODES_OK; } if (index == 6) { value.Add(m_CalendarNamePassive); return ERROR_CODES_OK; } // if (index == 7) { vector<unsigned char> data; data.push_back(DLMS_DATA_TYPE_ARRAY); int cnt = m_SeasonProfilePassive.size(); //Add count CGXOBISTemplate::SetObjectCount(cnt, data); for (vector<CGXDLMSSeasonProfile>::iterator it = m_SeasonProfilePassive.begin(); it != m_SeasonProfilePassive.end(); ++it) { data.push_back(DLMS_DATA_TYPE_STRUCTURE); data.push_back(3); CGXDLMSVariant tmp; tmp.Add((*it).GetName()); CGXOBISTemplate::SetData(data, DLMS_DATA_TYPE_OCTET_STRING, tmp); CGXOBISTemplate::SetData(data, DLMS_DATA_TYPE_OCTET_STRING, (*it).GetStart()); tmp.Clear(); tmp.Add((*it).GetWeekName()); CGXOBISTemplate::SetData(data, DLMS_DATA_TYPE_OCTET_STRING, tmp); } value = data; return ERROR_CODES_OK; } if (index == 8) { vector<unsigned char> data; data.push_back(DLMS_DATA_TYPE_ARRAY); int cnt = m_WeekProfileTablePassive.size(); //Add count CGXOBISTemplate::SetObjectCount(cnt, data); for (vector<CGXDLMSWeekProfile>::iterator it = m_WeekProfileTablePassive.begin(); it != m_WeekProfileTablePassive.end(); ++it) { data.push_back(DLMS_DATA_TYPE_ARRAY); data.push_back(8); CGXDLMSVariant tmp; tmp.Add((*it).GetName()); CGXOBISTemplate::SetData(data, DLMS_DATA_TYPE_OCTET_STRING, tmp); CGXOBISTemplate::SetData(data, DLMS_DATA_TYPE_UINT8, (*it).GetMonday()); CGXOBISTemplate::SetData(data, DLMS_DATA_TYPE_UINT8, (*it).GetTuesday()); CGXOBISTemplate::SetData(data, DLMS_DATA_TYPE_UINT8, (*it).GetWednesday()); CGXOBISTemplate::SetData(data, DLMS_DATA_TYPE_UINT8, (*it).GetThursday()); CGXOBISTemplate::SetData(data, DLMS_DATA_TYPE_UINT8, (*it).GetFriday()); CGXOBISTemplate::SetData(data, DLMS_DATA_TYPE_UINT8, (*it).GetSaturday()); CGXOBISTemplate::SetData(data, DLMS_DATA_TYPE_UINT8, (*it).GetSunday()); } value = data; return ERROR_CODES_OK; } if (index == 9) { vector<unsigned char> data; data.push_back(DLMS_DATA_TYPE_ARRAY); int cnt = m_DayProfileTablePassive.size(); //Add count CGXOBISTemplate::SetObjectCount(cnt, data); for (vector<CGXDLMSDayProfile>::iterator it = m_DayProfileTablePassive.begin(); it != m_DayProfileTablePassive.end(); ++it) { data.push_back(DLMS_DATA_TYPE_STRUCTURE); data.push_back(2); CGXOBISTemplate::SetData(data, DLMS_DATA_TYPE_UINT8, (*it).GetDayId()); data.push_back(DLMS_DATA_TYPE_ARRAY); //Add count CGXOBISTemplate::SetObjectCount((*it).GetDaySchedules().size(), data); for (vector<CGXDLMSDayProfileAction>::iterator action = (*it).GetDaySchedules().begin(); action != (*it).GetDaySchedules().end(); ++action) { CGXOBISTemplate::SetData(data, DLMS_DATA_TYPE_OCTET_STRING, (*action).GetStartTime()); CGXOBISTemplate::SetData(data, DLMS_DATA_TYPE_OCTET_STRING, (*action).GetScriptLogicalName()); CGXOBISTemplate::SetData(data, DLMS_DATA_TYPE_UINT16, (*action).GetScriptSelector()); } } value = data; return ERROR_CODES_OK; } if (index == 10) { value = GetTime(); return ERROR_CODES_OK; } return ERROR_CODES_INVALID_PARAMETER; } // Set value of given attribute. int CGXDLMSActivityCalendar::SetValue(int index, CGXDLMSVariant& value) { if (index == 1) { if (value.vt != DLMS_DATA_TYPE_OCTET_STRING || value.GetSize() != 6) { return ERROR_CODES_INVALID_PARAMETER; } memcpy(m_LN, &value.byteArr[0], 6); } else if (index == 2) { CGXDLMSVariant tmp; CGXDLMSClient::ChangeType(value.byteArr, DLMS_DATA_TYPE_STRING, tmp); SetCalendarNameActive(tmp.strVal); } else if (index == 3) { m_SeasonProfileActive.clear(); for(vector<CGXDLMSVariant>::iterator item = value.Arr.begin(); item != value.Arr.end(); ++item) { CGXDLMSSeasonProfile it; CGXDLMSVariant tmp; CGXDLMSClient::ChangeType((*item).Arr[0].byteArr, DLMS_DATA_TYPE_STRING, tmp); it.SetName(tmp.strVal); CGXDLMSClient::ChangeType((*item).Arr[1].byteArr, DLMS_DATA_TYPE_DATETIME, tmp); it.SetStart(tmp.dateTime); CGXDLMSClient::ChangeType((*item).Arr[2].byteArr, DLMS_DATA_TYPE_STRING, tmp); it.SetWeekName(tmp.strVal); m_SeasonProfileActive.push_back(it); } } else if (index == 4) { m_WeekProfileTableActive.clear(); for(vector<CGXDLMSVariant>::iterator item = value.Arr.begin(); item != value.Arr.end(); ++item) { CGXDLMSVariant tmp; CGXDLMSWeekProfile it; CGXDLMSClient::ChangeType((*item).Arr[0].byteArr, DLMS_DATA_TYPE_STRING, tmp); it.SetName(tmp.strVal); it.SetMonday((*item).Arr[1].lVal); it.SetTuesday((*item).Arr[1].lVal); it.SetWednesday((*item).Arr[1].lVal); it.SetThursday((*item).Arr[1].lVal); it.SetFriday((*item).Arr[1].lVal); it.SetSaturday((*item).Arr[1].lVal); it.SetSunday((*item).Arr[1].lVal); m_WeekProfileTableActive.push_back(it); } } else if (index == 5) { m_DayProfileTableActive.clear(); for(vector<CGXDLMSVariant>::iterator item = value.Arr.begin(); item != value.Arr.end(); ++item) { CGXDLMSDayProfile it; it.SetDayId(item->Arr[0].ToInteger()); for(vector<CGXDLMSVariant>::iterator it2 = (*item).Arr[1].Arr.begin(); it2 != (*item).Arr[1].Arr.end(); ++it2) { CGXDLMSDayProfileAction ac; CGXDLMSVariant tmp; CGXDLMSClient::ChangeType(it2->Arr[0].byteArr, DLMS_DATA_TYPE_TIME, tmp); ac.SetStartTime(tmp.dateTime); CGXDLMSClient::ChangeType(it2->Arr[1].byteArr, DLMS_DATA_TYPE_STRING, tmp); ac.SetScriptLogicalName(tmp.strVal); ac.SetScriptSelector(it2->Arr[2].ToInteger()); it.GetDaySchedules().push_back(ac); } m_DayProfileTableActive.push_back(it); } } else if (index == 6) { CGXDLMSVariant tmp; CGXDLMSClient::ChangeType(value.byteArr, DLMS_DATA_TYPE_STRING, tmp); SetCalendarNamePassive(tmp.strVal); } else if (index == 7) { for(vector<CGXDLMSVariant>::iterator item = value.Arr.begin(); item != value.Arr.end(); ++item) { CGXDLMSSeasonProfile it; CGXDLMSVariant tmp; CGXDLMSClient::ChangeType((*item).Arr[0].byteArr, DLMS_DATA_TYPE_STRING, tmp); it.SetName(tmp.strVal); CGXDLMSClient::ChangeType((*item).Arr[1].byteArr, DLMS_DATA_TYPE_DATETIME, tmp); it.SetStart(tmp.dateTime); CGXDLMSClient::ChangeType((*item).Arr[2].byteArr, DLMS_DATA_TYPE_STRING, tmp); it.SetWeekName(tmp.strVal); m_SeasonProfilePassive.push_back(it); } } else if (index == 8) { for(vector<CGXDLMSVariant>::iterator item = value.Arr.begin(); item != value.Arr.end(); ++item) { CGXDLMSWeekProfile it; CGXDLMSVariant tmp; CGXDLMSClient::ChangeType((*item).Arr[0].byteArr, DLMS_DATA_TYPE_STRING, tmp); it.SetName(tmp.strVal); it.SetMonday((*item).Arr[1].lVal); it.SetTuesday((*item).Arr[2].lVal); it.SetWednesday((*item).Arr[3].lVal); it.SetThursday((*item).Arr[4].lVal); it.SetFriday((*item).Arr[5].lVal); it.SetSaturday((*item).Arr[6].lVal); it.SetSunday((*item).Arr[7].lVal); m_WeekProfileTablePassive.push_back(it); } } else if (index == 9) { for(vector<CGXDLMSVariant>::iterator item = value.Arr.begin(); item != value.Arr.end(); ++item) { CGXDLMSDayProfile it; it.SetDayId((*item).Arr[0].lVal); for(vector<CGXDLMSVariant>::iterator it2 = (*item).Arr[1].Arr.begin(); it2 != (*item).Arr[1].Arr.end(); ++it2) { CGXDLMSDayProfileAction ac; CGXDLMSVariant tmp; CGXDLMSClient::ChangeType((*it2).Arr[0].byteArr, DLMS_DATA_TYPE_TIME, tmp); ac.SetStartTime(tmp.dateTime); CGXDLMSClient::ChangeType((*it2).Arr[1].byteArr, DLMS_DATA_TYPE_STRING, tmp); ac.SetScriptLogicalName(tmp.strVal); ac.SetScriptSelector((*it2).Arr[2].lVal); it.GetDaySchedules().push_back(ac); } m_DayProfileTablePassive.push_back(it); } } else if (index == 10) { CGXDLMSVariant tmp; CGXDLMSClient::ChangeType(value.byteArr, DLMS_DATA_TYPE_DATETIME, tmp); SetTime(tmp.dateTime); } else { return ERROR_CODES_INVALID_PARAMETER; } return ERROR_CODES_OK; }
[ "mikko.kurunsaari@gurux.fi" ]
mikko.kurunsaari@gurux.fi
781d8c0884e62365ebf8cdd2c2cd2bea058a9477
cefd6c17774b5c94240d57adccef57d9bba4a2e9
/WebKit/Source/JavaScriptCore/llint/LLIntData.h
8dd43b4e1c51cc31f702b836ad8399d3287fd956
[ "BSL-1.0" ]
permissive
adzhou/oragle
9c054c25b24ff0a65cb9639bafd02aac2bcdce8b
5442d418b87d0da161429ffa5cb83777e9b38e4d
refs/heads/master
2022-11-01T05:04:59.368831
2014-03-12T15:50:08
2014-03-12T15:50:08
17,238,063
0
1
BSL-1.0
2022-10-18T04:23:53
2014-02-27T05:39:44
C++
UTF-8
C++
false
false
3,038
h
/* * Copyright (C) 2011 Apple Inc. 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 APPLE INC. ``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 APPLE INC. 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 LLIntData_h #define LLIntData_h #include "JSCJSValue.h" #include "Opcode.h" namespace JSC { class VM; struct Instruction; #if ENABLE(LLINT_C_LOOP) typedef OpcodeID LLIntCode; #else typedef void (*LLIntCode)(); #endif namespace LLInt { #if ENABLE(LLINT) class Data { public: static void performAssertions(VM&); private: static Instruction* s_exceptionInstructions; static Opcode* s_opcodeMap; friend void initialize(); friend Instruction* exceptionInstructions(); friend Opcode* opcodeMap(); friend Opcode getOpcode(OpcodeID); friend void* getCodePtr(OpcodeID); }; void initialize(); inline Instruction* exceptionInstructions() { return Data::s_exceptionInstructions; } inline Opcode* opcodeMap() { return Data::s_opcodeMap; } inline Opcode getOpcode(OpcodeID id) { #if ENABLE(COMPUTED_GOTO_OPCODES) return Data::s_opcodeMap[id]; #else return static_cast<Opcode>(id); #endif } ALWAYS_INLINE void* getCodePtr(OpcodeID id) { return reinterpret_cast<void*>(getOpcode(id)); } #else // !ENABLE(LLINT) #if COMPILER(CLANG) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wmissing-noreturn" #endif class Data { public: static void performAssertions(VM&) { } }; #if COMPILER(CLANG) #pragma clang diagnostic pop #endif #endif // !ENABLE(LLINT) ALWAYS_INLINE void* getOpcode(void llintOpcode()) { return bitwise_cast<void*>(llintOpcode); } ALWAYS_INLINE void* getCodePtr(void glueHelper()) { return bitwise_cast<void*>(glueHelper); } ALWAYS_INLINE void* getCodePtr(JSC::EncodedJSValue glueHelper()) { return bitwise_cast<void*>(glueHelper); } } } // namespace JSC::LLInt #endif // LLIntData_h
[ "adzhou@hp.com" ]
adzhou@hp.com
14724db2d0b5e282eb2d4e8ed468b8675ab4275a
eec43b04a250260727e7d8bded8e923e57d27330
/Programming Code/2840.cpp
e787cf166535cc1670316bf2c5aea644983afdc0
[]
no_license
ShafiqurRohman/Competitive-programming
82e4c8c33c6e9e6236aca8daf4d6b24ce37089c6
84bdbe2abb7a6a927325c4c37ed8d15b1c082f2e
refs/heads/main
2023-06-25T14:23:18.371879
2021-07-25T17:10:04
2021-07-25T17:10:04
318,260,815
0
0
null
null
null
null
UTF-8
C++
false
false
195
cpp
#include<bits/stdc++.h> using namespace std; int main(){ long long int a,b; cin>>a>>b; long long int v=(4.0/3)*3.1415*a*a*a; long long int u=b/v; cout<<u<<endl; return 0; }
[ "SHAFIQ@DESKTOP-O8CRK89" ]
SHAFIQ@DESKTOP-O8CRK89
a8c3f7fd05a9292898e89082dbd76e39f0ff51d7
d61d05748a59a1a73bbf3c39dd2c1a52d649d6e3
/chromium/chrome/browser/search/search_suggest/search_suggest_loader_impl.cc
5481b39c46f03e549b57b54e137ce5c08f3b92ec
[ "BSD-3-Clause" ]
permissive
Csineneo/Vivaldi
4eaad20fc0ff306ca60b400cd5fad930a9082087
d92465f71fb8e4345e27bd889532339204b26f1e
refs/heads/master
2022-11-23T17:11:50.714160
2019-05-25T11:45:11
2019-05-25T11:45:11
144,489,531
5
4
BSD-3-Clause
2022-11-04T05:55:33
2018-08-12T18:04:37
null
UTF-8
C++
false
false
10,526
cc
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/search/search_suggest/search_suggest_loader_impl.h" #include <string> #include <utility> #include "base/bind.h" #include "base/callback.h" #include "base/json/json_writer.h" #include "base/strings/string_util.h" #include "base/values.h" #include "chrome/browser/search/search_suggest/search_suggest_data.h" #include "chrome/common/chrome_content_client.h" #include "chrome/common/webui_url_constants.h" #include "components/google/core/browser/google_url_tracker.h" #include "components/google/core/common/google_util.h" #include "components/signin/core/browser/chrome_connected_header_helper.h" #include "components/signin/core/browser/signin_header_helper.h" #include "components/variations/net/variations_http_headers.h" #include "content/public/common/service_manager_connection.h" #include "net/base/load_flags.h" #include "net/base/url_util.h" #include "net/http/http_status_code.h" #include "net/traffic_annotation/network_traffic_annotation.h" #include "services/data_decoder/public/cpp/safe_json_parser.h" #include "services/network/public/cpp/resource_request.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #include "services/network/public/cpp/simple_url_loader.h" #include "url/gurl.h" namespace { const char kNewTabSearchSuggestionsApiPath[] = "/async/newtab_suggestions"; const char kSearchSuggestResponsePreamble[] = ")]}'"; base::Optional<SearchSuggestData> JsonToSearchSuggestionData( const base::Value& value) { const base::DictionaryValue* dict = nullptr; if (!value.GetAsDictionary(&dict)) { DVLOG(1) << "Parse error: top-level dictionary not found"; return base::nullopt; } const base::DictionaryValue* update = nullptr; if (!dict->GetDictionary("update", &update)) { DVLOG(1) << "Parse error: no update"; return base::nullopt; } const base::DictionaryValue* query_suggestions = nullptr; if (!update->GetDictionary("query_suggestions", &query_suggestions)) { DVLOG(1) << "Parse error: no query_suggestions"; return base::nullopt; } // TODO(crbug.com/919905): Investigate if SafeHtml should be used here. std::string suggestions_html = std::string(); if (!query_suggestions->GetString("query_suggestions_with_html", &suggestions_html)) { DVLOG(1) << "Parse error: no query_suggestions_with_html"; return base::nullopt; } SearchSuggestData result; result.suggestions_html = suggestions_html; std::string end_of_body_script = std::string(); if (!query_suggestions->GetString("script", &end_of_body_script)) { DVLOG(1) << "Parse error: no script"; return base::nullopt; } result.end_of_body_script = end_of_body_script; int impression_cap_expire_time_ms; if (!query_suggestions->GetInteger("impression_cap_expire_time_ms", &impression_cap_expire_time_ms)) { DVLOG(1) << "Parse error: no impression_cap_expire_time_ms"; return base::nullopt; } result.impression_cap_expire_time_ms = impression_cap_expire_time_ms; int request_freeze_time_ms; if (!query_suggestions->GetInteger("request_freeze_time_ms", &request_freeze_time_ms)) { DVLOG(1) << "Parse error: no request_freeze_time_ms"; return base::nullopt; } result.request_freeze_time_ms = request_freeze_time_ms; int max_impressions; if (!query_suggestions->GetInteger("max_impressions", &max_impressions)) { DVLOG(1) << "Parse error: no max_impressions"; return base::nullopt; } result.max_impressions = max_impressions; return result; } } // namespace class SearchSuggestLoaderImpl::AuthenticatedURLLoader { public: using LoadDoneCallback = base::OnceCallback<void(const network::SimpleURLLoader* simple_loader, std::unique_ptr<std::string> response_body)>; AuthenticatedURLLoader( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, GURL api_url, LoadDoneCallback callback); ~AuthenticatedURLLoader() = default; void Start(); private: void OnURLLoaderComplete(std::unique_ptr<std::string> response_body); scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; const GURL api_url_; LoadDoneCallback callback_; // The underlying SimpleURLLoader which does the actual load. std::unique_ptr<network::SimpleURLLoader> simple_loader_; }; SearchSuggestLoaderImpl::AuthenticatedURLLoader::AuthenticatedURLLoader( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, GURL api_url, LoadDoneCallback callback) : url_loader_factory_(url_loader_factory), api_url_(std::move(api_url)), callback_(std::move(callback)) {} void SearchSuggestLoaderImpl::AuthenticatedURLLoader::Start() { net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("search_suggest_service", R"( semantics { sender: "Search Suggestion Service" description: "Downloads search suggestions to be shown on the New Tab Page to " "logged-in users based on their previous search history." trigger: "Displaying the new tab page, if Google is the " "configured search provider, and the user is signed in." data: "Google credentials if user is signed in." destination: GOOGLE_OWNED_SERVICE } policy { cookies_allowed: YES cookies_store: "user" setting: "Users can control this feature via selecting a non-Google default " "search engine in Chrome settings under 'Search Engine'. Users can " "opt out of this feature using a button attached to the suggestions." chrome_policy { DefaultSearchProviderEnabled { policy_options {mode: MANDATORY} DefaultSearchProviderEnabled: false } } })"); auto resource_request = std::make_unique<network::ResourceRequest>(); resource_request->url = api_url_; variations::AppendVariationsHeaderUnknownSignedIn( api_url_, variations::InIncognito::kNo, resource_request.get()); resource_request->request_initiator = url::Origin::Create(GURL(chrome::kChromeUINewTabURL)); simple_loader_ = network::SimpleURLLoader::Create(std::move(resource_request), traffic_annotation); simple_loader_->DownloadToString( url_loader_factory_.get(), base::BindOnce( &SearchSuggestLoaderImpl::AuthenticatedURLLoader::OnURLLoaderComplete, base::Unretained(this)), 1024 * 1024); } void SearchSuggestLoaderImpl::AuthenticatedURLLoader::OnURLLoaderComplete( std::unique_ptr<std::string> response_body) { std::move(callback_).Run(simple_loader_.get(), std::move(response_body)); } SearchSuggestLoaderImpl::SearchSuggestLoaderImpl( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, GoogleURLTracker* google_url_tracker, const std::string& application_locale) : url_loader_factory_(url_loader_factory), google_url_tracker_(google_url_tracker), application_locale_(application_locale), weak_ptr_factory_(this) {} SearchSuggestLoaderImpl::~SearchSuggestLoaderImpl() = default; void SearchSuggestLoaderImpl::Load(const std::string& blocklist, SearchSuggestionsCallback callback) { callbacks_.push_back(std::move(callback)); // Note: If there is an ongoing request, abandon it. It's possible that // something has changed in the meantime (e.g. signin state) that would make // the result obsolete. pending_request_ = std::make_unique<AuthenticatedURLLoader>( url_loader_factory_, GetApiUrl(blocklist), base::BindOnce(&SearchSuggestLoaderImpl::LoadDone, base::Unretained(this))); pending_request_->Start(); } GURL SearchSuggestLoaderImpl::GetLoadURLForTesting() const { std::string blocklist; return GetApiUrl(blocklist); } GURL SearchSuggestLoaderImpl::GetApiUrl(const std::string& blocklist) const { GURL google_base_url = google_util::CommandLineGoogleBaseURL(); if (!google_base_url.is_valid()) { google_base_url = google_url_tracker_->google_url(); } GURL api_url = google_base_url.Resolve(kNewTabSearchSuggestionsApiPath); api_url = net::AppendQueryParameter(api_url, "vtgb", blocklist); return api_url; } void SearchSuggestLoaderImpl::LoadDone( const network::SimpleURLLoader* simple_loader, std::unique_ptr<std::string> response_body) { // The loader will be deleted when the request is handled. std::unique_ptr<AuthenticatedURLLoader> deleter(std::move(pending_request_)); if (!response_body) { // This represents network errors (i.e. the server did not provide a // response). DVLOG(1) << "Request failed with error: " << simple_loader->NetError(); Respond(Status::TRANSIENT_ERROR, base::nullopt); return; } std::string response; response.swap(*response_body); // The response may start with )]}'. Ignore this. if (base::StartsWith(response, kSearchSuggestResponsePreamble, base::CompareCase::SENSITIVE)) { response = response.substr(strlen(kSearchSuggestResponsePreamble)); } data_decoder::SafeJsonParser::Parse( content::ServiceManagerConnection::GetForProcess()->GetConnector(), response, base::BindRepeating(&SearchSuggestLoaderImpl::JsonParsed, weak_ptr_factory_.GetWeakPtr()), base::BindRepeating(&SearchSuggestLoaderImpl::JsonParseFailed, weak_ptr_factory_.GetWeakPtr())); } void SearchSuggestLoaderImpl::JsonParsed(std::unique_ptr<base::Value> value) { base::Optional<SearchSuggestData> result = JsonToSearchSuggestionData(*value); Respond(result.has_value() ? Status::OK : Status::FATAL_ERROR, result); } void SearchSuggestLoaderImpl::JsonParseFailed(const std::string& message) { DVLOG(1) << "Parsing JSON failed: " << message; Respond(Status::FATAL_ERROR, base::nullopt); } void SearchSuggestLoaderImpl::Respond( Status status, const base::Optional<SearchSuggestData>& data) { for (auto& callback : callbacks_) { std::move(callback).Run(status, data); } callbacks_.clear(); }
[ "csineneo@gmail.com" ]
csineneo@gmail.com
984f3941dddc2b6013cce5c6d5479a86c71c2bdf
a3ecf6b0a02a1681dc7cb7568dd20859e490359e
/src/main.cpp
1d17eb9d100651a1268b3fa7ceedf0762e11f640
[]
no_license
GCarneiroA/sdl2template
801c461b58f9d17ae6a6cf14df865bd8cbd7d9a3
9d120fc7f9be8ee00a78c0dffb07cd7a5b9a8c33
refs/heads/master
2022-12-06T06:45:11.681871
2020-08-29T22:30:32
2020-08-29T22:30:32
291,232,195
0
0
null
null
null
null
UTF-8
C++
false
false
862
cpp
#include <SDL2/SDL.h> bool Running = true; SDL_Event mainEvent; int main(int argc, char **argv) { SDL_Init(SDL_INIT_VIDEO); SDL_Window *window = SDL_CreateWindow( "SDL2template", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0 ); SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_SOFTWARE); SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE); SDL_RenderClear(renderer); SDL_RenderPresent(renderer); // main application loop while (Running) { // main application events while (SDL_PollEvent(&mainEvent)) { // Quit event if (mainEvent.type == SDL_QUIT) { Running = false; } } } SDL_DestroyWindow(window); SDL_Quit(); return 0; }
[ "gcarneiroa@hotmail.com" ]
gcarneiroa@hotmail.com
209444b2dfa19218888cd7e97ce9acc55951eb1d
3d5d1c1e032c811a7973a327e94f13ba99e13eb6
/Camera.h
c7da0b09f2ec2c9a3ba058052ea4803f62eee9e0
[]
no_license
poetaster/timelapse
be0f08c2fde60b1678cf556816effa5b720c9c8f
657025baf95484f119e346271726d1c48552031f
refs/heads/master
2023-03-16T17:03:37.603865
2017-03-03T01:18:59
2017-03-03T01:18:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
943
h
#ifndef CAMERA_H #define CAMERA_H #include <QThread> class ImageProcessor; class QCamera; class QMediaRecorder; class QCameraImageCapture; class CameraFrameGrabber; class QTimer; /** * @brief Thread responsible for all camera signals * Lives in it's own thread, do not fuck with it. */ class Camera : public QThread { Q_OBJECT public: explicit Camera(QObject *parent = 0); signals: void frame(const QImage& img); void processedFrame(const QImage& img); public slots: void setImageProcessor(ImageProcessor* proc); protected: virtual void run() override; ImageProcessor* processor; QCamera* camera; CameraFrameGrabber* frameGrabber; // calls methods in this thread if they are called from another one QTimer* methodDelegator; //QMediaRecorder* mediaRecorder; //QCameraImageCapture* imageCapture; }; #endif // CAMERA_H
[ "jmareda@seznam.cz" ]
jmareda@seznam.cz
3f7a8d766f6741111be5f82d30705b7aa3953155
fba25049d7f760cc483371b3830bf21fe94779ec
/actividad11/act11.cpp
1b3c1770b26c475bad37db44643d56bc3b139eaf
[]
no_license
MarvoIke/Portafolio_00216219
994bf90143f5beaf1d50e99f527c30576db57536
b525b63bb72407d3d6799e39d23cecbea8520654
refs/heads/master
2020-07-09T23:03:26.054539
2019-11-11T05:47:30
2019-11-11T05:47:30
204,104,118
0
0
null
null
null
null
UTF-8
C++
false
false
422
cpp
#include <iostream> using namespace std; int main() { int cola[10]; int datos=0,n=1,opc=1,posi=0,frente=0; while(opc != 0) { switch(opc) { case 0: return 0; break; case 1: cout << "Digite un numero: "; cin >> n; posi=(frente + datos)%5; cola[posi]=n; datos++; break; } cout << "1. Agregar un numero " << endl; cout << "0. Salir \t Su opcion: "; cin >> opc; } return 0; }
[ "00216219²gmail.com" ]
00216219²gmail.com
b674941e1f8a275ab154c3514460a5af768f7e48
2054088f179a10d1ac9af2a7aa7aa9b5e67d40bf
/find-largest-value-in-each-tree-row/find-largest-value-in-each-tree-row.cpp
7bebde1668c5a2a1943899a3d122cfaa321262b9
[]
no_license
pradyumn263/my-leetcode
f03f5244a6d9f95fcfbc8c94edef80b30bc3cb31
f69d02c214465361658ff1db537f9624a5838574
refs/heads/main
2023-06-25T05:06:15.762764
2021-07-30T18:04:28
2021-07-30T18:04:28
370,429,137
0
0
null
null
null
null
UTF-8
C++
false
false
892
cpp
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<int> largestValues(TreeNode* root) { vector<int> res; traverse(root, 0, res); return res; } void traverse(TreeNode* root, int level, vector<int> &res) { if(!root) return; if (level == res.size()) res.push_back(root->val); if (root->val > res[level]) res[level] = root->val; traverse(root->left, level + 1, res); traverse(root->right, level + 1, res); } };
[ "50890905+pradyumn263@users.noreply.github.com" ]
50890905+pradyumn263@users.noreply.github.com
ac27a22da185b25f581f46f1287df2c8a1384913
39f85304733166ea1a6f770df0203bcb966f8be0
/src/ripple/ledger/impl/CachedSLEs.cpp
fe317263a9fff32d6a782e4f5fa378b3c4ca7fe5
[ "MIT-Wu", "MIT", "ISC", "BSL-1.0" ]
permissive
huahuolab/huahuod
ecb9570572f392fbc85d39935930f3e3bdf39883
f16d5e715d8175201c0c64b467ecc03be5f97841
refs/heads/master
2022-07-07T17:03:55.070702
2020-02-17T05:53:52
2020-02-17T05:53:52
241,029,489
16
15
NOASSERTION
2022-07-01T22:18:28
2020-02-17T05:46:22
C++
UTF-8
C++
false
false
1,954
cpp
//------------------------------------------------------------------------------ /* This file is part of rippled: https://github.com/ripple/rippled Copyright (c) 2012, 2013 Ripple Labs Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== #include <ripple/ledger/CachedSLEs.h> #include <vector> namespace ripple { void CachedSLEs::expire() { std::vector< std::shared_ptr<void const>> trash; { auto const expireTime = map_.clock().now() - timeToLive_; std::lock_guard< std::mutex> lock(mutex_); for (auto iter = map_.chronological.begin(); iter != map_.chronological.end(); ++iter) { if (iter.when() > expireTime) break; if (iter->second.unique()) { trash.emplace_back( std::move(iter->second)); iter = map_.erase(iter); } } } } double CachedSLEs::rate() const { std::lock_guard< std::mutex> lock(mutex_); auto const tot = hit_ + miss_; if (tot == 0) return 0; return double(hit_) / tot; } } // ripple
[ "huahuolab@gmail.com" ]
huahuolab@gmail.com
6eb167f5ce4fb06e70cc3a7c3b59e4a25af8a479
5e8e35d4c79798d9ca7176035b7bbc707b527e01
/firmware/Arduino/pmwMotorTest-ADC/pmwMotorTest-ADC.ino
7538f2578fa2f35bd2cb2c5c1bb8c4ed3f2b279d
[]
no_license
SteveMayze/GoGoGo
9baf265bad2ecb905533e90ed8fcd7bd71e1dd75
046b306a5cbcfa7cd79df0f0970b8a866698b053
refs/heads/master
2020-04-06T07:04:54.977455
2016-11-01T18:37:53
2016-11-01T18:37:53
37,485,145
0
0
null
null
null
null
UTF-8
C++
false
false
1,524
ino
#include <PinChangeInt.h> #include <PinChangeIntConfig.h> int lpwmPin = 11; int lstbyPin = 0; int linp1 = 1; int linp2 = 2; int rpwmPin = 10; int rstbyPin = 3; int rinp1 = 5; int rinp2 = 4; int potPin = 2; int speed = 0; void setup() { // put your setup code here, to run once: // Left pinMode(lstbyPin, OUTPUT); pinMode(linp1, OUTPUT); pinMode(linp2, OUTPUT); pinMode(lpwmPin, OUTPUT); // Right pinMode(rstbyPin, OUTPUT); pinMode(rinp1, OUTPUT); pinMode(rinp2, OUTPUT); pinMode(rpwmPin, OUTPUT); } void fullForward(int speed) { // Left digitalWrite(lstbyPin, HIGH); digitalWrite(lpwmPin, HIGH); digitalWrite(linp1, HIGH); digitalWrite(linp2, LOW); // Right digitalWrite(rstbyPin, HIGH); digitalWrite(rpwmPin, HIGH); digitalWrite(rinp1, HIGH); digitalWrite(rinp2, LOW); analogWrite(lpwmPin, speed); analogWrite(rpwmPin, speed); } void fullRev( int speed ){ digitalWrite(linp1, LOW); digitalWrite(linp2, HIGH); digitalWrite(rinp1, LOW); digitalWrite(rinp2, HIGH); digitalWrite(lstbyPin, HIGH); digitalWrite(rstbyPin, HIGH); analogWrite(lpwmPin, speed); analogWrite(rpwmPin, speed); } void allStop() { digitalWrite(linp1, LOW); digitalWrite(linp2, LOW); digitalWrite(rinp1, LOW); digitalWrite(rinp2, LOW); analogWrite(lpwmPin, 255); analogWrite(rpwmPin, 255); } void loop() { // put your main code here, to run repeatedly: speed = analogRead( potPin ) * 0.25; fullForward(speed); delay(1); }
[ "smayze@yahoo.com" ]
smayze@yahoo.com
3a5b162bae2251cff23062b8c8cd13ed2e4a053a
efd4bff3b752a1559f3595613a44afefc52767d1
/ulpi_wrapper/testbench/sc_vpi_clock.h
9d410ecdddfa44e22e899bc278962a8716a0cdf5
[]
no_license
Brightorange90/cores
1e8a72665472709cad7d5d3dad83759625146f5c
1ec49deea4fb4a494a61ebf960fb182025059f19
refs/heads/master
2020-06-07T14:40:55.236094
2019-04-23T16:10:45
2019-04-23T16:10:45
193,042,910
0
1
null
2019-06-21T06:24:47
2019-06-21T06:24:47
null
UTF-8
C++
false
false
2,174
h
#ifndef __SC_VPI_CLOCK_H__ #define __SC_VPI_CLOCK_H__ #include <systemc.h> #include <vpi_user.h> static int sc_vpi_clock_after_delay(p_cb_data cb_data); class sc_vpi_clock { public: sc_signal <bool> m_clk; int m_low_ns; int m_high_ns; uint64_t m_last_time; sc_module_name m_name; vpiHandle m_vpi_handle; sc_vpi_clock(sc_module_name name) : m_clk(name), m_name(name) { m_low_ns = 5; m_high_ns = 5; m_last_time = 0; m_vpi_handle = vpi_handle_by_name((const char*)name, NULL); sc_assert(m_vpi_handle != NULL); } void start(void) { after_delay(); } int after_delay(void) { bool clk_next = !m_clk.read(); s_vpi_time vpi_time_s; s_cb_data cb_data_s; vpi_time_s.type = vpiSimTime; vpi_time_s.high = 0; vpi_time_s.low = 0; s_vpi_value value_s; value_s.format = vpiIntVal; value_s.value.integer = clk_next; vpi_put_value(m_vpi_handle, &value_s, &vpi_time_s, vpiInertialDelay); // Setup wait time vpi_time_s.high = 0; vpi_time_s.low = clk_next ? m_high_ns : m_low_ns; vpi_time_s.type = vpiSimTime; m_clk.write(clk_next); // Get current time uint64_t time_value = 0; s_vpi_time time_now; time_now.type = vpiSimTime; vpi_get_time (0, &time_now); time_value = time_now.high; time_value <<= 32; time_value |= time_now.low; // Update systemC TB if(sc_pending_activity()) sc_start((int)(time_value-m_last_time),SC_NS); // Attach value change callbacks for outputs cb_data_s.user_data = (PLI_BYTE8*)this; cb_data_s.reason = cbAfterDelay; cb_data_s.cb_rtn = sc_vpi_clock_after_delay; cb_data_s.time = &vpi_time_s; cb_data_s.value = NULL; vpi_register_cb(&cb_data_s); } }; static int sc_vpi_clock_after_delay(p_cb_data cb_data) { sc_vpi_clock *p = (sc_vpi_clock*)cb_data->user_data; return p->after_delay(); } #endif
[ "ultraembedded.com@gmail.com" ]
ultraembedded.com@gmail.com
800ecb59c1a6460d7ebef87118d71383593f0a1d
7e8507b5baff820d87e092ff3bfdce6d28fb9203
/OscRealsenseCpp/osc_messages.h
78fc56fd8244d296a5d42600b69045fad8898d61
[ "MIT" ]
permissive
mpinner/RealsenseOscMulticast
47975e145d4db36ce8083ea1a13bda8f1a968de3
b9094be7f9fe460bcd432802cb091226426dd730
refs/heads/master
2021-09-14T05:44:33.837295
2018-05-08T19:27:19
2018-05-08T19:27:19
112,153,111
4
0
null
null
null
null
UTF-8
C++
false
false
1,351
h
#pragma once #include <stdio.h> #include <iostream> #include "timer.h" #include "osc/OscOutboundPacketStream.h" #include "ip/UdpSocket.h" class osc_messages { public: const int INTERVAL = 1; // In seconds char *camID; UdpTransmitSocket *transmitSocket; osc::OutboundPacketStream *packetStream; osc_messages(char *c, UdpTransmitSocket *t, osc::OutboundPacketStream *p) : camID(c), transmitSocket(t), packetStream(p) {}; ~osc_messages(); //void init(char *camID, UdpTransmitSocket transmitSocket, osc::OutboundPacketStream packetStream); void sendHeartbeat(int tick); void checkAndSendHeartbeat(); void cursorOpen(int tick); void cursorClose(int tick); // /cursor/camID/handedness <float x> <float y> <float z> void cursor(const char* handedness, float x, float y, float z); // /gesture/handedness/fingers <int thumb> <int index> <int middle> <int ring> <int pinky> void bend(const char* handedness, float f1, float f2, float f3, float f4, float f5); void bend(const char* handedness, int f1, int f2, int f3, int f4, int f5); // /midi/channel <int midi status> <int pitch> <int velocity> void midi_note_send(int status, int channel, int pitch, int velocity); void midi_note_on(int channel, int pitch, int velocity); void midi_note_off(int channel, int pitch); void cursorWithSuffix(int tick, char* suffix); };
[ "mpinner@gmail.com" ]
mpinner@gmail.com
964366b6bde7727e2250f37cd8b905c830449ecd
ee21b585dd1b31441735bce9451ca9d886482be9
/ViveDemoCpp/Intermediate/Build/Win64/UE4Editor/Development/ViveDemoCpp/PCH.ViveDemoCpp.cpp
995f2462575d013c7f1f414738e9d31e697c0a96
[]
no_license
ViveStudiosCN/ViveDemoCpp
63f77e03b6b8edba56f93414990607bf0572ea5c
8cc037fb73c57d6d4c2dd4158b4cba6749d546f3
refs/heads/master
2021-01-22T05:37:36.779599
2017-05-26T12:49:35
2017-05-26T12:49:35
92,481,298
0
0
null
null
null
null
UTF-8
C++
false
false
123
cpp
#include "D:/UE4_PRJ/ViveDemoCpp/ViveDemoCpp/Intermediate/Build/Win64/UE4Editor/Development/ViveDemoCpp/PCH.ViveDemoCpp.h"
[ "cnyuendon@gmail.com" ]
cnyuendon@gmail.com
759f1cb722fe54d3ed46ccc4fc7f5a077b832736
31f5cddb9885fc03b5c05fba5f9727b2f775cf47
/thirdparty/mlpack/thirdparty/armadillo/include/armadillo_bits/op_cor_bones.hpp
4d4fa4260bb2b526448e978ccea1d3bd57e6efaa
[ "MIT" ]
permissive
timi-liuliang/echo
2935a34b80b598eeb2c2039d686a15d42907d6f7
d6e40d83c86431a819c6ef4ebb0f930c1b4d0f24
refs/heads/master
2023-08-17T05:35:08.104918
2023-08-11T18:10:35
2023-08-11T18:10:35
124,620,874
822
102
MIT
2021-06-11T14:29:03
2018-03-10T04:07:35
C++
UTF-8
C++
false
false
1,227
hpp
// Copyright 2008-2016 Conrad Sanderson (http://conradsanderson.id.au) // Copyright 2008-2016 National ICT Australia (NICTA) // // 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. // ------------------------------------------------------------------------ //! \addtogroup op_cor //! @{ class op_cor { public: template<typename eT> inline static void direct_cor(Mat<eT>& out, const Mat<eT>& X, const uword norm_type); template<typename T> inline static void direct_cor(Mat< std::complex<T> >& out, const Mat< std::complex<T> >& X, const uword norm_type); template<typename T1> inline static void apply(Mat<typename T1::elem_type>& out, const Op<T1,op_cor>& in); }; //! @}
[ "qq79402005@gmail.com" ]
qq79402005@gmail.com
e4c1346b4a9ae91e7112adc7a91542065a4123e7
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5752104073297920_0/C++/strongoier/C.cpp
efbcebc0f7584bcc2fef574f1cd2aaa216a4fae5
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
489
cpp
#include <cstdio> int cs; inline void work() { int n, judge = 0; scanf("%d", &n); int score = 500; for (int i = 0; i < n; ++i) { int x; scanf("%d", &x); if (x > i) judge += score + i + 1 - x; else if (i < 800) judge += -x; } printf("Case #%d: %s\n", ++cs, judge > 0 ? "BAD" : "GOOD"); } int main() { int t; scanf("%d", &t); while (t--) work(); return 0; }
[ "eewestman@gmail.com" ]
eewestman@gmail.com
0c6bbcda75d3f2da6f76004e709ba458d28fa0d5
78918391a7809832dc486f68b90455c72e95cdda
/boost_lib/boost/bimap/container_adaptor/container_adaptor.hpp
77d79ffe45dfc3489f51df59b5844864a59a18b2
[ "MIT" ]
permissive
kyx0r/FA_Patcher
50681e3e8bb04745bba44a71b5fd04e1004c3845
3f539686955249004b4483001a9e49e63c4856ff
refs/heads/master
2022-03-28T10:03:28.419352
2020-01-02T09:16:30
2020-01-02T09:16:30
141,066,396
2
0
null
null
null
null
UTF-8
C++
false
false
7,534
hpp
// Boost.Bimap // // Copyright (c) 2006-2007 Matias Capeletto // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) /// \file container_adaptor/container_adaptor.hpp /// \brief Container adaptor to build a type that is compliant to the concept of a container. #ifndef BOOST_BIMAP_CONTAINER_ADAPTOR_CONTAINER_ADAPTOR_HPP #define BOOST_BIMAP_CONTAINER_ADAPTOR_CONTAINER_ADAPTOR_HPP #if defined(_MSC_VER) #pragma once #endif #include <boost/config.hpp> #include <utility> #include <boost/mpl/if.hpp> #include <boost/mpl/aux_/na.hpp> #include <boost/bimap/container_adaptor/detail/identity_converters.hpp> #include <boost/iterator/iterator_traits.hpp> #include <boost/bimap/container_adaptor/detail/functor_bag.hpp> #include <boost/mpl/vector.hpp> #include <boost/mpl/copy.hpp> #include <boost/mpl/front_inserter.hpp> #include <boost/call_traits.hpp> namespace boost { namespace bimaps { /// \brief Container Adaptor toolbox, easy way to build new containers from existing ones. namespace container_adaptor { /// \brief Container adaptor to build a type that is compliant to the concept of a container. template < class Base, class Iterator, class ConstIterator, class IteratorToBaseConverter = ::boost::mpl::na, class IteratorFromBaseConverter = ::boost::mpl::na, class ValueToBaseConverter = ::boost::mpl::na, class ValueFromBaseConverter = ::boost::mpl::na, class FunctorsFromDerivedClasses = mpl::vector<> > class container_adaptor { // MetaData ------------------------------------------------------------- public: typedef Iterator iterator; typedef ConstIterator const_iterator; typedef BOOST_DEDUCED_TYPENAME iterator_value < iterator >::type value_type; typedef BOOST_DEDUCED_TYPENAME iterator_pointer < iterator >::type pointer; typedef BOOST_DEDUCED_TYPENAME iterator_reference< iterator >::type reference; typedef BOOST_DEDUCED_TYPENAME iterator_reference< const_iterator >::type const_reference; typedef BOOST_DEDUCED_TYPENAME Base::size_type size_type; typedef BOOST_DEDUCED_TYPENAME Base::difference_type difference_type; typedef BOOST_DEDUCED_TYPENAME mpl::if_< ::boost::mpl::is_na<IteratorToBaseConverter>, // { ::boost::bimaps::container_adaptor::detail:: iterator_to_base_identity < BOOST_DEDUCED_TYPENAME Base::iterator, iterator, BOOST_DEDUCED_TYPENAME Base::const_iterator, const_iterator >, // } // else // { IteratorToBaseConverter // } >::type iterator_to_base; typedef BOOST_DEDUCED_TYPENAME mpl::if_< ::boost::mpl::is_na<IteratorFromBaseConverter>, // { ::boost::bimaps::container_adaptor::detail:: iterator_from_base_identity < BOOST_DEDUCED_TYPENAME Base::iterator, iterator, BOOST_DEDUCED_TYPENAME Base::const_iterator, const_iterator >, // } // else // { IteratorFromBaseConverter // } >::type iterator_from_base; typedef BOOST_DEDUCED_TYPENAME mpl::if_< ::boost::mpl::is_na<ValueToBaseConverter>, // { ::boost::bimaps::container_adaptor::detail:: value_to_base_identity < BOOST_DEDUCED_TYPENAME Base::value_type, value_type >, // } // else // { ValueToBaseConverter // } >::type value_to_base; typedef BOOST_DEDUCED_TYPENAME mpl::if_< ::boost::mpl::is_na<ValueFromBaseConverter>, // { ::boost::bimaps::container_adaptor::detail:: value_from_base_identity < BOOST_DEDUCED_TYPENAME Base::value_type, value_type >, // } // else // { ValueFromBaseConverter // } >::type value_from_base; // ACCESS ----------------------------------------------------------------- public: explicit container_adaptor(Base & c) : dwfb(c) {} protected: typedef Base base_type; typedef container_adaptor container_adaptor_; const Base & base() const { return dwfb.data; } Base & base() { return dwfb.data; } // Interface -------------------------------------------------------------- public: size_type size() const { return base().size(); } size_type max_size() const { return base().max_size(); } bool empty() const { return base().empty(); } iterator begin() { return this->template functor<iterator_from_base>()( base().begin() ); } iterator end() { return this->template functor<iterator_from_base>()( base().end() ); } const_iterator begin() const { return this->template functor<iterator_from_base>()( base().begin() ); } const_iterator end() const { return this->template functor<iterator_from_base>()( base().end() ); } iterator erase(iterator pos) { return this->template functor<iterator_from_base>()( base().erase(this->template functor<iterator_to_base>()(pos)) ); } iterator erase(iterator first, iterator last) { return this->template functor<iterator_from_base>()( base().erase( this->template functor<iterator_to_base>()(first), this->template functor<iterator_to_base>()(last) ) ); } void clear() { base().clear(); } template< class InputIterator > void insert(InputIterator iterBegin, InputIterator iterEnd) { for( ; iterBegin != iterEnd ; ++iterBegin ) { base().insert( this->template functor<value_to_base>()( *iterBegin ) ); } } std::pair<iterator, bool> insert( BOOST_DEDUCED_TYPENAME ::boost::call_traits< value_type >::param_type x) { std::pair< BOOST_DEDUCED_TYPENAME Base::iterator, bool > r( base().insert( this->template functor<value_to_base>()(x) ) ); return std::pair<iterator, bool>( this->template functor<iterator_from_base>()(r.first),r.second ); } iterator insert(iterator pos, BOOST_DEDUCED_TYPENAME ::boost::call_traits< value_type >::param_type x) { return this->template functor<iterator_from_base>()( base().insert( this->template functor<iterator_to_base>()(pos), this->template functor<value_to_base>()(x)) ); } void swap( container_adaptor & c ) { base().swap( c.base() ); } // Access to functors ---------------------------------------------------- protected: template< class Functor > Functor & functor() { return dwfb.template functor<Functor>(); } template< class Functor > Functor const & functor() const { return dwfb.template functor<Functor>(); } // Data ------------------------------------------------------------------ private: ::boost::bimaps::container_adaptor::detail::data_with_functor_bag < Base &, BOOST_DEDUCED_TYPENAME mpl::copy < mpl::vector < iterator_to_base, iterator_from_base, value_to_base, value_from_base >, mpl::front_inserter< FunctorsFromDerivedClasses > >::type > dwfb; }; } // namespace container_adaptor } // namespace bimaps } // namespace boost #endif // BOOST_BIMAP_CONTAINER_ADAPTOR_CONTAINER_ADAPTOR_HPP
[ "k.melekhin@gmail.com" ]
k.melekhin@gmail.com
cea5e69d6308892755f7f536244201d0521584ee
bf2e5b32db429a652c7f056ed5eb81db67c6832f
/pp1/Wednesday/week9/78879_2.cpp
453a22aea70df4899b357ca5a97d99c19b175607
[]
no_license
Beisenbek/kbtu-2018-fall-lecture-samples
6238ea274c669d9ec225ca98141ddde449649787
d51e72fa9e87d5152f9eb1352726c4f93d7b3259
refs/heads/master
2020-03-27T12:57:08.400510
2018-11-21T03:54:21
2018-11-21T03:54:21
146,580,401
3
3
null
null
null
null
UTF-8
C++
false
false
291
cpp
#include<iostream> using namespace std; bool f(int x){ if(x == 1) return true; if(x == 0 || x % 2 == 1) return false; return f(x / 2); } int main(){ long long x; cin >> x; if(f(x)){ cout << "Yes"; }else{ cout << "No"; } return 0; }
[ "beysenbek@gmail.com" ]
beysenbek@gmail.com
f18d5ec4b1b97cc64e19b804a00dee900c60a36a
3886f87b667eaa4a5bdfb22cf3f3dcaa28351016
/TESReloaded/Hooking/K32.cpp
2d5466686271b801e2b9e8064db3ae0a4a631b1c
[]
no_license
clayne/TES-Reloaded-Source
431214e6698a72bc2dd3ad79700e795422ea4730
45ffc88e0615bd510db3b9969ed2cbf608572c0e
refs/heads/master
2022-05-13T14:44:54.653622
2017-06-24T13:33:49
2017-06-24T13:33:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,337
cpp
#ifndef HOOKING_K32_CPP #define HOOKING_K32_CPP #include "K32.hpp" // Hook structure. enum { K32FN_LoadLibraryA = 0, // K32FN_LoadLibraryA = 1, K32FN_GetProcAddress = 1 }; SDLLHook K32Hook = { "kernel32.dll", NULL, false, NULL, // Default hook disabled, NULL function pointer. { { "LoadLibraryA", TESRLoadLibraryA}, // ANSI // { "LoadLibraryW", TESRLoadLibraryW}, // Unicode { "GetProcAddress", TESRGetProcAddress}, { NULL, NULL } } }; // Hook function. HMODULE WINAPI TESRLoadLibraryA(LPCTSTR dllName) { LoadLibraryA_t old_func = (LoadLibraryA_t) K32Hook.Functions[K32FN_LoadLibraryA].OrigFn; HMODULE hModDLL = old_func(dllName); // hook dyamically loaded D3D9 if ( lstrcmpi( "D3D9.DLL", dllName ) == 0 ) { D3DHook.hMod = hModDLL; _MESSAGE("DirectX: loaded."); // HookAPICalls(&D3DHook); } return hModDLL; } // Hook function. FARPROC WINAPI TESRGetProcAddress(HMODULE hModule, LPCSTR lpProcName) { GetProcAddress_t old_func = (GetProcAddress_t) K32Hook.Functions[K32FN_GetProcAddress].OrigFn; FARPROC jmp = old_func(hModule, lpProcName); // hook dyamically loaded D3D9 if ( D3DHook.hMod == hModule ) { FARPROC red; if ( ( red = (FARPROC)RedirectPA( &D3DHook, lpProcName, jmp ) ) ) { _MESSAGE("DirectX: hooked."); return red; } // HookAPICalls(&D3DHook); } return jmp; } #endif
[ "aletamburini78@gmail.com" ]
aletamburini78@gmail.com
b1343f644e10ebbb0041054901be6a3ac3810c0b
2939270daa498d290ded456e7f684bd8f1a02711
/Dont Touch The Spike v2.0/include/Spike.h
bfcb95b742b25c0fa16c19d65d9c4b14215fdf24
[]
no_license
tuananhlai/dont_touch_the_spike
bd95cecfee62cc47bfdcfa53919c34403f1cf8cc
52f6a11a1f8606479e2ef88af98982d6f3a49d51
refs/heads/master
2022-01-08T08:19:55.329484
2019-05-08T14:23:49
2019-05-08T14:23:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
841
h
#ifndef SPIKE_H #define SPIKE_H #include <iostream> #include <string> #include <vector> #include <SDL.h> #include <SDL_image.h> #include <SDL_ttf.h> #include <SDL_mixer.h> #include "Texture.h" #include "constant.h" using namespace std; class Spike: public Texture { public: Spike(); ~Spike(); void loadTexture(SDL_Renderer* renderer); void update(int &status, int &score, bool &isHittingWall); float getDx(int i); float getDy(int i); int getSpikeNumber(); void setSpikeNumber(int &score); protected: // vector <float> dx,dy; //t khai báo sẵn vận tốc gai cho rồi đấy :D int spike_number; private: }; class HardSpike: public Spike { private: int switchDirectionCounter = 0; protected: public: void moveSpikes(int, float, float); void hardUpdate(); }; #endif // SPIKE_H
[ "laituananh1711@gmail.com" ]
laituananh1711@gmail.com
57aad9ed9d44af3511e1c1e96beb09e23a202282
d688e8f1040846114bcc2f1afe5e6f98b531589b
/Source/Lexer.h
29e49c00414555297405d88b3ea6693097803f45
[]
no_license
mcmacker4/BooleanAlgebraParser
62879d963aedfc2d343c6e81801621ed87a6fd85
813cb516098b27468e11403e98856d7260d20282
refs/heads/master
2020-03-17T04:26:24.206438
2018-05-16T15:23:16
2018-05-16T15:23:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
612
h
#ifndef DISCRETEMATHSPARSER_LEXER_H #define DISCRETEMATHSPARSER_LEXER_H #include <queue> #include <istream> namespace Lexer { enum TokenType { VARIABLE, LITERAL, OPERATOR, LPAREN, RPAREN }; struct Token { TokenType type; char value; }; class LexException : public std::exception { public: const std::string message; explicit LexException(std::string message) : message(std::move(message)) {} }; std::queue<Token> Tokenize(std::istream &stream); } #endif //DISCRETEMATHSPARSER_LEXER_H
[ "mcmacker4@gmail.com" ]
mcmacker4@gmail.com
c85700672af49dda9344f1cc16a4d46c1a4cbe07
70418d8faa76b41715c707c54a8b0cddfb393fb3
/10769.cpp
f83ca66cf6c89fb4bc16fbe599c2dfb30951ed5f
[]
no_license
evandrix/UVa
ca79c25c8bf28e9e05cae8414f52236dc5ac1c68
17a902ece2457c8cb0ee70c320bf0583c0f9a4ce
refs/heads/master
2021-06-05T01:44:17.908960
2017-10-22T18:59:42
2017-10-22T18:59:42
107,893,680
3
1
null
null
null
null
UTF-8
C++
false
false
1,220
cpp
#include <bits/stdc++.h> using namespace std; char str[5000], *p; int w[100], nw; int b[100], nb; int H; int main() { int cases = 0; while (true) { if (gets(str) == NULL) { break; } if (strcmp(str, "") == 0) { continue; } sscanf(str, "%d", &H); gets(str); for (p = strtok(str, " "), nb = 0; p; p = strtok(NULL, " ")) { b[nb++] = atoi(p); } gets(str); for (p = strtok(str, " "), nw = 0; p; p = strtok(NULL, " ")) { w[nw++] = atoi(p); } for (int i = 0; i < nb; i++) for (int j = i + 1; j < nb; j++) if (b[i] < b[j]) { int t = b[i]; b[i] = b[j]; b[j] = t; } for (int i = 0; i < nw; i++) for (int j = i + 1; j < nw; j++) if (w[i] < w[j]) { int t = w[i]; w[i] = w[j]; w[j] = t; } bool flag = false; if (b[0] + b[1] + w[0] + w[1] >= H) { for (int i = 0; i < nb && !flag; i++) for (int j = 0; j < nw && !flag; j++) for (int k = i + 1; k < nb && !flag; k++) for (int l = j + 1; l < nw && !flag; l++) if (b[i] + w[j] + b[k] + w[l] == H) { printf("%d %d %d %d\n", b[i], w[j], b[k], w[l]); flag = true; } } if (!flag) { puts("no solution"); } } }
[ "yleewei@dso.org.sg" ]
yleewei@dso.org.sg
08764a7d98169715af2396c24a0f36028af6e3b1
6a9b7e3cd40dea425a33b4eaac442ca37eed0cb2
/src/protocols/AX25/AX25.h
7848850b3edefc69e5e2ced0370a1c1710e54f46
[ "MIT" ]
permissive
ivanpiter/RadioLib
e0b82926e9b670af6847719aa836a0d38f1a6efc
0c07b34e41c61b2aa8f52b126c88d17b9324f9ec
refs/heads/master
2023-07-23T10:20:29.857324
2021-09-03T08:26:53
2021-09-03T08:26:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,600
h
#if !defined(_RADIOLIB_AX25_H) #define _RADIOLIB_AX25_H #include "../../TypeDef.h" #if !defined(RADIOLIB_EXCLUDE_AX25) #include "../PhysicalLayer/PhysicalLayer.h" #include "../AFSK/AFSK.h" // macros to access bits in byte array, from http://www.mathcs.emory.edu/~cheung/Courses/255/Syllabus/1-C-intro/bit-array.html #define SET_BIT_IN_ARRAY(A, k) ( A[(k/8)] |= (1 << (k%8)) ) #define CLEAR_BIT_IN_ARRAY(A, k) ( A[(k/8)] &= ~(1 << (k%8)) ) #define TEST_BIT_IN_ARRAY(A, k) ( A[(k/8)] & (1 << (k%8)) ) #define GET_BIT_IN_ARRAY(A, k) ( (A[(k/8)] & (1 << (k%8))) ? 1 : 0 ) // CRC-CCITT calculation macros #define XOR(A, B) ( ((A) || (B)) && !((A) && (B)) ) #define CRC_CCITT_POLY 0x1021 // generator polynomial #define CRC_CCITT_POLY_REVERSED 0x8408 // CRC_CCITT_POLY in reversed bit order #define CRC_CCITT_INIT 0xFFFF // initial value // maximum callsign length in bytes #define AX25_MAX_CALLSIGN_LEN 6 // flag field MSB LSB DESCRIPTION #define AX25_FLAG 0b01111110 // 7 0 AX.25 frame start/end flag // address field #define AX25_SSID_COMMAND_DEST 0b10000000 // 7 7 frame type: command (set in destination SSID) #define AX25_SSID_COMMAND_SOURCE 0b00000000 // 7 7 command (set in source SSID) #define AX25_SSID_RESPONSE_DEST 0b00000000 // 7 7 response (set in destination SSID) #define AX25_SSID_RESPONSE_SOURCE 0b10000000 // 7 7 response (set in source SSID) #define AX25_SSID_HAS_NOT_BEEN_REPEATED 0b00000000 // 7 7 not repeated yet (set in repeater SSID) #define AX25_SSID_HAS_BEEN_REPEATED 0b10000000 // 7 7 repeated (set in repeater SSID) #define AX25_SSID_RESERVED_BITS 0b01100000 // 6 5 reserved bits in SSID #define AX25_SSID_HDLC_EXTENSION_CONTINUE 0b00000000 // 0 0 HDLC extension bit: next octet contains more address information #define AX25_SSID_HDLC_EXTENSION_END 0b00000001 // 0 0 address field end // control field #define AX25_CONTROL_U_SET_ASYNC_BAL_MODE 0b01101100 // 7 2 U frame type: set asynchronous balanced mode (connect request) #define AX25_CONTROL_U_SET_ASYNC_BAL_MODE_EXT 0b00101100 // 7 2 set asynchronous balanced mode extended (connect request with module 128) #define AX25_CONTROL_U_DISCONNECT 0b01000000 // 7 2 disconnect request #define AX25_CONTROL_U_DISCONNECT_MODE 0b00001100 // 7 2 disconnect mode (system busy or disconnected) #define AX25_CONTROL_U_UNNUMBERED_ACK 0b01100000 // 7 2 unnumbered acknowledge #define AX25_CONTROL_U_FRAME_REJECT 0b10000100 // 7 2 frame reject #define AX25_CONTROL_U_UNNUMBERED_INFORMATION 0b00000000 // 7 2 unnumbered information #define AX25_CONTROL_U_EXHANGE_IDENTIFICATION 0b10101100 // 7 2 exchange ID #define AX25_CONTROL_U_TEST 0b11100000 // 7 2 test #define AX25_CONTROL_POLL_FINAL_ENABLED 0b00010000 // 4 4 control field poll/final bit: enabled #define AX25_CONTROL_POLL_FINAL_DISABLED 0b00000000 // 4 4 disabled #define AX25_CONTROL_S_RECEIVE_READY 0b00000000 // 3 2 S frame type: receive ready (system ready to receive) #define AX25_CONTROL_S_RECEIVE_NOT_READY 0b00000100 // 3 2 receive not ready (TNC buffer full) #define AX25_CONTROL_S_REJECT 0b00001000 // 3 2 reject (out of sequence or duplicate) #define AX25_CONTROL_S_SELECTIVE_REJECT 0b00001100 // 3 2 selective reject (single frame repeat request) #define AX25_CONTROL_INFORMATION_FRAME 0b00000000 // 0 0 frame type: information (I frame) #define AX25_CONTROL_SUPERVISORY_FRAME 0b00000001 // 1 0 supervisory (S frame) #define AX25_CONTROL_UNNUMBERED_FRAME 0b00000011 // 1 0 unnumbered (U frame) // protocol identifier field #define AX25_PID_ISO_8208 0x01 #define AX25_PID_TCP_IP_COMPRESSED 0x06 #define AX25_PID_TCP_IP_UNCOMPRESSED 0x07 #define AX25_PID_SEGMENTATION_FRAGMENT 0x08 #define AX25_PID_TEXNET_DATAGRAM_PROTOCOL 0xC3 #define AX25_PID_LINK_QUALITY_PROTOCOL 0xC4 #define AX25_PID_APPLETALK 0xCA #define AX25_PID_APPLETALK_ARP 0xCB #define AX25_PID_ARPA_INTERNET_PROTOCOL 0xCC #define AX25_PID_ARPA_ADDRESS_RESOLUTION 0xCD #define AX25_PID_FLEXNET 0xCE #define AX25_PID_NET_ROM 0xCF #define AX25_PID_NO_LAYER_3 0xF0 #define AX25_PID_ESCAPE_CHARACTER 0xFF // AFSK tones in Hz #define AX25_AFSK_MARK 1200 #define AX25_AFSK_SPACE 2200 // tone duration in us (for 1200 baud AFSK) #define AX25_AFSK_TONE_DURATION 833 /*! \class AX25Frame \brief Abstraction of AX.25 frame format. */ class AX25Frame { public: /*! \brief Callsign of the destination station. */ char destCallsign[AX25_MAX_CALLSIGN_LEN + 1]; /*! \brief SSID of the destination station. */ uint8_t destSSID; /*! \brief Callsign of the source station. */ char srcCallsign[AX25_MAX_CALLSIGN_LEN + 1]; /*! \brief SSID of the source station. */ uint8_t srcSSID; /*! \brief Number of repeaters to be used. */ uint8_t numRepeaters; /*! \brief The control field. */ uint8_t control; /*! \brief The protocol identifier (PID) field. */ uint8_t protocolID; /*! \brief Number of bytes in the information field. */ uint16_t infoLen; /*! \brief Receive sequence number. */ uint8_t rcvSeqNumber; /*! \brief Send sequence number. */ uint16_t sendSeqNumber; #ifndef RADIOLIB_STATIC_ONLY /*! \brief The info field. */ uint8_t* info; /*! \brief Array of repeater callsigns. */ char** repeaterCallsigns; /*! \brief Array of repeater SSIDs. */ uint8_t* repeaterSSIDs; #else /*! \brief The info field. */ uint8_t info[RADIOLIB_STATIC_ARRAY_SIZE]; /*! \brief Array of repeater callsigns. */ char repeaterCallsigns[8][AX25_MAX_CALLSIGN_LEN + 1]; /*! \brief Array of repeater SSIDs. */ uint8_t repeaterSSIDs[8]; #endif /*! \brief Overloaded constructor, for frames without info field. \param destCallsign Callsign of the destination station. \param destSSID SSID of the destination station. \param srcCallsign Callsign of the source station. \param srcSSID SSID of the source station. \param control The control field. */ AX25Frame(const char* destCallsign, uint8_t destSSID, const char* srcCallsign, uint8_t srcSSID, uint8_t control); /*! \brief Overloaded constructor, for frames with C-string info field. \param destCallsign Callsign of the destination station. \param destSSID SSID of the destination station. \param srcCallsign Callsign of the source station. \param srcSSID SSID of the source station. \param control The control field. \param protocolID The protocol identifier (PID) field. Set to zero if the frame doesn't have this field. \param info Information field, in the form of null-terminated C-string. */ AX25Frame(const char* destCallsign, uint8_t destSSID, const char* srcCallsign, uint8_t srcSSID, uint8_t control, uint8_t protocolID, const char* info); /*! \brief Default constructor. \param destCallsign Callsign of the destination station. \param destSSID SSID of the destination station. \param srcCallsign Callsign of the source station. \param srcSSID SSID of the source station. \param control The control field. \param protocolID The protocol identifier (PID) field. Set to zero if the frame doesn't have this field. \param info Information field, in the form of arbitrary binary buffer. \param infoLen Number of bytes in the information field. */ AX25Frame(const char* destCallsign, uint8_t destSSID, const char* srcCallsign, uint8_t srcSSID, uint8_t control, uint8_t protocolID, uint8_t* info, uint16_t infoLen); /*! \brief Copy constructor. \param frame AX25Frame instance to copy. */ AX25Frame(const AX25Frame& frame); /*! \brief Default destructor. */ ~AX25Frame(); /*! \brief Overload for assignment operator. \param frame rvalue AX25Frame. */ AX25Frame& operator=(const AX25Frame& frame); /*! \brief Method to set the repeater callsigns and SSIDs. \param repeaterCallsigns Array of repeater callsigns in the form of null-terminated C-strings. \param repeaterSSIDs Array of repeater SSIDs. \param numRepeaters Number of repeaters, maximum is 8. \returns \ref status_codes */ int16_t setRepeaters(char** repeaterCallsigns, uint8_t* repeaterSSIDs, uint8_t numRepeaters); /*! \brief Method to set receive sequence number. \param seqNumber Sequence number to set, 0 to 7. */ void setRecvSequence(uint8_t seqNumber); /*! \brief Method to set send sequence number. \param seqNumber Sequence number to set, 0 to 7. */ void setSendSequence(uint8_t seqNumber); }; /*! \class AX25Client \brief Client for AX25 communication. */ class AX25Client { public: /*! \brief Constructor for 2-FSK mode. \param phy Pointer to the wireless module providing PhysicalLayer communication. */ explicit AX25Client(PhysicalLayer* phy); #if !defined(RADIOLIB_EXCLUDE_AFSK) /*! \brief Constructor for AFSK mode. \param audio Pointer to the AFSK instance providing audio. */ explicit AX25Client(AFSKClient* audio); #endif // basic methods /*! \brief Initialization method. \param srcCallsign Callsign of the source station. \param srcSSID 4-bit SSID of the source station (in case there are more stations with the same callsign). Defaults to 0. \param preambleLen Number of "preamble" bytes (AX25_FLAG) sent ahead of the actual AX.25 frame. Does not include the first AX25_FLAG byte, which is considered part of the frame. Defaults to 8. \returns \ref status_codes */ int16_t begin(const char* srcCallsign, uint8_t srcSSID = 0x00, uint8_t preambleLen = 8); /*! \brief Transmit unnumbered information (UI) frame. \param str Data to be sent. \param destCallsign Callsign of the destination station. \param destSSID 4-bit SSID of the destination station (in case there are more stations with the same callsign). Defaults to 0. \returns \ref status_codes */ int16_t transmit(const char* str, const char* destCallsign, uint8_t destSSID = 0x00); /*! \brief Transmit arbitrary AX.25 frame. \param frame Frame to be sent. \returns \ref status_codes */ int16_t sendFrame(AX25Frame* frame); #ifndef RADIOLIB_GODMODE private: #endif PhysicalLayer* _phy; #if !defined(RADIOLIB_EXCLUDE_AFSK) AFSKClient* _audio; #endif char _srcCallsign[AX25_MAX_CALLSIGN_LEN + 1] = {0, 0, 0, 0, 0, 0, 0}; uint8_t _srcSSID = 0; uint16_t _preambleLen = 0; static uint16_t getFrameCheckSequence(uint8_t* buff, size_t len); }; #endif #endif
[ "jgromes@users.noreply.github.com" ]
jgromes@users.noreply.github.com
d5d9deaa8db6577e042b46dd364828be060aa698
496b95ce18228acd29ab48586e12694b740fed42
/utils/gui/div/GUIParameterTableWindow.cpp
a8a5c75f1fc7c151c82a38f7b7cf777095f752d3
[]
no_license
pratik101agrawal/Indian_traffic_control
11fb0de64e09ab9c658ce6db9f48a364ce98e4f5
6de2c6880edc853cce7efacebcb10fce475ba8c1
refs/heads/master
2022-12-25T09:43:40.295535
2020-09-30T18:57:57
2020-09-30T18:57:57
300,026,534
1
0
null
2020-09-30T18:56:37
2020-09-30T18:56:36
null
UTF-8
C++
false
false
7,728
cpp
/****************************************************************************/ /// @file GUIParameterTableWindow.cpp /// @author Daniel Krajzewicz /// @date Sept 2002 /// @version $Id: GUIParameterTableWindow.cpp 8459 2010-03-17 22:02:19Z behrisch $ /// // The window that holds the table of an object's parameter /****************************************************************************/ // SUMO, Simulation of Urban MObility; see http://sumo.sourceforge.net/ // Copyright 2001-2010 DLR (http://www.dlr.de/) and contributors /****************************************************************************/ // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // /****************************************************************************/ // =========================================================================== // included modules // =========================================================================== #ifdef _MSC_VER #include <windows_config.h> #else #include <config.h> #endif #include <string> #include <fx.h> #include "GUIParameterTableWindow.h" #include <utils/gui/globjects/GUIGlObject.h> #include <utils/common/ToString.h> #include <utils/gui/div/GUIParam_PopupMenu.h> #include <utils/gui/windows/GUIAppEnum.h> #include <utils/gui/windows/GUIMainWindow.h> #include <utils/gui/images/GUIIconSubSys.h> #include <utils/gui/div/GUIParameterTableItem.h> #ifdef CHECK_MEMORY_LEAKS #include <foreign/nvwa/debug_new.h> #endif // CHECK_MEMORY_LEAKS // =========================================================================== // FOX callback mapping // =========================================================================== FXDEFMAP(GUIParameterTableWindow) GUIParameterTableWindowMap[]= { FXMAPFUNC(SEL_COMMAND, MID_SIMSTEP, GUIParameterTableWindow::onSimStep), FXMAPFUNC(SEL_SELECTED, MID_TABLE, GUIParameterTableWindow::onTableSelected), FXMAPFUNC(SEL_DESELECTED, MID_TABLE, GUIParameterTableWindow::onTableDeselected), FXMAPFUNC(SEL_RIGHTBUTTONPRESS, MID_TABLE, GUIParameterTableWindow::onRightButtonPress), }; FXIMPLEMENT(GUIParameterTableWindow, FXMainWindow, GUIParameterTableWindowMap, ARRAYNUMBER(GUIParameterTableWindowMap)) // =========================================================================== // method definitions // =========================================================================== GUIParameterTableWindow::GUIParameterTableWindow(GUIMainWindow &app, GUIGlObject &o, size_t noRows) throw() : FXMainWindow(app.getApp(), (o.getFullName() + " Parameter").c_str(), NULL,NULL,DECOR_ALL,20,20,300,(FXint)(noRows*20+60)), myObject(&o), myApplication(&app), myCurrentPos(0) { myTable = new FXTable(this, this, MID_TABLE, TABLE_COL_SIZABLE|TABLE_ROW_SIZABLE|LAYOUT_FILL_X|LAYOUT_FILL_Y); myTable->setVisibleRows((FXint)(noRows+1)); myTable->setVisibleColumns(3); myTable->setTableSize((FXint)(noRows+1), 3); myTable->setBackColor(FXRGB(255,255,255)); myTable->setColumnText(0, "Name"); myTable->setColumnText(1, "Value"); myTable->setColumnText(2, "Dynamic"); myTable->getRowHeader()->setWidth(0); FXHeader *header = myTable->getColumnHeader(); header->setItemJustify(0, JUSTIFY_CENTER_X); header->setItemSize(0, 150); header->setItemJustify(1, JUSTIFY_CENTER_X); header->setItemSize(1, 80); header->setItemJustify(2, JUSTIFY_CENTER_X); header->setItemSize(2, 60); setIcon(GUIIconSubSys::getIcon(ICON_APP_TABLE)); } GUIParameterTableWindow::~GUIParameterTableWindow() throw() { myApplication->removeChild(this); for (std::vector<GUIParameterTableItemInterface*>::iterator i=myItems.begin(); i!=myItems.end(); ++i) { delete(*i); } } long GUIParameterTableWindow::onSimStep(FXObject*,FXSelector,void*) { updateTable(); update(); return 1; } long GUIParameterTableWindow::onTableSelected(FXObject*,FXSelector,void*) { return 1; } long GUIParameterTableWindow::onTableDeselected(FXObject*,FXSelector,void*) { return 1; } long GUIParameterTableWindow::onRightButtonPress(FXObject*sender, FXSelector sel, void*data) { // check which value entry was pressed myTable->onLeftBtnPress(sender, sel, data); int row = myTable->getCurrentRow(); if (row==-1||row>=myItems.size()) { return 1; } GUIParameterTableItemInterface *i = myItems[row]; if (!i->dynamic()) { return 1; } GUIParam_PopupMenuInterface *p = new GUIParam_PopupMenuInterface(*myApplication, *this, *myObject, i->getName(), i->getSUMORealSourceCopy()); new FXMenuCommand(p, "Open in new Tracker", 0, p, MID_OPENTRACKER); // set geometry p->setX(static_cast<FXEvent*>(data)->root_x); p->setY(static_cast<FXEvent*>(data)->root_y); p->create(); // show p->show(); return 1; } void GUIParameterTableWindow::mkItem(const char *name, bool dynamic, ValueSource<unsigned> *src) throw() { GUIParameterTableItemInterface *i = new GUIParameterTableItem<unsigned>( myTable, myCurrentPos++, name, dynamic, src); myItems.push_back(i); } void GUIParameterTableWindow::mkItem(const char *name, bool dynamic, ValueSource<SUMOReal> *src) throw() { GUIParameterTableItemInterface *i = new GUIParameterTableItem<SUMOReal>( myTable, myCurrentPos++, name, dynamic, src); myItems.push_back(i); } #ifndef HAVE_SUBSECOND_TIMESTEPS void GUIParameterTableWindow::mkItem(const char *name, bool dynamic, ValueSource<SUMOTime> *src) throw() { GUIParameterTableItemInterface *i = new GUIParameterTableItem<SUMOTime>( myTable, myCurrentPos++, name, dynamic, src); myItems.push_back(i); } #endif void GUIParameterTableWindow::mkItem(const char *name, bool dynamic, std::string value) throw() { GUIParameterTableItemInterface *i = new GUIParameterTableItem<SUMOReal>( myTable, myCurrentPos++, name, dynamic, value); myItems.push_back(i); } void GUIParameterTableWindow::mkItem(const char *name, bool dynamic, SUMOReal value) throw() { GUIParameterTableItemInterface *i = new GUIParameterTableItem<SUMOReal>( myTable, myCurrentPos++, name, dynamic, value); myItems.push_back(i); } void GUIParameterTableWindow::mkItem(const char *name, bool dynamic, unsigned value) throw() { GUIParameterTableItemInterface *i = new GUIParameterTableItem<unsigned>( myTable, myCurrentPos++, name, dynamic, value); myItems.push_back(i); } #ifndef HAVE_SUBSECOND_TIMESTEPS void GUIParameterTableWindow::mkItem(const char *name, bool dynamic, SUMOTime value) throw() { GUIParameterTableItemInterface *i = new GUIParameterTableItem<SUMOTime>( myTable, myCurrentPos++, name, dynamic, value); myItems.push_back(i); } #endif void GUIParameterTableWindow::updateTable() throw() { for (std::vector<GUIParameterTableItemInterface*>::iterator i=myItems.begin(); i!=myItems.end(); i++) { (*i)->update(); } } void GUIParameterTableWindow::closeBuilding() throw() { myApplication->addChild(this, true); create(); show(); } /****************************************************************************/
[ "chordiasagar14@gmail.com" ]
chordiasagar14@gmail.com
d77f6406e2a9ca0520c7f0e9bc953dc69c865531
d89bca09bbe4a3cf3ded48ade073fe816bc0bec4
/Tables/IRow.h
b41a443b4b86232b7521ff97599c38185a81e444
[]
no_license
jonesbusy/datalyser
45652135f6c2e74f0f3a62fd660371866a178d70
8c874223ead41f725abec83ec590ffd29c75e78b
refs/heads/master
2022-04-21T00:52:00.932230
2020-04-18T14:52:57
2020-04-18T14:53:49
255,400,327
0
0
null
null
null
null
UTF-8
C++
false
false
1,003
h
/******************************************************************* | | File : IRow.h | | Description : Interface pour tout type de ligne de table. | | Author : | | Created : 06.01.2010 | | Modified : 06.01.2010 | | C++ std : - | | Dependencies : - | | Version : 1.0 | *******************************************************************/ #ifndef IROW_H_INCLUDED #define IROW_H_INCLUDED class IRow { public: /*************************************************************** | Description : Copie dynamiquement l'instance et place son | adresse dans le pointeur pass� en param�tre. | (Abstraite) | | Visibility : Public | | Parameters : row - Pointeur de ligne � instancier | | Return value : - ***************************************************************/ virtual void clone(IRow*& row) const = 0; }; #endif // IROW_H_INCLUDED
[ "jonesbusy@gmail.com" ]
jonesbusy@gmail.com
6832e068f15ceeb58436eff44dc1e8559c52c953
6de815048c50591388ab84b2632928aaba985037
/C++/oldcode/OrderServ/ChildFrm.cpp
24d59d49b3fd9dde9b470ca7b4c94d85541385ea
[]
no_license
soumyaukil/upwork
5a5b258d75e3af39bb7d1ba782073a47a75a3ad9
698dd874f537d315b6f90012afce757d7173b756
refs/heads/master
2021-05-16T09:28:42.380983
2017-09-23T09:59:13
2017-09-23T09:59:13
104,435,065
0
0
null
null
null
null
UTF-8
C++
false
false
1,542
cpp
// ChildFrm.cpp : implementation of the CChildFrame class // #include "stdafx.h" #include "OrderServ.h" #include "ChildFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CChildFrame IMPLEMENT_DYNCREATE(CChildFrame, CMDIChildWnd) BEGIN_MESSAGE_MAP(CChildFrame, CMDIChildWnd) //{{AFX_MSG_MAP(CChildFrame) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CChildFrame construction/destruction CChildFrame::CChildFrame() { // TODO: add member initialization code here } CChildFrame::~CChildFrame() { } BOOL CChildFrame::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs if( !CMDIChildWnd::PreCreateWindow(cs) ) return FALSE; return TRUE; } ///////////////////////////////////////////////////////////////////////////// // CChildFrame diagnostics #ifdef _DEBUG void CChildFrame::AssertValid() const { CMDIChildWnd::AssertValid(); } void CChildFrame::Dump(CDumpContext& dc) const { CMDIChildWnd::Dump(dc); } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CChildFrame message handlers
[ "ubuntu@ip-172-31-38-230.ec2.internal" ]
ubuntu@ip-172-31-38-230.ec2.internal
74acb28be8b3c706d50613d3c5376eb3e83b90f8
829b3f2d0ae685d01fe097c03bf5c1976cbc4723
/deps/boost/include/boost/asio/detail/impl/win_object_handle_service.ipp
dca1295057407dcf0ebd20106f9274164a814e18
[ "Apache-2.0" ]
permissive
liyoung1992/mediasoup-sfu-cpp
f0f0321f8974beb1f4263c9e658402620d82385f
b76564e068626b0d675f5486e56da3d69151e287
refs/heads/main
2023-08-21T21:40:51.710022
2021-10-14T06:29:18
2021-10-14T06:29:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,945
ipp
// // detail/impl/win_object_handle_service.ipp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com) // Copyright (c) 2011 Boris Schaeling (boris@highscore.de) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_ASIO_DETAIL_IMPL_WIN_OBJECT_HANDLE_SERVICE_IPP #define BOOST_ASIO_DETAIL_IMPL_WIN_OBJECT_HANDLE_SERVICE_IPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if defined(BOOST_ASIO_HAS_WINDOWS_OBJECT_HANDLE) #include <boost/asio/detail/win_object_handle_service.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { namespace detail { win_object_handle_service::win_object_handle_service(execution_context& context) : execution_context_service_base<win_object_handle_service>(context), scheduler_(boost::asio::use_service<scheduler_impl>(context)), mutex_(), impl_list_(0), shutdown_(false) { } void win_object_handle_service::shutdown() { mutex::scoped_lock lock(mutex_); // Setting this flag to true prevents new objects from being registered, and // new asynchronous wait operations from being started. We only need to worry // about cleaning up the operations that are currently in progress. shutdown_ = true; op_queue<operation> ops; for (implementation_type* impl = impl_list_; impl; impl = impl->next_) ops.push(impl->op_queue_); lock.unlock(); scheduler_.abandon_operations(ops); } void win_object_handle_service::construct( win_object_handle_service::implementation_type& impl) { impl.handle_ = INVALID_HANDLE_VALUE; impl.wait_handle_ = INVALID_HANDLE_VALUE; impl.owner_ = this; // Insert implementation into linked list of all implementations. mutex::scoped_lock lock(mutex_); if (!shutdown_) { impl.next_ = impl_list_; impl.prev_ = 0; if (impl_list_) impl_list_->prev_ = &impl; impl_list_ = &impl; } } void win_object_handle_service::move_construct( win_object_handle_service::implementation_type& impl, win_object_handle_service::implementation_type& other_impl) { mutex::scoped_lock lock(mutex_); // Insert implementation into linked list of all implementations. if (!shutdown_) { impl.next_ = impl_list_; impl.prev_ = 0; if (impl_list_) impl_list_->prev_ = &impl; impl_list_ = &impl; } impl.handle_ = other_impl.handle_; other_impl.handle_ = INVALID_HANDLE_VALUE; impl.wait_handle_ = other_impl.wait_handle_; other_impl.wait_handle_ = INVALID_HANDLE_VALUE; impl.op_queue_.push(other_impl.op_queue_); impl.owner_ = this; // We must not hold the lock while calling UnregisterWaitEx. This is because // the registered callback function might be invoked while we are waiting for // UnregisterWaitEx to complete. lock.unlock(); if (impl.wait_handle_ != INVALID_HANDLE_VALUE) ::UnregisterWaitEx(impl.wait_handle_, INVALID_HANDLE_VALUE); if (!impl.op_queue_.empty()) register_wait_callback(impl, lock); } void win_object_handle_service::move_assign( win_object_handle_service::implementation_type& impl, win_object_handle_service& other_service, win_object_handle_service::implementation_type& other_impl) { boost::system::error_code ignored_ec; close(impl, ignored_ec); mutex::scoped_lock lock(mutex_); if (this != &other_service) { // Remove implementation from linked list of all implementations. if (impl_list_ == &impl) impl_list_ = impl.next_; if (impl.prev_) impl.prev_->next_ = impl.next_; if (impl.next_) impl.next_->prev_= impl.prev_; impl.next_ = 0; impl.prev_ = 0; } impl.handle_ = other_impl.handle_; other_impl.handle_ = INVALID_HANDLE_VALUE; impl.wait_handle_ = other_impl.wait_handle_; other_impl.wait_handle_ = INVALID_HANDLE_VALUE; impl.op_queue_.push(other_impl.op_queue_); impl.owner_ = this; if (this != &other_service) { // Insert implementation into linked list of all implementations. impl.next_ = other_service.impl_list_; impl.prev_ = 0; if (other_service.impl_list_) other_service.impl_list_->prev_ = &impl; other_service.impl_list_ = &impl; } // We must not hold the lock while calling UnregisterWaitEx. This is because // the registered callback function might be invoked while we are waiting for // UnregisterWaitEx to complete. lock.unlock(); if (impl.wait_handle_ != INVALID_HANDLE_VALUE) ::UnregisterWaitEx(impl.wait_handle_, INVALID_HANDLE_VALUE); if (!impl.op_queue_.empty()) register_wait_callback(impl, lock); } void win_object_handle_service::destroy( win_object_handle_service::implementation_type& impl) { mutex::scoped_lock lock(mutex_); // Remove implementation from linked list of all implementations. if (impl_list_ == &impl) impl_list_ = impl.next_; if (impl.prev_) impl.prev_->next_ = impl.next_; if (impl.next_) impl.next_->prev_= impl.prev_; impl.next_ = 0; impl.prev_ = 0; if (is_open(impl)) { BOOST_ASIO_HANDLER_OPERATION((scheduler_.context(), "object_handle", &impl, reinterpret_cast<uintmax_t>(impl.wait_handle_), "close")); HANDLE wait_handle = impl.wait_handle_; impl.wait_handle_ = INVALID_HANDLE_VALUE; op_queue<operation> ops; while (wait_op* op = impl.op_queue_.front()) { op->ec_ = boost::asio::error::operation_aborted; impl.op_queue_.pop(); ops.push(op); } // We must not hold the lock while calling UnregisterWaitEx. This is // because the registered callback function might be invoked while we are // waiting for UnregisterWaitEx to complete. lock.unlock(); if (wait_handle != INVALID_HANDLE_VALUE) ::UnregisterWaitEx(wait_handle, INVALID_HANDLE_VALUE); ::CloseHandle(impl.handle_); impl.handle_ = INVALID_HANDLE_VALUE; scheduler_.post_deferred_completions(ops); } } boost::system::error_code win_object_handle_service::assign( win_object_handle_service::implementation_type& impl, const native_handle_type& handle, boost::system::error_code& ec) { if (is_open(impl)) { ec = boost::asio::error::already_open; return ec; } impl.handle_ = handle; ec = boost::system::error_code(); return ec; } boost::system::error_code win_object_handle_service::close( win_object_handle_service::implementation_type& impl, boost::system::error_code& ec) { if (is_open(impl)) { BOOST_ASIO_HANDLER_OPERATION((scheduler_.context(), "object_handle", &impl, reinterpret_cast<uintmax_t>(impl.wait_handle_), "close")); mutex::scoped_lock lock(mutex_); HANDLE wait_handle = impl.wait_handle_; impl.wait_handle_ = INVALID_HANDLE_VALUE; op_queue<operation> completed_ops; while (wait_op* op = impl.op_queue_.front()) { impl.op_queue_.pop(); op->ec_ = boost::asio::error::operation_aborted; completed_ops.push(op); } // We must not hold the lock while calling UnregisterWaitEx. This is // because the registered callback function might be invoked while we are // waiting for UnregisterWaitEx to complete. lock.unlock(); if (wait_handle != INVALID_HANDLE_VALUE) ::UnregisterWaitEx(wait_handle, INVALID_HANDLE_VALUE); if (::CloseHandle(impl.handle_)) { impl.handle_ = INVALID_HANDLE_VALUE; ec = boost::system::error_code(); } else { DWORD last_error = ::GetLastError(); ec = boost::system::error_code(last_error, boost::asio::error::get_system_category()); } scheduler_.post_deferred_completions(completed_ops); } else { ec = boost::system::error_code(); } return ec; } boost::system::error_code win_object_handle_service::cancel( win_object_handle_service::implementation_type& impl, boost::system::error_code& ec) { if (is_open(impl)) { BOOST_ASIO_HANDLER_OPERATION((scheduler_.context(), "object_handle", &impl, reinterpret_cast<uintmax_t>(impl.wait_handle_), "cancel")); mutex::scoped_lock lock(mutex_); HANDLE wait_handle = impl.wait_handle_; impl.wait_handle_ = INVALID_HANDLE_VALUE; op_queue<operation> completed_ops; while (wait_op* op = impl.op_queue_.front()) { op->ec_ = boost::asio::error::operation_aborted; impl.op_queue_.pop(); completed_ops.push(op); } // We must not hold the lock while calling UnregisterWaitEx. This is // because the registered callback function might be invoked while we are // waiting for UnregisterWaitEx to complete. lock.unlock(); if (wait_handle != INVALID_HANDLE_VALUE) ::UnregisterWaitEx(wait_handle, INVALID_HANDLE_VALUE); ec = boost::system::error_code(); scheduler_.post_deferred_completions(completed_ops); } else { ec = boost::asio::error::bad_descriptor; } return ec; } void win_object_handle_service::wait( win_object_handle_service::implementation_type& impl, boost::system::error_code& ec) { switch (::WaitForSingleObject(impl.handle_, INFINITE)) { case WAIT_FAILED: { DWORD last_error = ::GetLastError(); ec = boost::system::error_code(last_error, boost::asio::error::get_system_category()); break; } case WAIT_OBJECT_0: case WAIT_ABANDONED: default: ec = boost::system::error_code(); break; } } void win_object_handle_service::start_wait_op( win_object_handle_service::implementation_type& impl, wait_op* op) { scheduler_.work_started(); if (is_open(impl)) { mutex::scoped_lock lock(mutex_); if (!shutdown_) { impl.op_queue_.push(op); // Only the first operation to be queued gets to register a wait callback. // Subsequent operations have to wait for the first to finish. if (impl.op_queue_.front() == op) register_wait_callback(impl, lock); } else { lock.unlock(); scheduler_.post_deferred_completion(op); } } else { op->ec_ = boost::asio::error::bad_descriptor; scheduler_.post_deferred_completion(op); } } void win_object_handle_service::register_wait_callback( win_object_handle_service::implementation_type& impl, mutex::scoped_lock& lock) { lock.lock(); if (!RegisterWaitForSingleObject(&impl.wait_handle_, impl.handle_, &win_object_handle_service::wait_callback, &impl, INFINITE, WT_EXECUTEONLYONCE)) { DWORD last_error = ::GetLastError(); boost::system::error_code ec(last_error, boost::asio::error::get_system_category()); op_queue<operation> completed_ops; while (wait_op* op = impl.op_queue_.front()) { op->ec_ = ec; impl.op_queue_.pop(); completed_ops.push(op); } lock.unlock(); scheduler_.post_deferred_completions(completed_ops); } } void win_object_handle_service::wait_callback(PVOID param, BOOLEAN) { implementation_type* impl = static_cast<implementation_type*>(param); mutex::scoped_lock lock(impl->owner_->mutex_); if (impl->wait_handle_ != INVALID_HANDLE_VALUE) { ::UnregisterWaitEx(impl->wait_handle_, NULL); impl->wait_handle_ = INVALID_HANDLE_VALUE; } if (wait_op* op = impl->op_queue_.front()) { op_queue<operation> completed_ops; op->ec_ = boost::system::error_code(); impl->op_queue_.pop(); completed_ops.push(op); if (!impl->op_queue_.empty()) { if (!RegisterWaitForSingleObject(&impl->wait_handle_, impl->handle_, &win_object_handle_service::wait_callback, param, INFINITE, WT_EXECUTEONLYONCE)) { DWORD last_error = ::GetLastError(); boost::system::error_code ec(last_error, boost::asio::error::get_system_category()); while ((op = impl->op_queue_.front()) != 0) { op->ec_ = ec; impl->op_queue_.pop(); completed_ops.push(op); } } } scheduler_impl& sched = impl->owner_->scheduler_; lock.unlock(); sched.post_deferred_completions(completed_ops); } } } // namespace detail } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // defined(BOOST_ASIO_HAS_WINDOWS_OBJECT_HANDLE) #endif // BOOST_ASIO_DETAIL_IMPL_WIN_OBJECT_HANDLE_SERVICE_IPP
[ "yanhua133@126.com" ]
yanhua133@126.com
9514ffb0193b439d26a7aa33ff322c455167b01a
6197ece57df757f193afbe2448a01e4f76e720b0
/src/otlib/OTPasswordData.cpp
472bea5f38d9b304e04a0821da1438516cac3457
[]
no_license
klzns/Open-Transactions
609a558d05ceaf84a48921e62331201e824892df
77f731086496cc467c5e4653b31f9066b7f30087
refs/heads/master
2021-05-27T06:20:27.609609
2014-06-08T22:28:24
2014-06-08T22:28:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,987
cpp
/************************************************************ * * OTPasswordData.cpp * */ /************************************************************ -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 * OPEN TRANSACTIONS * * Financial Cryptography and Digital Cash * Library, Protocol, API, Server, CLI, GUI * * -- Anonymous Numbered Accounts. * -- Untraceable Digital Cash. * -- Triple-Signed Receipts. * -- Cheques, Vouchers, Transfers, Inboxes. * -- Basket Currencies, Markets, Payment Plans. * -- Signed, XML, Ricardian-style Contracts. * -- Scripted smart contracts. * * Copyright (C) 2010-2013 by "Fellow Traveler" (A pseudonym) * * EMAIL: * FellowTraveler@rayservers.net * * BITCOIN: 1NtTPVVjDsUfDWybS4BwvHpG2pdS9RnYyQ * * KEY FINGERPRINT (PGP Key in license file): * 9DD5 90EB 9292 4B48 0484 7910 0308 00ED F951 BB8E * * OFFICIAL PROJECT WIKI(s): * https://github.com/FellowTraveler/Moneychanger * https://github.com/FellowTraveler/Open-Transactions/wiki * * WEBSITE: * http://www.OpenTransactions.org/ * * Components and licensing: * -- Moneychanger..A Java client GUI.....LICENSE:.....GPLv3 * -- otlib.........A class library.......LICENSE:...LAGPLv3 * -- otapi.........A client API..........LICENSE:...LAGPLv3 * -- opentxs/ot....Command-line client...LICENSE:...LAGPLv3 * -- otserver......Server Application....LICENSE:....AGPLv3 * Github.com/FellowTraveler/Open-Transactions/wiki/Components * * All of the above OT components were designed and written by * Fellow Traveler, with the exception of Moneychanger, which * was contracted out to Vicky C (bitcointrader4@gmail.com). * The open-source community has since actively contributed. * * ----------------------------------------------------- * * LICENSE: * This program is free software: you can redistribute it * and/or modify it under the terms of the GNU Affero * General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your * option) any later version. * * ADDITIONAL PERMISSION under the GNU Affero GPL version 3 * section 7: (This paragraph applies only to the LAGPLv3 * components listed above.) If you modify this Program, or * any covered work, by linking or combining it with other * code, such other code is not for that reason alone subject * to any of the requirements of the GNU Affero GPL version 3. * (==> This means if you are only using the OT API, then you * don't have to open-source your code--only your changes to * Open-Transactions itself must be open source. Similar to * LGPLv3, except it applies to software-as-a-service, not * just to distributing binaries.) * * Extra WAIVER for OpenSSL, Lucre, and all other libraries * used by Open Transactions: This program is released under * the AGPL with the additional exemption that compiling, * linking, and/or using OpenSSL is allowed. The same is true * for any other open source libraries included in this * project: complete waiver from the AGPL is hereby granted to * compile, link, and/or use them with Open-Transactions, * according to their own terms, as long as the rest of the * Open-Transactions terms remain respected, with regard to * the Open-Transactions code itself. * * Lucre License: * This code is also "dual-license", meaning that Ben Lau- * rie's license must also be included and respected, since * the code for Lucre is also included with Open Transactions. * See Open-Transactions/src/otlib/lucre/LUCRE_LICENSE.txt * The Laurie requirements are light, but if there is any * problem with his license, simply remove the Lucre code. * Although there are no other blind token algorithms in Open * Transactions (yet. credlib is coming), the other functions * will continue to operate. * See Lucre on Github: https://github.com/benlaurie/lucre * ----------------------------------------------------- * You should have received a copy of the GNU Affero General * Public License along with this program. If not, see: * http://www.gnu.org/licenses/ * * If you would like to use this software outside of the free * software license, please contact FellowTraveler. * (Unfortunately many will run anonymously and untraceably, * so who could really stop them?) * * DISCLAIMER: * This program is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU Affero General Public License for * more details. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (Darwin) iQIcBAEBAgAGBQJRSsfJAAoJEAMIAO35UbuOQT8P/RJbka8etf7wbxdHQNAY+2cC vDf8J3X8VI+pwMqv6wgTVy17venMZJa4I4ikXD/MRyWV1XbTG0mBXk/7AZk7Rexk KTvL/U1kWiez6+8XXLye+k2JNM6v7eej8xMrqEcO0ZArh/DsLoIn1y8p8qjBI7+m aE7lhstDiD0z8mwRRLKFLN2IH5rAFaZZUvj5ERJaoYUKdn4c+RcQVei2YOl4T0FU LWND3YLoH8naqJXkaOKEN4UfJINCwxhe5Ke9wyfLWLUO7NamRkWD2T7CJ0xocnD1 sjAzlVGNgaFDRflfIF4QhBx1Ddl6wwhJfw+d08bjqblSq8aXDkmFA7HeunSFKkdn oIEOEgyj+veuOMRJC5pnBJ9vV+7qRdDKQWaCKotynt4sWJDGQ9kWGWm74SsNaduN TPMyr9kNmGsfR69Q2Zq/FLcLX/j8ESxU+HYUB4vaARw2xEOu2xwDDv6jt0j3Vqsg x7rWv4S/Eh18FDNDkVRChiNoOIilLYLL6c38uMf1pnItBuxP3uhgY6COm59kVaRh nyGTYCDYD2TK+fI9o89F1297uDCwEJ62U0Q7iTDp5QuXCoxkPfv8/kX6lS6T3y9G M9mqIoLbIQ1EDntFv7/t6fUTS2+46uCrdZWbQ5RjYXdrzjij02nDmJAm2BngnZvd kamH0Y/n11lCvo1oQxM+ =uSzz -----END PGP SIGNATURE----- **************************************************************/ #include <stdafx.hpp> #include <OTPasswordData.hpp> #include <OTPassword.hpp> #include <OTAssert.hpp> #include <OTString.hpp> #include <OTLog.hpp> #include <OTCrypto.hpp> // For SecureZeroMemory #ifdef _WIN32 #else // not _WIN32 // for mlock and munlock #include <sys/types.h> #include <sys/mman.h> #include <limits.h> #ifndef PAGESIZE #include <unistd.h> #define PAGESIZE sysconf(_SC_PAGESIZE) #endif // FT: Credit to the Bitcoin team for the mlock / munlock defines. #define mlock(a,b) \ mlock(((void *)(((size_t)(a)) & (~((PAGESIZE)-1)))),\ (((((size_t)(a)) + (b) - 1) | ((PAGESIZE) - 1)) + 1) - (((size_t)(a)) & (~((PAGESIZE) - 1)))) #define munlock(a,b) \ munlock(((void *)(((size_t)(a)) & (~((PAGESIZE)-1)))),\ (((((size_t)(a)) + (b) - 1) | ((PAGESIZE) - 1)) + 1) - (((size_t)(a)) & (~((PAGESIZE) - 1)))) #endif // Instantiate one of these whenever you do an action that may // require a passphrase. When you call the OpenSSL private key // using function, just pass in the address to this instance along // as one of the parameters. That way when the actual password // callback is activated, you'll get that pointer as the userdata // parameter to the callback. // This enables you to easily pass data to the callback about // which Nym is doing the action, or what string should be displayed // on the screen, etc. You'll also be able to use the same mechanism // for determining whether it's a wallet-Nym doing the action, or // a real Nym. (Thus making it possible to skip any "password caching" // code that normally happens for real nyms, when it's the wallet nym.) // /* class OTPasswordData { private: OTPassword * m_pMasterPW; // Used only when isForCachedKey is true. const std::string m_strDisplay; public: // -------------------------------- bool isForCachedKey() const; const char * GetDisplayString() const; // -------------------------------- OTPasswordData(const char * szDisplay, OTPassword * pMasterPW=NULL); OTPasswordData(const std::string & str_Display, OTPassword * pMasterPW=NULL); OTPasswordData(const OTString & strDisplay, OTPassword * pMasterPW=NULL); ~OTPasswordData(); }; */ bool OTPasswordData::isUsingOldSystem() const { return m_bUsingOldSystem; } void OTPasswordData::setUsingOldSystem(bool bUsing/*=true*/) { m_bUsingOldSystem = bUsing; } bool OTPasswordData::isForNormalNym() const { return (NULL == m_pMasterPW); } bool OTPasswordData::isForCachedKey() const { return (NULL != m_pMasterPW); } const char * OTPasswordData::GetDisplayString() const { return m_strDisplay.c_str(); } OTPasswordData::OTPasswordData(const char * szDisplay, OTPassword * pMasterPW/*=NULL*/, _SharedPtr<OTCachedKey> pCachedKey/*=_SharedPtr<OTCachedKey>()*/) : m_pMasterPW(pMasterPW), m_strDisplay(NULL == szDisplay ? "(Sorry, no user data provided.)" : szDisplay), m_bUsingOldSystem(false), m_pCachedKey(pCachedKey) { // They can both be NULL, or they can both be not NULL. // But you can't have one NULL, and the other not. OT_ASSERT( ( (NULL == pMasterPW) && (!pCachedKey) ) || ( (NULL != pMasterPW) && (pCachedKey) ) ); } OTPasswordData::OTPasswordData(const std::string & str_Display, OTPassword * pMasterPW/*=NULL*/, _SharedPtr<OTCachedKey> pCachedKey/*=_SharedPtr<OTCachedKey>()*/) : m_pMasterPW(pMasterPW), m_strDisplay(str_Display), m_bUsingOldSystem(false), m_pCachedKey(pCachedKey) { // They can both be NULL, or they can both be not NULL. // But you can't have one NULL, and the other not. OT_ASSERT( ( (NULL == pMasterPW) && (!pCachedKey) ) || ( (NULL != pMasterPW) && (pCachedKey) ) ); } OTPasswordData::OTPasswordData(const OTString & strDisplay, OTPassword * pMasterPW/*=NULL*/, _SharedPtr<OTCachedKey> pCachedKey/*=_SharedPtr<OTCachedKey>()*/) : m_pMasterPW(pMasterPW), m_strDisplay(strDisplay.Get()), m_bUsingOldSystem(false), m_pCachedKey(pCachedKey) { // They can both be NULL, or they can both be not NULL. // But you can't have one NULL, and the other not. OT_ASSERT( ( (NULL == pMasterPW) && (!pCachedKey) ) || ( (NULL != pMasterPW) && (pCachedKey) ) ); } OTPasswordData::~OTPasswordData() { m_pMasterPW = NULL; // not owned // m_pCachedKey = NULL; // not owned }
[ "F3llowTraveler@gmail.com" ]
F3llowTraveler@gmail.com
cd82eaf1f18c4f56a7722637eb012ec8c1ad470a
e466511e70ad132dad5275ddf4a606e233a8fc10
/WinsockAsync/ConnectionListenerFactory.h
d05076ac22286e41943cf38a69261efb1c5d89b3
[]
no_license
martinmine/winsockserver
1f8567ad1205586fa82954a0ad129dc7cd88c4a3
8237870f0cf6b1669a83c2c3c8955c893a549812
refs/heads/master
2021-01-22T05:53:53.167280
2013-07-22T21:21:14
2013-07-22T21:21:14
9,380,747
1
0
null
null
null
null
UTF-8
C++
false
false
436
h
#if !defined(__CONNECTIONLISTENERFACTORY_H) #define __CONNECTIONLISTENERFACTORY_H #include "IConnectionListener.h" #include "SessionManager.h" class ConnectionListenerFactory { public: // Creates a new connection manager with the given parameters static IClientConnectionListener* CreateConnectionListener( const int maxConnections, const unsigned short port) { return new ConnectionManager(maxConnections, port); } }; #endif
[ "martin_mine@hotmail.com" ]
martin_mine@hotmail.com
4c38e6528d39bf45db25a157fe00d80189a97daa
0562cf42a0680a32fd3a6a3e272f30c12a494b89
/lib/LcLuaFuncMap.cpp
1c89140651ceeeae39cfc3ea357d78b33c3ce030
[]
no_license
ammarhakim/gkeyll1
70131876e4a68851a548e4d45e225498911eb2b6
59da9591106207e22787d72b9c2f3e7fbdc1a7e4
refs/heads/master
2020-09-08T05:23:47.974889
2019-02-06T18:09:18
2019-02-06T18:09:18
221,027,635
0
0
null
null
null
null
UTF-8
C++
false
false
1,081
cpp
/** * @file LcLuaFuncMap.cpp * * @brief Class to store map of callable Lua functions. */ // config stuff #ifdef HAVE_CONFIG_H # include <config.h> #endif // lucee includes #include <LcLuaFuncMap.h> namespace Lucee { void LuaFuncMap::appendFunc(const std::string& nm, int (*func)(lua_State *L)) { std::map<std::string, int (*)(lua_State *L)>::iterator itr = funcs.find(nm); if (itr != funcs.end()) // replace by supplied function if already exists itr->second = func; else { // add a new entry to map funcs.insert(std::pair<std::string, int (*)(lua_State *L)>( nm, func)); } } void LuaFuncMap::setDelFunc(int (*func)(lua_State *L)) { delFunc = func; } void LuaFuncMap::fillWithFuncList(std::vector<luaL_Reg>& funcLst) { funcLst.clear(); // get rid of existing stuff std::map<std::string, int (*)(lua_State *L)>::iterator itr = funcs.begin(); for ( ; itr != funcs.end(); ++itr) { luaL_Reg reg = {itr->first.c_str(), itr->second}; funcLst.push_back(reg); } } }
[ "eshi@pppl.gov" ]
eshi@pppl.gov
aff152910e40bf7193f7f536ce85aa4446b6b51f
3413e3090573dcf72dfb031dcc25641ba5123297
/diamond-slice-viz-pov.cpp
80fd1ced4de24d55bddaa8c4c76c67e5101ea04e
[ "MIT" ]
permissive
aMiss-aWry/DiamondTilingViz
474c5e81e7f8e41fde1bc9d031f91b4b23feed62
519150d3d157030467f58c595bbea6775cfb8ec2
refs/heads/master
2021-01-17T21:33:20.314753
2016-05-04T22:59:51
2016-05-04T22:59:51
51,962,382
0
0
null
2016-02-17T23:09:35
2016-02-17T23:09:34
null
UTF-8
C++
false
false
13,372
cpp
/*! * \file diamond-slice-viz-pov.cpp * * \brief Driver for visualizing 3D diamond slabs in povray. * * Goal is to eventually incorporate back into the diamond-slice-viz.cpp * code, but first going to try it out here. * * \date Started: 12/19/14 * * \authors Michelle Strout * * Copyright (c) 2014, Colorado State University <br> * All rights reserved. <br> */ #include "CmdParams.h" #include "ColorInfo.hpp" #include "Printer.hpp" #include "PrinterSVG.hpp" #include "PrinterPOV.hpp" #include <fstream> #include <string> #include <sstream> #include <iostream> #include <vector> //============================================== // Global parameters with their default values. int tau = 15; // tile size is TAUxTAUxTAU int T = 4; int subset_s = 3; int Tstart = 1; int Tend = 4; int N = 10; int grid_spacing = -1; int cell_spacing = 60; int cell_radius = 20; bool label = false; bool debug = false; int color_incr = 1; bool one_tile = false; int one_tile_c0 = 1; int one_tile_c1 = 1; int one_tile_c2 = -1; typedef enum { normal, halfradius, } gridspacing_type; gridspacing_type gridspacingChoice = normal; char gridspacingStr[MAXPOSSVALSTRING]; #define num_GPairs 2 static EnumStringPair GPairs[] = {{normal,"normal"}, {halfradius,"halfradius"} }; //============================================== // Create the file name based on parameters. // Needs global parameter variables and TAU, SIGMA, and GAMMA defines. // example: diamond-slice-3x3x3-T4N10-c60r20 std::string create_file_name() { std::stringstream ss; ss << "diamond-slice-" << tau << "x" << tau << "x" << tau; ss << "-T" << T << "u" << subset_s << "N" << N; ss << "-s" << Tstart << "e" << Tend; ss << "-p" << grid_spacing << "c" << cell_spacing << "r" << cell_radius << "l" << label; ss << "i" << color_incr; ss << "-o" << one_tile; if (one_tile) { ss << "." << one_tile_c0 << "." << one_tile_c1 << "." << one_tile_c2; } return ss.str(); } void initParams(CmdParams * cmdparams) /*--------------------------------------------------------------*//*! Uses a CmdParams object to describe all of the command line parameters. \author Michelle Strout 9/21/13 *//*--------------------------------------------------------------*/ { /* CmdParams_describeNumParam(cmdparams,"tau", 't', 1, "size of the tile, tau x tau x tau, must be multiple of 3 and >=15", 15, 129, 15); // arbitrary upper bound at this point */ CmdParams_describeNumParam(cmdparams,"tau", 't', 1, "size of the tile, tau x tau x tau", 3, 129, 15); // arbitrary upper bound at this point CmdParams_describeNumParam(cmdparams,"numTimeSteps", 'T', 1, "number of time steps", 1, 30, 4); CmdParams_describeNumParam(cmdparams,"subset_s", 'u', 1, "number of slices within a slab", 1, 30, 4); CmdParams_describeNumParam(cmdparams,"Tstart", 's', 1, "start visualization at Tstart", 1, 30, 1); CmdParams_describeNumParam(cmdparams,"Tend", 'e', 1, "end visualization at Tend, will default to T", 1, 30, -1); CmdParams_describeNumParam(cmdparams,"spatialDim", 'N', 1, "2D data will be NxN", 20, 75, 20); CmdParams_describeEnumParam(cmdparams,"grid_spacing_approach", 'g', 1, "approach for spacing between top of slices", GPairs, num_GPairs, normal); CmdParams_describeNumParam(cmdparams,"grid_spacing", 'p', 1, "precise spacing between top of slices, " "overrides grid spacing approach if set", 1, 1000, -1); CmdParams_describeNumParam(cmdparams,"cell_spacing", 'c', 1, "cell spacing between iteration circles", 1, 100, 60); CmdParams_describeNumParam(cmdparams,"cell_radius", 'r', 1, "radius for iteration circles", 1, 100, 20); CmdParams_describeNumParam(cmdparams,"debug", 'd', 1, "debug flag", 0, 1, 0); CmdParams_describeNumParam(cmdparams,"label", 'l', 1, "whether to put tile coordinates on iteration points or not", 0, 1, 0); CmdParams_describeNumParam(cmdparams,"color_incr", 'i', 1, "amount to increment color by when tile changes", 0, 10, 1); CmdParams_describeNumParam(cmdparams,"one_tile", 'o', 1, "whether to just color one tile", 0, 1, 0); CmdParams_describeNumParam(cmdparams,"one_tile_c0", '0', 1, "c0 coord for one tile being shown", -10, 20, 1); CmdParams_describeNumParam(cmdparams,"one_tile_c1", '1', 1, "c1 coord for one tile being shown", -10, 20, 1); CmdParams_describeNumParam(cmdparams,"one_tile_c2", '2', 1, "c2 coord for one tile being shown", -10, 20, -1); } // converts the tile coordinates to a string std::string tileCoordToString(int c0, int c1, int c2) { std::stringstream ss; ss << c0 << "," << c1 << "," << c2; return ss.str(); } // Array of colors. std::string svgColors[] = //{"bisque","red","aqua","yellow","blue","green","fuchsia","lime","silver","coral","lavender","pink","powderblue","plum","palegreen"}; {"red","yellow","green","lime","aqua","blue","fuchsia","silver","bisque","coral","lavender","pink","powderblue","plum","palegreen","teal","navy"}; //{"maroon","red","olive","yellow","green","lime","teal","aqua","navy","blue","purple","fuchsia","black","grey","silver","white"}; //{"yellow","green","aqua","navy","red","teal","fuchsia","lime","maroon","silver","olive","blue","black","purple","gray","white"}; int num_colors = 17; // converts the tile coordinates to a string // MMS, 2/16/15, making things really simple // one color per wave of tiles std::string tileCoordToColor(int c0, int c1, int c2) { if (c0==-2) return "red"; else if (c0==-1) return "yellow"; else if (c0==0) return "green"; else return "white"; } /* std::string tileCoordToColor(int c0, int c1, int c2) { // CRO -- trying something a little different here return svgColors[c0*(-1)]; static int count = -1; static int last_c0 = -99; static int last_c1 = -99; static int last_c2 = -99; // We want to change the tile color if the tile coordinate // has changed. if (c0!=last_c0 || c1!=last_c1 || c2!=last_c2) { last_c0 = c0; last_c1 = c1; last_c2 = c2; count += color_incr; } return svgColors[ count % num_colors ]; } */ // Definitions and declarations needed for diamonds-tij-skew.is #include "eassert.h" #include "intops.h" int c0, c1, c2, c3, c4, c5, c6, c7, c8; // The computation macro prints the svg for each iteration point. // Capturing the c0, c1, and c2 variables in the generated code, which // should be the tile coordinates. #define computation(c0,c1,c2,t,i,j) { \ std::string colorstr = tileCoordToColor(c0,c1,c2); \ if (debug) { \ std::cout << "c0,c1,c2 = " << c0 << ", " << c1 << ", " << c2 << " "; \ std::cout << "t,i,j = " << t << ", " << i << ", " << j << std::endl; \ std::cout << "color = " << colorstr << std::endl; \ } \ pov.printCircle(t,i,j, colorTable.getR(colorstr), \ colorTable.getG(colorstr), \ colorTable.getB(colorstr) ); \ std::cout << "{ pos: " << t << " " << i << " " << j << "; color: "; \ std::cout << colorTable.getHexCode(colorstr) << "}" << std::endl; \ } //if (label) slices.setLabel(t,i,j,tileCoordToString(c0,c1,c2)); \ if (!one_tile || (c0==one_tile_c0 && c1==one_tile_c1 && c2==one_tile_c2)) {\ slices.setFill(t,i,j,tileCoordToColor(c0,c1,c2)); } } //Can use for SVG: rgb(205,133,63) int main(int argc, char ** argv) { // Do command-line parsing. CmdParams *cmdparams = CmdParams_ctor(1); initParams(cmdparams); CmdParams_parseParams(cmdparams,argc,argv); tau = CmdParams_getValue(cmdparams,'t'); /* if (tau<15 || (tau%3)!=0) { cerr << "Error: tau must be 15 or greater and a multiple of 3" << endl; exit(-1); } */ T = CmdParams_getValue(cmdparams,'T'); Tstart = CmdParams_getValue(cmdparams,'s'); Tend = CmdParams_getValue(cmdparams,'e'); if (Tend<0) { Tend = T; } // if Tend not set, then default for Tend is T N = CmdParams_getValue(cmdparams,'N'); grid_spacing = CmdParams_getValue(cmdparams,'p'); gridspacingChoice = (gridspacing_type)CmdParams_getValue(cmdparams,'g'); cell_spacing = CmdParams_getValue(cmdparams,'c'); cell_radius = CmdParams_getValue(cmdparams,'r'); debug = CmdParams_getValue(cmdparams,'d'); label = CmdParams_getValue(cmdparams,'l'); color_incr = CmdParams_getValue(cmdparams,'i'); one_tile = CmdParams_getValue(cmdparams,'o'); one_tile_c0 = CmdParams_getValue(cmdparams,'0'); one_tile_c1 = CmdParams_getValue(cmdparams,'1'); one_tile_c2 = CmdParams_getValue(cmdparams,'2'); // Compute the spacing between slices. if (grid_spacing<0) { switch (gridspacingChoice) { case normal: grid_spacing = cell_spacing*(N+1); break; case halfradius: grid_spacing = 0.5*(double)cell_radius; break; } } //======================================== ColorInfo colorTable("svg-colors-rgb.txt"); //======================================== // Open the svg file and print the header. /* std::string filename = create_file_name() + ".svg"; ofstream svgfile(filename.c_str()); // Specify file and height and width. SVGPrinter svg( svgfile, cell_spacing*(N+1)+((Tend-Tstart+1)-1)*grid_spacing, (N+1)*cell_spacing, cell_radius, grid_spacing); svg.printHeader(); */ //======================================== // Open the povray file and print the header. std::string povfilename = create_file_name() + ".pov"; ofstream povfile(povfilename.c_str()); PrinterPOV pov(povfile); std::cout << "Generating file " << povfilename << std::endl; pov.printHeader(); //======================================== int k1, k2, t, i, j; int Li=0, Ui=N, Lj=0, Uj=N; int tau_times_3 = 3*tau; // loops over bottom left, middle, top right for (int thyme = -2; thyme<=0; thyme+=1){ // MMS, 2/16/15, copied in code from // Jacobi2D-DiamondByHandParam-OMP.test.c // The next two loops iterate within a tile wavefront. int k1_lb = floord(3*Lj+2+(thyme-2)*tau,tau_times_3); int k1_ub = floord(3*Uj+(thyme+2)*tau-2,tau_times_3); // These bounds have been unskewed by adding in k1. // That also turns them into a bounding box. int k2_lb = floord((2*thyme-2)*tau-3*Ui+2,tau_times_3); int k2_ub = floord((2+2*thyme)*tau-2-3*Li,tau_times_3); for (k1=k1_lb; k1<=k1_ub; k1++) { for (int x=k2_lb; x<=k2_ub; x++) { k2 = x-k1; // skew back // Don't have to check bounds based on k1 because the skew // was the only dependence of k2 bounds on k1. // Loop over time within a tile. for (t=max(1,floord(thyme*tau,3)); t<= min(T,floord((3+thyme)*tau-3,3)); t++) { // Loops over spatial dimensions within tile. for (i=max(Li,max((thyme-k1-k2)*tau-t, 2*t-(2+k1+k2)*tau+2)); i<=min(Ui,min((1+thyme-k1-k2)*tau-t-1, 2*t-(k1+k2)*tau)); i++) { for (j=max(Lj,max(tau*k1-t,t-i-(1+k2)*tau+1)); j<=min(Uj,min((1+k1)*tau-t-1,t-i-k2*tau)); j++) { computation( thyme,k1,k2, t, i, j); } // for j } // for i } // for t } // for k2 } // for k1 } // for thyme // End of the file. //svg.printFooter(); pov.printFooter(); return 0; } // MMS, 2/16/15, commented below out on plane /* // loops over bottom left, middle, top right for (int c0 = -2; c0<=0; c0+=1){ // loops horizontally? for (int c1 = 0; c1 <= (Uj+tau-3)/(tau-3) ; c1 += 1){ // loops vertically?, but without skew for (int x = (-Ui-tau+2)/(tau-3); x<=0 ; x += 1){ int c2 = x-c1; //skew // loops for time steps within a slab (slices within slabs) for (int c3 = 1; c3<=subset_s; c3 += 1){ for (int c4 = max(max(max(-tau * c1 - tau * c2 + 2 * c3 - (2*tau-2), -Uj - tau * c2 + c3 - (tau-2)), tau * c0 - tau * c1 - tau * c2 - c3), Li); c4 <= min(min(min(tau * c0 - tau * c1 - tau * c2 - c3 + (tau-1), -tau * c1 - tau * c2 + 2 * c3), -Lj - tau * c2 + c3), Ui - 1); c4 += 1){ for (int c5 = max(max(tau * c1 - c3, Lj), -tau * c2 + c3 - c4 - (tau-1)); c5 <= min(min(Uj - 1, -tau * c2 + c3 - c4), tau * c1 - c3 + (tau-1)); c5 += 1){ computation(c3, c4, c5); } } } } } } */
[ "mstrout@cs.arizona.edu" ]
mstrout@cs.arizona.edu
a2a13abb396dba3943ecb03a3967881aa5a21d6b
fd591fc4b5cba7a2ecfe0a231507a0e9cb1d41c4
/maxflow-v3.02.src/maxflowwrap.cpp
aa6a097649070b4fcf95b1db3c5b75fefb1420f6
[]
no_license
aseembehl/contextssvm
fcc3b2a8c42223e7ac81bbee8e02077251ab9aa5
bd575d1c254bd9cd32176eb2ec00ad87b88ec788
refs/heads/master
2016-09-06T14:24:03.950764
2013-06-27T12:35:43
2013-06-27T12:35:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
901
cpp
#include <stdlib.h> #include "graph.h" int scaleFactor = 1e6; extern "C" int *maxflowwrapper(double *unary_pos, double *unary_neg, double **binary, int n_pos, int n_neg){ int i,j; int *labels; typedef Graph<int,int,int> GraphType; GraphType *g = new GraphType( (n_pos+n_neg), (n_pos+n_neg)*(n_pos+n_neg-1)/2); for (i = 0; i < (n_pos+n_neg); i++){ g -> add_node(); } for (i = 0; i < (n_pos+n_neg); i++){ g -> add_tweights( i, unary_pos[i]*scaleFactor, unary_neg[i]*scaleFactor); for (j = (i+1); j < (n_pos+n_neg); j++){ g -> add_edge( i, j, binary[i][j]*scaleFactor, binary[i][j]*scaleFactor ); } } int flow = g -> maxflow(); labels = (int *) malloc((n_pos+n_neg)*sizeof(int)); for (i = 0; i < (n_pos+n_neg); i++){ if (g->what_segment(i) == GraphType::SOURCE){ labels[i] = -1; } else{ labels[i] = 1; } } delete g; return labels; }
[ "aseembehl@hotmail.com" ]
aseembehl@hotmail.com
8813c0715be910920f9d708ecb6d0c422cd088ff
9287ee4c9477fb07d1e7f6fe5fcacde169923f34
/src/mfx/uitk/NodeInterface.h
d3532b881e9fef14119f7c6799b54100fb92afdb
[]
no_license
AlbertJean/pedalevite
529a73d0d6b858d282f89ae174f5b442d3222071
27e1b09aced5728dca728908a8e32635d3d16b65
refs/heads/master
2021-04-30T01:33:37.603220
2018-01-22T21:08:29
2018-01-22T21:08:29
121,486,765
1
0
null
2018-02-14T08:18:50
2018-02-14T08:18:50
null
UTF-8
C++
false
false
2,126
h
/***************************************************************************** NodeInterface.h Author: Laurent de Soras, 2016 --- Legal stuff --- This program is free software. It comes without any warranty, to the extent permitted by applicable law. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See http://sam.zoy.org/wtfpl/COPYING for more details. *Tab=3***********************************************************************/ #pragma once #if ! defined (mfx_uitk_NodeInterface_HEADER_INCLUDED) #define mfx_uitk_NodeInterface_HEADER_INCLUDED #if defined (_MSC_VER) #pragma warning (4 : 4250) #endif /*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ #include "mfx/uitk/MsgHandlerInterface.h" #include "mfx/uitk/Rect.h" #include "mfx/uitk/Vec2d.h" namespace mfx { namespace ui { class DisplayInterface; } namespace uitk { class ParentInterface; class NodeEvt; class NodeInterface : public MsgHandlerInterface { /*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ public: virtual ~NodeInterface () = default; void notify_attachment (ParentInterface *cont_ptr); int get_id () const; Vec2d get_coord () const; Rect get_bounding_box () const; void redraw (ui::DisplayInterface &disp, Rect clipbox, Vec2d parent_coord); /*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ protected: virtual void do_notify_attachment (ParentInterface *cont_ptr) = 0; virtual int do_get_id () const = 0; virtual Vec2d do_get_coord () const = 0; virtual Rect do_get_bounding_box () const = 0; virtual void do_redraw (ui::DisplayInterface &disp, Rect clipbox, Vec2d parent_coord) = 0; }; // class NodeInterface } // namespace uitk } // namespace mfx //#include "mfx/uitk/NodeInterface.hpp" #endif // mfx_uitk_NodeInterface_HEADER_INCLUDED /*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
[ "fuck@fuck.fuck" ]
fuck@fuck.fuck
75d7a50740abfd828649beb806467f3a4e2f518a
2a13326710803f63aec1f58c493cae5c933354eb
/src/MSMTRX.cpp
f507f679e8f2a808d119076c248d881ef5972cda
[]
no_license
aptrn/aP-Modules
4a7fa1d3132a990d0f649e8aef17dc396409d90d
5c9524936dfdfe9ae5af261519b89b906a3bd148
refs/heads/master
2020-03-28T01:34:02.860755
2019-06-28T19:18:52
2019-06-28T19:18:52
147,514,045
13
3
null
null
null
null
UTF-8
C++
false
false
2,546
cpp
#include "aP.hpp" //Mid/Side Matrix, simple LR to MS encoder and MS to LR decoder struct MSMTRX : Module { enum ParamIds { NUM_PARAMS }; enum InputIds { LEFT_INPUT, RIGHT_INPUT, MID_INPUT, SIDE_INPUT, NUM_INPUTS }; enum OutputIds { LEFT_OUTPUT, RIGHT_OUTPUT, MID_OUTPUT, SIDE_OUTPUT, NUM_OUTPUTS }; enum LightIds { NUM_LIGHTS }; MSMTRX() { config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS);} void process(const ProcessArgs &args) override; }; void MSMTRX::process(const ProcessArgs &args) { //ENCODER float left_in = inputs[LEFT_INPUT].getVoltage(); float right_in = inputs[RIGHT_INPUT].getVoltage(); float mid_out = (left_in + right_in)/sqrt(2); float side_out = (left_in - right_in)/sqrt(2); outputs[MID_OUTPUT].value = mid_out; outputs[SIDE_OUTPUT].value = side_out; //DECODER float mid_in = inputs[MID_INPUT].getVoltage(); float side_in = inputs[SIDE_INPUT].getVoltage(); float left_out = (mid_in + side_in)/sqrt(2); float right_out = (mid_in - side_in)/sqrt(2); outputs[LEFT_OUTPUT].value = left_out; outputs[RIGHT_OUTPUT].setVoltage(right_out); } struct MSMTRXWidget : ModuleWidget { MSMTRXWidget(MSMTRX *module) : ModuleWidget(module) { setPanel(APP->window->loadSvg(asset::plugin(pluginInstance, "res/MSMTRX.svg"))); addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, 0))); addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0))); addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); //ENCODER addInput(createInput<aPJackGiallo>(Vec(16.7, 113.2), module, MSMTRX::LEFT_INPUT)); addInput(createInput<aPJackArancione>(Vec(79.7, 113.2), module, MSMTRX::RIGHT_INPUT)); addOutput(createOutput<aPJackTurchese>(Vec(16.7, 167.2), module, MSMTRX::MID_OUTPUT)); addOutput(createOutput<aPJackBlu>(Vec(79.7, 167.2), module, MSMTRX::SIDE_OUTPUT)); //DECODER addInput(createInput<aPJackTurchese>(Vec(16.7, 247.9), module, MSMTRX::MID_INPUT)); addInput(createInput<aPJackBlu>(Vec(79.7, 247.9), module, MSMTRX::SIDE_INPUT)); addOutput(createOutput<aPJackVerde>(Vec(16.7, 305), module, MSMTRX::LEFT_OUTPUT)); addOutput(createOutput<aPJackRosso>(Vec(79.7, 305), module, MSMTRX::RIGHT_OUTPUT)); } }; Model *modelMSMTRX = createModel<MSMTRX, MSMTRXWidget>("MS-Matrix");
[ "alessandro.nge@gmail.com" ]
alessandro.nge@gmail.com
93f5e41c925213a63c2be98d662d685e89dd13e6
6c9d0a9412783106dbd0544928575924e5cdc168
/principal.h
d1111c827b0a6f91a990252963866f6a24305dd6
[]
no_license
MatSant0s/Internacionalizacion
8711f916c591d2597915b192a701daa5b3d06b28
e584efb5c89c116bf8402585e4db6bd1372f98fc
refs/heads/main
2023-06-23T17:46:30.076096
2021-07-20T03:11:52
2021-07-20T03:11:52
387,657,312
0
0
null
null
null
null
UTF-8
C++
false
false
844
h
#ifndef PRINCIPAL_H #define PRINCIPAL_H #include "calculosalario.h" #include "acerca.h" #include <QMainWindow> #define VERSION "1.0.0" //version #include <QDebug> #include <QFileDialog> #include <QDir> #include <QFile> #include <QTextStream> QT_BEGIN_NAMESPACE namespace Ui { class Principal; } QT_END_NAMESPACE class Principal : public QMainWindow { Q_OBJECT public: Principal(QWidget *parent = nullptr); ~Principal(); private slots: void on_actionSalir_triggered(); void on_cmdCalcular_clicked(); void on_actionCalcular_triggered(); void on_actionNuevo_triggered(); void on_actionAcerca_de_triggered(); void on_actionGuardar_triggered(); void on_actionAbrir_triggered(); private: Ui::Principal *ui; void calcular(); void borrar(); void nuevo(); }; #endif // PRINCIPAL_H
[ "santosmateo.2002@gmail.com" ]
santosmateo.2002@gmail.com
1f4614a85784f4fd2ad75d001466977d623cd5f4
98b63e3dc79c75048163512c3d1b71d4b6987493
/tensorflow/lite/delegates/gpu/cl/kernels/special/depthwise_conv_plus_1x1_conv.h
b87051104b76647649197ddef22edd0244b0c549
[ "Apache-2.0" ]
permissive
galeone/tensorflow
11a4e4a3f42f4f61a65b432c429ace00401c9cc4
1b6f13331f4d8e7fccc66bfeb0b066e77a2b7206
refs/heads/master
2022-11-13T11:56:56.143276
2020-11-10T14:35:01
2020-11-10T14:35:01
310,642,488
21
12
Apache-2.0
2020-11-06T16:01:03
2020-11-06T16:01:02
null
UTF-8
C++
false
false
2,012
h
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_LITE_DELEGATES_GPU_CL_KERNELS_SPECIAL_DEPTHWISE_CONV_PLUS_1X1_CONV_H_ #define TENSORFLOW_LITE_DELEGATES_GPU_CL_KERNELS_SPECIAL_DEPTHWISE_CONV_PLUS_1X1_CONV_H_ #include <vector> #include "tensorflow/lite/delegates/gpu/cl/buffer.h" #include "tensorflow/lite/delegates/gpu/cl/gpu_object.h" #include "tensorflow/lite/delegates/gpu/cl/kernels/gpu_operation.h" #include "tensorflow/lite/delegates/gpu/cl/util.h" #include "tensorflow/lite/delegates/gpu/common/data_type.h" #include "tensorflow/lite/delegates/gpu/common/operations.h" #include "tensorflow/lite/delegates/gpu/common/shape.h" #include "tensorflow/lite/delegates/gpu/common/status.h" #include "tensorflow/lite/delegates/gpu/common/tensor.h" #include "tensorflow/lite/delegates/gpu/common/types.h" namespace tflite { namespace gpu { namespace cl { bool IsDepthwiseConvPlus1x1ConvSupported( const OperationDef& definition, const DepthwiseConvolution2DAttributes& dw_attr, const Convolution2DAttributes& conv_attr); GPUOperation CreateDepthwiseConvPlus1x1Conv( const OperationDef& definition, const DepthwiseConvolution2DAttributes& dw_attr, const Convolution2DAttributes& conv_attr); } // namespace cl } // namespace gpu } // namespace tflite #endif // TENSORFLOW_LITE_DELEGATES_GPU_CL_KERNELS_SPECIAL_DEPTHWISE_CONV_PLUS_1X1_CONV_H_
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
7218cfed75cc07fe4097186795e7381ee75dc918
1118edba458a471ab0ed095aa1b80bd32c222c2a
/http_server_types.h
64a89abab43163c5009c64bc55f0a27b44503585
[]
no_license
vortarian/rest_service
1475ca73a9940501f3a55debfa4ce86b298d9129
6a5d947f1c31c7b33ee24166cae0693dd1c78b9b
refs/heads/master
2021-03-12T19:57:51.016143
2013-08-19T19:34:55
2013-08-19T19:34:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
300
h
#ifndef HTTP_SERVER_TYPES_H #define HTTP_SERVER_TYPES_H namespace http { namespace server { // key is name, entry is value typedef std::multimap<std::string, std::string> Headers; typedef std::multimap<std::string, std::string> Parameters; } // server } // http #endif /* HTTP_SERVER_TYPES_H */
[ "vortarian@systemicai.com" ]
vortarian@systemicai.com
36f68a5404ee4aa2c93a2fbd5609c67da619c3d4
b1edb72968077b39e00d19f969b64611ebe7215c
/VentanaEdit.h
9ad01b6b1ab98a361a3b8b728aa0fe60e96d0aa0
[]
no_license
hr9457/EDD_1S2020_P1_201314296
737f0a82e3e86f39599c826558b02f3892e2feff
b3b3cb5de2231baeccae2e5f2d6c449323337f63
refs/heads/master
2022-04-03T23:52:16.368636
2020-02-19T03:25:16
2020-02-19T03:25:16
239,230,350
0
0
null
null
null
null
UTF-8
C++
false
false
1,139
h
#ifndef VENTANAEDIT_H #define VENTANNAEDIT_H #include "ListaDobleEnlazada.h" #include "NodoListaDoble.h" #include <iostream> #include <string> #include <windows.h> #include <stdio.h> #include <stdlib.h> #include <conio.h> #include <fstream> using namespace std; class VentanaEdit { private: int inKeyboard,columna=1,saltoLinea=1,finalPantalla=117,altoPantalla=27; int inicioMenu=1; int columnaBuscar=inicioMenu, altoPantallaBuscar=altoPantalla; int ancho=GetSystemMetrics(SM_CXSCREEN); int alto=GetSystemMetrics(SM_CYSCREEN); char caracter; ListaDobleEnlazada listaDoble;//creacion objeto para la lista doble string palabraBuscar,palabraRemplazar,rutaArchivo; string rutaDeApertura; char caracterArchivo; public: VentanaEdit(); VentanaEdit(string ruta); bool existenciaArchivo(char *arg); void lercuturaArchivo(string arg); void gotoxy(int posx,int posy); void ediccion(); void marco(); void Repintar(); void guardar(string ruta); ~VentanaEdit(); }; #endif
[ "hr9457@gmail.com" ]
hr9457@gmail.com
f3edb6db114a4a1452f032ed09cdedc293a46306
b3c47795e8b6d95ae5521dcbbb920ab71851a92f
/Exemplars/图论/2-SAT/2-SAT 输出任意解.cc
b572452ab5b7604293e757280cd7db6b712700a0
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
Wizmann/ACM-ICPC
6afecd0fd09918c53a2a84c4d22c244de0065710
7c30454c49485a794dcc4d1c09daf2f755f9ecc1
refs/heads/master
2023-07-15T02:46:21.372860
2023-07-09T15:30:27
2023-07-09T15:30:27
3,009,276
51
23
null
null
null
null
UTF-8
C++
false
false
4,700
cc
/* * Wedding * Time Limit: 1000MS Memory Limit: 65536K * Total Submissions: 5932 Accepted: 1821 Special Judge * * Description * * Up to thirty couples will attend a wedding feast, at which they will be seated on either * side of a long table. The bride and groom sit at one end, opposite each other, and the * bride wears an elaborate headdress that keeps her from seeing people on the same side as * her. It is considered bad luck to have a husband and wife seated on the same side of the * table. Additionally, there are several pairs of people conducting adulterous relationships * (both different-sex and same-sex relationships are possible), and it is bad luck for the * bride to see both members of such a pair. Your job is to arrange people at the table * so as to avoid any bad luck. * * Input * * The input consists of a number of test cases, followed by a line containing 0 0. Each test * case gives n, the number of couples, followed by the number of adulterous pairs, followed * by the pairs, in the form "4h 2w" (husband from couple 4, wife from couple 2), or "10w 4w", * or "3h 1h". Couples are numbered from 0 to n - 1 with the bride and groom being 0w and 0h. * * Output * * For each case, output a single line containing a list of the people that should be seated * on the same side as the bride. If there are several solutions, any one will do. If there * is no solution, output a line containing "bad luck". * * Sample Input * * 10 6 * 3h 7h * 5w 3w * 7h 6w * 8w 3w * 7h 3w * 2w 5h * 0 0 * * Sample Output * * 1h 2h 3w 4h 5h 6h 7h 8h 9h */ /* * 2-SAT 输出解问题 * 一对(h,w)不能在一边,给出的通奸关系也不能在一边 * 输出解时,(i)为h,(i+n)为w */ //Result:wizmann 3648 Accepted 288K 16MS C++ 3133B 2012-10-16 13:59:03 #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <algorithm> #include <stack> #include <queue> using namespace std; #define print(x) cout<<x<<endl #define input(x) cin>>x #define NODE 1010 #define EDGE 300100 struct _link { int val,next; _link(){} _link(int ival,int inext) { val=ival; next=inext; } }; struct linklist { int head[NODE],ind; _link edge[EDGE]; inline void init() { memset(head,-1,sizeof(head)); ind=0; } inline void addEdge(int a,int b) { edge[ind]=_link(b,head[a]); head[a]=ind++; } }; int n,m; char instack[NODE]; stack<int> st; int dfn[NODE],scc[NODE],num[NODE],low[NODE]; int sccnr,nr; linklist g,sccg; void init() { memset(instack,0,sizeof(instack)); memset(scc,0,sizeof(scc)); memset(num,0,sizeof(num)); memset(low,0,sizeof(low)); memset(dfn,0,sizeof(dfn)); st=stack<int>(); nr=1;sccnr=0; g.init(); } void tarjan(int pos) { low[pos]=dfn[pos]=nr++; st.push(pos); instack[pos]=1; for(int i=g.head[pos];i!=-1;i=g.edge[i].next) { int j=g.edge[i].val; if(!dfn[j]) { tarjan(j); low[pos]=min(low[pos],low[j]); } else if(instack[j]) { low[pos]=min(low[pos],dfn[j]); } } if(dfn[pos]==low[pos]) { sccnr++; while(1) { int t=st.top(); instack[t]=0; st.pop(); scc[t]=sccnr; num[sccnr]++; if(t==pos) break; } } } bool slove() { for(int i=0;i<n*2;i++) { if(!dfn[i]) tarjan(i); } for(int i=0;i<n;i++) { if(scc[i]==scc[i+n]) return false; } return true; } void printAns() { int fami[NODE]={0}; int in[NODE]={0}; int mark[NODE]={0}; sccg.init(); for(int i=0;i<n;i++) { fami[scc[i]]=scc[i+n]; fami[scc[i+n]]=scc[i]; } for(int i=0;i<2*n;i++) { for(int j=g.head[i];j!=-1;j=g.edge[j].next) { if(scc[i]!=scc[g.edge[j].val]) { sccg.addEdge(scc[i],scc[g.edge[j].val]); in[scc[g.edge[j].val]]++; } } } queue<int> q; for(int i=1;i<=sccnr;i++) { if(!in[i]) q.push(i); } while(!q.empty()) { int now=q.front(); q.pop(); if(!mark[now]) { mark[now]=1; mark[fami[now]]=-1; } for(int i=sccg.head[now];i!=-1;i=sccg.edge[i].next) { int next=sccg.edge[i].val; if(--in[next]==0) q.push(next); } } for(int i=1;i<n;i++) { if(i>1) printf(" "); if(mark[scc[i]]==-1) printf("%dw",i); else printf("%dh",i); } puts(""); } int main() { int a,b; char aa,bb; while(input(n>>m) && n+m) { init(); g.addEdge(n,0);//The husband must in the group while(m--) { scanf("%d%c %d%c",&a,&aa,&b,&bb); if(aa=='h' && bb=='h') { g.addEdge(a,b+n); g.addEdge(b,a+n); } else if(aa=='w' && bb=='w') { g.addEdge(a+n,b); g.addEdge(b+n,a); } else if(aa=='h' && bb=='w') { g.addEdge(a,b); g.addEdge(b+n,a+n); } else if(aa=='w' && bb=='h') { g.addEdge(b,a); g.addEdge(a+n,b+n); } } if(!slove()) puts("bad luck"); else printAns(); } return 0; }
[ "kuuy@foxmail.com" ]
kuuy@foxmail.com
34a6adb8d3addc2165c7c1fa3c0e1bfd2650452d
154665777ea7209ffcc1e35b2511c19eff45899b
/Projects/Misc/CodeCleaner/DecisionTreeTrainer.cpp
b4ce1a83bb1c0d16aae4262c32a8ab98a4a8e0c1
[]
no_license
freelancer91/MyHub
33e9a81bd7c6c89a8a46d39b85f65d9f331ec05e
2b32961164418552fc3b494588cbfde13eb5aefc
refs/heads/master
2021-01-19T14:30:57.518138
2014-05-07T10:18:44
2014-05-07T10:18:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,890
cpp
#include "DecisionTreeTrainer.h" #include <iostream> using namespace std; DecisionTreeTrainer::DecisionTreeTrainer() { this->tree = NULL; } DecisionTreeTrainer::DecisionTreeTrainer(istream& metaDataStream,istream& trainingDataStream, DecisionTree* tree) { this->tree = tree; this->readInMetaData(metaDataStream); this->readInTrainingData(trainingDataStream); vector<int> openAttributeList; int i; for (i = 0; i < this->tree->getNumberOfAttributes() - 1; i++)openAttributeList.push_back(i); vector<shared_ptr<Example>> openExampleList; for (i = 0; i < this->getNumberOfExamples(); i++)openExampleList.push_back(this->exampleList.at(i)); this->trainNode(tree->getRoot(), openExampleList, openAttributeList); } DecisionTreeTrainer::DecisionTreeTrainer(DecisionTreeTrainer* original) { this->tree = original->tree; this->exampleList = original->exampleList; } DecisionTreeTrainer DecisionTreeTrainer::operator =( const DecisionTreeTrainer& rhs) { if (this == &rhs) return *this; this->tree = rhs.tree; this->exampleList = rhs.exampleList; return *this; } DecisionTreeTrainer::~DecisionTreeTrainer() { /* Nothing to do */ } void DecisionTreeTrainer::addExample(Example& example) { this->exampleList.push_back(make_shared<Example>(example)); } DecisionTree* DecisionTreeTrainer::getTree() { return this->tree; } Example& DecisionTreeTrainer::getExample(int index) { return *this->exampleList[index]; } int DecisionTreeTrainer::getNumberOfExamples() { return this->exampleList.size(); } void DecisionTreeTrainer::readInMetaData(istream& metaDataStream) { string line; while (getline(metaDataStream, line)) { line = line.substr(0, line.find('\r')); while (!line.empty()) { unsigned long cutOffPosition = line.find(":"); string attributeName = line.substr(0, cutOffPosition); Attribute attribute = new Attribute(); attribute.setAttributeName(attributeName); line = line.substr(cutOffPosition + 1); while (!line.empty()) { cutOffPosition = line.find(","); if (cutOffPosition != string::npos) { string possibleValue = line.substr(0, cutOffPosition); attribute.addPossibleValue(possibleValue); line = line.substr(cutOffPosition + 1); } else { attribute.addPossibleValue(line); line = ""; } } this->tree->addAttribute(attribute); } } } void DecisionTreeTrainer::readInTrainingData(istream& trainingDataStream) { string line; while (getline(trainingDataStream, line)) { line = line.substr(0, line.find('\r')); Example example = new Example(); this->readExampleAttributes(example, line); for (int i = 0; i < this->tree->getNumberOfClassifications(); i++) { if (tree->getClassification(i) == line) { example.setClassificationIndex(i); break; } } this->addExample(example); } } Example& DecisionTreeTrainer::readExampleAttributes(Example& example, string& line) { for (int i = 0; i < this->tree->getNumberOfAttributes() - 1; i++) { unsigned long commaPosition = line.find(","); string attributeValue = line.substr(0, commaPosition); for (int j = 0; j < tree->getAttribute(i).getNumberOfPossibleValues(); j++) { if (attributeValue == tree->getAttribute(i).getPossibleValue(j)) { example.addAttributeValueIndex(j); break; } } line = line.substr(commaPosition + 1); } return example; } void DecisionTreeTrainer::trainNode(shared_ptr<DecisionTreeNode>& node,vector<shared_ptr<Example>>& openExampleList,vector<int>& openAttributeList) { double entropy = 0.0; int i; for (i = 0; i < this->tree->getNumberOfClassifications(); i++)entropy += calculateEntropy(i, openExampleList); double highestInformationGain = 0.0; int highestInformationGainIndex = 0; unsigned int j; for (j = 0; j < openAttributeList.size(); j++) { double informationGain = this->calculateInformationGain(entropy, openExampleList,openAttributeList.at(j)); if (informationGain > highestInformationGain) { highestInformationGain = informationGain; highestInformationGainIndex = openAttributeList.at(j); } } (*node).setSplittingAttributeIndex(highestInformationGainIndex); for (i = 0;i <this->tree->getAttribute(highestInformationGainIndex).getNumberOfPossibleValues();i++) { shared_ptr<DecisionTreeNode> newNode (new DecisionTreeNode()); vector<shared_ptr<Example>> newOpenExampleList; unsigned int k; for (k = 0; k < openExampleList.size(); k++) { if ((*openExampleList.at(k)).getAttributeValueIndex(highestInformationGainIndex)== i)newOpenExampleList.push_back(openExampleList.at(k)); } if(newOpenExampleList.size() == 0){ (*node).addClassificationIndex(-2); (*node).addDecision(*newNode); }else{ int classificationForNode = (*newOpenExampleList.at(0)).getClassificationIndex(); for (k = 1; k < newOpenExampleList.size(); k++) { if (classificationForNode != (*newOpenExampleList.at(k)).getClassificationIndex()) { classificationForNode = -1; break; } } (*node).addClassificationIndex(classificationForNode); vector<int> newOpenAttributeList; for (k = 0; k < openAttributeList.size(); k++) { if (openAttributeList.at(k) != highestInformationGainIndex) newOpenAttributeList.push_back(openAttributeList.at(k)); } (*node).addDecision(*newNode); if ((*node).getClassificationIndex(i) == -1) this->trainNode((*node).getDecision(i), newOpenExampleList, newOpenAttributeList); } } } double DecisionTreeTrainer::calculateEntropy(int classificationIndex,vector<shared_ptr<Example>>& openExampleList) { int numberOfOccurrences = 0; for (unsigned int i = 0; i < openExampleList.size(); i++) { if ((*openExampleList.at(i)).getClassificationIndex() == classificationIndex)numberOfOccurrences++; } return -(((double)numberOfOccurrences / (double)openExampleList.size()) * this->log2((double)numberOfOccurrences /(double)openExampleList.size())); } double DecisionTreeTrainer::calculateInformationGain(double entropy,vector<shared_ptr<Example>>& openExampleList, int attribute) { int i; double sum = 0.0; for (i = 0; i < this->tree->getAttribute(attribute).getNumberOfPossibleValues(); i++) { unsigned int j; vector<shared_ptr<Example>> examplesWhereAttributeValueOccurred; for (j = 0; j < openExampleList.size(); j++) { if (i == (*openExampleList.at(j)).getAttributeValueIndex(attribute))examplesWhereAttributeValueOccurred.push_back(openExampleList.at(j)); } if(examplesWhereAttributeValueOccurred.size() == 0)continue; double attributeValueProbability = (double)examplesWhereAttributeValueOccurred.size() / (double)openExampleList.size(); vector<int> classifications; classifications.push_back((*examplesWhereAttributeValueOccurred.at(0)).getClassificationIndex()); unsigned int l; for (l = 1; l < examplesWhereAttributeValueOccurred.size();l++) { bool found = false; for(unsigned int m = 0; m < classifications.size();m++){ if(classifications[m] == (*examplesWhereAttributeValueOccurred.at(l)).getClassificationIndex()){ found = true; break; } } if(found){ continue; } classifications.push_back((*examplesWhereAttributeValueOccurred.at(l)).getClassificationIndex()); } if(classifications.size() == 1){ return 1.0; } double entropySum = 0.0; int k; for (k = 0; k < this->tree->getNumberOfClassifications(); k++) entropySum += calculateEntropy(k, examplesWhereAttributeValueOccurred); double subSum = attributeValueProbability * entropySum; sum += subSum; } return entropy - sum; } double DecisionTreeTrainer::log2(double x) { if (x == 0.0)return 0.0; return log(x) / log(2); }
[ "freelancer1991@gmail.com" ]
freelancer1991@gmail.com
4e3d32b22e0f9d4130cd8cb35d3063b622fbc662
20c1e398bbdae8da358c6099e451c9bf8ef6ff7f
/orca/include/orca/RVOSimulator.h
ec08834da30b3f9171a4fe9215b7291becc27f15
[]
no_license
YangZhengShi/DynamicObstacleAvoidance
4f953e3334c915bd41ac7326cb2c80fb3e90e99a
7d6b4bc6a4b47c96b49a52457f29cf0b3bdb6dbb
refs/heads/master
2023-04-29T11:36:52.765027
2020-11-20T00:34:18
2020-11-20T00:34:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
26,606
h
/* * RVOSimulator.h * RVO2 Library * * Copyright 2008 University of North Carolina at Chapel Hill * * 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. * * Please send all bug reports to <geom@cs.unc.edu>. * * The authors may be contacted via: * * Jur van den Berg, Stephen J. Guy, Jamie Snape, Ming C. Lin, Dinesh Manocha * Dept. of Computer Science * 201 S. Columbia St. * Frederick P. Brooks, Jr. Computer Science Bldg. * Chapel Hill, N.C. 27599-3175 * United States of America * * <http://gamma.cs.unc.edu/RVO2/> */ #ifndef RVO_RVO_SIMULATOR_H_ #define RVO_RVO_SIMULATOR_H_ # pragma once /** * \file RVOSimulator.h * \brief Contains the RVOSimulator class. */ #include <cstddef> #include <limits> #include <vector> #include "Vector2.h" //#include "orca/gazeboSO1.h" namespace RVO { /** * \brief Error value. * * A value equal to the largest unsigned integer that is returned in case * of an error by functions in RVO::RVOSimulator. */ const size_t RVO_ERROR = std::numeric_limits<size_t>::max(); /** * \brief Defines a directed line. */ class Line { public: /** * \brief A point on the directed line. */ Vector2 point; /** * \brief The direction of the directed line. */ Vector2 direction; }; class Agent; class KdTree; class Obstacle; //class Test_Sim; /** * \brief Defines the simulation. * * The main class of the library that contains all simulation functionality. */ class RVOSimulator { public: /** * \brief Constructs a simulator instance. */ RVOSimulator(); /** * \brief Constructs a simulator instance and sets the default * properties for any new agent that is added. * \param timeStep The time step of the simulation. * Must be positive. * \param neighborDist The default maximum distance (center point * to center point) to other agents a new agent * takes into account in the navigation. The * larger this number, the longer he running * time of the simulation. If the number is too * low, the simulation will not be safe. Must be * non-negative. * \param maxNeighbors The default maximum number of other agents a * new agent takes into account in the * navigation. The larger this number, the * longer the running time of the simulation. * If the number is too low, the simulation * will not be safe. * \param timeHorizon The default minimal amount of time for which * a new agent's velocities that are computed * by the simulation are safe with respect to * other agents. The larger this number, the * sooner an agent will respond to the presence * of other agents, but the less freedom the * agent has in choosing its velocities. * Must be positive. * \param timeHorizonObst The default minimal amount of time for which * a new agent's velocities that are computed * by the simulation are safe with respect to * obstacles. The larger this number, the * sooner an agent will respond to the presence * of obstacles, but the less freedom the agent * has in choosing its velocities. * Must be positive. * \param radius The default radius of a new agent. * Must be non-negative. * \param maxSpeed The default maximum speed of a new agent. * Must be non-negative. * \param velocity The default initial two-dimensional linear * velocity of a new agent (optional). */ RVOSimulator(float timeStep, float neighborDist, size_t maxNeighbors, float timeHorizon, float timeHorizonObst, float radius, float maxSpeed, const Vector2 &velocity = Vector2()); /** * \brief Destroys this simulator instance. */ ~RVOSimulator(); /** * \brief Adds a new agent with default properties to the * simulation. * \param position The two-dimensional starting position of * this agent. * \return The number of the agent, or RVO::RVO_ERROR when the agent * defaults have not been set. */ size_t addAgent(const Vector2 &position); /** * \brief Adds a new agent to the simulation. * \param position The two-dimensional starting position of * this agent. * \param neighborDist The maximum distance (center point to * center point) to other agents this agent * takes into account in the navigation. The * larger this number, the longer the running * time of the simulation. If the number is too * low, the simulation will not be safe. * Must be non-negative. * \param maxNeighbors The maximum number of other agents this * agent takes into account in the navigation. * The larger this number, the longer the * running time of the simulation. If the * number is too low, the simulation will not * be safe. * \param timeHorizon The minimal amount of time for which this * agent's velocities that are computed by the * simulation are safe with respect to other * agents. The larger this number, the sooner * this agent will respond to the presence of * other agents, but the less freedom this * agent has in choosing its velocities. * Must be positive. * \param timeHorizonObst The minimal amount of time for which this * agent's velocities that are computed by the * simulation are safe with respect to * obstacles. The larger this number, the * sooner this agent will respond to the * presence of obstacles, but the less freedom * this agent has in choosing its velocities. * Must be positive. * \param radius The radius of this agent. * Must be non-negative. * \param maxSpeed The maximum speed of this agent. * Must be non-negative. * \param velocity The initial two-dimensional linear velocity * of this agent (optional). * \return The number of the agent. */ size_t addAgent(const Vector2 &position, float neighborDist, size_t maxNeighbors, float timeHorizon, float timeHorizonObst, float radius, float maxSpeed, const Vector2 &velocity = Vector2()); /** * \brief Adds a new obstacle to the simulation. * \param vertices List of the vertices of the polygonal * obstacle in counterclockwise order. * \return The number of the first vertex of the obstacle, * or RVO::RVO_ERROR when the number of vertices is less than two. * \note To add a "negative" obstacle, e.g. a bounding polygon around * the environment, the vertices should be listed in clockwise * order. */ size_t addObstacle(const std::vector<Vector2> &vertices); /** * \brief Lets the simulator perform a simulation step and updates the * two-dimensional position and two-dimensional velocity of * each agent. */ void doStep(); /** * \brief Calls the getTestSimPtr function for each of the agents * \param agentNo The number of the agent whose agent * neighbor is to be retrieved. * \param test_sim_ptr Call the Agent's getTestSimPtr function with * this ptr as imput * \return Nada. */ /*void callAgentPtrGetterFunction(size_t agentNo, Test_Sim* test_sim_ptr) const;*/ /** * \brief Returns the specified agent neighbor of the specified * agent. * \param agentNo The number of the agent whose agent * neighbor is to be retrieved. * \param neighborNo The number of the agent neighbor to be * retrieved. * \return The number of the neighboring agent. */ size_t getAgentAgentNeighbor(size_t agentNo, size_t neighborNo) const; /** * \brief Returns the maximum neighbor count of a specified agent. * \param agentNo The number of the agent whose maximum * neighbor count is to be retrieved. * \return The present maximum neighbor count of the agent. */ size_t getAgentMaxNeighbors(size_t agentNo) const; /** * \brief Returns the maximum speed of a specified agent. * \param agentNo The number of the agent whose maximum speed * is to be retrieved. * \return The present maximum speed of the agent. */ float getAgentMaxSpeed(size_t agentNo) const; /** * \brief Returns the maximum neighbor distance of a specified * agent. * \param agentNo The number of the agent whose maximum * neighbor distance is to be retrieved. * \return The present maximum neighbor distance of the agent. */ float getAgentNeighborDist(size_t agentNo) const; /** * \brief Returns the count of agent neighbors taken into account to * compute the current velocity for the specified agent. * \param agentNo The number of the agent whose count of agent * neighbors is to be retrieved. * \return The count of agent neighbors taken into account to compute * the current velocity for the specified agent. */ size_t getAgentNumAgentNeighbors(size_t agentNo) const; /** * \brief Returns the count of obstacle neighbors taken into account * to compute the current velocity for the specified agent. * \param agentNo The number of the agent whose count of * obstacle neighbors is to be retrieved. * \return The count of obstacle neighbors taken into account to * compute the current velocity for the specified agent. */ size_t getAgentNumObstacleNeighbors(size_t agentNo) const; /** * \brief Returns the count of ORCA constraints used to compute * the current velocity for the specified agent. * \param agentNo The number of the agent whose count of ORCA * constraints is to be retrieved. * \return The count of ORCA constraints used to compute the current * velocity for the specified agent. */ size_t getAgentNumORCALines(size_t agentNo) const; /** * \brief Returns the specified obstacle neighbor of the specified * agent. * \param agentNo The number of the agent whose obstacle * neighbor is to be retrieved. * \param neighborNo The number of the obstacle neighbor to be * retrieved. * \return The number of the first vertex of the neighboring obstacle * edge. */ size_t getAgentObstacleNeighbor(size_t agentNo, size_t neighborNo) const; /** * \brief Returns the specified ORCA constraint of the specified * agent. * \param agentNo The number of the agent whose ORCA * constraint is to be retrieved. * \param lineNo The number of the ORCA constraint to be * retrieved. * \return A line representing the specified ORCA constraint. * \note The halfplane to the left of the line is the region of * permissible velocities with respect to the specified * ORCA constraint. */ const Line &getAgentORCALine(size_t agentNo, size_t lineNo) const; /** * \brief Returns the two-dimensional position of a specified * agent. * \param agentNo The number of the agent whose * two-dimensional position is to be retrieved. * \return The present two-dimensional position of the (center of the) * agent. */ const Vector2 &getAgentPosition(size_t agentNo) const; /** * \brief Returns the two-dimensional preferred velocity of a * specified agent. * \param agentNo The number of the agent whose * two-dimensional preferred velocity is to be * retrieved. * \return The present two-dimensional preferred velocity of the agent. */ const Vector2 &getAgentPrefVelocity(size_t agentNo) const; /** * \brief Returns the radius of a specified agent. * \param agentNo The number of the agent whose radius is to * be retrieved. * \return The present radius of the agent. */ float getAgentRadius(size_t agentNo) const; /** * \brief Returns the time horizon of a specified agent. * \param agentNo The number of the agent whose time horizon * is to be retrieved. * \return The present time horizon of the agent. */ float getAgentTimeHorizon(size_t agentNo) const; /** * \brief Returns the time horizon with respect to obstacles of a * specified agent. * \param agentNo The number of the agent whose time horizon * with respect to obstacles is to be * retrieved. * \return The present time horizon with respect to obstacles of the * agent. */ float getAgentTimeHorizonObst(size_t agentNo) const; /** * \brief Returns the two-dimensional linear velocity of a * specified agent. * \param agentNo The number of the agent whose * two-dimensional linear velocity is to be * retrieved. * \return The present two-dimensional linear velocity of the agent. */ const Vector2 &getAgentVelocity(size_t agentNo) const; /** * \brief Returns the global time of the simulation. * \return The present global time of the simulation (zero initially). */ float getGlobalTime() const; /** * \brief Returns the count of agents in the simulation. * \return The count of agents in the simulation. */ size_t getNumAgents() const; /** * \brief Returns the count of obstacle vertices in the simulation. * \return The count of obstacle vertices in the simulation. */ size_t getNumObstacleVertices() const; /** * \brief Returns the two-dimensional position of a specified obstacle * vertex. * \param vertexNo The number of the obstacle vertex to be * retrieved. * \return The two-dimensional position of the specified obstacle * vertex. */ const Vector2 &getObstacleVertex(size_t vertexNo) const; /** * \brief Returns the number of the obstacle vertex succeeding the * specified obstacle vertex in its polygon. * \param vertexNo The number of the obstacle vertex whose * successor is to be retrieved. * \return The number of the obstacle vertex succeeding the specified * obstacle vertex in its polygon. */ size_t getNextObstacleVertexNo(size_t vertexNo) const; /** * \brief Returns the number of the obstacle vertex preceding the * specified obstacle vertex in its polygon. * \param vertexNo The number of the obstacle vertex whose * predecessor is to be retrieved. * \return The number of the obstacle vertex preceding the specified * obstacle vertex in its polygon. */ size_t getPrevObstacleVertexNo(size_t vertexNo) const; /** * \brief Returns the time step of the simulation. * \return The present time step of the simulation. */ float getTimeStep() const; /** * \brief Processes the obstacles that have been added so that they * are accounted for in the simulation. * \note Obstacles added to the simulation after this function has * been called are not accounted for in the simulation. */ void processObstacles(); /** * \brief Performs a visibility query between the two specified * points with respect to the obstacles * \param point1 The first point of the query. * \param point2 The second point of the query. * \param radius The minimal distance between the line * connecting the two points and the obstacles * in order for the points to be mutually * visible (optional). Must be non-negative. * \return A boolean specifying whether the two points are mutually * visible. Returns true when the obstacles have not been * processed. */ bool queryVisibility(const Vector2 &point1, const Vector2 &point2, float radius = 0.0f) const; /** * \brief Sets the default properties for any new agent that is * added. * \param neighborDist The default maximum distance (center point * to center point) to other agents a new agent * takes into account in the navigation. The * larger this number, the longer he running * time of the simulation. If the number is too * low, the simulation will not be safe. * Must be non-negative. * \param maxNeighbors The default maximum number of other agents a * new agent takes into account in the * navigation. The larger this number, the * longer the running time of the simulation. * If the number is too low, the simulation * will not be safe. * \param timeHorizon The default minimal amount of time for which * a new agent's velocities that are computed * by the simulation are safe with respect to * other agents. The larger this number, the * sooner an agent will respond to the presence * of other agents, but the less freedom the * agent has in choosing its velocities. * Must be positive. * \param timeHorizonObst The default minimal amount of time for which * a new agent's velocities that are computed * by the simulation are safe with respect to * obstacles. The larger this number, the * sooner an agent will respond to the presence * of obstacles, but the less freedom the agent * has in choosing its velocities. * Must be positive. * \param radius The default radius of a new agent. * Must be non-negative. * \param maxSpeed The default maximum speed of a new agent. * Must be non-negative. * \param velocity The default initial two-dimensional linear * velocity of a new agent (optional). */ void setAgentDefaults(float neighborDist, size_t maxNeighbors, float timeHorizon, float timeHorizonObst, float radius, float maxSpeed, const Vector2 &velocity = Vector2()); /** * \brief Sets the maximum neighbor count of a specified agent. * \param agentNo The number of the agent whose maximum * neighbor count is to be modified. * \param maxNeighbors The replacement maximum neighbor count. */ void setAgentMaxNeighbors(size_t agentNo, size_t maxNeighbors); /** * \brief Sets the maximum speed of a specified agent. * \param agentNo The number of the agent whose maximum speed * is to be modified. * \param maxSpeed The replacement maximum speed. Must be * non-negative. */ void setAgentMaxSpeed(size_t agentNo, float maxSpeed); /** * \brief Sets the maximum neighbor distance of a specified agent. * \param agentNo The number of the agent whose maximum * neighbor distance is to be modified. * \param neighborDist The replacement maximum neighbor distance. * Must be non-negative. */ void setAgentNeighborDist(size_t agentNo, float neighborDist); /** * \brief Sets the two-dimensional position of a specified agent. * \param agentNo The number of the agent whose * two-dimensional position is to be modified. * \param position The replacement of the two-dimensional * position. */ void setAgentPosition(size_t agentNo, const Vector2 &position); /** * \brief Sets the two-dimensional preferred velocity of a * specified agent. * \param agentNo The number of the agent whose * two-dimensional preferred velocity is to be * modified. * \param prefVelocity The replacement of the two-dimensional * preferred velocity. */ void setAgentPrefVelocity(size_t agentNo, const Vector2 &prefVelocity); /** * \brief Sets the radius of a specified agent. * \param agentNo The number of the agent whose radius is to * be modified. * \param radius The replacement radius. * Must be non-negative. */ void setAgentRadius(size_t agentNo, float radius); /** * \brief Sets the time horizon of a specified agent with respect * to other agents. * \param agentNo The number of the agent whose time horizon * is to be modified. * \param timeHorizon The replacement time horizon with respect * to other agents. Must be positive. */ void setAgentTimeHorizon(size_t agentNo, float timeHorizon); /** * \brief Sets the time horizon of a specified agent with respect * to obstacles. * \param agentNo The number of the agent whose time horizon * with respect to obstacles is to be modified. * \param timeHorizonObst The replacement time horizon with respect to * obstacles. Must be positive. */ void setAgentTimeHorizonObst(size_t agentNo, float timeHorizonObst); /** * \brief Sets the two-dimensional linear velocity of a specified * agent. * \param agentNo The number of the agent whose * two-dimensional linear velocity is to be * modified. * \param velocity The replacement two-dimensional linear * velocity. */ void setAgentVelocity(size_t agentNo, const Vector2 &velocity); /** * \brief Sets the time step of the simulation. * \param timeStep The time step of the simulation. * Must be positive. */ void setTimeStep(float timeStep); /** * \brief Clears the obstacle vector for new vector to be build efficiently * */ void clearObstacleVector(); private: std::vector<Agent *> agents_; Agent *defaultAgent_; float globalTime_; KdTree *kdTree_; std::vector<Obstacle *> obstacles_; float timeStep_; friend class Agent; friend class KdTree; friend class Obstacle; }; } #endif /* RVO_RVO_SIMULATOR_H_ */
[ "kshah@wpi.edu" ]
kshah@wpi.edu
8a65be6f2ff1f4cca0e58f7cec1de3475badcfa8
6044aa8fa8792bbb2e781b09db3d87b11f25c6a5
/node_class.h
76d2a006e7da7359da0797ff0ac592f3e3016f6c
[]
no_license
melikebatihan/Linked_lists
b3ca289d67e78f2f764b8de37c33ba42ea9c3d24
30b3eb90dc95ca5cc187779d2b234adc058b39e1
refs/heads/master
2022-05-12T23:02:52.602342
2020-01-28T19:28:45
2020-01-28T19:28:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
593
h
// // Created by mel on 28.01.2020. // #ifndef LINKED_LISTS_NODE_CLASS_H #define LINKED_LISTS_NODE_CLASS_H template <typename T> struct node { T data; // at class scope, variable templates need to be declared static. node *next; node *previous; }; template <typename T> class doubleLinkedList { public: node<T> *head = nullptr; node<T> *tail = nullptr; void addItem (T val); void print_list(); }; //template <typename T> //class doubleLinkedList { //public: // node<T> *head = nullptr; // node<T> *tail = nullptr; //}; #endif //LINKED_LISTS_NODE_CLASS_H
[ "ettzmra@gmail.com" ]
ettzmra@gmail.com
3f75b229d28870b76f7175a8524dcfb419f6e8ed
935927010571e2f820e70cead9a1fd471d88ea16
/Online Judge/Codeforces/Practice/Others/BGR1.cpp
cfaae63d9817829dfff8288def9bd9085b985aaf
[]
no_license
muhammadhasan01/cp
ebb0869b94c2a2ab9487861bd15a8e62083193ef
3b0152b9621c81190dd1a96dde0eb80bff284268
refs/heads/master
2023-05-30T07:18:02.094877
2023-05-21T22:03:57
2023-05-21T22:03:57
196,739,005
6
0
null
null
null
null
UTF-8
C++
false
false
1,014
cpp
#include<bits/stdc++.h> #define mp make_pair #define pb push_back #define pf push_front #define ff first #define ss second #define inf INT_MAX #define MOD 1000000007 #define forn(i,j,k) for(int i=(int)j;i<=(int)k;i++) #define nrof(i,j,k) for(int i=(int)j;i>=(int)k;i--) #define MEM(a,b) memset(a,(b),sizeof(a)) #define LEN(x) (int)x.size() #define all(x) x.begin(),x.end() #define ll long long #define ld long double #define pll pair<long long,long long> #define pii pair<int,int> using namespace std; int n,k; ll m, a[100003]; ll solve(){ if(n == 1)return 1; if(k == 1)return a[n]-a[1]+1; priority_queue<ll> pq; forn(i,1,n-1)pq.push(a[i+1]-a[i]); ll ans = a[n]-a[1]+1; int cnt = 0; while(!pq.empty() && cnt != k-1){ ans -= pq.top()-1; pq.pop(); cnt++; } return ans; } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n >> m >> k; forn(i,1,n)cin >> a[i]; cout << solve() << "\n"; return 0; }
[ "39514247+muhammadhasan01@users.noreply.github.com" ]
39514247+muhammadhasan01@users.noreply.github.com
a5df9d940991a389facf2ccc6e7ab1c7c06a1254
3be3af53137e686fbea7c9dc71d1e3fef522e5df
/divide_by_powers_of_2.cpp
5ace954b322c482d21263db7e558a785a77d30a9
[]
no_license
rishirajsurti/dsa_ee
0163677f76e19ce3130d26f3c1032fe3e95dd3cf
5f9628f20ff03ebb866570e0b0b55d86d1768448
refs/heads/master
2021-01-20T07:48:17.387483
2015-04-14T07:06:23
2015-04-14T07:06:23
30,142,771
0
0
null
null
null
null
UTF-8
C++
false
false
306
cpp
#include <iostream> using namespace std; long long int pow(int a ,int b); long long int pow(int a ,int b){ if(b==1) return a; else{ if(b%2 == 0) return pow(a,b/2)*pow(a,b/2); else return a*pow(a,b/2)*pow(a,b/2); } } int main(){ long long int a; a = pow(2,99) ; cout<<a<<endl; return 0; }
[ "rishirajsurti.iitm@gmail.com" ]
rishirajsurti.iitm@gmail.com
9d82b25893856e9fcaf640fc1d1f1ee08653c32a
2ecf807f4f70b98f4dd417af2834ab0843aabdf0
/src/engine/platform/implementations/openal.cpp
1ec8d215d330a0d7d0f377f296f5059f4666dd1f
[ "MIT" ]
permissive
shizgnit/application-template
b30d9256932f594ab9396199ad19470ca201497b
3257e7655ebf205ff6d8260cd98c8bb879437fce
refs/heads/develop
2023-04-28T05:21:31.530939
2023-04-23T17:16:38
2023-04-23T17:16:38
234,957,574
0
0
MIT
2023-03-01T02:29:51
2020-01-19T20:01:28
C++
UTF-8
C++
false
false
3,985
cpp
/* ================================================================================ Copyright (c) 2023, Pandemos All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the organization nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================================================ */ #include "engine.hpp" #if defined __PLATFORM_SUPPORTS_OPENAL void implementation::openal::audio::init(int sources) { ALCint attributes[] = { ALC_FREQUENCY, 44100, 0 }; ALCdevice* device = alcOpenDevice(NULL); ALCcontext* context = alcCreateContext(device, attributes); alcMakeContextCurrent(context); float orientation[6] = { 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f }; alListener3f(AL_POSITION, 0., 1.5, 0.); alListener3f(AL_VELOCITY, 0., 0., 0.); alListenerfv(AL_ORIENTATION, orientation); this->sources = sources; this->identifiers = (unsigned int*)malloc(this->sources * sizeof(unsigned int)); alGenSources(this->sources, this->identifiers); } void implementation::openal::audio::compile(type::sound& sound) { if (sound.resource == NULL) { sound.resource = new type::info::opaque_t(); } alGenBuffers(1, &sound.resource->context); alBufferData(sound.resource->context, AL_FORMAT_MONO16, sound.buffer.data(), sound.size, 44100); //alBufferData(sound.context, AL_FORMAT_MONO8, (const ALvoid *)sound.buffer.data(), sound.size, 11000); } void implementation::openal::audio::shutdown(void) { //alDeleteSources(1, &sound.source); //alDeleteBuffers(1, &sound.context); //alcDestroyContext(context); //alcCloseDevice(device); } int implementation::openal::audio::start(type::sound& sound) { unsigned int selection; for (selection = 0; selection < this->sources; selection++) { ALenum state; alGetSourcei(this->identifiers[selection], AL_SOURCE_STATE, &state); if (state != AL_PLAYING) { break; } } unsigned int id = this->identifiers[selection]; alSourcef(id, AL_PITCH, 1.0f); alSourcef(id, AL_GAIN, 1.0f); alSource3f(id, AL_POSITION, 0.0f, 0.0f, -1.0f); alSource3f(id, AL_VELOCITY, 0.0f, 0.0f, 0.0f); alSourcei(id, AL_LOOPING, AL_FALSE); alSourcei(id, AL_BUFFER, sound.resource->context); alSourcePlay(id); alSource3f(id, AL_POSITION, 0.0f, 0.0f, -1.0f); //alSource3f(id, AL_VELOCITY, 0.0f, 0.0f, -1.0f); return id; } void implementation::openal::audio::stop(int id) { alSourceStop(id); } #endif
[ "codeneko@gmail.com" ]
codeneko@gmail.com
7b103558ac11e1700a60834374c061d68c12cf2e
746618906be83256b273ff69c5908f6983a40fc5
/seal_texture.h
ca2c409a9ec7e47abb799fc93c88d59993005120
[ "BSD-2-Clause" ]
permissive
sealfin/C-and-C-Plus-Plus
7714459c71d9e12d2361ce9d226832e7b282aa55
d4c2c1383246d4b2cd08a5eb9f0f7594e4e8dfbb
refs/heads/master
2021-01-17T14:58:27.466295
2019-01-29T12:24:08
2019-01-29T12:24:08
10,107,929
0
0
null
null
null
null
UTF-8
C++
false
false
1,043
h
#ifndef seal_texture_h #define seal_texture_h #include "seal_quad_triangles.h" #include <stdlib.h> class seal_Texture { private: static seal_Texture *mg_bound; GLfloat m_textureMatrix[ 16 ]; GLuint m_texture; size_t m_subTextureWidth, m_subTextureHeight, m_numberOfSubTextures; seal_Quad_Triangles **m_subTextureQuads; public: seal_Texture( const char * const p_imagePath, const size_t p_subTextureWidth, const size_t p_subTextureHeight ); ~seal_Texture( void ); void p_Bind( void ); size_t f_NumberOfSubTextures( void ) { return m_numberOfSubTextures; } size_t f_SubTextureWidth( void ) { return m_subTextureWidth; } size_t f_SubTextureHeight( void ) { return m_subTextureHeight; } void p_GetSubTextureQuad( const size_t p_subTexture, seal_Quad_Triangles *p_subTextureQuad ); private: GLubyte *f_Pixels( const char * const p_imagePath, size_t *p_imageWidth, size_t *p_imageHeight ); bool f_IsPowerOfTwo( const size_t p ); }; #endif
[ "github.sealfin@sealfin.com" ]
github.sealfin@sealfin.com
2e3674dd698772bb77782ae3cae40ceeef7a62f2
aa6d4c6da3fc9393c93b6e43d0337e835e0caa7b
/examples/source/unique_ptr.cpp
7824907498f8460adac419b150ca1fdbc789fc31
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
flingengine/sol2
eb82df9fd27db040ba4b90018c2b252494980063
d7505df28e8eeaac69799a9426f858434b60acf4
refs/heads/develop
2022-12-04T00:04:27.710631
2020-08-13T02:32:51
2020-08-13T02:32:51
282,674,905
0
2
MIT
2020-08-13T02:32:52
2020-07-26T15:11:24
null
UTF-8
C++
false
false
2,511
cpp
#define SOL_ALL_SAFETIES_ON 1 #include <sol/sol.hpp> #include "assert.hpp" #include <iostream> struct my_type { int value = 10; my_type() { std::cout << "my_type at " << static_cast<void*>(this) << " being default constructed!" << std::endl; } my_type(const my_type& other) : value(other.value) { std::cout << "my_type at " << static_cast<void*>(this) << " being copy constructed!" << std::endl; } my_type(my_type&& other) : value(other.value) { std::cout << "my_type at " << static_cast<void*>(this) << " being move-constructed!" << std::endl; } my_type& operator=(const my_type& other) { value = other.value; std::cout << "my_type at " << static_cast<void*>(this) << " being copy-assigned to!" << std::endl; return *this; } my_type& operator=(my_type&& other) { value = other.value; std::cout << "my_type at " << static_cast<void*>(this) << " being move-assigned to!" << std::endl; return *this; } ~my_type() { std::cout << "my_type at " << static_cast<void*>(this) << " being destructed!" << std::endl; } }; int main() { std::cout << "=== unique_ptr support ===" << std::endl; sol::state lua; lua.new_usertype<my_type>("my_type", "value", &my_type::value ); { std::unique_ptr<my_type> unique = std::make_unique<my_type>(); lua["unique"] = std::move(unique); } { std::cout << "getting reference to unique_ptr..." << std::endl; std::unique_ptr<my_type>& ref_to_unique_ptr = lua["unique"]; my_type& ref_to_my_type = lua["unique"]; my_type* ptr_to_my_type = lua["unique"]; c_assert(ptr_to_my_type == ref_to_unique_ptr.get()); c_assert(&ref_to_my_type == ref_to_unique_ptr.get()); c_assert(ref_to_unique_ptr->value == 10); // script affects all of them equally lua.script("unique.value = 20"); c_assert(ptr_to_my_type->value == 20); c_assert(ref_to_my_type.value == 20); c_assert(ref_to_unique_ptr->value == 20); } { std::cout << "getting copy of unique_ptr..." << std::endl; my_type copy_of_value = lua["unique"]; c_assert(copy_of_value.value == 20); // script still affects pointer, but does not affect copy of `my_type` lua.script("unique.value = 30"); c_assert(copy_of_value.value == 20); } // set to nil and collect garbage to destroy it lua.script("unique = nil"); lua.collect_garbage(); lua.collect_garbage(); std::cout << "garbage has been collected" << std::endl; std::cout << std::endl; return 0; }
[ "phdofthehouse@gmail.com" ]
phdofthehouse@gmail.com
735d8c1a128520501ebcb257c5e547e65fe5fb88
29b91fafb820e5513c7284072dca5bd77c189b22
/dp/lcs-print.cpp
877996b7df5184b719a0ba7f8aff2412bbab63c1
[]
no_license
rishirajsurti/gfg
c1d542ebb59790d529be7be2a107a67f4fae2b35
f7205bec70c39e085bf8a45b527f7464c8bcef8e
refs/heads/master
2021-03-27T19:13:06.466708
2016-11-15T11:43:31
2016-11-15T11:43:31
61,434,826
0
0
null
null
null
null
UTF-8
C++
false
false
707
cpp
#include <bits/stdc++.h> using namespace std; int lcs(string s1, string s2){ int m = s1.length(), n = s2.length(); int L[m+1][n+1]; int i,j; string s=""; for(i=0; i<=m; i++) for(j=0; j<=n; j++) L[i][j] = 0; for(i=1; i<=m; i++){ for(j=1; j<=n; j++){ if(s1[i-1]==s2[j-1]) L[i][j] = 1 + L[i-1][j-1]; else L[i][j] = max(L[i-1][j], L[i][j-1]); } } i=m; j=n; while(i>=0 && j>=0){ if(s1[i]==s2[j]){ s = s1[i]+s; i--; j--; } else if(L[i-1][j] > L[i][j-1]){ // s = s1[i-1]+s; i--; } else{ // s = s1[i]+s; j--; } } cout<<s<<endl; return L[m][n]; } int main(){ string s1, s2; s1 = "AGGTAB"; s2 = "GXTXAYB"; printf("Length of LCS = %d\n", lcs(s1, s2)); }
[ "rishirajsurti.iitm@gmail.com" ]
rishirajsurti.iitm@gmail.com
88f256dad358713b3eff3b70f37dbe4337249257
771f413024868ca431f95b06884c91bff34a6ce4
/linked_list/odd_even_linked_list.cpp
4830c61ee85cff11602bcc2d406d85cc11d163d0
[]
no_license
invrev/fft
eee6258f20f70576501c4465dd41123b7b326514
e4e2f279f5a4156202d19519c1a7d4b4586219c3
refs/heads/master
2020-06-14T12:23:57.283918
2016-11-28T23:56:03
2016-11-28T23:56:03
75,024,923
0
0
null
null
null
null
UTF-8
C++
false
false
1,750
cpp
//Odd Even Linked List // //Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes. // //You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity. // //Example: //Given 1->2->3->4->5->NULL, //return 1->3->5->2->4->NULL. // //Note: //The relative order inside both the even and odd groups should remain as it was in the input. //The first node is considered odd, the second node even and so on ... #include<iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; //NOTE : modify head pointer ListNode* oddEvenList(ListNode* head) { if(!head) { //cout << "No element found" << "\t" ; return head; } ListNode* oddList = head; ListNode* evenList = head->next; ListNode* tmpEvenList = evenList ; while(oddList && oddList->next) { //cout << head->val << "\t" ; oddList->next = oddList->next->next; evenList->next = evenList->next->next; oddList = oddList->next; evenList = evenList->next; } //evenList->next = NULL; // PLEASE NOTE : NULL is part of HEAD list oddList->next = tmpEvenList; return head; } int main() { //1->2->3->4->5->NULL, ListNode *head = new ListNode(1); head->next = new ListNode(2); head->next->next = new ListNode(3); head->next->next->next = new ListNode(4); head->next->next->next->next = new ListNode(5); cout << "cALL " << endl; ListNode *result = oddEvenList(head); cout << "after cALL " << endl; while(result != NULL) { cout << result->val << " "; result = result->next; } cout << endl; }
[ "vikram@vikram-VirtualBox.(none)" ]
vikram@vikram-VirtualBox.(none)
0aee04e90b2700f8aefff385819c92b4547ce51c
4ce30649e0bc2acc9c5d7bb2208dc068565c5c1d
/Recursion/Remove Duplicates from Sorted Array-26/Remove Duplicates from Sorted Array-26/main.cpp
5f9d617f6999b322450d395b38c9833e7504ad9b
[]
no_license
Kewin66/Data-Structures-And-Algorithms
1dc10358f0f995a550c12b2d679271e897fccaa7
861480631f22f4aa7935202229a8e088abc185af
refs/heads/main
2023-08-07T11:04:14.890947
2021-09-10T19:48:25
2021-09-10T19:48:25
383,228,633
0
0
null
null
null
null
UTF-8
C++
false
false
1,026
cpp
// // main.cpp // Remove Duplicates from Sorted Array-26 // // Created by Kewin Srinath on 7/26/21. // #include <iostream> #include <vector> using namespace std; int removeDuplicates(vector<int>& nums) { int left = 0, right = 1, count = 0; if(nums.size()) count++; else if(nums.size() == 1) return 1; else return 0; int k = 1; while(right<nums.size()) { if(nums[left] == nums[right]) {right++; continue; } else { count++; nums[k] = nums[right]; k++; left = right; right+=1; } } return count; } int main(int argc, const char * argv[]) { // insert code here... vector<int> a = {0,0,0,0}; int k = removeDuplicates(a); for(int i = 0; i< k; i ++) { cout<<a[i]<<" "; } return 0; }
[ "kewindev96@gmail.com" ]
kewindev96@gmail.com
fedd1503d265e82092927d2fc1c5648e7ec93a4d
b20353e26e471ed53a391ee02ea616305a63bbb0
/trunk/engine/sdk/inc/CTraitsClient.h
bd8210781b36fe7277b6d10d6e6170b7d0a9eb3e
[]
no_license
trancx/ybtx
61de88ef4b2f577e486aba09c9b5b014a8399732
608db61c1b5e110785639d560351269c1444e4c4
refs/heads/master
2022-12-17T05:53:50.650153
2020-09-19T12:10:09
2020-09-19T12:10:09
291,492,104
0
0
null
2020-08-30T15:00:16
2020-08-30T15:00:15
null
UTF-8
C++
false
false
1,410
h
#pragma once namespace sqr { #define USE_RENDER_SLOT class CAppClient; class IAppClientHandler; class CAppConfigClient; class CTimeSystemClient; class CConnClient; class CMetaSceneClient; class CMetaSceneMgrClient; class CObjMoveStateClient; class CCoreObjectClient; class CCoreSceneClient; class CCoreSceneMgrClient; class ICoreObjectClientHandler; class CConnMgrClient; class IConnMgrClientHandler; #ifdef USE_RENDER_SLOT class CRenderSlot; #else class CDistortedTick; #endif class CTraitsClient { public: typedef CAppClient App_t; typedef IAppClientHandler AppHandler_t; typedef CAppConfigClient AppConfig_t; typedef CTimeSystemClient TimeSystem_t; typedef CConnClient Conn_t; typedef CMetaSceneClient MetaScene_t; typedef CMetaSceneMgrClient MetaSceneMgr_t; typedef CCoreObjectClient CoreObject_t; typedef CObjMoveStateClient ObjMoveState_t; typedef CCoreSceneClient CoreScene_t; typedef CCoreSceneMgrClient CoreSceneMgr_t; typedef ICoreObjectClientHandler CoreObjectHandler_t; typedef CConnMgrClient ConnMgr_t; typedef IConnMgrClientHandler ConnMgrHandler_t; typedef CConnClient ConcreteConn_t; #ifdef USE_RENDER_SLOT typedef CRenderSlot Tick_t; #else typedef CDistortedTick Tick_t; #endif static uint32 GetObjectMoveCyc(); }; }
[ "CoolManBob@a2c23ad7-41ce-4a1d-83b7-33535e6483ee" ]
CoolManBob@a2c23ad7-41ce-4a1d-83b7-33535e6483ee
b54de7c1b49504acc113f14801e6670c4e4e4242
d3d801889d1be5cfa9ac41496b57dd3ec80dc5cd
/src/rpc_server/center_cluster_heartbeat.cpp
3c12ffea502437af32cad499c5f5ac9d2fa0a380
[]
no_license
zhaoruixbj/libevrpc
8dc02a8e777a759a33431ebf791e29ba49ed1a69
d8473f1f27fcf04e4387f476fde04e2ac4343b67
refs/heads/master
2021-01-22T03:23:05.766226
2017-02-20T16:45:57
2017-02-20T16:45:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,184
cpp
/*************************************************************************** * * Copyright (c) 2016 aishuyu, Inc. All Rights Reserved * **************************************************************************/ /** * @file center_cluster_heartbeat.cpp * @author aishuyu(asy5178@163.com) * @date 2016/09/07 19:44:39 * @brief * **/ #include "center_cluster_heartbeat.h" #include <unistd.h> #include <time.h> #include <fstream> #include <iostream> #include <stdlib.h> #include <sys/sysinfo.h> #include <linux/kernel.h> #include <google/protobuf/repeated_field.h> #include "center_proto/center_cluster.pb.h" #include "config_parser/config_parser.h" #include "util/rpc_communication.h" #include "util/rpc_util.h" #define random(x) (rand()%x) namespace libevrpc { using ::google::protobuf::RepeatedPtrField; using std::string; const int32_t sleep_time = 10; CenterClusterHeartbeat::CenterClusterHeartbeat(const string& config_file) : config_file_(config_file), center_addrs_ptr_(new ADDRS_LIST_TYPE()), reporter_center_addrs_ptr_(new ADDRS_LIST_TYPE()), running_(false), center_port_(NULL) { } CenterClusterHeartbeat::~CenterClusterHeartbeat() { if (NULL != center_addrs_ptr_) { delete center_addrs_ptr_; } if (NULL != reporter_center_addrs_ptr_) { delete reporter_center_addrs_ptr_; } if (NULL != center_port_) { free(center_port_); } } bool CenterClusterHeartbeat::InitCenterClusterHB() { const string cfile = "/tmp/centers.data"; int ftyp = access(cfile.c_str(), 0); if (0 != ftyp) { /* * 需要的服务器列表文件不存在,无法初始化后与其他机器进行通信 * 启动失败!!! */ return false; } const char* center_port = ConfigParser::GetInstance(config_file_).IniGetString("rpc_center:port", "8899"); strcpy(center_port_ = (char*)malloc(strlen(center_port) + 1), center_port); std::ifstream in(cfile); string line; const char* local_addr = GetLocalAddress(); while (getline (in, line)) { if (strcmp(line.c_str(), local_addr) == 0) { continue; } center_addrs_ptr_->push_back(line); } int32_t random_index = random(center_addrs_ptr_->size()); int32_t conn_fd = TcpConnect(center_addrs_ptr_->at(random_index).c_str(), center_port_, 15); if (conn_fd <= 0) { return false; } /* * 在RpcCenter注册本地RpcServer, 获取Report机器地址 */ RpcClusterServer rcs; rcs.set_cluster_action(REGISTER); rcs.set_cluster_server_addr(local_addr); string rcs_str; if (!rcs.SerializeToString(&rcs_str)) { close(conn_fd); return false; } if (!RpcSend(conn_fd, CENTER2CLUSTER, rcs_str, false)) { close(conn_fd); return false; } string crc_str; if (!RpcRecv(conn_fd, crc_str, true) < 0) { close(conn_fd); return false; } CenterResponseCluster crc_proto; if (!crc_proto.ParseFromString(crc_str)) { close(conn_fd); return false; } RepeatedPtrField<string>* reporter_centers = crc_proto.mutable_should_reporter_center(); for (RepeatedPtrField<string>::iterator iter = reporter_centers->begin(); iter != reporter_centers->end(); ++iter) { reporter_center_addrs_ptr_->push_back(std::move(*iter)); } running_ = true; return true; } void CenterClusterHeartbeat::Run() { int32_t rca_size = reporter_center_addrs_ptr_->size(); if (0 == rca_size || !InitCenterClusterHB()) { fprintf(stderr, "Center Init HeartBeat failed!\n"); return; } int32_t random_index = random(rca_size); int32_t should_reinit = ConfigParser::GetInstance(config_file_).IniGetInt("rpc_center:should_reinit", 10); int32_t reinit_cnt = 0; while (running_) { /** * 获取本地机器信息 CPU LOAD1等 */ struct sysinfo s_info; int32_t error_no = sysinfo(&s_info); if (error_no < 0) { /* * 获取本地机器信息失败 */ continue; } int32_t conn_fd = TcpConnect(reporter_center_addrs_ptr_->at(random_index).c_str(), center_port_, 15); if (conn_fd < 0) { ++reinit_cnt; if (reinit_cnt > should_reinit) { reinit_cnt = 0; InitCenterClusterHB(); } random_index = random(rca_size); sleep(sleep_time); continue; } RpcClusterServer rcs_proto; rcs_proto.set_cluster_action(CLUSTER_PING); rcs_proto.set_cluster_server_addr(GetLocalAddress()); rcs_proto.set_load(s_info.loads[0]); string rcs_str; if (!rcs_proto.SerializeToString(&rcs_str)) { close(conn_fd); continue; } if (!RpcSend(conn_fd, CENTER2CLUSTER, rcs_str)) { fprintf(stderr, "Send info to Center failed!\n"); } close(conn_fd); } } } // end of namespace libevrpc /* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */
[ "asy5178@163.com" ]
asy5178@163.com
bc09e6ac90a8343f966bfa7ee0864a8cb0bf53be
dd6147bf9433298a64bbceb7fdccaa4cc477fba6
/8382/Mironchik_Pavel/lr3/include/GAME/engine/behaviour/BaseUnitMoveBehaviour.hpp
1e0bd4d349579bfef062fb254f7a356369726613
[]
no_license
moevm/oop
64a89677879341a3e8e91ba6d719ab598dcabb49
faffa7e14003b13c658ccf8853d6189b51ee30e6
refs/heads/master
2023-03-16T15:48:35.226647
2020-06-08T16:16:31
2020-06-08T16:16:31
85,785,460
42
304
null
2023-03-06T23:46:08
2017-03-22T04:37:01
C++
UTF-8
C++
false
false
409
hpp
#pragma once #include <GAME/engine/behaviour/UnitMoveBehaviour.hpp> #include <GAME/utils/PathSearcher.hpp> #include <GAME/utils/VectorsSet.hpp> class BaseUnitMoveBehaviour : public UnitMoveBehaviour { private: VectorsSet<int> _availableCells; public: virtual void computeAvailableCells() override; virtual VectorsSet<int>& availableCells() override; virtual bool move(sf::Vector2i &toCell) override; };
[ "mairon-pasha@yandex.ru" ]
mairon-pasha@yandex.ru
77170eb7b7a65673c55ec830e1f80dc17ada19b1
0fb769ec9885dfa78ab0f1cb87ea5223f7aab75a
/reacteur.cpp
88cf0dcbb5862c3077485f53ea6f9290444e69b8
[]
no_license
GuilaDIA/projetC-
18db3e6fbef471b29ee0287ed3f45e8231b620c9
acf91c6dba44b67b02834d4d4ab16b31af1f3120
refs/heads/master
2023-03-27T20:15:35.934081
2021-03-25T15:26:29
2021-03-25T15:26:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,785
cpp
#include "reacteur.h" #include "circuitprimaire.h" #include <algorithm> #include "time.h" #include <stdio> #include <cstdlib> using namespace std; reacteur::reacteur() { Proportion_bar_graphi_hors_demandé=0.; Proportion_actuelle_bar_hors_demandé=0.; taux_bore_demande=0.47; taux_bore_actuel =0.47; etat_cuve=1.; radiation_piscine=0.; etat_piscine=1.; etat_barres_graphites=1.; etat_canaux =1.; etat_injecteur_bore = 1.; } double reacteur::get_Proportion_bar_graphi_hors_demandé() const { return Proportion_bar_graphi_hors_demandé; } double reacteur::get_Proportion_actuelle_bar_hors_demandé() const { return Proportion_actuelle_bar_hors_demandé; } double reacteur::get_taux_bore_demande() const { return taux_bore_demande; } double reacteur::get_taux_bore_actuel() const { return taux_bore_actuel; } double reacteur::get_etat_cuve() const { return etat_cuve; } double reacteur::get_radiation_piscine() const { return radiation_piscine; } double reacteur::get_etat_piscine() const { return etat_piscine; } double reacteur::get_etat_barres_graphites() const { return etat_barres_graphites; } double reacteur::get_etat_canaux() const { return etat_canaux; } double reacteur::get_etat_injecteur_bore() const { return etat_injecteur_bore; } void reacteur::set_Proportion_barres() { Proportion_actuelle_bar_hors_demandé= get_Proportion_bar_graphi_hors_demandé(); Proportion_bar_graphi_hors_demandé = (1-get_etat_barres_graphites())*100; } void reacteur::set_taux_bore(double taux_bore) { taux_bore_actuel = get_taux_bore_demande(); if (0<= taux_bore and taux_bore<=0.5) taux_bore_demande = taux_bore; } void reacteur::set_etat_cuve(circuit_prim &c) { srand(time(nullptr)); if (c.get_tempeaucircuit()>=50) { if (0.3<c.get_etat_circuit() and c.get_etat_circuit()<0.6) { if (rand()/RAND_MAX < 0.4) etat_cuve = get_etat_cuve()-rand(0.02); } else if (0.2<c.get_etat_circuit() and c.get_etat_circuit()<0.3) { if (rand()/RAND_MAX < 0.4) etat_cuve = get_etat_cuve()-rand(0.03); } else if (c.get_etat_circuit()<0.2) { if (rand()/RAND_MAX < 0.4) etat_cuve = get_etat_cuve()-rand(0.06); } } else etat_cuve = get_etat_cuve(); } void reacteur::set_radiation_piscine(circuit_prim &c) { radiation_piscine = (1-get_etat_cuve())*c.get_radioactivité() + 100 + rand(45); } void reacteur::set_etat_piscine(double e_piscine) { if (c.get_tempeaucircuit()>=50 and c.get_etat_circuit()<0.2) { if (rand()/RAND_MAX < 0.8) etat_piscine = get_etat_piscine()-rand(0.06); } else etat_piscine = get_etat_piscine(); } void reacteur::set_etat_barres_graphites(circuit_prim &c) { if (c.get_tempeaucircuit() >= 50 and get_Proportion_actuelle_bar_hors_demandé() >0.4)) { if (0.6<get_etat_cuve() and get_etat_cuve()<0.7) { if (rand()/RAND_MAX < 0.4) etat_barres_graphites = get_etat_barres_graphites()-rand(0.03); } else if (get_etat_cuve()<0.6) { if (rand()/RAND_MAX < 0.3) etat_barres_graphites = get_etat_barres_graphites()-rand(0.02); } } else etat_barres_graphites = get_etat_barres_graphites(); } void reacteur::set_etat_cannaux(circuit_prim &c) { if (c.get_tempeaucircuit()>=50 and c.geteatechaneur()<0.5) { if (rand()/RAND_MAX < 0.5) etat_canaux = get_etat_canaux()-rand(0.05); } else etat_canaux = get_etat_canaux(); } void reacteur::set_etat_injecteur_bore(circuit_prim &c) { if (c.get_tempeaucircuit()>=50 and (get_etat_cuve()<0.5 and c.get_etat_circuit()<0.5)) { if (rand()/RAND_MAX < 0.5) etat_injecteur_bore = get_etat_injecteur_bore()-rand(0.02); } else etat_injecteur_bore = get_etat_injecteur_bore(); }
[ "kennethbboy3@gmail.com" ]
kennethbboy3@gmail.com
205ebbc38d1282b7b6d31c7f211af861175a8960
ce85e74d28ef5906570749ed7f41fc052af701d2
/MungusEngine/stdafx.h
f9d47df9e880ec7d37f244f25d74db5b3dcd3f92
[]
no_license
Gigamungus/MungusEngine
514b8a887c2233b62498cd15088daa7bc9ef4e15
3cdfbe79672d2a162263516223ae6b0ea5179168
refs/heads/master
2020-04-14T09:17:56.821573
2019-02-24T06:18:11
2019-02-24T06:19:06
163,756,700
1
0
null
null
null
null
UTF-8
C++
false
false
632
h
#pragma once #pragma warning(disable:4251) #include "Core.h" #include "../Resources/OpenGL/GLEW/include/GL/glew.h" #include "../Resources/OpenGL/GLFW/include/GLFW/glfw3.h" #include "../Resources/Vendor/JSON/json.hpp" using json = nlohmann::json; #include "../Resources/MungusLibs/MungusMath.h" #include "../Resources/MungusLibs/MungusUtil.h" #include <iostream> #include <string> #include <sstream> #include <filesystem> #include <fstream> #include <vector> #include <unordered_map> #include <unordered_set> #include <stack> #include <queue> #include <memory> #include <chrono> #include <functional> #include <algorithm>
[ "that4wkwardguy@gmail.com" ]
that4wkwardguy@gmail.com
40374f3ab8a45f669817e01f2b406c1e35a97569
2cef75fd883b6fb5bcea827f215bf78b91007cb2
/catkin_ws/install/include/rosserial_mbed/TestRequest.h
aafec8efdf1c6466103ab685ce6d8592b0b5b198
[]
no_license
yorkurt/ros-OLD
925b757fac35ed44afe74c1cddfba70591576e50
a4ba0dd0842147d50383cdf1cb3f3f2db0b3fe08
refs/heads/master
2020-04-03T13:15:13.062258
2018-11-05T22:26:32
2018-11-05T22:26:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,086
h
// Generated by gencpp from file rosserial_mbed/TestRequest.msg // DO NOT EDIT! #ifndef ROSSERIAL_MBED_MESSAGE_TESTREQUEST_H #define ROSSERIAL_MBED_MESSAGE_TESTREQUEST_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> namespace rosserial_mbed { template <class ContainerAllocator> struct TestRequest_ { typedef TestRequest_<ContainerAllocator> Type; TestRequest_() : input() { } TestRequest_(const ContainerAllocator& _alloc) : input(_alloc) { (void)_alloc; } typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _input_type; _input_type input; typedef boost::shared_ptr< ::rosserial_mbed::TestRequest_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::rosserial_mbed::TestRequest_<ContainerAllocator> const> ConstPtr; }; // struct TestRequest_ typedef ::rosserial_mbed::TestRequest_<std::allocator<void> > TestRequest; typedef boost::shared_ptr< ::rosserial_mbed::TestRequest > TestRequestPtr; typedef boost::shared_ptr< ::rosserial_mbed::TestRequest const> TestRequestConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::rosserial_mbed::TestRequest_<ContainerAllocator> & v) { ros::message_operations::Printer< ::rosserial_mbed::TestRequest_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace rosserial_mbed namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False} // {'rosserial_mbed': ['/home/yurt/catkin_ws/src/rosserial/rosserial_mbed/msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::rosserial_mbed::TestRequest_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::rosserial_mbed::TestRequest_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::rosserial_mbed::TestRequest_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::rosserial_mbed::TestRequest_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::rosserial_mbed::TestRequest_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::rosserial_mbed::TestRequest_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::rosserial_mbed::TestRequest_<ContainerAllocator> > { static const char* value() { return "39e92f1778057359c64c7b8a7d7b19de"; } static const char* value(const ::rosserial_mbed::TestRequest_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x39e92f1778057359ULL; static const uint64_t static_value2 = 0xc64c7b8a7d7b19deULL; }; template<class ContainerAllocator> struct DataType< ::rosserial_mbed::TestRequest_<ContainerAllocator> > { static const char* value() { return "rosserial_mbed/TestRequest"; } static const char* value(const ::rosserial_mbed::TestRequest_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::rosserial_mbed::TestRequest_<ContainerAllocator> > { static const char* value() { return "string input\n\ "; } static const char* value(const ::rosserial_mbed::TestRequest_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::rosserial_mbed::TestRequest_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.input); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct TestRequest_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::rosserial_mbed::TestRequest_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::rosserial_mbed::TestRequest_<ContainerAllocator>& v) { s << indent << "input: "; Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.input); } }; } // namespace message_operations } // namespace ros #endif // ROSSERIAL_MBED_MESSAGE_TESTREQUEST_H
[ "ajs0429@my.yorku.ca" ]
ajs0429@my.yorku.ca
877c968b76a2a631e8d1f3ab97b61388decd806e
dfe071ef5c3df984aed4b13278c29b2dfe4dcf46
/Classes/graph/GraphMatrix.h
dbd615a93ea41cc70952fdaeee2327c6081219da
[]
no_license
Crasader/CrazySnow
4f1612a64d8502aa63513270323e76c4c6a5ad82
aacdcbce694603456630658b859dc7fa0c336bfc
refs/heads/master
2020-11-29T10:45:56.579622
2015-09-30T04:18:17
2015-09-30T04:18:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,475
h
// // ConnGraph.h // proj.ios // // Created by root911 on 14-5-12. // Copyright (c) 2014年 OneClick Co.,Ltd. All rights reserved. // #pragma once #include "GraphCommDef.h" #include "GraphTool.h" #include "GraphNode.h" #include "IElemPaddingStragy.h" class GraphMat { public: GraphMat(); ~GraphMat(); void buildGraph(const GraphData* cfg); bool check_bdy(Point2i pt) const { return m_graph_vis.check_bdy(pt); } bool check_bdy_enable(Point2i pt) const { return m_graph_vis.check_bdy(pt) && get_node(pt)->isEnable(); } bool isNodeLocked(Point2i pt) const { return get_node(pt)->getAttrib().bLock; } void setNodeLocked(Point2i pt, bool bLock); void setAllNodeLocked(bool bLock); GraphNode* get_node(Point2i pt) const { assert(check_bdy(pt)); return vertex[pt.y][pt.x]; } NodeCategory get_nodeCatg(Point2i pt) const { return get_node(pt)->get_category(); } void set_node(Point2i pt, const GraphAttrib& node_attrib); void create_node(Point2i pt, NodeCategory category); void erase_node(Point2i pt); void swap_node(Point2i pt1, Point2i pt2); void dump(); void getColorSeq(const std::vector<Point2i>& ptSeq, std::vector<enNodeColor>& colorSeq); void getEnblSeq(std::vector<Point2i>& ptSeq); void serilize(GraphData& iniData); public: GraphDistance m_distance; CoordConvert m_coordCvt; GraphNodeVisitorGraph m_graph_vis; int m_rows; int m_cols; int m_max_category_num; private: GraphNode* vertex[MAX_VERTEX_ROWS][MAX_VERTEX_COLS]; };
[ "652440522@qq.com" ]
652440522@qq.com
a597f25766dadbd3713e5fa23d132654fea30740
011919b17c3ab675aae6bf1e61e04b44476a97ec
/include/cppyplot.hpp
f61e230f5babd53b04372a0a670c3bed01b952ef
[]
no_license
VamosCC/cpp-pyplot
1401d2b7d2601647a891653ef7719d7edf477f58
b3d1b54e5ac083583ed6c51a8a5a8b3a52daab85
refs/heads/master
2023-08-14T17:59:51.923471
2021-09-19T03:29:28
2021-09-19T03:29:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,270
hpp
#ifndef _CPPYPLOT_ #define _CPPYPLOT_ /* References * python struct: https://docs.python.org/3/library/struct.html * python asteval: https://newville.github.io/asteval/api.html#asteval-api * cpp cppzmq: https://brettviren.github.io/cppzmq-tour/ */ #include <string> #include <vector> #include <map> #include <iostream> #include <numeric> #include <zmq.hpp> #include <zmq_addon.hpp> #include <cstdlib> #include <thread> #include <chrono> #include <utility> #include <filesystem> // Eigen #if __has_include(<Eigen/Core>) #include <Eigen/Core> #define EIGEN_AVAILABLE #elif __has_include (<Eigen/Eigen/Core>) #include <Eigen/Eigen/Core> #define EIGEN_AVAILABLE #endif using namespace std::chrono_literals; using namespace std::string_literals; #define PYTHON_PATH "C:/Anaconda3/python.exe" #define HOST_ADDR "tcp://127.0.0.1:5555" template <std::size_t ... indices> decltype(auto) build_string(const char * str, std::index_sequence<indices...>) { return std::string{str[indices]...}; } template <std::size_t N> constexpr decltype(auto) compile_time_str(const char(&str)[N]) { return build_string(str, std::make_index_sequence<N-1>()); } #define STRINGIFY(X) (#X) #define DATA_PAIR(X) std::make_pair(compile_time_str(STRINGIFY(X)), std::ref(X)) #define _p(X) DATA_PAIR(X) namespace Cppyplot { // utility function for raw string literal parsing std::string dedent_string(const std::string_view raw_str); template<typename T> std::string shape_str(const T& shape); #include "cppyplot_types.h" #include "cppyplot_container_support.h" class cppyplot{ private: static zmq::context_t context_; static zmq::socket_t socket_; static bool is_zmq_established_; static std::string python_path_; static std::string zmq_ip_addr_; std::stringstream plot_cmds_; public: cppyplot() { if (cppyplot::is_zmq_established_ == false) { cppyplot::socket_.bind(cppyplot::zmq_ip_addr_); std::this_thread::sleep_for(100ms); std::filesystem::path path(__FILE__); std::string server_file_spawn; #if defined(_WIN32) || defined(_WIN64) server_file_spawn.append("start /min "s); #endif server_file_spawn.append(cppyplot::python_path_); server_file_spawn += " "s; server_file_spawn += path.parent_path().string(); server_file_spawn += "/cppyplot_server.py "s; server_file_spawn.append(cppyplot::zmq_ip_addr_); #if defined(__unix__) server_file_spawn += " &"s; #endif std::system(server_file_spawn.c_str()); std::this_thread::sleep_for(3.0s); cppyplot::is_zmq_established_ = true; std::atexit(zmq_kill_command); } } cppyplot(cppyplot& other) = delete; cppyplot operator=(cppyplot& other) = delete; ~cppyplot() {} static void set_python_path(const std::string& python_path) noexcept { cppyplot::python_path_ = python_path; } static void set_host_ip(const std::string& host_ip) noexcept { cppyplot::zmq_ip_addr_ = host_ip; } static void zmq_kill_command() { if (cppyplot::is_zmq_established_ == true) { // if the python server is spawned through this class instance, then send exit command zmq::message_t exit_msg("exit", 4); cppyplot::socket_.send(exit_msg, zmq::send_flags::none); cppyplot::is_zmq_established_ = false; cppyplot::socket_.disconnect(cppyplot::zmq_ip_addr_); } } inline void push(const std::string& cmds) { plot_cmds_ << cmds << '\n'; } inline void operator<<(const std::string& cmds) { this->push(cmds); } template<unsigned int N> void raw(const char (&input_cmds)[N]) noexcept { plot_cmds_ << dedent_string(input_cmds); } template<unsigned int N, typename... Val_t> void raw(const char (&input_cmds)[N], std::pair<std::string, Val_t>&&... args) { plot_cmds_ << dedent_string(input_cmds); data_args(std::forward<std::pair<std::string, Val_t>>(args)...); } template<unsigned int N> void raw_nowait(const char (&input_cmds)[N]) { plot_cmds_ << dedent_string(input_cmds); zmq::message_t cmds(plot_cmds_.str()); cppyplot::socket_.send(cmds, zmq::send_flags::none); zmq::message_t final("finalize", 8); cppyplot::socket_.send(final, zmq::send_flags::none); /* reset */ plot_cmds_.str(""); } template<typename T> inline std::string create_header(const std::string& key, const T& cont) noexcept { auto elem_type = unpack_type<T>(); std::string header{"data|"}; // variable name header += key; header.append("|"); // container element type (float or int or ...) header += std::string{elem_type.typestr}; header.append("|"); // total number of elements in the container header += std::to_string(container_size(cont)); header.append("|"); // shape of the container header += shape_str(container_shape(cont)); return header; } template <typename T> void send_container(const std::string& key, const T& cont) { std::string data_header{create_header(key, cont)}; zmq::message_t msg(data_header.c_str(), data_header.length()); cppyplot::socket_.send(msg, zmq::send_flags::none); zmq::message_t payload; fill_zmq_buffer(cont, payload); cppyplot::socket_.send(payload, zmq::send_flags::none); } template<typename... Val_t> void data_args(std::pair<std::string, Val_t>&&... args) { zmq::message_t cmds(plot_cmds_.str()); cppyplot::socket_.send(cmds, zmq::send_flags::none); (send_container(args.first, args.second), ...); std::this_thread::sleep_for(5ms); // small delay which helps in eliminating packet loss zmq::message_t final("finalize", 8); cppyplot::socket_.send(final, zmq::send_flags::none); /* reset */ plot_cmds_.str(""); } }; // initialize static variables zmq::context_t cppyplot::context_ = zmq::context_t(1); zmq::socket_t cppyplot::socket_ = zmq::socket_t(cppyplot::context_, ZMQ_PUB); bool cppyplot::is_zmq_established_ = false; std::string cppyplot::python_path_{PYTHON_PATH}; std::string cppyplot::zmq_ip_addr_{HOST_ADDR}; // utility functions auto non_empty_line_idx(const std::string_view in_str) { int new_line_pos = -1; unsigned int num_spaces = 0u; for (unsigned int i = 0u; i < in_str.length(); i++) { if (in_str[i] == '\n') { new_line_pos = i; num_spaces = 0u; } else if ( (in_str[i] != ' ' ) && (in_str[i] != '\t')) { break; } else { num_spaces ++; } } return std::make_tuple(new_line_pos+1, num_spaces); } std::string dedent_string(const std::string_view raw_str) { auto [occupied_line_start, num_spaces] = non_empty_line_idx(raw_str); if (num_spaces == 0u) { return std::string(raw_str); } else { std::string out_str; out_str.reserve(raw_str.length()); int line_start = -1; bool process_spaces = true; int cur_space_count = 0; for (unsigned int i = static_cast<unsigned int>(occupied_line_start); i < raw_str.length(); i++) { if (process_spaces == true) { if (raw_str[i] == '\n') { process_spaces = true; line_start = -1; cur_space_count = 0; } else if ((raw_str[i] != ' ') && (raw_str[i] != '\t')) { process_spaces = false; line_start = i; } else { cur_space_count++; } } else if (raw_str[i] == '\n') { if (line_start != -1) { line_start -= (cur_space_count - num_spaces); out_str.append(raw_str.substr(line_start, i - line_start + 1u)); } process_spaces = true; line_start = -1; cur_space_count = 0; } } return out_str; } } template<typename T> std::string shape_str(const T& shape) { std::stringstream out_str; out_str << '('; for (auto size : shape) { out_str << size << ','; } out_str << ')'; return out_str.str(); } } #endif
[ "muralivnv@gmail.com" ]
muralivnv@gmail.com
34c6f41bc8f4d2950b82ba3da9d1a89dc52e96fa
4780fda8dd680f47293acde35f82c22e177619d4
/ext/intl/timezone/timezone_methods.cpp
eaa6b46e3940b2868ed9442ba4d2cdee1529c2ae
[ "PHP-3.01", "BSD-3-Clause", "BSD-4-Clause-UC", "Zlib", "ISC", "LicenseRef-scancode-other-permissive", "TCL", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "JSON", "LicenseRef-scancode-pcre", "blessing" ]
permissive
mageekguy/php-src
e6bc38343ea9d3ed24212d8ede129e589bfb15cc
904ca2f0b3fd8d15e3742d1bb16eb272e1c9e279
refs/heads/master
2022-05-05T00:16:51.576054
2012-04-18T22:30:58
2012-04-18T22:30:58
4,073,308
0
0
NOASSERTION
2023-01-17T17:38:38
2012-04-19T08:44:09
C
UTF-8
C++
false
false
17,714
cpp
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Gustavo Lopes <cataphract@php.net> | +----------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <unicode/locid.h> #include <unicode/timezone.h> #include <unicode/ustring.h> #include "intl_convertcpp.h" extern "C" { #define USE_TIMEZONE_POINTER 1 #include "timezone_class.h" #include "intl_convert.h" #include "../locale/locale.h" #include <zend_exceptions.h> } #include "common/common_enum.h" U_CFUNC PHP_FUNCTION(intltz_create_time_zone) { char *str_id; int str_id_len; intl_error_reset(NULL TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &str_id, &str_id_len) == FAILURE) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "intltz_create_time_zone: bad arguments", 0 TSRMLS_CC); RETURN_NULL(); } UErrorCode status = UErrorCode(); UnicodeString id = UnicodeString(); if (intl_stringFromChar(id, str_id, str_id_len, &status) == FAILURE) { intl_error_set(NULL, status, "intltz_create_time_zone: could not convert time zone id to UTF-16", 0 TSRMLS_CC); RETURN_NULL(); } //guaranteed non-null; GMT if timezone cannot be understood TimeZone *tz = TimeZone::createTimeZone(id); timezone_object_construct(tz, return_value, 1 TSRMLS_CC); } U_CFUNC PHP_FUNCTION(intltz_create_default) { intl_error_reset(NULL TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "intltz_create_default: bad arguments", 0 TSRMLS_CC); RETURN_NULL(); } TimeZone *tz = TimeZone::createDefault(); timezone_object_construct(tz, return_value, 1 TSRMLS_CC); } U_CFUNC PHP_FUNCTION(intltz_get_gmt) { intl_error_reset(NULL TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "intltz_get_gmt: bad arguments", 0 TSRMLS_CC); RETURN_NULL(); } timezone_object_construct(TimeZone::getGMT(), return_value, 0 TSRMLS_CC); } #if U_ICU_VERSION_MAJOR_NUM >= 49 U_CFUNC PHP_FUNCTION(intltz_get_unknown) { intl_error_reset(NULL TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "intltz_get_unknown: bad arguments", 0 TSRMLS_CC); RETURN_NULL(); } timezone_object_construct(&TimeZone::getUnknown(), return_value, 0 TSRMLS_CC); } #endif U_CFUNC PHP_FUNCTION(intltz_create_enumeration) { zval **arg = NULL; StringEnumeration *se = NULL; intl_error_reset(NULL TSRMLS_CC); /* double indirection to have the zend engine destroy the new zval that * results from separation */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|Z", &arg) == FAILURE) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "intltz_create_enumeration: bad arguments", 0 TSRMLS_CC); RETURN_FALSE; } if (arg == NULL || Z_TYPE_PP(arg) == IS_NULL) { se = TimeZone::createEnumeration(); } else if (Z_TYPE_PP(arg) == IS_LONG) { int_offset: if (Z_LVAL_PP(arg) < (long)INT32_MIN || Z_LVAL_PP(arg) > (long)INT32_MAX) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "intltz_create_enumeration: value is out of range", 0 TSRMLS_CC); RETURN_FALSE; } else { se = TimeZone::createEnumeration((int32_t) Z_LVAL_PP(arg)); } } else if (Z_TYPE_PP(arg) == IS_DOUBLE) { double_offset: convert_to_long_ex(arg); goto int_offset; } else if (Z_TYPE_PP(arg) == IS_OBJECT || Z_TYPE_PP(arg) == IS_STRING) { long lval; double dval; convert_to_string_ex(arg); switch (is_numeric_string(Z_STRVAL_PP(arg), Z_STRLEN_PP(arg), &lval, &dval, 0)) { case IS_DOUBLE: SEPARATE_ZVAL(arg); zval_dtor(*arg); Z_TYPE_PP(arg) = IS_DOUBLE; Z_DVAL_PP(arg) = dval; goto double_offset; case IS_LONG: SEPARATE_ZVAL(arg); zval_dtor(*arg); Z_TYPE_PP(arg) = IS_LONG; Z_LVAL_PP(arg) = lval; goto int_offset; } /* else call string version */ se = TimeZone::createEnumeration(Z_STRVAL_PP(arg)); } else { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "intltz_create_enumeration: invalid argument type", 0 TSRMLS_CC); RETURN_FALSE; } if (se) { IntlIterator_from_StringEnumeration(se, return_value TSRMLS_CC); } else { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "intltz_create_enumeration: error obtaining enumeration", 0 TSRMLS_CC); RETVAL_FALSE; } } U_CFUNC PHP_FUNCTION(intltz_count_equivalent_ids) { char *str_id; int str_id_len; intl_error_reset(NULL TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &str_id, &str_id_len) == FAILURE) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "intltz_count_equivalent_ids: bad arguments", 0 TSRMLS_CC); RETURN_FALSE; } UErrorCode status = UErrorCode(); UnicodeString id = UnicodeString(); if (intl_stringFromChar(id, str_id, str_id_len, &status) == FAILURE) { intl_error_set(NULL, status, "intltz_count_equivalent_ids: could not convert time zone id to UTF-16", 0 TSRMLS_CC); RETURN_FALSE; } int32_t result = TimeZone::countEquivalentIDs(id); RETURN_LONG((long)result); } #if U_ICU_VERSION_MAJOR_NUM * 10 + U_ICU_VERSION_MINOR_NUM >= 48 U_CFUNC PHP_FUNCTION(intltz_create_time_zone_id_enumeration) { long zoneType, offset_arg; char *region = NULL; int region_len = 0; int32_t offset, *offsetp = NULL; int arg3isnull = 0; intl_error_reset(NULL TSRMLS_CC); /* must come before zpp because zpp would convert the arg in the stack to 0 */ if (ZEND_NUM_ARGS() == 3) { zval **dummy, **zvoffset; arg3isnull = zend_get_parameters_ex(3, &dummy, &dummy, &zvoffset) != FAILURE && Z_TYPE_PP(zvoffset) == IS_NULL; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|s!l", &zoneType, &region, &region_len, &offset_arg) == FAILURE) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "intltz_create_time_zone_id_enumeration: bad arguments", 0 TSRMLS_CC); RETURN_FALSE; } if (zoneType != UCAL_ZONE_TYPE_ANY && zoneType != UCAL_ZONE_TYPE_CANONICAL && zoneType != UCAL_ZONE_TYPE_CANONICAL_LOCATION) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "intltz_create_time_zone_id_enumeration: bad zone type", 0 TSRMLS_CC); RETURN_FALSE; } if (ZEND_NUM_ARGS() == 3) { if (offset_arg < (long)INT32_MIN || offset_arg > (long)INT32_MAX) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "intltz_create_time_zone_id_enumeration: offset out of bounds", 0 TSRMLS_CC); RETURN_FALSE; } if (!arg3isnull) { offset = (int32_t)offset_arg; offsetp = &offset; } //else leave offsetp NULL } StringEnumeration *se; UErrorCode uec = UErrorCode(); se = TimeZone::createTimeZoneIDEnumeration((USystemTimeZoneType)zoneType, region, offsetp, uec); INTL_CHECK_STATUS(uec, "intltz_create_time_zone_id_enumeration: " "Error obtaining time zone id enumeration") IntlIterator_from_StringEnumeration(se, return_value TSRMLS_CC); } #endif U_CFUNC PHP_FUNCTION(intltz_get_canonical_id) { char *str_id; int str_id_len; zval *is_systemid = NULL; intl_error_reset(NULL TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|z", &str_id, &str_id_len, &is_systemid) == FAILURE) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "intltz_get_canonical_id: bad arguments", 0 TSRMLS_CC); RETURN_FALSE; } UErrorCode status = UErrorCode(); UnicodeString id; if (intl_stringFromChar(id, str_id, str_id_len, &status) == FAILURE) { intl_error_set(NULL, status, "intltz_get_canonical_id: could not convert time zone id to UTF-16", 0 TSRMLS_CC); RETURN_FALSE; } UnicodeString result; UBool isSystemID; TimeZone::getCanonicalID(id, result, isSystemID, status); INTL_CHECK_STATUS(status, "intltz_get_canonical_id: error obtaining canonical ID"); intl_convert_utf16_to_utf8(&Z_STRVAL_P(return_value), &Z_STRLEN_P(return_value), result.getBuffer(), result.length(), &status); INTL_CHECK_STATUS(status, "intltz_get_canonical_id: could not convert time zone id to UTF-16"); Z_TYPE_P(return_value) = IS_STRING; if (is_systemid) { /* by-ref argument passed */ zval_dtor(is_systemid); ZVAL_BOOL(is_systemid, isSystemID); } } #if U_ICU_VERSION_MAJOR_NUM * 10 + U_ICU_VERSION_MINOR_NUM >= 48 U_CFUNC PHP_FUNCTION(intltz_get_region) { char *str_id; int str_id_len; char outbuf[3]; intl_error_reset(NULL TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &str_id, &str_id_len) == FAILURE) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "intltz_get_region: bad arguments", 0 TSRMLS_CC); RETURN_FALSE; } UErrorCode status = UErrorCode(); UnicodeString id; if (intl_stringFromChar(id, str_id, str_id_len, &status) == FAILURE) { intl_error_set(NULL, status, "intltz_get_region: could not convert time zone id to UTF-16", 0 TSRMLS_CC); RETURN_FALSE; } int32_t region_len = TimeZone::getRegion(id, outbuf, sizeof(outbuf), status); INTL_CHECK_STATUS(status, "intltz_get_region: Error obtaining region"); RETURN_STRINGL(outbuf, region_len, 1); } #endif U_CFUNC PHP_FUNCTION(intltz_get_tz_data_version) { intl_error_reset(NULL TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "intltz_get_tz_data_version: bad arguments", 0 TSRMLS_CC); RETURN_FALSE; } UErrorCode status = UErrorCode(); const char *res = TimeZone::getTZDataVersion(status); INTL_CHECK_STATUS(status, "intltz_get_tz_data_version: " "Error obtaining time zone data version"); RETURN_STRING(res, 1); } U_CFUNC PHP_FUNCTION(intltz_get_equivalent_id) { char *str_id; int str_id_len; long index; intl_error_reset(NULL TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sl", &str_id, &str_id_len, &index) == FAILURE || index < (long)INT32_MIN || index > (long)INT32_MAX) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "intltz_get_equivalent_id: bad arguments", 0 TSRMLS_CC); RETURN_FALSE; } UErrorCode status = UErrorCode(); UnicodeString id; if (intl_stringFromChar(id, str_id, str_id_len, &status) == FAILURE) { intl_error_set(NULL, status, "intltz_get_equivalent_id: could not convert time zone id to UTF-16", 0 TSRMLS_CC); RETURN_FALSE; } const UnicodeString result = TimeZone::getEquivalentID(id, (int32_t)index); intl_convert_utf16_to_utf8(&Z_STRVAL_P(return_value), &Z_STRLEN_P(return_value), result.getBuffer(), result.length(), &status); INTL_CHECK_STATUS(status, "intltz_get_equivalent_id: " "could not convert resulting time zone id to UTF-16"); Z_TYPE_P(return_value) = IS_STRING; } U_CFUNC PHP_FUNCTION(intltz_get_id) { TIMEZONE_METHOD_INIT_VARS; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, TimeZone_ce_ptr) == FAILURE) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "intltz_get_id: bad arguments", 0 TSRMLS_CC); RETURN_FALSE; } TIMEZONE_METHOD_FETCH_OBJECT; UnicodeString id_us; to->utimezone->getID(id_us); char *id = NULL; int id_len = 0; intl_convert_utf16_to_utf8(&id, &id_len, id_us.getBuffer(), id_us.length(), TIMEZONE_ERROR_CODE_P(to)); INTL_METHOD_CHECK_STATUS(to, "intltz_get_id: Could not convert id to UTF-8"); RETURN_STRINGL(id, id_len, 0); } U_CFUNC PHP_FUNCTION(intltz_use_daylight_time) { TIMEZONE_METHOD_INIT_VARS; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, TimeZone_ce_ptr) == FAILURE) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "intltz_use_daylight_time: bad arguments", 0 TSRMLS_CC); RETURN_FALSE; } TIMEZONE_METHOD_FETCH_OBJECT; RETURN_BOOL(to->utimezone->useDaylightTime()); } U_CFUNC PHP_FUNCTION(intltz_get_offset) { UDate date; zend_bool local; zval *rawOffsetArg, *dstOffsetArg; int32_t rawOffset, dstOffset; TIMEZONE_METHOD_INIT_VARS; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Odbzz", &object, TimeZone_ce_ptr, &date, &local, &rawOffsetArg, &dstOffsetArg) == FAILURE) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "intltz_get_offset: bad arguments", 0 TSRMLS_CC); RETURN_FALSE; } TIMEZONE_METHOD_FETCH_OBJECT; to->utimezone->getOffset(date, (UBool) local, rawOffset, dstOffset, TIMEZONE_ERROR_CODE(to)); INTL_METHOD_CHECK_STATUS(to, "intltz_get_offset: error obtaining offset"); zval_dtor(rawOffsetArg); ZVAL_LONG(rawOffsetArg, rawOffset); zval_dtor(dstOffsetArg); ZVAL_LONG(dstOffsetArg, dstOffset); RETURN_TRUE; } U_CFUNC PHP_FUNCTION(intltz_get_raw_offset) { TIMEZONE_METHOD_INIT_VARS; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, TimeZone_ce_ptr) == FAILURE) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "intltz_get_raw_offset: bad arguments", 0 TSRMLS_CC); RETURN_FALSE; } TIMEZONE_METHOD_FETCH_OBJECT; RETURN_LONG(to->utimezone->getRawOffset()); } U_CFUNC PHP_FUNCTION(intltz_has_same_rules) { zval *other_object; TimeZone_object *other_to; TIMEZONE_METHOD_INIT_VARS; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO", &object, TimeZone_ce_ptr, &other_object, TimeZone_ce_ptr) == FAILURE) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "intltz_has_same_rules: bad arguments", 0 TSRMLS_CC); RETURN_FALSE; } TIMEZONE_METHOD_FETCH_OBJECT; other_to = (TimeZone_object *) zend_object_store_get_object(other_object TSRMLS_CC); if (other_to->utimezone == NULL) { intl_errors_set(&to->err, U_ILLEGAL_ARGUMENT_ERROR, "intltz_has_same_rules: The second IntlTimeZone is unconstructed", 0 TSRMLS_CC); RETURN_FALSE; } RETURN_BOOL(to->utimezone->hasSameRules(*other_to->utimezone)); } static const TimeZone::EDisplayType display_types[] = { TimeZone::SHORT, TimeZone::LONG, #if U_ICU_VERSION_MAJOR_NUM * 10 + U_ICU_VERSION_MINOR_NUM >= 44 TimeZone::SHORT_GENERIC, TimeZone::LONG_GENERIC, TimeZone::SHORT_GMT, TimeZone::LONG_GMT, TimeZone::SHORT_COMMONLY_USED, TimeZone::GENERIC_LOCATION #endif }; U_CFUNC PHP_FUNCTION(intltz_get_display_name) { zend_bool daylight = 0; long display_type = TimeZone::LONG; const char *locale_str = NULL; int dummy = 0; TIMEZONE_METHOD_INIT_VARS; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O|bls!", &object, TimeZone_ce_ptr, &daylight, &display_type, &locale_str, &dummy) == FAILURE) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "intltz_get_display_name: bad arguments", 0 TSRMLS_CC); RETURN_FALSE; } bool found = false; for (int i = 0; !found && i < sizeof(display_types)/sizeof(*display_types); i++) { if (display_types[i] == display_type) found = true; } if (!found) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "intltz_get_display_name: wrong display type", 0 TSRMLS_CC); RETURN_FALSE; } if (!locale_str) { locale_str = intl_locale_get_default(TSRMLS_C); } TIMEZONE_METHOD_FETCH_OBJECT; UnicodeString result; to->utimezone->getDisplayName((UBool)daylight, (TimeZone::EDisplayType)display_type, Locale::createFromName(locale_str), result); intl_convert_utf16_to_utf8(&Z_STRVAL_P(return_value), &Z_STRLEN_P(return_value), result.getBuffer(), result.length(), TIMEZONE_ERROR_CODE_P(to)); INTL_METHOD_CHECK_STATUS(to, "intltz_get_display_name: " "could not convert resulting time zone id to UTF-16"); Z_TYPE_P(return_value) = IS_STRING; } U_CFUNC PHP_FUNCTION(intltz_get_dst_savings) { TIMEZONE_METHOD_INIT_VARS; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, TimeZone_ce_ptr) == FAILURE) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "intltz_get_dst_savings: bad arguments", 0 TSRMLS_CC); RETURN_FALSE; } TIMEZONE_METHOD_FETCH_OBJECT; RETURN_LONG((long)to->utimezone->getDSTSavings()); } U_CFUNC PHP_FUNCTION(intltz_get_error_code) { TIMEZONE_METHOD_INIT_VARS if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, TimeZone_ce_ptr) == FAILURE) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "intltz_get_error_code: bad arguments", 0 TSRMLS_CC); RETURN_FALSE; } /* Fetch the object (without resetting its last error code ). */ to = (TimeZone_object*)zend_object_store_get_object(object TSRMLS_CC); if (to == NULL) RETURN_FALSE; RETURN_LONG((long)TIMEZONE_ERROR_CODE(to)); } U_CFUNC PHP_FUNCTION(intltz_get_error_message) { const char* message = NULL; TIMEZONE_METHOD_INIT_VARS if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, TimeZone_ce_ptr) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "intltz_get_error_message: bad arguments", 0 TSRMLS_CC ); RETURN_FALSE; } /* Fetch the object (without resetting its last error code ). */ to = (TimeZone_object*)zend_object_store_get_object(object TSRMLS_CC); if (to == NULL) RETURN_FALSE; /* Return last error message. */ message = intl_error_get_message(TIMEZONE_ERROR_P(to) TSRMLS_CC); RETURN_STRING(message, 0); }
[ "cataphract@php.net" ]
cataphract@php.net
2dcec44c8bc4addd0414222b1ddafff409ec5d31
609c4ac4d8e46ca6825f91cc77fb6fe4936fbd29
/Launcher/Config/config.h
29495db1127006d5dae70bbbfafd187f56dcbad7
[]
no_license
EDK3D-dev/HackAndSlash
a581be459ec09514e65398f12c7ff882c820c10b
e13a872a36327363f282fd78448aa318dce2f7db
refs/heads/master
2022-04-11T18:17:22.012764
2016-04-24T11:21:45
2016-04-24T11:21:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
945
h
#ifndef CONFIG_H #define CONFIG_H #include <QMainWindow> #include <QObject> #include <QFile> #include <QTextStream> #include <QMessageBox> #include <QDebug> #include <QDir> #include <QXmlStreamReader> #include "../QDownloader/QDownloader.h" class QDownloader; class Config : public QObject { Q_OBJECT public: explicit Config(QObject *parent = 0); bool LoadConfig(); void ParseStringManifest(QString str); void ParseManifest(QDownloader *down); bool isFileExist(); void RenameManifest(); bool IsManifestEmpty(); QString GetPathToPlace(QString str); bool LoadXml(); signals: private: QString manifest; QDownloader *downloader; QXmlStreamReader xmlReader; public: int totalfile; QString server; QString LauncherUrl; void ParseStringManifestUninstall(QString str); void UninstallParseManifest(QDownloader *down); public slots: }; #endif // CONFIG_H
[ "atidote63240@gmail.com" ]
atidote63240@gmail.com
daffca27c0cb85617692f40f063b3e457710d89d
9029e19e83262ecad3b64b8a8eb8202df1756c85
/aws-cpp-sdk-sdb/source/model/NumberDomainBytesExceeded.cpp
7845f7baecdf36d9fe6d8bf0cff0cedda23bdbb4
[ "MIT", "Apache-2.0", "JSON" ]
permissive
thesunisgas/aws-sdk-cpp
5da80c064039e2c4636d87bf69f9059fcfcc83c5
5e13f32f0c3f1e7c259bd06404b3aba12fa7b9a5
refs/heads/master
2022-08-25T13:15:44.713783
2019-03-12T20:52:49
2020-05-19T05:11:57
261,756,291
2
2
null
2020-05-06T12:47:07
2020-05-06T12:47:06
null
UTF-8
C++
false
false
2,186
cpp
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/sdb/model/NumberDomainBytesExceeded.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::Utils::Xml; using namespace Aws::Utils; namespace Aws { namespace SimpleDB { namespace Model { NumberDomainBytesExceeded::NumberDomainBytesExceeded() : m_boxUsage(0.0), m_boxUsageHasBeenSet(false) { } NumberDomainBytesExceeded::NumberDomainBytesExceeded(const XmlNode& xmlNode) : m_boxUsage(0.0), m_boxUsageHasBeenSet(false) { *this = xmlNode; } NumberDomainBytesExceeded& NumberDomainBytesExceeded::operator =(const XmlNode& xmlNode) { XmlNode resultNode = xmlNode; if(!resultNode.IsNull()) { XmlNode boxUsageNode = resultNode.FirstChild("BoxUsage"); if(!boxUsageNode.IsNull()) { m_boxUsage = StringUtils::ConvertToDouble(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(boxUsageNode.GetText()).c_str()).c_str()); m_boxUsageHasBeenSet = true; } } return *this; } void NumberDomainBytesExceeded::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const { if(m_boxUsageHasBeenSet) { oStream << location << index << locationValue << ".BoxUsage=" << m_boxUsage << "&"; } } void NumberDomainBytesExceeded::OutputToStream(Aws::OStream& oStream, const char* location) const { if(m_boxUsageHasBeenSet) { oStream << location << ".BoxUsage=" << m_boxUsage << "&"; } } } // namespace Model } // namespace SimpleDB } // namespace Aws
[ "thesunisgas7@icloud.com" ]
thesunisgas7@icloud.com
e7889c78055d105a10141b71035d74b5db70f1bc
72f6df52dd7c9863e6266b905b074f52c8fd17a1
/src/SolvedElectrostaticSystem.cpp
0fd299c4351ea0a7f359ce18974097e80fab31e4
[]
no_license
bruno-OG/Electrostatics
26066de50fe12cf7fbd0159037ce4443df3a7b19
314fc062e429ac226a16b0842112d43a4befb0f0
refs/heads/master
2021-01-09T21:44:57.736342
2016-02-17T21:04:20
2016-02-17T21:04:20
51,082,987
0
0
null
null
null
null
UTF-8
C++
false
false
2,122
cpp
#include <Eigen/Dense> #include <stdexcept> #include "ElectrostaticSystem.h" #include <iostream> #include <fstream> #include <cmath> #include <string> #include <list> #include <vector> #include "SolvedElectrostaticSystem.h" namespace electrostatics { /* Constructors */ SolvedElectrostaticSystem::SolvedElectrostaticSystem(int iMin, int iMax, int jMin, int jMax) : ElectrostaticSystem(iMin, iMax, jMin, jMax) { fieldFound = false; } /* Methods */ void SolvedElectrostaticSystem::findField() { fieldX = doubleGrid::Zero(iMax-iMin+1, jMax-jMin+1); // X components of field fieldY = doubleGrid::Zero(iMax-iMin+1, jMax-jMin+1); // Y components of field field = doubleGrid::Zero(iMax-iMin+1, jMax-jMin+1); // Magnitude of field for(int i=iMin; i<=iMax; i++) { for(int j=jMin; j<=jMax; j++) { // Components in i direction if(i==iMax) fieldX(i-iMin, j-jMin) = getPotentialIJ(i,j) - getPotentialIJ(i-1,j); else if(i==iMin) fieldX(i-iMin, j-jMin) = getPotentialIJ(i+1,j) -getPotentialIJ(i,j); else fieldX(i-iMin, j-jMin) = (getPotentialIJ(i+1,j)-getPotentialIJ(i-1,j))/2; // Components in j direction if(j==jMax) fieldY(i-iMin, j-jMin) = getPotentialIJ(i,j) - getPotentialIJ(i,j-1); else if(j==jMin) fieldY(i-iMin, j-jMin) = getPotentialIJ(i,j+1) -getPotentialIJ(i,j); else fieldY(i-iMin, j-jMin) = (getPotentialIJ(i,j+1)-getPotentialIJ(i,j-1))/2; // Full field field(i-iMin, j-jMin) = sqrt( pow(fieldX(i-iMin, j-jMin), 2) + pow(fieldY(i-iMin, j-jMin), 2) ); } } fieldFound = true; } void SolvedElectrostaticSystem::saveFieldGNUPlot(std::string fileName) { if(!fieldFound) findField(); std::ofstream outputFile; outputFile.open(fileName.c_str()); for(int i=iMin; i<=iMax; i++) { for(int j=jMin; j<=jMax; j++) { outputFile << i << " " << j << " " << field(i-iMin, j-jMin) << "\n"; } outputFile << "\n"; } outputFile.close(); } } // namespace electrostatics
[ "duncan@d1s.co.uk" ]
duncan@d1s.co.uk
732d3b5d987afce951f3770d32e84f0f295ee94f
7cf8ec6ec24edd575b57dc9408ba3c31d1f4a5c0
/Plain/src/Common/VertexInput.h
d2c62b7cfb281ff93b4bb81148ac6b45ee8fae20
[ "MIT" ]
permissive
sxin-h/PlainRenderer
98c32d3c6998e63e807c71db51be3c1f40bf2e58
cf0f41a2300bee9f29a886230c061776cb29ba5e
refs/heads/master
2023-07-01T23:26:00.394298
2021-08-01T11:38:39
2021-08-01T11:38:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,392
h
#pragma once #include "pch.h" enum class VertexInputFlags { Position = 0x00000001, UV = 0x00000002, Normal = 0x00000004, Tangent = 0x00000008, Bitangent = 0x00000010 }; VertexInputFlags operator&(const VertexInputFlags l, const VertexInputFlags r); VertexInputFlags operator|(const VertexInputFlags l, const VertexInputFlags r); #define VERTEX_INPUT_ATTRIBUTE_COUNT 5 //defines which vertex attribute goes to which binding const VertexInputFlags vertexInputFlagPerLocation[VERTEX_INPUT_ATTRIBUTE_COUNT] = { VertexInputFlags::Position, VertexInputFlags::UV, VertexInputFlags::Normal, VertexInputFlags::Tangent, VertexInputFlags::Bitangent }; const uint32_t vertexInputPositionByteSize = 12; const uint32_t vertexInputUVByteSize = 4; const uint32_t vertexInputNormalByteSize = 4; const uint32_t vertexInputTangentByteSize = 4; const uint32_t vertexInputBitangentByteSize = 4; const uint32_t vertexInputBytePerLocation[VERTEX_INPUT_ATTRIBUTE_COUNT] = { vertexInputPositionByteSize, vertexInputUVByteSize, vertexInputNormalByteSize, vertexInputTangentByteSize, vertexInputBitangentByteSize }; constexpr uint32_t getFullVertexFormatByteSize() { uint32_t size = 0; for (const uint32_t attributeSize : vertexInputBytePerLocation) { size += attributeSize; } return size; }
[ "agauggel@uni-koblenz.de" ]
agauggel@uni-koblenz.de
b9a1ff8bb2006b8c19e167a8eb4d3c2ef70177d2
bbba82f21a77f8aaafdc2c20d8ea533b59d44129
/Terrain.cpp
905632675115b94a873ff620a7af11ccbb50c503
[]
no_license
klwolfe365/camelride167
47ad4df366693e190d1bdbf60878171a9589f711
15c209511ca39206616aa46a508987e10ae66f8d
refs/heads/master
2021-01-19T04:34:49.610379
2016-06-23T06:10:14
2016-06-23T06:10:14
36,532,674
0
0
null
null
null
null
UTF-8
C++
false
false
8,816
cpp
// // Terrain.cpp // CSE167 Spring 2015 Starter Code // // Created by Karen Wolfe on 5/14/15. // Copyright (c) 2015 RexWest. All rights reserved. // #include "Terrain.h" #include "Cylinder.h" #ifdef __APPLE__ #include <GLUT/glut.h> #else #include <GL/glut.h> #endif #include "Globals.h" #include "Shader.h" #include "BezierPatch.h" #define COLOR_R 237.0 / 256.0 #define COLOR_G 201.0 / 256.0 #define COLOR_B 175.0 / 256.0 Terrain::Terrain() : Node(){ terrain_color = Color(COLOR_R, COLOR_G, COLOR_B); draw_bezier = false; map_texture = NULL; num_vert = num_ind = 0; width = WIDTH; height = HEIGHT; height_map = (unsigned char*)malloc( width * width * sizeof(unsigned char)); for(int i = 0; i < width*height; i++) height_map[i] = 0; //num_ind = generateIndices(height_map, width, height); draw_bezier = false; } Terrain::Terrain(const char * ppmFile) : Terrain() { init(ppmFile); draw_bezier = true; } Terrain::~Terrain(){} bool Terrain::init(const char * ppmFile){ height_map = Texture::loadPPM(ppmFile, width, height); /* Create a 1024*1024 array of vertex coordinates (Vector3). Populate the array as follows: the x values should correspond to the array's x index, the z values to the y index. For example: Vector3[x][y].x = x, Vector3[x][y].z = y. The y value should be the corresponding value from the height map array (Vector3[x][y].y = heightmap[x][y]). */ for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ coords[x][y] = Vector3(x, height_map[3*(x*height + y)], y); if((coords[x][y])[1] > max_height) max_height = (coords[x][y])[1]; } } setNormals(); update_levels(0); return true; } void Terrain::draw(Matrix4 c) { draw_bezier ? drawNormal(c) : drawBezier(c); } void Terrain::drawNormal(Matrix4 c){ //glDisable(GL_LIGHTING); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glMultMatrixf(c.ptr()); // Globals::shader->bind(); // GLint loc = glGetUniformLocationARB(Globals::shader->getPid(), "water_level"); // glUniform1f(loc, Shader::water_level); // // GLint col = glGetAttribLocationARB(Globals::shader->getPid(), "gl_Color"); // GLint bandLoc = glGetUniformLocationARB(Globals::shader->getPid(), "band_width"); // glUniform1f(bandLoc, Shader::band_width); // glDisable(GL_LIGHTING); for(int h = 0; h < (height/PORTION) - 1; h++){ glBegin(GL_TRIANGLE_STRIP); for(int w = 0; w < (width/PORTION); w++){ Vector3 curr = coords[w][h+1]; Vector3 n; Vector3 prev = coords[w][h]; n = normal[w][h+1]; glColor3f(terrain_color[0], terrain_color[1], terrain_color[2]); glNormal3f(n[0],n[1],n[2]); glVertex3f(prev[0], prev[1], prev[2]); glVertex3f(curr[0], curr[1], curr[2]); } glEnd(); } //Globals::shader->unbind(); glPopMatrix(); //glEnable(GL_LIGHTING); } void Terrain::drawBezier(Matrix4 c) { //glDisable(GL_LIGHTING); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glMultMatrixf(c.ptr()); // Globals::shader->bind(); // GLint loc = glGetUniformLocationARB(Globals::shader->getPid(), "water_level"); // glUniform1f(loc, Shader::water_level); // // GLint col = glGetAttribLocationARB(Globals::shader->getPid(), "gl_Color"); // GLint bandLoc = glGetUniformLocationARB(Globals::shader->getPid(), "band_width"); // glUniform1f(bandLoc, Shader::band_width); // glDisable(GL_LIGHTING); int indexW, indexH; for(int h = 0; h < (height/PORTION) - 4; h += 3){ for(int w = 0; w < (width/PORTION) - 4; w += 3){ BezierPatch p = BezierPatch(coords[w][h], coords[w+1][h], coords[w+2][h], coords[w+3][h], coords[w][h+1], coords[w+1][h+1], coords[w+2][h+1], coords[w+3][h+1], coords[w][h+2], coords[w+1][h+2], coords[w+2][h+2], coords[w+3][h+2], coords[w][h+3], coords[w+1][h+3], coords[w+2][h+3], coords[w+3][h+3]); for(float u = 0.0; u <= 1.0 - BEZ_ACC; u += BEZ_ACC) { glBegin(GL_TRIANGLE_STRIP); for(float v = 0.0; v <= 1.0; v += BEZ_ACC) { glColor3f(terrain_color[0], terrain_color[1], terrain_color[2]); glVertex3fv(p.getPoint(u, v).ptr()); glVertex3fv(p.getPoint(u + BEZ_ACC, v).ptr()); indexW = w + (int)(BEZ_POINTS*u); indexH = h + (int)(BEZ_POINTS*v); glNormal3fv(normal_bezier[indexW][indexH+1].ptr()); } glEnd(); } } } //Globals::shader->unbind(); glPopMatrix(); //glEnable(GL_LIGHTING); } void Terrain::update(){} void Terrain::heighten(int y){ int scaleFact = .1; if(y<0){ scaleFact *= -1; } max_height = 0; for(int w = 0; w < width; w++){ for(int h = 0; h< height; h++){ (coords[w][h])[1] += height_map[3*(w*width+h)+1]*scaleFact; if((coords[w][h])[1] > max_height) max_height = (coords[w][h])[1]; } } setNormals(); } void Terrain::setNormals(){ setNormalsBezier(); for(int r = 1; r < width - 1; r++){ for(int c = 0; c < height - 1; c++){ normal[r][c] = (coords[r][c+1]-coords[r][c]).cross(coords[r-1][c]-coords[r][c]); normal[r][c] = (normal[r][c]).normalize()*-1; } } for(int i = 0; i < width - 2; i++){ normal[0][i] = (coords[1][i] - coords[0][i]).cross(coords[0][i+1]-coords[0][i]); normal[0][i] = (normal[0][i]).normalize(); normal[i][height - 1] = (coords[i-1][height - 1] - coords[i][height - 1]).cross(coords[i][height - 1]-coords[i][height -1]); normal[i][height - 1] = (normal[i][height - 1]).normalize(); } } void Terrain::setNormalsBezier() { Vector3 v1, v2, v3, v4; int indexW, indexH; for(int h = 0; h < (height/PORTION) - 4; h += 3){ for(int w = 0; w < (width/PORTION) - 4; w += 3){ BezierPatch p = BezierPatch(coords[w][h], coords[w+1][h], coords[w+2][h], coords[w+3][h], coords[w][h+1], coords[w+1][h+1], coords[w+2][h+1], coords[w+3][h+1], coords[w][h+2], coords[w+1][h+2], coords[w+2][h+2], coords[w+3][h+2], coords[w][h+3], coords[w+1][h+3], coords[w+2][h+3], coords[w+3][h+3]); for(float u = 0.0; u <= 1.0 - BEZ_ACC; u += BEZ_ACC) { for(float v = 0.0; v <= 1.0 - BEZ_ACC; v += BEZ_ACC) { v1 = p.getPoint(u, v); v2 = p.getPoint(u, v+1); v3 = p.getPoint(u+1, v); v4 = p.getPoint(u+1, v+1); indexW = w + (int)(BEZ_POINTS*u); indexH = h + (int)(BEZ_POINTS*v); normal_bezier[indexW][indexH] = (v2-v1).cross(v3-v1).normalize(); normal_bezier[indexW][indexH+1] = (v3-v4).cross(v2-v4).normalize(); } } } } } //right cross above //end row above to left void Terrain::update_levels(float y){ if(y>0) Shader::water_level += 5; else if (y < 0) Shader::water_level -= 5; Shader::band_width = (max_height-Shader::water_level)/4; } Vector4 Terrain::getColor(float y){ float level = (y - Shader::water_level)/band_height; Vector4 color; /*Water Level*/ if(y <= Shader::water_level) return Vector4(0.0,0.0,1.0); /*Das beach yah*/ else if(level < .2) return Vector4(1.0,1.0,0.0); else if(level < 1.0) return Vector4(0.0,1.0,0.0); else if(level < 1.8) return Vector4(0.2,0.2,0.2); else return Vector4(1.0,1.0,1.0); } float Terrain::getLevel(float y){ float level = (y - Shader::water_level)/Shader::band_width; /*Water Level*/ if(y <= Shader::water_level) return 1.0; /*Das beach yah*/ else if(level < .2) return 1.0; else if(level < 1.0) return 2.0; else if(level < 1.8) return 3.0; else return 4.0; } void Terrain::setBezierMode(bool draw_bezier) { if(this->draw_bezier != draw_bezier) { this->draw_bezier = draw_bezier; draw_bezier ? setNormalsBezier() : setNormals(); } }
[ "karen@wolfenet.org" ]
karen@wolfenet.org
7f0b269987ad22a885847d0cbf5dfd29ee41ee5d
a80aa0db46db88d3b2235cd290210f136ba2d41e
/tecplotlib-master/tecplotread-win/CPR-post/CPR-post/TecplotZone.cpp
447beff93fba95fc2a0be7ba561fbecf78d3a629
[]
no_license
Wendroff/Post
8ce30b783671b09060b6351056526f7734edcc2d
34b4c15c31d27835f0fd5318c2cf6f6aadf63454
refs/heads/master
2021-09-15T14:45:00.978455
2018-03-10T11:40:58
2018-03-10T11:40:58
107,480,610
0
0
null
null
null
null
UTF-8
C++
false
false
793
cpp
#include "TecplotZone.h" TecplotZone::TecplotZone(string name, size_t start_index, string type, size_t i, size_t j, size_t k): name_(name), start_index_(start_index), type_(type), i_(i), j_(j), k_(k) { size_t add = i; if (j > 0) add *= j; if (k > 0) add *= k; end_index_ = start_index_+ add; } size_t TecplotZone::start() { return start_index_; } size_t TecplotZone::end() { return end_index_; } size_t TecplotZone::length() { return end_index_ - start_index_; } string TecplotZone::name() { return name_; } size_t TecplotZone::dim() { if (k_ > 0) return 3; if (j_ > 0) return 2; if (i_ > 0) return 1; return -1; } size_t TecplotZone::i() { return i_; } size_t TecplotZone::j() { return j_; } size_t TecplotZone::k() { return k_; }
[ "624101034@qq.com" ]
624101034@qq.com
9f31b21c098cd4d022765bbed503aa5809c35390
140163a8e8998382c1b8097187abf6111cecb02d
/T64.cpp
68e658321cd250780301daf7b59a1de63959d578
[]
no_license
yebanxinghui/leetcode
2112510d2bc794b8334ed3c94c8b52c56d4d4cca
e75433a521d798fd8bddd91d43ace94ced274686
refs/heads/master
2022-09-08T03:14:40.564157
2020-05-26T13:05:17
2020-05-26T13:05:17
267,042,189
1
0
null
null
null
null
UTF-8
C++
false
false
674
cpp
class Solution { public: int minPathSum(vector<vector<int>>& grid) { int m = grid.size(); int n = grid[0].size(); for(int i = 0;i<m;i++) { for(int j=0;j<n;j++) { if(i==0&&j!=0) { grid[i][j] += grid[i][j-1]; } else if(i!=0&&j==0) { grid[i][j] += grid[i-1][j]; } else if(i!=0 && j!=0) { grid[i][j] += min(grid[i][j-1],grid[i-1][j]); } } } return grid[m-1][n-1]; } };
[ "1225841522@qq.com" ]
1225841522@qq.com
10bab780124936490105063fb7b0d5104ab54454
5e0a393fc13ac4bc4c00aa7b7d7f62a78281c712
/tests.HIDE/utilities/optional/optional.object/optional.object.ctor/default.pass.cpp
5f9c5af5a29151db880cd32660cb32140a155d2e
[ "BSD-3-Clause" ]
permissive
lodyagin/bare_cxx
6b313fab6c7a683f8f71be8e8016154996f92490
bac88c1693d9728a9de4a253808a3655cf1da081
refs/heads/master
2021-12-09T03:42:33.084893
2021-09-30T20:39:23
2021-09-30T20:39:23
14,473,500
10
1
null
null
null
null
UTF-8
C++
false
false
1,330
cpp
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <optional> // constexpr optional() noexcept; #include <optional> #include <type_traits> #include <cassert> #if _LIBCPP_STD_VER > 11 template <class Opt> void test_constexpr() { static_assert(std::is_nothrow_default_constructible<Opt>::value, ""); constexpr Opt opt; static_assert(static_cast<bool>(opt) == false, ""); struct test_constexpr_ctor : public Opt { constexpr test_constexpr_ctor() {} }; } template <class Opt> void test() { static_assert(std::is_nothrow_default_constructible<Opt>::value, ""); Opt opt; assert(static_cast<bool>(opt) == false); struct test_constexpr_ctor : public Opt { constexpr test_constexpr_ctor() {} }; } struct X { X(); }; #endif // _LIBCPP_STD_VER > 11 int main() { #if _LIBCPP_STD_VER > 11 test_constexpr<std::optional<int>>(); test_constexpr<std::optional<int*>>(); test<std::optional<X>>(); #endif // _LIBCPP_STD_VER > 11 }
[ "hhinnant@91177308-0d34-0410-b5e6-96231b3b80d8" ]
hhinnant@91177308-0d34-0410-b5e6-96231b3b80d8
5d036e2ebff2d5c24dfbd252d540117f39e8754a
2e619c8e2b667640989c6703a39fde3e4485679b
/2. Leetcode/medium level/402. advantage shuffle.cpp
f39353b8cad001f4f02edf0cefa3d132a34f1f0b
[]
no_license
satyampandey9811/competitive-programming
76957cde72ba217894ba18370f6489d7c481ba55
8ca1e2608f5d221f4be87529052c8eb3b0713386
refs/heads/master
2022-10-14T11:13:16.704203
2022-09-20T18:24:09
2022-09-20T18:24:09
203,355,790
0
0
null
null
null
null
UTF-8
C++
false
false
531
cpp
// link to question - https://leetcode.com/problems/advantage-shuffle/ class Solution { public: vector<int> advantageCount(vector<int>& a, vector<int>& b) { int n = a.size(); vector<int> ans(n); multiset<int> ms(a.begin(), a.end()); for(int i = 0; i < n; i++) { auto it = ms.upper_bound(b[i]); if(it == ms.end()) { it = ms.begin(); } ans[i] = *it; ms.erase(it); } return ans; } };
[ "satyampandey9811@gmail.com" ]
satyampandey9811@gmail.com
d69021071f17a9105af9338c7f447e866569b181
b9ca6164b1ec49e38403123ea2f159033f3e9daf
/Sources/main.cpp
9417791f804c08395c202fb8febc24cab96190a3
[ "MIT" ]
permissive
Slin/ProjectZ
f553db64c63f89e4012d20a980f4242754ef3151
186c5ce8560112d5e8262b5aedf45c863cfb4a5b
refs/heads/master
2021-05-09T15:10:13.876955
2018-02-10T17:25:00
2018-02-10T17:25:00
119,084,845
0
1
null
null
null
null
UTF-8
C++
false
false
310
cpp
#include <Rayne.h> #include "PZApplication.h" #if RN_BUILD_RELEASE #pragma comment(linker, "/SUBSYSTEM:windows /ENTRY:mainCRTStartup") #endif int main(int argc, const char *argv[]) { #if RN_BUILD_DEBUG // _CrtSetDbgFlag(_CRTDBG_CHECK_ALWAYS_DF); #endif RN::Initialize(argc, argv, new PZ::Application()); }
[ "nils_daumann@slindev.com" ]
nils_daumann@slindev.com
abddd53ac696a3e865ca4fa9672ce774d1059522
a56252fda5c9e42eff04792c6e16e413ad51ba1a
/resources/home/dnanexus/root/include/TEnv.h
a08c1688ad3505c6855605b5ac317e0878e87715
[ "LGPL-2.1-or-later", "LGPL-2.1-only", "Apache-2.0" ]
permissive
edawson/parliament2
4231e692565dbecf99d09148e75c00750e6797c4
2632aa3484ef64c9539c4885026b705b737f6d1e
refs/heads/master
2021-06-21T23:13:29.482239
2020-12-07T21:10:08
2020-12-07T21:10:08
150,246,745
0
0
Apache-2.0
2019-09-11T03:22:55
2018-09-25T10:21:03
Python
UTF-8
C++
false
false
8,117
h
// @(#)root/base:$Id$ // Author: Fons Rademakers 22/09/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT_TEnv #define ROOT_TEnv ////////////////////////////////////////////////////////////////////////// // // // TEnv // // // // The TEnv class reads config files, by default named .rootrc. Three // // types of config files are read: global, user and local files. The // // global file is $ROOTSYS/etc/system<name> (or ROOTETCDIR/system<name>)// // the user file is $HOME/<name> and the local file is ./<name>. // // By setting the shell variable ROOTENV_NO_HOME=1 the reading of // // the $HOME/<name> resource file will be skipped. This might be useful // // in case the home directory resides on an automounted remote file // // system and one wants to avoid this file system from being mounted. // // // // The format of the .rootrc file is similar to the .Xdefaults format: // // // // [+]<SystemName>.<RootName|ProgName>.<name>[(type)]: <value> // // // // Where <SystemName> is either Unix, WinNT, MacOS or Vms, // // <RootName> the name as given in the TApplication ctor (or "RootApp" // // in case no explicit TApplication derived object was created), // // <ProgName> the current program name and <name> the resource name, // // with optionally a type specification. <value> can be either a // // string, an integer, a float/double or a boolean with the values // // TRUE, FALSE, ON, OFF, YES, NO, OK, NOT. Booleans will be returned as // // an integer 0 or 1. The options [+] allows the concatenation of // // values to the same resouce name. // // // // E.g.: // // // // Unix.Rint.Root.DynamicPath: .:$ROOTSYS/lib:~/lib // // myapp.Root.Debug: FALSE // // TH.Root.Debug: YES // // *.Root.MemStat: 1 // // // // <SystemName> and <ProgName> or <RootName> may be the wildcard "*". // // A # in the first column starts comment line. // // // // For the currently defined resources (and their default values) see // // $ROOTSYS/etc/system.rootrc. // // // // Note that the .rootrc config files contain the config for all ROOT // // based applications. // // // ////////////////////////////////////////////////////////////////////////// #include "TObject.h" #include "TString.h" class THashList; class TEnv; class TEnvParser; class TReadEnvParser; class TWriteEnvParser; enum EEnvLevel { kEnvGlobal, kEnvUser, kEnvLocal, kEnvChange, kEnvAll }; ////////////////////////////////////////////////////////////////////////// // // // TEnvRec // // // // Individual TEnv records. // // // ////////////////////////////////////////////////////////////////////////// class TEnvRec : public TObject { friend class TEnv; friend class TEnvParser; friend class TReadEnvParser; friend class TWriteEnvParser; private: TString fName; // env rec key name TString fType; // env rec type TString fValue; // env rec value EEnvLevel fLevel; // env rec level Bool_t fModified; // if env rec has been modified TEnvRec(const char *n, const char *v, const char *t, EEnvLevel l); Int_t Compare(const TObject *obj) const; void ChangeValue(const char *v, const char *t, EEnvLevel l, Bool_t append = kFALSE, Bool_t ignoredup = kFALSE); TString ExpandValue(const char *v); public: TEnvRec(): fName(), fType(), fValue(), fLevel(kEnvAll), fModified(kTRUE) { } ~TEnvRec(); const char *GetName() const { return fName; } const char *GetValue() const { return fValue; } const char *GetType() const { return fType; } EEnvLevel GetLevel() const { return fLevel; } ULong_t Hash() const { return fName.Hash(); } ClassDef(TEnvRec,2) // Individual TEnv records }; ////////////////////////////////////////////////////////////////////////// // // // TEnv // // // ////////////////////////////////////////////////////////////////////////// class TEnv : public TObject { private: THashList *fTable; // hash table containing env records TString fRcName; // resource file base name Bool_t fIgnoreDup; // ignore duplicates, don't issue warning TEnv(const TEnv&); // not implemented TEnv& operator=(const TEnv&); // not implemented const char *Getvalue(const char *name) const; public: TEnv(const char *name=""); virtual ~TEnv(); THashList *GetTable() const { return fTable; } Bool_t Defined(const char *name) const { return Getvalue(name) != 0; } virtual const char *GetRcName() const { return fRcName; } virtual void SetRcName(const char *name) { fRcName = name; } virtual Int_t GetValue(const char *name, Int_t dflt) const; virtual Double_t GetValue(const char *name, Double_t dflt) const; virtual const char *GetValue(const char *name, const char *dflt) const; virtual void SetValue(const char *name, const char *value, EEnvLevel level = kEnvChange, const char *type = 0); virtual void SetValue(const char *name, EEnvLevel level = kEnvChange); virtual void SetValue(const char *name, Int_t value); virtual void SetValue(const char *name, Double_t value); virtual TEnvRec *Lookup(const char *n) const; virtual Int_t ReadFile(const char *fname, EEnvLevel level); virtual Int_t WriteFile(const char *fname, EEnvLevel level = kEnvAll); virtual void Save(); virtual void SaveLevel(EEnvLevel level); virtual void Print(Option_t *option="") const; virtual void PrintEnv(EEnvLevel level = kEnvAll) const; Bool_t IgnoreDuplicates(Bool_t ignore); ClassDef(TEnv,2) // Handle ROOT configuration resources }; R__EXTERN TEnv *gEnv; #endif
[ "slzarate96@gmail.com" ]
slzarate96@gmail.com
bab4e9333999f5d6073d2c50884ea7e5a2f72f4c
56bae9c96e6512ea1d701e9b0f808a4008350f0e
/Source/HighPassFilter.h
77c193438da71fd23becfc4e683d2760fc8a1359
[]
no_license
JBijtebier/CuttleFish
ca25e10877e6bef4e88adfaaeffb24eedabb9687
3390e5dba8e91fca6c0089c59c3c2da35af16a51
refs/heads/master
2021-07-14T09:06:11.466574
2018-09-22T15:02:53
2018-09-22T15:02:53
130,035,434
1
0
null
null
null
null
UTF-8
C++
false
false
565
h
/* ============================================================================== HighPassFilter.h Created: 6 Jun 2018 4:47:21pm Author: Jens Bijtebier ============================================================================== */ #pragma once #include "Effect.h" #include "maximilian.h" namespace CuttleFish { class HighPassFilter : public Effect { public: HighPassFilter(int elementId); ~HighPassFilter(); juce::String getName() override; double getSignal() override; double cutoff; private: maxiFilter filter; }; }
[ "jens.bijtebier@gmail.com" ]
jens.bijtebier@gmail.com
2b5a176b2aaebda3f874500b47eb63f21f0ce940
2eb806e1a88fc2718fc142167c17528944c53303
/BaekJoon/2022/5.May/220521_5893.cpp
0e1e6c7a55c1423768ac7101b06f4bd6c15d31a8
[]
no_license
chichchic/algorithmPrac
4eec4bfbcadbeb78ada671bf19fab0b9304e1a34
bca786c8e2c983fe9ca54b5efe5b959cc7e67013
refs/heads/master
2022-11-22T09:10:21.642831
2022-11-10T14:16:04
2022-11-10T14:16:04
192,276,545
0
0
null
null
null
null
UTF-8
C++
false
false
862
cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { // freopen("../../input.txt", "r", stdin); ios_base::sync_with_stdio(0); cin.tie(0); string n; cin >> n; reverse(n.begin(), n.end()); vector<int> input(10000, -1); for (int i = 0; i < n.size(); i++) { if (n[i] == '1') { input[i] = 17; } else { input[i] = 0; } } string answer = ""; int i = 0; while (true) { int cur = input[i] % 2; if (cur == 1) { answer += '1'; } else { answer += '0'; } int carry = input[i] / 2; if (carry == 0 && input[i + 1] == -1) { break; } if (input[i + 1] == -1) { input[i + 1] = 0; } input[i + 1] += carry; i++; } reverse(answer.begin(), answer.end()); cout << answer; return 0; }
[ "pch6789@naver.com" ]
pch6789@naver.com
2d11cb2bb44c7201bf5ea4945b093392eeb82ecb
23389702ae1c5b167672cfef069fcb7e99025e2c
/lab5/lab5/lab5/BinarySearchTree.h
44ce18ee3c2c45b9cf5c48b817fcf027eb33392c
[]
no_license
verdande2/CST276-Design-Patterns-Winter-13
07d11378a56394b0ad5219dfc9825592e0ef8788
bf1919031e13ebeb7e34f37e1276d7c76caa5481
refs/heads/master
2020-09-23T03:19:58.396694
2016-08-23T17:10:14
2016-08-23T17:10:14
66,387,169
0
0
null
null
null
null
UTF-8
C++
false
false
12,911
h
/************************************************************************ * Class: BinarySearchTree * * Purpose: This class is a binary search tree. * * Manager functions: * BinarySearchTree() * BinarySearchTree(BinarySearchTree const& copy) * Various constructors to set up the object with the given parameters. * ~BinarySearchTree() * destructor * operator=() * Assignment operator * * Methods: * isInTree(T data) * returns true is data is in the tree, false otherwise * Insert(T data) * Inserts data into the tree * Delete(T data) * Deletes node in the tree matching data * Purge() * Removes all data from the tree * Height() * Gets the height of the tree * InOrderTraversal() * PreOrderTraversal() * PostOrderTraversal() * BreadthFirstTraversal() * Various traversal methods for the tree * *************************************************************************/ #pragma once #include "BinarySearchTreeNode.h" #include "Exception.h" #include <queue> using std::queue; #include <algorithm> using std::max; #include "BinarySearchTreePreOrderIterator.h" #include "BinarySearchTreeInOrderIterator.h" #include "BinarySearchTreePostOrderIterator.h" template <class T> class BinarySearchTree { private: BinarySearchTreeNode<T>* m_root; void Purge(BinarySearchTreeNode<T>* node); void Delete(T const& data, BinarySearchTreeNode<T>* & node); BinarySearchTreeNode<T>* FindMinimum(BinarySearchTreeNode<T>* node) const; unsigned Height(BinarySearchTreeNode<T>* node) const; public: BinarySearchTree(void); BinarySearchTree(BinarySearchTree<T> const& copy); ~BinarySearchTree(void); BinarySearchTree<T> const& operator=(BinarySearchTree<T> const& rhs); void Insert(T const& data); void Delete(T const& data); void Purge(); unsigned Height(void) const; void InOrderTraversal(void (*traverseFunc)(T& data)); void PreOrderTraversal(void (*traverseFunc)(T& data)); void PostOrderTraversal(void (*traverseFunc)(T& data)); void BreadthFirstTraversal(void (*traverseFunc)(T& data)); void InOrderTraversal(void (*traverseFunc)(T const& data)) const; void PreOrderTraversal(void (*traverseFunc)(T const& data)) const; void PostOrderTraversal(void (*traverseFunc)(T const& data)) const; void BreadthFirstTraversal(void (*traverseFunc)(T const& data)) const; bool isInTree(T const& data) const; BinarySearchTreeNode<T>* getFirst() const; BinarySearchTreeNode<T>* getLast() const; BinarySearchTreePreOrderIterator<T> PreOrderIterator() const; BinarySearchTreeInOrderIterator<T> InOrderIterator() const; BinarySearchTreePostOrderIterator<T> PostOrderIterator() const; }; /********************************************************************** * Purpose: Various constructors for BinarySearchTree. Acceptable forms: * Note: "Node" used as shorthand for BinarySearchTreeNode * BinarySearchTree() (default constructor) * BinarySearchTree(BinarySearchTree) (copy constructor) * * Entry: None. * * Exit: An object is created with the given parameters. * ************************************************************************/ template <class T> BinarySearchTree<T>::BinarySearchTree(void) : m_root(nullptr) { } template <class T> BinarySearchTree<T>::BinarySearchTree(BinarySearchTree<T> const& copy) : m_root(nullptr) { // duplicate the entire tree // method of doing so is basically inserting each element while breadth-first traversing the copy queue< BinarySearchTreeNode<T> const* > q; q.push(copy.m_root); BinarySearchTreeNode<T> const* ptr = nullptr; while(!q.empty()) { ptr = q.front(); q.pop(); Insert(ptr->m_data); if(ptr->m_left) { q.push(ptr->m_left); } if(ptr->m_right) { q.push(ptr->m_right); } } } /********************************************************************** * Purpose: Destructor * * Entry: None. * * Exit: Object is destroyed. * ************************************************************************/ template <class T> BinarySearchTree<T>::~BinarySearchTree(void) { Purge(); } /********************************************************************** * Purpose: Assignment operator * * Entry: * Parameters: * rhs is of type BinarySearchTree (with same templated class type) * * Exit: Current object is a duplicate copy of the rhs. (Deep copied) * ************************************************************************/ template <class T> BinarySearchTree<T> const& BinarySearchTree<T>::operator=(BinarySearchTree<T> const& rhs) { // unsure if this is even possible on a member function. // It should work in theory, but VS doesn't allow compilation, and google/stackoverflow didn't turn up much //rhs.BreadthFirstTraversal(&Insert<T>); // duplicate the entire tree // method of doing so is basically inserting each element while breadth-first traversing the rhs queue< BinarySearchTreeNode<T> const* > q; q.push(rhs.m_root); BinarySearchTreeNode<T> const* ptr = nullptr; while(!q.empty()) { ptr = q.front(); q.pop(); Insert(ptr->m_data); if(ptr->m_left) { q.push(ptr->m_left); } if(ptr->m_right) { q.push(ptr->m_right); } } return *this; } /********************************************************************** * Purpose: Used to insert data into the tree * * Entry: * Parameters: * data is of type T * * Exit: data added to tree * ************************************************************************/ template <class T> void BinarySearchTree<T>::Insert(T const& data) { if(m_root) // tree is not empty, add to root and let it recurse down tree if need be { m_root->Insert(data); } else // tree is empty, make the root a new node with the inserted data { m_root = new BinarySearchTreeNode<T>(nullptr, nullptr, data); } } /********************************************************************** * Purpose: Removes the nodes from the tree that match data. Limited to first occurence. * * Entry: * Parameters: * data is of type T * * Exit: Node is removed from tree. If data isn't found, function does nothing. * ************************************************************************/ template <class T> void BinarySearchTree<T>::Delete(T const& data) { if(m_root) { Delete(data, m_root); }else{ throw Exception("Cannot delete from empty tree"); } } // helper function for above template <class T> void BinarySearchTree<T>::Delete(T const& data, BinarySearchTreeNode<T>* & node) { if(node == nullptr) { // do nothing } else if(data < node->m_data) { Delete(data, node->m_left); } else if(data > node->m_data) { Delete(data, node->m_right); } else { BinarySearchTreeNode<T>* tempNode = nullptr; if(node->m_left == nullptr && node->m_right == nullptr) { delete node; node = nullptr; } else if(node->m_left == nullptr) { tempNode = node; node = node->m_right; delete tempNode; } else if(node->m_right == nullptr) { tempNode = node; node = node->m_left; delete tempNode; } else { tempNode = FindMinimum(node->m_right); node->m_data = tempNode->m_data; Delete(node->m_data, node->m_right); } } } /********************************************************************** * Purpose: Used to remove all data from tree * * Entry: None. * * Exit: tree is now entirely empty * ************************************************************************/ template <class T> void BinarySearchTree<T>::Purge() { Purge(m_root); m_root = nullptr; } // helper function for above template <class T> void BinarySearchTree<T>::Purge(BinarySearchTreeNode<T>* node) { if(node) { Purge(node->m_left); Purge(node->m_right); delete node; } } /********************************************************************** * Purpose: Used to determine the height of the tree * * Entry: None. * * Exit: Returns height of hte tree. * ************************************************************************/ template <class T> unsigned BinarySearchTree<T>::Height(void) const { return Height(m_root); } // helper function for above template <class T> unsigned BinarySearchTree<T>::Height(BinarySearchTreeNode<T>* node) const { unsigned height = 0; if(node == nullptr || (node->m_left == nullptr && node->m_right == nullptr)) { height = 0; // tree has no nodes, or is a leaf node } else { height = max(Height(node->m_left), Height(node->m_right)) + 1; } return height; } /********************************************************************** * Purpose: Various traversal methods for the binary search tree. * Includes: * In-order * Pre-order * Post-order * Breadth-First * As well as const flavors of each. * Used for traversing the tree and performing a function on each node's data. * * Entry: * Parameters: * traverseFunc is a function pointer to a function that takes data * by & or by const& respectively. * * Exit: The object is traversed and the traverseFunc is called on each node's data. * If tree is empty, will simply output to cout saying so. * ************************************************************************/ template <class T> void BinarySearchTree<T>::InOrderTraversal(void (*traverseFunc)(T& data)) { if(m_root) { m_root->InOrderTraversal(traverseFunc); } else { cout << "Tree is currently empty." << endl; } } template <class T> void BinarySearchTree<T>::InOrderTraversal(void (*traverseFunc)(T const& data)) const { if(m_root) { m_root->InOrderTraversal(traverseFunc); } else { cout << "Tree is currently empty." << endl; } } template <class T> void BinarySearchTree<T>::PreOrderTraversal(void (*traverseFunc)(T& data)) { if(m_root) { m_root->PreOrderTraversal(traverseFunc); } else { cout << "Tree is currently empty." << endl; } } template <class T> void BinarySearchTree<T>::PreOrderTraversal(void (*traverseFunc)(T const& data)) const { if(m_root) { m_root->PreOrderTraversal(traverseFunc); } else { cout << "Tree is currently empty." << endl; } } template <class T> void BinarySearchTree<T>::PostOrderTraversal(void (*traverseFunc)(T& data)) { if(m_root) { m_root->PostOrderTraversal(traverseFunc); } else { cout << "Tree is currently empty." << endl; } } template <class T> void BinarySearchTree<T>::PostOrderTraversal(void (*traverseFunc)(T const& data)) const { if(m_root) { m_root->PostOrderTraversal(traverseFunc); } else { cout << "Tree is currently empty." << endl; } } template <class T> void BinarySearchTree<T>::BreadthFirstTraversal(void (*traverseFunc)(T& data)) { if(m_root) { m_root->BreadthFirstTraversal(traverseFunc); } else { cout << "Tree is currently empty." << endl; } } template <class T> void BinarySearchTree<T>::BreadthFirstTraversal(void (*traverseFunc)(T const& data)) const { if(m_root) { m_root->BreadthFirstTraversal(traverseFunc); } else { cout << "Tree is currently empty." << endl; } } /********************************************************************** * Purpose: Used to determine if a value is in the tree. * * Entry: * Parameters: * data is of type T * * Exit: Return bool representing if the data was found in the tree. * ************************************************************************/ template <class T> bool BinarySearchTree<T>::isInTree(T const& data) const { bool inTree = false; if(m_root) { inTree = m_root->isInTree(data); } return inTree; } /********************************************************************** * Purpose: Helper function to determine the minimal value in the subtrees of a node * * Entry: * Parameters: * node is of type Node* * * Exit: Return pointer to minimal node * ************************************************************************/ template <class T> BinarySearchTreeNode<T>* BinarySearchTree<T>::FindMinimum(BinarySearchTreeNode<T>* node) const { BinarySearchTreeNode<T>* ptr = 0; if(node == nullptr) { ptr = nullptr; } else if(node->m_left == nullptr) { ptr = node; } else { ptr = FindMinimum(node->m_left); } return ptr; } template <class T> BinarySearchTreePreOrderIterator<T> BinarySearchTree<T>::PreOrderIterator() const { return BinarySearchTreePreOrderIterator<T>(*this, *m_root); } template <class T> BinarySearchTreeInOrderIterator<T> BinarySearchTree<T>::InOrderIterator() const { return BinarySearchTreeInOrderIterator<T>(*this, *m_root); } template <class T> BinarySearchTreePostOrderIterator<T> BinarySearchTree<T>::PostOrderIterator() const { return BinarySearchTreePostOrderIterator<T>(*this, *m_root); } template <class T> BinarySearchTreeNode<T>* BinarySearchTree<T>::getFirst() const { BinarySearchTreeNode<T>* n = m_root; if(m_root != nullptr) { while(n->m_left) { n = n->m_left; } } return n; } template <class T> BinarySearchTreeNode<T>* BinarySearchTree<T>::getLast() const { BinarySearchTreeNode<T>* n = m_root; if(m_root != nullptr) { while(n->m_right) { n = n->m_right; } } return n; }
[ "ASparkes@jeldwen.com" ]
ASparkes@jeldwen.com
410bbd10f6800814296bc1239246583a6c04ab98
ebecb4d5a9088af84b3255892b9ae9bd2af15648
/AlgorithmStudy/Searching/QiQiaoBan/QiQiaoBan_DFS.cpp
3a47cdb0b6ef0c42cd2b13ffec5c05fbb0b74b63
[]
no_license
lifajun/algorithm
7d6379823fa7d5f8ea46460e83041ca71e4b7c6d
7270abe44b073d1bc265056805970228e2eb22ef
refs/heads/master
2020-05-16T22:19:41.523186
2012-10-07T16:45:58
2012-10-07T16:45:58
6,112,915
3
0
null
null
null
null
UTF-8
C++
false
false
665
cpp
#include <iostream> using namespace std; int map[8][8] = { {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 1, 0, 0, 1, 0, 1}, {0, 1, 0, 0, 1, 0, 1, 0}, {0, 0, 0, 0, 1, 0, 0, 1}, {0, 0, 1, 1, 0, 0, 1, 1}, {0, 1, 0, 0, 0, 0, 0, 1}, {0, 0, 1, 0, 1, 0, 0, 0}, {0, 1, 0, 1, 1, 1, 0, 0} }; int c[8], total; bool ok(int s) { for(int i=1; i<s; i++) if(map[i][s] && c[i] == c[s]) return false; return true; } void dfs(int s) { if(s > 7) { for(int i=1; i<=7; i++) cout<<c[i]<<" "; cout<<endl; total++; } else { for(int i=1; i<=4; i++) { c[s] = i; if(ok(s)) dfs(s+1); } } } int main() { total = 0; dfs(1); cout<<total<<endl; return 0; }
[ "lifajun90@qq.com" ]
lifajun90@qq.com
a52c8b6fd837c06dc7febfe3aa9026363cfccf08
4cee9dd08f21a2985508ef09a77098d05de4f332
/lib/pmt_to_proto.cc
a411901e3db361672e93206977bba41f3aff0466
[]
no_license
matburnham/gr-meteor
72c01710de582b52906af230a130b03359288ae0
93f51b8eb90030bef8013292aae1062af203be60
refs/heads/master
2022-12-02T05:40:24.059218
2020-07-13T14:15:36
2020-07-13T14:15:36
276,685,924
0
0
null
null
null
null
UTF-8
C++
false
false
9,112
cc
/* -*- c++ -*- */ /* * Copyright 2018 Infostellar, Inc. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include "pmt_to_proto.h" void convert_proto_uniform_vector(const pmt::pmt_t &pmt_msg, meteor::UniformVector *uni_vector) { if (pmt::is_u8vector(pmt_msg)) { meteor::UVector *u_vector = uni_vector->mutable_u_value(); u_vector->set_size(meteor::IntSize::Size8); const std::vector<uint8_t> vector_elements = pmt::u8vector_elements(pmt_msg); std::copy( vector_elements.begin(), vector_elements.end(), google::protobuf::internal::RepeatedFieldBackInsertIterator<uint32_t>( u_vector->mutable_value())); } else if (pmt::is_s8vector(pmt_msg)) { meteor::IVector *i_vector = uni_vector->mutable_i_value(); i_vector->set_size(meteor::IntSize::Size8); const std::vector<int8_t> vector_elements = pmt::s8vector_elements(pmt_msg); std::copy( vector_elements.begin(), vector_elements.end(), google::protobuf::internal::RepeatedFieldBackInsertIterator<int32_t>( i_vector->mutable_value())); } else if (pmt::is_u16vector(pmt_msg)) { meteor::UVector *u_vector = uni_vector->mutable_u_value(); u_vector->set_size(meteor::IntSize::Size16); const std::vector<uint16_t> vector_elements = pmt::u16vector_elements(pmt_msg); std::copy( vector_elements.begin(), vector_elements.end(), google::protobuf::internal::RepeatedFieldBackInsertIterator<uint32_t>( u_vector->mutable_value())); } else if (pmt::is_s16vector(pmt_msg)) { meteor::IVector *i_vector = uni_vector->mutable_i_value(); i_vector->set_size(meteor::IntSize::Size16); const std::vector<int16_t> vector_elements = pmt::s16vector_elements(pmt_msg); std::copy( vector_elements.begin(), vector_elements.end(), google::protobuf::internal::RepeatedFieldBackInsertIterator<int32_t>( i_vector->mutable_value())); } else if (pmt::is_u32vector(pmt_msg)) { meteor::UVector *u_vector = uni_vector->mutable_u_value(); u_vector->set_size(meteor::IntSize::Size32); const std::vector<uint32_t> vector_elements = pmt::u32vector_elements(pmt_msg); std::copy( vector_elements.begin(), vector_elements.end(), google::protobuf::internal::RepeatedFieldBackInsertIterator<uint32_t>( u_vector->mutable_value())); } else if (pmt::is_s32vector(pmt_msg)) { meteor::IVector *i_vector = uni_vector->mutable_i_value(); i_vector->set_size(meteor::IntSize::Size32); const std::vector<int32_t> vector_elements = pmt::s32vector_elements(pmt_msg); std::copy( vector_elements.begin(), vector_elements.end(), google::protobuf::internal::RepeatedFieldBackInsertIterator<int32_t>( i_vector->mutable_value())); } else if (pmt::is_u64vector(pmt_msg)) { meteor::U64Vector *u64_vector = uni_vector->mutable_u64_value(); const std::vector<uint64_t> vector_elements = pmt::u64vector_elements(pmt_msg); std::copy( vector_elements.begin(), vector_elements.end(), google::protobuf::internal::RepeatedFieldBackInsertIterator<uint64_t>( u64_vector->mutable_value())); } else if (pmt::is_s64vector(pmt_msg)) { meteor::I64Vector *i64_vector = uni_vector->mutable_i64_value(); const std::vector<int64_t> vector_elements = pmt::s64vector_elements(pmt_msg); std::copy( vector_elements.begin(), vector_elements.end(), google::protobuf::internal::RepeatedFieldBackInsertIterator<int64_t>( i64_vector->mutable_value())); } else if (pmt::is_f32vector(pmt_msg)) { meteor::F32Vector *f32_vector = uni_vector->mutable_f32_value(); const std::vector<float> vector_elements = pmt::f32vector_elements(pmt_msg); std::copy( vector_elements.begin(), vector_elements.end(), google::protobuf::internal::RepeatedFieldBackInsertIterator<float>( f32_vector->mutable_value())); } else if (pmt::is_f64vector(pmt_msg)) { meteor::F64Vector *f64_vector = uni_vector->mutable_f64_value(); const std::vector<double> vector_elements = pmt::f64vector_elements(pmt_msg); std::copy( vector_elements.begin(), vector_elements.end(), google::protobuf::internal::RepeatedFieldBackInsertIterator<double>( f64_vector->mutable_value())); } else if (pmt::is_c32vector(pmt_msg)) { meteor::C32Vector *c32_vector = uni_vector->mutable_c32_value(); const std::vector<std::complex<float>> vector_elements = pmt::c32vector_elements(pmt_msg); std::transform( vector_elements.begin(), vector_elements.end(), google::protobuf::internal::RepeatedPtrFieldBackInsertIterator< meteor::Complex32>(c32_vector->mutable_value()), [](std::complex<float> c)->meteor::Complex32 { meteor::Complex32 new_val; new_val.set_real_value(c.real()); new_val.set_imaginary_value(c.imag()); return new_val; }); } else if (pmt::is_c64vector(pmt_msg)) { meteor::C64Vector *c64_vector = uni_vector->mutable_c64_value(); const std::vector<std::complex<double>> vector_elements = pmt::c64vector_elements(pmt_msg); std::transform( vector_elements.begin(), vector_elements.end(), google::protobuf::internal::RepeatedPtrFieldBackInsertIterator< meteor::Complex>(c64_vector->mutable_value()), [](std::complex<double> c)->meteor::Complex { meteor::Complex new_val; new_val.set_real_value(c.real()); new_val.set_imaginary_value(c.imag()); return new_val; }); } } meteor::BlockMessage convert_pmt_to_proto(const pmt::pmt_t &pmt_msg) { meteor::BlockMessage proto_msg; if (pmt::is_blob(pmt_msg)) { proto_msg.set_blob_value(pmt::blob_data(pmt_msg), pmt::blob_length(pmt_msg)); } else if (pmt::is_uniform_vector(pmt_msg)) { convert_proto_uniform_vector(pmt_msg, proto_msg.mutable_uniform_vector_value()); } else if (pmt::is_bool(pmt_msg)) { proto_msg.set_boolean_value(pmt::to_bool(pmt_msg)); } else if (pmt::is_symbol(pmt_msg)) { proto_msg.set_symbol_value(pmt::symbol_to_string(pmt_msg)); } else if (pmt::is_integer(pmt_msg)) { proto_msg.set_integer_value(pmt::to_long(pmt_msg)); } else if (pmt::is_uint64(pmt_msg)) { proto_msg.set_integer_value(pmt::to_uint64(pmt_msg)); } else if (pmt::is_real(pmt_msg)) { proto_msg.set_double_value(pmt::to_double(pmt_msg)); } else if (pmt::is_complex(pmt_msg)) { std::complex<double> val = pmt::to_complex(pmt_msg); meteor::Complex *complex = proto_msg.mutable_complex_value(); complex->set_real_value(val.real()); complex->set_imaginary_value(val.imag()); } else if (pmt::is_pair(pmt_msg)) { meteor::Pair *pair = proto_msg.mutable_pair_value(); meteor::BlockMessage car = convert_pmt_to_proto(pmt::car(pmt_msg)); meteor::BlockMessage cdr = convert_pmt_to_proto(pmt::cdr(pmt_msg)); pair->mutable_car()->Swap(&car); pair->mutable_cdr()->Swap(&cdr); } else if (pmt::is_tuple(pmt_msg)) { meteor::List *list = proto_msg.mutable_list_value(); list->set_type(meteor::List::TUPLE); for (int i = 0; i < pmt::length(pmt_msg); i++) { meteor::BlockMessage element = convert_pmt_to_proto(pmt::tuple_ref(pmt_msg, i)); list->add_value()->Swap(&element); } } else if (pmt::is_vector(pmt_msg)) { meteor::List *list = proto_msg.mutable_list_value(); list->set_type(meteor::List::VECTOR); for (int i = 0; i < pmt::length(pmt_msg); i++) { meteor::BlockMessage element = convert_pmt_to_proto(pmt::vector_ref(pmt_msg, i)); list->add_value()->Swap(&element); } } else if (pmt::is_dict(pmt_msg)) { meteor::Dict *dict = proto_msg.mutable_dict_value(); pmt::pmt_t key_value_pairs_list = pmt::dict_items(pmt_msg); for (int i = 0; i < pmt::length(key_value_pairs_list); i++) { meteor::Dict_Entry *entry = dict->add_entry(); meteor::BlockMessage key = convert_pmt_to_proto(pmt::car(pmt::nth(i, key_value_pairs_list))); meteor::BlockMessage value = convert_pmt_to_proto(pmt::cdr(pmt::nth(i, key_value_pairs_list))); entry->mutable_key()->Swap(&key); entry->mutable_value()->Swap(&value); } } return proto_msg; }
[ "matburnham@gmail.com" ]
matburnham@gmail.com
c2bc1bf1151d097ce550cf3193132959e8b60501
309975d60e30260f2e02d11e71eaaf6e08b93659
/Modules/FBX/Thirdparty/include/fbxsdk/scene/shading/fbxbindingoperator.h
18d7fa443f04b37015031accee4bf215c92fb397
[]
permissive
BlitzModder/dava.engine
e83b038a9d24b37c00b095e83ffdfd8cd497823c
0c7a16e627fc0d12309250d6e5e207333b35361e
refs/heads/development
2023-03-15T12:30:32.342501
2018-02-19T11:09:02
2018-02-19T11:09:02
122,161,150
4
3
BSD-3-Clause
2018-02-20T06:00:07
2018-02-20T06:00:07
null
UTF-8
C++
false
false
40,405
h
/**************************************************************************************** Copyright (C) 2015 Autodesk, Inc. All rights reserved. Use of this software is subject to the terms of the Autodesk license agreement provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. ****************************************************************************************/ //! \file fbxbindingoperator.h #ifndef _FBXSDK_SCENE_SHADING_BINDING_OPERATOR_H_ #define _FBXSDK_SCENE_SHADING_BINDING_OPERATOR_H_ #include <fbxsdk/fbxsdk_def.h> #include <fbxsdk/scene/shading/fbxbindingtablebase.h> #include <fbxsdk/fbxsdk_nsbegin.h> /** This object represents a binding operation on a FbxObject or FbxProperty. * For example, FbxBindingOperator can be used to bind a light object * to a parameter of shader via FbxNodeDirectionBOF or FbxNodePositionBOF. * \code * //Create an entry lEntry of binding table lTable. * FbxBindingTableEntry& lEntry = lTable->AddNewEntry(); * * //Create a NodePositionConvert binding operator and add it as source of the lEntry. * FbxOperatorEntryView lSrc(&lEntry, true, true); * lSrc.SetOperatorName( "NodePositionConvert"); * FbxBindingOperator* lOp = pImpl.AddNewBindingOperator( "NodePositionConvert", FbxNodePositionBOF::FunctionName); * * //Add a property entry to the binding operator. * FbxBindingTableEntry& lEntryPropParam = lOp->AddNewEntry(); * FbxPropertyEntryView lPropSrc(&lEntryPropParam, true, true); * //Set the shader parameter (the property's name) as source of the lEntryPropParam. * lPropSrc.SetProperty(lProp.GetHierarchicalName()); * //Set the operator function FbxNodePositionBOF as destination of the lEntryPropParam. * lEntryPropParam.SetDestination( FbxNodePositionBOF::FunctionName ); * * //Set the shader parameter as destination of the lEntry. * FbxSemanticEntryView lDst( &lEntry, false, true ); * lDst.SetSemantic( lProp.GetName() ); * \endcode * \nosubgrouping * \see FbxOperatorEntryView, FbxBindingTableEntry, FbxPropertyEntryView */ class FBXSDK_DLL FbxBindingOperator : public FbxBindingTableBase { FBXSDK_OBJECT_DECLARE(FbxBindingOperator, FbxBindingTableBase); public: /** Run the operator on the given object. * \param pObject The object that will be evaluated. * \param pResult A pointer to a buffer to hold the result. * \return \c true on success, \c false otherwise. */ template <class FBXTYPE> bool Evaluate(const FbxObject* pObject, FBXTYPE* pResult) const { EFbxType lResultType; void* lResult = NULL; bool lSuccess = Evaluate(pObject, &lResultType, &lResult); if (lSuccess) { FbxTypeCopy(*pResult, lResult, lResultType); } FreeEvaluationResult(lResultType, lResult); return lSuccess; } /** Run the inverse operator on the given object, * assigning the result directly to the object. * \param pObject The object that will be evaluated. * \param pInOut Type of value being reversed. * \param setObj Control to set the property (only to query by the default ). * \param index Used only in FbxMultiplyDistBOF. * \return \c true on success, \c false otherwise. */ template <class FBXTYPE> bool ReverseEvaluation(const FbxObject* pObject, FBXTYPE* pInOut, bool setObj = false, int index = 0) const { const void* lIn = pInOut; void* lOut = NULL; EFbxType lOutType; bool lSuccess = ReverseEvaluate(pObject, lIn, &lOut, &lOutType, setObj, index); if (lSuccess) { FbxTypeCopy(*pInOut, lOut, lOutType); } FreeEvaluationResult(lOutType, lOut); return lSuccess; } /** Evaluate the value of an operator parameter. * \param pObject The object that will be evaluated. * \param pEntryDestinationName The name of the parameter. * This is used to get the property or operator that is related to this parameter, * then to evaluate the property or operator. * \param pResult A pointer to the result. * \return \c true on success, \c false otherwise. * \remarks This method can handle different types of entries. For property entry and constant entry, * this method will find out the property via the pEntryDestinationName and then evaluate its value; * for operator entry, this method will find out the operator via the pEntryDestinationName and * evaluate the operator function to get the property's value; for any other types of entry, this method * is meaningless. */ template <class FBXTYPE> bool EvaluateEntry(const FbxObject* pObject, const char* pEntryDestinationName, FBXTYPE* pResult) const { EFbxType lResultType; void* lResult = NULL; bool lSuccess = EvaluateEntry(pObject, pEntryDestinationName, &lResultType, &lResult); if (lSuccess) { FbxTypeCopy(*pResult, lResult, lResultType); } FreeEvaluationResult(lResultType, lResult); return lSuccess; } /** This property stores the name of function. * * Default value is "". */ FbxPropertyT<FbxString> FunctionName; /** This property stores the name of target. * * Default value is "". */ FbxPropertyT<FbxString> TargetName; ////////////////////////////////////////////////////////////////////////// // Static values ////////////////////////////////////////////////////////////////////////// //! Function name. static const char* sFunctionName; //! Target name. static const char* sTargetName; //! Default value for function name. static const char* sDefaultFunctionName; //! Default value for target name. static const char* sDefaultTargetName; ////////////////////////////////////////////////////////////////////////// // Functions ////////////////////////////////////////////////////////////////////////// /** \internal * */ static void RegisterFunctions(); /** \internal * */ static void UnregisterFunctions(); /** It represents a binding relationship between current object and the target. * Any binding operation need to specify a certain kind of binding function. * \nosubgrouping */ class FBXSDK_DLL Function { public: //!Destructor. virtual ~Function() { } /** Run the operator on the given object. * \param pOperator The operator that will be applied. * \param pObject The object that will be evaluated. * \param pResultType Will be filled by the type of the result. * \param pResult Will be filled by a pointer to a buffer that hold the result. * The caller must call FreeEvaluationResult() when it is done with this pointer. * \return \c true on success, \c false otherwise. */ virtual bool Evaluate(const FbxBindingOperator* pOperator, const FbxObject* pObject, EFbxType* pResultType, void** pResult) const = 0; /** Run the inverse operator on the given object, * assigning the result directly to the object. * \param pOperator The operator that will be applied. * \param pTarget The object that will be evaluated. * \param pIn * \param pOut * \param pOutType Type of value being reversed. * \param setObj Control to set the property (only to query by the default ). * \param index Used only in FbxMultiplyDistBOF. * \return \c true on success, \c false otherwise. */ virtual bool ReverseEvaluate(const FbxBindingOperator* pOperator, const FbxObject* pTarget, const void* pIn, void** pOut, EFbxType* pOutType, bool setObj, int index) const = 0; }; /** The abstract factory class for binding function. * \nosubgrouping */ class FBXSDK_DLL FunctionCreatorBase { public: //!Destructor. virtual ~FunctionCreatorBase() { } /** Get name of the function. * \return The name of the function. */ virtual const char* GetFunctionName() const = 0; /** Create the function. */ virtual Function* CreateFunction() const = 0; }; /** The concrete factory class for binding function. * \nosubgrouping */ template <class FUNCTION> class FunctionCreator : public FunctionCreatorBase { public: /** Get Name of the operation function. * \return The Name of the operation function. */ virtual const char* GetFunctionName() const { return FUNCTION::FunctionName; } /** Create the operation function. */ virtual Function* CreateFunction() const { return FbxNew<FUNCTION>(); } }; /** This utility class is used to register and unregister the binding function creators. * \nosubgrouping */ class FBXSDK_DLL FunctionRegistry { public: /** To register the binding function creator. * \param pCreator The binding function creator to register. */ static void RegisterFunctionCreator(FunctionCreatorBase const& pCreator) { sRegistry.Insert(pCreator.GetFunctionName(), &pCreator); } /** To unregister the binding function creator. * \param pCreator The binding function creator to unregister. */ static void UnregisterFunctionCreator(FunctionCreatorBase const& pCreator) { sRegistry.Remove(pCreator.GetFunctionName()); } /** To find the binding function creator by name. * \param pName The name of the operation function creator to find. */ static const FunctionCreatorBase* FindCreator(const char* pName) { RegistryType::RecordType* lRecord = sRegistry.Find(pName); if (lRecord) { return lRecord->GetValue(); } else { return NULL; } } private: typedef FbxMap<const char*, const FunctionCreatorBase*, FbxCharPtrCompare> RegistryType; static RegistryType sRegistry; }; /***************************************************************************************************************************** ** WARNING! Anything beyond these lines is for internal use, may not be documented and is subject to change without notice! ** *****************************************************************************************************************************/ #ifndef DOXYGEN_SHOULD_SKIP_THIS bool EvaluateEntry(const FbxObject* pObject, const char* pEntryDestinationName, EFbxType* pResultType, void** pResult) const; bool GetEntryProperty(const FbxObject* pObject, const char* pEntryDestinationName, FbxProperty& pProp) const; protected: virtual void Construct(const FbxObject* pFrom); virtual void Destruct(bool pRecursive); virtual void ConstructProperties(bool pForceSet); void InstantiateFunction(); bool Evaluate(const FbxObject* pObject, EFbxType* pResultType, void** pResult) const; bool ReverseEvaluate(const FbxObject* pTarget, const void* pIn, void** pOut, EFbxType* pOutType, bool setObj, int index) const; void FreeEvaluationResult(EFbxType pResultType, void* pResult) const; Function* mFunction; #endif /* !DOXYGEN_SHOULD_SKIP_THIS *****************************************************************************************/ }; /** An evaluation operator to get the position of the node that is bound with this operator via a certain property. * The position of the node is represented by translation. */ class FbxNodePositionBOF : public FbxBindingOperator::Function { public: //! Name of the operation function. static const char* FunctionName; /** Evaluate the position of the node that is bound with this operator via a certain property. * The position of the node is represented by translation. * * \param pOperator Operator running on the object. * \param pObject The object that will be evaluated. * \param pResultType The type of the result to be returned, eFbxDouble4 in this case. * \param pResult A pointer to a buffer that can hold the result. * \return \c true on success, \c false otherwise. */ virtual bool Evaluate(const FbxBindingOperator* pOperator, const FbxObject* pObject, EFbxType* pResultType, void** pResult) const; //! Inverse evaluation for this binding function is not implemented yet. virtual bool ReverseEvaluate(const FbxBindingOperator* pOperator, const FbxObject* pTarget, const void* pIn, void** pOut, EFbxType* pOutType, bool setObj, int index) const; /***************************************************************************************************************************** ** WARNING! Anything beyond these lines is for internal use, may not be documented and is subject to change without notice! ** *****************************************************************************************************************************/ #ifndef DOXYGEN_SHOULD_SKIP_THIS FbxNodePositionBOF(); virtual ~FbxNodePositionBOF(); #endif /* !DOXYGEN_SHOULD_SKIP_THIS *****************************************************************************************/ }; /** An evaluation operator to get the direction of the node that is bound with this operator via a certain property. * The direction of the node is represented by Euler rotation. */ class FbxNodeDirectionBOF : public FbxBindingOperator::Function { public: //! Name of the operation function. static const char* FunctionName; /** Evaluate the direction of the node that is bound with this operator via a certain property. * The direction of the node is represented by Euler rotation. * * \param pOperator Operator running on the object. * \param pObject The object that will be evaluated. * \param pResultType The type of the result to be returned, eFbxDouble4 in this case. * \param pResult A pointer to a buffer that can hold the result. * \return \c true on success, \c false otherwise. */ virtual bool Evaluate(const FbxBindingOperator* pOperator, const FbxObject* pObject, EFbxType* pResultType, void** pResult) const; //! Inverse evaluation for this binding function is not implemented yet. virtual bool ReverseEvaluate(const FbxBindingOperator* pOperator, const FbxObject* pTarget, const void* pIn, void** pOut, EFbxType* pOutType, bool setObj, int index) const; /***************************************************************************************************************************** ** WARNING! Anything beyond these lines is for internal use, may not be documented and is subject to change without notice! ** *****************************************************************************************************************************/ #ifndef DOXYGEN_SHOULD_SKIP_THIS FbxNodeDirectionBOF(); virtual ~FbxNodeDirectionBOF(); #endif /* !DOXYGEN_SHOULD_SKIP_THIS *****************************************************************************************/ }; /** A pass through operator used to assign constants to parameters. */ class FbxAssignBOF : public FbxBindingOperator::Function { public: //! Name of the operation function. static const char* FunctionName; /** Evaluates the object property specified by "X" and returns it. * \param pOperator Operator running on the object. * \param pObject The object that will be evaluated. * \param pResultType Will be filled by the type of the result. * \param pResult Will be filled by a pointer to a buffer that hold the result. */ virtual bool Evaluate(const FbxBindingOperator* pOperator, const FbxObject* pObject, EFbxType* pResultType, void** pResult) const; //! Inverse evaluation for this binding function is not implemented yet. virtual bool ReverseEvaluate(const FbxBindingOperator* pOperator, const FbxObject* pTarget, const void* pIn, void** pOut, EFbxType* pOutType, bool setObj, int index) const; /***************************************************************************************************************************** ** WARNING! Anything beyond these lines is for internal use, may not be documented and is subject to change without notice! ** *****************************************************************************************************************************/ #ifndef DOXYGEN_SHOULD_SKIP_THIS FbxAssignBOF(); virtual ~FbxAssignBOF(); #endif /* !DOXYGEN_SHOULD_SKIP_THIS *****************************************************************************************/ }; /** A conditional operator that outputs one out of two properties, based on * the value of a predicate property. */ class FbxConditionalBOF : public FbxBindingOperator::Function { public: //! Name of the operation function. static const char* FunctionName; /** Evaluates the object property specified by "predicate". * If the property value is true (!= 0, != ""), returns the value of the * property specified by "ifTrue", else returns the value of the property * specified by "ifFalse". * * Currently the data types supported for the input property are * limited to "integer", "boolean", "float", "double" and "string". * \param pOperator Operator running on the object. * \param pObject The object that will be evaluated. * \param pResultType The type of the result to be returned. * \param pResult A pointer to a buffer that can hold the result. * \return \c true on success, \c false otherwise. */ virtual bool Evaluate(const FbxBindingOperator* pOperator, const FbxObject* pObject, EFbxType* pResultType, void** pResult) const; virtual bool ReverseEvaluate(const FbxBindingOperator* pOperator, const FbxObject* pTarget, const void* pIn, void** pOut, EFbxType* pOutType, bool setObj, int index) const; /***************************************************************************************************************************** ** WARNING! Anything beyond these lines is for internal use, may not be documented and is subject to change without notice! ** *****************************************************************************************************************************/ #ifndef DOXYGEN_SHOULD_SKIP_THIS FbxConditionalBOF(); virtual ~FbxConditionalBOF(); #endif /* !DOXYGEN_SHOULD_SKIP_THIS *****************************************************************************************/ }; /** A switch operator that outputs one out of n properties, based on * the value of a predicate property. */ class FbxSwitchBOF : public FbxBindingOperator::Function { public: //! Name of the operation function. static const char* FunctionName; /** Evaluates the object property specified by "predicate". * Returns the value of the property specified by "case_n", where n * is the value of "predicate". If there is no case_n entry, returns * the value of the property specified by "default". * * Currently the data types supported for the predicate property are * limited to "integer" and "boolean". * \param pOperator Operator running on the object. * \param pObject The object that will be evaluated. * \param pResultType The type of the result to be returned. * \param pResult A pointer to a buffer that can hold the result. * \return \c true on success, \c false otherwise. */ virtual bool Evaluate(const FbxBindingOperator* pOperator, const FbxObject* pObject, EFbxType* pResultType, void** pResult) const; virtual bool ReverseEvaluate(const FbxBindingOperator* pOperator, const FbxObject* pTarget, const void* pIn, void** pOut, EFbxType* pOutType, bool setObj, int index) const; /***************************************************************************************************************************** ** WARNING! Anything beyond these lines is for internal use, may not be documented and is subject to change without notice! ** *****************************************************************************************************************************/ #ifndef DOXYGEN_SHOULD_SKIP_THIS FbxSwitchBOF(); virtual ~FbxSwitchBOF(); #endif /* !DOXYGEN_SHOULD_SKIP_THIS *****************************************************************************************/ }; class FbxTRSToMatrixBOF : public FbxBindingOperator::Function { public: //! Name of the operation function. static const char* FunctionName; /** Evaluates the object properties specified by "T", "R" and "S" and * return a transform matrix. * * \param pOperator Operator running on the object. * \param pObject The object that will be evaluated. * \param pResultType The type of the result to be returned. * \param pResult A pointer to a buffer that can hold the result. * \return \c true on success, \c false otherwise. */ virtual bool Evaluate(const FbxBindingOperator* pOperator, const FbxObject* pObject, EFbxType* pResultType, void** pResult) const; virtual bool ReverseEvaluate(const FbxBindingOperator* pOperator, const FbxObject* pTarget, const void* pIn, void** pOut, EFbxType* pOutType, bool setObj, int index) const; /***************************************************************************************************************************** ** WARNING! Anything beyond these lines is for internal use, may not be documented and is subject to change without notice! ** *****************************************************************************************************************************/ #ifndef DOXYGEN_SHOULD_SKIP_THIS FbxTRSToMatrixBOF(); virtual ~FbxTRSToMatrixBOF(); #endif /* !DOXYGEN_SHOULD_SKIP_THIS *****************************************************************************************/ }; class FbxAddBOF : public FbxBindingOperator::Function { public: //! Name of the operation function. static const char* FunctionName; /** Evaluates the object properties specified by "X" and "Y" * return X+Y as a float. * * \param pOperator Operator running on the object. * \param pObject The object that will be evaluated. * \param pResultType The type of the result to be returned. * \param pResult A pointer to a buffer that can hold the result. * \return \c true on success, \c false otherwise. */ virtual bool Evaluate(const FbxBindingOperator* pOperator, const FbxObject* pObject, EFbxType* pResultType, void** pResult) const; virtual bool ReverseEvaluate(const FbxBindingOperator* pOperator, const FbxObject* pTarget, const void* pIn, void** pOut, EFbxType* pOutType, bool setObj, int index) const; /***************************************************************************************************************************** ** WARNING! Anything beyond these lines is for internal use, may not be documented and is subject to change without notice! ** *****************************************************************************************************************************/ #ifndef DOXYGEN_SHOULD_SKIP_THIS FbxAddBOF(); virtual ~FbxAddBOF(); #endif /* !DOXYGEN_SHOULD_SKIP_THIS *****************************************************************************************/ }; class FbxSubstractBOF : public FbxBindingOperator::Function { public: //! Name of the operation function. static const char* FunctionName; /** Evaluates the object properties specified by "X" and "Y" * return X-Y as a float. * * \param pOperator Operator running on the object. * \param pObject The object that will be evaluated. * \param pResultType The type of the result to be returned. * \param pResult A pointer to a buffer that can hold the result. * \return \c true on success, \c false otherwise. */ virtual bool Evaluate(const FbxBindingOperator* pOperator, const FbxObject* pObject, EFbxType* pResultType, void** pResult) const; virtual bool ReverseEvaluate(const FbxBindingOperator* pOperator, const FbxObject* pTarget, const void* pIn, void** pOut, EFbxType* pOutType, bool setObj, int index) const; /***************************************************************************************************************************** ** WARNING! Anything beyond these lines is for internal use, may not be documented and is subject to change without notice! ** *****************************************************************************************************************************/ #ifndef DOXYGEN_SHOULD_SKIP_THIS FbxSubstractBOF(); virtual ~FbxSubstractBOF(); #endif /* !DOXYGEN_SHOULD_SKIP_THIS *****************************************************************************************/ }; class FbxMultiplyBOF : public FbxBindingOperator::Function { public: //! Name of the operation function. static const char* FunctionName; /** Evaluates the object properties specified by "X" and "Y" * return X*Y as a float. * * \param pOperator Operator running on the object. * \param pObject The object that will be evaluated. * \param pResultType The type of the result to be returned. * \param pResult A pointer to a buffer that can hold the result. * \return \c true on success, \c false otherwise. */ virtual bool Evaluate(const FbxBindingOperator* pOperator, const FbxObject* pObject, EFbxType* pResultType, void** pResult) const; //Set index to 1 to get realWorldScale. virtual bool ReverseEvaluate(const FbxBindingOperator* pOperator, const FbxObject* pTarget, const void* pIn, void** pOut, EFbxType* pOutType, bool setObj, int index) const; /***************************************************************************************************************************** ** WARNING! Anything beyond these lines is for internal use, may not be documented and is subject to change without notice! ** *****************************************************************************************************************************/ #ifndef DOXYGEN_SHOULD_SKIP_THIS FbxMultiplyBOF(); virtual ~FbxMultiplyBOF(); #endif /* !DOXYGEN_SHOULD_SKIP_THIS *****************************************************************************************/ }; class FbxMultiplyDistBOF : public FbxBindingOperator::Function { public: //! Name of the operation function. static const char* FunctionName; /** Evaluates the object properties specified by "X" and "Y" * return X*Y as a float. * * \param pOperator Operator running on the object. * \param pObject The object that will be evaluated. * \param pResultType The type of the result to be returned. * \param pResult A pointer to a buffer that can hold the result. * \return \c true on success, \c false otherwise. */ virtual bool Evaluate(const FbxBindingOperator* pOperator, const FbxObject* pObject, EFbxType* pResultType, void** pResult) const; virtual bool ReverseEvaluate(const FbxBindingOperator* pOperator, const FbxObject* pTarget, const void* pIn, void** pOut, EFbxType* pOutType, bool setObj, int index) const; /***************************************************************************************************************************** ** WARNING! Anything beyond these lines is for internal use, may not be documented and is subject to change without notice! ** *****************************************************************************************************************************/ #ifndef DOXYGEN_SHOULD_SKIP_THIS FbxMultiplyDistBOF(); virtual ~FbxMultiplyDistBOF(); #endif /* !DOXYGEN_SHOULD_SKIP_THIS *****************************************************************************************/ }; class FbxOneOverXBOF : public FbxBindingOperator::Function { public: //! Name of the operation function. static const char* FunctionName; /** Evaluates the object properties specified by "X" * return 1/X as a float. * * \param pOperator Operator running on the object. * \param pObject The object that will be evaluated. * \param pResultType The type of the result to be returned. * \param pResult A pointer to a buffer that can hold the result. * \return \c true on success, \c false otherwise. */ virtual bool Evaluate(const FbxBindingOperator* pOperator, const FbxObject* pObject, EFbxType* pResultType, void** pResult) const; virtual bool ReverseEvaluate(const FbxBindingOperator* pOperator, const FbxObject* pTarget, const void* pIn, void** pOut, EFbxType* pOutType, bool setObj, int index) const; /***************************************************************************************************************************** ** WARNING! Anything beyond these lines is for internal use, may not be documented and is subject to change without notice! ** *****************************************************************************************************************************/ #ifndef DOXYGEN_SHOULD_SKIP_THIS FbxOneOverXBOF(); virtual ~FbxOneOverXBOF(); #endif /* !DOXYGEN_SHOULD_SKIP_THIS *****************************************************************************************/ }; class FbxPowerBOF : public FbxBindingOperator::Function { public: //! Name of the operation function. static const char* FunctionName; /** Evaluates the object properties specified by "X" and "Y" * return X^Y as a float. * * \param pOperator Operator running on the object. * \param pObject The object that will be evaluated. * \param pResultType The type of the result to be returned. * \param pResult A pointer to a buffer that can hold the result. * \return \c true on success, \c false otherwise. */ virtual bool Evaluate(const FbxBindingOperator* pOperator, const FbxObject* pObject, EFbxType* pResultType, void** pResult) const; virtual bool ReverseEvaluate(const FbxBindingOperator* pOperator, const FbxObject* pTarget, const void* pIn, void** pOut, EFbxType* pOutType, bool setObj, int index) const; /***************************************************************************************************************************** ** WARNING! Anything beyond these lines is for internal use, may not be documented and is subject to change without notice! ** *****************************************************************************************************************************/ #ifndef DOXYGEN_SHOULD_SKIP_THIS FbxPowerBOF(); virtual ~FbxPowerBOF(); #endif /* !DOXYGEN_SHOULD_SKIP_THIS *****************************************************************************************/ }; class FbxDegreeToRadianBOF : public FbxBindingOperator::Function { public: //! Name of the operation function. static const char* FunctionName; /** Evaluates the object property specified by "X" * return X converted to radian as a float. * * \param pOperator Operator running on the object. * \param pObject The object that will be evaluated. * \param pResultType The type of the result to be returned. * \param pResult A pointer to a buffer that can hold the result. * \return \c true on success, \c false otherwise. */ virtual bool Evaluate(const FbxBindingOperator* pOperator, const FbxObject* pObject, EFbxType* pResultType, void** pResult) const; virtual bool ReverseEvaluate(const FbxBindingOperator* pOperator, const FbxObject* pTarget, const void* pIn, void** pOut, EFbxType* pOutType, bool setObj, int index) const; /***************************************************************************************************************************** ** WARNING! Anything beyond these lines is for internal use, may not be documented and is subject to change without notice! ** *****************************************************************************************************************************/ #ifndef DOXYGEN_SHOULD_SKIP_THIS FbxDegreeToRadianBOF(); virtual ~FbxDegreeToRadianBOF(); #endif /* !DOXYGEN_SHOULD_SKIP_THIS *****************************************************************************************/ }; class FbxVectorDegreeToVectorRadianBOF : public FbxBindingOperator::Function { public: //! Name of the operation function. static const char* FunctionName; /** Evaluates the object property specified by "X" * return X converted to radian as a vector3. * * \param pOperator Operator running on the object. * \param pObject The object that will be evaluated. * \param pResultType The type of the result to be returned. * \param pResult A pointer to a buffer that can hold the result. * \return \c true on success, \c false otherwise. */ virtual bool Evaluate(const FbxBindingOperator* pOperator, const FbxObject* pObject, EFbxType* pResultType, void** pResult) const; virtual bool ReverseEvaluate(const FbxBindingOperator* pOperator, const FbxObject* pTarget, const void* pIn, void** pOut, EFbxType* pOutType, bool setObj, int index) const; /***************************************************************************************************************************** ** WARNING! Anything beyond these lines is for internal use, may not be documented and is subject to change without notice! ** *****************************************************************************************************************************/ #ifndef DOXYGEN_SHOULD_SKIP_THIS FbxVectorDegreeToVectorRadianBOF(); virtual ~FbxVectorDegreeToVectorRadianBOF(); #endif /* !DOXYGEN_SHOULD_SKIP_THIS *****************************************************************************************/ }; class FbxSphericalToCartesianBOF : public FbxBindingOperator::Function { public: //! Name of the operation function. static const char* FunctionName; /** Evaluates the object property specified by "rho", "theta" and "phi" * return the converted Cartesian coordinates as a double3. * * \param pOperator Operator running on the object. * \param pObject The object that will be evaluated. * \param pResultType The type of the result to be returned. * \param pResult A pointer to a buffer that can hold the result. * \return \c true on success, \c false otherwise. */ virtual bool Evaluate(const FbxBindingOperator* pOperator, const FbxObject* pObject, EFbxType* pResultType, void** pResult) const; virtual bool ReverseEvaluate(const FbxBindingOperator* pOperator, const FbxObject* pTarget, const void* pIn, void** pOut, EFbxType* pOutType, bool setObj, int index) const; /***************************************************************************************************************************** ** WARNING! Anything beyond these lines is for internal use, may not be documented and is subject to change without notice! ** *****************************************************************************************************************************/ #ifndef DOXYGEN_SHOULD_SKIP_THIS FbxSphericalToCartesianBOF(); virtual ~FbxSphericalToCartesianBOF(); #endif /* !DOXYGEN_SHOULD_SKIP_THIS *****************************************************************************************/ }; class FbxIsYupBOF : public FbxBindingOperator::Function { public: //! Name of the operation function. static const char* FunctionName; /** Check if the scene coordinate system is y-up * return a bool. * * \param pOperator Operator running on the object. * \param pObject The object that will be evaluated. * \param pResultType The type of the result to be returned. * \param pResult A pointer to a buffer that can hold the result. * \return \c true on success, \c false otherwise. */ virtual bool Evaluate(const FbxBindingOperator* pOperator, const FbxObject* pObject, EFbxType* pResultType, void** pResult) const; virtual bool ReverseEvaluate(const FbxBindingOperator* pOperator, const FbxObject* pTarget, const void* pIn, void** pOut, EFbxType* pOutType, bool setObj, int index) const; /***************************************************************************************************************************** ** WARNING! Anything beyond these lines is for internal use, may not be documented and is subject to change without notice! ** *****************************************************************************************************************************/ #ifndef DOXYGEN_SHOULD_SKIP_THIS FbxIsYupBOF(); virtual ~FbxIsYupBOF(); #endif /* !DOXYGEN_SHOULD_SKIP_THIS *****************************************************************************************/ }; /** A symbol(string) operator that search the string table and return its corresponding unique id, based on * the value of a predicate property. */ class FbxSymbolIDBOF : public FbxBindingOperator::Function { public: //! Name of the operation function. static const char* FunctionName; /** Check in the symbol table the string and returns its unique ID as an integer * * \param pOperator Operator running on the object. * \param pObject The object that will be evaluated. * \param pResultType The type of the result to be returned. * \param pResult A pointer to a buffer that can hold the result. * \return \c true on success, \c false otherwise. */ virtual bool Evaluate(const FbxBindingOperator* pOperator, const FbxObject* pObject, EFbxType* pResultType, void** pResult) const; virtual bool ReverseEvaluate(const FbxBindingOperator* pOperator, const FbxObject* pTarget, const void* pIn, void** pOut, EFbxType* pOutType, bool setObj, int index) const; /***************************************************************************************************************************** ** WARNING! Anything beyond these lines is for internal use, may not be documented and is subject to change without notice! ** *****************************************************************************************************************************/ #ifndef DOXYGEN_SHOULD_SKIP_THIS FbxSymbolIDBOF(); virtual ~FbxSymbolIDBOF(); #endif /* !DOXYGEN_SHOULD_SKIP_THIS *****************************************************************************************/ }; /** A chooser operator that check spot distribution and returns the correct value, based on * the value of a predicate property. */ class FbxSpotDistributionChooserBOF : public FbxBindingOperator::Function { public: //! Name of the operation function. static const char* FunctionName; /** Check the enum of the spot distribution and returns the correct value * as an int. * * \param pOperator Operator running on the object. * \param pObject The object that will be evaluated. * \param pResultType The type of the result to be returned. * \param pResult A pointer to a buffer that can hold the result. * \return \c true on success, \c false otherwise. */ virtual bool Evaluate(const FbxBindingOperator* pOperator, const FbxObject* pObject, EFbxType* pResultType, void** pResult) const; //! Inverse evaluation for this binding function is not implemented yet. virtual bool ReverseEvaluate(const FbxBindingOperator* pOperator, const FbxObject* pTarget, const void* pIn, void** pOut, EFbxType* pOutType, bool setObj, int index) const; /***************************************************************************************************************************** ** WARNING! Anything beyond these lines is for internal use, may not be documented and is subject to change without notice! ** *****************************************************************************************************************************/ #ifndef DOXYGEN_SHOULD_SKIP_THIS FbxSpotDistributionChooserBOF(); virtual ~FbxSpotDistributionChooserBOF(); #endif /* !DOXYGEN_SHOULD_SKIP_THIS *****************************************************************************************/ }; #include <fbxsdk/fbxsdk_nsend.h> #endif /* _FBXSDK_SCENE_SHADING_BINDING_OPERATOR_H_ */
[ "m_molokovskih@wargaming.net" ]
m_molokovskih@wargaming.net
18c9a1203875cf66ff0c6a968395ad1700313aa1
e9854cb02e90dab7ec0a49c65f658babba819d56
/Curve Editor Framework/QT/src/corelib/thread/qatomic.cpp
fae8a255b36dfbeee50854aded77c383b01f9789
[]
no_license
katzeforest/Computer-Animation
2bbb1df374d65240ca2209b3a75a0b6a8b99ad58
01481111a622ae8812fb0b76550f5d66de206bab
refs/heads/master
2021-01-23T19:46:13.455834
2015-06-08T21:29:02
2015-06-08T21:29:02
37,092,780
1
1
null
null
null
null
UTF-8
C++
false
false
38,209
cpp
/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ /*! \class QAtomicInt \brief The QAtomicInt class provides platform-independent atomic operations on integers. \since 4.4 \ingroup thread For atomic operations on pointers, see the QAtomicPointer class. An \e atomic operation is a complex operation that completes without interruption. The QAtomicInt class provides atomic reference counting, test-and-set, fetch-and-store, and fetch-and-add for integers. \section1 Non-atomic convenience operators For convenience, QAtomicInt provides integer comparison, cast, and assignment operators. Note that a combination of these operators is \e not an atomic operation. \section1 The Atomic API \section2 Reference counting The ref() and deref() functions provide an efficient reference counting API. The return value of these functions are used to indicate when the last reference has been released. These functions allow you to implement your own implicitly shared classes. \snippet doc/src/snippets/code/src_corelib_thread_qatomic.cpp 0 \section2 Memory ordering QAtomicInt provides several implementations of the atomic test-and-set, fetch-and-store, and fetch-and-add functions. Each implementation defines a memory ordering semantic that describes how memory accesses surrounding the atomic instruction are executed by the processor. Since many modern architectures allow out-of-order execution and memory ordering, using the correct semantic is necessary to ensure that your application functions properly on all processors. \list \o Relaxed - memory ordering is unspecified, leaving the compiler and processor to freely reorder memory accesses. \o Acquire - memory access following the atomic operation (in program order) may not be re-ordered before the atomic operation. \o Release - memory access before the atomic operation (in program order) may not be re-ordered after the atomic operation. \o Ordered - the same Acquire and Release semantics combined. \endlist \section2 Test-and-set If the current value of the QAtomicInt is an expected value, the test-and-set functions assign a new value to the QAtomicInt and return true. If values are \a not the same, these functions do nothing and return false. This operation equates to the following code: \snippet doc/src/snippets/code/src_corelib_thread_qatomic.cpp 1 There are 4 test-and-set functions: testAndSetRelaxed(), testAndSetAcquire(), testAndSetRelease(), and testAndSetOrdered(). See above for an explanation of the different memory ordering semantics. \section2 Fetch-and-store The atomic fetch-and-store functions read the current value of the QAtomicInt and then assign a new value, returning the original value. This operation equates to the following code: \snippet doc/src/snippets/code/src_corelib_thread_qatomic.cpp 2 There are 4 fetch-and-store functions: fetchAndStoreRelaxed(), fetchAndStoreAcquire(), fetchAndStoreRelease(), and fetchAndStoreOrdered(). See above for an explanation of the different memory ordering semantics. \section2 Fetch-and-add The atomic fetch-and-add functions read the current value of the QAtomicInt and then add the given value to the current value, returning the original value. This operation equates to the following code: \snippet doc/src/snippets/code/src_corelib_thread_qatomic.cpp 3 There are 4 fetch-and-add functions: fetchAndAddRelaxed(), fetchAndAddAcquire(), fetchAndAddRelease(), and fetchAndAddOrdered(). See above for an explanation of the different memory ordering semantics. \section1 Feature Tests for the Atomic API Providing a platform-independent atomic API that works on all processors is challenging. The API provided by QAtomicInt is guaranteed to work atomically on all processors. However, since not all processors implement support for every operation provided by QAtomicInt, it is necessary to expose information about the processor. You can check at compile time which features are supported on your hardware using various macros. These will tell you if your hardware always, sometimes, or does not support a particular operation. The macros have the form Q_ATOMIC_INT_\e{OPERATION}_IS_\e{HOW}_NATIVE. \e{OPERATION} is one of REFERENCE_COUNTING, TEST_AND_SET, FETCH_AND_STORE, or FETCH_AND_ADD, and \e{HOW} is one of ALWAYS, SOMETIMES, or NOT. There will always be exactly one defined macro per operation. For example, if Q_ATOMIC_INT_REFERENCE_COUNTING_IS_ALWAYS_NATIVE is defined, neither Q_ATOMIC_INT_REFERENCE_COUNTING_IS_SOMETIMES_NATIVE nor Q_ATOMIC_INT_REFERENCE_COUNTING_IS_NOT_NATIVE will be defined. An operation that completes in constant time is said to be wait-free. Such operations are not implemented using locks or loops of any kind. For atomic operations that are always supported, and that are wait-free, Qt defines the Q_ATOMIC_INT_\e{OPERATION}_IS_WAIT_FREE in addition to the Q_ATOMIC_INT_\e{OPERATION}_IS_ALWAYS_NATIVE. In cases where an atomic operation is only supported in newer generations of the processor, QAtomicInt also provides a way to check at runtime what your hardware supports with the isReferenceCountingNative(), isTestAndSetNative(), isFetchAndStoreNative(), and isFetchAndAddNative() functions. Wait-free implementations can be detected using the isReferenceCountingWaitFree(), isTestAndSetWaitFree(), isFetchAndStoreWaitFree(), and isFetchAndAddWaitFree() functions. Below is a complete list of all feature macros for QAtomicInt: \list \o Q_ATOMIC_INT_REFERENCE_COUNTING_IS_ALWAYS_NATIVE \o Q_ATOMIC_INT_REFERENCE_COUNTING_IS_SOMETIMES_NATIVE \o Q_ATOMIC_INT_REFERENCE_COUNTING_IS_NOT_NATIVE \o Q_ATOMIC_INT_REFERENCE_COUNTING_IS_WAIT_FREE \o Q_ATOMIC_INT_TEST_AND_SET_IS_ALWAYS_NATIVE \o Q_ATOMIC_INT_TEST_AND_SET_IS_SOMETIMES_NATIVE \o Q_ATOMIC_INT_TEST_AND_SET_IS_NOT_NATIVE \o Q_ATOMIC_INT_TEST_AND_SET_IS_WAIT_FREE \o Q_ATOMIC_INT_FETCH_AND_STORE_IS_ALWAYS_NATIVE \o Q_ATOMIC_INT_FETCH_AND_STORE_IS_SOMETIMES_NATIVE \o Q_ATOMIC_INT_FETCH_AND_STORE_IS_NOT_NATIVE \o Q_ATOMIC_INT_FETCH_AND_STORE_IS_WAIT_FREE \o Q_ATOMIC_INT_FETCH_AND_ADD_IS_ALWAYS_NATIVE \o Q_ATOMIC_INT_FETCH_AND_ADD_IS_SOMETIMES_NATIVE \o Q_ATOMIC_INT_FETCH_AND_ADD_IS_NOT_NATIVE \o Q_ATOMIC_INT_FETCH_AND_ADD_IS_WAIT_FREE \endlist \sa QAtomicPointer */ /*! \fn QAtomicInt::QAtomicInt(int value) Constructs a QAtomicInt with the given \a value. */ /*! \fn QAtomicInt::QAtomicInt(const QAtomicInt &other) Constructs a copy of \a other. */ /*! \fn QAtomicInt &QAtomicInt::operator=(int value) Assigns the \a value to this QAtomicInt and returns a reference to this QAtomicInt. */ /*! \fn QAtomicInt &QAtomicInt::operator=(const QAtomicInt &other) Assigns \a other to this QAtomicInt and returns a reference to this QAtomicInt. */ /*! \fn bool QAtomicInt::operator==(int value) const Returns true if the \a value is equal to the value in this QAtomicInt; otherwise returns false. */ /*! \fn bool QAtomicInt::operator!=(int value) const Returns true if the value of this QAtomicInt is not equal to \a value; otherwise returns false. */ /*! \fn bool QAtomicInt::operator!() const Returns true is the value of this QAtomicInt is zero; otherwise returns false. */ /*! \fn QAtomicInt::operator int() const Returns the value stored by the QAtomicInt object as an integer. */ /*! \fn bool QAtomicInt::isReferenceCountingNative() Returns true if reference counting is implemented using atomic processor instructions, false otherwise. */ /*! \fn bool QAtomicInt::isReferenceCountingWaitFree() Returns true if atomic reference counting is wait-free, false otherwise. */ /*! \fn bool QAtomicInt::ref() Atomically increments the value of this QAtomicInt. Returns true if the new value is non-zero, false otherwise. This function uses \e ordered \l {QAtomicInt#Memory ordering}{memory ordering} semantics, which ensures that memory access before and after the atomic operation (in program order) may not be re-ordered. \sa deref() */ /*! \fn bool QAtomicInt::deref() Atomically decrements the value of this QAtomicInt. Returns true if the new value is non-zero, false otherwise. This function uses \e ordered \l {QAtomicInt#Memory ordering}{memory ordering} semantics, which ensures that memory access before and after the atomic operation (in program order) may not be re-ordered. \sa ref() */ /*! \fn bool QAtomicInt::isTestAndSetNative() Returns true if test-and-set is implemented using atomic processor instructions, false otherwise. */ /*! \fn bool QAtomicInt::isTestAndSetWaitFree() Returns true if atomic test-and-set is wait-free, false otherwise. */ /*! \fn bool QAtomicInt::testAndSetRelaxed(int expectedValue, int newValue) Atomic test-and-set. If the current value of this QAtomicInt is the \a expectedValue, the test-and-set functions assign the \a newValue to this QAtomicInt and return true. If the values are \e not the same, this function does nothing and returns false. This function uses \e relaxed \l {QAtomicInt#Memory ordering}{memory ordering} semantics, leaving the compiler and processor to freely reorder memory accesses. */ /*! \fn bool QAtomicInt::testAndSetAcquire(int expectedValue, int newValue) Atomic test-and-set. If the current value of this QAtomicInt is the \a expectedValue, the test-and-set functions assign the \a newValue to this QAtomicInt and return true. If the values are \e not the same, this function does nothing and returns false. This function uses \e acquire \l {QAtomicInt#Memory ordering}{memory ordering} semantics, which ensures that memory access following the atomic operation (in program order) may not be re-ordered before the atomic operation. */ /*! \fn bool QAtomicInt::testAndSetRelease(int expectedValue, int newValue) Atomic test-and-set. If the current value of this QAtomicInt is the \a expectedValue, the test-and-set functions assign the \a newValue to this QAtomicInt and return true. If the values are \e not the same, this function does nothing and returns false. This function uses \e release \l {QAtomicInt#Memory ordering}{memory ordering} semantics, which ensures that memory access before the atomic operation (in program order) may not be re-ordered after the atomic operation. */ /*! \fn bool QAtomicInt::testAndSetOrdered(int expectedValue, int newValue) Atomic test-and-set. If the current value of this QAtomicInt is the \a expectedValue, the test-and-set functions assign the \a newValue to this QAtomicInt and return true. If the values are \e not the same, this function does nothing and returns false. This function uses \e ordered \l {QAtomicInt#Memory ordering}{memory ordering} semantics, which ensures that memory access before and after the atomic operation (in program order) may not be re-ordered. */ /*! \fn bool QAtomicInt::isFetchAndStoreNative() Returns true if fetch-and-store is implemented using atomic processor instructions, false otherwise. */ /*! \fn bool QAtomicInt::isFetchAndStoreWaitFree() Returns true if atomic fetch-and-store is wait-free, false otherwise. */ /*! \fn int QAtomicInt::fetchAndStoreRelaxed(int newValue) Atomic fetch-and-store. Reads the current value of this QAtomicInt and then assigns it the \a newValue, returning the original value. This function uses \e relaxed \l {QAtomicInt#Memory ordering}{memory ordering} semantics, leaving the compiler and processor to freely reorder memory accesses. */ /*! \fn int QAtomicInt::fetchAndStoreAcquire(int newValue) Atomic fetch-and-store. Reads the current value of this QAtomicInt and then assigns it the \a newValue, returning the original value. This function uses \e acquire \l {QAtomicInt#Memory ordering}{memory ordering} semantics, which ensures that memory access following the atomic operation (in program order) may not be re-ordered before the atomic operation. */ /*! \fn int QAtomicInt::fetchAndStoreRelease(int newValue) Atomic fetch-and-store. Reads the current value of this QAtomicInt and then assigns it the \a newValue, returning the original value. This function uses \e release \l {QAtomicInt#Memory ordering}{memory ordering} semantics, which ensures that memory access before the atomic operation (in program order) may not be re-ordered after the atomic operation. */ /*! \fn int QAtomicInt::fetchAndStoreOrdered(int newValue) Atomic fetch-and-store. Reads the current value of this QAtomicInt and then assigns it the \a newValue, returning the original value. This function uses \e ordered \l {QAtomicInt#Memory ordering}{memory ordering} semantics, which ensures that memory access before and after the atomic operation (in program order) may not be re-ordered. */ /*! \fn bool QAtomicInt::isFetchAndAddNative() Returns true if fetch-and-add is implemented using atomic processor instructions, false otherwise. */ /*! \fn bool QAtomicInt::isFetchAndAddWaitFree() Returns true if atomic fetch-and-add is wait-free, false otherwise. */ /*! \fn int QAtomicInt::fetchAndAddRelaxed(int valueToAdd) Atomic fetch-and-add. Reads the current value of this QAtomicInt and then adds \a valueToAdd to the current value, returning the original value. This function uses \e relaxed \l {QAtomicInt#Memory ordering}{memory ordering} semantics, leaving the compiler and processor to freely reorder memory accesses. */ /*! \fn int QAtomicInt::fetchAndAddAcquire(int valueToAdd) Atomic fetch-and-add. Reads the current value of this QAtomicInt and then adds \a valueToAdd to the current value, returning the original value. This function uses \e acquire \l {QAtomicInt#Memory ordering}{memory ordering} semantics, which ensures that memory access following the atomic operation (in program order) may not be re-ordered before the atomic operation. */ /*! \fn int QAtomicInt::fetchAndAddRelease(int valueToAdd) Atomic fetch-and-add. Reads the current value of this QAtomicInt and then adds \a valueToAdd to the current value, returning the original value. This function uses \e release \l {QAtomicInt#Memory ordering}{memory ordering} semantics, which ensures that memory access before the atomic operation (in program order) may not be re-ordered after the atomic operation. */ /*! \fn int QAtomicInt::fetchAndAddOrdered(int valueToAdd) Atomic fetch-and-add. Reads the current value of this QAtomicInt and then adds \a valueToAdd to the current value, returning the original value. This function uses \e ordered \l {QAtomicInt#Memory ordering}{memory ordering} semantics, which ensures that memory access before and after the atomic operation (in program order) may not be re-ordered. */ /*! \macro Q_ATOMIC_INT_REFERENCE_COUNTING_IS_ALWAYS_NATIVE \relates QAtomicInt This macro is defined if and only if all generations of your processor support atomic reference counting. */ /*! \macro Q_ATOMIC_INT_REFERENCE_COUNTING_IS_SOMETIMES_NATIVE \relates QAtomicInt This macro is defined when only certain generations of the processor support atomic reference counting. Use the QAtomicInt::isReferenceCountingNative() function to check what your processor supports. */ /*! \macro Q_ATOMIC_INT_REFERENCE_COUNTING_IS_NOT_NATIVE \relates QAtomicInt This macro is defined when the hardware does not support atomic reference counting. */ /*! \macro Q_ATOMIC_INT_REFERENCE_COUNTING_IS_WAIT_FREE \relates QAtomicInt This macro is defined together with Q_ATOMIC_INT_REFERENCE_COUNTING_IS_ALWAYS_NATIVE to indicate that the reference counting is wait-free. */ /*! \macro Q_ATOMIC_INT_TEST_AND_SET_IS_ALWAYS_NATIVE \relates QAtomicInt This macro is defined if and only if your processor supports atomic test-and-set on integers. */ /*! \macro Q_ATOMIC_INT_TEST_AND_SET_IS_SOMETIMES_NATIVE \relates QAtomicInt This macro is defined when only certain generations of the processor support atomic test-and-set on integers. Use the QAtomicInt::isTestAndSetNative() function to check what your processor supports. */ /*! \macro Q_ATOMIC_INT_TEST_AND_SET_IS_NOT_NATIVE \relates QAtomicInt This macro is defined when the hardware does not support atomic test-and-set on integers. */ /*! \macro Q_ATOMIC_INT_TEST_AND_SET_IS_WAIT_FREE \relates QAtomicInt This macro is defined together with Q_ATOMIC_INT_TEST_AND_SET_IS_ALWAYS_NATIVE to indicate that the atomic test-and-set on integers is wait-free. */ /*! \macro Q_ATOMIC_INT_FETCH_AND_STORE_IS_ALWAYS_NATIVE \relates QAtomicInt This macro is defined if and only if your processor supports atomic fetch-and-store on integers. */ /*! \macro Q_ATOMIC_INT_FETCH_AND_STORE_IS_SOMETIMES_NATIVE \relates QAtomicInt This macro is defined when only certain generations of the processor support atomic fetch-and-store on integers. Use the QAtomicInt::isFetchAndStoreNative() function to check what your processor supports. */ /*! \macro Q_ATOMIC_INT_FETCH_AND_STORE_IS_NOT_NATIVE \relates QAtomicInt This macro is defined when the hardware does not support atomic fetch-and-store on integers. */ /*! \macro Q_ATOMIC_INT_FETCH_AND_STORE_IS_WAIT_FREE \relates QAtomicInt This macro is defined together with Q_ATOMIC_INT_FETCH_AND_STORE_IS_ALWAYS_NATIVE to indicate that the atomic fetch-and-store on integers is wait-free. */ /*! \macro Q_ATOMIC_INT_FETCH_AND_ADD_IS_ALWAYS_NATIVE \relates QAtomicInt This macro is defined if and only if your processor supports atomic fetch-and-add on integers. */ /*! \macro Q_ATOMIC_INT_FETCH_AND_ADD_IS_SOMETIMES_NATIVE \relates QAtomicInt This macro is defined when only certain generations of the processor support atomic fetch-and-add on integers. Use the QAtomicInt::isFetchAndAddNative() function to check what your processor supports. */ /*! \macro Q_ATOMIC_INT_FETCH_AND_ADD_IS_NOT_NATIVE \relates QAtomicInt This macro is defined when the hardware does not support atomic fetch-and-add on integers. */ /*! \macro Q_ATOMIC_INT_FETCH_AND_ADD_IS_WAIT_FREE \relates QAtomicInt This macro is defined together with Q_ATOMIC_INT_FETCH_AND_ADD_IS_ALWAYS_NATIVE to indicate that the atomic fetch-and-add on integers is wait-free. */ /*! \class QAtomicPointer \brief The QAtomicPointer class is a template class that provides platform-independent atomic operations on pointers. \since 4.4 \ingroup thread For atomic operations on integers, see the QAtomicInt class. An \e atomic operation is a complex operation that completes without interruption. The QAtomicPointer class provides atomic test-and-set, fetch-and-store, and fetch-and-add for pointers. \section1 Non-atomic convenience operators For convenience, QAtomicPointer provides pointer comparison, cast, dereference, and assignment operators. Note that these operators are \e not atomic. \section1 The Atomic API \section2 Memory ordering QAtomicPointer provides several implementations of the atomic test-and-set, fetch-and-store, and fetch-and-add functions. Each implementation defines a memory ordering semantic that describes how memory accesses surrounding the atomic instruction are executed by the processor. Since many modern architectures allow out-of-order execution and memory ordering, using the correct semantic is necessary to ensure that your application functions properly on all processors. \list \o Relaxed - memory ordering is unspecified, leaving the compiler and processor to freely reorder memory accesses. \o Acquire - memory access following the atomic operation (in program order) may not be re-ordered before the atomic operation. \o Release - memory access before the atomic operation (in program order) may not be re-ordered after the atomic operation. \o Ordered - the same Acquire and Release semantics combined. \endlist \section2 Test-and-set If the current value of the QAtomicPointer is an expected value, the test-and-set functions assign a new value to the QAtomicPointer and return true. If values are \a not the same, these functions do nothing and return false. This operation equates to the following code: \snippet doc/src/snippets/code/src_corelib_thread_qatomic.cpp 4 There are 4 test-and-set functions: testAndSetRelaxed(), testAndSetAcquire(), testAndSetRelease(), and testAndSetOrdered(). See above for an explanation of the different memory ordering semantics. \section2 Fetch-and-store The atomic fetch-and-store functions read the current value of the QAtomicPointer and then assign a new value, returning the original value. This operation equates to the following code: \snippet doc/src/snippets/code/src_corelib_thread_qatomic.cpp 5 There are 4 fetch-and-store functions: fetchAndStoreRelaxed(), fetchAndStoreAcquire(), fetchAndStoreRelease(), and fetchAndStoreOrdered(). See above for an explanation of the different memory ordering semantics. \section2 Fetch-and-add The atomic fetch-and-add functions read the current value of the QAtomicPointer and then add the given value to the current value, returning the original value. This operation equates to the following code: \snippet doc/src/snippets/code/src_corelib_thread_qatomic.cpp 6 There are 4 fetch-and-add functions: fetchAndAddRelaxed(), fetchAndAddAcquire(), fetchAndAddRelease(), and fetchAndAddOrdered(). See above for an explanation of the different memory ordering semantics. \section1 Feature Tests for the Atomic API Providing a platform-independent atomic API that works on all processors is challenging. The API provided by QAtomicPointer is guaranteed to work atomically on all processors. However, since not all processors implement support for every operation provided by QAtomicPointer, it is necessary to expose information about the processor. You can check at compile time which features are supported on your hardware using various macros. These will tell you if your hardware always, sometimes, or does not support a particular operation. The macros have the form Q_ATOMIC_POINTER_\e{OPERATION}_IS_\e{HOW}_NATIVE. \e{OPERATION} is one of TEST_AND_SET, FETCH_AND_STORE, or FETCH_AND_ADD, and \e{HOW} is one of ALWAYS, SOMETIMES, or NOT. There will always be exactly one defined macro per operation. For example, if Q_ATOMIC_POINTER_TEST_AND_SET_IS_ALWAYS_NATIVE is defined, neither Q_ATOMIC_POINTER_TEST_AND_SET_IS_SOMETIMES_NATIVE nor Q_ATOMIC_POINTER_TEST_AND_SET_IS_NOT_NATIVE will be defined. An operation that completes in constant time is said to be wait-free. Such operations are not implemented using locks or loops of any kind. For atomic operations that are always supported, and that are wait-free, Qt defines the Q_ATOMIC_POINTER_\e{OPERATION}_IS_WAIT_FREE in addition to the Q_ATOMIC_POINTER_\e{OPERATION}_IS_ALWAYS_NATIVE. In cases where an atomic operation is only supported in newer generations of the processor, QAtomicPointer also provides a way to check at runtime what your hardware supports with the isTestAndSetNative(), isFetchAndStoreNative(), and isFetchAndAddNative() functions. Wait-free implementations can be detected using the isTestAndSetWaitFree(), isFetchAndStoreWaitFree(), and isFetchAndAddWaitFree() functions. Below is a complete list of all feature macros for QAtomicPointer: \list \o Q_ATOMIC_POINTER_TEST_AND_SET_IS_ALWAYS_NATIVE \o Q_ATOMIC_POINTER_TEST_AND_SET_IS_SOMETIMES_NATIVE \o Q_ATOMIC_POINTER_TEST_AND_SET_IS_NOT_NATIVE \o Q_ATOMIC_POINTER_TEST_AND_SET_IS_WAIT_FREE \o Q_ATOMIC_POINTER_FETCH_AND_STORE_IS_ALWAYS_NATIVE \o Q_ATOMIC_POINTER_FETCH_AND_STORE_IS_SOMETIMES_NATIVE \o Q_ATOMIC_POINTER_FETCH_AND_STORE_IS_NOT_NATIVE \o Q_ATOMIC_POINTER_FETCH_AND_STORE_IS_WAIT_FREE \o Q_ATOMIC_POINTER_FETCH_AND_ADD_IS_ALWAYS_NATIVE \o Q_ATOMIC_POINTER_FETCH_AND_ADD_IS_SOMETIMES_NATIVE \o Q_ATOMIC_POINTER_FETCH_AND_ADD_IS_NOT_NATIVE \o Q_ATOMIC_POINTER_FETCH_AND_ADD_IS_WAIT_FREE \endlist \sa QAtomicInt */ /*! \fn QAtomicPointer::QAtomicPointer(T *value) Constructs a QAtomicPointer with the given \a value. */ /*! \fn QAtomicPointer::QAtomicPointer(const QAtomicPointer<T> &other) Constructs a copy of \a other. */ /*! \fn QAtomicPointer<T> &QAtomicPointer::operator=(T *value) Assigns the \a value to this QAtomicPointer and returns a reference to this QAtomicPointer. */ /*! \fn QAtomicPointer<T> &QAtomicPointer::operator=(const QAtomicPointer<T> &other) Assigns \a other to this QAtomicPointer and returns a reference to this QAtomicPointer. */ /*! \fn bool QAtomicPointer::operator==(T *value) const Returns true if the \a value is equal to the value in this QAtomicPointer; otherwise returns false. */ /*! \fn bool QAtomicPointer::operator!=(T *value) const Returns true if the value of this QAtomicPointer is not equal to \a value; otherwise returns false. */ /*! \fn bool QAtomicPointer::operator!() const Returns true is the current value of this QAtomicPointer is zero; otherwise returns false. */ /*! \fn QAtomicPointer::operator T *() const Returns the current pointer value stored by this QAtomicPointer object. */ /*! \fn T *QAtomicPointer::operator->() const */ /*! \fn bool QAtomicPointer::isTestAndSetNative() Returns true if test-and-set is implemented using atomic processor instructions, false otherwise. */ /*! \fn bool QAtomicPointer::isTestAndSetWaitFree() Returns true if atomic test-and-set is wait-free, false otherwise. */ /*! \fn bool QAtomicPointer::testAndSetRelaxed(T *expectedValue, T *newValue) Atomic test-and-set. If the current value of this QAtomicPointer is the \a expectedValue, the test-and-set functions assign the \a newValue to this QAtomicPointer and return true. If the values are \e not the same, this function does nothing and returns false. This function uses \e relaxed \l {QAtomicPointer#Memory ordering}{memory ordering} semantics, leaving the compiler and processor to freely reorder memory accesses. */ /*! \fn bool QAtomicPointer::testAndSetAcquire(T *expectedValue, T *newValue) Atomic test-and-set. If the current value of this QAtomicPointer is the \a expectedValue, the test-and-set functions assign the \a newValue to this QAtomicPointer and return true. If the values are \e not the same, this function does nothing and returns false. This function uses \e acquire \l {QAtomicPointer#Memory ordering}{memory ordering} semantics, which ensures that memory access following the atomic operation (in program order) may not be re-ordered before the atomic operation. */ /*! \fn bool QAtomicPointer::testAndSetRelease(T *expectedValue, T *newValue) Atomic test-and-set. If the current value of this QAtomicPointer is the \a expectedValue, the test-and-set functions assign the \a newValue to this QAtomicPointer and return true. If the values are \e not the same, this function does nothing and returns false. This function uses \e release \l {QAtomicPointer#Memory ordering}{memory ordering} semantics, which ensures that memory access before the atomic operation (in program order) may not be re-ordered after the atomic operation. */ /*! \fn bool QAtomicPointer::testAndSetOrdered(T *expectedValue, T *newValue) Atomic test-and-set. If the current value of this QAtomicPointer is the \a expectedValue, the test-and-set functions assign the \a newValue to this QAtomicPointer and return true. If the values are \e not the same, this function does nothing and returns false. This function uses \e ordered \l {QAtomicPointer#Memory ordering}{memory ordering} semantics, which ensures that memory access before and after the atomic operation (in program order) may not be re-ordered. */ /*! \fn bool QAtomicPointer::isFetchAndStoreNative() Returns true if fetch-and-store is implemented using atomic processor instructions, false otherwise. */ /*! \fn bool QAtomicPointer::isFetchAndStoreWaitFree() Returns true if atomic fetch-and-store is wait-free, false otherwise. */ /*! \fn T *QAtomicPointer::fetchAndStoreRelaxed(T *newValue) Atomic fetch-and-store. Reads the current value of this QAtomicPointer and then assigns it the \a newValue, returning the original value. This function uses \e relaxed \l {QAtomicPointer#Memory ordering}{memory ordering} semantics, leaving the compiler and processor to freely reorder memory accesses. */ /*! \fn T *QAtomicPointer::fetchAndStoreAcquire(T *newValue) Atomic fetch-and-store. Reads the current value of this QAtomicPointer and then assigns it the \a newValue, returning the original value. This function uses \e acquire \l {QAtomicPointer#Memory ordering}{memory ordering} semantics, which ensures that memory access following the atomic operation (in program order) may not be re-ordered before the atomic operation. */ /*! \fn T *QAtomicPointer::fetchAndStoreRelease(T *newValue) Atomic fetch-and-store. Reads the current value of this QAtomicPointer and then assigns it the \a newValue, returning the original value. This function uses \e release \l {QAtomicPointer#Memory ordering}{memory ordering} semantics, which ensures that memory access before the atomic operation (in program order) may not be re-ordered after the atomic operation. */ /*! \fn T *QAtomicPointer::fetchAndStoreOrdered(T *newValue) Atomic fetch-and-store. Reads the current value of this QAtomicPointer and then assigns it the \a newValue, returning the original value. This function uses \e ordered \l {QAtomicPointer#Memory ordering}{memory ordering} semantics, which ensures that memory access before and after the atomic operation (in program order) may not be re-ordered. */ /*! \fn bool QAtomicPointer::isFetchAndAddNative() Returns true if fetch-and-add is implemented using atomic processor instructions, false otherwise. */ /*! \fn bool QAtomicPointer::isFetchAndAddWaitFree() Returns true if atomic fetch-and-add is wait-free, false otherwise. */ /*! \fn T *QAtomicPointer::fetchAndAddRelaxed(qptrdiff valueToAdd) Atomic fetch-and-add. Reads the current value of this QAtomicPointer and then adds \a valueToAdd to the current value, returning the original value. This function uses \e relaxed \l {QAtomicPointer#Memory ordering}{memory ordering} semantics, leaving the compiler and processor to freely reorder memory accesses. */ /*! \fn T *QAtomicPointer::fetchAndAddAcquire(qptrdiff valueToAdd) Atomic fetch-and-add. Reads the current value of this QAtomicPointer and then adds \a valueToAdd to the current value, returning the original value. This function uses \e acquire \l {QAtomicPointer#Memory ordering}{memory ordering} semantics, which ensures that memory access following the atomic operation (in program order) may not be re-ordered before the atomic operation. */ /*! \fn T *QAtomicPointer::fetchAndAddRelease(qptrdiff valueToAdd) Atomic fetch-and-add. Reads the current value of this QAtomicPointer and then adds \a valueToAdd to the current value, returning the original value. This function uses \e release \l {QAtomicPointer#Memory ordering}{memory ordering} semantics, which ensures that memory access before the atomic operation (in program order) may not be re-ordered after the atomic operation. */ /*! \fn T *QAtomicPointer::fetchAndAddOrdered(qptrdiff valueToAdd) Atomic fetch-and-add. Reads the current value of this QAtomicPointer and then adds \a valueToAdd to the current value, returning the original value. This function uses \e ordered \l {QAtomicPointer#Memory ordering}{memory ordering} semantics, which ensures that memory access before and after the atomic operation (in program order) may not be re-ordered. */ /*! \macro Q_ATOMIC_POINTER_TEST_AND_SET_IS_ALWAYS_NATIVE \relates QAtomicPointer This macro is defined if and only if your processor supports atomic test-and-set on pointers. */ /*! \macro Q_ATOMIC_POINTER_TEST_AND_SET_IS_SOMETIMES_NATIVE \relates QAtomicPointer This macro is defined when only certain generations of the processor support atomic test-and-set on pointers. Use the QAtomicPointer::isTestAndSetNative() function to check what your processor supports. */ /*! \macro Q_ATOMIC_POINTER_TEST_AND_SET_IS_NOT_NATIVE \relates QAtomicPointer This macro is defined when the hardware does not support atomic test-and-set on pointers. */ /*! \macro Q_ATOMIC_POINTER_TEST_AND_SET_IS_WAIT_FREE \relates QAtomicPointer This macro is defined together with Q_ATOMIC_POINTER_TEST_AND_SET_IS_ALWAYS_NATIVE to indicate that the atomic test-and-set on pointers is wait-free. */ /*! \macro Q_ATOMIC_POINTER_FETCH_AND_STORE_IS_ALWAYS_NATIVE \relates QAtomicPointer This macro is defined if and only if your processor supports atomic fetch-and-store on pointers. */ /*! \macro Q_ATOMIC_POINTER_FETCH_AND_STORE_IS_SOMETIMES_NATIVE \relates QAtomicPointer This macro is defined when only certain generations of the processor support atomic fetch-and-store on pointers. Use the QAtomicPointer::isFetchAndStoreNative() function to check what your processor supports. */ /*! \macro Q_ATOMIC_POINTER_FETCH_AND_STORE_IS_NOT_NATIVE \relates QAtomicPointer This macro is defined when the hardware does not support atomic fetch-and-store on pointers. */ /*! \macro Q_ATOMIC_POINTER_FETCH_AND_STORE_IS_WAIT_FREE \relates QAtomicPointer This macro is defined together with Q_ATOMIC_POINTER_FETCH_AND_STORE_IS_ALWAYS_NATIVE to indicate that the atomic fetch-and-store on pointers is wait-free. */ /*! \macro Q_ATOMIC_POINTER_FETCH_AND_ADD_IS_ALWAYS_NATIVE \relates QAtomicPointer This macro is defined if and only if your processor supports atomic fetch-and-add on pointers. */ /*! \macro Q_ATOMIC_POINTER_FETCH_AND_ADD_IS_SOMETIMES_NATIVE \relates QAtomicPointer This macro is defined when only certain generations of the processor support atomic fetch-and-add on pointers. Use the QAtomicPointer::isFetchAndAddNative() function to check what your processor supports. */ /*! \macro Q_ATOMIC_POINTER_FETCH_AND_ADD_IS_NOT_NATIVE \relates QAtomicPointer This macro is defined when the hardware does not support atomic fetch-and-add on pointers. */ /*! \macro Q_ATOMIC_POINTER_FETCH_AND_ADD_IS_WAIT_FREE \relates QAtomicPointer This macro is defined together with Q_ATOMIC_POINTER_FETCH_AND_ADD_IS_ALWAYS_NATIVE to indicate that the atomic fetch-and-add on pointers is wait-free. */
[ "sonyang@seas.upenn.edu" ]
sonyang@seas.upenn.edu
2084ae28820c6e3e3126400b0fa38c4fa41bd5f6
79d7929bc3df1831c720703dd28f9b2f2aae2502
/gn/proj0/tools/gn/tutorial/hello_world.cc
7778b442ad18704707c1131cf28187680d499ab3
[]
no_license
caijw/learn
6e0ed79e5fc41e545dfa72f377b37d0dde8debd6
0bb4aebffd0ccfff79473649b6beb2b2f9a7d091
refs/heads/master
2023-01-12T16:01:48.890316
2020-03-05T08:44:42
2020-03-05T08:44:42
161,798,529
0
1
null
2023-01-11T19:00:58
2018-12-14T14:51:34
HTML
UTF-8
C++
false
false
125
cc
#include <iostream> void hello() { std::cout << "hello world" << std::endl; } int main() { hello(); return 0; }
[ "285025525@qq.com" ]
285025525@qq.com
cf93dd0e9b9bfda428b1396526aeba4c8ba0b530
93da15c2f834b6f8ff575e1ac74c4a1e43a22633
/radeon-profile/uiElements.cpp
067b4388f5100e80d698a7fcc281cab3f9ff92c6
[]
no_license
JamesLinus/radeon-profile
5b7c4c0b0af8990dbf79f1ac8beba6748a3fcb97
8f8e38bed45db3285382a9ee2402639030109d95
refs/heads/master
2021-01-15T18:45:00.812515
2016-01-24T17:25:46
2016-01-24T17:25:46
50,300,890
1
0
null
null
null
null
UTF-8
C++
false
false
8,472
cpp
// copyright marazmista @ 29.12.2013 // this file contains functions for creating some gui elements (menus, graphs) #include "radeon_profile.h" #include "ui_radeon_profile.h" #include <QMenu> //=================================== // === GUI setup functions === // void radeon_profile::setupGraphs() { ui->plotColcks->yAxis->setRange(startClocksScaleL,startClocksScaleH); ui->plotVolts->yAxis->setRange(startVoltsScaleL,startVoltsScaleH); ui->plotTemp->xAxis->setLabel("time"); ui->plotTemp->yAxis->setLabel("temperature"); ui->plotColcks->xAxis->setLabel("time"); ui->plotColcks->yAxis->setLabel("MHz"); ui->plotVolts->xAxis->setLabel("time"); ui->plotVolts->yAxis->setLabel("mV"); ui->plotTemp->xAxis->setTickLabels(false); ui->plotColcks->xAxis->setTickLabels(false); ui->plotVolts->xAxis->setTickLabels(false); ui->plotTemp->addGraph(); // temp graph ui->plotColcks->addGraph(); // core clock graph ui->plotColcks->addGraph(); // mem clock graph ui->plotColcks->addGraph(); // uvd ui->plotColcks->addGraph(); // uvd ui->plotVolts->addGraph(); // volts gpu ui->plotVolts->addGraph(); // volts mem ui->plotFanProfile->addGraph(); ui->plotFanProfile->yAxis->setRange(0,100); ui->plotFanProfile->xAxis->setRange(0,110); ui->plotFanProfile->xAxis->setLabel("Temperature"); ui->plotFanProfile->yAxis->setLabel("Fan speed [%]"); setupGraphsStyle(); // legend clocks // ui->plotColcks->graph(0)->setName("GPU clock"); ui->plotColcks->graph(1)->setName("Memory clock"); ui->plotColcks->graph(2)->setName("Video core clock"); ui->plotColcks->graph(3)->setName("Decoder clock"); ui->plotColcks->axisRect()->insetLayout()->setInsetAlignment(0, Qt::AlignTop|Qt::AlignLeft); ui->plotColcks->legend->setVisible(true); ui->plotVolts->graph(0)->setName("GPU voltage"); ui->plotVolts->graph(1)->setName("Memory voltage"); ui->plotVolts->axisRect()->insetLayout()->setInsetAlignment(0,Qt::AlignTop|Qt::AlignLeft); ui->plotVolts->legend->setVisible(true); ui->plotColcks->replot(); ui->plotTemp->replot(); ui->plotVolts->replot(); } void radeon_profile::setupGraphsStyle() { QPen pen; pen.setWidth(ui->spin_lineThick->value()); pen.setCapStyle(Qt::SquareCap); pen.setColor(ui->graphColorsList->topLevelItem(TEMP_LINE)->backgroundColor(1)); ui->plotTemp->graph(0)->setPen(pen); ui->plotFanProfile->graph(0)->setPen(pen); pen.setColor(ui->graphColorsList->topLevelItem(GPU_CLOCK_LINE)->backgroundColor(1)); ui->plotColcks->graph(0)->setPen(pen); pen.setColor(ui->graphColorsList->topLevelItem(MEM_CLOCK_LINE)->backgroundColor(1)); ui->plotColcks->graph(1)->setPen(pen); pen.setColor(ui->graphColorsList->topLevelItem(UVD_VIDEO_LINE)->backgroundColor(1)); ui->plotColcks->graph(2)->setPen(pen); pen.setColor(ui->graphColorsList->topLevelItem(UVD_DECODER_LINE)->backgroundColor(1)); ui->plotColcks->graph(3)->setPen(pen); pen.setColor(ui->graphColorsList->topLevelItem(CORE_VOLTS_LINE)->backgroundColor(1)); ui->plotVolts->graph(0)->setPen(pen); pen.setColor(ui->graphColorsList->topLevelItem(MEM_VOLTS_LINE)->backgroundColor(1)); ui->plotVolts->graph(1)->setPen(pen); ui->plotTemp->setBackground(QBrush(ui->graphColorsList->topLevelItem(TEMP_BG)->backgroundColor(1))); ui->plotColcks->setBackground(QBrush(ui->graphColorsList->topLevelItem(CLOCKS_BG)->backgroundColor(1))); ui->plotVolts->setBackground(QBrush(ui->graphColorsList->topLevelItem(VOLTS_BG)->backgroundColor(1))); ui->plotFanProfile->setBackground(QBrush(ui->graphColorsList->topLevelItem(TEMP_BG)->backgroundColor(1))); } void radeon_profile::setupTrayIcon() { trayMenu = new QMenu(); setWindowState(Qt::WindowMinimized); //close // closeApp = new QAction(this); closeApp->setText("Quit"); connect(closeApp,SIGNAL(triggered()),this,SLOT(closeFromTray())); // standard profiles changeProfile = new QAction(this); changeProfile->setText("Change standard profile"); connect(changeProfile,SIGNAL(triggered()),this,SLOT(on_chProfile_clicked())); // refresh when hidden refreshWhenHidden = new QAction(this); refreshWhenHidden->setCheckable(true); refreshWhenHidden->setChecked(true); refreshWhenHidden->setText("Keep refreshing when hidden"); // dpm menu // dpmMenu = new QMenu(this); dpmMenu->setTitle("DPM"); dpmSetBattery = new QAction(this); dpmSetBalanced = new QAction(this); dpmSetPerformance = new QAction(this); dpmSetBattery->setText("Battery"); dpmSetBattery->setIcon(QIcon(":/icon/symbols/arrow1.png")); dpmSetBalanced->setText("Balanced"); dpmSetBalanced->setIcon(QIcon(":/icon/symbols/arrow2.png")); dpmSetPerformance->setText("Performance"); dpmSetPerformance->setIcon(QIcon(":/icon/symbols/arrow3.png")); connect(dpmSetBattery,SIGNAL(triggered()),this,SLOT(on_btn_dpmBattery_clicked())); connect(dpmSetBalanced,SIGNAL(triggered()),this, SLOT(on_btn_dpmBalanced_clicked())); connect(dpmSetPerformance,SIGNAL(triggered()),this,SLOT(on_btn_dpmPerformance_clicked())); dpmMenu->addAction(dpmSetBattery); dpmMenu->addAction(dpmSetBalanced); dpmMenu->addAction(dpmSetPerformance); dpmMenu->addSeparator(); dpmMenu->addMenu(forcePowerMenu); // add stuff above to menu // trayMenu->addAction(refreshWhenHidden); trayMenu->addSeparator(); trayMenu->addAction(changeProfile); trayMenu->addMenu(dpmMenu); trayMenu->addSeparator(); trayMenu->addAction(closeApp); // setup icon finally // QIcon appicon(":/icon/extra/radeon-profile.png"); trayIcon = new QSystemTrayIcon(appicon,this); trayIcon->show(); trayIcon->setContextMenu(trayMenu); connect(trayIcon,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),this,SLOT(iconActivated(QSystemTrayIcon::ActivationReason))); } void radeon_profile::setupOptionsMenu() { optionsMenu = new QMenu(this); ui->btn_options->setMenu(optionsMenu); QAction *resetMinMax = new QAction(this); resetMinMax->setText("Reset min/max temperature"); QAction *resetGraphs = new QAction(this); resetGraphs->setText("Reset graphs vertical scale"); QAction *showLegend = new QAction(this); showLegend->setText("Show legend"); showLegend->setCheckable(true); showLegend->setChecked(true); QAction *graphOffset = new QAction(this); graphOffset->setText("Graph offset on right"); graphOffset->setCheckable(true); graphOffset->setChecked(true); optionsMenu->addAction(showLegend); optionsMenu->addAction(graphOffset); optionsMenu->addSeparator(); optionsMenu->addAction(resetMinMax); optionsMenu->addAction(resetGraphs); connect(resetMinMax,SIGNAL(triggered()),this,SLOT(resetMinMax())); connect(resetGraphs,SIGNAL(triggered()),this,SLOT(resetGraphs())); connect(showLegend,SIGNAL(triggered(bool)),this,SLOT(showLegend(bool))); connect(graphOffset,SIGNAL(triggered(bool)),this,SLOT(setGraphOffset(bool))); } void radeon_profile::setupForcePowerLevelMenu() { forcePowerMenu = new QMenu(this); QAction *forceAuto = new QAction(this); forceAuto->setText("Auto"); QAction *forceLow = new QAction(this); forceLow->setText("Low"); QAction *forceHigh = new QAction(this); forceHigh->setText("High"); forcePowerMenu->setTitle("Force power level"); forcePowerMenu->addAction(forceAuto); forcePowerMenu->addSeparator(); forcePowerMenu->addAction(forceLow); forcePowerMenu->addAction(forceHigh); connect(forceAuto,SIGNAL(triggered()),this,SLOT(forceAuto())); connect(forceLow,SIGNAL(triggered()),this,SLOT(forceLow())); connect(forceHigh,SIGNAL(triggered()),this,SLOT(forceHigh())); } void radeon_profile::setupContextMenus() { QAction *copyToClipboard = new QAction(this); copyToClipboard->setText("Copy to clipboard"); ui->list_glxinfo->setContextMenuPolicy(Qt::ActionsContextMenu); ui->list_glxinfo->addAction(copyToClipboard); QAction *reset = new QAction(this); reset->setText("Reset statistics"); ui->list_stats->setContextMenuPolicy(Qt::ActionsContextMenu); ui->list_stats->addAction(reset); connect(copyToClipboard, SIGNAL(triggered()),this,SLOT(copyGlxInfoToClipboard())); connect(reset,SIGNAL(triggered()),this,SLOT(resetStats())); } //========
[ "marazmista@gmail.com" ]
marazmista@gmail.com
32a3904102319982766efc93217df3b4501c8486
a2702eec939ab6f8ba9586156fddb6404a0b9ffd
/Estructura de datos en C++ - PILA - Parte 3 - Modificar Nodo.cpp
9c36f52bd2d0b1586d7de614f7654e9fc5c32685
[ "MIT" ]
permissive
jamesg19/Estructura-de-Datos-en-CPP
dc5060d793ff2aca72fb110fc389b6ef95d3f659
4985c92df16c0ecf3ea4dd23853b003f19bdbb24
refs/heads/main
2023-03-14T05:04:54.117271
2021-02-27T01:47:05
2021-02-27T01:47:05
342,745,504
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
3,598
cpp
#include <iostream> using namespace::std; struct nodo{ int dato; nodo* siguiente; } *primero; void insertarNodo(); void buscarNodo(); void modificarNodo(); void desplegarPila(); int main(){ int opcion_menu=0; do { cout << endl << "|-------------------------------------|"; cout << endl << "| ° PILA ° |"; cout << endl << "|------------------|------------------|"; cout << endl << "| 1. Insertar | 4. Eliminar |"; cout << endl << "| 2. Buscar | 5. Desplegar |"; cout << endl << "| 3. Modificar | 6. Salir |"; cout << endl << "|------------------|------------------|"; cout << endl << endl << " Escoja una Opcion: "; cin >> opcion_menu; switch(opcion_menu ){ case 1: cout << endl << endl << " INSERTA NODO EN LA PILA " << endl << endl; insertarNodo(); break; case 2: cout << endl << endl << " BUSCAR UN NODO EN LA PILA " << endl << endl; buscarNodo(); break; case 3: cout << endl << endl << " MODIFICAR UN NODO DE LA PILA " << endl << endl; modificarNodo(); break; case 4: cout << endl << endl << " ELIMINAR UN NODO DE LA PILA " << endl << endl; break; case 5: cout << endl << endl << " DESPLEGAR PILA DE NODOS " << endl << endl; desplegarPila(); break; case 6: cout << endl << endl << " Programa finalizado..." << endl << endl; break; default: cout << endl << endl << " Opcion No Valida " << endl << endl; } } while (opcion_menu != 6); return 0; } // primero = 9 actual = 7 nodoBuscado = 8 encontrado = true 4,7,8,9 //PILA - 9 -> 6 -> 7 -> 4 -> null 9 8 7 4 void insertarNodo(){ nodo* nuevo = new nodo(); cout << " Ingrese el dato que contendra el nuevo Nodo: "; cin >> nuevo->dato; nuevo->siguiente = primero; primero = nuevo; cout << endl << " Nodo Ingresado " << endl << endl; } void buscarNodo(){ nodo* actual = new nodo(); actual = primero; int nodoBuscado = 0; bool encontrado = false; cout << " Ingrese el dato del Nodo a Buscar: "; cin >> nodoBuscado; if(primero!=NULL){ while(actual!=NULL && encontrado != true){ if(actual->dato == nodoBuscado){ cout << endl << " Nodo con el dato ( " << nodoBuscado << " ) Encontrado" << endl << endl; encontrado = true; } actual = actual->siguiente; } if(encontrado==false){ cout << endl << " Nodo no Encontrado" << endl << endl; } }else{ cout << endl << " La Pila se encuentra vacia" << endl << endl; } } void modificarNodo(){ nodo* actual = new nodo(); actual = primero; int nodoBuscado = 0; bool encontrado = false; cout << " Ingrese el dato del Nodo a Buscar par Modificar: "; cin >> nodoBuscado; if(primero!=NULL){ while(actual!=NULL && encontrado != true){ if(actual->dato == nodoBuscado){ cout << endl << " Nodo con el dato ( " << nodoBuscado << " ) Encontrado"; cout << endl << " Ingrese el nuevo dato para este Nodo: "; cin >> actual->dato; cout << endl << " Nodo Modificado " << endl << endl; encontrado = true; } actual = actual->siguiente; } if(encontrado==false){ cout << endl << " Nodo no Encontrado" << endl << endl; } }else{ cout << endl << " La Pila se encuentra vacia" << endl << endl; } } void desplegarPila(){ nodo* actual = new nodo(); actual = primero; if(primero!=NULL){ while(actual!=NULL){ cout << endl << " " << actual->dato; actual = actual->siguiente; } }else{ cout << endl << " La Pila se encuentra vacia" << endl << endl; } } /* */
[ "jamesosmin-gramajocarcamo@cunoc.edu.gt" ]
jamesosmin-gramajocarcamo@cunoc.edu.gt
c97e860f8642827fe6a3e34f3607b6ce7a814d8c
82db0a91f5ef9cc264c51a4cb0fc0f03e03412d8
/examples/Blinker_TEXT/TEXT_BLE/TEXT_BLE.ino
cde938906c0e0bbf4486c3c98bca86e7b2791076
[ "MIT" ]
permissive
coloz/blinker-library
50da458d91906b3a36f6907cdf96a2876deaa080
892d8e5654960c6c8b348146e136d354b69c7878
refs/heads/master
2020-05-27T13:26:02.273082
2019-05-24T09:19:04
2019-05-24T09:19:04
188,639,001
2
0
null
2019-05-26T04:15:46
2019-05-26T04:15:46
null
UTF-8
C++
false
false
2,184
ino
/* ***************************************************************** * * Download latest Blinker library here: * https://github.com/blinker-iot/blinker-library/archive/master.zip * * * Blinker is a cross-hardware, cross-platform solution for the IoT. * It provides APP, device and server support, * and uses public cloud services for data transmission and storage. * It can be used in smart home, data monitoring and other fields * to help users build Internet of Things projects better and faster. * * Make sure installed 2.5.0 or later ESP8266/Arduino package, * if use ESP8266 with Blinker. * https://github.com/esp8266/Arduino/releases * * Docs: https://doc.blinker.app/ * https://github.com/blinker-iot/blinker-doc/wiki * * ***************************************************************** * * Blinker 库下载地址: * https://github.com/blinker-iot/blinker-library/archive/master.zip * * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 * * 如果使用 ESP8266 接入 Blinker, * 请确保安装了 2.5.0 或更新的 ESP8266/Arduino 支持包。 * https://github.com/esp8266/Arduino/releases * * 文档: https://doc.blinker.app/ * https://github.com/blinker-iot/blinker-doc/wiki * * *****************************************************************/ #define BLINKER_BLE #include <Blinker.h> #define TEXTE_1 "TextKey" BlinkerText Text1(TEXTE_1); void dataRead(const String & data) { BLINKER_LOG("Blinker readString: ", data); Blinker.vibrate(); uint32_t BlinkerTime = millis(); Blinker.print("millis", BlinkerTime); Text1.print("os time", BlinkerTime); digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); } void setup() { Serial.begin(115200); BLINKER_DEBUG.stream(Serial); pinMode(LED_BUILTIN, OUTPUT); digitalWrite(LED_BUILTIN, LOW); Blinker.begin(); Blinker.attachData(dataRead); } void loop() { Blinker.run(); }
[ "121024123@qq.com" ]
121024123@qq.com
b9be807eb1321dbfa02ded3e1808b7a21e161805
1ef5a27c9326065db448dd539810e900cae9460d
/Classes/Round046_02.h
fe6733c508721caffa866a6ff91116743c3d136d
[]
no_license
langtuandroid/SuperBaby
c4e3f7faaa82d40c8da0f518b71251a8ff466c2f
957a5202ba7d1078bdcfb6b0cd6b73a966893efe
refs/heads/master
2021-01-06T20:43:54.083245
2017-06-18T14:19:00
2017-06-18T14:19:00
99,549,410
0
1
null
2017-08-07T07:25:29
2017-08-07T07:25:29
null
UTF-8
C++
false
false
1,268
h
// // Round046_02.h // superBaby // // Created by Administrator on 15/8/4. // // #ifndef __superBaby__Round046_02__ #define __superBaby__Round046_02__ #include "RoundBase.h" USING_NS_CC; class Actor; class StageScene; class Round046_02 : public RoundBase { public: Round046_02(); virtual ~Round046_02(); public: bool initWithRoundIndex(const int, StageScene*, const Vec2& pos = Vec2::ZERO); static Round046_02* createWithRoundIndex(const int, StageScene*, const Vec2& pos = Vec2::ZERO); public: void cleanUp(); virtual void onEnterRound(); virtual void celebrate(const float); /* 开启触摸 */ virtual void openTouch(); /* 回合结束回调 */ virtual void endRound(); /* 处理npc收集 */ virtual void processNpcCollect(); //上升答案 void upAnswersSchedule(float); void downAnswers(); private: Sprite* m_pAnswers[4]; Vec2 m_answersPos[4]; Vec2 m_answersEndPos[4]; Image* m_pImages[4]; Actor* m_pMSActor= nullptr; int m_effectId = 0; //音效play的id int m_InitAniIndex = 0; bool m_opentouched = false; bool m_jumped = false; unsigned int m_curSelIndex = 0; }; #endif /* defined(__superBaby__Round046_02__) */
[ "linyang24@sina.cn" ]
linyang24@sina.cn