blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
sequencelengths
1
1
author_id
stringlengths
0
158
ffda868c8414073cd81810d2b4a14a429f238ea2
a07e85e8d12b69ee8cb928f1b50b0fe65072b485
/Source/MasterringAcorn/Public/TESTWeaponPickUp.h
ae2efc26e742c04d7d32ebeb3279a21335bb8ab1
[]
no_license
bigcat0815/MasteringACORN
54e5ecaacf71059514754c771c848d84095b3fff
f8492aff8731e8d8ca2df8a544d9c8e3e6ccdc78
refs/heads/master
2022-11-30T07:35:01.712986
2020-08-19T03:28:06
2020-08-19T03:28:06
286,441,217
0
0
null
null
null
null
UHC
C++
false
false
1,148
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "MasterringAcorn.h" #include "GameFramework/Actor.h" #include "TESTWeaponPickUp.generated.h" UCLASS() class MASTERRINGACORN_API ATESTWeaponPickUp : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties ATESTWeaponPickUp(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; //액터와 접촉했을때 이벤트 virtual void NotifyActorBeginOverlap(AActor* OtherActor) override; public: // Called every frame virtual void Tick(float DeltaTime) override; UPROPERTY(EditAnywhere, BlueprintReadWrite) TSubclassOf<class ATESTWeaponBase> WeaponClass; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Gameplay) float RotatorSpeed = 30.f; //획득시 탄약수 UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Gameplay) uint8 Ammunition = 10; //다른무기와 비교한 이 무기의 상대적 파워 랭크 기본이 1로 되어있다. UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Gameplay) uint8 WeaponPower = 1; };
504e526dfb26f76bcd9b7848c834d62d8f840824
4427f459aa7337b81188c374d7f2a0ebc760e70a
/addons/artycomputer_models/config.cpp
93d933722eb3d8aa250837e4faf36fb5305936e6
[]
no_license
tuntematonjr/Tun-Firesupport
fa426c207ee7236882d6a0d3ee1dd2f1a12090a4
47bd5dc8bc59ccf0049ecf9dda7b736dedd68492
refs/heads/master
2023-04-18T11:08:17.360317
2023-03-19T09:10:36
2023-03-19T09:10:36
220,298,728
1
0
null
2021-02-22T20:09:03
2019-11-07T18:02:33
C++
UTF-8
C++
false
false
853
cpp
#include "script_component.hpp" class CfgPatches { class tun_artycomputer_models { requiredVersion = 1.94; requiredAddons[] = {"A3_Weapons_F","cba_main","cba_xeh","cba_settings"}; units[]={}; weapons[]={"tun_tablet"}; author = "Immonen & Nurmi"; authorUrl = "https://armafinland.fi/"; }; }; class CfgWeapons { class CBA_MiscItem; class CBA_MiscItem_ItemInfo; class tun_tablet: CBA_MiscItem { displayName="Military Tablet"; scope=2; author="Immonen & Nurmi"; picture= "\x\Tun\addons\artycomputer_models\data\tablet_icon.paa"; model= "\x\Tun\addons\artycomputer_models\tablet.p3d"; icon= "\x\Tun\addons\artycomputer_models\data\tablet_icon.paa"; descriptionShort="Tablet used to run AFI (Advanced Firesupport Interface)"; class ItemInfo: CBA_MiscItem_ItemInfo { mass = 2; }; }; };
a03fc88278c0d3985d5469828bdd9630541b148b
879648a75cdbcffe840ed09e00687e110d7e8f88
/Beginner/DWNLD.cpp
9d79842bccf47df90d623dc10248b3b24af10624
[]
no_license
shubhgkr/Codechef
c910126463796ce551a7a725dd623a60ad394c09
63a4ce2765ec77361ca5cb1dd61f495ddb43bedb
refs/heads/master
2021-07-19T03:02:33.655256
2020-08-02T20:16:22
2020-08-02T20:16:22
200,067,130
2
0
null
null
null
null
UTF-8
C++
false
false
684
cpp
/* * @author Shubham Kumar Gupta (shubhgkr) * github: http://www.github.com/shubhgkr * Created on 19/12/19. * Problem link: https://www.codechef.com/problems/DWNLD */ #include <iostream> int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); int tc; std::cin >> tc; while (tc--) { int n; int k; std::cin >> n >> k; int t[n]; int d[n]; for (int i = 0; i < n; ++i) { std::cin >> t[i] >> d[i]; } int sum = 0; for (int i = 0; i < n; ++i) { if (k != 0) { if (k >= t[i]) { k -= t[i]; t[i] = 0; } else { t[i] -= k; k = 0; } } sum += (t[i] * d[i]); } std::cout << sum << "\n"; } return 0; }
17e3676c3ccf5a07b384efb80b3d6e4406029469
b0b894bcfcf4b64bbb8281d2b9d684f90e106419
/src/main/cpp/Commands/ZeroTurretPosition.cpp
ada36393d99a8b065fb56bcfbc471dd7b326df2d
[]
no_license
FRCTeam16/TMW2020Prototype
f73dc93cfe121afd5cff44b3d8e67640d1ccb905
6caf3159d3b760a58f3e66bcc8202b71427690cc
refs/heads/master
2023-02-25T18:22:40.373699
2020-03-07T23:34:09
2020-03-07T23:34:09
234,454,024
1
0
null
null
null
null
UTF-8
C++
false
false
958
cpp
#include <iostream> #include <ctre/Phoenix.h> #include "Commands/ZeroTurretPosition.h" #include "Robot.h" ZeroTurretPosition::ZeroTurretPosition() : Command() { SetRunWhenDisabled(true); } // Called just before this Command runs the first time void ZeroTurretPosition::Initialize() { std::cout << "****** ZERO TURRET POSITION ******\n"; Robot::turret->GetTurretRotation().ZeroTurretPosition(); std::cout << "****** ZERO TURRET POSITION ******\n"; SetTimeout(1); } // Called repeatedly when this Command is scheduled to run void ZeroTurretPosition::Execute() { } // Make this return true when this Command no longer needs to run execute() bool ZeroTurretPosition::IsFinished() { return IsTimedOut(); } // Called once after isFinished returns true void ZeroTurretPosition::End() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run void ZeroTurretPosition::Interrupted() { }
4192fad7663cbf3606e9301e770e4b6dae41c809
e173fc6d152b4313036df82d6b61cad2646a536b
/OsmmdCore/Row.h
cec945d64d0d91b68403aac6d16a6b53837bc3b5
[]
no_license
sinzens/Osmmd
0b829927f929817aeef6e100f70c6f2f374f672b
c7f51bec40f1e4a1a02ff73d016fc9253acd89fc
refs/heads/master
2023-07-15T00:03:19.945782
2021-09-09T15:57:12
2021-09-09T15:57:12
400,107,044
2
0
null
null
null
null
UTF-8
C++
false
false
1,375
h
/* * Created by Zeng Yinuo, 2021.09.01 * Edited by Zeng Yinuo, 2021.09.04 * Edited by Zeng Yinuo, 2021.09.06 * Edited by Zeng Yinuo, 2021.09.08 */ #pragma once #include "Column.h" namespace Osmmd { struct OSMMD_CORE_API Row : public ISerializable { std::deque<Column> Columns; void AddColumn(const Column& column); void RemoveColumn(int index); void RemoveColumn(const std::string& name); void UpdateColumn(int index, const Column& column); void UpdateColumn(const std::string& name, const Column& column); const Column& ColumnAt(int index) const; const Column& ColumnAt(const std::string& name) const; bool HasColumn(const std::string& name) const; bool HasColumn(const Column& column) const; int ColumnIndex(const std::string& name) const; int ColumnIndex(const Column& column) const; int GetLength() const; Row Sliced(const std::vector<int>& indexes) const; Row Sliced(const std::vector<std::string>& columnNames) const; std::string ToString() const override; Bytes ToBytes() const override; static Row FromBytes(const Bytes& bytes); bool operator==(const Row& other) const; bool operator!=(const Row& other) const; private: std::map<std::string, int> m_nameIndexMap; }; }
165ec7e29a217d8c306f4f4ec2885364061ce75e
b89bfdeb7e026d71dfc0a51d8559451346c0973c
/src/test/main_tests.cpp
01378e01760f7e3436d6b1ae2b376eea11e10a01
[ "MIT" ]
permissive
quantumnode-group/qnodecoin
992095103dd4de3ee25a7c1419c23643e567732d
defdf04d1754ddaa6b57ee4b7e8b655c38bb6662
refs/heads/master
2021-01-14T05:51:33.325311
2020-06-29T12:37:49
2020-06-29T12:37:49
275,385,524
0
1
MIT
2020-07-24T03:13:05
2020-06-27T14:09:45
C++
UTF-8
C++
false
false
833
cpp
// Copyright (c) 2014-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "net.h" #include "test/test_qnodecoin.h" #include <boost/signals2/signal.hpp> #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(main_tests, TestingSetup) bool ReturnFalse() { return false; } bool ReturnTrue() { return true; } BOOST_AUTO_TEST_CASE(test_combiner_all) { boost::signals2::signal<bool (), CombinerAll> Test; BOOST_CHECK(Test()); Test.connect(&ReturnFalse); BOOST_CHECK(!Test()); Test.connect(&ReturnTrue); BOOST_CHECK(!Test()); Test.disconnect(&ReturnFalse); BOOST_CHECK(Test()); Test.disconnect(&ReturnTrue); BOOST_CHECK(Test()); } BOOST_AUTO_TEST_SUITE_END()
669fc14567af77725738f09f10a848e693a0a909
8752485a7c71f2a78bc340155950bf54988b2c8c
/caveman.hpp
bc07978514f3ee9bb19811302c25825d51cb1c07
[]
no_license
mfry1/Caveman-Adventure-Game
9335483a4560b312c5f4a5f67475bff08848cd29
2b6583476d91425fe7850974ccd049e86b4e6a9e
refs/heads/master
2021-06-12T14:37:04.390748
2017-03-27T19:39:15
2017-03-27T19:39:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,116
hpp
/*************************************************************************************** Author: Matt Fry Date: 12/2/16 Description: ***************************************************************************************/ #ifndef CAVEMAN_HPP #define CAVEMAN_HPP #include "Creature.hpp" class Caveman : public Creature { private: int foodAmount, // The amount of food being carried by the caveman hunger, // The level of hunger the caveman has hungerMax; // The hunger level at which starvation is reached bool hasFire, // Whether or not the user has found the fire item hasClub, // Wheter or not the user has found the first weapon upgrade hasSpear; // Wheter or not the user has found the second weapon upgrade public: Caveman(); int getFoodAmount(); void addToFood(int); int getHunger(); int getHungerMax(); void changeHunger(int); bool checkFire(); bool checkClub(); bool checkSpear(); void addClub(); void addSpear(); void addFire(); bool inventory(); }; #endif
fb13cb3ae337927e68e9deb43747ddf76bf4084a
866fda88bfbd0fe608c64a96ef759c5a65eb0a08
/GLEngine/Components/Renderer.h
66e96da16828d10bade6d734905d2bfff8c5b3e2
[]
no_license
erikdakool/sengine
45d3d6a3c9c137f19386124203027dd7399221af
cb8e3111451489ee1db1efca434f84512400ff43
refs/heads/master
2022-11-25T08:34:25.717156
2019-11-13T20:19:50
2019-11-13T20:19:50
164,163,341
0
0
null
null
null
null
UTF-8
C++
false
false
1,193
h
// // Created by erik on 22.10.2019. // #ifndef GLENGINE_RENDERER_H #define GLENGINE_RENDERER_H #include <vector> #include <glm/glm.hpp> #include <GL/glew.h> #include "../Managers/VboIndex.h" #include "../Managers.h" #include "Component.h" enum Primitive{ Null = 0, Plain = 1, //Cube, Sphere = 3, Pyramid = 4 }; class Renderer : public Component{ public: Renderer(Gameobject& gameobject,GameDataRef data); Renderer(Gameobject& gameobject,GameDataRef data,std::string name, std::string url); Renderer(Gameobject& gameobject,GameDataRef data,std::string name, std::string url,std::string tname, std::string turl); ~Renderer(); void update(float deltaT) override; void draw(); void drawIndexed(); private: std::vector<glm::vec3> vertices; std::vector<glm::vec2> uvs; std::vector<glm::vec3> normals; std::vector<unsigned short> indices; std::vector<glm::vec3> indexed_vertices; std::vector<glm::vec2> indexed_uvs; std::vector<glm::vec3> indexed_normals; GLuint vertexbuffer = 0; GLuint uvbuffer = 0; std::string name = "default"; std::string tname = "default"; }; #endif //GLENGINE_RENDERER_H
418a30cb9e5ef8662450c26061b5476d3fdf572f
46d4712c82816290417d611a75b604d51b046ecc
/Samples/Win7Samples/netds/messagequeuing/mqf_draw/drawarea.h
8cfea18d827318f06ba53fc3ca46541a7ad588e5
[ "MIT" ]
permissive
ennoherr/Windows-classic-samples
00edd65e4808c21ca73def0a9bb2af9fa78b4f77
a26f029a1385c7bea1c500b7f182d41fb6bcf571
refs/heads/master
2022-12-09T20:11:56.456977
2022-12-04T16:46:55
2022-12-04T16:46:55
156,835,248
1
0
NOASSERTION
2022-12-04T16:46:55
2018-11-09T08:50:41
null
UTF-8
C++
false
false
1,802
h
// -------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. All rights reserved // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // -------------------------------------------------------------------- // // drawarea.h : header file // #define MAX_MSG_BODY_LEN 32 typedef struct tagLINE { CPoint ptStart; CPoint ptEnd; } LINE; ///////////////////////////////////////////////////////////////////////////// // CDrawArea window class CDrawArea : public CEdit { // Construction public: CDrawArea(); // Attributes public: protected: CPoint m_ptLast; CList<LINE, LINE &> m_listLines; // Operations public: void AddLine(LINE line); void AddKeystroke(char *mbsKey); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CDrawArea) //}}AFX_VIRTUAL // Implementation public: virtual ~CDrawArea(); // Generated message map functions protected: //{{AFX_MSG(CDrawArea) afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnPaint(); afx_msg void OnRButtonUp(UINT nFlags, CPoint point); afx_msg HBRUSH CtlColor(CDC* pDC, UINT nCtlColor); afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags); afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags); afx_msg void OnSetFocus(CWnd* pOldWnd); afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message); afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; /////////////////////////////////////////////////////////////////////////////
108e18576206d01e5a7625b91eae759ab2d2f951
431f1e3c3faa58cb84ec4973823597e1d92f9d92
/playbvh/vcg/space/index/grid_static_ptr.h
4443c0d1ea5820546f2475562056f093ab63c24a
[]
no_license
DengzhiLiu/CG
d83d89ae9fc357e8292eba3057ad960bd3420a9c
deccfd7cda546ab2fefa4a2199ff4968a7f6d255
refs/heads/master
2021-01-16T19:20:46.775694
2015-04-11T09:02:22
2015-04-11T09:02:22
33,616,167
1
0
null
null
null
null
UTF-8
C++
false
false
20,925
h
/**************************************************************************** * VCGLib o o * * Visual and Computer Graphics Library o o * * _ O _ * * Copyright(C) 2004 \/)\/ * * Visual Computing Lab /\/| * * ISTI - Italian National Research Council | * * \ * * All rights reserved. * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License (http://www.gnu.org/licenses/gpl.txt) * * for more details. * * * ****************************************************************************/ /**************************************************************************** History $Log: not supported by cvs2svn $ Revision 1.37 2007/07/16 15:13:39 cignoni Splitted initialiazation functions of grid to add flexibility in the creation Revision 1.36 2005/12/02 00:43:31 cignoni Forgotten a base deferencing like the previous one Note also the different possible sintax with this-> instead of the base class name Revision 1.35 2005/12/02 00:25:13 cignoni Added and removed typenames for gcc compiling. Added base class qualifier for referencing the elemntes of the templated base class (BasicGrid) it seems to be needed by the standard Revision 1.34 2005/11/30 16:01:25 m_di_benedetto Added std:: namespace for max() and min(). Revision 1.33 2005/11/30 10:32:44 m_di_benedetto Added (int) cast to std::distance to prevent compiler warning message. Revision 1.32 2005/11/10 15:44:17 cignoni Added casts to remove warnings Revision 1.31 2005/10/07 13:27:22 turini Minor changes in Set method: added use of template scalar type computing BBox. Revision 1.30 2005/10/05 17:05:08 pietroni corrected bug on Set Function .... bbox must be exetended in order to have'nt any object on his borde Revision 1.29 2005/10/03 13:57:56 pietroni added GetInSphere and GetInBox functions Revision 1.28 2005/10/02 23:15:26 cignoni Inveted the boolean sign of an assert in Grid() Revision 1.27 2005/09/30 15:07:28 cignoni Reordered grid access functions Added possibility of setting BBox explicitly in Set(...) Revision 1.26 2005/09/30 13:15:21 pietroni added wrapping to functions defined in GridClosest: - GetClosest - GetKClosest - DoRay Revision 1.25 2005/09/21 09:22:51 pietroni removed closest functions. Closest function is now on index\\Closest.h Users must use trimesh\\closest.h to perform spatial query. Revision 1.24 2005/09/16 11:57:15 cignoni Removed two wrong typenames Revision 1.23 2005/09/15 13:16:42 spinelli fixed bugs Revision 1.22 2005/09/15 11:14:39 pietroni minor changes Revision 1.21 2005/09/14 13:27:38 spinelli minor changes Revision 1.20 2005/09/14 12:57:52 pietroni canged template parameters for Closest Function (use of TempMark class) Revision 1.19 2005/09/14 09:05:32 pietroni added * operator to Link modified getClosest in order to use Temporary mark corrected bug on functor calling compilation Revision 1.18 2005/09/09 11:29:21 m_di_benedetto Modified old GetClosest() to respect old min_dist semantic (in/out) and removed #included <limits> Revision 1.17 2005/09/09 11:11:15 m_di_benedetto #included <limits> for std::numeric_limits<ScalarType>::max() and corrected parameters bug in old GetClosest(); Revision 1.16 2005/09/09 11:01:02 m_di_benedetto Modified GetClosest(): now it uses a functor for distance calculation. Added comments and a GetClosest() method with backward compatibility. Revision 1.15 2005/08/26 09:27:58 cignoni Added a templated version of SetBBox Revision 1.14 2005/08/02 11:18:36 pietroni exetended form BasicGrid, changed type of t in class Link (from Iterator to Pointer to the object) Revision 1.13 2005/04/14 17:23:08 ponchio *** empty log message *** Revision 1.12 2005/03/15 11:43:18 cignoni Removed BestDim function from the grid_static_ptr class and moved to a indipendent file (grid_util.h) for sake of generality. Revision 1.11 2005/01/03 11:21:26 cignoni Added some casts Revision 1.10 2004/09/28 10:25:05 ponchio SetBox minimal change. Revision 1.9 2004/09/23 14:29:42 ponchio Small bugs fixed. Revision 1.8 2004/09/23 13:44:25 ponchio Removed SetSafeBBox. SetBBox is now safe enough. Revision 1.7 2004/09/09 12:44:39 fasano included stdio.h Revision 1.6 2004/09/09 08:39:29 ganovelli minor changes for gcc Revision 1.5 2004/06/25 18:34:23 ganovelli added Grid to return all the cells sharing a specified edge Revision 1.4 2004/06/23 15:49:03 ponchio Added some help and inndentation Revision 1.3 2004/05/12 18:50:58 ganovelli changed calls to Dist Revision 1.2 2004/05/11 14:33:46 ganovelli changed to grid_static_obj to grid_static_ptr Revision 1.1 2004/05/10 14:44:13 ganovelli created Revision 1.1 2004/03/08 09:21:31 cignoni Initial commit ****************************************************************************/ #ifndef __VCGLIB_UGRID #define __VCGLIB_UGRID #include <vector> #include <algorithm> #include <stdio.h> #include <vcg/space/box3.h> #include <vcg/space/line3.h> #include <vcg/space/index/grid_util.h> #include <vcg/space/index/grid_closest.h> #include <vcg/simplex/face/distance.h> namespace vcg { /** Static Uniform Grid A spatial search structure for a accessing a container of objects. It is based on a uniform grid overlayed over a protion of space. The grid partion the space into cells. Cells contains just pointers to the object that are stored elsewhere. The set of objects is meant to be static and pointer stable. Useful for situation were many space related query are issued over the same dataset (ray tracing, measuring distances between meshes, re-detailing ecc.). Works well for distribution that ar reasonably uniform. How to use it: ContainerType must have a 'value_type' typedef inside. (stl containers already have it) Objects pointed by cells (of kind 'value_type') must have a 'ScalarType' typedef (float or double usually) and a member function: void GetBBox(Box3<ScalarType> &b) which return the bounding box of the object When using the GetClosest() method, the user must supply a functor object (whose type is a method template argument) which expose the following operator (): bool operator () (const ObjType & obj, const Point3f & point, ScalarType & mindist, Point3f & result); which return true if the distance from point to the object 'obj' is < mindist and set mindist to said distance, and result must be set as the closest point of the object to point) */ template < class OBJTYPE, class FLT=float > class GridStaticPtr: public BasicGrid<FLT>, SpatialIndex<OBJTYPE,FLT> { public: typedef OBJTYPE ObjType; typedef ObjType* ObjPtr; typedef typename ObjType::ScalarType ScalarType; typedef Point3<ScalarType> CoordType; typedef Box3<ScalarType> Box3x; typedef Line3<ScalarType> Line3x; typedef GridStaticPtr<OBJTYPE,FLT> GridPtrType; typedef BasicGrid<FLT> BT; /** Internal class for keeping the first pointer of object. Definizione Link dentro la griglia. Classe di supporto per GridStaticObj. */ class Link { public: /// Costruttore di default inline Link(){}; /// Costruttore con inizializzatori inline Link(ObjPtr nt, const int ni ){ assert(ni>=0); t = nt; i = ni; }; inline bool operator < ( const Link & l ) const{ return i < l.i; } inline bool operator <= ( const Link & l ) const{ return i <= l.i; } inline bool operator > ( const Link & l ) const{ return i > l.i; } inline bool operator >= ( const Link & l ) const{ return i >= l.i; } inline bool operator == ( const Link & l ) const{ return i == l.i; } inline bool operator != ( const Link & l ) const{ return i != l.i; } inline ObjPtr & Elem() { return t; } ObjType &operator *(){return *(t);} inline int & Index() { return i; } private: /// Puntatore all'elemento T ObjPtr t; /// Indirizzo del voxel dentro la griglia int i; };//end class Link typedef Link* Cell; typedef Cell CellIterator; std::vector<Link> links; /// Insieme di tutti i links std::vector<Cell> grid; /// Griglia vera e propria /// Date le coordinate di un grid point (corner minx,miy,minz) ritorna le celle che condividono /// l'edge cell che parte dal grid point in direzione axis inline void Grid( Point3i p, const int axis, std::vector<Cell*> & cl) { #ifndef NDEBUG if ( p[0]<0 || p[0] > BT::siz[0] || p[1]<0 || p[1]> BT::siz[1] || p[2]<0 || p[2]> BT::siz[2] ) assert(0); //return NULL; else #endif assert(((unsigned int) p[0]+BT::siz[0]*p[1]+BT::siz[1]*p[2])<grid.size()); int axis0 = (axis+1)%3; int axis1 = (axis+2)%3; int i,j,x,y; x = p[axis0]; y = p[axis1]; for(i = std::max(x-1,0); i <= std::min( x,BT::siz[axis0]-1);++i) for(j = std::max(y-1,0); j <= std::min( y,this->siz[axis1]-1);++j){ p[axis0]=i; p[axis1]=j; cl.push_back(Grid(p[0]+BT::siz[0]*(p[1]+BT::siz[1]*p[2]))); } } //////////////// // Official access functions //////////////// /// BY CELL Cell* Grid(const int i) { return &grid[i]; } void Grid( const Cell* g, Cell & first, Cell & last ) { first = *g; last = *(g+1); } /// BY INTEGER COORDS inline Cell* Grid( const int x, const int y, const int z ) { assert(!( x<0 || x>=BT::siz[0] || y<0 || y>=BT::siz[1] || z<0 || z>=BT::siz[2] )); assert(grid.size()>0); return &*grid.begin() + ( x+BT::siz[0]*(y+BT::siz[1]*z) ); } inline Cell* Grid( const Point3i &pi) { return Grid(pi[0],pi[1],pi[2]); } void Grid( const int x, const int y, const int z, Cell & first, Cell & last ) { Cell* g = Grid(x,y,z); first = *g; last = *(g+1); } void Grid( const Point3<ScalarType> & p, Cell & first, Cell & last ) { Cell* g = Grid(GridP(p)); first = *g; last = *(g+1); } /// Set the bounding box of the grid ///We need some extra space for numerical precision. template <class Box3Type> void SetBBox( const Box3Type & b ) { this->bbox.Import( b ); ScalarType t = this->bbox.Diag()/100.0; if(t == 0) t = ScalarType(1e-20); // <--- Some doubts on this (Cigno 5/1/04) this->bbox.Offset(t); this->dim = this->bbox.max - this->bbox.min; } void ShowStats(FILE *fp) { // Conto le entry //int nentry = 0; //Hist H; //H.SetRange(0,1000,1000); //int pg; //for(pg=0;pg<grid.size()-1;++pg) // if( grid[pg]!=grid[pg+1] ) // { // ++nentry; // H.Add(grid[pg+1]-grid[pg]); // } // fprintf(fp,"Uniform Grid: %d x %d x %d (%d voxels), %.1f%% full, %d links \nNon empty Cell Occupancy Distribution Avg: %f (%4.0f %4.0f %4.0f) \n", // siz[0],siz[1],siz[2],grid.size()-1, // double(nentry)*100.0/(grid.size()-1),links.size(),H.Avg(),H.Percentile(.25),H.Percentile(.5),H.Percentile(.75) // //); } template <class OBJITER> inline void Set(const OBJITER & _oBegin, const OBJITER & _oEnd, int _size=0) { Box3<FLT> _bbox; Box3<FLT> b; OBJITER i; for(i = _oBegin; i!= _oEnd; ++i) { (*i).GetBBox(b); _bbox.Add(b); } ///inflate the bb calculated if(_size ==0) _size=(int)std::distance<OBJITER>(_oBegin,_oEnd); ScalarType infl=_bbox.Diag()/_size; _bbox.min-=vcg::Point3<FLT>(infl,infl,infl); _bbox.max+=vcg::Point3<FLT>(infl,infl,infl); Set(_oBegin,_oEnd,_bbox); } // This function automatically compute a reasonable size for the uniform grid providing the side (radius) of the cell // // Note that the bbox must be already 'inflated' so to be sure that no object will fall on the border of the grid. template <class OBJITER> inline void Set(const OBJITER & _oBegin, const OBJITER & _oEnd, const Box3x &_bbox, FLT radius) { Point3i _siz; Point3<FLT> _dim = _bbox.max - _bbox.min; _dim/=radius; assert(_dim[0]>0 && _dim[1]>0 && _dim[2]>0 ); _siz[0] = (int)ceil(_dim[0]); _siz[1] = (int)ceil(_dim[1]); _siz[2] = (int)ceil(_dim[2]); Point3<FLT> offset=Point3<FLT>::Construct(_siz); offset*=radius; offset -= (_bbox.max - _bbox.min); offset /=2; assert( offset[0]>=0 && offset[1]>=0 && offset[2]>=0 ); Box3x bb = _bbox; bb.min -= offset; bb.max += offset; Set(_oBegin,_oEnd, bb,_siz); } // This function automatically compute a reasonable size for the uniform grid such that the number of cells is // the same of the nubmer of elements to be inserted in the grid. // // Note that the bbox must be already 'inflated' so to be sure that no object will fall on the border of the grid. template <class OBJITER> inline void Set(const OBJITER & _oBegin, const OBJITER & _oEnd, const Box3x &_bbox) { int _size=(int)std::distance<OBJITER>(_oBegin,_oEnd); Point3<FLT> _dim = _bbox.max - _bbox.min; Point3i _siz; BestDim( _size, _dim, _siz ); Set(_oBegin,_oEnd,_bbox,_siz); } template <class OBJITER> inline void Set(const OBJITER & _oBegin, const OBJITER & _oEnd, const Box3x &_bbox, Point3i _siz) { OBJITER i; this->bbox=_bbox; this->siz=_siz; // find voxel size starting from the provided bbox and grid size. this->dim = this->bbox.max - this->bbox.min; this->voxel[0] = this->dim[0]/this->siz[0]; this->voxel[1] = this->dim[1]/this->siz[1]; this->voxel[2] = this->dim[2]/this->siz[2]; // "Alloca" la griglia: +1 per la sentinella grid.resize( this->siz[0]*this->siz[1]*this->siz[2]+1 ); // Ciclo inserimento dei tetraedri: creazione link links.clear(); for(i=_oBegin; i!=_oEnd; ++i) { Box3x bb; // Boundig box del tetraedro corrente (*i).GetBBox(bb); bb.Intersect(this->bbox); if(! bb.IsNull() ) { Box3i ib; // Boundig box in voxels this->BoxToIBox( bb,ib ); int x,y,z; for(z=ib.min[2];z<=ib.max[2];++z) { int bz = z*this->siz[1]; for(y=ib.min[1];y<=ib.max[1];++y) { int by = (y+bz)*this->siz[0]; for(x=ib.min[0];x<=ib.max[0];++x) // Inserire calcolo cella corrente // if( pt->Intersect( ... ) links.push_back( Link(&(*i),by+x) ); } } } } // Push della sentinella /*links.push_back( Link((typename ContainerType::iterator)NULL, (grid.size()-1)));*/ links.push_back( Link( NULL, int(grid.size())-1) ); // Ordinamento dei links sort( links.begin(), links.end() ); // Creazione puntatori ai links typename std::vector<Link>::iterator pl; unsigned int pg; pl = links.begin(); for(pg=0;pg<grid.size();++pg) { assert(pl!=links.end()); grid[pg] = &*pl; while( (int)pg == pl->Index() ) // Trovato inizio { ++pl; // Ricerca prossimo blocco if(pl==links.end()) break; } } } int MemUsed() { return sizeof(GridStaticPtr)+ sizeof(Link)*links.size() + sizeof(Cell) * grid.size(); } template <class OBJPOINTDISTFUNCTOR, class OBJMARKER> ObjPtr GetClosest(OBJPOINTDISTFUNCTOR & _getPointDistance, OBJMARKER & _marker, const typename OBJPOINTDISTFUNCTOR::QueryType & _p, const ScalarType & _maxDist,ScalarType & _minDist, CoordType & _closestPt) { return (vcg::GridClosest<GridPtrType,OBJPOINTDISTFUNCTOR,OBJMARKER>(*this,_getPointDistance,_marker, _p,_maxDist,_minDist,_closestPt)); } template <class OBJPOINTDISTFUNCTOR, class OBJMARKER, class OBJPTRCONTAINER,class DISTCONTAINER, class POINTCONTAINER> unsigned int GetKClosest(OBJPOINTDISTFUNCTOR & _getPointDistance,OBJMARKER & _marker, const unsigned int _k, const CoordType & _p, const ScalarType & _maxDist,OBJPTRCONTAINER & _objectPtrs, DISTCONTAINER & _distances, POINTCONTAINER & _points) { return (vcg::GridGetKClosest<GridPtrType, OBJPOINTDISTFUNCTOR,OBJMARKER,OBJPTRCONTAINER,DISTCONTAINER,POINTCONTAINER>(*this,_getPointDistance,_marker,_k,_p,_maxDist,_objectPtrs,_distances,_points)); } template <class OBJPOINTDISTFUNCTOR, class OBJMARKER, class OBJPTRCONTAINER, class DISTCONTAINER, class POINTCONTAINER> unsigned int GetInSphere(OBJPOINTDISTFUNCTOR & _getPointDistance, OBJMARKER & _marker, const CoordType & _p, const ScalarType & _r, OBJPTRCONTAINER & _objectPtrs, DISTCONTAINER & _distances, POINTCONTAINER & _points) { return(vcg::GridGetInSphere<GridPtrType, OBJPOINTDISTFUNCTOR,OBJMARKER,OBJPTRCONTAINER,DISTCONTAINER,POINTCONTAINER> (*this,_getPointDistance,_marker,_p,_r,_objectPtrs,_distances,_points)); } template <class OBJMARKER, class OBJPTRCONTAINER> unsigned int GetInBox(OBJMARKER & _marker, const vcg::Box3<ScalarType> _bbox, OBJPTRCONTAINER & _objectPtrs) { return(vcg::GridGetInBox<GridPtrType,OBJMARKER,OBJPTRCONTAINER> (*this,_marker,_bbox,_objectPtrs)); } template <class OBJRAYISECTFUNCTOR, class OBJMARKER> ObjPtr DoRay(OBJRAYISECTFUNCTOR & _rayIntersector, OBJMARKER & _marker, const Ray3<ScalarType> & _ray, const ScalarType & _maxDist, ScalarType & _t) { return(vcg::GridDoRay<GridPtrType,OBJRAYISECTFUNCTOR,OBJMARKER>(*this,_rayIntersector,_marker,_ray,_maxDist,_t)); } /* If the grid has a cubic voxel of side <radius> this function process all couple of elementes in neighbouring cells. GATHERFUNCTOR needs to expose this method: bool operator()(OBJTYPE *v1, OBJTYPE *v2); which is then called ONCE per unordered pair v1,v2. example: struct GFunctor { double radius2, iradius2; GFunctor(double radius) { radius2 = radius*radius; iradius2 = 1/radius2; } bool operator()(CVertex *v1, CVertex *v2) { Point3d &p = v1->P(); Point3d &q = v2->P(); double dist2 = (p-q).SquaredNorm(); if(dist2 < radius2) { double w = exp(dist2*iradius2); //do something } } }; */ template <class GATHERFUNCTOR> void Gather(GATHERFUNCTOR gfunctor) { static int corner[8*3] = { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1 }; static int diagonals[14*2] = { 0, 0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 2, 3, 1, 3, 1, 2, 1, 4, 2, 5, 3, 6 }; Cell ostart, oend, dstart, dend; for(int z = 0; z < this->siz[2]; z++) { for(int y = 0; y < this->siz[1]; y++) { for(int x = 0; x < this->siz[0]; x++) { Grid(x, y, z, ostart, oend); for(Cell c = ostart; c != oend; c++) for(Cell s = c+1; s != oend; s++) gfunctor(c->Elem(), s->Elem()); for(int d = 2; d < 28; d += 2) { //skipping self int *cs = corner + 3*diagonals[d]; int *ce = corner + 3*diagonals[d+1]; if((x + cs[0] < this->siz[0]) && (y + cs[1] < this->siz[1]) && (z + cs[2] < this->siz[2]) && (x + ce[0] < this->siz[0]) && (y + ce[1] < this->siz[1]) && (z + ce[2] < this->siz[2])) { Grid(x+cs[0], y+cs[1], z+cs[2], ostart, oend); Grid(x+ce[0], y+ce[1], z+ce[2], dstart, dend); for(Cell c = ostart; c != oend; c++) for(Cell s = dstart; s != dend; s++) gfunctor(c->Elem(), s->Elem()); } } } } } } }; //end class GridStaticPtr } // end namespace #endif
98650d90cf79de449f95004a160d0377daf91379
458e61f29a20446b2fe7e5ae4fa8d34cae6e42e3
/cpp_programs/constants.cpp
589eca1fcc819b8c1e6bd53492ee8ecd54f73d39
[]
no_license
dhrvdwvd/practice
f7976f552b294a85c3d313ae2fc4293707e0b7e4
228de8b6d20ca094efa100648909e85161e02953
refs/heads/master
2023-09-04T20:13:44.530911
2021-10-19T07:55:51
2021-10-19T07:55:51
408,071,491
0
0
null
null
null
null
UTF-8
C++
false
false
500
cpp
#include<iostream> #include<iomanip> // contains setw manipulator to set field width using namespace std; int main(){ const float pi = 3.141593; int i=1, j=13, k=435; cout<< "Constant data type cannot be changed, here pi is a constant equal to "<<pi<<endl; cout<< "endl is a manipulator."<<endl; cout<< "i = "<<i<<endl; cout<< "j = "<<j<<endl; cout<< "k = "<<k<<endl; cout<< "i = "<<setw(3)<<i<<endl; cout<< "j = "<<setw(3)<<j<<endl; cout<< "k = "<<setw(3)<<k<<endl; return 0; }
7806c2d0358c4b572ce703bd7a96a43bb2069b2f
78268deed66ed2e6d785f01eb1e7880b9be4b714
/src/qt/forms/ui_multisigdialog.h
0aa08cfb49350951dacf6011053ef93952eb880a
[ "MIT" ]
permissive
DRC333/QMC
78f17eb31f2b5308cc2f5ea7ac949a09d9229738
41ce091c33f5ce62c043b7ae98c8163e770971d4
refs/heads/master
2020-06-09T07:39:54.422092
2018-12-16T23:47:16
2018-12-16T23:47:16
193,402,947
0
0
MIT
2019-06-23T22:53:18
2019-06-23T22:53:17
null
UTF-8
C++
false
false
36,343
h
/******************************************************************************** ** Form generated from reading UI file 'multisigdialog.ui' ** ** Created by: Qt User Interface Compiler version 5.9.5 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_MULTISIGDIALOG_H #define UI_MULTISIGDIALOG_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QDialog> #include <QtWidgets/QFormLayout> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QPushButton> #include <QtWidgets/QScrollArea> #include <QtWidgets/QSpacerItem> #include <QtWidgets/QSpinBox> #include <QtWidgets/QTabWidget> #include <QtWidgets/QTextEdit> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_MultisigDialog { public: QVBoxLayout *verticalLayout_8; QTabWidget *multisigTabWidget; QWidget *addMultisigTab; QVBoxLayout *verticalLayout; QHBoxLayout *enterMLayout; QSpinBox *enterMSpinbox; QSpacerItem *horizontalSpacer_2; QLabel *enterMLabel; QHBoxLayout *addressLabelLayout; QLabel *addressLableLabel; QSpacerItem *horizontalSpacer; QLineEdit *multisigAddressLabel; QHBoxLayout *addAddressLayout; QPushButton *addAddressButton; QSpacerItem *horizontalSpacer_3; QLabel *addAddressLabel; QSpacerItem *addAddressSpacer_2; QScrollArea *addAddressScrollArea; QWidget *addAddressWidget; QVBoxLayout *verticalLayout_5; QVBoxLayout *addressList; QSpacerItem *verticalSpacer; QHBoxLayout *addMultisigLayout; QPushButton *addMultisigButton; QSpacerItem *horizontalSpacer_4; QLabel *label; QTextEdit *addMultisigStatus; QLabel *label_2; QHBoxLayout *importLayout; QPushButton *importAddressButton; QLineEdit *importRedeem; QWidget *createTransactionTab; QVBoxLayout *verticalLayout_3; QHBoxLayout *horizontalLayout_2; QVBoxLayout *createTxLayout; QHBoxLayout *addTxInputLayout; QLabel *addTxInputLabel; QPushButton *pushButtonCoinControl; QFormLayout *formLayout_2; QLabel *labelQuantity; QLabel *labelQuantity_int; QLabel *labelAmount; QLabel *labelAmount_int; QPushButton *addInputButton; QScrollArea *txInputsScrollArea; QWidget *txInputsWidget; QVBoxLayout *verticalLayout_7; QVBoxLayout *inputsList; QSpacerItem *txInputsSpacer; QHBoxLayout *addDestinationLayout; QLabel *addDestinationLabel; QPushButton *addDestinationButton; QSpacerItem *addDestinationHorizontalSpacer; QScrollArea *destionationsScrollArea; QWidget *destinationsScrollAreaContents; QVBoxLayout *verticalLayout_11; QVBoxLayout *destinationsList; QSpacerItem *destinationsSpacer; QHBoxLayout *horizontalLayout_4; QPushButton *createButton; QLabel *createButtonLabel; QTextEdit *createButtonStatus; QHBoxLayout *horizontalLayout_3; QWidget *signMultisigTransaction; QVBoxLayout *verticalLayout_4; QHBoxLayout *transactionHexLayout; QLabel *transactionHexLabel; QLineEdit *transactionHex; QHBoxLayout *horizontalLayout; QVBoxLayout *verticalLayout_2; QHBoxLayout *horizontalLayout_7; QPushButton *signButton; QPushButton *commitButton; QHBoxLayout *addPrivKeyLayout; QPushButton *addPrivKeyButton; QLabel *addPrivKeyLabel; QHBoxLayout *horizontalLayout_5; QLabel *signButtonStatusLabel; QTextEdit *signButtonStatus; QScrollArea *keyScrollArea; QWidget *keyScrollAreaContents; QVBoxLayout *verticalLayout_9; QVBoxLayout *keyList; QSpacerItem *keySpacer; QSpacerItem *verticalSpacer_2; void setupUi(QDialog *MultisigDialog) { if (MultisigDialog->objectName().isEmpty()) MultisigDialog->setObjectName(QStringLiteral("MultisigDialog")); MultisigDialog->resize(801, 504); QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(MultisigDialog->sizePolicy().hasHeightForWidth()); MultisigDialog->setSizePolicy(sizePolicy); verticalLayout_8 = new QVBoxLayout(MultisigDialog); verticalLayout_8->setObjectName(QStringLiteral("verticalLayout_8")); multisigTabWidget = new QTabWidget(MultisigDialog); multisigTabWidget->setObjectName(QStringLiteral("multisigTabWidget")); multisigTabWidget->setStyleSheet(QLatin1String("QScrollArea{border: 1px solid #5b4c7c;}\n" "QFrame{background-color:#f2f0f0;}\n" "QLabel{background-color:#ffffff;}\n" "QFrame > QLabel{background-color:#f2f0f0;}")); addMultisigTab = new QWidget(); addMultisigTab->setObjectName(QStringLiteral("addMultisigTab")); QSizePolicy sizePolicy1(QSizePolicy::Minimum, QSizePolicy::Minimum); sizePolicy1.setHorizontalStretch(0); sizePolicy1.setVerticalStretch(0); sizePolicy1.setHeightForWidth(addMultisigTab->sizePolicy().hasHeightForWidth()); addMultisigTab->setSizePolicy(sizePolicy1); verticalLayout = new QVBoxLayout(addMultisigTab); verticalLayout->setObjectName(QStringLiteral("verticalLayout")); enterMLayout = new QHBoxLayout(); enterMLayout->setObjectName(QStringLiteral("enterMLayout")); enterMSpinbox = new QSpinBox(addMultisigTab); enterMSpinbox->setObjectName(QStringLiteral("enterMSpinbox")); sizePolicy.setHeightForWidth(enterMSpinbox->sizePolicy().hasHeightForWidth()); enterMSpinbox->setSizePolicy(sizePolicy); enterMSpinbox->setMinimumSize(QSize(120, 30)); enterMSpinbox->setMaximumSize(QSize(120, 30)); enterMSpinbox->setMinimum(1); enterMSpinbox->setMaximum(16); enterMSpinbox->setValue(1); enterMLayout->addWidget(enterMSpinbox); horizontalSpacer_2 = new QSpacerItem(10, 20, QSizePolicy::Fixed, QSizePolicy::Minimum); enterMLayout->addItem(horizontalSpacer_2); enterMLabel = new QLabel(addMultisigTab); enterMLabel->setObjectName(QStringLiteral("enterMLabel")); enterMLabel->setMinimumSize(QSize(0, 30)); enterMLabel->setMaximumSize(QSize(16777215, 30)); enterMLayout->addWidget(enterMLabel); verticalLayout->addLayout(enterMLayout); addressLabelLayout = new QHBoxLayout(); addressLabelLayout->setObjectName(QStringLiteral("addressLabelLayout")); addressLableLabel = new QLabel(addMultisigTab); addressLableLabel->setObjectName(QStringLiteral("addressLableLabel")); addressLabelLayout->addWidget(addressLableLabel); horizontalSpacer = new QSpacerItem(10, 20, QSizePolicy::Fixed, QSizePolicy::Minimum); addressLabelLayout->addItem(horizontalSpacer); multisigAddressLabel = new QLineEdit(addMultisigTab); multisigAddressLabel->setObjectName(QStringLiteral("multisigAddressLabel")); multisigAddressLabel->setMinimumSize(QSize(0, 30)); multisigAddressLabel->setMaximumSize(QSize(16777215, 30)); addressLabelLayout->addWidget(multisigAddressLabel); verticalLayout->addLayout(addressLabelLayout); addAddressLayout = new QHBoxLayout(); addAddressLayout->setObjectName(QStringLiteral("addAddressLayout")); addAddressButton = new QPushButton(addMultisigTab); addAddressButton->setObjectName(QStringLiteral("addAddressButton")); addAddressButton->setMinimumSize(QSize(160, 30)); addAddressButton->setMaximumSize(QSize(160, 30)); QIcon icon; icon.addFile(QStringLiteral(":/icons/add"), QSize(), QIcon::Normal, QIcon::Off); addAddressButton->setIcon(icon); addAddressButton->setAutoDefault(false); addAddressLayout->addWidget(addAddressButton); horizontalSpacer_3 = new QSpacerItem(10, 20, QSizePolicy::Fixed, QSizePolicy::Minimum); addAddressLayout->addItem(horizontalSpacer_3); addAddressLabel = new QLabel(addMultisigTab); addAddressLabel->setObjectName(QStringLiteral("addAddressLabel")); QSizePolicy sizePolicy2(QSizePolicy::Preferred, QSizePolicy::Fixed); sizePolicy2.setHorizontalStretch(0); sizePolicy2.setVerticalStretch(0); sizePolicy2.setHeightForWidth(addAddressLabel->sizePolicy().hasHeightForWidth()); addAddressLabel->setSizePolicy(sizePolicy2); addAddressLayout->addWidget(addAddressLabel); addAddressSpacer_2 = new QSpacerItem(40, 10, QSizePolicy::Expanding, QSizePolicy::Minimum); addAddressLayout->addItem(addAddressSpacer_2); verticalLayout->addLayout(addAddressLayout); addAddressScrollArea = new QScrollArea(addMultisigTab); addAddressScrollArea->setObjectName(QStringLiteral("addAddressScrollArea")); QSizePolicy sizePolicy3(QSizePolicy::Preferred, QSizePolicy::Expanding); sizePolicy3.setHorizontalStretch(0); sizePolicy3.setVerticalStretch(0); sizePolicy3.setHeightForWidth(addAddressScrollArea->sizePolicy().hasHeightForWidth()); addAddressScrollArea->setSizePolicy(sizePolicy3); addAddressScrollArea->setWidgetResizable(true); addAddressWidget = new QWidget(); addAddressWidget->setObjectName(QStringLiteral("addAddressWidget")); addAddressWidget->setGeometry(QRect(0, 0, 759, 147)); verticalLayout_5 = new QVBoxLayout(addAddressWidget); verticalLayout_5->setObjectName(QStringLiteral("verticalLayout_5")); addressList = new QVBoxLayout(); addressList->setObjectName(QStringLiteral("addressList")); verticalLayout_5->addLayout(addressList); verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); verticalLayout_5->addItem(verticalSpacer); addAddressScrollArea->setWidget(addAddressWidget); verticalLayout->addWidget(addAddressScrollArea); addMultisigLayout = new QHBoxLayout(); addMultisigLayout->setObjectName(QStringLiteral("addMultisigLayout")); addMultisigButton = new QPushButton(addMultisigTab); addMultisigButton->setObjectName(QStringLiteral("addMultisigButton")); sizePolicy2.setHeightForWidth(addMultisigButton->sizePolicy().hasHeightForWidth()); addMultisigButton->setSizePolicy(sizePolicy2); addMultisigButton->setMinimumSize(QSize(100, 30)); addMultisigButton->setMaximumSize(QSize(100, 30)); addMultisigButton->setToolTipDuration(-3); QIcon icon1; icon1.addFile(QStringLiteral(":/icons/filesave"), QSize(), QIcon::Normal, QIcon::Off); addMultisigButton->setIcon(icon1); addMultisigButton->setAutoDefault(false); addMultisigLayout->addWidget(addMultisigButton); horizontalSpacer_4 = new QSpacerItem(10, 20, QSizePolicy::Fixed, QSizePolicy::Minimum); addMultisigLayout->addItem(horizontalSpacer_4); label = new QLabel(addMultisigTab); label->setObjectName(QStringLiteral("label")); addMultisigLayout->addWidget(label); addMultisigStatus = new QTextEdit(addMultisigTab); addMultisigStatus->setObjectName(QStringLiteral("addMultisigStatus")); QSizePolicy sizePolicy4(QSizePolicy::Expanding, QSizePolicy::Fixed); sizePolicy4.setHorizontalStretch(0); sizePolicy4.setVerticalStretch(0); sizePolicy4.setHeightForWidth(addMultisigStatus->sizePolicy().hasHeightForWidth()); addMultisigStatus->setSizePolicy(sizePolicy4); addMultisigStatus->setMaximumSize(QSize(16777215, 75)); addMultisigStatus->setReadOnly(true); addMultisigStatus->setTextInteractionFlags(Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse); addMultisigLayout->addWidget(addMultisigStatus); verticalLayout->addLayout(addMultisigLayout); label_2 = new QLabel(addMultisigTab); label_2->setObjectName(QStringLiteral("label_2")); QSizePolicy sizePolicy5(QSizePolicy::Preferred, QSizePolicy::Preferred); sizePolicy5.setHorizontalStretch(0); sizePolicy5.setVerticalStretch(0); sizePolicy5.setHeightForWidth(label_2->sizePolicy().hasHeightForWidth()); label_2->setSizePolicy(sizePolicy5); label_2->setScaledContents(false); label_2->setWordWrap(true); verticalLayout->addWidget(label_2); importLayout = new QHBoxLayout(); importLayout->setObjectName(QStringLiteral("importLayout")); importAddressButton = new QPushButton(addMultisigTab); importAddressButton->setObjectName(QStringLiteral("importAddressButton")); sizePolicy.setHeightForWidth(importAddressButton->sizePolicy().hasHeightForWidth()); importAddressButton->setSizePolicy(sizePolicy); importAddressButton->setMinimumSize(QSize(160, 30)); importAddressButton->setMaximumSize(QSize(160, 30)); QIcon icon2; icon2.addFile(QStringLiteral(":/icons/receiving_addresses"), QSize(), QIcon::Normal, QIcon::Off); importAddressButton->setIcon(icon2); importLayout->addWidget(importAddressButton); importRedeem = new QLineEdit(addMultisigTab); importRedeem->setObjectName(QStringLiteral("importRedeem")); sizePolicy2.setHeightForWidth(importRedeem->sizePolicy().hasHeightForWidth()); importRedeem->setSizePolicy(sizePolicy2); importRedeem->setMinimumSize(QSize(0, 30)); importRedeem->setMaximumSize(QSize(16777215, 30)); importLayout->addWidget(importRedeem); verticalLayout->addLayout(importLayout); multisigTabWidget->addTab(addMultisigTab, QString()); createTransactionTab = new QWidget(); createTransactionTab->setObjectName(QStringLiteral("createTransactionTab")); verticalLayout_3 = new QVBoxLayout(createTransactionTab); verticalLayout_3->setObjectName(QStringLiteral("verticalLayout_3")); horizontalLayout_2 = new QHBoxLayout(); horizontalLayout_2->setObjectName(QStringLiteral("horizontalLayout_2")); createTxLayout = new QVBoxLayout(); createTxLayout->setObjectName(QStringLiteral("createTxLayout")); addTxInputLayout = new QHBoxLayout(); addTxInputLayout->setObjectName(QStringLiteral("addTxInputLayout")); addTxInputLabel = new QLabel(createTransactionTab); addTxInputLabel->setObjectName(QStringLiteral("addTxInputLabel")); QSizePolicy sizePolicy6(QSizePolicy::Fixed, QSizePolicy::Preferred); sizePolicy6.setHorizontalStretch(0); sizePolicy6.setVerticalStretch(0); sizePolicy6.setHeightForWidth(addTxInputLabel->sizePolicy().hasHeightForWidth()); addTxInputLabel->setSizePolicy(sizePolicy6); addTxInputLayout->addWidget(addTxInputLabel); pushButtonCoinControl = new QPushButton(createTransactionTab); pushButtonCoinControl->setObjectName(QStringLiteral("pushButtonCoinControl")); sizePolicy2.setHeightForWidth(pushButtonCoinControl->sizePolicy().hasHeightForWidth()); pushButtonCoinControl->setSizePolicy(sizePolicy2); pushButtonCoinControl->setMinimumSize(QSize(160, 30)); pushButtonCoinControl->setMaximumSize(QSize(160, 30)); addTxInputLayout->addWidget(pushButtonCoinControl); formLayout_2 = new QFormLayout(); formLayout_2->setObjectName(QStringLiteral("formLayout_2")); formLayout_2->setContentsMargins(-1, -1, 10, -1); labelQuantity = new QLabel(createTransactionTab); labelQuantity->setObjectName(QStringLiteral("labelQuantity")); formLayout_2->setWidget(0, QFormLayout::LabelRole, labelQuantity); labelQuantity_int = new QLabel(createTransactionTab); labelQuantity_int->setObjectName(QStringLiteral("labelQuantity_int")); formLayout_2->setWidget(0, QFormLayout::FieldRole, labelQuantity_int); labelAmount = new QLabel(createTransactionTab); labelAmount->setObjectName(QStringLiteral("labelAmount")); formLayout_2->setWidget(1, QFormLayout::LabelRole, labelAmount); labelAmount_int = new QLabel(createTransactionTab); labelAmount_int->setObjectName(QStringLiteral("labelAmount_int")); formLayout_2->setWidget(1, QFormLayout::FieldRole, labelAmount_int); addTxInputLayout->addLayout(formLayout_2); addInputButton = new QPushButton(createTransactionTab); addInputButton->setObjectName(QStringLiteral("addInputButton")); sizePolicy2.setHeightForWidth(addInputButton->sizePolicy().hasHeightForWidth()); addInputButton->setSizePolicy(sizePolicy2); addInputButton->setMinimumSize(QSize(160, 30)); addInputButton->setMaximumSize(QSize(160, 30)); QIcon icon3; icon3.addFile(QStringLiteral(":/css/default"), QSize(), QIcon::Normal, QIcon::Off); addInputButton->setIcon(icon3); addTxInputLayout->addWidget(addInputButton); createTxLayout->addLayout(addTxInputLayout); txInputsScrollArea = new QScrollArea(createTransactionTab); txInputsScrollArea->setObjectName(QStringLiteral("txInputsScrollArea")); sizePolicy3.setHeightForWidth(txInputsScrollArea->sizePolicy().hasHeightForWidth()); txInputsScrollArea->setSizePolicy(sizePolicy3); txInputsScrollArea->setWidgetResizable(true); txInputsWidget = new QWidget(); txInputsWidget->setObjectName(QStringLiteral("txInputsWidget")); txInputsWidget->setGeometry(QRect(0, 0, 747, 68)); verticalLayout_7 = new QVBoxLayout(txInputsWidget); verticalLayout_7->setObjectName(QStringLiteral("verticalLayout_7")); inputsList = new QVBoxLayout(); inputsList->setObjectName(QStringLiteral("inputsList")); verticalLayout_7->addLayout(inputsList); txInputsSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); verticalLayout_7->addItem(txInputsSpacer); txInputsScrollArea->setWidget(txInputsWidget); createTxLayout->addWidget(txInputsScrollArea); addDestinationLayout = new QHBoxLayout(); addDestinationLayout->setObjectName(QStringLiteral("addDestinationLayout")); addDestinationLabel = new QLabel(createTransactionTab); addDestinationLabel->setObjectName(QStringLiteral("addDestinationLabel")); addDestinationLayout->addWidget(addDestinationLabel); addDestinationButton = new QPushButton(createTransactionTab); addDestinationButton->setObjectName(QStringLiteral("addDestinationButton")); sizePolicy.setHeightForWidth(addDestinationButton->sizePolicy().hasHeightForWidth()); addDestinationButton->setSizePolicy(sizePolicy); addDestinationButton->setMinimumSize(QSize(0, 30)); addDestinationButton->setMaximumSize(QSize(150, 30)); addDestinationButton->setIcon(icon); addDestinationLayout->addWidget(addDestinationButton); addDestinationHorizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); addDestinationLayout->addItem(addDestinationHorizontalSpacer); createTxLayout->addLayout(addDestinationLayout); destionationsScrollArea = new QScrollArea(createTransactionTab); destionationsScrollArea->setObjectName(QStringLiteral("destionationsScrollArea")); QSizePolicy sizePolicy7(QSizePolicy::Expanding, QSizePolicy::Expanding); sizePolicy7.setHorizontalStretch(0); sizePolicy7.setVerticalStretch(0); sizePolicy7.setHeightForWidth(destionationsScrollArea->sizePolicy().hasHeightForWidth()); destionationsScrollArea->setSizePolicy(sizePolicy7); destionationsScrollArea->setWidgetResizable(true); destinationsScrollAreaContents = new QWidget(); destinationsScrollAreaContents->setObjectName(QStringLiteral("destinationsScrollAreaContents")); destinationsScrollAreaContents->setGeometry(QRect(0, 0, 747, 68)); verticalLayout_11 = new QVBoxLayout(destinationsScrollAreaContents); verticalLayout_11->setObjectName(QStringLiteral("verticalLayout_11")); destinationsList = new QVBoxLayout(); destinationsList->setObjectName(QStringLiteral("destinationsList")); verticalLayout_11->addLayout(destinationsList); destinationsSpacer = new QSpacerItem(20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding); verticalLayout_11->addItem(destinationsSpacer); destionationsScrollArea->setWidget(destinationsScrollAreaContents); createTxLayout->addWidget(destionationsScrollArea); horizontalLayout_4 = new QHBoxLayout(); horizontalLayout_4->setObjectName(QStringLiteral("horizontalLayout_4")); createButton = new QPushButton(createTransactionTab); createButton->setObjectName(QStringLiteral("createButton")); sizePolicy.setHeightForWidth(createButton->sizePolicy().hasHeightForWidth()); createButton->setSizePolicy(sizePolicy); createButton->setMinimumSize(QSize(150, 30)); createButton->setMaximumSize(QSize(150, 30)); QIcon icon4; icon4.addFile(QStringLiteral(":/icons/export"), QSize(), QIcon::Normal, QIcon::Off); createButton->setIcon(icon4); createButton->setAutoDefault(false); horizontalLayout_4->addWidget(createButton); createButtonLabel = new QLabel(createTransactionTab); createButtonLabel->setObjectName(QStringLiteral("createButtonLabel")); sizePolicy6.setHeightForWidth(createButtonLabel->sizePolicy().hasHeightForWidth()); createButtonLabel->setSizePolicy(sizePolicy6); createButtonLabel->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter); horizontalLayout_4->addWidget(createButtonLabel); createButtonStatus = new QTextEdit(createTransactionTab); createButtonStatus->setObjectName(QStringLiteral("createButtonStatus")); QSizePolicy sizePolicy8(QSizePolicy::Expanding, QSizePolicy::Minimum); sizePolicy8.setHorizontalStretch(0); sizePolicy8.setVerticalStretch(0); sizePolicy8.setHeightForWidth(createButtonStatus->sizePolicy().hasHeightForWidth()); createButtonStatus->setSizePolicy(sizePolicy8); createButtonStatus->setMaximumSize(QSize(16777215, 16777215)); createButtonStatus->setReadOnly(true); horizontalLayout_4->addWidget(createButtonStatus); createTxLayout->addLayout(horizontalLayout_4); horizontalLayout_2->addLayout(createTxLayout); horizontalLayout_3 = new QHBoxLayout(); horizontalLayout_3->setObjectName(QStringLiteral("horizontalLayout_3")); horizontalLayout_2->addLayout(horizontalLayout_3); verticalLayout_3->addLayout(horizontalLayout_2); multisigTabWidget->addTab(createTransactionTab, QString()); signMultisigTransaction = new QWidget(); signMultisigTransaction->setObjectName(QStringLiteral("signMultisigTransaction")); signMultisigTransaction->setStyleSheet(QLatin1String("txScrollArea:{\n" " border: 1px solid #5b4c7c;\n" "}\n" "keyScrollArea:{\n" " border: 1px solid #5b4c7c;\n" "}\n" "txScrollArea:{\n" " border: 1px solid #5b4c7c;\n" "}")); verticalLayout_4 = new QVBoxLayout(signMultisigTransaction); verticalLayout_4->setObjectName(QStringLiteral("verticalLayout_4")); transactionHexLayout = new QHBoxLayout(); transactionHexLayout->setObjectName(QStringLiteral("transactionHexLayout")); transactionHexLabel = new QLabel(signMultisigTransaction); transactionHexLabel->setObjectName(QStringLiteral("transactionHexLabel")); transactionHexLayout->addWidget(transactionHexLabel); transactionHex = new QLineEdit(signMultisigTransaction); transactionHex->setObjectName(QStringLiteral("transactionHex")); transactionHex->setMinimumSize(QSize(0, 30)); transactionHex->setMaximumSize(QSize(16777215, 30)); transactionHexLayout->addWidget(transactionHex); verticalLayout_4->addLayout(transactionHexLayout); horizontalLayout = new QHBoxLayout(); horizontalLayout->setObjectName(QStringLiteral("horizontalLayout")); verticalLayout_2 = new QVBoxLayout(); verticalLayout_2->setObjectName(QStringLiteral("verticalLayout_2")); horizontalLayout_7 = new QHBoxLayout(); horizontalLayout_7->setObjectName(QStringLiteral("horizontalLayout_7")); signButton = new QPushButton(signMultisigTransaction); signButton->setObjectName(QStringLiteral("signButton")); sizePolicy2.setHeightForWidth(signButton->sizePolicy().hasHeightForWidth()); signButton->setSizePolicy(sizePolicy2); signButton->setMinimumSize(QSize(150, 30)); signButton->setMaximumSize(QSize(150, 30)); QIcon icon5; icon5.addFile(QStringLiteral(":/icons/edit"), QSize(), QIcon::Normal, QIcon::Off); signButton->setIcon(icon5); signButton->setAutoDefault(false); horizontalLayout_7->addWidget(signButton); commitButton = new QPushButton(signMultisigTransaction); commitButton->setObjectName(QStringLiteral("commitButton")); commitButton->setEnabled(false); sizePolicy2.setHeightForWidth(commitButton->sizePolicy().hasHeightForWidth()); commitButton->setSizePolicy(sizePolicy2); commitButton->setMinimumSize(QSize(0, 30)); commitButton->setMaximumSize(QSize(150, 30)); commitButton->setAutoFillBackground(false); QIcon icon6; icon6.addFile(QStringLiteral(":/icons/send"), QSize(), QIcon::Normal, QIcon::Off); commitButton->setIcon(icon6); commitButton->setAutoDefault(true); horizontalLayout_7->addWidget(commitButton); addPrivKeyLayout = new QHBoxLayout(); addPrivKeyLayout->setObjectName(QStringLiteral("addPrivKeyLayout")); addPrivKeyButton = new QPushButton(signMultisigTransaction); addPrivKeyButton->setObjectName(QStringLiteral("addPrivKeyButton")); sizePolicy.setHeightForWidth(addPrivKeyButton->sizePolicy().hasHeightForWidth()); addPrivKeyButton->setSizePolicy(sizePolicy); addPrivKeyButton->setMinimumSize(QSize(0, 30)); addPrivKeyButton->setMaximumSize(QSize(150, 30)); addPrivKeyButton->setIcon(icon); addPrivKeyLayout->addWidget(addPrivKeyButton); addPrivKeyLabel = new QLabel(signMultisigTransaction); addPrivKeyLabel->setObjectName(QStringLiteral("addPrivKeyLabel")); addPrivKeyLayout->addWidget(addPrivKeyLabel); horizontalLayout_7->addLayout(addPrivKeyLayout); verticalLayout_2->addLayout(horizontalLayout_7); horizontalLayout_5 = new QHBoxLayout(); horizontalLayout_5->setObjectName(QStringLiteral("horizontalLayout_5")); signButtonStatusLabel = new QLabel(signMultisigTransaction); signButtonStatusLabel->setObjectName(QStringLiteral("signButtonStatusLabel")); horizontalLayout_5->addWidget(signButtonStatusLabel); signButtonStatus = new QTextEdit(signMultisigTransaction); signButtonStatus->setObjectName(QStringLiteral("signButtonStatus")); QSizePolicy sizePolicy9(QSizePolicy::Expanding, QSizePolicy::Preferred); sizePolicy9.setHorizontalStretch(0); sizePolicy9.setVerticalStretch(0); sizePolicy9.setHeightForWidth(signButtonStatus->sizePolicy().hasHeightForWidth()); signButtonStatus->setSizePolicy(sizePolicy9); signButtonStatus->setMaximumSize(QSize(16777215, 16777215)); signButtonStatus->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); signButtonStatus->setReadOnly(true); signButtonStatus->setTextInteractionFlags(Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse); horizontalLayout_5->addWidget(signButtonStatus); verticalLayout_2->addLayout(horizontalLayout_5); keyScrollArea = new QScrollArea(signMultisigTransaction); keyScrollArea->setObjectName(QStringLiteral("keyScrollArea")); sizePolicy7.setHeightForWidth(keyScrollArea->sizePolicy().hasHeightForWidth()); keyScrollArea->setSizePolicy(sizePolicy7); keyScrollArea->setWidgetResizable(true); keyScrollAreaContents = new QWidget(); keyScrollAreaContents->setObjectName(QStringLiteral("keyScrollAreaContents")); keyScrollAreaContents->setGeometry(QRect(0, 0, 755, 68)); verticalLayout_9 = new QVBoxLayout(keyScrollAreaContents); verticalLayout_9->setObjectName(QStringLiteral("verticalLayout_9")); keyList = new QVBoxLayout(); keyList->setObjectName(QStringLiteral("keyList")); verticalLayout_9->addLayout(keyList); keySpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); verticalLayout_9->addItem(keySpacer); keyScrollArea->setWidget(keyScrollAreaContents); verticalLayout_2->addWidget(keyScrollArea); horizontalLayout->addLayout(verticalLayout_2); verticalLayout_4->addLayout(horizontalLayout); verticalSpacer_2 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); verticalLayout_4->addItem(verticalSpacer_2); multisigTabWidget->addTab(signMultisigTransaction, QString()); verticalLayout_8->addWidget(multisigTabWidget); retranslateUi(MultisigDialog); multisigTabWidget->setCurrentIndex(0); createButton->setDefault(true); signButton->setDefault(true); QMetaObject::connectSlotsByName(MultisigDialog); } // setupUi void retranslateUi(QDialog *MultisigDialog) { MultisigDialog->setWindowTitle(QApplication::translate("MultisigDialog", "Multisignature Address Interactions", Q_NULLPTR)); #ifndef QT_NO_TOOLTIP enterMSpinbox->setToolTip(QApplication::translate("MultisigDialog", "How many people must sign to verify a transaction", Q_NULLPTR)); #endif // QT_NO_TOOLTIP enterMLabel->setText(QApplication::translate("MultisigDialog", "Enter the minimum number of signatures required to sign transactions", Q_NULLPTR)); addressLableLabel->setText(QApplication::translate("MultisigDialog", "Address Label:", Q_NULLPTR)); #ifndef QT_NO_TOOLTIP addAddressButton->setToolTip(QApplication::translate("MultisigDialog", "Add another address that could sign to verify a transaction from the multisig address.", Q_NULLPTR)); #endif // QT_NO_TOOLTIP addAddressButton->setText(QApplication::translate("MultisigDialog", "&Add Address / Key", Q_NULLPTR)); addAddressLabel->setText(QApplication::translate("MultisigDialog", "Local addresses or public keys that can sign:", Q_NULLPTR)); #ifndef QT_NO_TOOLTIP addMultisigButton->setToolTip(QApplication::translate("MultisigDialog", "Create a new multisig address", Q_NULLPTR)); #endif // QT_NO_TOOLTIP addMultisigButton->setText(QApplication::translate("MultisigDialog", "C&reate", Q_NULLPTR)); label->setText(QApplication::translate("MultisigDialog", "Status:", Q_NULLPTR)); label_2->setText(QApplication::translate("MultisigDialog", "Use below to quickly import an address by its redeem. Don't forget to add a label before clicking import!\n" "Keep in mind, the wallet will rescan the blockchain to find transactions containing the new address.\n" "Please be patient after clicking import.", Q_NULLPTR)); importAddressButton->setText(QApplication::translate("MultisigDialog", "&Import Redeem", Q_NULLPTR)); multisigTabWidget->setTabText(multisigTabWidget->indexOf(addMultisigTab), QApplication::translate("MultisigDialog", "Create MultiSignature &Address", Q_NULLPTR)); addTxInputLabel->setText(QApplication::translate("MultisigDialog", "Inputs:", Q_NULLPTR)); pushButtonCoinControl->setText(QApplication::translate("MultisigDialog", "Coin Control", Q_NULLPTR)); labelQuantity->setText(QApplication::translate("MultisigDialog", "Quantity Selected:", Q_NULLPTR)); labelQuantity_int->setText(QApplication::translate("MultisigDialog", "0", Q_NULLPTR)); labelAmount->setText(QApplication::translate("MultisigDialog", "Amount:", Q_NULLPTR)); labelAmount_int->setText(QApplication::translate("MultisigDialog", "0", Q_NULLPTR)); #ifndef QT_NO_TOOLTIP addInputButton->setToolTip(QApplication::translate("MultisigDialog", "Add an input to fund the outputs", Q_NULLPTR)); #endif // QT_NO_TOOLTIP addInputButton->setText(QApplication::translate("MultisigDialog", "Add a Raw Input", Q_NULLPTR)); addDestinationLabel->setText(QApplication::translate("MultisigDialog", "Address / Amount:", Q_NULLPTR)); #ifndef QT_NO_TOOLTIP addDestinationButton->setToolTip(QApplication::translate("MultisigDialog", "Add destinations to send QMC to", Q_NULLPTR)); #endif // QT_NO_TOOLTIP addDestinationButton->setText(QApplication::translate("MultisigDialog", "Add &Destination", Q_NULLPTR)); #ifndef QT_NO_TOOLTIP createButton->setToolTip(QApplication::translate("MultisigDialog", "Create a transaction object using the given inputs to the given outputs", Q_NULLPTR)); #endif // QT_NO_TOOLTIP createButton->setText(QApplication::translate("MultisigDialog", "Cr&eate", Q_NULLPTR)); createButtonLabel->setText(QApplication::translate("MultisigDialog", "Status:", Q_NULLPTR)); createButtonStatus->setHtml(QApplication::translate("MultisigDialog", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:'FreeSerif Italic'; font-size:10pt; font-weight:400; font-style:normal;\">\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Noto Sans'; font-size:9pt;\"><br /></p></body></html>", Q_NULLPTR)); multisigTabWidget->setTabText(multisigTabWidget->indexOf(createTransactionTab), QApplication::translate("MultisigDialog", "&Create MultiSignature Tx", Q_NULLPTR)); transactionHexLabel->setText(QApplication::translate("MultisigDialog", "Transaction Hex:", Q_NULLPTR)); #ifndef QT_NO_TOOLTIP transactionHex->setToolTip(QString()); #endif // QT_NO_TOOLTIP #ifndef QT_NO_TOOLTIP signButton->setToolTip(QApplication::translate("MultisigDialog", "Sign the transaction from this wallet or from provided private keys", Q_NULLPTR)); #endif // QT_NO_TOOLTIP signButton->setText(QApplication::translate("MultisigDialog", "S&ign", Q_NULLPTR)); #ifndef QT_NO_TOOLTIP commitButton->setToolTip(QApplication::translate("MultisigDialog", "<html><head/><body><p>DISABLED until transaction has been signed enough times.</p></body></html>", Q_NULLPTR)); #endif // QT_NO_TOOLTIP commitButton->setText(QApplication::translate("MultisigDialog", "Co&mmit", Q_NULLPTR)); #ifndef QT_NO_TOOLTIP addPrivKeyButton->setToolTip(QApplication::translate("MultisigDialog", "Add private keys to sign the transaction with", Q_NULLPTR)); #endif // QT_NO_TOOLTIP addPrivKeyButton->setText(QApplication::translate("MultisigDialog", "Add Private &Key", Q_NULLPTR)); addPrivKeyLabel->setText(QApplication::translate("MultisigDialog", "Sign with only private keys (Not Recommened)", Q_NULLPTR)); signButtonStatusLabel->setText(QApplication::translate("MultisigDialog", "Status:", Q_NULLPTR)); multisigTabWidget->setTabText(multisigTabWidget->indexOf(signMultisigTransaction), QApplication::translate("MultisigDialog", "&Sign MultiSignature Tx", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class MultisigDialog: public Ui_MultisigDialog {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_MULTISIGDIALOG_H
babb15079f8a30a6a4652bca0b5a75959e8438a4
1337a747db741d24a11cf10d3c4b0c9d173f8a6d
/Libraries/gtkmm/include/gtkmm/gdkmm/private/rectangle_p.h
fa9e9288079193e3b3722fd487e150522c5b4ef7
[ "MIT" ]
permissive
iCodeIN/Wings
0a1c17979439fc17e9bd55c43a7cc993973a3032
1dbf0c88cf3cc97b48788c23abc50c32447e228a
refs/heads/master
2021-06-12T22:29:07.009637
2017-03-19T07:10:42
2017-03-19T07:10:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
159
h
// -*- c++ -*- // Generated by gmmproc 2.44.0 -- DO NOT MODIFY! #ifndef _GDKMM_RECTANGLE_P_H #define _GDKMM_RECTANGLE_P_H #endif /* _GDKMM_RECTANGLE_P_H */
b4a28f132036cd7e19da6e00e17d3e1c4d82561e
d0a39caca85e49b1878da3a1fc60284ffda98b63
/N6B/++++stl_vector.h
7c3c49a5ad3a5f3e203503e34ef729e88cb1b57a
[]
no_license
sguzwf/datastruct
489ec47937ffbae38c683ff4f44018e8d39beccc
d613f9a815706d06b89dc2e306f1b7f6979dbc50
refs/heads/master
2021-01-18T14:36:06.961414
2015-11-29T14:08:25
2015-11-29T14:08:25
null
0
0
null
null
null
null
GB18030
C++
false
false
33,903
h
// Vector implementation -*- C++ -*- // Copyright (C) 2001, 2002, 2003 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library 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, or (at your option) // any later version. // This library 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 library; see the file COPYING. If not, write to the Free // Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. // As a special exception, you may use this file as part of a free software // library without restriction. Specifically, if other files instantiate // templates or use macros or inline functions from this file, or you compile // this file and link it with other files to produce an executable, this // file does not by itself cause the resulting executable to be covered by // the GNU General Public License. This exception does not however // invalidate any other reasons why the executable file might be covered by // the GNU General Public License. /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file stl_vector.h * This is an internal header file, included by other library headers. * You should not attempt to use it directly. */ #ifndef _VECTOR_H #define _VECTOR_H 1 #include <bits/stl_iterator_base_funcs.h> #include <bits/functexcept.h> #include <bits/concept_check.h> namespace _GLIBCXX_STD { /** * @if maint * See bits/stl_deque.h's _Deque_base for an explanation. * @endif */ template<typename _Tp, typename _Alloc> struct _Vector_base { struct _Vector_impl : public _Alloc { _Tp* _M_start; _Tp* _M_finish; _Tp* _M_end_of_storage; _Vector_impl (_Alloc const& __a) : _Alloc(__a), _M_start(0), _M_finish(0), _M_end_of_storage(0) { } }; public: typedef _Alloc allocator_type; allocator_type get_allocator() const { return *static_cast<const _Alloc*>(&this->_M_impl); } _Vector_base(const allocator_type& __a) : _M_impl(__a) { } _Vector_base(size_t __n, const allocator_type& __a) : _M_impl(__a) { this->_M_impl._M_start = this->_M_allocate(__n); this->_M_impl._M_finish = this->_M_impl._M_start; this->_M_impl._M_end_of_storage = this->_M_impl._M_start + __n; } ~_Vector_base() { _M_deallocate(this->_M_impl._M_start, this->_M_impl._M_end_of_storage - this->_M_impl._M_start); } public: _Vector_impl _M_impl; _Tp* _M_allocate(size_t __n) { return _M_impl.allocate(__n); } void _M_deallocate(_Tp* __p, size_t __n) { if (__p) _M_impl.deallocate(__p, __n); } }; /** * @brief A standard container which offers fixed time access to * individual elements in any order. * * @ingroup Containers * @ingroup Sequences * * Meets the requirements of a <a href="tables.html#65">container</a>, a * <a href="tables.html#66">reversible container</a>, and a * <a href="tables.html#67">sequence</a>, including the * <a href="tables.html#68">optional sequence requirements</a> with the * %exception of @c push_front and @c pop_front. * * In some terminology a %vector can be described as a dynamic * C-style array, it offers fast and efficient access to individual * elements in any order and saves the user from worrying about * memory and size allocation. Subscripting ( @c [] ) access is * also provided as with C-style arrays. */ template<typename _Tp, typename _Alloc = allocator<_Tp> > class vector : protected _Vector_base<_Tp, _Alloc> { // Concept requirements. __glibcxx_class_requires(_Tp, _SGIAssignableConcept) typedef _Vector_base<_Tp, _Alloc> _Base; typedef vector<_Tp, _Alloc> vector_type; public: typedef _Tp value_type; typedef typename _Alloc::pointer pointer; typedef typename _Alloc::const_pointer const_pointer; typedef typename _Alloc::reference reference; typedef typename _Alloc::const_reference const_reference; typedef __gnu_cxx::__normal_iterator<pointer, vector_type> iterator; typedef __gnu_cxx::__normal_iterator<const_pointer, vector_type> const_iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; typedef std::reverse_iterator<iterator> reverse_iterator; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef typename _Base::allocator_type allocator_type; protected: /** @if maint * These two functions and three data members are all from the * base class. They should be pretty self-explanatory, as * %vector uses a simple contiguous allocation scheme. @endif */ using _Base::_M_allocate; using _Base::_M_deallocate; using _Base::_M_impl; public: // [23.2.4.1] construct/copy/destroy // (assign() and get_allocator() are also listed in this section) /** * @brief Default constructor creates no elements. */ explicit vector(const allocator_type& __a = allocator_type()) : _Base(__a) { } /** * @brief Create a %vector with copies of an exemplar element. * @param n The number of elements to initially create. * @param value An element to copy. * * This constructor fills the %vector with @a n copies of @a value. */ vector(size_type __n, const value_type& __value, const allocator_type& __a = allocator_type()) : _Base(__n, __a) { this->_M_impl._M_finish = std::uninitialized_fill_n(this->_M_impl._M_start, __n, __value); } /** * @brief Create a %vector with default elements. * @param n The number of elements to initially create. * * This constructor fills the %vector with @a n copies of a * default-constructed element. */ explicit vector(size_type __n) : _Base(__n, allocator_type()) { this->_M_impl._M_finish = std::uninitialized_fill_n(this->_M_impl._M_start, __n, value_type()); } /** * @brief %Vector copy constructor. * @param x A %vector of identical element and allocator types. * * The newly-created %vector uses a copy of the allocation * object used by @a x. All the elements of @a x are copied, * but any extra memory in * @a x (for fast expansion) will not be copied. */ vector(const vector& __x) : _Base(__x.size(), __x.get_allocator()) //拷贝构造函数.初始化_Base的方式是复制过来基类分配器 { this->_M_impl._M_finish = std::uninitialized_copy(__x.begin(), __x.end(), this->_M_impl._M_start); } /** * @brief Builds a %vector from a range. * @param first An input iterator. * @param last An input iterator. * * Create a %vector consisting of copies of the elements from * [first,last). * * If the iterators are forward, bidirectional, or * random-access, then this will call the elements' copy * constructor N times (where N is distance(first,last)) and do * no memory reallocation. But if only input iterators are * used, then this will do at most 2N calls to the copy * constructor, and logN memory reallocations. */ template<typename _InputIterator> vector(_InputIterator __first, _InputIterator __last, const allocator_type& __a = allocator_type()) : _Base(__a) { // Check whether it's an integral type. If so, it's not an iterator. typedef typename _Is_integer<_InputIterator>::_Integral _Integral; //iterator_traits萃取机制 _M_initialize_dispatch(__first, __last, _Integral()); //通过类型不同,萃取不同的_Intergral,因而调用不同的_M_initialize函数 } /** * The dtor only erases the elements, and note that if the * elements themselves are pointers, the pointed-to memory is * not touched in any way. Managing the pointer is the user's * responsibilty. *///析构只单纯删除元素,如果元素是指针,指针指向的空间不是析构函数管的事---也就是说这里如果使用不当容易导致memory leak ~vector() { std::_Destroy(this->_M_impl._M_start, this->_M_impl._M_finish); } /** * @brief %Vector assignment operator. * @param x A %vector of identical element and allocator types. * * All the elements of @a x are copied, but any extra memory in * @a x (for fast expansion) will not be copied. Unlike the * copy constructor, the allocator object is not copied. *///不像拷贝构造函数,这里分配器对象是不被复制的 vector& operator=(const vector& __x); /** * @brief Assigns a given value to a %vector. * @param n Number of elements to be assigned. * @param val Value to be assigned. * * This function fills a %vector with @a n copies of the given * value. Note that the assignment completely changes the * %vector and that the resulting %vector's size is the same as * the number of elements assigned. Old data may be lost. */ void assign(size_type __n, const value_type& __val) { _M_fill_assign(__n, __val); } /** * @brief Assigns a range to a %vector. * @param first An input iterator. * @param last An input iterator. * * This function fills a %vector with copies of the elements in the * range [first,last). * * Note that the assignment completely changes the %vector and * that the resulting %vector's size is the same as the number * of elements assigned. Old data may be lost. */ template<typename _InputIterator> void assign(_InputIterator __first, _InputIterator __last) { // Check whether it's an integral type. If so, it's not an iterator. typedef typename _Is_integer<_InputIterator>::_Integral _Integral; _M_assign_dispatch(__first, __last, _Integral()); } /// Get a copy of the memory allocation object. using _Base::get_allocator; // iterators /** * Returns a read/write iterator that points to the first * element in the %vector. Iteration is done in ordinary * element order. */ iterator begin() { return iterator (this->_M_impl._M_start); } /** * Returns a read-only (constant) iterator that points to the * first element in the %vector. Iteration is done in ordinary * element order. */ const_iterator begin() const { return const_iterator (this->_M_impl._M_start); } /** * Returns a read/write iterator that points one past the last * element in the %vector. Iteration is done in ordinary * element order. */ iterator end() { return iterator (this->_M_impl._M_finish); } /** * Returns a read-only (constant) iterator that points one past * the last element in the %vector. Iteration is done in * ordinary element order. */ const_iterator end() const { return const_iterator (this->_M_impl._M_finish); } /** * Returns a read/write reverse iterator that points to the * last element in the %vector. Iteration is done in reverse * element order. */ reverse_iterator rbegin() { return reverse_iterator(end()); } /** * Returns a read-only (constant) reverse iterator that points * to the last element in the %vector. Iteration is done in * reverse element order. */ const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } /** * Returns a read/write reverse iterator that points to one * before the first element in the %vector. Iteration is done * in reverse element order. */ reverse_iterator rend() { return reverse_iterator(begin()); } /** * Returns a read-only (constant) reverse iterator that points * to one before the first element in the %vector. Iteration * is done in reverse element order. */ const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } // [23.2.4.2] capacity /** Returns the number of elements in the %vector. */ size_type size() const { return size_type(end() - begin()); } /** Returns the size() of the largest possible %vector. */ size_type max_size() const { return size_type(-1) / sizeof(value_type); } /** * @brief Resizes the %vector to the specified number of elements. * @param new_size Number of elements the %vector should contain. * @param x Data with which new elements should be populated. * * This function will %resize the %vector to the specified * number of elements. If the number is smaller than the * %vector's current size the %vector is truncated, otherwise * the %vector is extended and new elements are populated with * given data. */ void resize(size_type __new_size, const value_type& __x) { if (__new_size < size()) erase(begin() + __new_size, end()); else insert(end(), __new_size - size(), __x); } /** * @brief Resizes the %vector to the specified number of elements. * @param new_size Number of elements the %vector should contain. * * This function will resize the %vector to the specified * number of elements. If the number is smaller than the * %vector's current size the %vector is truncated, otherwise * the %vector is extended and new elements are * default-constructed. */ void resize(size_type __new_size) { resize(__new_size, value_type()); } /** * Returns the total number of elements that the %vector can * hold before needing to allocate more memory. */ size_type capacity() const { return size_type(const_iterator(this->_M_impl._M_end_of_storage) - begin()); } /** * Returns true if the %vector is empty. (Thus begin() would * equal end().) */ bool empty() const { return begin() == end(); } /** * @brief Attempt to preallocate enough memory for specified number of * elements. * @param n Number of elements required. * @throw std::length_error If @a n exceeds @c max_size(). * * This function attempts to reserve enough memory for the * %vector to hold the specified number of elements. If the * number requested is more than max_size(), length_error is * thrown. * * The advantage of this function is that if optimal code is a * necessity and the user can determine the number of elements * that will be required, the user can reserve the memory in * %advance, and thus prevent a possible reallocation of memory * and copying of %vector data. */ void reserve(size_type __n); // element access /** * @brief Subscript access to the data contained in the %vector. * @param n The index of the element for which data should be * accessed. * @return Read/write reference to data. * * This operator allows for easy, array-style, data access. * Note that data access with this operator is unchecked and * out_of_range lookups are not defined. (For checked lookups * see at().) */ reference operator[](size_type __n) { return *(begin() + __n); } /** * @brief Subscript access to the data contained in the %vector. * @param n The index of the element for which data should be * accessed. * @return Read-only (constant) reference to data. * * This operator allows for easy, array-style, data access. * Note that data access with this operator is unchecked and * out_of_range lookups are not defined. (For checked lookups * see at().) */ const_reference operator[](size_type __n) const { return *(begin() + __n); } protected: /// @if maint Safety check used only from at(). @endif void _M_range_check(size_type __n) const { if (__n >= this->size()) __throw_out_of_range(__N("vector::_M_range_check")); } public: /** * @brief Provides access to the data contained in the %vector. * @param n The index of the element for which data should be * accessed. * @return Read/write reference to data. * @throw std::out_of_range If @a n is an invalid index. * * This function provides for safer data access. The parameter * is first checked that it is in the range of the vector. The * function throws out_of_range if the check fails. */ reference at(size_type __n) { _M_range_check(__n); return (*this)[__n]; } /** * @brief Provides access to the data contained in the %vector. * @param n The index of the element for which data should be * accessed. * @return Read-only (constant) reference to data. * @throw std::out_of_range If @a n is an invalid index. * * This function provides for safer data access. The parameter * is first checked that it is in the range of the vector. The * function throws out_of_range if the check fails. */ const_reference at(size_type __n) const { _M_range_check(__n); return (*this)[__n]; } /** * Returns a read/write reference to the data at the first * element of the %vector. */ reference front() { return *begin(); } /** * Returns a read-only (constant) reference to the data at the first * element of the %vector. */ const_reference front() const { return *begin(); } /** * Returns a read/write reference to the data at the last * element of the %vector. */ reference back() { return *(end() - 1); } /** * Returns a read-only (constant) reference to the data at the * last element of the %vector. */ const_reference back() const { return *(end() - 1); } // [23.2.4.3] modifiers /** * @brief Add data to the end of the %vector. * @param x Data to be added. * * This is a typical stack operation. The function creates an * element at the end of the %vector and assigns the given data * to it. Due to the nature of a %vector this operation can be * done in constant time if the %vector has preallocated space * available. */ void push_back(const value_type& __x) { if (this->_M_impl._M_finish != this->_M_impl._M_end_of_storage) { std::_Construct(this->_M_impl._M_finish, __x); ++this->_M_impl._M_finish; } else _M_insert_aux(end(), __x); } /** * @brief Removes last element. * * This is a typical stack operation. It shrinks the %vector by one. * * Note that no data is returned, and if the last element's * data is needed, it should be retrieved before pop_back() is * called. */ void pop_back() { --this->_M_impl._M_finish; std::_Destroy(this->_M_impl._M_finish); } /** * @brief Inserts given value into %vector before specified iterator. * @param position An iterator into the %vector. * @param x Data to be inserted. * @return An iterator that points to the inserted data. * * This function will insert a copy of the given value before * the specified location. Note that this kind of operation * could be expensive for a %vector and if it is frequently * used the user should consider using std::list. */ iterator insert(iterator __position, const value_type& __x); /** * @brief Inserts a number of copies of given data into the %vector. * @param position An iterator into the %vector. * @param n Number of elements to be inserted. * @param x Data to be inserted. * * This function will insert a specified number of copies of * the given data before the location specified by @a position. * * Note that this kind of operation could be expensive for a * %vector and if it is frequently used the user should * consider using std::list. */ void insert(iterator __position, size_type __n, const value_type& __x) { _M_fill_insert(__position, __n, __x); } /** * @brief Inserts a range into the %vector. * @param position An iterator into the %vector. * @param first An input iterator. * @param last An input iterator. * * This function will insert copies of the data in the range * [first,last) into the %vector before the location specified * by @a pos. * * Note that this kind of operation could be expensive for a * %vector and if it is frequently used the user should * consider using std::list. */ template<typename _InputIterator> void insert(iterator __position, _InputIterator __first, _InputIterator __last) { // Check whether it's an integral type. If so, it's not an iterator. typedef typename _Is_integer<_InputIterator>::_Integral _Integral; _M_insert_dispatch(__position, __first, __last, _Integral()); } /** * @brief Remove element at given position. * @param position Iterator pointing to element to be erased. * @return An iterator pointing to the next element (or end()). * * This function will erase the element at the given position and thus * shorten the %vector by one. * * Note This operation could be expensive and if it is * frequently used the user should consider using std::list. * The user is also cautioned that this function only erases * the element, and that if the element is itself a pointer, * the pointed-to memory is not touched in any way. Managing * the pointer is the user's responsibilty. */ iterator erase(iterator __position); /** * @brief Remove a range of elements. * @param first Iterator pointing to the first element to be erased. * @param last Iterator pointing to one past the last element to be * erased. * @return An iterator pointing to the element pointed to by @a last * prior to erasing (or end()). * * This function will erase the elements in the range [first,last) and * shorten the %vector accordingly. * * Note This operation could be expensive and if it is * frequently used the user should consider using std::list. * The user is also cautioned that this function only erases * the elements, and that if the elements themselves are * pointers, the pointed-to memory is not touched in any way. * Managing the pointer is the user's responsibilty. */ iterator erase(iterator __first, iterator __last); /** * @brief Swaps data with another %vector. * @param x A %vector of the same element and allocator types. * * This exchanges the elements between two vectors in constant time. * (Three pointers, so it should be quite fast.) * Note that the global std::swap() function is specialized such that * std::swap(v1,v2) will feed to this function. */ void swap(vector& __x) { std::swap(this->_M_impl._M_start, __x._M_impl._M_start); std::swap(this->_M_impl._M_finish, __x._M_impl._M_finish); std::swap(this->_M_impl._M_end_of_storage, __x._M_impl._M_end_of_storage); } /** * Erases all the elements. Note that this function only erases the * elements, and that if the elements themselves are pointers, the * pointed-to memory is not touched in any way. Managing the pointer is * the user's responsibilty. */ void clear() { erase(begin(), end()); } protected: /** * @if maint * Memory expansion handler. Uses the member allocation function to * obtain @a n bytes of memory, and then copies [first,last) into it. * @endif */ template<typename _ForwardIterator> pointer _M_allocate_and_copy(size_type __n, _ForwardIterator __first, _ForwardIterator __last) { pointer __result = this->_M_allocate(__n); try { std::uninitialized_copy(__first, __last, __result); return __result; } catch(...) { _M_deallocate(__result, __n); __throw_exception_again; } } // Internal constructor functions follow. // Called by the range constructor to implement [23.1.1]/9 template<typename _Integer> void _M_initialize_dispatch(_Integer __n, _Integer __value, __true_type) { this->_M_impl._M_start = _M_allocate(__n); this->_M_impl._M_end_of_storage = this->_M_impl._M_start + __n; this->_M_impl._M_finish = std::uninitialized_fill_n(this->_M_impl._M_start, __n, __value); } // Called by the range constructor to implement [23.1.1]/9 template<typename _InputIterator> void _M_initialize_dispatch(_InputIterator __first, _InputIterator __last, __false_type) { typedef typename iterator_traits<_InputIterator>::iterator_category _IterCategory; _M_range_initialize(__first, __last, _IterCategory()); } // Called by the second initialize_dispatch above template<typename _InputIterator> void _M_range_initialize(_InputIterator __first, _InputIterator __last, input_iterator_tag) { for ( ; __first != __last; ++__first) push_back(*__first); } // Called by the second initialize_dispatch above template<typename _ForwardIterator> void _M_range_initialize(_ForwardIterator __first, _ForwardIterator __last, forward_iterator_tag) { size_type __n = std::distance(__first, __last); this->_M_impl._M_start = this->_M_allocate(__n); this->_M_impl._M_end_of_storage = this->_M_impl._M_start + __n; this->_M_impl._M_finish = std::uninitialized_copy(__first, __last, this->_M_impl._M_start); } // Internal assign functions follow. The *_aux functions do the actual // assignment work for the range versions. // Called by the range assign to implement [23.1.1]/9 template<typename _Integer> void _M_assign_dispatch(_Integer __n, _Integer __val, __true_type) { _M_fill_assign(static_cast<size_type>(__n), static_cast<value_type>(__val)); } // Called by the range assign to implement [23.1.1]/9 template<typename _InputIterator> void _M_assign_dispatch(_InputIterator __first, _InputIterator __last, __false_type) { typedef typename iterator_traits<_InputIterator>::iterator_category _IterCategory; _M_assign_aux(__first, __last, _IterCategory()); } // Called by the second assign_dispatch above template<typename _InputIterator> void _M_assign_aux(_InputIterator __first, _InputIterator __last, input_iterator_tag); // Called by the second assign_dispatch above template<typename _ForwardIterator> void _M_assign_aux(_ForwardIterator __first, _ForwardIterator __last, forward_iterator_tag); // Called by assign(n,t), and the range assign when it turns out // to be the same thing. void _M_fill_assign(size_type __n, const value_type& __val); // Internal insert functions follow. // Called by the range insert to implement [23.1.1]/9 template<typename _Integer> void _M_insert_dispatch(iterator __pos, _Integer __n, _Integer __val, __true_type) { _M_fill_insert(__pos, static_cast<size_type>(__n), static_cast<value_type>(__val)); } // Called by the range insert to implement [23.1.1]/9 template<typename _InputIterator> void _M_insert_dispatch(iterator __pos, _InputIterator __first, _InputIterator __last, __false_type) { typedef typename iterator_traits<_InputIterator>::iterator_category _IterCategory; _M_range_insert(__pos, __first, __last, _IterCategory()); } // Called by the second insert_dispatch above template<typename _InputIterator> void _M_range_insert(iterator __pos, _InputIterator __first, _InputIterator __last, input_iterator_tag); // Called by the second insert_dispatch above template<typename _ForwardIterator> void _M_range_insert(iterator __pos, _ForwardIterator __first, _ForwardIterator __last, forward_iterator_tag); // Called by insert(p,n,x), and the range insert when it turns out to be // the same thing. void _M_fill_insert(iterator __pos, size_type __n, const value_type& __x); // Called by insert(p,x) void _M_insert_aux(iterator __position, const value_type& __x); }; /** * @brief Vector equality comparison. * @param x A %vector. * @param y A %vector of the same type as @a x. * @return True iff the size and elements of the vectors are equal. * * This is an equivalence relation. It is linear in the size of the * vectors. Vectors are considered equivalent if their sizes are equal, * and if corresponding elements compare equal. */ template<typename _Tp, typename _Alloc> inline bool operator==(const vector<_Tp,_Alloc>& __x, const vector<_Tp,_Alloc>& __y) { return __x.size() == __y.size() && std::equal(__x.begin(), __x.end(), __y.begin()); } /** * @brief Vector ordering relation. * @param x A %vector. * @param y A %vector of the same type as @a x. * @return True iff @a x is lexicographically less than @a y. * * This is a total ordering relation. It is linear in the size of the * vectors. The elements must be comparable with @c <. * * See std::lexicographical_compare() for how the determination is made. */ template<typename _Tp, typename _Alloc> inline bool operator<(const vector<_Tp,_Alloc>& __x, const vector<_Tp,_Alloc>& __y) { return std::lexicographical_compare(__x.begin(), __x.end(), __y.begin(), __y.end()); } /// Based on operator== template<typename _Tp, typename _Alloc> inline bool operator!=(const vector<_Tp,_Alloc>& __x, const vector<_Tp,_Alloc>& __y) { return !(__x == __y); } /// Based on operator< template<typename _Tp, typename _Alloc> inline bool operator>(const vector<_Tp,_Alloc>& __x, const vector<_Tp,_Alloc>& __y) { return __y < __x; } /// Based on operator< template<typename _Tp, typename _Alloc> inline bool operator<=(const vector<_Tp,_Alloc>& __x, const vector<_Tp,_Alloc>& __y) { return !(__y < __x); } /// Based on operator< template<typename _Tp, typename _Alloc> inline bool operator>=(const vector<_Tp,_Alloc>& __x, const vector<_Tp,_Alloc>& __y) { return !(__x < __y); } /// See std::vector::swap(). template<typename _Tp, typename _Alloc> inline void swap(vector<_Tp,_Alloc>& __x, vector<_Tp,_Alloc>& __y) { __x.swap(__y); } } // namespace std #endif /* _VECTOR_H */
090171f19ecb03e480a89e4575374f1b1a13d466
367e570a378469a9cccf1d49874e92963b3e01eb
/ClientFile.h
d999e5598355b05e66b2540437700bde5ad3393b
[]
no_license
aditikocherlakota/File_Copy
6616f8e7c8a03c735b6f1a71a3766c96efd0b44b
4264217bb965e6f069cdd8478de7b77a9ec519d9
refs/heads/master
2020-04-28T19:35:52.964551
2019-03-13T23:55:42
2019-03-13T23:55:42
175,516,504
0
0
null
null
null
null
UTF-8
C++
false
false
959
h
#ifndef CLIENTFILE_H #define CLIENTFILE_H #include "sharedfiledefs.h" #define WINDOW_SIZE 5 #define RETRIES_BEFORE_FAILURE 5 enum State{INITIAL, SENDING_E2E_CHECK, SENDING_E2E_CONF, SENDING_E2E_FAILED, DONE}; class ClientFile { private: State state; int fileNastiness; int numTimeouts; int receivedPacketNum; int totalTries; int finalPacketNum; int windowPacketNum; string filename; NASTYFILE* file; void changeState(State state); void send(C150DgmSocket *sock, Type type); void sendFilePackets(C150DgmSocket *sock); client_packet createPacket(Type type); void setup(); public: ClientFile(string filename, int fileNastiness); bool isDone(); void timeOut(); bool shouldContinue(); void sendData(C150DgmSocket *sock); void receiveData(server_packet serverResponse); }; #endif
7ce29ef295216d4273907eab9cac205637887d75
72774739eadc535e1aeed276e039e244d16cb86d
/MQTT.ino
8c315b9594668b8197862c93c92a4e5bafe85889
[]
no_license
xlogerais/esp8266-mqtt-sensor-sht30
3fabdf152843857b6c7377819ad1b9deb16765d3
41296db02448fb8ca244af9039be3b2fb4d55794
refs/heads/master
2021-01-21T14:33:42.808967
2017-06-24T15:48:05
2017-06-24T15:48:05
95,304,079
6
0
null
null
null
null
UTF-8
C++
false
false
796
ino
void mqtt_connect(const char* server, const char* port, const char* name) { Serial.println(); Serial.print("Connecting to MQTT server : "); Serial.print(server); Serial.print(":"); Serial.println(port); mqtt.begin(server,atoi(port),wifi); while (!mqtt.connect(name)) { Serial.print("."); delay(500); } Serial.println(" connected."); // Announce us on the announce topic mqtt.publish(MQTT_PREFIX"/announce", name); // Subscribe to our dedicated topic //mqtt.subscribe(MQTT_PREFIX"/"MODULE_NAME); //mqtt.subscribe(MQTT_PREFIX"/"MODULE_NAME"/#"); } void messageReceived(String topic, String payload, char * bytes, unsigned int length) { Serial.print("incoming: "); Serial.print(topic); Serial.print(" - "); Serial.print(payload); Serial.println(); }
104d9309934035415f682e8a0b4b992254d6d3da
d47c341d59ed8ba577463ccf100a51efb669599c
/boost/variant/polymorphic_get.hpp
c693c510999a3ec7e77377979dde168b92ddd3ed
[ "BSL-1.0" ]
permissive
cms-externals/boost
5980d39d50b7441536eb3b10822f56495fdf3635
9615b17aa7196c42a741e99b4003a0c26f092f4c
refs/heads/master
2023-08-29T09:15:33.137896
2020-08-04T16:50:18
2020-08-04T16:50:18
30,637,301
0
4
BSL-1.0
2023-08-09T23:00:37
2015-02-11T08:07:04
C++
UTF-8
C++
false
false
5,006
hpp
//----------------------------------------------------------------------------- // boost variant/polymorphic_get.hpp header file // See http://www.boost.org for updates, documentation, and revision history. //----------------------------------------------------------------------------- // // Copyright (c) 2013 Antony Polukhin // // 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_VARIANT_POLYMORPHIC_GET_HPP #define BOOST_VARIANT_POLYMORPHIC_GET_HPP #include <exception> #include "boost/config.hpp" #include "boost/detail/workaround.hpp" #include "boost/throw_exception.hpp" #include "boost/utility/addressof.hpp" #include "boost/variant/variant_fwd.hpp" #include "boost/variant/get.hpp" #include "boost/type_traits/add_reference.hpp" #include "boost/type_traits/add_pointer.hpp" #include "boost/type_traits/is_base_of.hpp" namespace boost { ////////////////////////////////////////////////////////////////////////// // class bad_polymorphic_get // // The exception thrown in the event of a failed get of a value. // class BOOST_SYMBOL_VISIBLE bad_polymorphic_get : public bad_get { public: // std::exception implementation virtual const char * what() const BOOST_NOEXCEPT_OR_NOTHROW { return "boost::bad_polymorphic_get: " "failed value get using boost::polymorphic_get"; } }; ////////////////////////////////////////////////////////////////////////// // function template get<T> // // Retrieves content of given variant object if content is of type T. // Otherwise: pointer ver. returns 0; reference ver. throws bad_get. // namespace detail { namespace variant { // (detail) class template get_polymorphic_visitor // // Generic static visitor that: if the value is of the specified // type or of a type derived from specified, returns a pointer // to the value it visits; else a null pointer. // template <typename Base> struct get_polymorphic_visitor { private: // private typedefs typedef typename add_pointer<Base>::type pointer; typedef typename add_reference<Base>::type reference; pointer get(reference operand, boost::true_type) const BOOST_NOEXCEPT { return boost::addressof(operand); } template <class T> pointer get(T&, boost::false_type) const BOOST_NOEXCEPT { return static_cast<pointer>(0); } public: // visitor interfaces typedef pointer result_type; template <typename U> pointer operator()(U& operand) const BOOST_NOEXCEPT { typedef boost::integral_constant< bool, boost::is_base_of<Base, U>::value || boost::is_same<Base, U>::value > tag_t; return get(operand, tag_t()); } }; }} // namespace detail::variant #ifndef BOOST_VARIANT_AUX_GET_EXPLICIT_TEMPLATE_TYPE # if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x0551)) # define BOOST_VARIANT_AUX_GET_EXPLICIT_TEMPLATE_TYPE(t) # else # define BOOST_VARIANT_AUX_GET_EXPLICIT_TEMPLATE_TYPE(t) \ , t* = 0 # endif #endif template <typename U, BOOST_VARIANT_ENUM_PARAMS(typename T) > inline typename add_pointer<U>::type polymorphic_get( boost::variant< BOOST_VARIANT_ENUM_PARAMS(T) >* operand BOOST_VARIANT_AUX_GET_EXPLICIT_TEMPLATE_TYPE(U) ) BOOST_NOEXCEPT { typedef typename add_pointer<U>::type U_ptr; if (!operand) return static_cast<U_ptr>(0); detail::variant::get_polymorphic_visitor<U> v; return operand->apply_visitor(v); } template <typename U, BOOST_VARIANT_ENUM_PARAMS(typename T) > inline typename add_pointer<const U>::type polymorphic_get( const boost::variant< BOOST_VARIANT_ENUM_PARAMS(T) >* operand BOOST_VARIANT_AUX_GET_EXPLICIT_TEMPLATE_TYPE(U) ) BOOST_NOEXCEPT { typedef typename add_pointer<const U>::type U_ptr; if (!operand) return static_cast<U_ptr>(0); detail::variant::get_polymorphic_visitor<const U> v; return operand->apply_visitor(v); } template <typename U, BOOST_VARIANT_ENUM_PARAMS(typename T) > inline typename add_reference<U>::type polymorphic_get( boost::variant< BOOST_VARIANT_ENUM_PARAMS(T) >& operand BOOST_VARIANT_AUX_GET_EXPLICIT_TEMPLATE_TYPE(U) ) { typedef typename add_pointer<U>::type U_ptr; U_ptr result = polymorphic_get<U>(&operand); if (!result) boost::throw_exception(bad_polymorphic_get()); return *result; } template <typename U, BOOST_VARIANT_ENUM_PARAMS(typename T) > inline typename add_reference<const U>::type polymorphic_get( const boost::variant< BOOST_VARIANT_ENUM_PARAMS(T) >& operand BOOST_VARIANT_AUX_GET_EXPLICIT_TEMPLATE_TYPE(U) ) { typedef typename add_pointer<const U>::type U_ptr; U_ptr result = polymorphic_get<const U>(&operand); if (!result) boost::throw_exception(bad_polymorphic_get()); return *result; } } // namespace boost #endif // BOOST_VARIANT_POLYMORPHIC_GET_HPP
6389e2fcd7c6742d269472abb53e431ed12b16e0
c9b02ab1612c8b436c1de94069b139137657899b
/server/app/data/DataBase.h
c0fa78d2d98b2ed9a66d73070d1a8350b6a305a2
[]
no_license
colinblack/game_server
a7ee95ec4e1def0220ab71f5f4501c9a26ab61ab
a7724f93e0be5c43e323972da30e738e5fbef54f
refs/heads/master
2020-03-21T19:25:02.879552
2020-03-01T08:57:07
2020-03-01T08:57:07
138,948,382
1
1
null
null
null
null
UTF-8
C++
false
false
8,769
h
#ifndef DATABASE_H_ #define DATABASE_H_ #include "Kernel.h" enum { COINTS_TYPE = 1, WOOD_TYPE = 2, FOOD_TYPE = 3, IRON_TYPE = 4, RESOURCE_TYPE = 5, }; enum { INTEGRA_TIME_CNT_INIT = 5,//整点/后勤奖励次数 PK_FIELD_CNT_INIT = 5, //竞技场次数 }; struct DataBase{ uint32_t uid; uint8_t register_platform;//注册平台 uint32_t register_time;//注册时间 uint32_t invite_uid;//邀请者id uint8_t last_login_platform;//上次登录平台 uint32_t last_login_time;//上次登录时间 uint32_t login_times;//连续登录次数 uint32_t login_days;//累计登录天数 uint32_t last_active_time;//上次活跃时间 uint32_t last_off_time;//上次下线时间 uint32_t forbid_ts;//封号到期时间 char forbid_reason[BASE_FORBID_REASON_LEN];//封号原因 uint16_t invite_count;//邀请次数 uint16_t today_invite_count;//今日邀请次数 uint16_t tutorial_stage;//新手教程步骤 char name[BASE_NAME_LEN];//名字 char fig[BASE_FIG_LEN];//头像url uint8_t kingdom;//国家 uint64_t exp;//经验 uint8_t level;//等级 uint32_t acccharge;//累计充值 uint8_t viplevel;//vip等级 uint32_t cash;//元宝 uint32_t coin;//铜币--钞票--民居 uint32_t wood;//木材--钢材--伐木厂 uint32_t food;//粮食--石油--田 uint32_t iron;//镔铁--黄金---矿场 uint32_t ticket;//点券 uint32_t silk;//(丝绸)废弃,作为回血ts uint16_t order;//募兵令 uint16_t bag;//背包格子 uint32_t preward;//内政功勋 uint8_t loyal;//民忠 uint8_t sacrifice;//免费祭祀次数 uint32_t market;//(集市次数)废弃,作为龙鳞 uint32_t bmarketcd;//黑市cd uint8_t banquet;//宴会次数 uint16_t eshopintimacy;//装备商店亲密度 uint32_t eshopcd;//装备商店cd uint8_t refresh;//免费洗练次数 uint8_t arefresh;//免费至尊洗练次数 uint8_t harmmer;//金色锤子次数 uint8_t shadow; //(影子次数)废弃,作为充点小钱和杀敌活跃的标志位 uint32_t up_res_time; //更新资源时间戳 uint32_t rests;//领取国战资源的时戳 uint8_t mp1;//国战个人任务状态 012 0--不可领取 1--可领取 2--已经领取 uint8_t mp2;//国战个人任务状态 012 uint8_t mk1;//国战国家任务状态 01 0--可领取 1--已经领取 uint8_t mk2;//国战国家任务状态 01 uint8_t rewardb;//国战功勋箱子数 uint8_t mp3;//国战个人任务状态 01 uint16_t npc_pass; //副本关卡 uint16_t flamen_coins_cnt; //花费元宝祭祀金币次数 uint16_t flamem_wood_cnt; //花费元宝祭祀木材 uint16_t flamem_food_cnt; //花费元宝祭祀食物 uint16_t flamem_iron_cnt; //花费元宝祭祀镔铁 uint8_t first_recharge; //首充 1--可领取 2--已经领取 uint8_t auto_build_flag; //建筑自动升级特权标志 uint8_t integral_time_cnt; //整点奖励次数 uint8_t vip_reward; //vip奖励领取进度 uint8_t use_ship; //运船次数 uint8_t rob_ship; //截船次数 uint8_t ladder; //竞技场次数 uint8_t mission_time; //政务次数 uint32_t mission_id; //政务id uint32_t ladder_ts; //领取竞技场奖励时间 uint32_t job_reward_ts; //领取军职奖励时间 uint32_t mine_normal_ts; //普通矿开启时间 uint32_t mine_reward_ts; //国家矿领取奖励时间 uint32_t mine_exp; //开矿经验 uint32_t token_op_ts; //响应官员令的时间戳 uint16_t pass_reward; //闯关送钻,位标记 uint32_t daily_refresh_ts; //每日任务的刷新时间 uint8_t daily_reward_times; //每日任务领取奖励次数 uint8_t daily_free_times; //每日任务已使用免费刷新次数 uint32_t harbor_reward_ts; //上次领取偷袭珍珠港奖励的时间 DataBase(){ uid = 0; register_platform = 0; register_time = 0; invite_uid = 0; last_login_platform = 0; last_login_time = 0; login_times = 0; login_days = 0; last_active_time = 0; last_off_time = 0; forbid_ts = 0; invite_count = 0; today_invite_count = 0; tutorial_stage = 0; kingdom = 0; exp = 0; level = 0; acccharge = 0; viplevel = 0; cash = 0; coin = 0; wood = 0; food = 0; iron = 0; ticket = 0; silk = 0; order = 0; bag = 0; preward = 0; loyal = 0; sacrifice = 0; market = 0; bmarketcd = 0; banquet = 0; eshopintimacy = 0; eshopcd = 0; refresh = 0; arefresh = 0; harmmer = 0; shadow = 0; up_res_time = 0; rests = 0; mp1 = 0; mp2 = 0; mp3 = 0; mk1 = 0; mk2 = 0; rewardb = 0; npc_pass = 0; flamen_coins_cnt = 0; flamem_wood_cnt = 0; flamem_food_cnt = 0; flamem_iron_cnt = 0; first_recharge = 0; auto_build_flag = 0; integral_time_cnt = 0; vip_reward = 0; use_ship = 0; rob_ship = 0; ladder = 0; mission_time = 0; mission_id = 0; ladder_ts = 0; job_reward_ts = 0; mine_normal_ts = 0; mine_reward_ts = 0; mine_exp = 0; token_op_ts = 0; pass_reward = 0; daily_refresh_ts = 0; daily_reward_times = 0; daily_free_times = 0; harbor_reward_ts = 0; memset(forbid_reason, 0, sizeof(forbid_reason)); memset(name, 0, sizeof(name)); memset(fig, 0, sizeof(fig)); } void SetMessage(User::Base* msg) { msg->set_register_platform(register_platform); msg->set_register_time(register_time); msg->set_invite_uid(invite_uid); msg->set_last_login_platform(last_login_platform); msg->set_last_login_time(last_login_time); msg->set_login_times(login_times); msg->set_login_days(login_days); msg->set_last_active_time(last_active_time); msg->set_last_off_time(last_off_time); msg->set_forbid_ts(forbid_ts); msg->set_forbid_reason(string(forbid_reason)); msg->set_invite_count(invite_count); msg->set_today_invite_count(today_invite_count); msg->set_tutorial_stage(tutorial_stage); msg->set_name(string(name)); msg->set_fig(string(fig)); msg->set_kingdom(kingdom); msg->set_exp(exp); msg->set_level(level); msg->set_acccharge(acccharge); msg->set_viplevel(viplevel); msg->set_cash(cash); msg->set_coin(coin); msg->set_wood(wood); msg->set_food(food); msg->set_iron(iron); msg->set_ticket(ticket); msg->set_silk(silk); msg->set_order(order); msg->set_bag(bag); msg->set_preward(preward); msg->set_loyal(loyal); msg->set_sacrifice(sacrifice); msg->set_market(market); msg->set_bmarketcd(bmarketcd); msg->set_banquet(banquet); msg->set_eshopintimacy(eshopintimacy); msg->set_eshopcd(eshopcd); msg->set_refresh(refresh); msg->set_arefresh(arefresh); msg->set_harmmer(harmmer); msg->set_shadow(shadow); msg->set_up_res_time(up_res_time); msg->set_rests(rests); msg->set_mp1(mp1); msg->set_mp2(mp2); msg->set_mp3(mp3); msg->set_mk1(mk1); msg->set_mk2(mk2); msg->set_rewardb(rewardb); msg->set_npc_pass(npc_pass); msg->set_flamem_food_cnt(flamem_food_cnt); msg->set_flamem_wood_cnt(flamem_wood_cnt); msg->set_flamen_coins_cnt(flamen_coins_cnt); msg->set_flamem_iron_cnt(flamem_iron_cnt); msg->set_first_recharge(first_recharge); msg->set_auto_build_flag(auto_build_flag); msg->set_integral_time_cnt(integral_time_cnt); msg->set_mission_time(mission_time); msg->set_mission_id(mission_id); msg->set_vip_reward(vip_reward); msg->set_ladder(ladder); msg->set_ladder_ts(ladder_ts); msg->set_job_reward_ts(job_reward_ts); msg->set_token_ts(token_op_ts); msg->set_daily_refresh_ts(daily_refresh_ts); msg->set_daily_reward_times(daily_reward_times); msg->set_daily_free_times(daily_free_times); } void FullBuildSyncMessage(ProtoBuilding::BuildUserSyncInfo* obj) const { obj->set_total_exploit(preward); obj->set_user_coins(coin); obj->set_user_woods(wood); obj->set_user_exp(exp); obj->set_user_level(level); } void FullResourceMessage(ProtoBuilding::BuildResourceSyncResq* obj) const { obj->set_coin(coin); obj->set_wood(wood); obj->set_food(food); obj->set_iron(iron); } bool IsOnline() { return last_off_time < last_login_time; } bool CanOff() { return IsOnline() && last_active_time + 12 * 3600 < Time::GetGlobalTime(); } bool CanClear() { return !IsOnline() && last_off_time + 300 < Time::GetGlobalTime(); } void AddExp(int exp); void AddFlamenBuyCnt(int type, int cnt); uint16_t GetFlamenBuyCnt(int type); // uint32_t GetResource(int type); void AddResource(int type, int val); void RefreshIntegralTime(); //重置国家任务状态 void ResetCountryTaskStatus(); }; class CDataBase :public DBCBase<DataBase, DB_BASE> { public: virtual int Get(DataBase &data); virtual int Add(DataBase &data); virtual int Set(DataBase &data); virtual int Del(DataBase &data); }; struct DataUser { uint32_t uid; string name; uint32_t level; uint64_t exp; uint8_t viplevel; DataUser(): uid(0), name(""), level(0), exp(0), viplevel(0) { } }; #endif /* DATABASE_H_ */
c6ba8d5667f063dcb4f0ae4b03756dae7bb0925c
86a8184a35cc8a23f44c21827f21d99540d02f5b
/cocos2d-x-2.2.3/projects/touchball/Classes/scene/map/touchMap.cpp
c25366a9d073cd28061176b85383b7ea0dabe5da
[ "MIT" ]
permissive
jfjl/chengxu
947b6f2c1347637dd10c672d8537d52672dd6054
e05023c31173bb31bf341ec68605f29280cecb39
refs/heads/master
2021-01-22T11:58:30.695890
2014-07-08T11:50:23
2014-07-08T11:50:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,330
cpp
// touchMap.cpp // ppball // // Created by carlor on 13-3-13. // // #include "touchMap.h" #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS #include "ClientData.h" #elif CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID #include "../../datas/ClientData.h" #endif touchMap::touchMap(void) : m_PathFinder(NULL), m_actionBalls(NULL), m_pPropsManager(NULL) { } touchMap::~touchMap(void) { clear(); CC_SAFE_DELETE(m_actionBalls); CC_SAFE_DELETE(m_PathFinder); CC_SAFE_DELETE(m_mapCells); CC_SAFE_DELETE(m_pPropsManager); m_mShapes.clear(); } void touchMap::clear() { m_actionBalls->removeAllObjects(); m_mMaskSprite.clear(); } bool touchMap::init(const char*fileName, int width, int height) { if (ballMap::init(fileName, width, height)){ setTouchEnabled(true); setMapState(MapStateNormal); m_PathFinder = pathFinder::create(this, getWidth(), getHeight()); m_actionBalls = CCDictionary::create(); m_actionBalls->retain(); m_BallManager->setPosition(ccp(BALLMARGIN_LEFT, BALLMARGIN_TOP)); m_pPropsManager = PropsManager::create(this, width, height); this->addChild(m_pPropsManager); m_mMaskSprite.clear(); this->setPosition(ccp(SCENEMARGIN_LEFT, SCENEMARGIN_TOP)); m_MarginX = 0; m_MarginY = 0; m_Margin = MAPCELL_SIZE; return true; } return false; } touchMap* touchMap::create(const char*fileName, int width, int height) { touchMap *pTouchMap = new touchMap(); pTouchMap->init(fileName, width, height); pTouchMap->autorelease(); return pTouchMap; } //////////////event bool touchMap::checkOver() { CCArray *visballs = new CCArray(); this->getBallManager()->getVisibleBall(false, visballs); int count = 0; CCObject *pElement; CCARRAY_FOREACH(visballs, pElement) { ball *pball = (ball*) pElement; mapCell* pCell = (mapCell*) m_mapCells->objectAtIndex(m_BallManager->getKey(pball->getPos().x, pball->getPos().y)); if (pCell->getState() == MC_STATE_NOMOVE || pCell->getState() == MC_STATE_BLOCK) { count++; } } bool isOver = visballs->count() - count <= 0; visballs->removeAllObjects(); CC_SAFE_DELETE(visballs); return isOver; } void touchMap::remove(CCArray *balls) { setActionCount(balls->count()); for (int i = 0; i < balls->count(); i++){ ball *temp = (ball*) balls->objectAtIndex(i); this->playAction(temp); this->getBallManager()->playHide(temp); } } bool touchMap::checkRemove() { int removeCount = REMOVECOUNT; const levelCfg* pLevelCfg = g_clientData->getLevelCfg(m_level); if (pLevelCfg) removeCount = pLevelCfg->RemoveCount; m_mShapes.clear(); CCArray *balls = new CCArray(); CCDictElement *pElement; CCDICT_FOREACH(m_actionBalls, pElement) { ball *pball = (ball*) pElement->getObject(); int shape = 0; CCArray *removeBalls = m_BallManager->checkRemove(pball, removeCount, shape); if (removeBalls->count() >= removeCount - 1){ for (int i = 0; i < removeBalls->count(); i++) { ball* tempball = (ball*) removeBalls->objectAtIndex(i); if (balls->containsObject(tempball)) continue; balls->addObject(tempball); } if (! balls->containsObject(pball)) { balls->addObject(pball); if (shape) m_mShapes[m_BallManager->getKey(pball->getPos().x, pball->getPos().y)] = shape; } } removeBalls->removeAllObjects(); CC_SAFE_DELETE(removeBalls); } bool result = balls->count() >= removeCount; if (result){ m_BallManager->getRemoveBall(balls); CCNotificationCenter::sharedNotificationCenter()->postNotification(EVENT_SCENE_REMOVE, (CCObject*)balls); remove(balls); } balls->removeAllObjects(); CC_SAFE_DELETE(balls); return result; } bool touchMap::onEnterEvent(CCObject *pball) { //ball *temp = dynamic_cast<ball *> (pball); //m_actionBalls->removeObjectForKey(temp->getID()); return --m_ActionCount <= 0; } void touchMap::onShowComplete(CCObject *pball) { if (! onEnterEvent(pball)) return; if (! checkRemove()) { if (checkOver()) CCNotificationCenter::sharedNotificationCenter()->postNotification(EVENT_GAME_COMPLETE, (CCObject*)this); } m_actionBalls->removeAllObjects(); } void touchMap::onHideComplete(CCObject *pball) { ball *temp = dynamic_cast<ball *> (pball); m_pPropsManager->onRemoveBall(getPosition(temp->getPos().x, temp->getPos().y)); if (! onEnterEvent(pball)) return; m_actionBalls->removeAllObjects(); //检查是否出现奖励球 bool bShow = false; for (map<int, int>::iterator it = m_mShapes.begin(); it != m_mShapes.end(); it++) { int px = it->first % GAMEMAPSIZE_WIDTH; int py = it->first / GAMEMAPSIZE_WIDTH; ball* pball = m_BallManager->getBall(px, py); if (! pball) continue; const ballCfg* pballCfg = g_clientData->getBallCfg(pball->getClassID()); if (! pballCfg) continue; int shape = it->second; const awardBallCfg* pawardBallCfg = g_clientData->getAwardBallCfg(shape); if (! pawardBallCfg) continue; int id = pballCfg->nBasicBall + pawardBallCfg->BallType * 10; const ballCfg* pawardCfg = g_clientData->getBallCfg(id); if (! pawardCfg) continue; incActionCount(); playAction(pball); m_BallManager->playShow(id, px, py); bShow = true; } if (! bShow) CCNotificationCenter::sharedNotificationCenter()->postNotification(EVENT_SCENE_NEXT, (CCObject*)this); } void touchMap::onMoveComplete(ball *pball) { m_ActionCount = 0; m_actionBalls->removeAllObjects(); m_actionBalls->setObject(pball, pball->getID()); if (! checkRemove()) CCNotificationCenter::sharedNotificationCenter()->postNotification(EVENT_SCENE_NEXT, (CCObject*)this); } void touchMap::addEventLister(CCObject *pball) { CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(touchMap::onShowComplete), EVENT_ACTION_SHOWCOMPLETE, NULL); CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(touchMap::onHideComplete), EVENT_ACTION_HIDECOMPLETE, NULL); } void touchMap::playAction(ball *pball) { m_actionBalls->setObject(pball, pball->getID()); } void touchMap::incActionCount() { m_ActionCount++; } ///////////////////////update void touchMap::onUpate(float dt) { bool nextStep = true; switch (getMapState()) { case MapStateShow: break; case MapStateMove: nextStep = onUpdateMove(dt); break; case MapStateHide: break; default: break; } if (nextStep){ setMapState(MapStateNormal); } } bool touchMap::onUpdateMove(float dt) { int nextPos = m_PathFinder->getNextNode(); if (nextPos >= 0){ ball *pball = m_BallManager->getBall(getCurMovePos()); m_BallManager->hide(pball->getID()); setCurMovePos(nextPos); m_BallManager->show(pball->getClassID(), nextPos); } if (nextPos < 0){ ball *pball = m_BallManager->getBall(m_PathFinder->getDestPosition()); onMoveComplete(pball); } return nextPos < 0; } /////////////////////////event void touchMap::registerWithTouchDispatcher(void) { CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, kCCMenuHandlerPriority, true); } CCPoint touchMap::getLocalPoint(CCPoint value) { float s = MAPCELL_SIZE * GAMESCALE; return CCPointMake(floor((value.x - BALLMARGIN_LEFT - SCENEMARGIN_LEFT) / s), floor((value.y - BALLMARGIN_TOP - SCENEMARGIN_TOP) / s)); } bool touchMap::checkMove(int srcPos, int x, int y) { if (m_PathFinder->inBlockList(y*getWidth()+x)) return false; return m_PathFinder->onMoveBall(srcPos, y*getWidth()+x); } bool touchMap::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent) { CCPoint touchPoint = pTouch->getLocationInView(); touchPoint = CCDirector::sharedDirector()->convertToGL( touchPoint ); int oldSel = getBallManager()->getSelectId(); CCPoint p = getLocalPoint(touchPoint); if (p.x < 0 || p.x >= m_Width || p.y < 0 || p.y >= m_Height) return false; int id = getBallManager()->select(p.x, p.y); if (id < 0 && oldSel >= 0){ if (checkMove(oldSel, p.x, p.y)){ CCNotificationCenter::sharedNotificationCenter()->postNotification(EVENT_BALL_MOVE, (CCObject *)this); //move setCurMovePos(oldSel); setMapState(MapStateMove); getBallManager()->setSelectId(-1); } } m_pPropsManager->put(getPosition(p.x, p.y)); return false; } void touchMap::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent) { } void touchMap::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent) { } void touchMap::ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent) { } //////// void touchMap::createMask(int pos, int r, int g, int b) { float s = MAPCELL_SIZE;// * TEXTURESCALE; int w = getWidth(); CCLayerColor* pSprite = CCLayerColor::create();//("mask.png"); pSprite->setColor(ccc3(r, g, b)); pSprite->setContentSize(CCSize(s, s)); pSprite->setOpacity(150); int x = pos % w; int y = pos / w; pSprite->setPosition(ccp(s * x + BALLMARGIN_LEFT, s * y + BALLMARGIN_TOP )); this->addChild(pSprite); m_mMaskSprite[pos] = pSprite; } void touchMap::deleteMask(int pos) { map<int, CCLayerColor*>::iterator it = m_mMaskSprite.find(pos); if (it == m_mMaskSprite.end()) return; this->removeChild(it->second); m_mMaskSprite.erase(it); } void touchMap::setLevel(int level) { if (m_level == level) return; clear(); m_level = level; const levelCfg* pLevelCfg = g_clientData->getLevelCfg(level); if (! pLevelCfg) { return; //CCSpriteFrame *frame=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("headleft.png"); //m_Backgound->setDisplayFrame(frame); } const mapCfg* pMapCfg = g_clientData->getMapCfg(pLevelCfg->MapId); if (! pMapCfg) { return; } for (size_t i = 0; i < pMapCfg->vMapCell.size(); i++) { if (pMapCfg->vMapCell[i] == 0) continue; mapCell* pMapCell = getMapCell(i); if (! pMapCell) continue; switch (pMapCfg->vMapCell[i]) { case 1: pMapCell->setState(MC_STATE_BLOCK); createMask(i, 255, 0, 0); break; default: m_pPropsManager->show(i, pMapCfg->vMapCell[i]); break; } } } int touchMap::getLevel() { return m_level; } void touchMap::getRandomPosition(std::vector<int> *pos, int count) { CCArray *visballs = new CCArray(); m_BallManager->getVisibleBall(false, visballs); while (pos->size() < count && visballs->count() > 0){ int index = rand() % visballs->count(); int p = dynamic_cast<ball*>(visballs->objectAtIndex(index))->getID(); if (! m_PathFinder->inBlockList(p)) pos->push_back(p); visballs->removeObjectAtIndex(index); } CC_SAFE_DELETE(visballs); } /////////////////props void touchMap::maskMap(int pos, int maskType) { mapCell* pMapCell = getMapCell(pos); if (! pMapCell) return; pMapCell->setState(maskType); int r = 0, g = 0, b = 0; switch (maskType) { case MC_STATE_MASK: b = 255; break; case MC_STATE_NOMOVE: g = 255; break; case MC_STATE_BLOCK: r = 255, g = 100; break; default: r = 255, g = 255; break; } createMask(pos, r, g, b); } void touchMap::disMaskMap(int pos) { mapCell* pMapCell = getMapCell(pos); if (! pMapCell) return; deleteMask(pos); pMapCell->setState(MC_STATE_NORMAL); m_pPropsManager->hide(pos); } ///////////////Script int touchMap::script_destroyBall(lua_State* L) { int p = m_pPropsManager->getSelectPos(); ball* pBall = m_BallManager->getBall(p); if (! pBall) return 0; pBall->setVisible(false, false); m_pPropsManager->pick(0); return 1; } int touchMap::script_getOldSelect(lua_State* L) { lua_pushnumber(L, m_BallManager->getOldSelectId()); return 1; } int touchMap::script_getSelect(lua_State* L) { lua_pushnumber(L, m_BallManager->getSelectId()); return 1; } int touchMap::script_changePosition(lua_State* L) { int result = 0; int paramCount = lua_gettop(L) - 2; if (paramCount != 2) { lua_pushboolean(L, result); return result; } int oldp = lua_tonumber(L, 3); int newp = lua_tonumber(L, 4); m_BallManager->changePosition(oldp, newp); result = 1; lua_pushboolean(L, result); return result; } int touchMap::script_disableSpecialBall(lua_State* L) { return 0; } int touchMap::script_clearSelectProps(lua_State* L) { m_pPropsManager->pick(0); return 1; } int touchMap::script_getBall(lua_State* L) { int result = 0; int paramCount = lua_gettop(L) - 2; if (paramCount != 1) { lua_pushboolean(L, result); return result; } int p = lua_tonumber(L, 3); ball* pball = m_BallManager->getBall(p); if (pball && pball->isVisible()) { lua_pushlightuserdata(L, pball); }else{ lua_pushboolean(L, false); } return 1; } int touchMap::script_moveto(lua_State* L) { int result = 0; int paramCount = lua_gettop(L) - 2; if (paramCount != 2) { lua_pushboolean(L, result); return result; } int p = lua_tonumber(L, 3); ball* pselect = m_BallManager->getBall(m_BallManager->getSelectId()); if (! pselect || ! pselect->isVisible()) return result; int flag = lua_tonumber(L, 4); if (flag) { ball* pball = m_BallManager->getBall(p); if (! pball || pball->isVisible()) return result; pball->setBallClass(pselect->getClassID()); m_BallManager->show(pselect->getClassID(), p); m_BallManager->hide(pselect->getPos().x, pselect->getPos().y); }else{ m_PathFinder->onMoveBall(m_BallManager->getKey(pselect->getPos().x, pselect->getPos().y), p); } return 1; } int touchMap::callFunction(lua_State* L) { const char* funcName = lua_tostring(L, 2); if (strcmp(funcName, "destroyBall") == 0) return script_destroyBall(L); else if (strcmp(funcName, "getOldSelect") == 0) return script_getOldSelect(L); else if (strcmp(funcName, "getSelect") == 0) return script_getSelect(L); else if (strcmp(funcName, "changePosition") == 0) return script_changePosition(L); else if (strcmp(funcName, "disableSpecialBall") == 0) return script_disableSpecialBall(L); else if (strcmp(funcName, "clearSelectProps") == 0) return script_clearSelectProps(L); else if (strcmp(funcName, "getBall") == 0) return script_getBall(L); else if (strcmp(funcName, "moveto") == 0) return script_moveto(L); return 1; }
c19be88ca6252650e3e53f7d771a892aef126ba0
deb996979262cd31a1086a415ad6f8971aae9a2a
/example1.cpp
c39a1f48189dba249634b8ebab9d9ae60d445704
[]
no_license
harperchen/PinTaint
a881b3e2405497fb75b1cefa31b8c70b1775ab66
03cf3e009d3f7e4f7bee09ea474caa884604fb1e
refs/heads/master
2022-12-02T10:26:40.658934
2020-08-20T16:25:21
2020-08-20T16:25:21
289,011,647
1
0
null
null
null
null
UTF-8
C++
false
false
3,021
cpp
#include <fstream> #include <asm/unistd.h> #include <list> #include <iostream> #include "pin.H" using namespace std; // http://shell-storm.org/blog/Taint-analysis-and-pattern-matching-with-Pin/ /* area of bytes tainted */ struct range { UINT64 start; UINT64 end; }; std::list<struct range> bytesTainted; INT32 Usage() { cerr << "Ex 1" << endl; return -1; } VOID ReadMem(UINT64 insAddr, std::string insDis, UINT64 memOp) { list<struct range>::iterator i; UINT64 addr = memOp; for(i = bytesTainted.begin(); i != bytesTainted.end(); ++i){ if (addr >= i->start && addr < i->end){ std::cout << std::hex << "[READ in " << addr << "]\t" << insAddr << ": " << insDis<< std::endl; } } } VOID WriteMem(UINT64 insAddr, std::string insDis, UINT64 memOp) { list<struct range>::iterator i; UINT64 addr = memOp; for(i = bytesTainted.begin(); i != bytesTainted.end(); ++i){ if (addr >= i->start && addr < i->end){ std::cout << std::hex << "[WRITE in " << addr << "]\t" << insAddr << ": " << insDis<< std::endl; } } } VOID Instruction(INS ins, VOID *v) { if (INS_MemoryOperandIsRead(ins, 0) && INS_OperandIsReg(ins, 0)){ INS_InsertCall( ins, IPOINT_BEFORE, (AFUNPTR)ReadMem, IARG_ADDRINT, INS_Address(ins), IARG_PTR, new string(INS_Disassemble(ins)), IARG_MEMORYOP_EA, 0, IARG_END); } else if (INS_MemoryOperandIsWritten(ins, 0)){ INS_InsertCall( ins, IPOINT_BEFORE, (AFUNPTR)WriteMem, IARG_ADDRINT, INS_Address(ins), IARG_PTR, new string(INS_Disassemble(ins)), IARG_MEMORYOP_EA, 0, IARG_END); } } static unsigned int lock; #define TRICKS(){if (lock++ == 0)return;} VOID Syscall_entry(THREADID thread_id, CONTEXT *ctx, SYSCALL_STANDARD std, void *v) { struct range taint; /* If the syscall is read take the branch */ if (PIN_GetSyscallNumber(ctx, std) == __NR_read){ TRICKS(); /* Get the second argument */ taint.start = static_cast<UINT64>((PIN_GetSyscallArgument(ctx, std, 1))); /* Get the third argument */ taint.end = taint.start + static_cast<UINT64>((PIN_GetSyscallArgument(ctx, std, 2))); /* Add this area in our tainted bytes list */ bytesTainted.push_back(taint); /* Just display information */ std::cout << "[TAINT]\t\t\tbytes tainted from " << std::hex << "0x" << taint.start \ << " to 0x" << taint.end << " (via read)"<< std::endl; } } int main(int argc, char *argv[]) { /* Init Pin arguments */ if(PIN_Init(argc, argv)){ return Usage(); } // PIN_SetSyntaxIntel(); /* Add the syscall handler */ PIN_AddSyscallEntryFunction(Syscall_entry, 0); // Register Instruction to be called to instrument instructions INS_AddInstrumentFunction(Instruction, 0); /* Start the program */ PIN_StartProgram(); return 0; }
98d477fbd02721cc612a3c126e7b204086027e5b
f082493a8cbf47dc9f44b390f3a96df850123e25
/maxQOriginalCode/release/h-fuel-maxq.c
a2fa291fa77531a214430cc1cb37a8a729f716cd
[]
no_license
nakulgopalan/amdpTestRepo
37d18372112378d85387537228137020e0518a3c
a4cc0d93943c8979b59439ef18027d5906dc7ba0
refs/heads/master
2020-02-26T15:27:36.730210
2016-07-21T16:18:58
2016-07-21T16:18:58
63,868,710
0
0
null
null
null
null
UTF-8
C++
false
false
20,521
c
// -*- C++ -*- // // Hierarchical Q learning maxq hierarchy for taxi task. // // #include "predicate.h" #include "taxi.h" #include "fueltaxi.h" #include "hq.h" #include "parameter.h" #include "hq-features.h" #include "global.h" #include <minmax.h> #include <stdlib.h> // ---------------------------------------------------------------------- // // inherit termination // // ---------------------------------------------------------------------- // In this domain, we do not inherit termination of parent nodes. int inheritTerminationPredicates = 0; int impTFalse(FuelTaxiState & state, ActualParameterList & apl) { return 0; } Predicate TFalse( /* name */ "TFalse", /* function */ &impTFalse, /* parameters */ 0); int impTTrue(FuelTaxiState & state, ActualParameterList & apl) { return 1; } Predicate TTrue( /* name */ "TTrue", /* function */ &impTTrue, /* parameters */ makeArgs()); // ---------------------------------------------------------------------- // // Parameter Types // // ---------------------------------------------------------------------- ParameterType * AnySite = new ParameterType("FuelSite", (int) Red, (int) Fuel); // hack warning: state.source is an enumerated type with values {Red, // Green, Blue, Yellow, Fuel, Held, None}. We use its value directly // for PTarget, which is of type AnySite, and for PSource. However, // sometimes we need a variable whose value can be {Red, Green, Blue, // Yellow, Held}. We have defined another feature, PSourceOrHeld, for // this purpose. PSource takes on values {Red, Green, Blue, Yellow}, // so it should only be used in cases where we know we are not holding // a passenger. // ---------------------------------------------------------------------- // // Primitive nodes // // ---------------------------------------------------------------------- MaxNode MaxNorth ("MaxNorth", &ActNorth); MaxNode MaxEast ("MaxEast", &ActEast); MaxNode MaxSouth ("MaxSouth", &ActSouth); MaxNode MaxWest ("MaxWest", &ActWest); MaxNode MaxPickup ("MaxPickup", &ActPickup); MaxNode MaxPutdown ("MaxPutdown", &ActPutdown); MaxNode MaxFillup ("MaxFillup", &ActFillup); list<ParameterName *> * allFeatures = makeList(&PTaxiX, &PTaxiY, &PSourceOrHeld, &PDestination, &PFuel); // ---------------------------------------------------------------------- // // Navigation // // ---------------------------------------------------------------------- // // Each navigation node must estimate the cost-to-go of completing the // navigation. Hence, it needs to know its current location (PTaxiX // and PTaxiY) and also the target. QNode QNorth( /* name */ "QNorth", /* parameters */ makeArgs(AnySite, &PTarget), /* child */ MaxNorth, /* child args */ makePPL(), /* features */ makeList(&PTarget, &PTaxiX, &PTaxiY), /* nhidden */ 4, /* minValue */ -40.123, /* maxvalue */ 0.0, /* useTable */ 1); QNode QEast( /* name */ "QEast", /* parameters */ makeArgs(AnySite, &PTarget), /* child */ MaxEast, /* child args */ makePPL(), /* features */ makeList(&PTarget, &PTaxiX, &PTaxiY), /* nhidden */ 4, /* minValue */ -40.123, /* maxvalue */ 0.0, /* useTable */ 1); QNode QSouth( /* name */ "QSouth", /* parameters */ makeArgs(AnySite, &PTarget), /* child */ MaxSouth, /* child args */ makePPL(), /* features */ makeList(&PTarget, &PTaxiX, &PTaxiY), /* nhidden */ 4, /* minValue */ -40.123, /* maxvalue */ 0.0, /* useTable */ 1); QNode QWest( /* name */ "QWest", /* parameters */ makeArgs(AnySite, &PTarget), /* child */ MaxWest, /* child args */ makePPL(), /* features */ makeList(&PTarget, &PTaxiX, &PTaxiY), /* nhidden */ 4, /* minValue */ -40.123, /* maxvalue */ 0.0, /* useTable */ 1); int impTAtTarget(FuelTaxiState & state, ActualParameterList & apl) { int target = apl[&PTarget]; return state.location == (*Sites)[target]; } Predicate TAtTarget( /* name */ "AtTarget", /* function */ &impTAtTarget, /* parameters */ makeArgs(AnySite, &PTarget)); QNode * PolicyNavigate(FuelTaxiState & state, ActualParameterList & apl, ActualParameterList & cpl) { int target = apl[&PTarget]; if (target == Red) { if (state.location.x < 2) { if (state.location.y < 4) return &QNorth; else return &QWest; } else if (state.location.y == 2) return &QWest; else if (state.location.y > 2) return &QSouth; else return &QNorth; } else if (target == Yellow) { if (state.location.x == 0) return &QSouth; else if (state.location.y == 2) return &QWest; else if (state.location.y > 2) return &QSouth; else return &QNorth; } else if (target == Green) { if (state.location.x > 1) { if (state.location.y < 4) return &QNorth; else return &QEast; } else if (state.location.y == 2) return &QEast; else if (state.location.y > 2) return &QSouth; else return &QNorth; } else if (target == Blue) { if (state.location.x > 2) { if (state.location.y > 0) return &QSouth; else return &QWest; } else if (state.location.y == 2) return &QEast; else if (state.location.y > 2) return &QSouth; else return &QNorth; } #if 0 else if (target == Fuel) { if (state.location.x < 1) { if (state.location.y == 2) return &QEast; else if (state.location.y > 2) return &QSouth; else return &QNorth; } else if (state.location.x > 2) { if (state.location.y == 2) return &QWest; else if (state.location.y > 2) return &QSouth; else return &QNorth; } // in the MD region. Get y right first. else if (state.location.y == 1) return &QEast; else if (state.location.y > 1) return &QSouth; else return &QNorth; } #endif else if (target == Fuel) { if (state.location.x == 2) { if (state.location.y < 1) return &QNorth; else return &QSouth; } else if (state.location.x == 0) { if (state.location.y > 2) return &QSouth; else if (state.location.y < 2) return &QNorth; else return &QEast; } else if (state.location.x == 1) { if (state.location.y > 2) return &QSouth; else return &QEast; } else if (state.location.x > 2) { if (state.location.y > 2) return &QSouth; else if (state.location.y < 2) return &QNorth; else return &QWest; } } else { cout << "Unknown Target " << target << endl; abort(); } } MaxNode MaxNavigate( /* name */ "MaxNavigate", /* parameters */ makeArgs(AnySite, &PTarget), /* precondition pred */ &TTrue, /* termination predicate */ &TAtTarget, /* goal predicate */ &TAtTarget, /* children */ makeList(&QNorth, &QEast, &QSouth, &QWest), /* features */ makeList(&PTaxiX, &PTaxiY, &PTarget), /* policy */ &PolicyNavigate, /* nonGoal penalty */ -100.0); // ---------------------------------------------------------------------- // // Get // // ---------------------------------------------------------------------- // We only need to estimate the cost of finishing the parent task // (Get) after completing the navigation. This is just a single // action, so we don't need any features here. // Sun Mar 21 11:51:36 1999 I have added a feature to make this // consistent with the paper. Because of our representation of the // state space, the four source states are in different equivalence // classes, and must therefore have separate values. QNode QNavigateForGet( /* name */ "QNavigateForGet", /* parameters */ makeArgs(), /* child */ MaxNavigate, /* child args */ makePPL(&PSource, &PTarget), /* features */ makeList(&PSource), /* nhidden */ 4, /* minValue */ -40.123, /* maxvalue */ 0.0, /* useTable */ 1); // We need to model the cost of completing the Navigate after // inappropriately executing a QPickup. For now, I will not do any // feature engineering. QNode QPickup( /* name */ "QPickup", /* parameters */ makeArgs(), /* child */ MaxPickup, /* child args */ makePPL(), /* features */ makeList(&PSource, &PTaxiX, &PTaxiY), /* nhidden */ 4, /* minValue */ -40.123, /* maxvalue */ 0.0, /* useTable */ 1); extern int EVALVERBOSE; int impTHolding(FuelTaxiState & state, ActualParameterList & apl) { int result = (state.source == Held); if (EVALVERBOSE) cout << "impTHolding = " << result << endl; return result; } Predicate THolding( /* name */ "Holding", /* function */ &impTHolding, /* parameters */ makeArgs()); QNode * PolicyGet(FuelTaxiState & state, ActualParameterList & apl, ActualParameterList & cpl) { if (state.location == state.SourcePoint()) return &QPickup; else return &QNavigateForGet; } // Goal is to be holding the customer at the source location. MaxNode MaxGet( /* name */ "MaxGet", /* parameters */ makeArgs(), /* precondition pred */ &TTrue, /* termination predicate */ &THolding, /* goal predicate */ &THolding, /* children */ makeList(&QNavigateForGet, &QPickup), /* features */ makeList(&PTaxiX, &PTaxiY, &PSourceOrHeld), /* policy */ &PolicyGet, /* nonGoal penalty */ -100.0); // ---------------------------------------------------------------------- // // Put // // ---------------------------------------------------------------------- // We only need to estimate the cost of finishing the parent task // (Put) after completing the nagivation. This is just a single // action, so we don't need any features here either. // We are protected from inappropriate invocation by the termination // condition of MaxNavigate. // Sun Mar 21 11:53:19 1999 added Destination feature for consistency // with paper QNode QNavigateForPut( /* name */ "QNavigateForPut", /* parameters */ makeArgs(), /* child */ MaxNavigate, /* child args */ makePPL(&PDestination, &PTarget), /* features */ makeList(&PDestination), /* nhidden */ 4, /* minValue */ -40.123, /* maxvalue */ 0.0, /* useTable */ 1); // This needs to handle the case where we attempt to Putdown before we // are at the target position. QNode QPutdown( /* name */ "QPutdown", /* parameters */ makeArgs(), /* child */ MaxPutdown, /* child args */ makePPL(), /* features */ makeList(&PDestination, &PTaxiX, &PTaxiY), /* nhidden */ 4, /* minValue */ -40.123, /* maxvalue */ 0.0, /* useTable */ 1); int impTNotHolding(FuelTaxiState & state, ActualParameterList & apl) { return state.source != Held; } Predicate TNotHolding( /* name */ "NotHolding", /* function */ &impTNotHolding, /* parameters */ makeArgs()); int impTNotHoldingAtDestination(FuelTaxiState & state, ActualParameterList & apl) { // If we succeed, then the source is set to None and the // simulation is terminated. return (state.source == None); } Predicate TNotHoldingAtDestination( /* name */ "NotHoldingAtDestination", /* function */ &impTNotHoldingAtDestination, /* parameters */ makeArgs()); QNode * PolicyPut(FuelTaxiState & state, ActualParameterList & apl, ActualParameterList & cpl) { if (state.location == state.DestinationPoint()) return &QPutdown; else return &QNavigateForPut; } MaxNode MaxPut( /* name */ "MaxPut", /* parameters */ makeArgs(), /* precondition pred */ &TTrue, /* termination predicate */ &TNotHolding, /* goal predicate */ &TNotHoldingAtDestination, /* children */ makeList(&QNavigateForPut, &QPutdown), /* features */ makeList(&PTaxiX, &PTaxiY, &PSourceOrHeld, &PDestination, &PFuel), /* policy */ &PolicyPut, /* nonGoal penalty */ -100.0); // ---------------------------------------------------------------------- // // Refuel // // ---------------------------------------------------------------------- // We need to estimate the cost of completing the refueling after we // have reached the Fuel location. This will always be trivial. So // we have no features. We pass the Fuel Site name as a parameter to // MaxNavigate. QNode QNavigateForRefuel( /* name */ "QNavigateForRefuel", /* parameters */ makeArgs(), /* child */ MaxNavigate, /* child args */ makePPL(&PFuelSite, &PTarget), /* features */ 0, /* nhidden */ 4, /* minValue */ -40.123, /* maxvalue */ 0.0, /* useTable */ 1); // This is a primitive. But we need to determine whether we are at // the fuel location or not. Hence, we need our current location. QNode QFillup( /* name */ "QFillup", /* parameters */ makeArgs(), /* child */ MaxFillup, /* child args */ makePPL(), /* features */ makeList(&PTaxiX, &PTaxiY), /* nhidden */ 4, /* minValue */ -40.123, /* maxvalue */ 0.0, /* useTable */ 1); int impTFuelFull(FuelTaxiState & state, ActualParameterList & apl) { return (state.fuel == 12 && state.location == state.FuelPoint()); } Predicate TFuelFull( /* name */ "TFuelFull", /* function */ &impTFuelFull, /* parameters */ makeArgs()); QNode * PolicyRefuel(FuelTaxiState & state, ActualParameterList & apl, ActualParameterList & cpl) { if (state.location == state.FuelPoint()) return &QFillup; else return &QNavigateForRefuel; } // // I'm not sure what to put for the features here. My guess is that I // only need to know taxi location and amount of fuel, everything else // remains unchanged by refueling // MaxNode MaxRefuel( /* name */ "MaxRefuel", /* parameters */ makeArgs(), /* precondition pred */ &TTrue, /* termination predicate */ &TFuelFull, /* goal predicate */ &TFuelFull, /* children */ makeList(&QNavigateForRefuel, &QFillup), /* features */ makeList(&PTaxiX, &PTaxiY, &PFuel), /* policy */ &PolicyRefuel, /* nonGoal penalty */ -100.0); // ---------------------------------------------------------------------- // // Top Level // // ---------------------------------------------------------------------- // We need to estimate the cost of completing the Put (and possible // refueling) after completing the Get. This means we need to know // the source, the destination, and the amount of fuel. It turns out // we also need to know our location to cover the cases where we will // run out of fuel before we get to the source or after we get to the // source but before we can put or refuel. This is unfortunate. QNode QGet( /* name */ "QGet", /* parameters */ makeArgs(), /* child */ MaxGet, /* child args */ makePPL(), /* features */ makeList(&PSource, &PDestination, &PFuel, &PTaxiX, &PTaxiY), /* nhidden */ 4, /* minValue */ -40.123, /* maxvalue */ 0.0, /* useTable */ 1); // This node will always be terminal. (Either we will succeed, in which // case, it is trivial to estimate the resulting value. It will // always be zero. Or we fail because we exhaust fuel.) So we need to // know the destination, the amount of fuel, and our current location. QNode QPut( /* name */ "QPut", /* parameters */ makeArgs(), /* child */ MaxPut, /* child args */ makePPL(), /* features */ makeList(&PDestination, &PFuel, &PTaxiX, &PTaxiY), /* nhidden */ 4, /* minValue */ -40.123, /* maxvalue */ 0.0, /* useTable */ 1); // This node is interesting. Because of the hierarchical credit // assignment, all top level nodes must predict whether we will run // out of fuel during their execution. Hence, this node needs the // full state. If we are willing to assume that we won't run out of // fuel while moving toward the F location, then this node could just // use the source and destination locations, since after successful // execution, the location and fuel of the taxi will be known // implicitly. QNode QRefuel( /* name */ "QRefuel", /* parameters */ makeArgs(), /* child */ MaxRefuel, /* child args */ makePPL(), /* features */ makeList(&PSourceOrHeld, &PDestination, &PFuel, &PTaxiX, &PTaxiY), /* nhidden */ 4, /* minValue */ -40.123, /* maxvalue */ 0.0, /* useTable */ 1); QNode * PolicyRoot(FuelTaxiState & state, ActualParameterList & apl, ActualParameterList & cpl) { // There are four policies in general: // 1. pickup, putdown // 2. pickup, fillup, putdown // 3. fillup, pickup, putdown // 4. fillup, pickup, fillup, putdown // Determine current goal: source, destination, or fuel. if (state.source != Held) { // Goal is either Fuel or Source. if (state.Distance(state.location, state.source) + state.Distance(state.source, state.destination) <= state.fuel) { // we can do everything without refueling. Case 1. return &QGet; } else { // is case 2 possible? int case2 = state.Distance(state.location, state.source) + state.Distance(state.source, Fuel); if (case2 <= state.fuel) { // Yes, case 2 is possible, so we must compare against case 3. // Is case 3 possible? After fueling, goto source and dest. int case3 = state.Distance(Fuel, state.source) + state.Distance(state.source, state.destination); if (case3 <= 12) { // Yes, case3 is possible, so we must compare case2 and // case3. case2 += state.Distance(Fuel, state.destination); case3 += state.Distance(state.location, Fuel); if (case2 < case3) return &QGet; else return &QRefuel; } else { // Only case 2 is possible. return &QGet; } } else return &QRefuel; } } else { // Goal is either Fuel or Destination. if (state.Distance(state.location, state.destination) <= state.fuel) { // we can make it without refueling return &QPut; } else return &QRefuel; } } int impTSimulationTerminatedAndPassengerDelivered(FuelTaxiState & state, ActualParameterList & apl) { return (state.Terminated() && state.source == None); } Predicate TSimulationTerminatedAndPassengerDelivered( /* name */ "TSimulationTerminatedAndPassengerDelivered", /* function */ &impTSimulationTerminatedAndPassengerDelivered, /* parameters */ makeArgs()); int impTSimulationTerminated(FuelTaxiState & state, ActualParameterList & apl) { return state.Terminated(); } Predicate TSimulationTerminated( /* name */ "TSimulationTerminated", /* function */ &impTSimulationTerminated, /* parameters */ makeArgs()); MaxNode MaxRoot( /* name */ "MaxRoot", /* parameters */ makeArgs(), /* precondition pred */ &TTrue, /* termination predicate */ &TSimulationTerminated, /* goal predicate */ &TSimulationTerminatedAndPassengerDelivered, /* children */ makeList(&QGet, &QPut, &QRefuel), /* features */ makeList(&PTaxiX, &PTaxiY, &PSourceOrHeld, &PDestination, &PFuel), /* policy */ &PolicyRoot, /* nonGoal penalty */ -100.0); // ---------------------------------------------------------------------- // // Reward Decomposition // // ---------------------------------------------------------------------- list<QNode *> * primitiveQNodes = makeList(&QNorth, &QEast, &QSouth, &QWest, &QPickup, &QPutdown, &QFillup); list<QNode *> * topLevelQNodes = makeList(&QGet, &QPut, &QRefuel); list<RewardResponsibility *> * RewardDecomposition = makeList( new RewardResponsibility(&TENone, // no error primitiveQNodes), new RewardResponsibility(&TENotAtFuel, // attempt to fillup not at Fuel makeList(&QFillup)), new RewardResponsibility(&TEEmpty, // no fuel left topLevelQNodes), new RewardResponsibility(&TEAlreadyHolding, // already holding makeList(&QPickup)), new RewardResponsibility(&TENoPassenger, // bad putdown makeList(&QPutdown)), new RewardResponsibility(&TENotAtSource, // can't pickup makeList(&QPickup)), new RewardResponsibility(&TENotHolding, // bad putdown makeList(&QPutdown)), new RewardResponsibility(&TENotAtDestination, // bad putdown makeList(&QPutdown)));
6c32692f04669eff50caeac51acd909c4d224cf0
2f511f3ebec034d49339e638253eeadb88072fab
/Facebook/Nov. 20th/BinaryTreePaths.cpp
36ff9602fe355ba1101f914be6c9a23257ff117a
[]
no_license
Gaojie-Li/leetcode-cpp
04b92ba22aecc98f7644101c5cd41003b7b1573b
a641048d47f3ef5303af624dd00bbc6d593d66a7
refs/heads/master
2021-01-19T04:52:12.881874
2016-12-04T20:50:17
2016-12-04T20:50:17
63,753,320
0
0
null
null
null
null
UTF-8
C++
false
false
960
cpp
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void binaryTreePath(TreeNode* root, string res, vector<string>& result) { if (!root -> left && !root -> right) { result.push_back(res); return; } if (root -> left) { binaryTreePath(root -> left, res + "->" + to_string(root -> left -> val), result); } if (root -> right) { binaryTreePath(root -> right, res + "->" + to_string(root -> right -> val), result); } } vector<string> binaryTreePaths(TreeNode* root) { vector<string> result; if (root == NULL) { return result; } binaryTreePath(root, to_string(root -> val), result); return result; } };
3c07acf389a95a850c03bfb4b9ed1aeca7522361
1bd97afce7323e1a3de011b7ff4a4c944a174c5a
/Tareas/T06-Transformaciones/T06-App-Transformaciones/src/main.cpp
caded7d4cc66cf8df1eaab63f08dd44a6fc50ef5
[]
no_license
katriel18/CG-2020-I-BarrozoFigueroaOsti
01aca4904c13dc62852406b17db17cf3d921f30f
26e3f1ff4538d586ca8fad08079d6f8a7a5e1cb9
refs/heads/master
2022-11-16T21:45:29.172496
2020-07-21T14:22:12
2020-07-21T14:22:12
268,586,135
0
0
null
null
null
null
ISO-8859-1
C++
false
false
11,086
cpp
//============================================================================ // Name : YING YANG // Editado : Barrozo Figueroa Osti Katriel //============================================================================ // Include standard headers #include <stdio.h> #include <stdlib.h> #include <iostream> // Include GLEW #define GLEW_STATIC #include <GL/glew.h> // Include GLFW #include <GLFW/glfw3.h> #include <string> #include <fstream> #include "Utils.h" #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> using namespace std; const float toRadians = 3.14159265f / 180.0f; GLuint renderingProgram; GLuint renderingProgram2;/////////KATRIEL /* GLfloat* m_Vertices;*/ GLuint n_Vertices; GLuint m_VBO; GLuint m_VAO; //// GLuint m_VBO2; GLuint m_VAO2; //// float curAngle = 0.0f; int dimVertices;//katriel int numberOfVertices;//katriel--------------------------------- void init (GLFWwindow* window) { // Utils renderingProgram = Utils::createShaderProgram("src/vertShader.glsl", "src/fragShader.glsl"); // Cria um ID na GPU para um array de buffers glGenVertexArrays(1, &m_VAO); glBindVertexArray(m_VAO); ///////////////////////////////////////////////////////////////////////////////////////////// GLfloat radius = 0.8;//GLfloat radius = 0.5;//KATRIEL------------------------------------ GLint numberOfSides = 800; // 50 numberOfVertices = numberOfSides+1; // points + one center point GLfloat twicePi = /*2.0f**/ M_PI; GLfloat verticesX[numberOfVertices*6]; GLfloat verticesY[numberOfVertices*6]; GLfloat verticesZ[numberOfVertices*6]; GLfloat verticesc1[numberOfVertices*6];//KATRIEL------------------------------------ GLfloat verticesc2[numberOfVertices*6];///KATRIEL------------------------------------ GLfloat verticesc3[numberOfVertices*6];//KATRIEL------------------------------------ //CIRCULO 1 for (int i = 0; i < numberOfVertices; i++) {// int i = 1 //KATRIEL------------------------------------ verticesX[i] =0.0 + (radius * cos(i * twicePi / numberOfSides)); verticesY[i] = 0.0+ (radius * sin(i * twicePi / numberOfSides)); verticesZ[i] = 0.0; verticesc1[i] = 0.0;//KATRIEL------------------------------------ verticesc2[i] = 0.0;//KATRIEL------------------------------------ verticesc3[i] = 0.0;//KATRIEL------------------------------------ } //CIRCULO 2 twicePi = 2.0f * M_PI; for (int i = numberOfVertices; i < numberOfVertices*2; i++) { verticesX[i] = 0.4 + (0.4 * cos(i * twicePi / numberOfSides)); verticesY[i] = 0.0 + (0.4 * sin(i * twicePi / numberOfSides)); verticesZ[i] = 0.0; verticesc1[i] = 0.0;//KATRIEL------------------------------------ verticesc2[i] = 0.0;//KATRIEL------------------------------------ verticesc3[i] = 0.0;//KATRIEL------------------------------------ } //CIRCULO 3 twicePi = 2.0f * M_PI; for (int i = numberOfVertices*2; i < numberOfVertices*3; i++) { verticesX[i] = -0.4 + (0.4 * cos(i * twicePi / numberOfSides)); verticesY[i] = 0.0 + (0.4 * sin(i * twicePi / numberOfSides)); verticesZ[i] = 0.0; verticesc1[i] = 1.0;//KATRIEL------------------------------------ verticesc2[i] = 1.0;//KATRIEL------------------------------------ verticesc3[i] = 1.0;//KATRIEL------------------------------------ } //CIRCULO 4 twicePi = 2.0f * M_PI; for (int i = numberOfVertices*3; i < numberOfVertices*4; i++) { verticesX[i] = 0.0 + (0.8 * cos(i * twicePi / numberOfSides)); verticesY[i] = 0.0 + (0.8 * sin(i * twicePi / numberOfSides)); verticesZ[i] = 0.0; verticesc1[i] = 0.0;//KATRIEL------------------------------------ verticesc2[i] = 0.0;//KATRIEL------------------------------------ verticesc3[i] = 0.0;//KATRIEL------------------------------------ } //CIRCULO 5 twicePi = 2.0f * M_PI; for (int i = numberOfVertices*4; i < numberOfVertices*5; i++) { verticesX[i] = 0.4 + (0.1 * cos(i * twicePi / numberOfSides)); verticesY[i] = 0.0 + (0.1 * sin(i * twicePi / numberOfSides)); verticesZ[i] = 0.0; verticesc1[i] = 1.0;//KATRIEL------------------------------------ verticesc2[i] = 1.0;//KATRIEL------------------------------------ verticesc3[i] = 1.0;//KATRIEL------------------------------------ } //CIRCULO 6 twicePi = 2.0f * M_PI; for (int i = numberOfVertices*5; i < numberOfVertices*6; i++) { verticesX[i] = -0.4 + (0.1 * cos(i * twicePi / numberOfSides)); verticesY[i] = 0.0 + (0.1 * sin(i * twicePi / numberOfSides)); verticesZ[i] = 0.0; verticesc1[i] = 0.0;//KATRIEL------------------------------------ verticesc2[i] = 0.0;//KATRIEL------------------------------------ verticesc3[i] = 0.0;//KATRIEL------------------------------------ } dimVertices = (numberOfVertices*6) * 6; GLfloat m_Vertices[dimVertices]; for (int i = 0; i < numberOfVertices*6; i++) { m_Vertices[i * 6] = verticesX[i]; m_Vertices[i * 6 + 1] = verticesY[i]; m_Vertices[i * 6 + 2] = verticesZ[i]; m_Vertices[i * 6+3] = verticesc1[i]; m_Vertices[i * 6 + 4] = verticesc2[i]; m_Vertices[i * 6 + 5] = verticesc3[i]; } ////////////////////////////////////////////////////////////////////////////////////////////// // Cria um ID na GPU para nosso buffer glGenBuffers(1, &m_VBO); // Cria um ID na GPU para um array de buffers glGenVertexArrays(1, &m_VAO); glBindVertexArray(m_VAO); glBindBuffer(GL_ARRAY_BUFFER, m_VBO); // Reserva memoria na GPU para um TARGET receber dados // Copia esses dados pra essa área de memoria glBufferData( GL_ARRAY_BUFFER, // TARGET associado ao nosso buffer dimVertices * sizeof(GLfloat), // tamanho do buffer m_Vertices, // Dados a serem copiados pra GPU GL_STATIC_DRAW // Política de acesso aos dados, para otimização ); glVertexAttribPointer( 0, // Lembra do (layout = 0 ) no vertex shader ? Esse valor indica qual atributo estamos indicando 3, // cada vertice é composto de 3 valores GL_FLOAT, // cada valor do vértice é do tipo GLfloat GL_FALSE, // Quer normalizar os dados e converter tudo pra NDC ? ( no nosso caso, já esta tudo correto, então deixamos como FALSE) 6 * sizeof(GLfloat),// De quantos em quantos bytes, este atributo é encontrado no buffer ? No nosso caso 3 floats pros vertices + 3 floats pra cor = 6 floats (GLvoid*) 0 // Onde está o primeiro valor deste atributo no buffer. Nesse caso, está no início do buffer ); glEnableVertexAttribArray(0); // Habilita este atributo ////////////////katriel-hoy//////////////////////// // Faremos a mesma coisa pra cor de cada vértice glVertexAttribPointer( 1, // Lembra do (layout = 1 ) no vertex shader ? Esse valor indica qual atributo estamos indicando 3, // cada vertice é composto de 3 valores GL_FLOAT, // cada valor do vértice é do tipo GLfloat GL_FALSE, // Quer normalizar os dados e converter tudo pra NDC ? ( no nosso caso, já esta tudo correto, então deixamos como FALSE) 6 * sizeof(GLfloat),// De quantos em quantos bytes, este atributo é encontrado no buffer ? No nosso caso 3 floats pros vertices + 3 floats pra cor = 6 floats (GLvoid*) (3 * sizeof(GLfloat)) // Onde está o primeiro valor deste atributo no buffer. Nesse caso, 3 floats após o início do buffer ); glEnableVertexAttribArray(1); // Habilita este atributo //////////////////////////////////////////////// glBindVertexArray(0); } void display(GLFWwindow* window, double currentTime) { glClear(GL_DEPTH_BUFFER_BIT); glClearColor(1.0, 1.0, 1.0, 1.0); glClear(GL_COLOR_BUFFER_BIT); glUseProgram(renderingProgram); GLuint uniformModel = glGetUniformLocation(renderingProgram, "model"); // gl_Position = model * vec4(0.4 * pos.x, 0.4 * pos.y, pos.z, 1.0); curAngle += 5.0f;//RAPIDES CUANDO AUMENTA>>>> if (curAngle >= 360) { curAngle -= 360; } // Matriz con elementos de valor 1 glm::mat4 model(1.0f);//model(1.0f); //Giro Antihorario model = glm::rotate(model, curAngle *toRadians, glm::vec3(0.0f, 0.0f, -1.0f));//glm::vec3(0.0f, 0.0f, 1.0f));//ANTIHORARIO //Usando UniformMatrix glUniformMatrix4fv(uniformModel, 1, GL_FALSE, glm::value_ptr(model)); //Usando ProgramUniform //glProgramUniformMatrix4fv(renderingProgram, uniformModel, 1, GL_FALSE, glm::value_ptr(model)); // Use este VAO e suas configurações glBindVertexArray(m_VAO); glPointSize(10.0f);//-----------------numberOfVertices*4 glDrawArrays(GL_TRIANGLE_FAN,0,numberOfVertices); // glDrawArrays(GL_LINES, 0, 3);//-------------- glBindVertexArray(0); ///////////////CIRCULO 2 glBindVertexArray(m_VAO); glPointSize(10.0f);//-----------------numberOfVertices*4 glDrawArrays(GL_TRIANGLE_FAN,numberOfVertices,numberOfVertices); // glDrawArrays(GL_LINES, 0, 3);//-------------- glBindVertexArray(0); ///////////////CIRCULO 3 glBindVertexArray(m_VAO); glPointSize(10.0f);//-----------------numberOfVertices*4 glDrawArrays(GL_TRIANGLE_FAN,numberOfVertices*2,numberOfVertices); // glDrawArrays(GL_LINES, 0, 3);//-------------- glBindVertexArray(0); ///////////////CIRCULO 4 glBindVertexArray(m_VAO); glPointSize(3.0f);//-----------------numberOfVertices*4 glDrawArrays(GL_POINTS,numberOfVertices*3,numberOfVertices); // glDrawArrays(GL_LINES, 0, 3);//-------------- glBindVertexArray(0); ///////////////CIRCULO 5 glBindVertexArray(m_VAO); glPointSize(10.0f);//-----------------numberOfVertices*4 glDrawArrays(GL_TRIANGLE_FAN,numberOfVertices*4,numberOfVertices); // glDrawArrays(GL_LINES, 0, 3);//-------------- glBindVertexArray(0); ///////////////CIRCULO 6 glBindVertexArray(m_VAO); glPointSize(10.0f);//-----------------numberOfVertices*4 glDrawArrays(GL_TRIANGLE_FAN,numberOfVertices*5,numberOfVertices); // glDrawArrays(GL_LINES, 0, 3);//-------------- glBindVertexArray(0); glUseProgram(0); } int main(void) { if (!glfwInit()) { exit(EXIT_FAILURE); } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 4); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // Resizable option. GLFWwindow* window = glfwCreateWindow(500, 500, "Barrozo Figueroa Osti Katriel", NULL, NULL); glfwMakeContextCurrent(window); if (glewInit() != GLEW_OK) { exit(EXIT_FAILURE); } glfwSwapInterval(1); init(window); // init2(window);// while (!glfwWindowShouldClose(window)) { display(window, glfwGetTime()); // display2(window, glfwGetTime());// glfwSwapBuffers(window); glfwPollEvents(); } glfwDestroyWindow(window); glfwTerminate(); exit(EXIT_SUCCESS); }
412fb931ea43da506951eb48001804d18f24b688
575731c1155e321e7b22d8373ad5876b292b0b2f
/examples/native/ios/Pods/boost-for-react-native/boost/preprocessor/detail/is_binary.hpp
f2180e54ee6d0da0f94bd1b473a701df8c5841e7
[ "BSL-1.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Nozbe/zacs
802a84ffd47413a1687a573edda519156ca317c7
c3d455426bc7dfb83e09fdf20781c2632a205c04
refs/heads/master
2023-06-12T20:53:31.482746
2023-06-07T07:06:49
2023-06-07T07:06:49
201,777,469
432
10
MIT
2023-01-24T13:29:34
2019-08-11T14:47:50
JavaScript
UTF-8
C++
false
false
1,271
hpp
# /* ************************************************************************** # * * # * (C) Copyright Paul Mensonides 2002. # * Distributed under the Boost Software License, Version 1.0. (See # * accompanying file LICENSE_1_0.txt or copy at # * http://www.boost.org/LICENSE_1_0.txt) # * * # ************************************************************************** */ # # /* See http://www.boost.org for most recent version. */ # # ifndef BOOST_PREPROCESSOR_DETAIL_IS_BINARY_HPP # define BOOST_PREPROCESSOR_DETAIL_IS_BINARY_HPP # # include <boost/preprocessor/config/config.hpp> # include <boost/preprocessor/detail/check.hpp> # # /* BOOST_PP_IS_BINARY */ # # if ~BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_EDG() # define BOOST_PP_IS_BINARY(x) BOOST_PP_CHECK(x, BOOST_PP_IS_BINARY_CHECK) # else # define BOOST_PP_IS_BINARY(x) BOOST_PP_IS_BINARY_I(x) # define BOOST_PP_IS_BINARY_I(x) BOOST_PP_CHECK(x, BOOST_PP_IS_BINARY_CHECK) # endif # # define BOOST_PP_IS_BINARY_CHECK(a, b) 1 # define BOOST_PP_CHECK_RESULT_BOOST_PP_IS_BINARY_CHECK 0, BOOST_PP_NIL # # endif
af0c983c56eecc8ac9f2edd8717937590e622b42
98e86df1ec2841721f75c5c8474c2636de193fa8
/Algorithm_in_topics/dp/game_based_dp/coins_in_a_line_II.cpp
6bc73c4cb82368e19946213140c3c97e688819c2
[]
no_license
cyscgzx33/Leetcode-Practice
59bb7cf3a92e7fcaca2b0a0ad3ba2471a5effc8f
ce025a8e555344974611ab35ef4874e788bbd808
refs/heads/master
2021-06-26T22:02:14.437882
2020-10-23T21:10:58
2020-10-23T21:10:58
146,931,961
4
4
null
null
null
null
UTF-8
C++
false
false
925
cpp
class Solution { public: /** * @param values: a vector of integers * @return: a boolean which equals to true if the first player will win */ bool firstWillWin(vector<int> &values) { // write your code here int n = values.size(); // f[i] indicates the max value diff to fetch the coins between [, ..., n-1], suppo // state transition equation: f[i] = max(a[i] - f[i-1], a[i] + a[i+1] - f[i-2]) vector<int> f(n + 1, 0); f[n-1] = values[n-1]; // Note: one can also derive it thru the equation, but it should be changed into f[i] = max(a[i] - f[i-1]), thus f[n-1] = a[n-1] for (int i = n-2; i >= 0; i--) f[i] = max(values[i] - f[i+1], values[i] + values[i+1] - f[i+2]); return f[0] >= 0; // it means: the max value diff to fetch the coins between [0, ..., n-1] (i.e., all the coins) is >= 0 } };
9ec4d397c47283ac34d530d35677de1974f3b56c
99d37c9a6507b2cc2c65ec0b7366f0aa6d9b06f4
/third_party/cc/absl/absl/random/distributions_test.cc
53f5455edb1938c00cea69cbdbfb762d4e9992f9
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
ahmedtd/ballistae
aa834f9109ea5f1226c8d3edd7b0456f4f0bc2e3
918e3007087c9b4dd118763c106eb5080d649705
refs/heads/master
2023-03-17T22:47:53.207953
2020-06-01T09:13:36
2020-06-01T09:14:13
345,562,932
0
0
null
null
null
null
UTF-8
C++
false
false
18,820
cc
// Copyright 2017 The Abseil Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "third_party/cc/absl/absl/random/distributions.h" #include <cmath> #include <cstdint> #include <random> #include <vector> #include "gtest/gtest.h" #include "third_party/cc/absl/absl/random/internal/distribution_test_util.h" #include "third_party/cc/absl/absl/random/random.h" namespace { constexpr int kSize = 400000; class RandomDistributionsTest : public testing::Test {}; TEST_F(RandomDistributionsTest, UniformBoundFunctions) { using absl::IntervalClosedClosed; using absl::IntervalClosedOpen; using absl::IntervalOpenClosed; using absl::IntervalOpenOpen; using absl::random_internal::uniform_lower_bound; using absl::random_internal::uniform_upper_bound; // absl::uniform_int_distribution natively assumes IntervalClosedClosed // absl::uniform_real_distribution natively assumes IntervalClosedOpen EXPECT_EQ(uniform_lower_bound(IntervalOpenClosed, 0, 100), 1); EXPECT_EQ(uniform_lower_bound(IntervalOpenOpen, 0, 100), 1); EXPECT_GT(uniform_lower_bound<float>(IntervalOpenClosed, 0, 1.0), 0); EXPECT_GT(uniform_lower_bound<float>(IntervalOpenOpen, 0, 1.0), 0); EXPECT_GT(uniform_lower_bound<double>(IntervalOpenClosed, 0, 1.0), 0); EXPECT_GT(uniform_lower_bound<double>(IntervalOpenOpen, 0, 1.0), 0); EXPECT_EQ(uniform_lower_bound(IntervalClosedClosed, 0, 100), 0); EXPECT_EQ(uniform_lower_bound(IntervalClosedOpen, 0, 100), 0); EXPECT_EQ(uniform_lower_bound<float>(IntervalClosedClosed, 0, 1.0), 0); EXPECT_EQ(uniform_lower_bound<float>(IntervalClosedOpen, 0, 1.0), 0); EXPECT_EQ(uniform_lower_bound<double>(IntervalClosedClosed, 0, 1.0), 0); EXPECT_EQ(uniform_lower_bound<double>(IntervalClosedOpen, 0, 1.0), 0); EXPECT_EQ(uniform_upper_bound(IntervalOpenOpen, 0, 100), 99); EXPECT_EQ(uniform_upper_bound(IntervalClosedOpen, 0, 100), 99); EXPECT_EQ(uniform_upper_bound<float>(IntervalOpenOpen, 0, 1.0), 1.0); EXPECT_EQ(uniform_upper_bound<float>(IntervalClosedOpen, 0, 1.0), 1.0); EXPECT_EQ(uniform_upper_bound<double>(IntervalOpenOpen, 0, 1.0), 1.0); EXPECT_EQ(uniform_upper_bound<double>(IntervalClosedOpen, 0, 1.0), 1.0); EXPECT_EQ(uniform_upper_bound(IntervalOpenClosed, 0, 100), 100); EXPECT_EQ(uniform_upper_bound(IntervalClosedClosed, 0, 100), 100); EXPECT_GT(uniform_upper_bound<float>(IntervalOpenClosed, 0, 1.0), 1.0); EXPECT_GT(uniform_upper_bound<float>(IntervalClosedClosed, 0, 1.0), 1.0); EXPECT_GT(uniform_upper_bound<double>(IntervalOpenClosed, 0, 1.0), 1.0); EXPECT_GT(uniform_upper_bound<double>(IntervalClosedClosed, 0, 1.0), 1.0); // Negative value tests EXPECT_EQ(uniform_lower_bound(IntervalOpenClosed, -100, -1), -99); EXPECT_EQ(uniform_lower_bound(IntervalOpenOpen, -100, -1), -99); EXPECT_GT(uniform_lower_bound<float>(IntervalOpenClosed, -2.0, -1.0), -2.0); EXPECT_GT(uniform_lower_bound<float>(IntervalOpenOpen, -2.0, -1.0), -2.0); EXPECT_GT(uniform_lower_bound<double>(IntervalOpenClosed, -2.0, -1.0), -2.0); EXPECT_GT(uniform_lower_bound<double>(IntervalOpenOpen, -2.0, -1.0), -2.0); EXPECT_EQ(uniform_lower_bound(IntervalClosedClosed, -100, -1), -100); EXPECT_EQ(uniform_lower_bound(IntervalClosedOpen, -100, -1), -100); EXPECT_EQ(uniform_lower_bound<float>(IntervalClosedClosed, -2.0, -1.0), -2.0); EXPECT_EQ(uniform_lower_bound<float>(IntervalClosedOpen, -2.0, -1.0), -2.0); EXPECT_EQ(uniform_lower_bound<double>(IntervalClosedClosed, -2.0, -1.0), -2.0); EXPECT_EQ(uniform_lower_bound<double>(IntervalClosedOpen, -2.0, -1.0), -2.0); EXPECT_EQ(uniform_upper_bound(IntervalOpenOpen, -100, -1), -2); EXPECT_EQ(uniform_upper_bound(IntervalClosedOpen, -100, -1), -2); EXPECT_EQ(uniform_upper_bound<float>(IntervalOpenOpen, -2.0, -1.0), -1.0); EXPECT_EQ(uniform_upper_bound<float>(IntervalClosedOpen, -2.0, -1.0), -1.0); EXPECT_EQ(uniform_upper_bound<double>(IntervalOpenOpen, -2.0, -1.0), -1.0); EXPECT_EQ(uniform_upper_bound<double>(IntervalClosedOpen, -2.0, -1.0), -1.0); EXPECT_EQ(uniform_upper_bound(IntervalOpenClosed, -100, -1), -1); EXPECT_EQ(uniform_upper_bound(IntervalClosedClosed, -100, -1), -1); EXPECT_GT(uniform_upper_bound<float>(IntervalOpenClosed, -2.0, -1.0), -1.0); EXPECT_GT(uniform_upper_bound<float>(IntervalClosedClosed, -2.0, -1.0), -1.0); EXPECT_GT(uniform_upper_bound<double>(IntervalOpenClosed, -2.0, -1.0), -1.0); EXPECT_GT(uniform_upper_bound<double>(IntervalClosedClosed, -2.0, -1.0), -1.0); // Edge cases: the next value toward itself is itself. const double d = 1.0; const float f = 1.0; EXPECT_EQ(uniform_lower_bound(IntervalOpenClosed, d, d), d); EXPECT_EQ(uniform_lower_bound(IntervalOpenClosed, f, f), f); EXPECT_GT(uniform_lower_bound(IntervalOpenClosed, 1.0, 2.0), 1.0); EXPECT_LT(uniform_lower_bound(IntervalOpenClosed, 1.0, +0.0), 1.0); EXPECT_LT(uniform_lower_bound(IntervalOpenClosed, 1.0, -0.0), 1.0); EXPECT_LT(uniform_lower_bound(IntervalOpenClosed, 1.0, -1.0), 1.0); EXPECT_EQ(uniform_upper_bound(IntervalClosedClosed, 0.0f, std::numeric_limits<float>::max()), std::numeric_limits<float>::max()); EXPECT_EQ(uniform_upper_bound(IntervalClosedClosed, 0.0, std::numeric_limits<double>::max()), std::numeric_limits<double>::max()); } struct Invalid {}; template <typename A, typename B> auto InferredUniformReturnT(int) -> decltype(absl::Uniform(std::declval<absl::InsecureBitGen&>(), std::declval<A>(), std::declval<B>())); template <typename, typename> Invalid InferredUniformReturnT(...); template <typename TagType, typename A, typename B> auto InferredTaggedUniformReturnT(int) -> decltype(absl::Uniform(std::declval<TagType>(), std::declval<absl::InsecureBitGen&>(), std::declval<A>(), std::declval<B>())); template <typename, typename, typename> Invalid InferredTaggedUniformReturnT(...); // Given types <A, B, Expect>, CheckArgsInferType() verifies that // // absl::Uniform(gen, A{}, B{}) // // returns the type "Expect". // // This interface can also be used to assert that a given absl::Uniform() // overload does not exist / will not compile. Given types <A, B>, the // expression // // decltype(absl::Uniform(..., std::declval<A>(), std::declval<B>())) // // will not compile, leaving the definition of InferredUniformReturnT<A, B> to // resolve (via SFINAE) to the overload which returns type "Invalid". This // allows tests to assert that an invocation such as // // absl::Uniform(gen, 1.23f, std::numeric_limits<int>::max() - 1) // // should not compile, since neither type, float nor int, can precisely // represent both endpoint-values. Writing: // // CheckArgsInferType<float, int, Invalid>() // // will assert that this overload does not exist. template <typename A, typename B, typename Expect> void CheckArgsInferType() { static_assert( absl::conjunction< std::is_same<Expect, decltype(InferredUniformReturnT<A, B>(0))>, std::is_same<Expect, decltype(InferredUniformReturnT<B, A>(0))>>::value, ""); static_assert( absl::conjunction< std::is_same<Expect, decltype(InferredTaggedUniformReturnT< absl::IntervalOpenOpenTag, A, B>(0))>, std::is_same<Expect, decltype(InferredTaggedUniformReturnT< absl::IntervalOpenOpenTag, B, A>(0))>>::value, ""); } template <typename A, typename B, typename ExplicitRet> auto ExplicitUniformReturnT(int) -> decltype( absl::Uniform<ExplicitRet>(*std::declval<absl::InsecureBitGen*>(), std::declval<A>(), std::declval<B>())); template <typename, typename, typename ExplicitRet> Invalid ExplicitUniformReturnT(...); template <typename TagType, typename A, typename B, typename ExplicitRet> auto ExplicitTaggedUniformReturnT(int) -> decltype(absl::Uniform<ExplicitRet>( std::declval<TagType>(), *std::declval<absl::InsecureBitGen*>(), std::declval<A>(), std::declval<B>())); template <typename, typename, typename, typename ExplicitRet> Invalid ExplicitTaggedUniformReturnT(...); // Given types <A, B, Expect>, CheckArgsReturnExpectedType() verifies that // // absl::Uniform<Expect>(gen, A{}, B{}) // // returns the type "Expect", and that the function-overload has the signature // // Expect(URBG&, Expect, Expect) template <typename A, typename B, typename Expect> void CheckArgsReturnExpectedType() { static_assert( absl::conjunction< std::is_same<Expect, decltype(ExplicitUniformReturnT<A, B, Expect>(0))>, std::is_same<Expect, decltype(ExplicitUniformReturnT<B, A, Expect>( 0))>>::value, ""); static_assert( absl::conjunction< std::is_same<Expect, decltype(ExplicitTaggedUniformReturnT< absl::IntervalOpenOpenTag, A, B, Expect>(0))>, std::is_same<Expect, decltype(ExplicitTaggedUniformReturnT< absl::IntervalOpenOpenTag, B, A, Expect>(0))>>::value, ""); } TEST_F(RandomDistributionsTest, UniformTypeInference) { // Infers common types. CheckArgsInferType<uint16_t, uint16_t, uint16_t>(); CheckArgsInferType<uint32_t, uint32_t, uint32_t>(); CheckArgsInferType<uint64_t, uint64_t, uint64_t>(); CheckArgsInferType<int16_t, int16_t, int16_t>(); CheckArgsInferType<int32_t, int32_t, int32_t>(); CheckArgsInferType<int64_t, int64_t, int64_t>(); CheckArgsInferType<float, float, float>(); CheckArgsInferType<double, double, double>(); // Explicitly-specified return-values override inferences. CheckArgsReturnExpectedType<int16_t, int16_t, int32_t>(); CheckArgsReturnExpectedType<uint16_t, uint16_t, int32_t>(); CheckArgsReturnExpectedType<int16_t, int16_t, int64_t>(); CheckArgsReturnExpectedType<int16_t, int32_t, int64_t>(); CheckArgsReturnExpectedType<int16_t, int32_t, double>(); CheckArgsReturnExpectedType<float, float, double>(); CheckArgsReturnExpectedType<int, int, int16_t>(); // Properly promotes uint16_t. CheckArgsInferType<uint16_t, uint32_t, uint32_t>(); CheckArgsInferType<uint16_t, uint64_t, uint64_t>(); CheckArgsInferType<uint16_t, int32_t, int32_t>(); CheckArgsInferType<uint16_t, int64_t, int64_t>(); CheckArgsInferType<uint16_t, float, float>(); CheckArgsInferType<uint16_t, double, double>(); // Properly promotes int16_t. CheckArgsInferType<int16_t, int32_t, int32_t>(); CheckArgsInferType<int16_t, int64_t, int64_t>(); CheckArgsInferType<int16_t, float, float>(); CheckArgsInferType<int16_t, double, double>(); // Invalid (u)int16_t-pairings do not compile. // See "CheckArgsInferType" comments above, for how this is achieved. CheckArgsInferType<uint16_t, int16_t, Invalid>(); CheckArgsInferType<int16_t, uint32_t, Invalid>(); CheckArgsInferType<int16_t, uint64_t, Invalid>(); // Properly promotes uint32_t. CheckArgsInferType<uint32_t, uint64_t, uint64_t>(); CheckArgsInferType<uint32_t, int64_t, int64_t>(); CheckArgsInferType<uint32_t, double, double>(); // Properly promotes int32_t. CheckArgsInferType<int32_t, int64_t, int64_t>(); CheckArgsInferType<int32_t, double, double>(); // Invalid (u)int32_t-pairings do not compile. CheckArgsInferType<uint32_t, int32_t, Invalid>(); CheckArgsInferType<int32_t, uint64_t, Invalid>(); CheckArgsInferType<int32_t, float, Invalid>(); CheckArgsInferType<uint32_t, float, Invalid>(); // Invalid (u)int64_t-pairings do not compile. CheckArgsInferType<uint64_t, int64_t, Invalid>(); CheckArgsInferType<int64_t, float, Invalid>(); CheckArgsInferType<int64_t, double, Invalid>(); // Properly promotes float. CheckArgsInferType<float, double, double>(); // Examples. absl::InsecureBitGen gen; EXPECT_NE(1, absl::Uniform(gen, static_cast<uint16_t>(0), 1.0f)); EXPECT_NE(1, absl::Uniform(gen, 0, 1.0)); EXPECT_NE(1, absl::Uniform(absl::IntervalOpenOpen, gen, static_cast<uint16_t>(0), 1.0f)); EXPECT_NE(1, absl::Uniform(absl::IntervalOpenOpen, gen, 0, 1.0)); EXPECT_NE(1, absl::Uniform(absl::IntervalOpenOpen, gen, -1, 1.0)); EXPECT_NE(1, absl::Uniform<double>(absl::IntervalOpenOpen, gen, -1, 1)); EXPECT_NE(1, absl::Uniform<float>(absl::IntervalOpenOpen, gen, 0, 1)); EXPECT_NE(1, absl::Uniform<float>(gen, 0, 1)); } TEST_F(RandomDistributionsTest, UniformNoBounds) { absl::InsecureBitGen gen; absl::Uniform<uint8_t>(gen); absl::Uniform<uint16_t>(gen); absl::Uniform<uint32_t>(gen); absl::Uniform<uint64_t>(gen); } // TODO(lar): Validate properties of non-default interval-semantics. TEST_F(RandomDistributionsTest, UniformReal) { std::vector<double> values(kSize); absl::InsecureBitGen gen; for (int i = 0; i < kSize; i++) { values[i] = absl::Uniform(gen, 0, 1.0); } const auto moments = absl::random_internal::ComputeDistributionMoments(values); EXPECT_NEAR(0.5, moments.mean, 0.02); EXPECT_NEAR(1 / 12.0, moments.variance, 0.02); EXPECT_NEAR(0.0, moments.skewness, 0.02); EXPECT_NEAR(9 / 5.0, moments.kurtosis, 0.02); } TEST_F(RandomDistributionsTest, UniformInt) { std::vector<double> values(kSize); absl::InsecureBitGen gen; for (int i = 0; i < kSize; i++) { const int64_t kMax = 1000000000000ll; int64_t j = absl::Uniform(absl::IntervalClosedClosed, gen, 0, kMax); // convert to double. values[i] = static_cast<double>(j) / static_cast<double>(kMax); } const auto moments = absl::random_internal::ComputeDistributionMoments(values); EXPECT_NEAR(0.5, moments.mean, 0.02); EXPECT_NEAR(1 / 12.0, moments.variance, 0.02); EXPECT_NEAR(0.0, moments.skewness, 0.02); EXPECT_NEAR(9 / 5.0, moments.kurtosis, 0.02); /* // NOTE: These are not supported by absl::Uniform, which is specialized // on integer and real valued types. enum E { E0, E1 }; // enum enum S : int { S0, S1 }; // signed enum enum U : unsigned int { U0, U1 }; // unsigned enum absl::Uniform(gen, E0, E1); absl::Uniform(gen, S0, S1); absl::Uniform(gen, U0, U1); */ } TEST_F(RandomDistributionsTest, Exponential) { std::vector<double> values(kSize); absl::InsecureBitGen gen; for (int i = 0; i < kSize; i++) { values[i] = absl::Exponential<double>(gen); } const auto moments = absl::random_internal::ComputeDistributionMoments(values); EXPECT_NEAR(1.0, moments.mean, 0.02); EXPECT_NEAR(1.0, moments.variance, 0.025); EXPECT_NEAR(2.0, moments.skewness, 0.1); EXPECT_LT(5.0, moments.kurtosis); } TEST_F(RandomDistributionsTest, PoissonDefault) { std::vector<double> values(kSize); absl::InsecureBitGen gen; for (int i = 0; i < kSize; i++) { values[i] = absl::Poisson<int64_t>(gen); } const auto moments = absl::random_internal::ComputeDistributionMoments(values); EXPECT_NEAR(1.0, moments.mean, 0.02); EXPECT_NEAR(1.0, moments.variance, 0.02); EXPECT_NEAR(1.0, moments.skewness, 0.025); EXPECT_LT(2.0, moments.kurtosis); } TEST_F(RandomDistributionsTest, PoissonLarge) { constexpr double kMean = 100000000.0; std::vector<double> values(kSize); absl::InsecureBitGen gen; for (int i = 0; i < kSize; i++) { values[i] = absl::Poisson<int64_t>(gen, kMean); } const auto moments = absl::random_internal::ComputeDistributionMoments(values); EXPECT_NEAR(kMean, moments.mean, kMean * 0.015); EXPECT_NEAR(kMean, moments.variance, kMean * 0.015); EXPECT_NEAR(std::sqrt(kMean), moments.skewness, kMean * 0.02); EXPECT_LT(2.0, moments.kurtosis); } TEST_F(RandomDistributionsTest, Bernoulli) { constexpr double kP = 0.5151515151; std::vector<double> values(kSize); absl::InsecureBitGen gen; for (int i = 0; i < kSize; i++) { values[i] = absl::Bernoulli(gen, kP); } const auto moments = absl::random_internal::ComputeDistributionMoments(values); EXPECT_NEAR(kP, moments.mean, 0.01); } TEST_F(RandomDistributionsTest, Beta) { constexpr double kAlpha = 2.0; constexpr double kBeta = 3.0; std::vector<double> values(kSize); absl::InsecureBitGen gen; for (int i = 0; i < kSize; i++) { values[i] = absl::Beta(gen, kAlpha, kBeta); } const auto moments = absl::random_internal::ComputeDistributionMoments(values); EXPECT_NEAR(0.4, moments.mean, 0.01); } TEST_F(RandomDistributionsTest, Zipf) { std::vector<double> values(kSize); absl::InsecureBitGen gen; for (int i = 0; i < kSize; i++) { values[i] = absl::Zipf<int64_t>(gen, 100); } // The mean of a zipf distribution is: H(N, s-1) / H(N,s). // Given the parameter v = 1, this gives the following function: // (Hn(100, 1) - Hn(1,1)) / (Hn(100,2) - Hn(1,2)) = 6.5944 const auto moments = absl::random_internal::ComputeDistributionMoments(values); EXPECT_NEAR(6.5944, moments.mean, 2000) << moments; } TEST_F(RandomDistributionsTest, Gaussian) { std::vector<double> values(kSize); absl::InsecureBitGen gen; for (int i = 0; i < kSize; i++) { values[i] = absl::Gaussian<double>(gen); } const auto moments = absl::random_internal::ComputeDistributionMoments(values); EXPECT_NEAR(0.0, moments.mean, 0.02); EXPECT_NEAR(1.0, moments.variance, 0.04); EXPECT_NEAR(0, moments.skewness, 0.2); EXPECT_NEAR(3.0, moments.kurtosis, 0.5); } TEST_F(RandomDistributionsTest, LogUniform) { std::vector<double> values(kSize); absl::InsecureBitGen gen; for (int i = 0; i < kSize; i++) { values[i] = absl::LogUniform<int64_t>(gen, 0, (1 << 10) - 1); } // The mean is the sum of the fractional means of the uniform distributions: // [0..0][1..1][2..3][4..7][8..15][16..31][32..63] // [64..127][128..255][256..511][512..1023] const double mean = (0 + 1 + 1 + 2 + 3 + 4 + 7 + 8 + 15 + 16 + 31 + 32 + 63 + 64 + 127 + 128 + 255 + 256 + 511 + 512 + 1023) / (2.0 * 11.0); const auto moments = absl::random_internal::ComputeDistributionMoments(values); EXPECT_NEAR(mean, moments.mean, 2) << moments; } } // namespace
b659a79c04312aa3c10cf9c08fbb201839d82c6e
d0f614fcd9ec4e9ed7bf4bbae43c4e57339cf0f7
/src/Resources.h
67091e18b2684b6ebab75643e839c77038ef880c
[]
no_license
henne90gen/RacingToHell
6f0cda167b6432016ae8629f37047762b5456df5
4b928478ecc7ef1f3d9714721ab02e0c22947733
refs/heads/master
2023-03-15T13:57:49.191425
2023-03-10T11:27:57
2023-03-10T11:28:02
51,105,446
3
0
null
null
null
null
UTF-8
C++
false
false
537
h
#pragma once #include <optional> #include <string> #include <string_view> #include "Platform.h" struct Resource { std::string resource_name; int64_t last_modified = 0; File file = {}; explicit Resource(std::string _resource_name); std::string_view get_content(Platform &platform); [[nodiscard]] bool has_changed(Platform &platform) const; [[nodiscard]] std::string get_file_name(Platform &platform) const; }; std::optional<Resource *> get_resource(Platform &platform, const std::string &resource_name);
19fc9b37b62b6cfc456371ffbc9d8d71457f220a
ceb7431363e36a4698a93540cdeafcd9d9b315ad
/lib/StaticAnalyzer/Checkers/IvarInvalidationChecker.cpp
0a20011c7dbf1b451d994a036687078823c5fa12
[ "MIT" ]
permissive
primitivorm/latino-llvm
8b5d8759271eb6c328cb4c81a2523bbecce10222
33c820aeef006b7190e347e0839cf4f268b70639
refs/heads/master
2023-08-02T06:15:42.365363
2023-05-05T13:28:32
2023-05-05T13:28:32
133,191,211
4
2
MIT
2022-03-31T01:39:29
2018-05-12T23:39:50
C++
UTF-8
C++
false
false
30,008
cpp
//===- IvarInvalidationChecker.cpp ------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This checker implements annotation driven invalidation checking. If a class // contains a method annotated with 'objc_instance_variable_invalidator', // - (void) foo // __attribute__((annotate("objc_instance_variable_invalidator"))); // all the "ivalidatable" instance variables of this class should be // invalidated. We call an instance variable ivalidatable if it is an object of // a class which contains an invalidation method. There could be multiple // methods annotated with such annotations per class, either one can be used // to invalidate the ivar. An ivar or property are considered to be // invalidated if they are being assigned 'nil' or an invalidation method has // been called on them. An invalidation method should either invalidate all // the ivars or call another invalidation method (on self). // // Partial invalidor annotation allows to address cases when ivars are // invalidated by other methods, which might or might not be called from // the invalidation method. The checker checks that each invalidation // method and all the partial methods cumulatively invalidate all ivars. // __attribute__((annotate("objc_instance_variable_invalidator_partial"))); // //===----------------------------------------------------------------------===// #include "latino/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h" #include "latino/AST/Attr.h" // #include "latino/AST/DeclObjC.h" #include "latino/AST/StmtVisitor.h" #include "latino/StaticAnalyzer/Core/BugReporter/BugReporter.h" #include "latino/StaticAnalyzer/Core/Checker.h" #include "latino/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallString.h" using namespace latino; using namespace ento; namespace { struct ChecksFilter { /// Check for missing invalidation method declarations. DefaultBool check_MissingInvalidationMethod; /// Check that all ivars are invalidated. DefaultBool check_InstanceVariableInvalidation; CheckerNameRef checkName_MissingInvalidationMethod; CheckerNameRef checkName_InstanceVariableInvalidation; }; // class IvarInvalidationCheckerImpl { // typedef llvm::SmallSetVector<const ObjCMethodDecl*, 2> MethodSet; // typedef llvm::DenseMap<const ObjCMethodDecl*, // const ObjCIvarDecl*> MethToIvarMapTy; // typedef llvm::DenseMap<const ObjCPropertyDecl*, // const ObjCIvarDecl*> PropToIvarMapTy; // typedef llvm::DenseMap<const ObjCIvarDecl*, // const ObjCPropertyDecl*> IvarToPropMapTy; // struct InvalidationInfo { // /// Has the ivar been invalidated? // bool IsInvalidated; // /// The methods which can be used to invalidate the ivar. // MethodSet InvalidationMethods; // InvalidationInfo() : IsInvalidated(false) {} // void addInvalidationMethod(const ObjCMethodDecl *MD) { // InvalidationMethods.insert(MD); // } // bool needsInvalidation() const { // return !InvalidationMethods.empty(); // } // bool hasMethod(const ObjCMethodDecl *MD) { // if (IsInvalidated) // return true; // for (MethodSet::iterator I = InvalidationMethods.begin(), // E = InvalidationMethods.end(); I != E; ++I) { // if (*I == MD) { // IsInvalidated = true; // return true; // } // } // return false; // } // }; // typedef llvm::DenseMap<const ObjCIvarDecl*, InvalidationInfo> IvarSet; // /// Statement visitor, which walks the method body and flags the ivars // /// referenced in it (either directly or via property). // class MethodCrawler : public ConstStmtVisitor<MethodCrawler> { // /// The set of Ivars which need to be invalidated. // IvarSet &IVars; // /// Flag is set as the result of a message send to another // /// invalidation method. // bool &CalledAnotherInvalidationMethod; // /// Property setter to ivar mapping. // const MethToIvarMapTy &PropertySetterToIvarMap; // /// Property getter to ivar mapping. // const MethToIvarMapTy &PropertyGetterToIvarMap; // /// Property to ivar mapping. // const PropToIvarMapTy &PropertyToIvarMap; // /// The invalidation method being currently processed. // const ObjCMethodDecl *InvalidationMethod; // ASTContext &Ctx; // /// Peel off parens, casts, OpaqueValueExpr, and PseudoObjectExpr. // const Expr *peel(const Expr *E) const; // /// Does this expression represent zero: '0'? // bool isZero(const Expr *E) const; // /// Mark the given ivar as invalidated. // void markInvalidated(const ObjCIvarDecl *Iv); // /// Checks if IvarRef refers to the tracked IVar, if yes, marks it as // /// invalidated. // void checkObjCIvarRefExpr(const ObjCIvarRefExpr *IvarRef); // /// Checks if ObjCPropertyRefExpr refers to the tracked IVar, if yes, marks // /// it as invalidated. // void checkObjCPropertyRefExpr(const ObjCPropertyRefExpr *PA); // /// Checks if ObjCMessageExpr refers to (is a getter for) the tracked IVar, // /// if yes, marks it as invalidated. // void checkObjCMessageExpr(const ObjCMessageExpr *ME); // /// Checks if the Expr refers to an ivar, if yes, marks it as invalidated. // void check(const Expr *E); // public: // MethodCrawler(IvarSet &InIVars, // bool &InCalledAnotherInvalidationMethod, // const MethToIvarMapTy &InPropertySetterToIvarMap, // const MethToIvarMapTy &InPropertyGetterToIvarMap, // const PropToIvarMapTy &InPropertyToIvarMap, // ASTContext &InCtx) // : IVars(InIVars), // CalledAnotherInvalidationMethod(InCalledAnotherInvalidationMethod), // PropertySetterToIvarMap(InPropertySetterToIvarMap), // PropertyGetterToIvarMap(InPropertyGetterToIvarMap), // PropertyToIvarMap(InPropertyToIvarMap), // InvalidationMethod(nullptr), // Ctx(InCtx) {} // void VisitStmt(const Stmt *S) { VisitChildren(S); } // void VisitBinaryOperator(const BinaryOperator *BO); // // void VisitObjCMessageExpr(const ObjCMessageExpr *ME); // void VisitChildren(const Stmt *S) { // for (const auto *Child : S->children()) { // if (Child) // this->Visit(Child); // if (CalledAnotherInvalidationMethod) // return; // } // } // }; // /// Check if the any of the methods inside the interface are annotated with // /// the invalidation annotation, update the IvarInfo accordingly. // /// \param LookForPartial is set when we are searching for partial // /// invalidators. // static void containsInvalidationMethod(const ObjCContainerDecl *D, // InvalidationInfo &Out, // bool LookForPartial); // /// Check if ivar should be tracked and add to TrackedIvars if positive. // /// Returns true if ivar should be tracked. // static bool trackIvar(const ObjCIvarDecl *Iv, IvarSet &TrackedIvars, // const ObjCIvarDecl **FirstIvarDecl); // /// Given the property declaration, and the list of tracked ivars, finds // /// the ivar backing the property when possible. Returns '0' when no such // /// ivar could be found. // static const ObjCIvarDecl *findPropertyBackingIvar( // const ObjCPropertyDecl *Prop, // const ObjCInterfaceDecl *InterfaceD, // IvarSet &TrackedIvars, // const ObjCIvarDecl **FirstIvarDecl); // /// Print ivar name or the property if the given ivar backs a property. // static void printIvar(llvm::raw_svector_ostream &os, // const ObjCIvarDecl *IvarDecl, // const IvarToPropMapTy &IvarToPopertyMap); // void reportNoInvalidationMethod(CheckerNameRef CheckName, // const ObjCIvarDecl *FirstIvarDecl, // const IvarToPropMapTy &IvarToPopertyMap, // const ObjCInterfaceDecl *InterfaceD, // bool MissingDeclaration) const; // void reportIvarNeedsInvalidation(const ObjCIvarDecl *IvarD, // const IvarToPropMapTy &IvarToPopertyMap, // const ObjCMethodDecl *MethodD) const; // AnalysisManager& Mgr; // BugReporter &BR; // /// Filter on the checks performed. // const ChecksFilter &Filter; // public: // IvarInvalidationCheckerImpl(AnalysisManager& InMgr, // BugReporter &InBR, // const ChecksFilter &InFilter) : // Mgr (InMgr), BR(InBR), Filter(InFilter) {} // void visit(const ObjCImplementationDecl *D) const; // }; // static bool isInvalidationMethod(const ObjCMethodDecl *M, bool LookForPartial) { // for (const auto *Ann : M->specific_attrs<AnnotateAttr>()) { // if (!LookForPartial && // Ann->getAnnotation() == "objc_instance_variable_invalidator") // return true; // if (LookForPartial && // Ann->getAnnotation() == "objc_instance_variable_invalidator_partial") // return true; // } // return false; // } // void IvarInvalidationCheckerImpl::containsInvalidationMethod( // const ObjCContainerDecl *D, InvalidationInfo &OutInfo, bool Partial) { // if (!D) // return; // assert(!isa<ObjCImplementationDecl>(D)); // // TODO: Cache the results. // // Check all methods. // for (const auto *MDI : D->methods()) // if (isInvalidationMethod(MDI, Partial)) // OutInfo.addInvalidationMethod( // cast<ObjCMethodDecl>(MDI->getCanonicalDecl())); // // If interface, check all parent protocols and super. // if (const ObjCInterfaceDecl *InterfD = dyn_cast<ObjCInterfaceDecl>(D)) { // // Visit all protocols. // for (const auto *I : InterfD->protocols()) // containsInvalidationMethod(I->getDefinition(), OutInfo, Partial); // // Visit all categories in case the invalidation method is declared in // // a category. // for (const auto *Ext : InterfD->visible_extensions()) // containsInvalidationMethod(Ext, OutInfo, Partial); // containsInvalidationMethod(InterfD->getSuperClass(), OutInfo, Partial); // return; // } // // If protocol, check all parent protocols. // // if (const ObjCProtocolDecl *ProtD = dyn_cast<ObjCProtocolDecl>(D)) { // // for (const auto *I : ProtD->protocols()) { // // containsInvalidationMethod(I->getDefinition(), OutInfo, Partial); // // } // // return; // // } // } // bool IvarInvalidationCheckerImpl::trackIvar(const ObjCIvarDecl *Iv, // IvarSet &TrackedIvars, // const ObjCIvarDecl **FirstIvarDecl) { // QualType IvQTy = Iv->getType(); // const ObjCObjectPointerType *IvTy = IvQTy->getAs<ObjCObjectPointerType>(); // if (!IvTy) // return false; // const ObjCInterfaceDecl *IvInterf = IvTy->getInterfaceDecl(); // InvalidationInfo Info; // containsInvalidationMethod(IvInterf, Info, /*LookForPartial*/ false); // if (Info.needsInvalidation()) { // const ObjCIvarDecl *I = cast<ObjCIvarDecl>(Iv->getCanonicalDecl()); // TrackedIvars[I] = Info; // if (!*FirstIvarDecl) // *FirstIvarDecl = I; // return true; // } // return false; // } // const ObjCIvarDecl *IvarInvalidationCheckerImpl::findPropertyBackingIvar( // const ObjCPropertyDecl *Prop, // const ObjCInterfaceDecl *InterfaceD, // IvarSet &TrackedIvars, // const ObjCIvarDecl **FirstIvarDecl) { // const ObjCIvarDecl *IvarD = nullptr; // // Lookup for the synthesized case. // IvarD = Prop->getPropertyIvarDecl(); // // We only track the ivars/properties that are defined in the current // // class (not the parent). // if (IvarD && IvarD->getContainingInterface() == InterfaceD) { // if (TrackedIvars.count(IvarD)) { // return IvarD; // } // // If the ivar is synthesized we still want to track it. // if (trackIvar(IvarD, TrackedIvars, FirstIvarDecl)) // return IvarD; // } // // Lookup IVars named "_PropName"or "PropName" among the tracked Ivars. // StringRef PropName = Prop->getIdentifier()->getName(); // for (IvarSet::const_iterator I = TrackedIvars.begin(), // E = TrackedIvars.end(); I != E; ++I) { // const ObjCIvarDecl *Iv = I->first; // StringRef IvarName = Iv->getName(); // if (IvarName == PropName) // return Iv; // SmallString<128> PropNameWithUnderscore; // { // llvm::raw_svector_ostream os(PropNameWithUnderscore); // os << '_' << PropName; // } // if (IvarName == PropNameWithUnderscore) // return Iv; // } // // Note, this is a possible source of false positives. We could look at the // // getter implementation to find the ivar when its name is not derived from // // the property name. // return nullptr; // } // void IvarInvalidationCheckerImpl::printIvar(llvm::raw_svector_ostream &os, // const ObjCIvarDecl *IvarDecl, // const IvarToPropMapTy &IvarToPopertyMap) { // if (IvarDecl->getSynthesize()) { // const ObjCPropertyDecl *PD = IvarToPopertyMap.lookup(IvarDecl); // assert(PD &&"Do we synthesize ivars for something other than properties?"); // os << "Property "<< PD->getName() << " "; // } else { // os << "Instance variable "<< IvarDecl->getName() << " "; // } // } // Check that the invalidatable interfaces with ivars/properties implement the // invalidation methods. // void IvarInvalidationCheckerImpl:: // visit(const ObjCImplementationDecl *ImplD) const { // // Collect all ivars that need cleanup. // IvarSet Ivars; // // Record the first Ivar needing invalidation; used in reporting when only // // one ivar is sufficient. Cannot grab the first on the Ivars set to ensure // // deterministic output. // const ObjCIvarDecl *FirstIvarDecl = nullptr; // const ObjCInterfaceDecl *InterfaceD = ImplD->getClassInterface(); // // Collect ivars declared in this class, its extensions and its implementation // ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(InterfaceD); // for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; // Iv= Iv->getNextIvar()) // trackIvar(Iv, Ivars, &FirstIvarDecl); // // Construct Property/Property Accessor to Ivar maps to assist checking if an // // ivar which is backing a property has been reset. // MethToIvarMapTy PropSetterToIvarMap; // MethToIvarMapTy PropGetterToIvarMap; // PropToIvarMapTy PropertyToIvarMap; // IvarToPropMapTy IvarToPopertyMap; // ObjCInterfaceDecl::PropertyMap PropMap; // ObjCInterfaceDecl::PropertyDeclOrder PropOrder; // InterfaceD->collectPropertiesToImplement(PropMap, PropOrder); // for (ObjCInterfaceDecl::PropertyMap::iterator // I = PropMap.begin(), E = PropMap.end(); I != E; ++I) { // const ObjCPropertyDecl *PD = I->second; // if (PD->isClassProperty()) // continue; // const ObjCIvarDecl *ID = findPropertyBackingIvar(PD, InterfaceD, Ivars, // &FirstIvarDecl); // if (!ID) // continue; // // Store the mappings. // PD = cast<ObjCPropertyDecl>(PD->getCanonicalDecl()); // PropertyToIvarMap[PD] = ID; // IvarToPopertyMap[ID] = PD; // // Find the setter and the getter. // const ObjCMethodDecl *SetterD = PD->getSetterMethodDecl(); // if (SetterD) { // SetterD = SetterD->getCanonicalDecl(); // PropSetterToIvarMap[SetterD] = ID; // } // const ObjCMethodDecl *GetterD = PD->getGetterMethodDecl(); // if (GetterD) { // GetterD = GetterD->getCanonicalDecl(); // PropGetterToIvarMap[GetterD] = ID; // } // } // // If no ivars need invalidation, there is nothing to check here. // if (Ivars.empty()) // return; // // Find all partial invalidation methods. // InvalidationInfo PartialInfo; // containsInvalidationMethod(InterfaceD, PartialInfo, /*LookForPartial*/ true); // // Remove ivars invalidated by the partial invalidation methods. They do not // // need to be invalidated in the regular invalidation methods. // bool AtImplementationContainsAtLeastOnePartialInvalidationMethod = false; // for (MethodSet::iterator // I = PartialInfo.InvalidationMethods.begin(), // E = PartialInfo.InvalidationMethods.end(); I != E; ++I) { // const ObjCMethodDecl *InterfD = *I; // // Get the corresponding method in the @implementation. // const ObjCMethodDecl *D = ImplD->getMethod(InterfD->getSelector(), // InterfD->isInstanceMethod()); // if (D && D->hasBody()) { // AtImplementationContainsAtLeastOnePartialInvalidationMethod = true; // bool CalledAnotherInvalidationMethod = false; // // The MethodCrowler is going to remove the invalidated ivars. // MethodCrawler(Ivars, // CalledAnotherInvalidationMethod, // PropSetterToIvarMap, // PropGetterToIvarMap, // PropertyToIvarMap, // BR.getContext()).VisitStmt(D->getBody()); // // If another invalidation method was called, trust that full invalidation // // has occurred. // if (CalledAnotherInvalidationMethod) // Ivars.clear(); // } // } // // If all ivars have been invalidated by partial invalidators, there is // // nothing to check here. // if (Ivars.empty()) // return; // // Find all invalidation methods in this @interface declaration and parents. // InvalidationInfo Info; // containsInvalidationMethod(InterfaceD, Info, /*LookForPartial*/ false); // // Report an error in case none of the invalidation methods are declared. // if (!Info.needsInvalidation() && !PartialInfo.needsInvalidation()) { // if (Filter.check_MissingInvalidationMethod) // reportNoInvalidationMethod(Filter.checkName_MissingInvalidationMethod, // FirstIvarDecl, IvarToPopertyMap, InterfaceD, // /*MissingDeclaration*/ true); // // If there are no invalidation methods, there is no ivar validation work // // to be done. // return; // } // // Only check if Ivars are invalidated when InstanceVariableInvalidation // // has been requested. // if (!Filter.check_InstanceVariableInvalidation) // return; // // Check that all ivars are invalidated by the invalidation methods. // bool AtImplementationContainsAtLeastOneInvalidationMethod = false; // for (MethodSet::iterator I = Info.InvalidationMethods.begin(), // E = Info.InvalidationMethods.end(); I != E; ++I) { // const ObjCMethodDecl *InterfD = *I; // // Get the corresponding method in the @implementation. // const ObjCMethodDecl *D = ImplD->getMethod(InterfD->getSelector(), // InterfD->isInstanceMethod()); // if (D && D->hasBody()) { // AtImplementationContainsAtLeastOneInvalidationMethod = true; // // Get a copy of ivars needing invalidation. // IvarSet IvarsI = Ivars; // bool CalledAnotherInvalidationMethod = false; // MethodCrawler(IvarsI, // CalledAnotherInvalidationMethod, // PropSetterToIvarMap, // PropGetterToIvarMap, // PropertyToIvarMap, // BR.getContext()).VisitStmt(D->getBody()); // // If another invalidation method was called, trust that full invalidation // // has occurred. // if (CalledAnotherInvalidationMethod) // continue; // // Warn on the ivars that were not invalidated by the method. // for (IvarSet::const_iterator // I = IvarsI.begin(), E = IvarsI.end(); I != E; ++I) // reportIvarNeedsInvalidation(I->first, IvarToPopertyMap, D); // } // } // // Report an error in case none of the invalidation methods are implemented. // if (!AtImplementationContainsAtLeastOneInvalidationMethod) { // if (AtImplementationContainsAtLeastOnePartialInvalidationMethod) { // // Warn on the ivars that were not invalidated by the prrtial // // invalidation methods. // for (IvarSet::const_iterator // I = Ivars.begin(), E = Ivars.end(); I != E; ++I) // reportIvarNeedsInvalidation(I->first, IvarToPopertyMap, nullptr); // } else { // // Otherwise, no invalidation methods were implemented. // reportNoInvalidationMethod(Filter.checkName_InstanceVariableInvalidation, // FirstIvarDecl, IvarToPopertyMap, InterfaceD, // /*MissingDeclaration*/ false); // } // } // } // void IvarInvalidationCheckerImpl::reportNoInvalidationMethod( // CheckerNameRef CheckName, const ObjCIvarDecl *FirstIvarDecl, // const IvarToPropMapTy &IvarToPopertyMap, // const ObjCInterfaceDecl *InterfaceD, bool MissingDeclaration) const { // SmallString<128> sbuf; // llvm::raw_svector_ostream os(sbuf); // assert(FirstIvarDecl); // printIvar(os, FirstIvarDecl, IvarToPopertyMap); // os << "needs to be invalidated; "; // if (MissingDeclaration) // os << "no invalidation method is declared for "; // else // os << "no invalidation method is defined in the @implementation for "; // os << InterfaceD->getName(); // PathDiagnosticLocation IvarDecLocation = // PathDiagnosticLocation::createBegin(FirstIvarDecl, BR.getSourceManager()); // BR.EmitBasicReport(FirstIvarDecl, CheckName, "Incomplete invalidation", // categories::CoreFoundationObjectiveC, os.str(), // IvarDecLocation); // } // void IvarInvalidationCheckerImpl:: // reportIvarNeedsInvalidation(const ObjCIvarDecl *IvarD, // const IvarToPropMapTy &IvarToPopertyMap, // const ObjCMethodDecl *MethodD) const { // SmallString<128> sbuf; // llvm::raw_svector_ostream os(sbuf); // printIvar(os, IvarD, IvarToPopertyMap); // os << "needs to be invalidated or set to nil"; // if (MethodD) { // PathDiagnosticLocation MethodDecLocation = // PathDiagnosticLocation::createEnd(MethodD->getBody(), // BR.getSourceManager(), // Mgr.getAnalysisDeclContext(MethodD)); // BR.EmitBasicReport(MethodD, Filter.checkName_InstanceVariableInvalidation, // "Incomplete invalidation", // categories::CoreFoundationObjectiveC, os.str(), // MethodDecLocation); // } else { // BR.EmitBasicReport( // IvarD, Filter.checkName_InstanceVariableInvalidation, // "Incomplete invalidation", categories::CoreFoundationObjectiveC, // os.str(), // PathDiagnosticLocation::createBegin(IvarD, BR.getSourceManager())); // } // } // void IvarInvalidationCheckerImpl::MethodCrawler::markInvalidated( // const ObjCIvarDecl *Iv) { // IvarSet::iterator I = IVars.find(Iv); // if (I != IVars.end()) { // // If InvalidationMethod is present, we are processing the message send and // // should ensure we are invalidating with the appropriate method, // // otherwise, we are processing setting to 'nil'. // if (!InvalidationMethod || I->second.hasMethod(InvalidationMethod)) // IVars.erase(I); // } // } const Expr *IvarInvalidationCheckerImpl::MethodCrawler::peel(const Expr *E) const { E = E->IgnoreParenCasts(); if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) E = POE->getSyntacticForm()->IgnoreParenCasts(); if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) E = OVE->getSourceExpr()->IgnoreParenCasts(); return E; } // void IvarInvalidationCheckerImpl::MethodCrawler::checkObjCIvarRefExpr( // const ObjCIvarRefExpr *IvarRef) { // if (const Decl *D = IvarRef->getDecl()) // markInvalidated(cast<ObjCIvarDecl>(D->getCanonicalDecl())); // } // void IvarInvalidationCheckerImpl::MethodCrawler::checkObjCMessageExpr( // const ObjCMessageExpr *ME) { // const ObjCMethodDecl *MD = ME->getMethodDecl(); // if (MD) { // MD = MD->getCanonicalDecl(); // MethToIvarMapTy::const_iterator IvI = PropertyGetterToIvarMap.find(MD); // if (IvI != PropertyGetterToIvarMap.end()) // markInvalidated(IvI->second); // } // } // void IvarInvalidationCheckerImpl::MethodCrawler::checkObjCPropertyRefExpr( // const ObjCPropertyRefExpr *PA) { // if (PA->isExplicitProperty()) { // const ObjCPropertyDecl *PD = PA->getExplicitProperty(); // if (PD) { // PD = cast<ObjCPropertyDecl>(PD->getCanonicalDecl()); // PropToIvarMapTy::const_iterator IvI = PropertyToIvarMap.find(PD); // if (IvI != PropertyToIvarMap.end()) // markInvalidated(IvI->second); // return; // } // } // if (PA->isImplicitProperty()) { // const ObjCMethodDecl *MD = PA->getImplicitPropertySetter(); // if (MD) { // MD = MD->getCanonicalDecl(); // MethToIvarMapTy::const_iterator IvI =PropertyGetterToIvarMap.find(MD); // if (IvI != PropertyGetterToIvarMap.end()) // markInvalidated(IvI->second); // return; // } // } // } // bool IvarInvalidationCheckerImpl::MethodCrawler::isZero(const Expr *E) const { // E = peel(E); // return (E->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull) // != Expr::NPCK_NotNull); // } // void IvarInvalidationCheckerImpl::MethodCrawler::check(const Expr *E) { // E = peel(E); // if (const ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) { // checkObjCIvarRefExpr(IvarRef); // return; // } // if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E)) { // checkObjCPropertyRefExpr(PropRef); // return; // } // if (const ObjCMessageExpr *MsgExpr = dyn_cast<ObjCMessageExpr>(E)) { // checkObjCMessageExpr(MsgExpr); // return; // } // } void IvarInvalidationCheckerImpl::MethodCrawler::VisitBinaryOperator( const BinaryOperator *BO) { VisitStmt(BO); // Do we assign/compare against zero? If yes, check the variable we are // assigning to. BinaryOperatorKind Opcode = BO->getOpcode(); if (Opcode != BO_Assign && Opcode != BO_EQ && Opcode != BO_NE) return; if (isZero(BO->getRHS())) { check(BO->getLHS()); return; } if (Opcode != BO_Assign && isZero(BO->getLHS())) { check(BO->getRHS()); return; } } // void IvarInvalidationCheckerImpl::MethodCrawler::VisitObjCMessageExpr( // const ObjCMessageExpr *ME) { // const ObjCMethodDecl *MD = ME->getMethodDecl(); // const Expr *Receiver = ME->getInstanceReceiver(); // // Stop if we are calling '[self invalidate]'. // if (Receiver && isInvalidationMethod(MD, /*LookForPartial*/ false)) // if (Receiver->isObjCSelfExpr()) { // CalledAnotherInvalidationMethod = true; // return; // } // // Check if we call a setter and set the property to 'nil'. // if (MD && (ME->getNumArgs() == 1) && isZero(ME->getArg(0))) { // MD = MD->getCanonicalDecl(); // MethToIvarMapTy::const_iterator IvI = PropertySetterToIvarMap.find(MD); // if (IvI != PropertySetterToIvarMap.end()) { // markInvalidated(IvI->second); // return; // } // } // // Check if we call the 'invalidation' routine on the ivar. // if (Receiver) { // InvalidationMethod = MD; // check(Receiver->IgnoreParenCasts()); // InvalidationMethod = nullptr; // } // VisitStmt(ME); // } } // end anonymous namespace // Register the checkers. // namespace { // class IvarInvalidationChecker : // public Checker<check::ASTDecl<ObjCImplementationDecl> > { // public: // ChecksFilter Filter; // public: // void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& Mgr, // BugReporter &BR) const { // IvarInvalidationCheckerImpl Walker(Mgr, BR, Filter); // Walker.visit(D); // } // }; // } // end anonymous namespace // void ento::registerIvarInvalidationModeling(CheckerManager &mgr) { // mgr.registerChecker<IvarInvalidationChecker>(); // } bool ento::shouldRegisterIvarInvalidationModeling(const CheckerManager &mgr) { return true; } // #define REGISTER_CHECKER(name) \ // void ento::register##name(CheckerManager &mgr) { \ // IvarInvalidationChecker *checker = \ // mgr.getChecker<IvarInvalidationChecker>(); \ // checker->Filter.check_##name = true; \ // checker->Filter.checkName_##name = mgr.getCurrentCheckerName(); \ // } \ // \ // bool ento::shouldRegister##name(const CheckerManager &mgr) { return true; } // REGISTER_CHECKER(InstanceVariableInvalidation) // REGISTER_CHECKER(MissingInvalidationMethod)
1932cbb600210678c38e43f96b0bc2565ce64344
1e70eb1fc33e88a0b2a08690d961cbd06ca5f0c2
/Numerical methods/Krylov's_method/Метод Крылова/Нахождение собственных чисел.cpp
d9a4fe32f52a35493495c49ad16295771d5b6e4e
[]
no_license
LenaAlymova/LenaAlymova.github.io
c04d57cd62fc9dceeb0c4bc3655de02f15be3aad
8033f6a480036322d57e366d72f4c1fb4ac919b9
refs/heads/master
2022-10-30T02:12:53.863782
2020-06-15T18:15:50
2020-06-15T18:15:50
258,787,717
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
780
cpp
#include "Решение кубических уравнений.cpp" using namespace std; void FindingEigenValues(double *arrRootNumber,int n,int n2, double **initialMatrix,double **vectorC1) { double *x = new double[n]; double trA = 0.0;//Сумма главной диагонали for(int i = 0; i < n2; i++) { trA += initialMatrix[i][i];//Изначальная матрица } cout << "trA= " << trA <<endl; for(int j = 0; j < n; j++) { x[n-(j+1)] = arrRootNumber[j]; cout << "x[ "<<n-(j+1) <<" ] = " <<x[n-(j+1)]<<endl; } cout << "voy" <<endl; for(int o = 0; o < n; o++) { cout <<"x= " << x[ o ] << endl ; } if(n == 2) { metodKasatelnyh(x,n,trA,vectorC1); } if(n == 3) { metodKasatelnyh(x,n,trA,vectorC1); } delete[]x; }
90a7b5f453dc3c2a3588be7dd503b55a0d47fb27
1c8642d1903778d12c6c3a88a8e1254b1d6a25f7
/pallindrome.cpp
f7d39638a220456bd83713d283b3795905afe484
[]
no_license
Pushpankkatare/My-Project-Euler-Codes
8ef26fb325e2636867fddc4ec963489fb3ef94e2
621af7247a019a97615a189266a63b169b966bb2
refs/heads/main
2022-12-28T08:51:26.751988
2020-10-08T11:41:04
2020-10-08T11:41:04
302,320,404
0
0
null
null
null
null
UTF-8
C++
false
false
1,220
cpp
#include<iostream> #include<cmath> using namespace std; int pallindrome(int k) { int rev=0,p=k; //CHECKING FOR PALLINDROME while(k!=0) { rev=(rev*10)+(k%10); k=k/10; } if(p==rev) {return 1;} else return 0; } int main() { long long n; cin>>n; long long m=pow(10,n)-1; long long p=pow(10,(n-1)); long long max=0; for(long long i=m; i>=p; i--) { int u,ne; //HERE 111111 CAN BE SPLITTED INTO TWO THREE DIGIT MULTIPLES SO THEREFORE THE PALLINDROME HAS TO BE EVEN DIGIT //ALL THE EVEN DIGIT PALLINDROMES ARE MULTIPLE OF 11 if(i%11==0) { ne=1; u=i; } else { ne=11; u=i-(i%11); } for(long long j=u; j>=p; j=j-ne) { long long k=i*j; if(pallindrome(k)) { if(k>max) max=k; // SINCE EVERY PALLINDROME IN THE LOOP OF j WILL BE LESS THAN MAX THE ELSE CONDITION SHOULD BREAK THE LOOP OF j else break; } else continue; } } cout<<max; }
98b88f6c5043721e8dbe406c8eb23d8bc3fbd162
2ba42799db544fc3233d9648e392620d4d96fc9a
/old/wrapper/mr3_host.cxx
ea751133a722ea5eab42a707b2e8f98503add943
[]
no_license
mlochbaum/exafmm
f446d282fa14beb683e87c2460a7230cab7efafe
dabc3238aadf24df0f1ff8c27aa2e15e22cb744b
refs/heads/master
2021-01-17T15:44:52.407030
2016-03-18T07:47:39
2016-03-18T07:47:39
54,066,859
1
0
null
2016-03-16T21:14:15
2016-03-16T21:14:15
null
UTF-8
C++
false
false
8,550
cxx
#include <cstdlib> #include <cstdio> #include <cmath> #include "mr3.h" void MR3calccoulomb_ij_host(int ni, double xi[], double qi[], double force[], int nj, double xj[], double qj[], double rscale, int tblno, double xmax, int periodicflag) { /* periodic flag bit 0 : 0 --- non periodic, 1 --- periodic bit 1 : 0 --- no multiplication of qi 1 --- multiplication of qi */ int i,j,k; double dr[3],dtmp,r2,x,factor,rsqrt; static int rcutflag=0,ini=0; static double rcut,rcut2; char *s; int multiplyq=0; if(ini==0){ if((s=getenv("MR3_HOST_CUTOFF"))!=NULL){ sscanf(s,"%le",&rcut); rcut2=rcut*rcut; printf("rcut=%e is read from MR3_HOST_CUTOFF\n",rcut); rcutflag=1; } ini=1; } if((periodicflag & 2)!=0) multiplyq=1; if((periodicflag & 1)==0){ xmax*=2.0; } for(i=0;i<ni;i++){ for(j=0;j<nj;j++){ r2=0.0; for(k=0;k<3;k++){ dr[k]=xi[i*3+k]-xj[j*3+k]; if(dr[k]<-xmax/2.0){ dr[k]+=xmax; } if(dr[k]>=xmax/2.0){ dr[k]-=xmax; } r2+=dr[k]*dr[k]; } x=r2*rscale*rscale; if(r2!=0.0 && (rcutflag==0 || (rcutflag==1 && x<rcut2))){ if(tblno==0){ rsqrt=1.0/sqrt(r2); dtmp=qj[j]*rsqrt*rsqrt*rsqrt; if(multiplyq) dtmp*=qi[i]; for(k=0;k<3;k++){ force[i*3+k]+=dtmp*dr[k]; } } else if(tblno==1){ rsqrt=1.0/sqrt(r2); dtmp=qj[j]*rsqrt; if(multiplyq) dtmp*=qi[i]; for(k=0;k<3;k++){ force[i*3+k]+=dtmp; } } else if(tblno==6){ x=r2*rscale*rscale; dtmp=qj[j]*(M_2_SQRTPI*exp(-x)*pow(x,-1.0) + erfc(sqrt(x))*pow(x,-1.5)); factor=rscale*rscale*rscale*qi[i]; for(k=0;k<3;k++){ force[i*3+k]+=dtmp*dr[k]*factor; } } else if(tblno==7){ x=r2*rscale*rscale; dtmp=qj[j]*erfc(sqrt(x))*pow(x,-0.5); factor=rscale*qi[i]; for(k=0;k<3;k++){ force[i*3+k]+=dtmp*factor; } } } } } } void MR3calcvdw_ij_host(int ni, double xi[], int atypei[], double force[], int nj, double xj[], int atypej[], int nat, double gscale[], double rscale[], int tblno, double xmax, int periodicflag) { /* periodic flag 0 --- non periodic 1 --- periodic */ int i,j,k; double dr[3],r,dtmp,rs,gs,rrs,r2,r1,r6; // double r2min=0.25,r2max=64.0; double r2min=MD_LJ_R2MIN,r2max=MD_LJ_R2MAX; if((periodicflag & 1)==0){ xmax*=2.0; } if(tblno==5){ r2min=0.01;r2max=1e6;} for(i=0;i<ni;i++){ for(j=0;j<nj;j++){ r2=0.0; for(k=0;k<3;k++){ dr[k]=xi[i*3+k]-xj[j*3+k]; if(dr[k]<-xmax/2.0){ dr[k]+=xmax; } if(dr[k]>=xmax/2.0){ dr[k]-=xmax; } r2+=dr[k]*dr[k]; } if(r2!=0.0){ r=sqrt(r2); rs=rscale[atypei[i]*nat+atypej[j]]; gs=gscale[atypei[i]*nat+atypej[j]]; rrs=r2*rs; if(rrs>=r2min && rrs<r2max){ r1=1.0/rrs; r6=r1*r1*r1; if(tblno==2){ dtmp=gs*r6*r1*(2.0*r6-1.0); for(k=0;k<3;k++){ force[i*3+k]+=dtmp*dr[k]; } } else if(tblno==3){ dtmp=gs*r6*(r6-1.0); for(k=0;k<3;k++){ force[i*3+k]+=dtmp; } } else if(tblno==5){ dtmp=-gs*r6; for(k=0;k<3;k++){ force[i*3+k]+=dtmp*dr[k]; } } } } } } } void MR3calcewald_dft(int k[], int knum, double x[], int n, double chg[], double cellsize[3], double bs[], double bc[]) { int i,i3,j,j3,c; double th,cellsize_1[3]; for(i=0;i<3;i++) cellsize_1[i]=1.0/cellsize[i]; for(i=i3=0;i<knum;i++,i3+=3){ bs[i]=bc[i]=0.0; for(j=j3=0;j<n;j++,j3+=3){ th=0.0; for(c=0;c<3;c++) th+=k[i3+c]*x[j3+c]*cellsize_1[c]; th*=2.0*M_PI; bs[i]+=chg[j]*sin(th); bc[i]+=chg[j]*cos(th); } } } void MR3calcewald_idft_eng(int k[], double bs[], double bc[], int knum, double x[], int n, double cellsize[3], double force[]) { int i,i3,j,j3,c; double th,sth,cth; double cellsize_1[3]; double fstmp,fctmp; for(i=0;i<3;i++) cellsize_1[i]=1.0/cellsize[i]; for(i=i3=0;i<n;i++,i3+=3){ fstmp=fctmp=0.0; for(j=j3=0;j<knum;j++,j3+=3){ th=0.0; for(c=0;c<3;c++) th+=k[j3+c]*x[i3+c]*cellsize_1[c]; th*=2.0*M_PI; sth=sin(th); cth=cos(th); fstmp+=bs[j]*sth; fctmp+=bc[j]*cth; } force[i3]+=fstmp+fctmp; } } void MR3calcewald_idft_force(int k[], double bs[], double bc[], int knum, double x[], int n, double cellsize[3], double force[]) { int i,i3,j,j3,c; double th,sth,cth,cellsize_1[3]; double fst[3],fct[3]; double fstmp[3],fctmp[3]; for(i=0;i<3;i++) cellsize_1[i]=1.0/cellsize[i]; for(i=i3=0;i<n;i++,i3+=3){ for(c=0;c<3;c++) fstmp[c]=fctmp[c]=0.0; for(j=j3=0;j<knum;j++,j3+=3){ th=0.0; for(c=0;c<3;c++) th+=k[j3+c]*x[i3+c]*cellsize_1[c]; th*=2.0*M_PI; sth=sin(th); cth=cos(th); for(c=0;c<3;c++){ fst[c]=bc[j]*sth*k[j3+c]; fct[c]=bs[j]*cth*k[j3+c]; } for(c=0;c<3;c++){ fstmp[c]+=fst[c]; fctmp[c]+=fct[c]; } } for(c=0;c<3;c++){ force[i3+c]+=fstmp[c]-fctmp[c]; } } } void MR3calcewald_host(int *k, int knum_org, double *x, int n, double *chg, double alpha, double epsilon, double cell[3][3], double *force, double *tpot, double(*)[3]) { double *bs,*bc,cellsize[3],cellsize_1[3]; int knum,i,j,c,i3,j3; double factor1_tmp,vol1,eps1,alpha4,r2,kvtmp; knum=knum_org<0 ? -knum_org:knum_org; if((bs=(double *)malloc(sizeof(double)*knum))==NULL){ fprintf(stderr,"** error : can't malloc bs **\n"); exit(1); } if((bc=(double *)malloc(sizeof(double)*knum))==NULL){ fprintf(stderr,"** error : can't malloc bc **\n"); exit(1); } for(i=0;i<3;i++) cellsize[i]=cell[i][i]; for(i=0;i<3;i++) cellsize_1[i]=1.0/cellsize[i]; for(i=0,vol1=1.0;i<3;i++) vol1*=cellsize_1[i]; eps1=1.0/epsilon; alpha4=1.0/(4.0*alpha*alpha); for(i=0;i<n*3;i++) force[i]=0.0; /* DFT */ MR3calcewald_dft(k,knum,x,n,chg,cellsize,bs,bc); /* multiply factor etc */ *tpot=0.0; for(j=j3=0;j<knum;j++,j3+=3){ for(c=0,r2=0.0;c<3;c++){ kvtmp=2.0*M_PI*k[j3+c]*cellsize_1[c]; r2+=kvtmp*kvtmp; } factor1_tmp=2.0*eps1*vol1*exp(-r2*alpha4)/r2; *tpot+=0.5*factor1_tmp*(bs[j]*bs[j]+bc[j]*bc[j]); bs[j]*=factor1_tmp; bc[j]*=factor1_tmp; } /* IDFT */ if(knum_org<0){ /* potential energy */ MR3calcewald_idft_eng(k,bs,bc,knum,x,n,cellsize,force); for(i=i3=0;i<n;i++,i3+=3) force[i3]*=chg[i]; } else{ /* force */ MR3calcewald_idft_force(k,bs,bc,knum,x,n,cellsize,force); for(i=i3=0;i<n;i++,i3+=3){ for(c=0;c<3;c++) force[i3+c]*=2.0*M_PI*chg[i]*cellsize_1[c]; } } free(bs); free(bc); } int get_knum(double ksize) { double kmaxsq = ksize * ksize; int kmax = ksize; int knum = 0; for( int l=0; l<=kmax; l++ ) { int mmin = -kmax; if( l==0 ) mmin = 0; for( int m=mmin; m<=kmax; m++ ) { int nmin = -kmax; if( l==0 && m==0 ) nmin=1; for( int n=nmin; n<=kmax; n++ ) { double ksq = l * l + m * m + n * n; if( ksq <= kmaxsq ) { knum++; } } } } return knum; } void init_kvec(double ksize, int *kvec) { double kmaxsq = ksize * ksize; int kmax = ksize; int knum = 0; for( int l=0; l<=kmax; l++ ) { int mmin = -kmax; if( l==0 ) mmin = 0; for( int m=mmin; m<=kmax; m++ ) { int nmin = -kmax; if( l==0 && m==0 ) nmin=1; for( int n=nmin; n<=kmax; n++ ) { double ksq = l * l + m * m + n * n; if( ksq <= kmaxsq ) { kvec[3*knum+0] = l; kvec[3*knum+1] = m; kvec[3*knum+2] = n; knum++; } } } } }
b581b74f997808ca4c2d8474cc67e8a7be89342d
4f54fb00cfb3bed4e8132ce2e783c6d93fc9c7ca
/libc/src/stdio/printf_core/converter_atlas.h
71354cc0b96ce6f772286b9f12e8ab3ec18c4be9
[ "Apache-2.0", "LLVM-exception", "NCSA" ]
permissive
koparasy/HPAC
357101325a32ba5e27bf211400d9501e9fc37e7b
207b5b570375b9835d79c949b6efe33e7146fec2
refs/heads/develop
2023-04-14T04:36:50.098763
2022-08-24T17:48:58
2022-08-24T17:48:58
356,543,963
1
0
null
2022-08-26T02:09:59
2021-04-10T10:13:27
C++
UTF-8
C++
false
false
1,513
h
//===-- Map of converter headers in printf ----------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // This file exists so that if the user wants to supply a custom atlas they can // just replace the #include, additionally it keeps the ifdefs out of the // converter header. #ifndef LLVM_LIBC_SRC_STDIO_PRINTF_CORE_CONVERTER_ATLAS_H #define LLVM_LIBC_SRC_STDIO_PRINTF_CORE_CONVERTER_ATLAS_H // defines convert_string #include "src/stdio/printf_core/string_converter.h" // defines convert_char #include "src/stdio/printf_core/char_converter.h" // defines convert_int #include "src/stdio/printf_core/int_converter.h" // defines convert_oct #include "src/stdio/printf_core/oct_converter.h" // defines convert_hex #include "src/stdio/printf_core/hex_converter.h" // TODO(michaelrj): add a flag to disable float point values here // defines convert_float_decimal // defines convert_float_dec_exp // defines convert_float_hex_exp // defines convert_float_mixed #ifndef LLVM_LIBC_PRINTF_DISABLE_WRITE_INT #include "src/stdio/printf_core/write_int_converter.h" #endif // LLVM_LIBC_PRINTF_DISABLE_WRITE_INT // defines convert_pointer #include "src/stdio/printf_core/ptr_converter.h" #endif // LLVM_LIBC_SRC_STDIO_PRINTF_CORE_CONVERTER_ATLAS_H
fb470da426d393d5f90a7ed9628fbd70311280c6
2f258bbe75cda9fe965f47f802e27b80a9c744f8
/maximum_subarray.cpp
0fe906de29ec86141b4904ebabfd4befbca4cae2
[]
no_license
vancexu/LeetCode
4641ca7924a1d7c18eff27fccdb9b6ded8ff78bc
192dbde2eee188945029f375e8525f39ef4ab208
refs/heads/master
2021-01-10T21:28:23.677630
2014-11-18T20:26:58
2014-11-18T20:26:58
17,379,798
1
1
null
null
null
null
UTF-8
C++
false
false
567
cpp
/* Find the contiguous subarray within an array (containing at least one number) which has the largest sum. */ #include <iostream> using namespace std; class Solution { public: int maxSubArray(int A[], int n) { int res = A[0]; int curMax = A[0]; for (int i=1; i < n; ++i) { curMax = max(A[i], curMax+A[i]); res = max(res, curMax); } return res; } }; int main () { Solution sol; int A[] = {-2,1,-3,4,-1,2,1,-5,4}; cout << (6 == sol.maxSubArray(A, 9)) << endl; cout << endl; }
f49037ccb4892adba5fdad9f6dccf2874829b2de
35160cf953bdfa5767f26c924e58d5b736dee361
/prov1865/prov1865/소스.cpp
a61025fa54978beaadffdb407d204fbe1f13727d
[]
no_license
S4nop/Baekjoon
518cd27d1adbf19098295f93952e97b9e204c895
770db7da3f79b4c9962ce67973a9504dc1d64c97
refs/heads/master
2023-02-13T09:47:30.664987
2021-01-22T05:56:48
2021-01-22T05:56:48
315,946,879
0
0
null
null
null
null
UTF-8
C++
false
false
1,381
cpp
#include <cstdio> #include <iostream> #include <vector> #include <algorithm> #include <utility> #include <queue> #define INF 10000000 using namespace std; typedef pair<int, int> p; queue<int> q; vector<p> adj[505]; bool cango; int dist[505], chk[505], chkvs; void ClearQ(queue<int> &q){ queue<int> empty; swap(q, empty); } int main(){ ios_base::sync_with_stdio(0); int T, i, N, M, W, s, e, t; cin >> T; while (T-- != 0){ cin >> N >> M >> W; fill(dist, dist + 505, INF); fill(chk, chk + 505, 0); chkvs = 0; cango = 0; for (i = 0; i < 505; i++) adj[i].clear(); ClearQ(q); for (i = 0; i < M; i++){ cin >> s >> e >> t; if (e == 1) cango = true; adj[s - 1].push_back(p(e - 1, t)); } for (i = 0; i < W; i++){ cin >> s >> e >> t; if (e == 1) cango = true; adj[s - 1].push_back(p(e - 1, -t)); } dist[0] = 0; if (!cango) goto n; q.push(0); chk[0] = 1; int tmp; while (!q.empty()){ tmp = q.front(); if (++chkvs > N * N) { cout << "YES\n"; break; } q.pop(); chk[tmp] = 0; for (auto &u : adj[tmp]){ int n = u.first, w = u.second; if (dist[n] > dist[tmp] + w && w != INF){ dist[n] = dist[tmp] + w; if (chk[n]) continue; chk[n] = 1; q.push(n); } } } n: if (chkvs <= N * N) cout << "NO\n"; } }
ceb8ba035af545a9dcbcc1db357b7e12abb09d87
3267258116d79f880371c1885a23d8781d0ae9ad
/game_of_life/icontroller.h
0dd7a595c85e986c182ad8cd424c234321f366fc
[ "MIT" ]
permissive
XoDeR/game_of_life
d033249b148323076293497c56827e67ab8d6393
ff6a75e09a60a13b2c17949af55fe2d5e8f1074d
refs/heads/master
2021-01-16T18:10:12.656431
2016-03-29T23:50:30
2016-03-29T23:50:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
323
h
#ifndef ICONTROLLER_H #define ICONTROLLER_H #include <memory> class IController : public std::enable_shared_from_this<IController> { public: ~IController() {} virtual void ShowView() = 0; virtual size_t CountLiveNeighbours(size_t x, size_t y) = 0; virtual void ComputeNextIteration() = 0; }; #endif//ICONTROLLER_H
321a4e1c0641d85794ada37fd465bedb27263b2d
a7843c857fc8ddbb9a2408cc04c799f2d695019f
/holiday.cpp
41afab6118d1b6fdf1340f87a93387369136697b
[]
no_license
heilfitz/homework2
e444317e558ec47c896ec3d7491fabbbccc94dc6
bdb4e24a213b3b6451b17104c9819cb94435ce97
refs/heads/main
2023-08-23T09:14:58.732735
2021-10-11T07:01:47
2021-10-11T07:01:47
415,634,972
0
0
null
null
null
null
UTF-8
C++
false
false
2,063
cpp
/* 题目背景与描述 终于到了国庆了,小V开心的在思源湖上开船,他上午开150公里,下午开100公里,晚上和周末都休息(实行双休日),假设从周x(1<=x<=7)开始算起,请问这样过了n天以后,小V一共累计划了多少公里呢? 输入格式 输入两个整数x,n(表示从周x算起,经过n天,n在long int范围内)。 输出格式 输出一个整数,表示总共划了多少公里。 输入输出样例 Sample Input 3 10 Sample Output 2000 */ //解析:关键在于判定休息的日期 #include <iostream> using namespace std; int main() { int x,n; cin>>x>>n; int a,b; long long ans; a=n/7;//算过了几个礼拜 b=n%7;//几个礼拜剩下多少天 ans=5ll*a*250;//一整周一处理 //接下来处理剩下的日期,标答分成周一到周五、周六、周日三种情况 if(x<=5) { if(x+b-1<=5)//去掉完整周,结束时候是第几天,判定是否牵涉休息 ans+=b*250; else if(x+b-1<=7)//有没有过礼拜天,判定休息天数 ans+=(b-(x+b-1-5))*250; else//过了礼拜天一定休息两天 ans+=(b-2)*250; } else { if(x+b-1>7) ans+=(b-2)*250; } cout<<ans<<endl; return 0; } //xzy的程序 #include <iostream> using namespace std; int main() { long long int a,b,c,d,e,f; cin >> a >> b ; c = b / 7;//拆出来完整的周 d = b % 7;//剩下的日期 e=a+d-1;//结束后礼拜几 if (a!=7)//第一天休息拆出来 { //分别拆出休息一天、两天、不休息 if (e==6) f=c*5*250+(d-1)*250; else if (e>=7) f=c*5*250+(d-2)*250; else f=c*5*250+d*250; } else { if (e==6)//剩下最多六天,讨论剩下情况 f=c*5*250+(d)*250; else f=c*5*250+(d-1)*250; } cout << f << endl; return 0; }
487ab413eb2f486223bbad0b526e43151ad9f77f
a22196e847f4f5eaaed1d1a83b5fdb0e2cd3f352
/include/engine/datafacade_provider.hpp
99e5fad58f6d170617001fa63c7f700d910169c6
[ "BSD-2-Clause" ]
permissive
schollz/osrm-backend
671c3998e42eb65187416df94cb921376f728fc7
5b79640b44d15694a38cb9522ee97a9d675e438e
refs/heads/master
2023-08-31T23:07:31.173592
2017-11-08T05:11:08
2017-11-08T16:26:47
110,091,441
1
0
null
2017-11-09T09:02:05
2017-11-09T09:02:05
null
UTF-8
C++
false
false
2,426
hpp
#ifndef OSRM_ENGINE_DATAFACADE_PROVIDER_HPP #define OSRM_ENGINE_DATAFACADE_PROVIDER_HPP #include "engine/data_watchdog.hpp" #include "engine/datafacade.hpp" #include "engine/datafacade/contiguous_internalmem_datafacade.hpp" #include "engine/datafacade/process_memory_allocator.hpp" #include "engine/datafacade_factory.hpp" namespace osrm { namespace engine { namespace detail { template <typename AlgorithmT, template <typename A> class FacadeT> class DataFacadeProvider { public: using Facade = FacadeT<AlgorithmT>; virtual ~DataFacadeProvider() = default; virtual std::shared_ptr<const Facade> Get(const api::BaseParameters &) const = 0; virtual std::shared_ptr<const Facade> Get(const api::TileParameters &) const = 0; }; template <typename AlgorithmT, template <typename A> class FacadeT> class ImmutableProvider final : public DataFacadeProvider<AlgorithmT, FacadeT> { public: using Facade = typename DataFacadeProvider<AlgorithmT, FacadeT>::Facade; ImmutableProvider(const storage::StorageConfig &config) : facade_factory(std::make_shared<datafacade::ProcessMemoryAllocator>(config)) { } std::shared_ptr<const Facade> Get(const api::TileParameters &params) const override final { return facade_factory.Get(params); } std::shared_ptr<const Facade> Get(const api::BaseParameters &params) const override final { return facade_factory.Get(params); } private: DataFacadeFactory<FacadeT, AlgorithmT> facade_factory; }; template <typename AlgorithmT, template <typename A> class FacadeT> class WatchingProvider : public DataFacadeProvider<AlgorithmT, FacadeT> { DataWatchdog<AlgorithmT, FacadeT> watchdog; public: using Facade = typename DataFacadeProvider<AlgorithmT, FacadeT>::Facade; std::shared_ptr<const Facade> Get(const api::TileParameters &params) const override final { return watchdog.Get(params); } std::shared_ptr<const Facade> Get(const api::BaseParameters &params) const override final { return watchdog.Get(params); } }; } template <typename AlgorithmT> using DataFacadeProvider = detail::DataFacadeProvider<AlgorithmT, DataFacade>; template <typename AlgorithmT> using WatchingProvider = detail::WatchingProvider<AlgorithmT, DataFacade>; template <typename AlgorithmT> using ImmutableProvider = detail::ImmutableProvider<AlgorithmT, DataFacade>; } } #endif
cc09407407637d6bf53a30836f7feee823521341
a3254b9ee437a6fb55dde9037e29fe083b15fedd
/PYTHIA6/AliPythia6/AliPythia6.h
c5703224017ab208ff761fae24a39b72ecbc0c7a
[]
permissive
ALICEHLT/AliRoot
d768c99669c9794cf1b73f23076caa336dadb15b
2c786600dd440722389cbb32f6397038fab71bbd
refs/heads/dev
2021-01-23T02:10:15.531036
2018-05-14T15:16:37
2018-05-14T15:16:37
85,963,435
1
5
BSD-3-Clause
2018-04-17T19:04:17
2017-03-23T15:05:30
C++
UTF-8
C++
false
false
5,215
h
#ifndef ALIPYTHIA6_H #define ALIPYTHIA6_H /* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * See cxx source for full Copyright notice */ /* $Id: AliPythia.h,v 1.22 2007/10/09 08:43:24 morsch Exp $ */ #include <TPythia6.h> #include "AliPythiaBase.h" class AliFastGlauber; class AliQuenchingWeights; class AliStack; class AliPythia6 : public TPythia6, public AliPythiaBase { public: virtual ~AliPythia6(){;} virtual Int_t Version() {return (6);} // convert to compressed code and print result (for debugging only) virtual Int_t CheckedLuComp(Int_t kf); // Pythia initialisation for selected processes virtual void ProcInit (Process_t process, Float_t energy, StrucFunc_t strucfunc, Int_t tune); virtual void GenerateEvent() {Pyevnt();} virtual void GenerateMIEvent() {Pyevnw();} virtual void HadronizeEvent() {Pyexec();} virtual Int_t GetNumberOfParticles() {return GetN();} virtual void SetNumberOfParticles(Int_t i) {SetN(i);} virtual void EditEventList(Int_t i) {Pyedit(i);} virtual void PrintStatistics(); virtual void EventListing(); virtual Int_t GetParticles(TClonesArray *particles) {return ImportParticles(particles, "All");} // Treat protons as inside nuclei virtual void SetNuclei(Int_t a1, Int_t a2); // Set colliding nuclei ("p","n",...) virtual void SetCollisionSystem(TString projectile, TString target) { fProjectile = projectile; fTarget = target; } // Print particle properties virtual void PrintParticles(); // Reset the decay table virtual void ResetDecayTable(); // // Common Physics Configuration virtual void SetWeightPower(Double_t pow); // use pT,hard dependent weight instead of p_T,hard bins virtual void SetPtHardRange(Float_t ptmin, Float_t ptmax); virtual void SetYHardRange(Float_t ymin, Float_t ymax); virtual void SetFragmentation(Int_t flag); virtual void SetInitialAndFinalStateRadiation(Int_t flag1, Int_t flag2); virtual void SetIntrinsicKt(Float_t kt); virtual void SwitchHFOff(); virtual void SetPycellParameters(Float_t etamax, Int_t neta, Int_t nphi, Float_t thresh, Float_t etseed, Float_t minet, Float_t r); virtual void ModifiedSplitting(); virtual void SwitchHadronisationOff(); virtual void SwitchHadronisationOn(); // // Common Getters virtual void GetXandQ(Float_t& x1, Float_t& x2, Float_t& q); virtual Float_t GetXSection(); virtual Int_t ProcessCode(); virtual Float_t GetPtHard(); virtual Int_t GetNMPI(); // // virtual void SetDecayTable(); virtual void Pyevnw(); virtual void Pyjoin(Int_t& npart, Int_t* ipart); virtual void Pycell(Int_t& nclus); virtual void Pyclus(Int_t& nclus); virtual void GetJet(Int_t i, Float_t& px, Float_t& py, Float_t& pz, Float_t& e); virtual void LoadEvent(AliStack* stack, Int_t flag, Int_t reHadr); virtual void Pyshow(Int_t ip1, Int_t ip2, Double_t qmax); virtual void Pyshowq(Int_t ip1, Int_t ip2, Double_t qmax); virtual void Pyrobo(Int_t imi, Int_t ima, Double_t the, Double_t phi, Double_t bex, Double_t bey, Double_t bez); virtual void InitQuenching(Float_t bmin, Float_t bmax, Float_t k, Int_t iECMethod, Float_t zmax = 0.97, Int_t ngmax = 30); virtual void SetPyquenParameters(Double_t t0, Double_t tau0, Int_t nf, Int_t iengl, Int_t iangl); virtual void Pyquen(Double_t a, Int_t ibf, Double_t b); virtual void Qpygin0(); virtual void GetQuenchingParameters(Double_t& xp, Double_t& yp, Double_t z[4]); // return instance of the singleton static AliPythia6* Instance(); virtual void Quench(); // Assignment Operator AliPythia6 & operator=(const AliPythia6 & rhs); void Copy(TObject&) const; protected: Process_t fProcess; // Process type Float_t fEcms; // Centre of mass energy StrucFunc_t fStrucFunc; // Structure function TString fProjectile; // Projectile TString fTarget; // Target Int_t fDefMDCY[501]; // ! Default decay switches per particle Int_t fDefMDME[2001]; // ! Default decay switches per mode Double_t fZQuench[4]; // ! Quenching fractions for this even Double_t fXJet; // ! Jet production point X Double_t fYJet; // ! Jet production point Y Int_t fNGmax; // Maximum number of radiated gluons in quenching Float_t fZmax; // Maximum energy loss in quenching AliFastGlauber* fGlauber; // ! The Glauber model AliQuenchingWeights* fQuenchingWeights; // ! The Quenching Weights model static AliPythia6* fgAliPythia; // Pointer to single instance private: AliPythia6(); AliPythia6(const AliPythia6& pythia); void ConfigHeavyFlavor(); void AtlasTuning(); void AtlasTuningMC09(); ClassDef(AliPythia6,1) //ALICE UI to PYTHIA }; #endif
91f1d213f0d33be0229e2498aa86a947e682268e
675ff6d908bf86354e3c030e495df40fbee650ac
/discovery-examples/SEQ_mm/original.cc
4b776885572ff82d4c22cd8d40ed7627462fbd57
[]
no_license
chrisbrown1982/restoration
099dc3f53bf18174cdcb8c5423528a41b8b0835f
72daf0e6b559bdcef6ed3d037e3e9ea3cdd1fd7f
refs/heads/master
2023-01-05T22:53:35.548379
2020-11-05T15:29:54
2020-11-05T15:29:54
254,417,053
0
0
null
null
null
null
UTF-8
C++
false
false
414
cc
/*** we detect a GEMM, **/ #include <stdio.h> #include <stdlib.h> float matrix1[1000][1000]; float matrix2[1000][1000]; float matrix3[1000][1000]; int main() { for(int i = 0; i < 1000; i++) { for(int j = 0; j < 1000; j++) { float c = 0.0f; for(int k = 0; k < 1000; k++) { c+=matrix1[i][k]*matrix2[k][j]; } matrix3[i][j]=c; } } return EXIT_SUCCESS; }
70ceda283683246909bc12a6b562825e3ef932d5
a967c00721b9fe3e221bf60f8d1e3ec6f44eb130
/src/dynamic_index/singlethread/art_tree_generic_index.h
136ddc1db49bbc8ffa98f8ed12a57b7378ff35f6
[ "Apache-2.0" ]
permissive
JolyZhang/IndexZoo
128552f6a07cc967a94791ad88b767f57e5abe37
37d5be5273638e713a1e2ea47c6c474774a7cd3d
refs/heads/master
2020-03-28T12:38:01.485102
2018-09-10T00:42:23
2018-09-10T00:42:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,328
h
#pragma once #include "art_tree/art.h" #include "base_dynamic_generic_index.h" namespace dynamic_index { namespace singlethread { class ArtTreeGenericIndex : public BaseDynamicGenericIndex { public: ArtTreeGenericIndex(GenericDataTable *table_ptr) : BaseDynamicGenericIndex(table_ptr) { art_tree_init(&container_); } virtual ~ArtTreeGenericIndex() { art_tree_destroy(&container_); } virtual void insert(const GenericKey &key, const Uint64 &value) final { art_insert(&container_, (unsigned char*)(key.raw()), key.size(), value); } virtual void find(const GenericKey &key, std::vector<Uint64> &values) final { art_search(&container_, (unsigned char*)(key.raw()), key.size(), values); } virtual void find_range(const GenericKey &lhs_key, const GenericKey &rhs_key, std::vector<Uint64> &values) final { art_range_scan(&container_, (unsigned char*)(lhs_key.raw()), lhs_key.size(), (unsigned char*)(rhs_key.raw()), rhs_key.size(), values); } virtual void scan_full(std::vector<Uint64> &values, const size_t count) final { art_scan_limit(&container_, values, count); } virtual void erase(const GenericKey &key) final { // container_.erase(key); } virtual size_t size() const final { return art_size(&container_); } private: art_tree container_; }; } }
ce08a78113010a1604cde516603e6893c33211cc
b09920b9708b7436e7df144b35aa0f2fece05b9e
/Ad-Hoc/1546 - Feedback.cpp
0928028f7ed89a6223b734034994768a05c7e6d7
[ "MIT" ]
permissive
ahmedengu/URI-solutions
a964249ae80ce79a85423f848bb8b3a203021c73
c4f1a0f9635d13407983a2c89e3307e68c38651c
refs/heads/master
2021-01-17T14:26:31.341491
2020-08-11T18:29:58
2020-08-11T18:29:58
50,340,109
44
1
null
null
null
null
UTF-8
C++
false
false
476
cpp
#include <iostream> #include<cstdio> #include<cmath> #include<iomanip> #include <cstdlib> #include<cstring> using namespace std; int main() { int n,x,k; scanf("%d",&n); while(n>0){ n--; scanf("%d",&k); while(k>0){ k--; scanf("%d",&x); switch(x){ case 1: printf("Rolien\n"); break; case 2: printf("Naej\n"); break; case 3: printf("Elehcim\n"); break; case 4: printf("Odranoel\n"); break; } } } return 0; }
8e0611e08882661c2e84424fc3c42fec222ea1df
90108215838410ae143212878d43375ef5245bf0
/AtCoder/C++/AtCoder/abc138/d.cpp
4a20e76301585aef140aacc930290fde2a3fbb9c
[]
no_license
officer/CompetitivePrograming
1caa669d322984e490a8fdf7e225426b60cb2b33
522c155683027758ea72b7fadb7e3d072b2b1371
refs/heads/master
2020-06-28T15:55:23.039410
2020-01-09T07:12:06
2020-01-09T07:12:06
200,274,336
0
0
null
null
null
null
UTF-8
C++
false
false
1,002
cpp
#include <iostream> #include <algorithm> #include <map> #include <vector> #include <set> #include <bitset> #include <unordered_map> #include <queue> using namespace std; #define rep(i, n) for (int i = 0; i < (int)(n); i++) struct Node { vector<int> to; int score; }; void dfs(int vertex, vector<Node> &nodes, int parent = -1){ Node current = nodes[vertex]; for(vector<int>::iterator i = nodes[vertex].to.begin(); i != nodes[vertex].to.end(); i++){ if (*i == parent){ continue; } nodes[*i].score += current.score; dfs(*i, nodes, vertex); } } int main(){ int N,Q; int a,b; cin >> N >> Q; vector<Node> nodes(N); rep(i, N-1){ cin >> a >> b; a--; b--; nodes[a].to.push_back(b); nodes[b].to.push_back(a); } rep(i, Q){ cin >> a >> b; a--; nodes[a].score += b; } dfs(0, nodes); rep(i, N){ cout << nodes[i].score << " "; } }
27d07916f25636bcff134028f6c3775fb429bb36
4178989e42b66a44ea90a9aa19b0ade57a9e2d80
/commands.cpp
e18f37f04e1f9ffd9365ea81492f4cdd036a35e2
[]
no_license
pullasunil/CodeForces
4505df4303f4199fc15b8cdc72b2aef8b2d92bf4
bb8cdbc7f0193f9372556983e4afe5e38351fc42
refs/heads/master
2021-01-15T13:12:07.957045
2013-01-04T14:49:43
2013-01-04T14:49:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,069
cpp
#include <iostream> #include <string> #include <cstdlib> #include <vector> using namespace std; vector<string> tokenize(string str){ int init = 0,i,length = str.length(); string curr; vector<string> retval; for(i=0;i<length;i++){ if(str[i] == '/'){ curr = str.substr(init,i - init); if(curr != "") retval.push_back(curr); init = i+1; } } if(init <= length - 1) retval.push_back(str.substr(init)); return retval; } int main(){ string inp,path,pwd; std::vector<string> v; pwd = "/"; int j,N,length,i,len; cin>>N; while(N--){ cin>>inp; if(inp == "pwd") cout<<pwd<<endl; else{ cin>>path; if(path[0] == '/') pwd = "/"; v = tokenize(path); length = v.size(); for(i=0;i<length;i++){ if(v[i] == ".."){ len = pwd.length(); if(len > 1){ pwd = pwd.substr(0,len - 1); len = pwd.length(); for(j=len-1;j>=0;j--){ if(pwd[j] == '/') break; } pwd = pwd.substr(0,j+1); } } else{ pwd = pwd + v[i]; pwd = pwd + "/"; } } } v.clear(); } return 0; }
bf1ab84de032419b7200762e79cfb00f7461445c
425063d3980a46dbe60a075436c3262fff92f655
/src/wavelength_assignment_sub_problem.h
740f302992ea611e03e1acb8ec6d1264e60113e5
[]
no_license
eduardogama/rwba-problem
4e21f5d8c07e40c219ab4cef9ceb0d5c8713c8db
59d8dea5c770f4c44d6bab62239304a238407c64
refs/heads/master
2021-01-01T18:50:05.548984
2017-08-08T17:03:31
2017-08-08T17:03:31
98,442,204
0
0
null
null
null
null
UTF-8
C++
false
false
1,431
h
#ifndef WAVELENGTHASSIGNMENTSUBPROBLEM_H #define WAVELENGTHASSIGNMENTSUBPROBLEM_H #include "path.h" #include <iostream> #include <climits> #include <omp.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include "lambda_control.h" #include "hole.h" class WavelengthAssignmentSubProblem { public: WavelengthAssignmentSubProblem(); virtual ~WavelengthAssignmentSubProblem(){} virtual bool searchLambda(Path &path, unsigned nSlots); virtual bool searchLambda(Path &path, vector<Path> &path_int, unsigned nSlots); void setStateNetwork(LambdaControl *lambdaControl); bool hasFindedLambda() const; unsigned getLastLambdaFinded() const; unsigned getLastSlotFinded() const; void getActualSateNetwork(vector<bool> &actualStateNetwork, Path &path); void getNextStateNetwork(Path &path, Hole &hole, vector<bool> &nextStateNetwork, unsigned nSlots); protected: bool findedLambda; unsigned lastLambdaFinded; bool findedSlots; unsigned lastSlotFinded; LambdaControl *lambdaControl; bool firstFitHeuristic(Path &path, unsigned nSlots); bool firstFitExtremesHeuristic(Path &path, unsigned nSlots); bool randomHeuristic(Path &path, unsigned nSlots); bool leastCapacityLossHeuristc(Path &path, unsigned nSlots); bool lossOfCapacityHeuristc(Path &path, vector<Path> &path_int, unsigned nSlots); void copyArray(int pathSize, bool *from, bool *to); }; #endif // WAVELENGTHASSIGNMENTSUBPROBLEM_H
c5976a86f85adae68f5ce4b017e96288dd03c0a2
9240ceb15f7b5abb1e4e4644f59d209b83d70066
/sp/src/public/engine/SndInfo.h
3a60b3e5195f615e62c8fd1f449d0209643131db
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Margen67/blamod
13e5cd9f7f94d1612eb3f44a2803bf2f02a3dcbe
d59b5f968264121d013a81ae1ba1f51432030170
refs/heads/master
2023-04-16T12:05:12.130933
2019-02-20T10:23:04
2019-02-20T10:23:04
264,556,156
2
0
NOASSERTION
2020-05-17T00:47:56
2020-05-17T00:47:55
null
UTF-8
C++
false
false
1,667
h
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //============================================================================= #ifndef SNDINFO_H #define SNDINFO_H #ifdef _WIN32 #pragma once #endif class Vector; #include "utlsymbol.h" //----------------------------------------------------------------------------- // Purpose: Client side only //----------------------------------------------------------------------------- struct SndInfo_t { // Sound Guid int m_nGuid; FileNameHandle_t m_filenameHandle; // filesystem filename handle - call IFilesystem to conver this to a string int m_nSoundSource; int m_nChannel; // If a sound is being played through a speaker entity (e.g., on a monitor,), this is the // entity upon which to show the lips moving, if the sound has sentence data int m_nSpeakerEntity; float m_flVolume; float m_flLastSpatializedVolume; // Radius of this sound effect (spatialization is different within the radius) float m_flRadius; int m_nPitch; Vector *m_pOrigin; Vector *m_pDirection; // if true, assume sound source can move and update according to entity bool m_bUpdatePositions; // true if playing linked sentence bool m_bIsSentence; // if true, bypass all dsp processing for this sound (ie: music) bool m_bDryMix; // true if sound is playing through in-game speaker entity. bool m_bSpeaker; // true if sound is playing with special DSP effect bool m_bSpecialDSP; // for snd_show, networked sounds get colored differently than local sounds bool m_bFromServer; }; #endif // SNDINFO_H
69df624188b15da8da31b98af0041c61ac68d65d
388625bcd64f7b5493ebc7990f59455501a5e7a8
/Arduino/I2C_Scaner/I2C_Scaner.ino
26db5f83c3b9852e55e5b0dbe602d7a6fd5a96ba
[]
no_license
FatalErrror/Arduino-Motion-Caption
070669c3374fd0adbd924e3c8740593e5d3057bf
59a6f2bd132dc7915e5c067bf2574ee9475f7920
refs/heads/main
2023-02-19T22:39:06.348939
2021-01-25T14:03:25
2021-01-25T14:03:25
320,860,051
1
0
null
null
null
null
UTF-8
C++
false
false
1,533
ino
#include <Wire.h> // подключим стандартную библиотеку I2C #define addr 0x0D // I2C адрес цифрового компаса HMC5883L void setup() { Serial.begin(115200); // инициализация последовательного порта Wire.begin(); // инициализация I2C } void loop() { Wire.beginTransmission(addr); // начинаем связь с устройством по адресу 0x1E Wire.write(0x00); // регистр, с которого мы начнём запрашивать данные Wire.endTransmission(); Wire.requestFrom(addr, 48, true); // запрашиваем 3 байта у ведомого while( Wire.available() ) { for (int i = 0; i < 48;i++) { Serial.print(i); Serial.print(" = "); Serial.println(Wire.read(), HEX); } /* char a = Wire.read(); // считываем байт из регистра 0xA; устройство само переходит к следующему регистру char b = Wire.read(); // считываем байт из регистра 0xB char c = Wire.read(); // считываем байт из регистра 0xС // Выводим считанное в последовательный порт: Serial.print("A = "); Serial.println(a, HEX); Serial.print("B = "); Serial.println(b, HEX); Serial.print("C = "); Serial.println(c, HEX); Serial.println(); */ } delay(100); }
ab23f158023c04bf9f54857415b3758684fc378a
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/curl/gumtree/curl_new_log_2120.cpp
e84f7eed5a8b03ace0d1a86033ac5026cd3cdad1
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
535
cpp
fputs( " proxy HTTP Basic authentication.\n" "\n" " --proxy-digest\n" " Tells curl to use HTTP Digest authentication when communicating\n" " with the given proxy. Use --digest for enabling HTTP Digest with\n" " a remote host.\n" "\n" " If this option is used twice, the second will again disable\n" " proxy HTTP Digest.\n" "\n" " --proxy-ntlm\n" " Tells curl to use HTTP NTLM authentication when communicating\n" , stdout);
607a8019514915023dfa70ae9f68ef427202c71d
0fef9cfbcb202abb1a40cbca01ba4e2755beed28
/LeGO-LOAM/src/imageProjection.cpp
996fe3c563e08a961dfc45378080ad41dacf051d
[ "BSD-3-Clause" ]
permissive
lliuguangwei/LeGO-LOAM
9eebbec4558c27c5859be1862435f861570fde3f
ce39b29b0aa883e43b387c13df05a40725f991bf
refs/heads/master
2020-04-01T13:14:26.958307
2019-02-24T13:09:33
2019-02-24T13:09:33
153,243,348
0
0
BSD-3-Clause
2018-10-16T07:41:28
2018-10-16T07:41:28
null
UTF-8
C++
false
false
17,562
cpp
// Copyright 2013, Ji Zhang, Carnegie Mellon University // Further contributions copyright (c) 2016, Southwest Research Institute // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // 3. Neither the name of the copyright holder 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 HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include "utility.h" class ImageProjection{ private: ros::NodeHandle nh; ros::Subscriber subLaserCloud; ros::Publisher pubFullCloud; ros::Publisher pubFullInfoCloud; ros::Publisher pubGroundCloud; ros::Publisher pubSegmentedCloud; ros::Publisher pubSegmentedCloudPure; ros::Publisher pubSegmentedCloudInfo; ros::Publisher pubOutlierCloud; pcl::PointCloud<PointType>::Ptr laserCloudIn; pcl::PointCloud<PointType>::Ptr fullCloud; pcl::PointCloud<PointType>::Ptr fullInfoCloud; pcl::PointCloud<PointType>::Ptr groundCloud; pcl::PointCloud<PointType>::Ptr segmentedCloud; pcl::PointCloud<PointType>::Ptr segmentedCloudPure; pcl::PointCloud<PointType>::Ptr outlierCloud; PointType nanPoint; cv::Mat rangeMat; cv::Mat labelMat; cv::Mat groundMat; int labelCount; float startOrientation; float endOrientation; cloud_msgs::cloud_info segMsg; std_msgs::Header cloudHeader; std::vector<std::pair<uint8_t, uint8_t> > neighborIterator; uint16_t *allPushedIndX; uint16_t *allPushedIndY; uint16_t *queueIndX; uint16_t *queueIndY; public: ImageProjection(): nh("~"){ subLaserCloud = nh.subscribe<sensor_msgs::PointCloud2>("/velodyne_points", 1, &ImageProjection::cloudHandler, this); pubFullCloud = nh.advertise<sensor_msgs::PointCloud2> ("/full_cloud_projected", 1); pubFullInfoCloud = nh.advertise<sensor_msgs::PointCloud2> ("/full_cloud_info", 1); pubGroundCloud = nh.advertise<sensor_msgs::PointCloud2> ("/ground_cloud", 1); pubSegmentedCloud = nh.advertise<sensor_msgs::PointCloud2> ("/segmented_cloud", 1); pubSegmentedCloudPure = nh.advertise<sensor_msgs::PointCloud2> ("/segmented_cloud_pure", 1); pubSegmentedCloudInfo = nh.advertise<cloud_msgs::cloud_info> ("/segmented_cloud_info", 1); pubOutlierCloud = nh.advertise<sensor_msgs::PointCloud2> ("/outlier_cloud", 1); nanPoint.x = std::numeric_limits<float>::quiet_NaN(); nanPoint.y = std::numeric_limits<float>::quiet_NaN(); nanPoint.z = std::numeric_limits<float>::quiet_NaN(); nanPoint.intensity = -1; allocateMemory(); resetParameters(); } void allocateMemory(){ laserCloudIn.reset(new pcl::PointCloud<PointType>()); fullCloud.reset(new pcl::PointCloud<PointType>()); fullInfoCloud.reset(new pcl::PointCloud<PointType>()); groundCloud.reset(new pcl::PointCloud<PointType>()); segmentedCloud.reset(new pcl::PointCloud<PointType>()); segmentedCloudPure.reset(new pcl::PointCloud<PointType>()); outlierCloud.reset(new pcl::PointCloud<PointType>()); fullCloud->points.resize(N_SCAN*Horizon_SCAN); fullInfoCloud->points.resize(N_SCAN*Horizon_SCAN); segMsg.startRingIndex.assign(N_SCAN, 0); segMsg.endRingIndex.assign(N_SCAN, 0); segMsg.segmentedCloudGroundFlag.assign(N_SCAN*Horizon_SCAN, false); segMsg.segmentedCloudColInd.assign(N_SCAN*Horizon_SCAN, 0); segMsg.segmentedCloudRange.assign(N_SCAN*Horizon_SCAN, 0); std::pair<int8_t, int8_t> neighbor; neighbor.first = -1; neighbor.second = 0; neighborIterator.push_back(neighbor); neighbor.first = 0; neighbor.second = 1; neighborIterator.push_back(neighbor); neighbor.first = 0; neighbor.second = -1; neighborIterator.push_back(neighbor); neighbor.first = 1; neighbor.second = 0; neighborIterator.push_back(neighbor); allPushedIndX = new uint16_t[N_SCAN*Horizon_SCAN]; allPushedIndY = new uint16_t[N_SCAN*Horizon_SCAN]; queueIndX = new uint16_t[N_SCAN*Horizon_SCAN]; queueIndY = new uint16_t[N_SCAN*Horizon_SCAN]; } void resetParameters(){ laserCloudIn->clear(); groundCloud->clear(); segmentedCloud->clear(); segmentedCloudPure->clear(); outlierCloud->clear(); rangeMat = cv::Mat(N_SCAN, Horizon_SCAN, CV_32F, cv::Scalar::all(FLT_MAX)); groundMat = cv::Mat(N_SCAN, Horizon_SCAN, CV_8S, cv::Scalar::all(0)); labelMat = cv::Mat(N_SCAN, Horizon_SCAN, CV_32S, cv::Scalar::all(0)); labelCount = 1; std::fill(fullCloud->points.begin(), fullCloud->points.end(), nanPoint); std::fill(fullInfoCloud->points.begin(), fullInfoCloud->points.end(), nanPoint); } ~ImageProjection(){} void copyPointCloud(const sensor_msgs::PointCloud2ConstPtr& laserCloudMsg){ cloudHeader = laserCloudMsg->header; pcl::fromROSMsg(*laserCloudMsg, *laserCloudIn); } void cloudHandler(const sensor_msgs::PointCloud2ConstPtr& laserCloudMsg){ copyPointCloud(laserCloudMsg); findStartEndAngle(); projectPointCloud(); groundRemoval(); cloudSegmentation(); publishCloud(); resetParameters(); } void findStartEndAngle(){ segMsg.startOrientation = -atan2(laserCloudIn->points[0].y, laserCloudIn->points[0].x); segMsg.endOrientation = -atan2(laserCloudIn->points[laserCloudIn->points.size() - 1].y, laserCloudIn->points[laserCloudIn->points.size() - 2].x) + 2 * M_PI; if (segMsg.endOrientation - segMsg.startOrientation > 3 * M_PI) { segMsg.endOrientation -= 2 * M_PI; } else if (segMsg.endOrientation - segMsg.startOrientation < M_PI) segMsg.endOrientation += 2 * M_PI; segMsg.orientationDiff = segMsg.endOrientation - segMsg.startOrientation; } void projectPointCloud(){ float verticalAngle, horizonAngle, range; size_t rowIdn, columnIdn, index, cloudSize; PointType thisPoint; cloudSize = laserCloudIn->points.size(); for (size_t i = 0; i < cloudSize; ++i){ thisPoint.x = laserCloudIn->points[i].x; thisPoint.y = laserCloudIn->points[i].y; thisPoint.z = laserCloudIn->points[i].z; verticalAngle = atan2(thisPoint.z, sqrt(thisPoint.x * thisPoint.x + thisPoint.y * thisPoint.y)) * 180 / M_PI; rowIdn = (verticalAngle + ang_bottom) / ang_res_y; if (rowIdn < 0 || rowIdn >= N_SCAN) continue; horizonAngle = atan2(thisPoint.x, thisPoint.y) * 180 / M_PI; if (horizonAngle <= -90) columnIdn = -int(horizonAngle / ang_res_x) - 450; else if (horizonAngle >= 0) columnIdn = -int(horizonAngle / ang_res_x) + 1350; else columnIdn = 1350 - int(horizonAngle / ang_res_x); range = sqrt(thisPoint.x * thisPoint.x + thisPoint.y * thisPoint.y + thisPoint.z * thisPoint.z); rangeMat.at<float>(rowIdn, columnIdn) = range; thisPoint.intensity = (float)rowIdn + (float)columnIdn / 10000.0; index = columnIdn + rowIdn * Horizon_SCAN; fullCloud->points[index] = thisPoint; fullInfoCloud->points[index].intensity = range; } } void groundRemoval(){ size_t lowerInd, upperInd; float diffX, diffY, diffZ, angle; for (size_t j = 0; j < Horizon_SCAN; ++j){ for (size_t i = 0; i < groundScanInd; ++i){ lowerInd = j + ( i )*Horizon_SCAN; upperInd = j + (i+1)*Horizon_SCAN; if (fullCloud->points[lowerInd].intensity == -1 || fullCloud->points[upperInd].intensity == -1){ groundMat.at<int8_t>(i,j) = -1; continue; } diffX = fullCloud->points[upperInd].x - fullCloud->points[lowerInd].x; diffY = fullCloud->points[upperInd].y - fullCloud->points[lowerInd].y; diffZ = fullCloud->points[upperInd].z - fullCloud->points[lowerInd].z; angle = atan2(diffZ, sqrt(diffX*diffX + diffY*diffY) ) * 180 / M_PI; if (abs(angle - sensorMountAngle) <= 10){ groundMat.at<int8_t>(i,j) = 1; groundMat.at<int8_t>(i+1,j) = 1; } } } for (size_t i = 0; i < N_SCAN; ++i){ for (size_t j = 0; j < Horizon_SCAN; ++j){ if (groundMat.at<int8_t>(i,j) == 1 || rangeMat.at<float>(i,j) == FLT_MAX){ labelMat.at<int>(i,j) = -1; } } } if (pubGroundCloud.getNumSubscribers() != 0){ for (size_t i = 0; i <= groundScanInd; ++i){ for (size_t j = 0; j < Horizon_SCAN; ++j){ if (groundMat.at<int8_t>(i,j) == 1) groundCloud->push_back(fullCloud->points[j + i*Horizon_SCAN]); } } } } void cloudSegmentation(){ for (size_t i = 0; i < N_SCAN; ++i) for (size_t j = 0; j < Horizon_SCAN; ++j) if (labelMat.at<int>(i,j) == 0) labelComponents(i, j); int sizeOfSegCloud = 0; for (size_t i = 0; i < N_SCAN; ++i) { segMsg.startRingIndex[i] = sizeOfSegCloud-1 + 5; for (size_t j = 0; j < Horizon_SCAN; ++j) { if (labelMat.at<int>(i,j) > 0 || groundMat.at<int8_t>(i,j) == 1){ if (labelMat.at<int>(i,j) == 999999){ if (i > groundScanInd && j % 5 == 0){ outlierCloud->push_back(fullCloud->points[j + i*Horizon_SCAN]); continue; }else{ continue; } } if (groundMat.at<int8_t>(i,j) == 1){ if (j%5!=0 && j>5 && j<Horizon_SCAN-5) continue; } segMsg.segmentedCloudGroundFlag[sizeOfSegCloud] = (groundMat.at<int8_t>(i,j) == 1); segMsg.segmentedCloudColInd[sizeOfSegCloud] = j; segMsg.segmentedCloudRange[sizeOfSegCloud] = rangeMat.at<float>(i,j); segmentedCloud->push_back(fullCloud->points[j + i*Horizon_SCAN]); ++sizeOfSegCloud; } } segMsg.endRingIndex[i] = sizeOfSegCloud-1 - 5; } if (pubSegmentedCloudPure.getNumSubscribers() != 0){ for (size_t i = 0; i < N_SCAN; ++i){ for (size_t j = 0; j < Horizon_SCAN; ++j){ if (labelMat.at<int>(i,j) > 0 && labelMat.at<int>(i,j) != 999999){ segmentedCloudPure->push_back(fullCloud->points[j + i*Horizon_SCAN]); segmentedCloudPure->points.back().intensity = labelMat.at<int>(i,j); } } } } } void labelComponents(int row, int col){ float d1, d2, alpha, angle; int fromIndX, fromIndY, thisIndX, thisIndY; bool lineCountFlag[N_SCAN] = {false}; queueIndX[0] = row; queueIndY[0] = col; int queueSize = 1; int queueStartInd = 0; int queueEndInd = 1; allPushedIndX[0] = row; allPushedIndY[0] = col; int allPushedIndSize = 1; while(queueSize > 0){ fromIndX = queueIndX[queueStartInd]; fromIndY = queueIndY[queueStartInd]; --queueSize; ++queueStartInd; labelMat.at<int>(fromIndX, fromIndY) = labelCount; for (auto iter = neighborIterator.begin(); iter != neighborIterator.end(); ++iter){ thisIndX = fromIndX + (*iter).first; thisIndY = fromIndY + (*iter).second; if (thisIndX < 0 || thisIndX >= N_SCAN) continue; if (thisIndY < 0) thisIndY = Horizon_SCAN - 1; if (thisIndY >= Horizon_SCAN) thisIndY = 0; if (labelMat.at<int>(thisIndX, thisIndY) != 0) continue; d1 = std::max(rangeMat.at<float>(fromIndX, fromIndY), rangeMat.at<float>(thisIndX, thisIndY)); d2 = std::min(rangeMat.at<float>(fromIndX, fromIndY), rangeMat.at<float>(thisIndX, thisIndY)); if ((*iter).first == 0) alpha = segmentAlphaX; else alpha = segmentAlphaY; angle = atan2(d2*sin(alpha), (d1 -d2*cos(alpha))); if (angle > segmentTheta){ queueIndX[queueEndInd] = thisIndX; queueIndY[queueEndInd] = thisIndY; ++queueSize; ++queueEndInd; labelMat.at<int>(thisIndX, thisIndY) = labelCount; lineCountFlag[thisIndX] = true; allPushedIndX[allPushedIndSize] = thisIndX; allPushedIndY[allPushedIndSize] = thisIndY; ++allPushedIndSize; } } } bool feasibleSegment = false; if (allPushedIndSize >= 30) feasibleSegment = true; else if (allPushedIndSize >= segmentValidPointNum){ int lineCount = 0; for (size_t i = 0; i < N_SCAN; ++i) if (lineCountFlag[i] == true) ++lineCount; if (lineCount >= segmentValidLineNum) feasibleSegment = true; } if (feasibleSegment == true){ ++labelCount; }else{ for (size_t i = 0; i < allPushedIndSize; ++i){ labelMat.at<int>(allPushedIndX[i], allPushedIndY[i]) = 999999; } } } void publishCloud(){ segMsg.header = cloudHeader; pubSegmentedCloudInfo.publish(segMsg); sensor_msgs::PointCloud2 laserCloudTemp; pcl::toROSMsg(*outlierCloud, laserCloudTemp); laserCloudTemp.header.stamp = cloudHeader.stamp; laserCloudTemp.header.frame_id = "base_link"; pubOutlierCloud.publish(laserCloudTemp); pcl::toROSMsg(*segmentedCloud, laserCloudTemp); laserCloudTemp.header.stamp = cloudHeader.stamp; laserCloudTemp.header.frame_id = "base_link"; pubSegmentedCloud.publish(laserCloudTemp); if (pubFullCloud.getNumSubscribers() != 0){ pcl::toROSMsg(*fullCloud, laserCloudTemp); laserCloudTemp.header.stamp = cloudHeader.stamp; laserCloudTemp.header.frame_id = "base_link"; pubFullCloud.publish(laserCloudTemp); } if (pubGroundCloud.getNumSubscribers() != 0){ pcl::toROSMsg(*groundCloud, laserCloudTemp); laserCloudTemp.header.stamp = cloudHeader.stamp; laserCloudTemp.header.frame_id = "base_link"; pubGroundCloud.publish(laserCloudTemp); } if (pubSegmentedCloudPure.getNumSubscribers() != 0){ pcl::toROSMsg(*segmentedCloudPure, laserCloudTemp); laserCloudTemp.header.stamp = cloudHeader.stamp; laserCloudTemp.header.frame_id = "base_link"; pubSegmentedCloudPure.publish(laserCloudTemp); } if (pubFullInfoCloud.getNumSubscribers() != 0){ pcl::toROSMsg(*fullInfoCloud, laserCloudTemp); laserCloudTemp.header.stamp = cloudHeader.stamp; laserCloudTemp.header.frame_id = "base_link"; pubFullInfoCloud.publish(laserCloudTemp); } } }; int main(int argc, char** argv){ ros::init(argc, argv, "lego_loam"); ImageProjection IP; ROS_INFO("\033[1;32m---->\033[0m Image Projection Started."); ros::spin(); return 0; }
be68d24176b7cf52a1ff95afc0128b240b5cdc8a
9d74109009f15b47d4dacf4a1afc67c218f22b88
/src/Darksend.h
6f82664bb4b6cc2aa152c7ae7c921d1fabb3d926
[ "MIT" ]
permissive
cryptoghass/timeismoneycrypto
45b9bf195df7d6a31b86407765099dc8c96fb7c8
b6ba5d76dcc8bda13cd91331d2794ba5ca2349c4
refs/heads/master
2020-03-31T08:52:09.640298
2018-09-17T21:18:36
2018-09-17T21:18:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,842
h
// Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2015-2017 The ALQO developers // Copyright (c) 2017-2018 The TimeIsMoney developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef DARKSEND_H #define DARKSEND_H #include "main.h" #include "masternode-payments.h" #include "masternode-sync.h" #include "masternodeman.h" #include "Darksend-relay.h" #include "sync.h" class CTxIn; class CDarksendPool; class CDarKsendSigner; class CMasterNodeVote; class CBitcoinAddress; class CDarksendQueue; class CDarksendBroadcastTx; class CActiveMasternode; // pool states for mixing #define POOL_STATUS_UNKNOWN 0 // waiting for update #define POOL_STATUS_IDLE 1 // waiting for update #define POOL_STATUS_QUEUE 2 // waiting in a queue #define POOL_STATUS_ACCEPTING_ENTRIES 3 // accepting entries #define POOL_STATUS_FINALIZE_TRANSACTION 4 // master node will broadcast what it accepted #define POOL_STATUS_SIGNING 5 // check inputs/outputs, sign final tx #define POOL_STATUS_TRANSMISSION 6 // transmit transaction #define POOL_STATUS_ERROR 7 // error #define POOL_STATUS_SUCCESS 8 // success // status update message constants #define MASTERNODE_ACCEPTED 1 #define MASTERNODE_REJECTED 0 #define MASTERNODE_RESET -1 #define DARKSEND_QUEUE_TIMEOUT 30 #define DARKSEND_SIGNING_TIMEOUT 15 // used for anonymous relaying of inputs/outputs/sigs #define DARKSEND_RELAY_IN 1 #define DARKSEND_RELAY_OUT 2 #define DARKSEND_RELAY_SIG 3 static const int64_t DARKSEND_COLLATERAL = (10 * COIN); static const int64_t DARKSEND_POOL_MAX = (999.99 * COIN); extern CDarksendPool DarKsendPool; extern CDarKsendSigner DarKsendSigner; extern std::vector<CDarksendQueue> vecDarksendQueue; extern std::string strMasterNodePrivKey; extern map<uint256, CDarksendBroadcastTx> mapDarksendBroadcastTxes; extern CActiveMasternode activeMasternode; /** Holds an Darksend input */ class CTxDSIn : public CTxIn { public: bool fHasSig; // flag to indicate if signed int nSentTimes; //times we've sent this anonymously CTxDSIn(const CTxIn& in) { prevout = in.prevout; scriptSig = in.scriptSig; prevPubKey = in.prevPubKey; nSequence = in.nSequence; nSentTimes = 0; fHasSig = false; } }; /** Holds an Darksend output */ class CTxDSOut : public CTxOut { public: int nSentTimes; //times we've sent this anonymously CTxDSOut(const CTxOut& out) { nValue = out.nValue; nRounds = out.nRounds; scriptPubKey = out.scriptPubKey; nSentTimes = 0; } }; // A clients transaction in the Darksend pool class CDarKsendEntry { public: bool isSet; std::vector<CTxDSIn> sev; std::vector<CTxDSOut> vout; int64_t amount; CTransaction collateral; CTransaction txSupporting; int64_t addedTime; // time in UTC milliseconds CDarKsendEntry() { isSet = false; collateral = CTransaction(); amount = 0; } /// Add entries to use for Darksend bool Add(const std::vector<CTxIn> vinIn, int64_t amountIn, const CTransaction collateralIn, const std::vector<CTxOut> voutIn) { if (isSet) { return false; } BOOST_FOREACH (const CTxIn& in, vinIn) sev.push_back(in); BOOST_FOREACH (const CTxOut& out, voutIn) vout.push_back(out); amount = amountIn; collateral = collateralIn; isSet = true; addedTime = GetTime(); return true; } bool AddSig(const CTxIn& vin) { BOOST_FOREACH (CTxDSIn& s, sev) { if (s.prevout == vin.prevout && s.nSequence == vin.nSequence) { if (s.fHasSig) { return false; } s.scriptSig = vin.scriptSig; s.prevPubKey = vin.prevPubKey; s.fHasSig = true; return true; } } return false; } bool IsExpired() { return (GetTime() - addedTime) > DARKSEND_QUEUE_TIMEOUT; // 120 seconds } }; /** * A currently inprogress Darksend merge and denomination information */ class CDarksendQueue { public: CTxIn vin; int64_t time; int nDenom; bool ready; //ready for submit std::vector<unsigned char> vchSig; CDarksendQueue() { nDenom = 0; vin = CTxIn(); time = 0; vchSig.clear(); ready = false; } ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { READWRITE(nDenom); READWRITE(vin); READWRITE(time); READWRITE(ready); READWRITE(vchSig); } bool GetAddress(CService& addr) { CMasternode* pmn = mnodeman.Find(vin); if (pmn != NULL) { addr = pmn->addr; return true; } return false; } /// Get the protocol version bool GetProtocolVersion(int& protocolVersion) { CMasternode* pmn = mnodeman.Find(vin); if (pmn != NULL) { protocolVersion = pmn->protocolVersion; return true; } return false; } /** Sign this Darksend transaction * \return true if all conditions are met: * 1) we have an active Masternode, * 2) we have a valid Masternode private key, * 3) we signed the message successfully, and * 4) we verified the message successfully */ bool Sign(); bool Relay(); /// Is this Darksend expired? bool IsExpired() { return (GetTime() - time) > DARKSEND_QUEUE_TIMEOUT; // 120 seconds } /// Check if we have a valid Masternode address bool CheckSignature(); }; /** Helper class to store Darksend transaction (tx) information. */ class CDarksendBroadcastTx { public: CTransaction tx; CTxIn vin; vector<unsigned char> vchSig; int64_t sigTime; }; /** Helper object for signing and checking signatures */ class CDarKsendSigner { public: /// Is the inputs associated with this public key? (and there is 1000 TIM - checking if valid masternode) bool IsVinAssociatedWithPubkey(CTxIn& vin, CPubKey& pubkey); /// Set the private/public key values, returns true if successful bool GetKeysFromSecret(std::string strSecret, CKey& keyRet, CPubKey& pubkeyRet); /// Set the private/public key values, returns true if successful bool SetKey(std::string strSecret, std::string& errorMessage, CKey& key, CPubKey& pubkey); /// Sign the message, returns true if successful bool SignMessage(std::string strMessage, std::string& errorMessage, std::vector<unsigned char>& vchSig, CKey key); /// Verify the message, returns true if succcessful bool VerifyMessage(CPubKey pubkey, std::vector<unsigned char>& vchSig, std::string strMessage, std::string& errorMessage); }; /** Used to keep track of current status of Darksend pool */ class CDarksendPool { private: mutable CCriticalSection cs_Darksend; std::vector<CDarKsendEntry> entries; // Masternode/clients entries CMutableTransaction finalTransaction; // the finalized transaction ready for signing int64_t lastTimeChanged; // last time the 'state' changed, in UTC milliseconds unsigned int state; // should be one of the POOL_STATUS_XXX values unsigned int entriesCount; unsigned int lastEntryAccepted; unsigned int countEntriesAccepted; std::vector<CTxIn> lockedCoins; std::string lastMessage; bool unitTest; int sessionID; int sessionUsers; //N Users have said they'll join bool sessionFoundMasternode; //If we've found a compatible Masternode std::vector<CTransaction> vecSessionCollateral; int cachedLastSuccess; int minBlockSpacing; //required blocks between mixes CMutableTransaction txCollateral; int64_t lastNewBlock; //debugging data std::string strAutoDenomResult; public: enum messages { ERR_ALREADY_HAVE, ERR_DENOM, ERR_ENTRIES_FULL, ERR_EXISTING_TX, ERR_FEES, ERR_INVALID_COLLATERAL, ERR_INVALID_INPUT, ERR_INVALID_SCRIPT, ERR_INVALID_TX, ERR_MAXIMUM, ERR_MN_LIST, ERR_MODE, ERR_NON_STANDARD_PUBKEY, ERR_NOT_A_MN, ERR_QUEUE_FULL, ERR_RECENT, ERR_SESSION, ERR_MISSING_TX, ERR_VERSION, MSG_NOERR, MSG_SUCCESS, MSG_ENTRIES_ADDED }; // where collateral should be made out to CScript collateralPubKey; CMasternode* pSubmittedToMasternode; int sessionDenom; //Users must submit an denom matching this int cachedNumBlocks; //used for the overview screen CDarksendPool() { /* Darksend uses collateral addresses to trust parties entering the pool to behave themselves. If they don't it takes their money. */ cachedLastSuccess = 0; cachedNumBlocks = std::numeric_limits<int>::max(); unitTest = false; txCollateral = CMutableTransaction(); minBlockSpacing = 0; lastNewBlock = 0; SetNull(); } /** Process a Darksend message using the Darksend protocol * \param pfrom * \param strCommand lower case command string; valid values are: * Command | Description * -------- | ----------------- * dsa | Darksend Acceptable * dsc | Darksend Complete * dsf | Darksend Final tx * dsi | Darksend vIn * dsq | Darksend Queue * dss | Darksend Signal Final Tx * dssu | Darksend status update * dssub | Darksend Subscribe To * \param vRecv */ void ProcessMessageDarksend(CNode* pfrom, std::string& strCommand, CDataStream& vRecv); void InitCollateralAddress() { SetCollateralAddress(Params().DarksendPoolDummyAddress()); } void SetMinBlockSpacing(int minBlockSpacingIn) { minBlockSpacing = minBlockSpacingIn; } bool SetCollateralAddress(std::string strAddress); void Reset(); void SetNull(); void UnlockCoins(); bool IsNull() const { return state == POOL_STATUS_ACCEPTING_ENTRIES && entries.empty(); } int GetState() const { return state; } std::string GetStatus(); int GetEntriesCount() const { return entries.size(); } /// Get the time the last entry was accepted (time in UTC milliseconds) int GetLastEntryAccepted() const { return lastEntryAccepted; } /// Get the count of the accepted entries int GetCountEntriesAccepted() const { return countEntriesAccepted; } // Set the 'state' value, with some logging and capturing when the state changed void UpdateState(unsigned int newState) { if (fMasterNode && (newState == POOL_STATUS_ERROR || newState == POOL_STATUS_SUCCESS)) { LogPrint("Darksend", "CDarksendPool::UpdateState() - Can't set state to ERROR or SUCCESS as a Masternode. \n"); return; } LogPrintf("CDarksendPool::UpdateState() == %d | %d \n", state, newState); if (state != newState) { lastTimeChanged = GetTimeMillis(); if (fMasterNode) { RelayStatus(DarKsendPool.sessionID, DarKsendPool.GetState(), DarKsendPool.GetEntriesCount(), MASTERNODE_RESET); } } state = newState; } /// Get the maximum number of transactions for the pool int GetMaxPoolTransactions() { return Params().PoolMaxTransactions(); } /// Do we have enough users to take entries? bool IsSessionReady() { return sessionUsers >= GetMaxPoolTransactions(); } /// Are these outputs compatible with other client in the pool? bool IsCompatibleWithEntries(std::vector<CTxOut>& vout); /// Is this amount compatible with other client in the pool? bool IsCompatibleWithSession(int64_t nAmount, CTransaction txCollateral, int& errorID); /// Passively run Darksend in the background according to the configuration in settings (only for QT) bool DoAutomaticDenominating(bool fDryRun = false); bool PrepareDarksendDenominate(); /// Check for process in Darksend void Check(); void CheckFinalTransaction(); /// Charge fees to bad actors (Charge clients a fee if they're abusive) void ChargeFees(); /// Rarely charge fees to pay miners void ChargeRandomFees(); void CheckTimeout(); void CheckForCompleteQueue(); /// Check to make sure a signature matches an input in the pool bool SignatureValid(const CScript& newSig, const CTxIn& newVin); /// If the collateral is valid given by a client bool IsCollateralValid(const CTransaction& txCollateral); /// Add a clients entry to the pool bool AddEntry(const std::vector<CTxIn>& newInput, const int64_t& nAmount, const CTransaction& txCollateral, const std::vector<CTxOut>& newOutput, int& errorID); /// Add signature to a vin bool AddScriptSig(const CTxIn& newVin); /// Check that all inputs are signed. (Are all inputs signed?) bool SignaturesComplete(); /// As a client, send a transaction to a Masternode to start the denomination process void SendDarksendDenominate(std::vector<CTxIn>& vin, std::vector<CTxOut>& vout, int64_t amount); /// Get Masternode updates about the progress of Darksend bool StatusUpdate(int newState, int newEntriesCount, int newAccepted, int& errorID, int newSessionID = 0); /// As a client, check and sign the final transaction bool SignFinalTransaction(CTransaction& finalTransactionNew, CNode* node); /// Get the last valid block hash for a given modulus bool GetLastValidBlockHash(uint256& hash, int mod = 1, int nBlockHeight = 0); /// Process a new block void NewBlock(); void CompletedTransaction(bool error, int errorID); void ClearLastMessage(); /// Used for liquidity providers bool SendRandomPaymentToSelf(); /// Split up large inputs or make fee sized inputs bool MakeCollateralAmounts(); bool CreateDenominated(int64_t nTotalValue); /// Get the denominations for a list of outputs (returns a bitshifted integer) int GetDenominations(const std::vector<CTxOut>& vout, bool fSingleRandomDenom = false); int GetDenominations(const std::vector<CTxDSOut>& vout); void GetDenominationsToString(int nDenom, std::string& strDenom); /// Get the denominations for a specific amount of TIM. int GetDenominationsByAmount(int64_t nAmount, int nDenomTarget = 0); // is not used anymore? int GetDenominationsByAmounts(std::vector<int64_t>& vecAmount); std::string GetMessageByID(int messageID); // // Relay Darksend Messages // void RelayFinalTransaction(const int sessionID, const CTransaction& txNew); void RelaySignaturesAnon(std::vector<CTxIn>& vin); void RelayInAnon(std::vector<CTxIn>& vin, std::vector<CTxOut>& vout); void RelayIn(const std::vector<CTxDSIn>& vin, const int64_t& nAmount, const CTransaction& txCollateral, const std::vector<CTxDSOut>& vout); void RelayStatus(const int sessionID, const int newState, const int newEntriesCount, const int newAccepted, const int errorID = MSG_NOERR); void RelayCompletedTransaction(const int sessionID, const bool error, const int errorID); }; void ThreadCheckDarKsendPool(); #endif
2a09745048bb69469d1789f412a2757041bb824a
14c2d3193d39e973e00df21351ed5d0186526dd2
/ch10/ConsoleOutput.cpp
440990e867fd78ff344372f52e89fda305e642c3
[]
no_license
younnggsuk/cpp
f914b8deb6436b527615bf30ee0b040526648ca8
2b99d9e447ad7c91f49bbd38b4b18b74c0a98dac
refs/heads/master
2020-05-19T08:43:58.955580
2019-05-04T17:58:53
2019-05-04T17:58:53
184,927,631
0
0
null
null
null
null
UTF-8
C++
false
false
635
cpp
#include <iostream> namespace mystd { class ostream { public: void operator<<(const char *str) { printf("%s", str); } void operator<<(char str) { printf("%c", str); } void operator<<(int num) { printf("%d", num); } void operator<<(double e) { printf("%g", e); } void operator<<(ostream& (*fp)(ostream& ostm)) { fp(*this); } }; ostream& endl(ostream& ostm) { ostm<<'\n'; fflush(stdout); return ostm; } ostream cout; } int main() { using mystd::cout; using mystd::endl; cout<<"Simple String"; cout<<endl; cout<<3.14; cout<<endl; cout<<123; endl(cout); return 0; }
e35ae1c377a91032c9a486678f38967359d666f4
31b33fd6d6500964b2f4aa29186451c3db30ea1b
/Userland/Libraries/LibGfx/QOIWriter.cpp
07d389fb58cd72464e746d9c10fe267350ab20dc
[ "BSD-2-Clause" ]
permissive
jcs/serenity
4ca6f6eebdf952154d50d74516cf5c17dbccd418
0f1f92553213c6c2c7268078c9d39b813c24bb49
refs/heads/master
2022-11-27T13:12:11.214253
2022-11-21T17:01:22
2022-11-22T20:13:35
229,094,839
10
2
BSD-2-Clause
2019-12-19T16:25:40
2019-12-19T16:25:39
null
UTF-8
C++
false
false
6,598
cpp
/* * Copyright (c) 2022, Olivier De Cannière <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ #include "QOIWriter.h" #include <AK/String.h> namespace Gfx { ByteBuffer QOIWriter::encode(Bitmap const& bitmap) { QOIWriter writer; writer.add_header(bitmap.width(), bitmap.height(), Channels::RGBA, Colorspace::sRGB); Color previous_pixel = { 0, 0, 0, 255 }; bool creating_run = false; int run_length = 0; for (auto y = 0; y < bitmap.height(); y++) { for (auto x = 0; x < bitmap.width(); x++) { auto pixel = bitmap.get_pixel(x, y); // Check for at most 62 consecutive identical pixels. if (pixel == previous_pixel) { if (!creating_run) { creating_run = true; run_length = 0; writer.insert_into_running_array(pixel); } run_length++; // If the run reaches a maximum length of 62 or if this is the last pixel then create the chunk. if (run_length == 62 || (y == bitmap.height() - 1 && x == bitmap.width() - 1)) { writer.add_run_chunk(run_length); creating_run = false; } continue; } // Run ended with the previous pixel. Create a chunk for it and continue processing this pixel. if (creating_run) { writer.add_run_chunk(run_length); creating_run = false; } // Check if the pixel matches a pixel in the running array. auto index = pixel_hash_function(pixel); auto& array_pixel = writer.running_array[index]; if (array_pixel == pixel) { writer.add_index_chunk(index); previous_pixel = pixel; continue; } writer.running_array[index] = pixel; // Check if pixel can be expressed as a difference of the previous pixel. if (pixel.alpha() == previous_pixel.alpha()) { int red_difference = pixel.red() - previous_pixel.red(); int green_difference = pixel.green() - previous_pixel.green(); int blue_difference = pixel.blue() - previous_pixel.blue(); int relative_red_difference = red_difference - green_difference; int relative_blue_difference = blue_difference - green_difference; if (red_difference > -3 && red_difference < 2 && green_difference > -3 && green_difference < 2 && blue_difference > -3 && blue_difference < 2) { writer.add_diff_chunk(red_difference, green_difference, blue_difference); previous_pixel = pixel; continue; } if (relative_red_difference > -9 && relative_red_difference < 8 && green_difference > -33 && green_difference < 32 && relative_blue_difference > -9 && relative_blue_difference < 8) { writer.add_luma_chunk(relative_red_difference, green_difference, relative_blue_difference); previous_pixel = pixel; continue; } writer.add_rgb_chunk(pixel.red(), pixel.green(), pixel.blue()); previous_pixel = pixel; continue; } previous_pixel = pixel; // Write full color values. writer.add_rgba_chunk(pixel.red(), pixel.green(), pixel.blue(), pixel.alpha()); } } writer.add_end_marker(); return ByteBuffer::copy(writer.m_data).release_value_but_fixme_should_propagate_errors(); } void QOIWriter::add_header(u32 width, u32 height, Channels channels = Channels::RGBA, Colorspace color_space = Colorspace::sRGB) { // FIXME: Handle RGB and all linear channels. if (channels == Channels::RGB || color_space == Colorspace::Linear) TODO(); m_data.append(qoi_magic_bytes.data(), sizeof(qoi_magic_bytes)); auto big_endian_width = AK::convert_between_host_and_big_endian(width); m_data.append(bit_cast<u8*>(&big_endian_width), sizeof(width)); auto big_endian_height = AK::convert_between_host_and_big_endian(height); m_data.append(bit_cast<u8*>(&big_endian_height), sizeof(height)); // Number of channels: 3 = RGB, 4 = RGBA. m_data.append(4); // Colorspace: 0 = sRGB, 1 = all linear channels. m_data.append(color_space == Colorspace::sRGB ? 0 : 1); } void QOIWriter::add_rgb_chunk(u8 r, u8 g, u8 b) { constexpr static u8 rgb_tag = 0b1111'1110; m_data.append(rgb_tag); m_data.append(r); m_data.append(g); m_data.append(b); } void QOIWriter::add_rgba_chunk(u8 r, u8 g, u8 b, u8 a) { constexpr static u8 rgba_tag = 0b1111'1111; m_data.append(rgba_tag); m_data.append(r); m_data.append(g); m_data.append(b); m_data.append(a); } void QOIWriter::add_index_chunk(unsigned int index) { constexpr static u8 index_tag = 0b0000'0000; u8 chunk = index_tag | index; m_data.append(chunk); } void QOIWriter::add_diff_chunk(i8 red_difference, i8 green_difference, i8 blue_difference) { constexpr static u8 diff_tag = 0b0100'0000; u8 bias = 2; u8 red = red_difference + bias; u8 green = green_difference + bias; u8 blue = blue_difference + bias; u8 chunk = diff_tag | (red << 4) | (green << 2) | blue; m_data.append(chunk); } void QOIWriter::add_luma_chunk(i8 relative_red_difference, i8 green_difference, i8 relative_blue_difference) { constexpr static u8 luma_tag = 0b1000'0000; u8 green_bias = 32; u8 red_blue_bias = 8; u8 chunk1 = luma_tag | (green_difference + green_bias); u8 chunk2 = ((relative_red_difference + red_blue_bias) << 4) | (relative_blue_difference + red_blue_bias); m_data.append(chunk1); m_data.append(chunk2); } void QOIWriter::add_run_chunk(unsigned run_length) { constexpr static u8 run_tag = 0b1100'0000; int bias = -1; u8 chunk = run_tag | (run_length + bias); m_data.append(chunk); } void QOIWriter::add_end_marker() { m_data.append(qoi_end_marker.data(), sizeof(qoi_end_marker)); } u32 QOIWriter::pixel_hash_function(Color pixel) { return (pixel.red() * 3 + pixel.green() * 5 + pixel.blue() * 7 + pixel.alpha() * 11) % 64; } void QOIWriter::insert_into_running_array(Color pixel) { auto index = pixel_hash_function(pixel); running_array[index] = pixel; } }
5639d5ecf882fe33dbc0affb37b674d139e87dba
c637ab9662be02f44bbcf16f4d26c9019cd70ceb
/moc/moc_QUpdateWin.cpp
b4d07ef11a74f1acb8290218c9e20002aaff60ff
[]
no_license
junagit/rns510_dtv
54de294b96ffdbbd4243518791dad6d1b1c9f07b
733646485d67fcbbba5773462dc8fed87bb6a448
refs/heads/master
2020-05-30T23:24:03.221330
2016-08-03T07:15:50
2016-08-03T07:15:50
64,822,394
0
0
null
null
null
null
UTF-8
C++
false
false
3,785
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'QUpdateWin.h' ** ** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.5) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../include/QUpdateWin.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'QUpdateWin.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 63 #error "This file was generated using the moc from 4.8.5. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_QUpdateWin[] = { // content: 6, // revision 0, // classname 0, 0, // classinfo 5, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 2, // signalCount // signals: signature, parameters, type, tag, flags 19, 12, 11, 11, 0x05, 44, 38, 11, 11, 0x05, // slots: signature, parameters, type, tag, flags 64, 12, 11, 11, 0x08, 85, 38, 11, 11, 0x08, 102, 11, 11, 11, 0x08, 0 // eod }; static const char qt_meta_stringdata_QUpdateWin[] = { "QUpdateWin\0\0action\0sigMenuAction(int)\0" "value\0sigSetValue(qint64)\0" "doSigMenuAction(int)\0setValue(qint64)\0" "media_timerEvent()\0" }; void QUpdateWin::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { Q_ASSERT(staticMetaObject.cast(_o)); QUpdateWin *_t = static_cast<QUpdateWin *>(_o); switch (_id) { case 0: _t->sigMenuAction((*reinterpret_cast< int(*)>(_a[1]))); break; case 1: _t->sigSetValue((*reinterpret_cast< qint64(*)>(_a[1]))); break; case 2: _t->doSigMenuAction((*reinterpret_cast< int(*)>(_a[1]))); break; case 3: _t->setValue((*reinterpret_cast< qint64(*)>(_a[1]))); break; case 4: _t->media_timerEvent(); break; default: ; } } } const QMetaObjectExtraData QUpdateWin::staticMetaObjectExtraData = { 0, qt_static_metacall }; const QMetaObject QUpdateWin::staticMetaObject = { { &QMainWindow::staticMetaObject, qt_meta_stringdata_QUpdateWin, qt_meta_data_QUpdateWin, &staticMetaObjectExtraData } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &QUpdateWin::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *QUpdateWin::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *QUpdateWin::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_QUpdateWin)) return static_cast<void*>(const_cast< QUpdateWin*>(this)); return QMainWindow::qt_metacast(_clname); } int QUpdateWin::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QMainWindow::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 5) qt_static_metacall(this, _c, _id, _a); _id -= 5; } return _id; } // SIGNAL 0 void QUpdateWin::sigMenuAction(int _t1) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } // SIGNAL 1 void QUpdateWin::sigSetValue(qint64 _t1) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 1, _a); } QT_END_MOC_NAMESPACE
f7fb56ddc606b49d4b71bd02c7df4accd61475d5
64149532267289ea48aa65ad13fc9b040c7640f6
/Employee_Store.cpp
91f7c574eb1dc99a3c4705ff8b0cc3f4e3e921ca
[]
no_license
cianmcateer/CPP_CA2
891cfb835d01778e6d2b7f7bad434fa67586d520
54b98f274d121615852c07b2e983b29bd1d8aa8f
refs/heads/master
2021-08-29T11:12:37.746385
2017-12-13T20:50:21
2017-12-13T20:50:21
111,662,472
0
0
null
null
null
null
UTF-8
C++
false
false
15,493
cpp
#include "Employee_Store.h" Employee_Store::Employee_Store(std::string path) : employeeStore(read(path)) {} /** * Testing and backup data in case * read file fails * @author Cian McAteer * @return backup */ std::vector<Employee*> Employee_Store::load() { Office* o1 = new Office("Cian McAteer", 22, 40,"[email protected]", 1200); Office* o2 = new Office("John Smith", 27, 35, "[email protected]", 1600); Office* o3 = new Office("Matthew McCardle", 44, 38, "matthew@email", 1500); Office* o4 = new Office("Jamie Simmons", 30, 25, "[email protected]", 900); Factory* f1 = new Factory("Barry Smith", 19, 45, 420); Factory* f2 = new Factory("Michael Sweeney", 21, 30, 270); Factory* f3 = new Factory("Phil Bowlington", 18, 20, 210); Factory* f4 = new Factory("Carl Bingham", 25, 10, 400); std::vector<Employee*> backup; backup.push_back(o1); backup.push_back(f1); backup.push_back(o3); backup.push_back(f2); backup.push_back(o2); backup.push_back(f2); backup.push_back(o4); backup.push_back(f4); return backup; } inline std::vector<Employee*> Employee_Store::getEmployeeStore() const { return employeeStore; } /** * @author Ciaran Maher */ void Employee_Store::print() { std::cout << "Current number of employees: " << employeeStore.size() << "." << std::endl; for(Employee* e : employeeStore) { e->print(); } } /** * Destructor must delete heap allocated object pointers */ Employee_Store::~Employee_Store() { for(Employee* e : employeeStore) { delete e; } employeeStore.clear(); } /** * @author Cian McAteer */ void Employee_Store::add(Employee* e) { employeeStore.push_back(e); } /** * @author Cian McAteer */ bool Employee_Store::inRange(int& index) { return index < employeeStore.size(); } /** * @author Cian McAteer */ void Employee_Store::show_index() { for(unsigned int i = 0;i < employeeStore.size();++i) { std::cout << "Index: " << i << " Name: " << employeeStore[i]->getName() << "." << std::endl; } } /** * @author Cian McAteer */ void Employee_Store::erase(int& index) { employeeStore.erase(employeeStore.begin() + index); } /** * @author Cian McAteer */ void Employee_Store::clear() { employeeStore.clear(); } /*** * @author Ciaran Maher */ void Employee_Store::updateEmployee(int& employee_type) { int index; std::string search; if(employee_type == 1) { std::cout << "Factory Employees:" << std::endl; for(Employee* e : employeeStore) { if(dynamic_cast<Factory*>(e)) { e->print(); } } } else{ std::cout << "Office Employees:" << std::endl; for(Employee* e : employeeStore) { if(dynamic_cast<Office*>(e)) { e->print(); } } } std::cout << "\nEnter employee name to begin editing"<< std::endl; std::cout << "> "; std::cin.ignore(); std::getline(std::cin,search); bool menu = true; std::string newName; int newAge; int newHours; std::string newEmail; float newWage; float newSalary; while(menu) { for(unsigned int i = 0;i < employeeStore.size();++i) { if(equalsIgnoreCase(search, employeeStore[i]->getName())) { index = i; } } std::cout << "\nEdit "<< employeeStore[index]->getName()<<"'s details" <<std::endl; if(employee_type == 1) { display_file("menus/factory_edit.txt"); } else { display_file("menus/office_edit.txt"); } int menuSelect; std::cin >> menuSelect; std::cin.ignore(); switch(menuSelect) { case 1 : std::cout << "Edit name:"; std::getline(std::cin,newName); employeeStore[index]->setName(newName); std::cout << employeeStore[index]->getName() << " " << employeeStore[index]->getAge() << " " << employeeStore[index]->getHours() << std::endl; addLog("Name of employee edited on"); break; case 2 : std::cout << "Edit Age:"; std::cin >> newAge; employeeStore[index]->setAge(newAge); std::cout << employeeStore[index]->getName()<<" "<<employeeStore[index]->getAge() << " " <<employeeStore[index]->getHours() << std::endl; addLog("Age of employee edited on"); break; case 3 : std::cout << "Edit Hours:"; std::cin >> newHours; employeeStore[index]->setHours(newHours); std::cout <<employeeStore[index]->getName()<<" "<<employeeStore[index]->getAge() <<" "<<employeeStore[index]->getHours()<< std::endl; addLog("Hours of employee edited on"); break; case 4 : { if(employee_type == 1) { std::cout << "Edit Wages:"; std::cin >> newWage; Factory* f1 = dynamic_cast<Factory*>(employeeStore[index]); f1->setWage(newWage); std::cout <<employeeStore[index]->getName()<<" "<<employeeStore[index]->getAge() <<" "<<employeeStore[index]->getHours()<<" "<< f1->getWage() << std::endl; addLog("Wages edited on"); } else { std::cout << "Edit Email:"; std::getline(std::cin,newEmail); Office* off1 = dynamic_cast<Office*>(employeeStore[index]); off1->setEmail(newEmail); std::cout <<employeeStore[index]->getName()<<" "<<employeeStore[index]->getAge() <<" "<<employeeStore[index]->getHours()<<" "<< off1->getEmail()<<" "<< off1->getSalary()<< std::endl; addLog("Email of office staff edited on"); } break; } case 5 : { std::cout << "Edit Salary:"; std::cin >> newSalary; Office* off2 = dynamic_cast<Office*>(employeeStore[index]); off2->setSalary(newSalary); std::cout <<employeeStore[index]->getName()<<" "<<employeeStore[index]->getAge() <<" "<<employeeStore[index]->getHours()<< " "<<off2->getEmail()<<" "<< off2->getSalary() << std::endl; addLog("Salary of office staff edited on"); break; } case 0 : menu = false; break; } } } /** * Writes employee objects to save file * using a virtual save method * for each subclass * @author Cian McAteer * @param fileName */ void Employee_Store::save(std::string fileName) { std::ofstream employeefileWrite; employeefileWrite.open(fileName.c_str()); if(employeefileWrite.is_open()) { for(Employee* e : employeeStore) { employeefileWrite << e->save(); } } else { std::cerr << "Could not save data" << std::endl; } } /** * @author Cian McAteer */ void Employee_Store::history() { // Append students instead of overwritting students std::ofstream employeeRecords("records.txt",std::fstream::in | std::ios::out | std::ios::app); if(employeeRecords.is_open()) { for(Employee* e : employeeStore) { employeeRecords << e-> save(); } } else { std::cerr << "Records could not be accessed" << std::endl; } } /** * @author Cian McAteer */ std::set<Employee*> Employee_Store::getRecords() { std::set<Employee*> records; std::ifstream history("records.txt"); if(history.is_open()) { std::string line; std::set<std::string> lines; while(getline(history, line)) { lines.insert(line); } std::string type; std::string name; int age; int hours; float wages; std::string email; float salary; for(const std::string& line : lines) { std::stringstream ss(line); while(ss >> type) { if(type == "Factory") { while(ss >> name >> age >> hours >> wages) { std::replace(name.begin(), name.end(), '-', ' '); Employee* e = new Factory(name, age, hours, wages); records.insert(e); } } else { while(ss >> name >> age >> hours >> email >> salary) { std::replace(name.begin(), name.end(), '-', ' '); Employee* e = new Office(name, age, hours, email, salary); records.insert(e); } } } } } else { std::cerr << "Could not retrieve records from database" << std::endl; } return records; } /** * @author Cian McAteer */ void Employee_Store::show_history() { std::set<Employee*> records = getRecords(); for(Employee* e : records) { e->print(); } } /** * @author Ciaran Maher */ void Employee_Store::printEmployees(bool type) { if(type) { for(Employee* e : employeeStore) { if(dynamic_cast<Office*>(e)) { e->print(); } } } else { for(Employee* e : employeeStore) { if(dynamic_cast<Factory*>(e)) { e->print(); } } } } /** * @author Cian McAteer */ std::vector<Employee*> Employee_Store::read(std::string path) { std::ifstream data(path); std::vector<Employee*> employees; if(data.is_open()) { std::string line; std::vector<std::string> lines; while(getline(data, line)) { lines.push_back(line); } std::string type; std::string name; int age; int hours; float wages; std::string email; float salary; for(unsigned int i = 0;i < lines.size();++i) { std::stringstream ss(lines[i]); while(ss >> type) { if(type == "Factory") { while(ss >> name >> age >> hours >> wages) { std::replace(name.begin(), name.end(), '-', ' '); Employee* e = new Factory(name, age, hours, wages); employees.push_back(e); } } else { while(ss >> name >> age >> hours >> email >> salary) { std::replace(name.begin(), name.end(), '-', ' '); Employee* e = new Office(name, age, hours, email, salary); employees.push_back(e); } } } } } else { std::cerr << "Unable to open save file" << std::endl; } return employees; } /** * @author Cian McAteer */ std::stack<std::string> Employee_Store::readLog() { std::stack<std::string> logs; std::ifstream readLogs("logs.txt"); if(readLogs.is_open()) { std::string line; while(getline(readLogs, line)) { logs.push(line); } } else { std::cerr << "Error opening log file" << std::endl; } return logs; } /** * @author Ciaran Maher */ void Employee_Store::sortEmployees() { std::string search; display_file("menus/sort_menu.txt"); std::cin.ignore(); std::getline(std::cin,search); std::cout << std::endl; if(search == "name"){ sort(employeeStore.begin(), employeeStore.end(), [](const Employee* e1, const Employee* e2){ return e1->getName() < e2->getName(); }); } if(search == "age"){ sort(employeeStore.begin(), employeeStore.end(), [](const Employee* e1, const Employee* e2){ return e1->getAge() < e2->getAge(); }); } if(search == "hours"){ sort(employeeStore.begin(), employeeStore.end(), [](const Employee* e1, const Employee* e2){ return e1->getHours() < e2->getHours(); }); } print(); } /** * @author Ciaran Maher */ void Employee_Store::createWebpage() { std::ofstream html_page("worker_catalogue.html"); // HTML header tags html_page << "<!DOCTYPE html><html><head>"; // Header tags html_page << "<link href=\"worker_page.css\" rel=\"stylesheet\">"; // Style sheet link html_page << "</head><body>"; html_page << "<h1></h1>"; html_page << "<img>"; html_page << "<table border='1'>"; html_page << "<h2>Office Workers</h2>"; html_page << "<tr><td class='title'>Name</td><td class='title'>Age</td><td class='title'>Hours</td><td class='title'>Email</td><td class='title'>Salary</td></tr>"; for(Employee* e : employeeStore) { if(dynamic_cast<Office*>(e)){ Office* o = dynamic_cast<Office*>(e); html_page << "<tr>"; html_page << "<td>" << e->getName() << "</td>"; // Converts to HTML string html_page << "<td>" << e->getAge() << "</td>"; // Converts to HTML string html_page << "<td>" << e->getHours() << "</td>"; // Converts to HTML string html_page << "<td>" << o->getEmail() << "</td>"; // Converts to HTML string html_page << "<td>" << o->getSalary() << "</td>"; // Converts to HTML string } html_page << "</tr>"; } html_page << "</table>"; html_page << "<table border='1'>"; html_page << "<h2>Factory Workers</h2>"; html_page << "<tr><td class='title'>Name</td><td class='title'>Age</td><td class='title'>Hours</td><td class='title'>Wages</td></tr>"; for(Employee* e : employeeStore) { if(dynamic_cast<Factory*>(e)) { Factory* f = dynamic_cast<Factory*>(e); html_page << "<tr>"; html_page << "<td>" << e->getName() << "</td>"; // Converts to HTML string html_page << "<td>" << e->getAge() << "</td>"; // Converts to HTML string html_page << "<td>" << e->getHours() << "</td>"; // Converts to HTML string html_page << "<td>" << f->getWage() << "</td>"; // Converts to HTML string } html_page << "</tr>"; } html_page << "</table>"; // Close off page and end connection html_page << "</body></html>"; html_page.close(); } /** * @author Cian McAteer */ void Employee_Store::displayLogs() { std::stack<std::string> logs = readLog(); std::cout << "Log size " << logs.size() << std::endl; while(!logs.empty()) { // Print last element added to stack std::cout << logs.top() << std::endl; logs.pop(); // Pop element off to print next element } } float Employee_Store::averagePayment() { std::vector<float> payments; for(Employee* e : employeeStore) { if(dynamic_cast<Factory*>(e)) { Factory* f = dynamic_cast<Factory*>(e); payments.push_back(f->getWage()); } else { Office* o = dynamic_cast<Office*>(e); payments.push_back(o->getSalary()); } } return average(payments); } float Employee_Store::averageHours() { std::vector<int> hours; for(Employee* e : employeeStore) { hours.push_back(e->getHours()); } return average(hours); } /** * Displays all employees by catagory by inserting them into a map * @author Cian McAteer */ std::ostream& operator<<(std::ostream& output_stream, const Employee_Store& et) { std::map<std::string,std::vector<Employee*> > map; std::vector<Employee*> office_staff; std::vector<Employee*> factory_workers; for(Employee* e : et.employeeStore) { if(dynamic_cast<Office*>(e)) { office_staff.push_back(e); } else { factory_workers.push_back(e); } } map.insert(std::pair<std::string, std::vector<Employee*> >("Office", office_staff)); map.insert(std::pair<std::string, std::vector<Employee*> >("Factory", factory_workers)); for(const auto& s : map) { output_stream << " Number of " << s.first << " employees: " << s.second.size() << std::endl; for(Employee* e : s.second) { output_stream << '\t' << e->toString() << std::endl; } } return output_stream; }
ef780200ac313e1499983ebec9abb6db23014c9e
e32b348ad5c87eab6600be4ffb659e66032b9008
/0004. Median of Two Sorted Arrays.cpp
b8ba84745bceefc53ecda892f0a05d417eca590c
[]
no_license
joyjwlee/LeetCode
889abe907cf5a6a360f1a4f2b0538b8f5dff9758
c944fe374998a98e221244245173da64213a681f
refs/heads/master
2021-08-18T07:43:10.155761
2021-07-05T04:32:44
2021-07-05T04:32:44
241,488,117
1
0
null
null
null
null
UTF-8
C++
false
false
490
cpp
class Solution { public: double findMedianSortedArrays(vector<int> &nums1, vector<int> &nums2) { // combine the vectors and sort nums1.insert(nums1.end(), nums2.begin(), nums2.end()); sort(nums1.begin(), nums1.end()); // if odd size if (nums1.size() % 2 != 0) return nums1[nums1.size() / 2]; // otherwise return avg of middle 2 return (nums1[(nums1.size() - 1) / 2] + nums1[(nums1.size() + 1) / 2]) / 2.00; } };
a8d5ec29cde273cb953ba0f098b1736c7929e86e
d9142bdff80cad8a1bf5a138f55c442a04e2674d
/1939.cpp
80d3fc33749ebc24fe316ff286bbf17f1bc6b417
[]
no_license
epicurean21/Algorithm
280a84d5f73db7787eb2589a3a37901983496691
d5fa2f0318d45bdd17c5ccda9e72468b4711100c
refs/heads/master
2023-07-22T05:30:47.982546
2023-07-09T06:22:09
2023-07-09T06:22:09
199,615,976
3
0
null
null
null
null
UTF-8
C++
false
false
1,170
cpp
#include <iostream> #include <vector> #include <cstring> using namespace std; #define MAX 100001 #define INF 1000000000 int N, M, a, b, w, start_point, end_point, ans; bool visited[MAX]; vector<vector<pair<int, int>>> map(MAX); bool dfs(int cur, int w) { visited[cur] = true; if(cur == end_point) return true; for (auto n : map[cur]) { int next = n.first; int weight = n.second; if (!visited[next] && w <= weight) { if(!dfs(next, weight)) continue; else return true; } } return false; } int main() { ios::sync_with_stdio(false); cin.tie(NULL); cin >> N >> M; for (int i = 0; i < M; i++) { cin >> a >> b >> w; map[a].push_back({b, w}); map[b].push_back({a, w}); } cin >> start_point >> end_point; int left = 0; int right = INF; while (left <= right) { int m = (left + right) / 2; if (dfs(start_point, m)) { ans = m; left = m + 1; } else right = m - 1; memset(visited, false, sizeof(visited)); } cout << ans << "\n"; return 0; }
c24d5fc0eb16c16a6a35d9cf2c3c83ddd57da9e9
8dc84558f0058d90dfc4955e905dab1b22d12c08
/third_party/blink/renderer/core/css/cssom/css_scale.h
76bcf7736e6497dca3e3807950c06a2d3f4e2b41
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause", "LGPL-2.0-only", "BSD-2-Clause", "LGPL-2.1-only" ]
permissive
meniossin/src
42a95cc6c4a9c71d43d62bc4311224ca1fd61e03
44f73f7e76119e5ab415d4593ac66485e65d700a
refs/heads/master
2022-12-16T20:17:03.747113
2020-09-03T10:43:12
2020-09-03T10:43:12
263,710,168
1
0
BSD-3-Clause
2020-05-13T18:20:09
2020-05-13T18:20:08
null
UTF-8
C++
false
false
2,727
h
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSSOM_CSS_SCALE_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSSOM_CSS_SCALE_H_ #include "base/macros.h" #include "third_party/blink/renderer/core/css/cssom/css_transform_component.h" #include "third_party/blink/renderer/core/css/cssom/css_unit_value.h" #include "third_party/blink/renderer/core/geometry/dom_matrix.h" namespace blink { class CSSNumericValue; class DOMMatrix; // Represents a scale value in a CSSTransformValue used for properties like // "transform". // See CSSScale.idl for more information about this class. class CORE_EXPORT CSSScale final : public CSSTransformComponent { DEFINE_WRAPPERTYPEINFO(); public: // Constructors defined in the IDL. static CSSScale* Create(const CSSNumberish&, const CSSNumberish&, ExceptionState&); static CSSScale* Create(const CSSNumberish&, const CSSNumberish&, const CSSNumberish&, ExceptionState&); // Blink-internal ways of creating CSSScales. static CSSScale* Create(CSSNumericValue* x, CSSNumericValue* y) { return new CSSScale(x, y, CSSUnitValue::Create(1), true /* is2D */); } static CSSScale* Create(CSSNumericValue* x, CSSNumericValue* y, CSSNumericValue* z) { return new CSSScale(x, y, z, false /* is2D */); } static CSSScale* FromCSSValue(const CSSFunctionValue&); // Getters and setters for attributes defined in the IDL. void x(CSSNumberish& x) { x.SetCSSNumericValue(x_); } void y(CSSNumberish& y) { y.SetCSSNumericValue(y_); } void z(CSSNumberish& z) { z.SetCSSNumericValue(z_); } void setX(const CSSNumberish&, ExceptionState&); void setY(const CSSNumberish&, ExceptionState&); void setZ(const CSSNumberish&, ExceptionState&); DOMMatrix* toMatrix(ExceptionState&) const final; // Internal methods - from CSSTransformComponent. TransformComponentType GetType() const final { return kScaleType; } const CSSFunctionValue* ToCSSValue() const final; void Trace(blink::Visitor* visitor) override { visitor->Trace(x_); visitor->Trace(y_); visitor->Trace(z_); CSSTransformComponent::Trace(visitor); } private: CSSScale(CSSNumericValue* x, CSSNumericValue* y, CSSNumericValue* z, bool is2D); Member<CSSNumericValue> x_; Member<CSSNumericValue> y_; Member<CSSNumericValue> z_; DISALLOW_COPY_AND_ASSIGN(CSSScale); }; } // namespace blink #endif
d54c10d55cea79289b0a8c60a333500071679808
a78ad1040cd9757437c591bb5dad4fb8347bc8fc
/nik/sources/kernel/lib/logic/LogicCooling.cpp
c540553cbde45ba85a0cc33e73caf4045a50c25d
[]
no_license
imptz/Uso
4e1488f94997c71cbc1a006ddc974e356767be8a
55caaf5af59c6e1872e91c8d3b16d999ffbe25c9
refs/heads/master
2020-03-26T15:30:23.469236
2014-08-13T05:16:41
2014-08-13T05:16:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,137
cpp
#include "LogicCooling.h" #include "../DEBUG/serialDebug.h" #include "../extension/subsystems/monitoring/monitoringSubsystem.h" const char* LogicCooling::CONFIRMATION_TEXT = LOCAL_CONFIRMATION_USO_LOGIC_COOLING_TEXT; const char* LogicCooling::CANCEL_LOG_TEXT = LOCAL_LOGIC_COOLING_CANCEL_LOG_TEXT; const char* LogicCooling::START_LOG_TEXT = LOCAL_LOGIC_COOLING_START_LOG_TEXT; const char* LogicCooling::FINISH_LOG_TEXT = LOCAL_LOGIC_COOLING_FINISH_LOG_TEXT; const char* LogicCooling::LOG_FAULT_TEXT = LOCAL_LOGIC_COOLING_LOG_FAULT_TEXT; bool ffll = false; LogicCooling::LogicCooling(MessageReceiver* _messageReceiver) : Logic(), phase(PHASE_INPUT_CONTROL) { addReceiver(_messageReceiver); dialogText = const_cast<char*>(CONFIRMATION_TEXT); cancelLogText = const_cast<char*>(CANCEL_LOG_TEXT); startLogText = const_cast<char*>(START_LOG_TEXT); } LogicCooling::~LogicCooling() { } void LogicCooling::onMessage(Message message) { switch (message.msg) { case MainConfirmation::CONFIRMATION_MESSAGE_RESULT: // M061112 timeOutWaiting = TIME_OUT_WAITING_UNDEFINED; // M061112E if (message.par1 == MainConfirmation::CONFIRMATION_RESULT_YES) { if (start()) { Log::getSingleton().add(LOG_MESSAGE_FROM_LOGIC, LOG_MESSAGE_TYPE_INFO, startLogText, START_ACTOR_HALF_AUTO, initSignal); MonitoringSubsystem::getSingleton().createAndSendMessage(IMonitoringDevice::MESSAGE_NUMBER_START_OROSHENIA, START_ACTOR_HALF_AUTO, initSignal); } } else { stop(); MonitoringSubsystem::getSingleton().createAndSendMessage(IMonitoringDevice::MESSAGE_NUMBER_OTMENA_SIGNALA_O_VOZGORANII, 0, initSignal); Log::getSingleton().add(LOG_MESSAGE_FROM_LOGIC, LOG_MESSAGE_TYPE_INFO, cancelLogText, 0, initSignal); } break; case MainFinish::FINISH_MESSAGE_RESULT: finish(FINISH_ACTOR_BUTTON); break; } } bool LogicCooling::start() { if (listProgramIndexCount != 0) { if (phaseStopProgram_Start()) { sendMessage(Message(MESSAGE_FROM_OFFSET_LOGIC, LOGIC_MESSAGE_GET_FINISH, 0, 0)); IOSubsystem::getSingleton().enableAllFireAlarmOutputs(); IOSubsystem::getSingleton().enableAllHardwareOutputs(); phase = PHASE_STOP_PROGRAM; pumpOutputEnable = false; return true; } else { stop(); return false; } } else { stop(); return false; } } void LogicCooling::stop(bool msg, bool resetPozhSig) { timeOutBeforeStart = -1; finishTimer = -1; SAFE_DELETE_ARRAY(listProgramIndex) listProgramIndexCount = 0; setInitSignalIgnorable(initSignal, true); sendMessage(Message(MESSAGE_FROM_OFFSET_LOGIC, MainTabControl::MAIN_TAB_MESSAGE_SET_MAIN_TAB, 0, 0)); if (msg) { Log::getSingleton().add(LOG_MESSAGE_FROM_LOGIC, LOG_MESSAGE_TYPE_INFO, const_cast<char*>(FINISH_LOG_TEXT), finishActor, 0); MonitoringSubsystem::getSingleton().createAndSendMessage(IMonitoringDevice::MESSAGE_NUMBER_STOP_POISKA_OROSHENIA, finishActor, 0); } if (actionCount != 0) { for (unsigned int i = 0; i < actionCount; i++) SAFE_DELETE(actionList[i]) } actionCount = 0; SAFE_DELETE_ARRAY(actionList) UI::getSingleton().getUsoModeControl()->unLock(); phase = PHASE_INPUT_CONTROL; } void LogicCooling::action() { for (unsigned int i = 0; i < actionCount; i++) if (actionList[i] != nullptr) actionList[i]->step(); switch (phase) { case PHASE_INPUT_CONTROL: initSignal = getActiveInitialSignal(LOGIC_FUNCTION_COOLING_POINT, LOGIC_FUNCTION_COOLING_LINE); if (initSignal != -1) { if (!UI::getSingleton().getUsoModeControl()->isInTools()) { phase = PHASE_INPUT_WAITING_CONTROL; timeOutBeforeStart = Config::getSingleton().getConfigData()->getConfigDataStructConst()->timeOutBeforeStart; } } break; case PHASE_INPUT_WAITING_CONTROL: if (timeOutBeforeStart == 0) { timeOutBeforeStart = -1; if (testInitSignal(initSignal)) { MonitoringSubsystem::getSingleton().createAndSendMessage(IMonitoringDevice::MESSAGE_NUMBER_SIGNAL_O_VOZGORANII, 0, initSignal); phase = PHASE_INPUT_ACTION; } else { initSignal = -1; phase = PHASE_INPUT_CONTROL; } } break; case PHASE_INPUT_ACTION: if (UI::getSingleton().getUsoModeControl()->getMode() == UsoModeControl::USO_MODE_HALF_AUTO) { sendMessage(Message(MESSAGE_FROM_OFFSET_LOGIC, LOGIC_MESSAGE_GET_CONFIRMATION, reinterpret_cast<unsigned int>(dialogText), 0)); // M061112 startWaitingConf(); //phase = PHASE_WAITING_CONFIRMATION; // M061112E return; } else if (UI::getSingleton().getUsoModeControl()->getMode() == UsoModeControl::USO_MODE_FULL_AUTO) { if (start()) { Log::getSingleton().add(LOG_MESSAGE_FROM_LOGIC, LOG_MESSAGE_TYPE_INFO, startLogText, START_ACTOR_FULL_AUTO, initSignal); MonitoringSubsystem::getSingleton().createAndSendMessage(IMonitoringDevice::MESSAGE_NUMBER_START_OROSHENIA, START_ACTOR_FULL_AUTO, initSignal); } return; } break; // M061112 case PHASE_WAITING_CONFIRMATION: if (timeOutWaiting == 0) { DEBUG_PUT_METHOD("PHASE_WAITING_CONFIRMATION ... timeOutWaiting == 0\n"); timeOutWaiting = TIME_OUT_WAITING_UNDEFINED; // M13112012 // UI::getSingleton().getUsoModeControl()->setMode(UsoModeControl::USO_MODE_FULL_AUTO, UsoModeControl::USO_MODE_CONTROL_ACTOR_TIME_OUT, true); // M13112012E UI::getSingleton().getMainTabControl()->activateMainTab(); if (start()) { Log::getSingleton().add(LOG_MESSAGE_FROM_LOGIC, LOG_MESSAGE_TYPE_INFO, startLogText, START_ACTOR_FULL_AUTO, initSignal); MonitoringSubsystem::getSingleton().createAndSendMessage(IMonitoringDevice::MESSAGE_NUMBER_START_OROSHENIA, START_ACTOR_FULL_AUTO, initSignal); } } break; // M061112E case PHASE_STOP_PROGRAM: if (phaseStopProgram_Execution()) { phaseStartProgram_Start(); phase = PHASE_START_PROGRAM; } break; case PHASE_START_PROGRAM: if (phaseStartProgram_Execution()) { if (testTotalError()) { stop(); Log::getSingleton().add(LOG_MESSAGE_FROM_LOGIC, LOG_MESSAGE_TYPE_INFO, const_cast<char*>(LOG_FAULT_TEXT), finishActor, 0); } else { //stop(); //Log::getSingleton().add(LOG_MESSAGE_FROM_LOGIC, LOG_MESSAGE_TYPE_INFO, const_cast<char*>(LOG_FAULT_TEXT), finishActor, 13); phaseGateOpen_Start(); phase = PHASE_OPEN_GATE; } } break; case PHASE_OPEN_GATE: if (phaseGateOpen_Execution()) { phaseWaitingStop_Start(); phase = PHASE_WAITING_STOP; } break; case PHASE_WAITING_STOP: if (phaseWaitingStop_Execution()) { phaseGateClose_Start(); phase = PHASE_CLOSE_GATE; } break; case PHASE_CLOSE_GATE: if (phaseGateClose_Execution()) { phase = PHASE_STOP_PROGRAM_END; phaseStopProgramEnd_Start(); } break; case PHASE_STOP_PROGRAM_END: if (phaseStopProgramEnd_Execution()) { stop(true); } break; } } void LogicCooling::finish(FINISH_ACTOR _finishActor) { _asm cli if (phase == PHASE_WAITING_STOP) { finishTimer = -1; phase = PHASE_CLOSE_GATE; finishActor = _finishActor; sendMessage(Message(MESSAGE_FROM_OFFSET_LOGIC, MainFinish::FINISH_MESSAGE_LABEL, MainFinish::FINISH_MESSAGE_PARAM_FINISH, 0)); _asm sti phaseGateClose_Start(); } _asm sti } bool LogicCooling::phaseStopProgram_Start() { actionCount = listProgramIndexCount; actionList = new Action*[actionCount]; ConfigDataStructProgram** sp = Config::getSingleton().getConfigData()->getConfigDataStructPrograms(); for (unsigned int i = 0; i < actionCount; i++) { actionList[i] = new ActionStopProgramScan(Config::getSingleton().getConfigData()->getPRAddressByNumber(sp[listProgramIndex[i]]->prNumber)); } return true; } bool LogicCooling::phaseStopProgram_Execution() { for (unsigned int i = 0; i < actionCount; i++) if (actionList[i]->getState() == Action::STATE_UNDEFINED) return false; for (unsigned int i = 0; i < actionCount; i++) switch (actionList[i]->getState()) { case Action::STATE_ERROR: break; case Action::STATE_READY: break; } return true; } bool LogicCooling::phaseStartProgram_Start() { ConfigDataStructProgram** sp = Config::getSingleton().getConfigData()->getConfigDataStructPrograms(); for (unsigned int i = 0; i < actionCount; i++) { if (actionList[i] != nullptr) delete actionList[i]; unsigned char addr = Config::getSingleton().getConfigData()->getPRAddressByNumber(sp[listProgramIndex[i]]->prNumber); switch (sp[listProgramIndex[i]]->function) { case LOGIC_FUNCTION_COOLING_LINE: actionList[i] = new ActionStartProgramScanLine(sp[listProgramIndex[i]]->point1, sp[listProgramIndex[i]]->point2, sp[listProgramIndex[i]]->nasadok, SCAN_PROGRAM_BALLISTICS_OFF, addr); break; case LOGIC_FUNCTION_COOLING_POINT: actionList[i] = new ActionStartProgramScanPoint(sp[listProgramIndex[i]]->nPointProgram, addr); break; } } return true; } bool LogicCooling::phaseStartProgram_Execution() { for (unsigned int i = 0; i < actionCount; i++) if (actionList[i]->getState() == Action::STATE_UNDEFINED) return false; unsigned int _actionCount = actionCount; for (unsigned int i = 0; i < _actionCount; i++) { switch (actionList[i]->getState()) { case Action::STATE_ERROR: deleteActionInList(i); break; case Action::STATE_READY: break; } } return true; } bool LogicCooling::phaseGateOpen_Start() { for (unsigned int i = 0; i < actionCount; i++) { unsigned char deviceAddress; if (actionList[i] != nullptr) { deviceAddress = actionList[i]->getDeviceAddress(); delete actionList[i]; } actionList[i] = new ActionGateOpen(deviceAddress); } return true; } bool LogicCooling::phaseGateOpen_Execution() { bool isUndefined = false; for (unsigned int i = 0; i < actionCount; i++) { switch (actionList[i]->getState()) { case Action::STATE_UNDEFINED: isUndefined = true; break; case Action::STATE_READY: if (!pumpOutputEnable) { pumpOutputEnable = true; IOSubsystem::getSingleton().enableAllPumpStationOutputs(); } break; } } if (isUndefined) return false; unsigned int _actionCount = actionCount; for (unsigned int i = 0; i < _actionCount; i++) { switch (actionList[i]->getState()) { case Action::STATE_ERROR: //deleteActionInList(i); break; case Action::STATE_READY: break; } } return true; } bool LogicCooling::phaseWaitingStop_Start() { sendMessage(Message(MESSAGE_FROM_OFFSET_LOGIC, MainFinish::FINISH_MESSAGE_LABEL, MainFinish::FINISH_MESSAGE_PARAM_START, 0)); return true; } bool LogicCooling::phaseWaitingStop_Execution() { if (UI::getSingleton().getUsoModeControl()->getMode() == UsoModeControl::USO_MODE_FULL_AUTO) { if (!testInitSignal(initSignal)) { if (finishTimer == -1) finishTimer = Config::getSingleton().getConfigData()->getConfigDataStructConst()->timeOutBeforeFinish; } } return false; } bool LogicCooling::phaseGateClose_Start() { IOSubsystem::getSingleton().disableAllFireAlarmOutputs(); IOSubsystem::getSingleton().disableAllHardwareOutputs(); IOSubsystem::getSingleton().disableAllPumpStationOutputs(); ConfigDataStructProgram** sp = Config::getSingleton().getConfigData()->getConfigDataStructPrograms(); for (unsigned int i = 0; i < actionCount; i++) { if (actionList[i] != nullptr) delete actionList[i]; } actionCount = listProgramIndexCount; for (unsigned int i = 0; i < actionCount; i++) { unsigned char addr = Config::getSingleton().getConfigData()->getPRAddressByNumber(sp[listProgramIndex[i]]->prNumber); actionList[i] = new ActionGateClose(addr); } return true; } bool LogicCooling::phaseGateClose_Execution() { for (unsigned int i = 0; i < actionCount; i++) if (actionList[i]->getState() == Action::STATE_UNDEFINED) return false; for (unsigned int i = 0; i < actionCount; i++) switch (actionList[i]->getState()) { case Action::STATE_ERROR: break; case Action::STATE_READY: break; } return true; } bool LogicCooling::phaseStopProgramEnd_Start() { ConfigDataStructProgram** sp = Config::getSingleton().getConfigData()->getConfigDataStructPrograms(); for (unsigned int i = 0; i < actionCount; i++) { if (actionList[i] != nullptr) delete actionList[i]; } actionCount = listProgramIndexCount; for (unsigned int i = 0; i < actionCount; i++) { unsigned char addr = Config::getSingleton().getConfigData()->getPRAddressByNumber(sp[listProgramIndex[i]]->prNumber); actionList[i] = new ActionStopProgramScan(addr); } return true; } bool LogicCooling::phaseStopProgramEnd_Execution() { for (unsigned int i = 0; i < actionCount; i++) if (actionList[i]->getState() == Action::STATE_UNDEFINED) return false; for (unsigned int i = 0; i < actionCount; i++) { if (actionList[i] == nullptr) break; switch (actionList[i]->getState()) { case Action::STATE_ERROR: break; case Action::STATE_READY: break; } } return true; } // M061112 void LogicCooling::startWaitingConf() { timeOutWaiting = getConfigTimeOutWaiting(); phase = PHASE_WAITING_CONFIRMATION; } // M061112E
807b6c3c2489679e35df18d0d42d06f3eacf5027
a1344869f50d5c9515fb532bd0a2a90f2f7c9f72
/Joystick/Joystick.cpp
9a58e029370511de07117c3c40fd8c7b8b4efd0c
[]
no_license
ipewzner/Joystick
925df65da30a30efdeb8d4c8c301f4894c62a434
cb9589efc79d41910a2d93b7064f97a518d165ed
refs/heads/master
2023-08-04T22:13:43.716336
2021-09-29T11:46:17
2021-09-29T11:46:17
411,644,252
0
0
null
null
null
null
UTF-8
C++
false
false
2,534
cpp
#include "Joystick.h" Joystick::Joystick() { for (size_t i = 0; i < 3; i++) { max[i] = -1500; min[i] = 1500; } } void Joystick::sendJoyReport() { Serial.write((uint8_t*)&report, sizeof(joyReport_t)); } void Joystick::setButton(uint8_t button) { uint8_t index = button / 8; uint8_t bit = button - 8 * index; this->report.button[index] |= 1 << bit; } void Joystick::clearButton(uint8_t button) { uint8_t index = button / 8; uint8_t bit = button - 8 * index; this->report.button[index] &= ~(1 << bit); } void Joystick::clearAllButtons() { for (int button = 0; button < 8; button++) { clearButton(button); } } void Joystick::readButtons() { clearAllButtons(); int button = 0; bool b1 = !digitalRead(BUTTON_PIN_1); bool b2 = !digitalRead(BUTTON_PIN_2); bool b3 = !digitalRead(BUTTON_PIN_3); bool b4 = !digitalRead(BUTTON_PIN_4); //Button 5-8 if (b1 && b2) { button = 5; if (b3)button += 2; if (b4)button += 1; } //Button 1-4 else { b1 ? button = 1 : 0; b2 ? button = 2 : 0; b3 ? button = 3 : 0; b4 ? button = 4 : 0; } if (button > 0) setButton(button - 1); } int16_t Joystick::calibration(int16_t in, int axis) { float axisValue; //percentag of axis //Adjest the opretion range if (in > max[axis]) max[axis] = in; if (in < min[axis]) min[axis] = in; if (axis == THROTTLE) { axisValue = delta(in, min[axis]) / stepSize(max[axis], min[axis]); //0-100% if (axisValue < SENSITIVITY) axisValue = 0; return (int16_t)(MIN + axisValue * RANGE * 2); } else { middle[axis] = delta(max[axis], min[axis]) / 2 + min[axis]; // The division is due to the change in the behavior of the axis if (in > middle[axis]) { axisValue = delta(in, middle[axis]) / stepSize(max[axis], middle[axis]); if (axisValue < SENSITIVITY) axisValue = 0; } else if (in < middle[axis]) { axisValue = delta(in, middle[axis]) / stepSize(middle[axis], min[axis]); if (axisValue > -SENSITIVITY) axisValue = 0; } //Turn step to linear data return (int16_t)(axisValue * RANGE); } return (int16_t) 0; } void Joystick::readAxis() { int16_t axis[] = { analogRead(AXIS_PIN_1), analogRead(AXIS_PIN_2), analogRead(AXIS_PIN_3) }; for (size_t i = 0; i < 3; i++) { this->report.axis[i] = -calibration(axis[i], i); this->report.axis[i] = constrain(this->report.axis[i], MIN, MAX); } } float Joystick::stepSize(int16_t big, int16_t small) { return (float)(big - small) / 100; } float Joystick::delta(int16_t big, int16_t small) { return big - small; }
f337c604611b2bdda26cc9cac5f16e62c4b1d1b2
b401c03dba939316419dcd52006ba669bb35c432
/4thSemesterActivities/Project/beagleKombat.cpp
c738b57645fc9341d30669e896815b026bcd5079
[]
no_license
memo-saldana/C-small-projects
46deab93db191a59a33617b6464b36411ff3982c
aa03f0539f7c089a28b0def920d8dccb4b3e1e25
refs/heads/master
2021-06-08T11:43:39.142435
2019-12-19T02:00:48
2019-12-19T02:00:48
110,714,520
3
2
null
2019-02-20T16:50:36
2017-11-14T16:18:23
C++
UTF-8
C++
false
false
846
cpp
#include <iostream> #include <queue> #include <vector> #include <string> using namespace std; int main() { vector<int> values; int l, k, data, result=0; string keys; char prev; cin>> l >> k; for(int i = 0; i < l; i++) { cin>>data; values.push_back(data); } cin>>keys; prev = keys[0]; priority_queue<int> current; current.push(values[0]); for(int i = 1; i < l; i++) { if(keys[i]==prev){ current.push(values[i]); } else { for(int j = 0; j < k && !current.empty(); j++) { result+=current.top(); current.pop(); } current = priority_queue<int>(); prev = keys[i]; current.push(values[i]); } } for(int j = 0; j < k && !current.empty(); j++) { result+=current.top(); current.pop(); } cout<<result<<endl; return 0; }
e0bdb7c7a0d85bb922e0f546153e3006c440225c
43a8e7435ce1cb38a7bb07b3cd7400c69da05345
/src/XY_LIB/charuco.hpp
6e37916b38f42434f506f15dba994e5be0b32020
[]
no_license
zhanglei8411/DemoFlight
01d116b01cc123a480296c465021fc31fae22555
4a9f5d0dd66c286275857fe1b6366730517055a0
refs/heads/master
2021-01-10T01:44:11.775239
2016-03-29T06:41:56
2016-03-29T06:41:56
48,409,681
1
2
null
2016-03-05T15:03:09
2015-12-22T04:08:55
C++
UTF-8
C++
false
false
14,982
hpp
/* By downloading, copying, installing or using the software you agree to this license. If you do not agree to this license, do not download, install, copy or use the software. License Agreement For Open Source Computer Vision Library (3-clause BSD License) Copyright (C) 2013, OpenCV Foundation, all rights reserved. Third party copyrights are property of their respective owners. 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 names of the copyright holders nor the names of the 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 copyright holders 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 __OPENCV_CHARUCO_HPP__ #define __OPENCV_CHARUCO_HPP__ #include <opencv2/core/core.hpp> #include <vector> #include "aruco.hpp" namespace xyVision { namespace aruco { //! @addtogroup aruco //! @{ /** * @brief ChArUco board * Specific class for ChArUco boards. A ChArUco board is a planar board where the markers are placed * inside the white squares of a chessboard. The benefits of ChArUco boards is that they provide * both, ArUco markers versatility and chessboard corner precision, which is important for * calibration and pose estimation. * This class also allows the easy creation and drawing of ChArUco boards. */ class CharucoBoard : public Board { public: // vector of chessboard 3D corners precalculated std::vector< Point3f > chessboardCorners; // for each charuco corner, nearest marker id and nearest marker corner id of each marker std::vector< std::vector< int > > nearestMarkerIdx; std::vector< std::vector< int > > nearestMarkerCorners; /** * @brief Draw a ChArUco board * * @param outSize size of the output image in pixels. * @param img output image with the board. The size of this image will be outSize * and the board will be on the center, keeping the board proportions. * @param marginSize minimum margins (in pixels) of the board in the output image * @param borderBits width of the marker borders. * * This function return the image of the ChArUco board, ready to be printed. */ void draw(Size outSize, OutputArray img, int marginSize = 0, int borderBits = 1); /** * @brief Create a CharucoBoard object * * @param squaresX number of chessboard squares in X direction * @param squaresY number of chessboard squares in Y direction * @param squareLength chessboard square side length (normally in meters) * @param markerLength marker side length (same unit than squareLength) * @param dictionary dictionary of markers indicating the type of markers. * The first markers in the dictionary are used to fill the white chessboard squares. * @return the output CharucoBoard object * * This functions creates a CharucoBoard object given the number of squares in each direction * and the size of the markers and chessboard squares. */ static CharucoBoard create(int squaresX, int squaresY, float squareLength, float markerLength, Dictionary dictionary); /** * */ Size getChessboardSize() const { return Size(_squaresX, _squaresY); } /** * */ float getSquareLength() const { return _squareLength; } /** * */ float getMarkerLength() const { return _markerLength; } private: void _getNearestMarkerCorners(); // number of markers in X and Y directions int _squaresX, _squaresY; // size of chessboard squares side (normally in meters) float _squareLength; // marker side lenght (normally in meters) float _markerLength; }; /** * @brief Interpolate position of ChArUco board corners * @param markerCorners vector of already detected markers corners. For each marker, its four * corners are provided, (e.g std::vector<std::vector<cv::Point2f> > ). For N detected markers, the * dimensions of this array should be Nx4. The order of the corners should be clockwise. * @param markerIds list of identifiers for each marker in corners * @param image input image necesary for corner refinement. Note that markers are not detected and * should be sent in corners and ids parameters. * @param board layout of ChArUco board. * @param charucoCorners interpolated chessboard corners * @param charucoIds interpolated chessboard corners identifiers * @param cameraMatrix optional 3x3 floating-point camera matrix * \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ * @param distCoeffs optional vector of distortion coefficients * \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6],[s_1, s_2, s_3, s_4]])\f$ of 4, 5, 8 or 12 elements * * This function receives the detected markers and returns the 2D position of the chessboard corners * from a ChArUco board using the detected Aruco markers. If camera parameters are provided, * the process is based in an approximated pose estimation, else it is based on local homography. * Only visible corners are returned. For each corner, its corresponding identifier is * also returned in charucoIds. * The function returns the number of interpolated corners. */ int interpolateCornersCharuco(InputArrayOfArrays markerCorners, InputArray markerIds, InputArray image, const CharucoBoard &board, OutputArray charucoCorners, OutputArray charucoIds, InputArray cameraMatrix = noArray(), InputArray distCoeffs = noArray()); /** * @brief Pose estimation for a ChArUco board given some of their corners * @param charucoCorners vector of detected charuco corners * @param charucoIds list of identifiers for each corner in charucoCorners * @param board layout of ChArUco board. * @param cameraMatrix input 3x3 floating-point camera matrix * \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ * @param distCoeffs vector of distortion coefficients * \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6],[s_1, s_2, s_3, s_4]])\f$ of 4, 5, 8 or 12 elements * @param rvec Output vector (e.g. cv::Mat) corresponding to the rotation vector of the board * (@sa Rodrigues). * @param tvec Output vector (e.g. cv::Mat) corresponding to the translation vector of the board. * * This function estimates a Charuco board pose from some detected corners. * The function checks if the input corners are enough and valid to perform pose estimation. * If pose estimation is valid, returns true, else returns false. */ bool estimatePoseCharucoBoard(InputArray charucoCorners, InputArray charucoIds, CharucoBoard &board, InputArray cameraMatrix, InputArray distCoeffs, OutputArray rvec, OutputArray tvec); /** * @brief Draws a set of Charuco corners * @param image input/output image. It must have 1 or 3 channels. The number of channels is not * altered. * @param charucoCorners vector of detected charuco corners * @param charucoIds list of identifiers for each corner in charucoCorners * @param cornerColor color of the square surrounding each corner * * This function draws a set of detected Charuco corners. If identifiers vector is provided, it also * draws the id of each corner. */ void drawDetectedCornersCharuco(InputOutputArray image, InputArray charucoCorners, InputArray charucoIds = noArray(), Scalar cornerColor = Scalar(255, 0, 0)); /** * @brief Calibrate a camera using Charuco corners * * @param charucoCorners vector of detected charuco corners per frame * @param charucoIds list of identifiers for each corner in charucoCorners per frame * @param board Marker Board layout * @param imageSize input image size * @param cameraMatrix Output 3x3 floating-point camera matrix * \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . If CV\_CALIB\_USE\_INTRINSIC\_GUESS * and/or CV_CALIB_FIX_ASPECT_RATIO are specified, some or all of fx, fy, cx, cy must be * initialized before calling the function. * @param distCoeffs Output vector of distortion coefficients * \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6],[s_1, s_2, s_3, s_4]])\f$ of 4, 5, 8 or 12 elements * @param rvecs Output vector of rotation vectors (see Rodrigues ) estimated for each board view * (e.g. std::vector<cv::Mat>>). That is, each k-th rotation vector together with the corresponding * k-th translation vector (see the next output parameter description) brings the board pattern * from the model coordinate space (in which object points are specified) to the world coordinate * space, that is, a real position of the board pattern in the k-th pattern view (k=0.. *M* -1). * @param tvecs Output vector of translation vectors estimated for each pattern view. * @param flags flags Different flags for the calibration process (@sa calibrateCamera) * @param criteria Termination criteria for the iterative optimization algorithm. * * This function calibrates a camera using a set of corners of a Charuco Board. The function * receives a list of detected corners and its identifiers from several views of the Board. * The function returns the final re-projection error. */ double calibrateCameraCharuco( InputArrayOfArrays charucoCorners, InputArrayOfArrays charucoIds, const CharucoBoard &board, Size imageSize, InputOutputArray cameraMatrix, InputOutputArray distCoeffs, OutputArrayOfArrays rvecs = noArray(), OutputArrayOfArrays tvecs = noArray(), int flags = 0, TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON)); /** * @brief Detect ChArUco Diamond markers * * @param image input image necessary for corner subpixel. * @param markerCorners list of detected marker corners from detectMarkers function. * @param markerIds list of marker ids in markerCorners. * @param squareMarkerLengthRate rate between square and marker length: * squareMarkerLengthRate = squareLength/markerLength. The real units are not necessary. * @param diamondCorners output list of detected diamond corners (4 corners per diamond). The order * is the same than in marker corners: top left, top right, bottom right and bottom left. Similar * format than the corners returned by detectMarkers (e.g std::vector<std::vector<cv::Point2f> > ). * @param diamondIds ids of the diamonds in diamondCorners. The id of each diamond is in fact of * type Vec4i, so each diamond has 4 ids, which are the ids of the aruco markers composing the * diamond. * @param cameraMatrix Optional camera calibration matrix. * @param distCoeffs Optional camera distortion coefficients. * * This function detects Diamond markers from the previous detected ArUco markers. The diamonds * are returned in the diamondCorners and diamondIds parameters. If camera calibration parameters * are provided, the diamond search is based on reprojection. If not, diamond search is based on * homography. Homography is faster than reprojection but can slightly reduce the detection rate. */ void detectCharucoDiamond(InputArray image, InputArrayOfArrays markerCorners, InputArray markerIds, float squareMarkerLengthRate, OutputArrayOfArrays diamondCorners, OutputArray diamondIds, InputArray cameraMatrix = noArray(), InputArray distCoeffs = noArray()); /** * @brief Draw a set of detected ChArUco Diamond markers * * @param image input/output image. It must have 1 or 3 channels. The number of channels is not * altered. * @param diamondCorners positions of diamond corners in the same format returned by * detectCharucoDiamond(). (e.g std::vector<std::vector<cv::Point2f> > ). For N detected markers, * the dimensions of this array should be Nx4. The order of the corners should be clockwise. * @param diamondIds vector of identifiers for diamonds in diamondCorners, in the same format * returned by detectCharucoDiamond() (e.g. std::vector<Vec4i>). * Optional, if not provided, ids are not painted. * @param borderColor color of marker borders. Rest of colors (text color and first corner color) * are calculated based on this one. * * Given an array of detected diamonds, this functions draws them in the image. The marker borders * are painted and the markers identifiers if provided. * Useful for debugging purposes. */ void drawDetectedDiamonds(InputOutputArray image, InputArrayOfArrays diamondCorners, InputArray diamondIds = noArray(), Scalar borderColor = Scalar(0, 0, 255)); /** * @brief Draw a ChArUco Diamond marker * * @param dictionary dictionary of markers indicating the type of markers. * @param ids list of 4 ids for each ArUco marker in the ChArUco marker. * @param squareLength size of the chessboard squares in pixels. * @param markerLength size of the markers in pixels. * @param img output image with the marker. The size of this image will be * 3*squareLength + 2*marginSize,. * @param marginSize minimum margins (in pixels) of the marker in the output image * @param borderBits width of the marker borders. * * This function return the image of a ChArUco marker, ready to be printed. */ void drawCharucoDiamond(Dictionary dictionary, Vec4i ids, int squareLength, int markerLength, OutputArray img, int marginSize = 0, int borderBits = 1); //! @} } } #endif
[ "zhanglei8411" ]
zhanglei8411
77ff25705c5ca27ebd6302d2b0074e60d81e9826
d7a3eb1e4b9eb56480afdc5a4b4988ad46a5ac62
/Vivado/SDR_Full/test_board/vivado/test_board.srcs/sources_1/bd/zsys/ip/zsys_xlconstant_3_0/sim/zsys_xlconstant_3_0.h
6dc4346c839c95c6db94307231fcf1acf91555b7
[]
no_license
mfkiwl/Microwave-SDR
7d08870fc9cec46de844fca37fa03783b1e881ca
1e79ae79361bdff754cc055453d85acd0b7f4dbb
refs/heads/main
2023-08-23T14:05:34.294368
2021-10-23T20:31:27
2021-10-23T20:31:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,658
h
// (c) Copyright 1995-2014 Xilinx, Inc. All rights reserved. // // This file contains confidential and proprietary information // of Xilinx, Inc. and is protected under U.S. and // international copyright and other intellectual property // laws. // // DISCLAIMER // This disclaimer is not a license and does not grant any // rights to the materials distributed herewith. Except as // otherwise provided in a valid license issued to you by // Xilinx, and to the maximum extent permitted by applicable // law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND // WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES // AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING // BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON- // INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and // (2) Xilinx shall not be liable (whether in contract or tort, // including negligence, or under any other theory of // liability) for any loss or damage of any kind or nature // related to, arising under or in connection with these // materials, including for any direct, or any indirect, // special, incidental, or consequential loss or damage // (including loss of data, profits, goodwill, or any type of // loss or damage suffered as a result of any action brought // by a third party) even if such damage or loss was // reasonably foreseeable or Xilinx had been advised of the // possibility of the same. // // CRITICAL APPLICATIONS // Xilinx products are not designed or intended to be fail- // safe, or for use in any application requiring fail-safe // performance, such as life-support or safety devices or // systems, Class III medical devices, nuclear facilities, // applications related to the deployment of airbags, or any // other applications that could lead to death, personal // injury, or severe property or environmental damage // (individually and collectively, "Critical // Applications"). Customer assumes the sole risk and // liability of any use of Xilinx products in Critical // Applications, subject only to applicable laws and // regulations governing limitations on product liability. // // THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS // PART OF THIS FILE AT ALL TIMES. // // DO NOT MODIFY THIS FILE. // IP VLNV: xilinx.com:ip:xlconstant:1.1 // IP Revision: 1 #ifndef _zsys_xlconstant_3_0_H_ #define _zsys_xlconstant_3_0_H_ #include "xlconstant_v1_1_6.h" #include "systemc.h" class zsys_xlconstant_3_0 : public sc_module { public: xlconstant_v1_1_6<16,0> mod; sc_out< sc_bv<16> > dout; zsys_xlconstant_3_0 (sc_core::sc_module_name name) :sc_module(name), mod("mod") { mod.dout(dout); } }; #endif
cd69282c56f3842dee799dc297972b146661fe40
1a84606d22123496db6e83b563d5ae445ffd3195
/src/SwaggerComponent.hpp
496923cf49b97cd94364229ebe15d66e4768fdc0
[ "Apache-2.0" ]
permissive
oatpp/example-mongodb
eeb01f28281cddc676cb4dc11fd8e88b901dc5c4
52bc412115dfdceb35e6e2f971ab32b00c1b21a8
refs/heads/master
2023-09-06T08:39:50.707930
2021-10-25T22:03:18
2021-10-25T22:03:18
267,971,084
10
3
null
null
null
null
UTF-8
C++
false
false
1,286
hpp
#ifndef example_oatpp_mongo_SwaggerComponent_hpp #define example_oatpp_mongo_SwaggerComponent_hpp #include "oatpp-swagger/Model.hpp" #include "oatpp-swagger/Resources.hpp" #include "oatpp/core/macro/component.hpp" /** * Swagger ui is served at * http://host:port/swagger/ui */ class SwaggerComponent { public: /** * General API docs info */ OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::swagger::DocumentInfo>, swaggerDocumentInfo)([] { oatpp::swagger::DocumentInfo::Builder builder; builder .setTitle("Example Project - Oat++ MongoDB") .setDescription("Example project how-to work with MongoDB using oatpp-mongo module") .setVersion("1.0") .setContactName("Mr. Porridge") .setContactUrl("https://oatpp.io/") .addServer("http://localhost:8000", "server on localhost"); return builder.build(); }()); /** * Swagger-Ui Resources (<oatpp-examples>/lib/oatpp-swagger/res) */ OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::swagger::Resources>, swaggerResources)([] { // Make sure to specify correct full path to oatpp-swagger/res folder !!! return oatpp::swagger::Resources::loadResources(OATPP_SWAGGER_RES_PATH); }()); }; #endif /* example_oatpp_mongo_SwaggerComponent_hpp */
555792167d168e3e3269f2da34521d085bf16fec
c34f46ea941aa42a3c7c976d70cc987684d988b5
/HW7/ResultSet.cpp
e45ed9157793a69493b8fdf7e50383c168a4e5a5
[]
no_license
emperorbyl/PeerReview
c613dda92b5c8beb5c4412068adc7b1200f823d4
78d182aaa586af30b731534dd9abb1d6896cd909
refs/heads/master
2021-01-20T03:29:14.129404
2017-04-27T02:26:37
2017-04-27T02:26:37
89,545,239
0
0
null
null
null
null
UTF-8
C++
false
false
475
cpp
// // Created by Justin Fairbourn on 4/23/2017. // #include "ResultSet.h" const void ResultSet::print(std::ostream &out){ for(int i = 0; i < results->getSize(); i++){ KeyValue<std::string, std::vector<std::string>> *thisPair; thisPair = results->getByIndex(i); out << thisPair->getKey() << std::endl; for(int j = 0; j < thisPair->getValue().size(); j++){ out << '\t' << thisPair->getValue()[j] << std::endl; } } }
5fdc595de272340148db0335aab8a431ad138ca2
08c64f2a7d75101c2bc78bcfdce98dafe5f49523
/ShoppingList.h
0ceb7aad6e8429177924f47f2db70ac0144b1cff
[]
no_license
TommasoCapanni/ProgettoListaSpesa
868267d6a1ed7810b2911e304e0099b161e28f7c
ae2c707de878f553d59329273590a61d1ae4a55f
refs/heads/master
2023-06-24T00:48:43.319512
2021-07-23T15:54:10
2021-07-23T15:54:10
385,278,197
0
0
null
null
null
null
UTF-8
C++
false
false
1,336
h
// // Created by Tommaso Capanni on 12/07/2021. // #ifndef PROGETTOLISTASPESA_SHOPPINGLIST_H #define PROGETTOLISTASPESA_SHOPPINGLIST_H #include <memory> #include "Subject.h" #include "Articolo.h" #include "NegativeNumberException.h" class ShoppingList : public Subject { public: explicit ShoppingList(std::string name) : name(name) { boughtItems = 0; }; void addItem(const Articolo &ar, int i = 1); void removeItem(const Articolo &ar); bool findItem(const Articolo &ar) const; void toggleCheckItem(const Articolo &ar); std::string getName() const { return name; } std::map<std::string, int> getList() const { return shopList; } std::map<std::string, Articolo> getArticleList() const { return artList; } int getListSize() const { return shopList.size(); } int getBoughtItemsNumber() const { return boughtItems; } int getItemsToBuyNumber() const; void attach(Observer *o) { obs.push_back(o); } void detach(Observer *o) { obs.remove(o); } void notify() const { for (auto &i : obs) { i->update((Subject *) this); } } private: std::string name; std::map<std::string, int> shopList; std::list<Observer *> obs; std::map<std::string, Articolo> artList; int boughtItems; }; #endif //PROGETTOLISTASPESA_SHOPPINGLIST_H
81bd239c5b1821b3c8289e11d25c22dc2d613b63
9fd12a8116a34ad534c66280d7047aac4e149bfb
/jsb-default/frameworks/cocos2d-x/tools/simulator/frameworks/runtime-src/Classes/ide-support/RuntimeJsImpl.cpp
4eb5c3d66865012e9b1de102fb9eafac94f5d318
[ "MIT" ]
permissive
noneGMJ/Cosos_try
b1c90320e0e138de46e646c16a81851110b16e31
500102549c74c194dde77331e97807045c9821ca
refs/heads/master
2020-04-13T03:47:16.230320
2018-12-24T02:52:59
2018-12-24T03:00:17
162,942,158
0
1
null
null
null
null
UTF-8
C++
false
false
10,333
cpp
// // RuntimeJsImpl.cpp // Simulator // // #include "RuntimeJsImpl.h" #include "cocos/base/CCDirector.h" // 2dx engine #if (COCOS2D_DEBUG > 0) && (CC_CODE_IDE_DEBUG_SUPPORT > 0) #include "runtime/ConfigParser.h" // config #include "runtime/Runtime.h" #include "runtime/FileServer.h" // js #include "scripting/js-bindings/manual/ScriptingCore.h" #include "js_module_register.h" static const char *RUNTIME_JS_BOOT_SCRIPT = "script/jsb_boot.js"; static bool reloadScript(const string& file) { auto director = cocos2d::Director::getInstance(); cocos2d::FontFNT::purgeCachedData(); if (director->getOpenGLView()) { cocos2d::SpriteFrameCache::getInstance()->removeSpriteFrames(); director->getTextureCache()->removeAllTextures(); } cocos2d::FileUtils::getInstance()->purgeCachedEntries(); //director->getScheduler()->unscheduleAll(); //director->getScheduler()->scheduleUpdate(director->getActionManager(), Scheduler::PRIORITY_SYSTEM, false); string modulefile = file; if (modulefile.empty()) { modulefile = ConfigParser::getInstance()->getEntryFile().c_str(); } return ScriptingCore::getInstance()->runScript(modulefile.c_str()); } bool runtime_FileUtils_addSearchPath(JSContext *cx, uint32_t argc, JS::Value *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); bool ok = true; JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); js_proxy_t *proxy = jsb_get_js_proxy(cx, obj); cocos2d::FileUtils* cobj = (cocos2d::FileUtils *)(proxy ? proxy->ptr : NULL); JSB_PRECONDITION2( cobj, cx, false, "cocos2dx_FileUtils_addSearchPath : Invalid Native Object"); if (argc == 1 || argc == 2) { std::string arg0; bool arg1 = false; ok &= jsval_to_std_string(cx, args.get(0), &arg0); JSB_PRECONDITION2(ok, cx, false, "cocos2dx_FileUtils_addSearchPath : Error processing arguments"); if (argc == 2) { arg1 = args.get(1).isBoolean() ? args.get(1).toBoolean() : false; } if (! cocos2d::FileUtils::getInstance()->isAbsolutePath(arg0)) { // add write path to search path if (FileServer::getShareInstance()->getIsUsingWritePath()) { cobj->addSearchPath(FileServer::getShareInstance()->getWritePath() + arg0, arg1); } else { cobj->addSearchPath(arg0, arg1); } #if(CC_TARGET_PLATFORM == CC_PLATFORM_MAC || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) // add project path to search path cobj->addSearchPath(RuntimeEngine::getInstance()->getRuntime()->getProjectPath() + arg0, arg1); #endif } args.rval().setUndefined(); return true; } JS_ReportErrorUTF8(cx, "cocos2dx_FileUtils_addSearchPath : wrong number of arguments: %d, was expecting %d", argc, 1); return false; } bool runtime_FileUtils_setSearchPaths(JSContext *cx, uint32_t argc, JS::Value *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); bool ok = true; JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); js_proxy_t *proxy = jsb_get_js_proxy(cx, obj); cocos2d::FileUtils* cobj = (cocos2d::FileUtils *)(proxy ? proxy->ptr : NULL); JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_FileUtils_setSearchPaths : Invalid Native Object"); if (argc == 1) { std::vector<std::string> vecPaths, writePaths; ok &= jsval_to_std_vector_string(cx, args.get(0), &vecPaths); JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_FileUtils_setSearchPaths : Error processing arguments"); std::vector<std::string> originPath; // for IOS platform. std::vector<std::string> projPath; // for Desktop platform. for (int i = 0; i < vecPaths.size(); i++) { if (!cocos2d::FileUtils::getInstance()->isAbsolutePath(vecPaths[i])) { originPath.push_back(vecPaths[i]); // for IOS platform. projPath.push_back(RuntimeEngine::getInstance()->getRuntime()->getProjectPath()+vecPaths[i]); //for Desktop platform. writePaths.push_back(FileServer::getShareInstance()->getWritePath() + vecPaths[i]); } } #if(CC_TARGET_PLATFORM == CC_PLATFORM_MAC || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) vecPaths.insert(vecPaths.end(), projPath.begin(), projPath.end()); #endif if (FileServer::getShareInstance()->getIsUsingWritePath()) { vecPaths.insert(vecPaths.end(), writePaths.begin(), writePaths.end()); } else { vecPaths.insert(vecPaths.end(), originPath.begin(), originPath.end()); } cobj->setSearchPaths(vecPaths); args.rval().setUndefined(); return true; } JS_ReportErrorUTF8(cx, "js_cocos2dx_FileUtils_setSearchPaths : wrong number of arguments: %d, was expecting %d", argc, 1); return false; } void register_FileUtils(JSContext *cx, JS::HandleObject global) { JS::RootedValue nsval(cx); JS::RootedObject ns(cx); JS_GetProperty(cx, global, "cc", &nsval); if (nsval.isNullOrUndefined()) { return; } else { ns.set(nsval.toObjectOrNull()); } JS::RootedObject proto(cx); get_jsb_cocos2d_FileUtils_prototype(&proto); JS_DefineFunction(cx, proto, "addSearchPath", runtime_FileUtils_addSearchPath, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE); JS_DefineFunction(cx, proto, "setSearchPaths", runtime_FileUtils_setSearchPaths, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE); } RuntimeJsImpl* RuntimeJsImpl::create() { RuntimeJsImpl *instance = new RuntimeJsImpl(); return instance; } bool RuntimeJsImpl::initJsEnv() { if (!ScriptingCore::getInstance()->getGlobalContext()) { _hasStarted = false; } if (_hasStarted) { return true; } js_module_register(); ScriptingCore::getInstance()->addRegisterCallback(register_FileUtils); ScriptingCore::getInstance()->start(); _hasStarted = true; cocos2d::ScriptEngineProtocol *engine = ScriptingCore::getInstance(); cocos2d::ScriptEngineManager::getInstance()->setScriptEngine(engine); return true; } bool RuntimeJsImpl::startWithDebugger() { initJsEnv(); return true; } void RuntimeJsImpl::startScript(const std::string& path) { loadScriptFile(path); } void RuntimeJsImpl::onStartDebuger(const rapidjson::Document& dArgParse, rapidjson::Document& dReplyParse) { if (loadScriptFile(ConfigParser::getInstance()->getEntryFile())) { dReplyParse.AddMember("code",0,dReplyParse.GetAllocator()); } else { dReplyParse.AddMember("code",1,dReplyParse.GetAllocator()); } } void RuntimeJsImpl::onClearCompile(const rapidjson::Document& dArgParse, rapidjson::Document& dReplyParse) { if (dArgParse.HasMember("modulefiles") && dArgParse["modulefiles"].Size() != 0) { const rapidjson::Value& objectfiles = dArgParse["modulefiles"]; for (rapidjson::SizeType i = 0; i < objectfiles.Size(); i++) { ScriptingCore::getInstance()->cleanScript(objectfiles[i].GetString()); } } else { std::unordered_map<std::string, JS::PersistentRootedScript*> *filenameScript = ScriptingCore::getInstance()->getFileScript(); filenameScript->clear(); } dReplyParse.AddMember("code",0,dReplyParse.GetAllocator()); } void RuntimeJsImpl::onPrecompile(const rapidjson::Document& dArgParse, rapidjson::Document& dReplyParse) { const rapidjson::Value& objectfiles = dArgParse["modulefiles"]; for (rapidjson::SizeType i = 0; i < objectfiles.Size(); i++) { ScriptingCore* sc = ScriptingCore::getInstance(); JSContext* gc = sc->getGlobalContext(); JS::RootedObject global(gc, sc->getGlobalObject()); JS::RootedScript script(gc); sc->compileScript(objectfiles[i].GetString(), global, &script); } dReplyParse.AddMember("code",0,dReplyParse.GetAllocator()); } void RuntimeJsImpl::onReload(const rapidjson::Document &dArgParse, rapidjson::Document &dReplyParse) { if (dArgParse.HasMember("modulefiles")){ auto& allocator = dReplyParse.GetAllocator(); rapidjson::Value bodyvalue(rapidjson::kObjectType); const rapidjson::Value& objectfiles = dArgParse["modulefiles"]; for (rapidjson::SizeType i = 0; i < objectfiles.Size(); i++){ if (!reloadScript(objectfiles[i].GetString())) { bodyvalue.AddMember(rapidjson::Value(objectfiles[i].GetString(), allocator) , rapidjson::Value(1) , allocator); } } if (0 == objectfiles.Size()) { reloadScript(""); } dReplyParse.AddMember("body", bodyvalue, dReplyParse.GetAllocator()); }else { reloadScript(""); } dReplyParse.AddMember("code", 0, dReplyParse.GetAllocator()); } void RuntimeJsImpl::onRemove(const std::string &filename) { ScriptingCore::getInstance()->cleanScript(filename.c_str()); } void RuntimeJsImpl::end() { cocos2d::ScriptEngineManager::destroyInstance(); RuntimeProtocol::end(); } // private RuntimeJsImpl::RuntimeJsImpl() : _hasStarted(false) { } bool RuntimeJsImpl::loadScriptFile(const std::string& path) { std::string filepath = path; if (filepath.empty()) { filepath = ConfigParser::getInstance()->getEntryFile(); } CCLOG("------------------------------------------------"); CCLOG("LOAD Js FILE: %s", filepath.c_str()); CCLOG("------------------------------------------------"); initJsEnv(); auto engine = ScriptingCore::getInstance(); engine->runScript(RUNTIME_JS_BOOT_SCRIPT); // if (RuntimeEngine::getInstance()->getProjectConfig().getDebuggerType() != kCCRuntimeDebuggerNone) // { this->startWithDebugger(); // } cocos2d::ScriptEngineManager::getInstance()->setScriptEngine(engine); return ScriptingCore::getInstance()->runScript(filepath.c_str()); } #endif // (COCOS2D_DEBUG > 0) && (CC_CODE_IDE_DEBUG_SUPPORT > 0)
c63140dabb60ee70c89441728e152e3d1c785111
0fd6c95a57373850d5fc79d3bd019619af87bb84
/main.cpp
e8ceb00d2db648f7df02a8fa7b67905951aaaacd
[]
no_license
lYC92/Evil_Hangman
0f6ae71a0271529b518bc3cc095d7bdbbe8823d9
0b3b6e5f5984f35a9a9d549174910b543a9fb7ce
refs/heads/master
2020-11-28T07:55:53.461226
2016-11-15T03:28:54
2016-11-15T03:28:54
73,506,496
0
0
null
null
null
null
UTF-8
C++
false
false
5,121
cpp
#include <iostream> #include <fstream> #include <string> #include <cassert> #include <iterator> #include <algorithm> #include <map> using namespace std; const string fileName = "dictionary.txt"; class notSameLength { size_t length; public: notSameLength (size_t length) : length(length) {} bool operator()(string str) { return length != str.length(); } }; int LengthSelect (size_t length, vector<string> &dic) { dic.erase(remove_if(dic.begin(),dic.end(),notSameLength(length)), dic.end()); return dic.size(); } void LoadDic(vector<string> &dic) { ifstream input("dictionary.txt"); assert(input.is_open()); istream_iterator<string> eos; copy(istream_iterator<string>(input), eos, inserter(dic, dic.begin())); } class game { private: size_t wordLength; size_t remainChance; vector<char> guessedLetters; // e.g. "c" int wordRemain; // e.g. 100 string currentWord; // e.g. "---a---e--" public: vector<string> dictionary; // map<string, vector<int>> relation; game() { LoadDic(dictionary); inputWordLength(); remainChance = wordLength * 10; setWordRemain(LengthSelect(wordLength,dictionary)); string temp; temp.append(wordLength,'-'); setCurrentWord(temp); } typename vector<char>::iterator start() { return guessedLetters.begin(); } typename vector<char>::iterator final() { return guessedLetters.end(); } void pushGuessed(char a) { guessedLetters.push_back(a); } void setCurrentWord(string word) { currentWord = word; } string getCurrentWord() { return currentWord; } void setWordLength(int length) { wordLength = length; } int getWordLength() { return wordLength; } int getRemainChance () { return remainChance; } void setRemainChance (int chance) { remainChance = chance; } int getWordRemain () { return wordRemain; } void setWordRemain (int input) {wordRemain = input;} void inputWordLength () { cout << "Please input word length: "; cin >> wordLength; string dummy; getline(cin,dummy); } }; void PrintOut (game &hangman) { cout << "Word Length: " << hangman.getWordLength() << endl; cout << "Current Word: " << hangman.getCurrentWord() << endl; cout << "Mistakes Remaining: " << hangman.getRemainChance() << endl; cout << "Letters Guessed: "; copy(hangman.start(), hangman.final(), ostream_iterator<char>(cout, " ")); cout << endl; cout << "Words Remaining: " << hangman.getWordRemain() << endl; cout << "===================================" << endl << endl; } string Getline() { string a; getline(cin,a); return a.c_str(); } void analysis(game &hangman, char letter) { // this will update hangman.currentWord map<string, pair<vector<size_t>,size_t>> relation ; map<vector<size_t>,size_t> summary; for(auto itr = hangman.dictionary.begin(); itr != hangman.dictionary.end(); itr++) { string word = *itr; vector<size_t> position; size_t pos = word.find(letter,0); while (pos != string::npos) { position.push_back(pos); pos = word.find(letter,pos+1); } relation[word] = make_pair(position,position.size()); summary[position] = summary[position] + 1; } auto itrInitial = relation.begin(); vector<size_t> maxIndx = itrInitial->second.first; for (auto itr = summary.begin(); itr != summary.end(); itr++) { if (itr->second > summary[maxIndx]) maxIndx = itr->first; } cout << "max chances is for " << letter << " is "; copy(maxIndx.begin(),maxIndx.end(),ostream_iterator<size_t>(cout," ")); cout << endl; hangman.dictionary.clear(); for (auto itr = relation.begin(); itr != relation.end(); ++itr) { if (itr->second.first == maxIndx) hangman.dictionary.push_back(itr->first); } for (auto itr = maxIndx.begin(); itr != maxIndx.end(); ++itr) { string temp = hangman.getCurrentWord(); temp[*itr] = letter; hangman.setCurrentWord(temp); } copy(hangman.dictionary.begin(),hangman.dictionary.end(),ostream_iterator<string>(cout, "\n")); } void SelectWords(game &hangman) { char letter; do { cout << "Guess a letter (not guessed one): "; string temp = Getline(); letter = temp[0]; }while( find(hangman.start(), hangman.final(), letter) != hangman.final()); // update guessed letter and remain chances hangman.pushGuessed(letter); hangman.setRemainChance(hangman.getRemainChance() - 1); analysis(hangman, letter); hangman.setWordRemain(hangman.dictionary.size()); } int main() { game hangman; while(hangman.getRemainChance()) { SelectWords(hangman); PrintOut(hangman); if (hangman.getWordRemain() == 1) { cout << "You win!" << endl; break; } if (hangman.getRemainChance() == 0) cout << "You lose." << endl; } return 0; }
925833f89f21fd55b466c1a99f614d5c8d36b57b
bea698595acf98c96089a202c3606090c5bfeab2
/Server/Core/Debug/DLSources/AMMO/AMMO-1/Ammo1.h
a5b36d30b63541c923d6ca4d51ba499fe3c3048f
[]
no_license
ekersale/RType
1b904a1094820c150134d1152308c5874ec40d1a
1ce77e9eb69efeeeebf83a3d049cc96ab5ce804f
refs/heads/master
2020-12-25T10:34:32.068425
2016-08-01T13:05:57
2016-08-01T13:05:57
62,563,089
0
0
null
null
null
null
UTF-8
C++
false
false
243
h
#ifndef AMMO1_H_ #define AMMO1_H_ #include "IAmmo.h" class Ammo1 : public IAmmo { public: Ammo1(); ~Ammo1(); DRect calcPos(DRect); e_type getType() const; int getPower() const; void setMovement(int); private: int _movement; }; #endif
2cff411c32abba97a646e48baee527caca084c7e
118aef490b85fedd0e85fbcd63b1ed1590b4e932
/src/vkkp2p/vkkp2p/src/libpeer/UACChannel.cpp
503461b5ec5117a1e588f7944b1695d55d1d031b
[]
no_license
wsljmlin/p2p
12ce3cb77ef9c1453d81d0c964c1ea94b69dbd23
bb526637865a727d8ea400162c6ff4431736cd04
refs/heads/master
2020-05-25T15:36:21.604600
2017-03-14T12:22:58
2017-03-14T12:22:58
84,943,893
3
1
null
null
null
null
WINDOWS-1252
C++
false
false
2,238
cpp
#include "UACChannel.h" #include "Util.h" UACChannel::UACChannel(void) { m_last_active_tick = GetTickCount(); } UACChannel::~UACChannel(void) { } int UACChannel::attach(SOCKET s,sockaddr_in& addr) { UAC_sockaddr uac_addr; uac_addr.ip = ntohl(addr.sin_addr.s_addr); uac_addr.port = ntohs(addr.sin_port); uac_addr.nattype = 0; m_hip = ntohl(addr.sin_addr.s_addr); m_hport = ntohs(addr.sin_port); m_is_accept = true; return uac_attach((int)s,uac_addr); } int UACChannel::connect(const char* ip,unsigned short port,const char* bindip/*=NULL*/,int nattype/*=0*/) { return connect(Util::ip_atoh(ip),port,bindip,nattype); } int UACChannel::connect(unsigned int ip,unsigned short port,const char* bindip/*=NULL*/,int nattype/*=0*/) { m_hip = ip; m_hport = port; m_state = CONNECTING; return this->uac_connect(ip,port,nattype); } int UACChannel::disconnect() { if(DISCONNECTED!=m_state) { uac_disconnect(); m_state = DISCONNECTED; reset(); fire(ChannelListener::Disconnected(),this); } return 0; } int UACChannel::send(MemBlock *b,bool more/*=false*/) //-1:false; 0:send ok; 1:put int sendlist { m_last_active_tick = GetTickCount(); assert(b); if(CONNECTED != m_state) { b->free(); return -1; } if(b->datalen <= b->datapos) { b->free(); return 0; } int sendsize = b->datalen - b->datapos; int ret = uac_send(b->buf + b->datapos,sendsize); b->free(); if(ret!=sendsize) { disconnect(); return -1; } return uac_is_write()?0:1; //0¼ÌÐø¿ÉÒÔд } int UACChannel::recv(char *b,int size) { m_last_active_tick = GetTickCount(); int ret = uac_recv(b,size); if(-1==ret) { disconnect(); return -1; } return ret; } //uac int UACChannel::uac_on_read() { int wait = 0; fire(ChannelListener::Readable(),this,wait); return 0; } void UACChannel::uac_on_write() { if(UAC_CONNECTED==m_uac_state) { fire(ChannelListener::Writable(),this); } else { UAC_Socket::uac_on_write(); } } void UACChannel::uac_on_connected() { m_state = CONNECTED; uac_setsendbuf(102400); uac_setrecvbuf(1024000); UAC_Socket::uac_on_connected(); fire(ChannelListener::Connected(),this); }
4798309f8877dcff2a8cf7dc672f713717a6a071
e7c0c64db63eb51b79a02f78fa9c2dcb61b9664d
/imx/display/display/Composer.h
2b69ed7b8b56e16c8861914225d2155c87a8411e
[ "Apache-2.0" ]
permissive
ivan-kits/android_nxp_opensource
3839ebbba74542781cd3d6064caed80b61d8f617
17fe0cb699007eca790085be141e2687ab065211
refs/heads/master
2023-07-27T11:41:31.606785
2019-03-13T08:10:12
2019-03-13T08:10:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,329
h
/* * Copyright 2017 NXP. * * 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 _FSL_COMPOSER_H_ #define _FSL_COMPOSER_H_ #include <g2dExt.h> #include "Memory.h" #include "Layer.h" namespace fsl { typedef int (*hwc_func1)(void* handle); typedef int (*hwc_func2)(void* handle, void* arg1); typedef int (*hwc_func3)(void* handle, void* arg1, void* arg2); typedef int (*hwc_func4)(void* handle, void* arg1, void* arg2, void* arg3); typedef int (*hwc_func5)(void* handle, void* arg1, void* arg2, void* arg3, void* arg4); class Composer { public: Composer(); ~Composer(); bool isValid(); // set composite target buffer. int setRenderTarget(Memory* memory); // clear worm hole introduced by layers not cover whole screen. int clearWormHole(LayerVector& layers); // compose display layer. int composeLayer(Layer* layer, bool bypass); // sync 2D blit engine. int finishComposite(); // lock surface to get GPU specific resource. int lockSurface(Memory *handle); // unlock surface to release resource. int unlockSurface(Memory *handle); bool isFeatureSupported(g2d_feature feature); private: int setG2dSurface(struct g2d_surfaceEx& surfaceX, Memory *handle, Rect& rect); enum g2d_format convertFormat(int format, Memory *handle); int convertRotation(int transform, struct g2d_surface& src, struct g2d_surface& dst); int convertBlending(int blending, struct g2d_surface& src, struct g2d_surface& dst); void getModule(char *path, const char *name); int checkDimBuffer(); int clearRect(Memory* target, Rect& rect); int getAlignedSize(Memory *handle, int *width, int *height); int getFlipOffset(Memory *handle, int *offset); int getTiling(Memory *handle, enum g2d_tiling* tile); enum g2d_format alterFormat(Memory *handle, enum g2d_format format); int setClipping(Rect& src, Rect& dst, Rect& clip, int rotation); int blitSurface(struct g2d_surfaceEx *srcEx, struct g2d_surfaceEx *dstEx); int openEngine(void** handle); int closeEngine(void* handle); int clearFunction(void* handle, struct g2d_surface* area); int enableFunction(void* handle, enum g2d_cap_mode cap, bool enable); int finishEngine(void* handle); private: void* mHandle; Memory* mTarget; Memory* mDimBuffer; hwc_func3 mGetAlignedSize; hwc_func2 mGetFlipOffset; hwc_func2 mGetTiling; hwc_func2 mAlterFormat; hwc_func1 mLockSurface; hwc_func1 mUnlockSurface; hwc_func5 mSetClipping; hwc_func3 mBlitFunction; hwc_func1 mOpenEngine; hwc_func1 mCloseEngine; hwc_func2 mClearFunction; hwc_func2 mEnableFunction; hwc_func2 mDisableFunction; hwc_func1 mFinishEngine; hwc_func3 mQueryFeature; }; } #endif
28d1243f706761b2e1702c5ba0706f59c5f07d68
1026bf6ee3f34c85f017e5cee2105f81ec043e35
/code/svec/src/rop-orig/include/BottleWrapper.h
2c3bd2be51d4209cc9373e40d20a3e84d973dbbd
[]
no_license
martinkellner/master-thesis
4557a6876f6da49b70516212307ca789781e099f
71d39c706fb216ccc3224f20270eaaf42fd33532
refs/heads/master
2022-01-06T22:41:51.574314
2019-06-04T20:04:27
2019-06-04T20:04:27
122,238,963
0
0
null
null
null
null
UTF-8
C++
false
false
858
h
#pragma once #ifndef BOTTLE_WRAPPER_H #define BOTTLE_WRAPPER_H #include <yarp/os/Bottle.h> using namespace yarp::os; class BottleWrapper { //Bottle getBottle(char* s); public: static Bottle prepareBottle(char *szTypes, ...); //creation static Bottle box(double sx, double sy, double sz, double px, double py, double pz, double r=1, double g=0, double b=0); static Bottle cyl(double radius, double length, double px, double py, double pz, double r=1, double g=0, double b=0); static Bottle sph(double radius, double px, double py, double pz, double r=1, double g=0, double b=0); //rotation static Bottle r_box(int index, double rx, double ry, double rz); static Bottle r_cyl(int index, double rx, double ry, double rz); static Bottle r_sph(int index, double rx, double ry, double rz); }; #endif
5aa577b8875d254acbfb765f2b695aa471c9ef81
6240d8c171d182e969ec24b9e5f88a8137cfebce
/UVa/12250 - Language Detection.cpp
20f1eb26ba469ee018c98a9b4976ab1c3ba5439f
[]
no_license
BillySilver/Online-Judge
04e93d05e054df33c054cdfdd1cb89145815ae8b
2d2ba064b01007f9a1a99f427595ae6f807a3d5e
refs/heads/master
2021-07-12T22:21:10.389235
2017-10-14T21:48:38
2017-10-14T21:53:47
106,046,686
0
0
null
null
null
null
UTF-8
C++
false
false
554
cpp
#include <iostream> #include <cstdio> #include <string> std::string maps[6][2] = { { "HELLO", "ENGLISH" }, { "HOLA", "SPANISH" }, { "HALLO", "GERMAN" }, { "BONJOUR", "FRENCH" }, { "CIAO", "ITALIAN" }, { "ZDRAVSTVUJTE", "RUSSIAN" } }; int main() { int cases = 0; std::string s, lang; while (std::cin >> s, "#" != s) { lang = "UNKNOWN"; for (int i = 0; i < 6; ++i) if ( s == maps[i][0] ) lang = maps[i][1]; printf("Case %d: %s\n", ++cases, lang.c_str()); } }
20ce9f7bd71b8256d6762327761d0a4deb0887e7
46e1d567fcee62b4a726a505e53aeed8271cf84a
/Algorithm_Study/baekjun/baek_16235(tree_investment).cpp
1186acf108584c2cdd7c79abf5961c68d451d728
[]
no_license
ahnus123/algorithm-cpp
c88e1bc55cce477cec79631374a9401920d248bb
0eab3407b352f6b8d0be022b7095cc3ea374c77b
refs/heads/master
2022-12-02T22:24:20.309413
2020-07-28T13:59:55
2020-07-28T13:59:55
null
0
0
null
null
null
null
UHC
C++
false
false
2,280
cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; struct Tree { int x; int y; int z; }; void p(vector< vector<int> > vec) { for (int i = 0; i < vec.size(); i++) { for (int j = 0; j < vec[i].size(); j++) { cout << vec[i][j] << " "; } cout << "\n"; } cout << "\n"; } bool cmp(Tree &t1, Tree &t2) { if (t1.x == t2.x) { if (t1.y == t2.y) { return t1.z < t2.z; } else { return t1.y < t2.y; } } else { return t1.x < t2.x; } } int main() { int n, m, k, answer = 0; int nutrient[11][11]; int A[11][11]; int dx[8] = { -1, -1, -1, 0, 0, 1, 1, 1 }; int dy[8] = { -1, 0, 1, -1, 1, -1, 0, 1 }; vector<Tree> tree, live_tree, dead_tree, breeding; cin >> n >> m >> k; //input & init for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cin >> A[i][j]; nutrient[i][j] = 5; } } for (int i = 0; i < m; i++) { Tree t; cin >> t.x; cin >> t.y; cin >> t.z; tree.push_back(t); } while (k-- != 0) { sort(tree.begin(), tree.end(), cmp); //Spring //양분 주기 & 나이++ or 죽음 for (int i = 0; i < tree.size(); i++) { int x = tree[i].x; int y = tree[i].y; int age = tree[i].z; if (age <= nutrient[x - 1][y - 1]) { //양분 주기 nutrient[x - 1][y - 1] -= age; tree[i].z++; if (tree[i].z % 5 == 0) breeding.push_back({ x, y, tree[i].z }); live_tree.push_back({ x, y, tree[i].z }); } else { //죽은 나무 저장 dead_tree.push_back({ x, y, age / 2 }); } } //Summer //죽은 나무 나이 / 2 >> 양분 for (int i = 0; i < dead_tree.size(); i++) nutrient[dead_tree[i].x - 1][dead_tree[i].y - 1] += dead_tree[i].z; //Fall //나이 == 5의 배수 >> 주변에 나무 추가 for (int i = 0; i < breeding.size(); i++) { int x = breeding[i].x; int y = breeding[i].y; for (int j = 0; j < 8; j++) if (x + dx[j] > 0 && x + dx[j] <= n && y + dy[j] > 0 && y + dy[j] <= n) live_tree.push_back({ x + dx[j], y + dy[j], 1 }); } //Winter //양분 추가 for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) nutrient[i][j] += A[i][j]; tree = live_tree; live_tree.clear(); dead_tree.clear(); breeding.clear(); } answer = tree.size(); cout << answer << endl; return 0; }
29a9180412b87529ffcffd9796f416e413746951
64763bf14f8666380a219210a4de75187bd31d58
/P02.02/TreeNode.h
fea14165a0986b81c8f378d3c570ea6aa57cd788
[]
no_license
denis-adobe/ADS2017
cb893c1fa6b15a91c53edfb0347a2530b1519462
ec68e2972c4534f2aca125a43db70dade8890e0b
refs/heads/master
2021-01-19T20:47:50.509359
2017-08-13T13:39:01
2017-08-13T13:39:01
88,554,319
0
2
null
null
null
null
UTF-8
C++
false
false
407
h
#pragma once #include<string> class TreeNode { int NodePosID; int NodeID; std::string Name; int Alter; double Einkommen; int PLZ; TreeNode *links; TreeNode *rechts; public: TreeNode(); ~TreeNode(); std::string getName(); int getAlter(); double getEinkommen(); int getPLZ(); void setName(std::string); void setAlter(int); void setEinkommen(double); void setPLZ(int); void printData(); };
dc8bc173b55e93945d7030938e776375a7aca79d
bc1d68d7a7c837b8a99e516050364a7254030727
/src/POJ/POJ1157 LITTLE SHOP OF FLOWERS.cpp
020c7c5a780b1d656d9d2e1cf9384435e9fdfd52
[]
no_license
kester-lin/acm_backup
1e86b0b4699f8fa50a526ce091f242ee75282f59
a4850379c6c67a42da6b5aea499306e67edfc9fd
refs/heads/master
2021-05-28T20:01:31.044690
2013-05-16T03:27:21
2013-05-16T03:27:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,178
cpp
/******************************************************************************* # Author : Neo Fung # Email : [email protected] # Last modified: 2012-03-16 20:11 # Filename: POJ1157 LITTLE SHOP OF FLOWERS.cpp # Description : ******************************************************************************/ #ifdef _MSC_VER #define DEBUG #define _CRT_SECURE_NO_DEPRECATE #endif #include <fstream> #include <stdio.h> #include <iostream> #include <string.h> #include <string> #include <limits.h> #include <algorithm> #include <math.h> #include <numeric> #include <functional> #include <ctype.h> #define MAX 110 using namespace std; int dp[MAX][MAX]; int value[MAX][MAX]; int main(void) { #ifdef DEBUG freopen("../stdin.txt","r",stdin); freopen("../stdout.txt","w",stdout); #endif int n,m; while(~scanf("%d%d",&n,&m)) { memset(dp,0,sizeof(dp)); for(int i=1;i<=n;++i) for(int j=1;j<=m;++j) { scanf("%d",&value[i][j]); dp[i][j]=INT_MIN; } for(int i=1;i<=n;++i) { dp[i][i]=dp[i-1][i-1]+value[i][i]; for(int j=i+1;j<=m;++j) dp[i][j]=max(dp[i][j-1],dp[i-1][j-1]+value[i][j]); } printf("%d\n",dp[n][m]); } return 0; }
81d4c14b6324ebf4e57ddb8d3e0ff1dbe95b7370
47928449f08c336c9e21b5387f7522d531a48fb8
/init.cpp
6699a63bbd1b0bfd0077f00f3ae04a497941b4da
[ "Apache-2.0" ]
permissive
lanceleefeng/TomatoDownUI
f001f14029c65e439064e0e4f939f8b65ebdf21b
a71ba0905aa365cee0d1f48a6b6659bb36394b5b
refs/heads/master
2022-11-29T09:35:58.450658
2022-11-20T17:29:48
2022-11-20T17:29:48
99,590,513
1
0
null
null
null
null
UTF-8
C++
false
false
1,651
cpp
#include <QtSql> #include "db.h" #include "init.h" Init::Init() : m_success(false) { QString connectionName = "tomato_"; static DB& db = DB::instance(connectionName); QString sqlCreateCountDownTable = "create table if not exists t_count_down(" ")"; QString sqlCreateMusicTable = "create table if not exists t_music(" ")"; //"YYYY-MM-DD HH:MM:SS.SSS" // sqlite 不支持表注释、字段注释 QString sqlCreateSettingsTable = "create table if not exists td_settings(" "id integer PRIMARY KEY AUTOINCREMENT," "uid integer default 0," "language text," "auto_start integer default 1," "count_down integer default 1," "auto_hide integer default 1," "auto_hide_delay integer default 0," "first_run_hide integer default 0," "tomato_time integer default 25," "tip_time integer default 3," "break_time integer default 5," "created_at text," "updated_at text" ")"; if(!db.exec(sqlCreateSettingsTable)){ return; } QString sqlCreateTestTable = "create table if not exists td_test(" "id integer PRIMARY KEY AUTOINCREMENT," "uid integer default 0," "test_auto_start integer default 1," "countdown integer default 0," "created_at text," "updated_at text" ")"; if(!db.exec(sqlCreateTestTable)){ return; } m_success = true; } Init::~Init() { } /** * 初始化是否成功 * @return bool */ bool Init::succeed() { //return false; return m_success; }
cc98e9b4278bece4040b885da8b3b37e6aaebc67
1218f0e55768af3c39e4f643ce4e0799c10f19da
/flipcoin.cpp
154b55a3d6de2827c58c606fd099ec90a6fa2683
[]
no_license
ravinderdevesh/codechef
a5c35ea185663506f5e263c05e8262e5106802d8
f3bec3e9691afb552bf3d70e9582947958b20243
refs/heads/master
2021-01-19T19:01:49.612685
2015-02-21T16:37:44
2015-02-21T16:37:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,583
cpp
#include <iostream> #include <stdio.h> using namespace std ; void flip(int node , int a , int b , int i , int j , int * m) { if(b < i || a > j) { return ; } if(a <= i && b >= j) { if(m[node] == 0) { m[node] = 1 ; } else if(m[node] == 1) { m[node] = 0 ; } else { flip(2 * node , a , b , i , (i + j) / 2 , m) ; flip(2 * node + 1 , a , b , (i + j) / 2 + 1 , j , m) ; if(m[2 * node] == m[2 * node + 1]) m[node] = m[2 * node] ; else m[node] = -1 ; } } else { flip(2 * node , a , b , i , (i + j) / 2 , m) ; flip(2 * node + 1 , a , b , (i + j) / 2 + 1 , j , m) ; if(m[2 * node] == m[2 * node + 1]) m[node] = m[2 * node] ; else m[node] = -1 ; } } int count(int node , int a , int b , int i , int j , int * m) { if(b < i || a > j) { return 0 ; } if(a <= i && b >= j) { if(m[node] == 0) return 0 ; else if(m[node] == 1) return j - i + 1 ; else { return count(2 * node , a , b , i , (i + j) / 2 , m) + count(2 * node + 1 , a , b , (i + j) / 2 + 1 , j , m) ; } } else { return count(2 * node , a , b , i , (i + j) / 2 , m) + count(2 * node + 1 , a , b , (i + j) / 2 + 1 , j , m) ; } } int main () { int n , q , a , b , t ; scanf("%d" , &n) ; scanf("%d" , &q) ; int p[n] ; for(int i = 0 ; i < n ; i++) p[i] = 0 ; int m[2 * n] ; for(int i = 1 ; i <= 2 * n ; i++) m[i] = 0 ; while(q--) { scanf("%d" , &t) ; scanf("%d" , &a) ; scanf("%d" , &b) ; if(t == 0) { flip(1 , a , b , 0 , n - 1 , m) ; } else { int c = count(1 , a , b , 0 , n - 1 , m) ; printf("%d\n" , c) ; } } }
4649cb7e9ebdf80f19a2a5fcb306f73de591c545
553a22eb54b2bc5df030d0c72d4a74ac4003aa4e
/tahook.h
3dddc5ce398b30ca8a0bd9f8ceae537cd53c77f9
[]
no_license
jchristi/taddraw
d2cffaae01c660351e0f56235671e9d2fad6e0a1
b52868b1f5ffede884c9c0ea46fb11b105d24f2b
refs/heads/master
2016-09-06T14:36:20.774557
2015-05-30T16:11:35
2015-05-30T16:11:35
35,358,173
2
0
null
null
null
null
UTF-8
C++
false
false
2,896
h
#ifndef tahookH #define tahookH #include "tamem.h" #define ShareMacro 1 #define DTLine 2 #define ScrolledDTLine 3 #define DTRing 4 #define SCROLL 10000 struct QueMSG { UINT Message; WPARAM wParam; LPARAM lParam; }; class InlineSingleHook; typedef struct tagInlineX86StackBuffer InlineX86StackBuffer, * PInlineX86StackBuffer; typedef int (__stdcall * InlineX86HookRouter) (PInlineX86StackBuffer X86StrackBuffer); class CTAHook { private: TAdynmemStruct *TAdynmem; int VirtualKeyCode; char ShareText[1000]; bool OptimizeRows; bool FullRingsEnabled; QueMSG MessageQueue[1000]; int QueuePos; int QueueLength; //void QueueMessage(UINT M, WPARAM W, LPARAM L); //void SendQueued(); void WriteDTLine(); void CalculateLine(); void OptimizeDTRows(); void VisualizeRow(); void WriteScrollDTLine(); unsigned int SendMessage; int Delay; bool WriteLine; int StartX, StartY; int EndX, EndY; int FootPrintX; int FootPrintY; int Spacing; int QueueStatus; void UpdateSpacing(); short XMatrix[1000]; short YMatrix[1000]; int MouseOverUnit; int MatrixLength; int Direction; LPDIRECTDRAWSURFACE lpRectSurf; bool ScrollEnabled; bool RingWrite; void CalculateRing(); void CalculateRing(int posx, int posy, int footx, int footy); void FindConnectedSquare(int &x1, int &y1, int &x2, int &y2, char *unittested); //void VisualizeRing(LPDIRECTDRAWSURFACE DestSurf); void ClickBuilding(int Xpos, int Ypos); short GetFootX(); short GetFootY(); void DrawBuildRect(int posx, int posy, int sizex, int sizey, int color); void EnableTABuildRect(); void DisableTABuildRect(); void PaintMinimapRect(); void (__stdcall *ShowText)(PlayerStruct *Player, char *Text, int Unk1, int Unk2); void (__stdcall *InterpretCommand)(char *Command, int Access); void (__stdcall *TAMapClick)(void *msgstruct); void (__stdcall *TestBuildSpot)(void); void (__stdcall *TADrawRect)(tagRECT *unk, tagRECT *rect, int color); unsigned short (__stdcall *FindMouseUnit)(void); int (__stdcall *SendText)(char *Text, int Type); //int StartMapX; //int StartMapY; //int EndMapX; //int EndMapY; //int *MapX; //int *MapY; struct msgstruct{ int xpos; int ypos; int shiftstatus; //should be 5 for shiftclick }; public: CTAHook(); ~CTAHook(); bool Message(HWND WinProcWnd, UINT Msg, WPARAM wParam, LPARAM lParam); void Set(int KeyCodei, char *ChatMacroi, bool FullRingsi, bool VisualizeRowsi, int iDelay); void WriteShareMacro(); void Blit(LPDIRECTDRAWSURFACE DestSurf); void TABlit(); BOOL IsLineBuilding (void); void VisualizeRow_ForME_megamap (OFFSCREEN * argc); //addtion public: HWND TAhWnd; }; #endif
[ "xpoy@d74ebf05-6d01-4e7b-8b90-17afc8ece2ee" ]
xpoy@d74ebf05-6d01-4e7b-8b90-17afc8ece2ee
0b2a31bc9f72d572c71604ab4807ae797dcb671a
ae2b5043e288f6129a895373515f5db81d3a36a7
/xulrunner-sdk/include/nsIDOMXPathResult.h
d5307d3e234d2b4f5968952647c0172c897fb277
[]
no_license
gh4ck3r/FirefoxOSInsight
c1307c82c2a4075648499ff429363f600c47276c
a7f3d9b6e557e229ddd70116ed2d27c4a553b314
refs/heads/master
2021-01-01T06:33:16.046113
2013-11-20T11:28:07
2013-11-20T11:28:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,662
h
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM /builds/slave/rel-m-rel-xr_lx_bld-0000000000/build/dom/interfaces/xpath/nsIDOMXPathResult.idl */ #ifndef __gen_nsIDOMXPathResult_h__ #define __gen_nsIDOMXPathResult_h__ #ifndef __gen_domstubs_h__ #include "domstubs.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif class XPathException; /* forward declaration */ /* starting interface: nsIDOMXPathResult */ #define NS_IDOMXPATHRESULT_IID_STR "75506f84-b504-11d5-a7f2-ca108ab8b6fc" #define NS_IDOMXPATHRESULT_IID \ {0x75506f84, 0xb504, 0x11d5, \ { 0xa7, 0xf2, 0xca, 0x10, 0x8a, 0xb8, 0xb6, 0xfc }} class NS_NO_VTABLE nsIDOMXPathResult : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMXPATHRESULT_IID) enum { ANY_TYPE = 0U, NUMBER_TYPE = 1U, STRING_TYPE = 2U, BOOLEAN_TYPE = 3U, UNORDERED_NODE_ITERATOR_TYPE = 4U, ORDERED_NODE_ITERATOR_TYPE = 5U, UNORDERED_NODE_SNAPSHOT_TYPE = 6U, ORDERED_NODE_SNAPSHOT_TYPE = 7U, ANY_UNORDERED_NODE_TYPE = 8U, FIRST_ORDERED_NODE_TYPE = 9U }; /* readonly attribute unsigned short resultType; */ NS_IMETHOD GetResultType(uint16_t *aResultType) = 0; /* readonly attribute double numberValue; */ NS_IMETHOD GetNumberValue(double *aNumberValue) = 0; /* readonly attribute DOMString stringValue; */ NS_IMETHOD GetStringValue(nsAString & aStringValue) = 0; /* readonly attribute boolean booleanValue; */ NS_IMETHOD GetBooleanValue(bool *aBooleanValue) = 0; /* readonly attribute nsIDOMNode singleNodeValue; */ NS_IMETHOD GetSingleNodeValue(nsIDOMNode * *aSingleNodeValue) = 0; /* readonly attribute boolean invalidIteratorState; */ NS_IMETHOD GetInvalidIteratorState(bool *aInvalidIteratorState) = 0; /* readonly attribute unsigned long snapshotLength; */ NS_IMETHOD GetSnapshotLength(uint32_t *aSnapshotLength) = 0; /* nsIDOMNode iterateNext () raises (XPathException,DOMException); */ NS_IMETHOD IterateNext(nsIDOMNode * *_retval) = 0; /* nsIDOMNode snapshotItem (in unsigned long index) raises (XPathException); */ NS_IMETHOD SnapshotItem(uint32_t index, nsIDOMNode * *_retval) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMXPathResult, NS_IDOMXPATHRESULT_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIDOMXPATHRESULT \ NS_IMETHOD GetResultType(uint16_t *aResultType); \ NS_IMETHOD GetNumberValue(double *aNumberValue); \ NS_IMETHOD GetStringValue(nsAString & aStringValue); \ NS_IMETHOD GetBooleanValue(bool *aBooleanValue); \ NS_IMETHOD GetSingleNodeValue(nsIDOMNode * *aSingleNodeValue); \ NS_IMETHOD GetInvalidIteratorState(bool *aInvalidIteratorState); \ NS_IMETHOD GetSnapshotLength(uint32_t *aSnapshotLength); \ NS_IMETHOD IterateNext(nsIDOMNode * *_retval); \ NS_IMETHOD SnapshotItem(uint32_t index, nsIDOMNode * *_retval); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIDOMXPATHRESULT(_to) \ NS_IMETHOD GetResultType(uint16_t *aResultType) { return _to GetResultType(aResultType); } \ NS_IMETHOD GetNumberValue(double *aNumberValue) { return _to GetNumberValue(aNumberValue); } \ NS_IMETHOD GetStringValue(nsAString & aStringValue) { return _to GetStringValue(aStringValue); } \ NS_IMETHOD GetBooleanValue(bool *aBooleanValue) { return _to GetBooleanValue(aBooleanValue); } \ NS_IMETHOD GetSingleNodeValue(nsIDOMNode * *aSingleNodeValue) { return _to GetSingleNodeValue(aSingleNodeValue); } \ NS_IMETHOD GetInvalidIteratorState(bool *aInvalidIteratorState) { return _to GetInvalidIteratorState(aInvalidIteratorState); } \ NS_IMETHOD GetSnapshotLength(uint32_t *aSnapshotLength) { return _to GetSnapshotLength(aSnapshotLength); } \ NS_IMETHOD IterateNext(nsIDOMNode * *_retval) { return _to IterateNext(_retval); } \ NS_IMETHOD SnapshotItem(uint32_t index, nsIDOMNode * *_retval) { return _to SnapshotItem(index, _retval); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIDOMXPATHRESULT(_to) \ NS_IMETHOD GetResultType(uint16_t *aResultType) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetResultType(aResultType); } \ NS_IMETHOD GetNumberValue(double *aNumberValue) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetNumberValue(aNumberValue); } \ NS_IMETHOD GetStringValue(nsAString & aStringValue) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetStringValue(aStringValue); } \ NS_IMETHOD GetBooleanValue(bool *aBooleanValue) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetBooleanValue(aBooleanValue); } \ NS_IMETHOD GetSingleNodeValue(nsIDOMNode * *aSingleNodeValue) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSingleNodeValue(aSingleNodeValue); } \ NS_IMETHOD GetInvalidIteratorState(bool *aInvalidIteratorState) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetInvalidIteratorState(aInvalidIteratorState); } \ NS_IMETHOD GetSnapshotLength(uint32_t *aSnapshotLength) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSnapshotLength(aSnapshotLength); } \ NS_IMETHOD IterateNext(nsIDOMNode * *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->IterateNext(_retval); } \ NS_IMETHOD SnapshotItem(uint32_t index, nsIDOMNode * *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->SnapshotItem(index, _retval); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsDOMXPathResult : public nsIDOMXPathResult { public: NS_DECL_ISUPPORTS NS_DECL_NSIDOMXPATHRESULT nsDOMXPathResult(); private: ~nsDOMXPathResult(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsDOMXPathResult, nsIDOMXPathResult) nsDOMXPathResult::nsDOMXPathResult() { /* member initializers and constructor code */ } nsDOMXPathResult::~nsDOMXPathResult() { /* destructor code */ } /* readonly attribute unsigned short resultType; */ NS_IMETHODIMP nsDOMXPathResult::GetResultType(uint16_t *aResultType) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute double numberValue; */ NS_IMETHODIMP nsDOMXPathResult::GetNumberValue(double *aNumberValue) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute DOMString stringValue; */ NS_IMETHODIMP nsDOMXPathResult::GetStringValue(nsAString & aStringValue) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute boolean booleanValue; */ NS_IMETHODIMP nsDOMXPathResult::GetBooleanValue(bool *aBooleanValue) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute nsIDOMNode singleNodeValue; */ NS_IMETHODIMP nsDOMXPathResult::GetSingleNodeValue(nsIDOMNode * *aSingleNodeValue) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute boolean invalidIteratorState; */ NS_IMETHODIMP nsDOMXPathResult::GetInvalidIteratorState(bool *aInvalidIteratorState) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute unsigned long snapshotLength; */ NS_IMETHODIMP nsDOMXPathResult::GetSnapshotLength(uint32_t *aSnapshotLength) { return NS_ERROR_NOT_IMPLEMENTED; } /* nsIDOMNode iterateNext () raises (XPathException,DOMException); */ NS_IMETHODIMP nsDOMXPathResult::IterateNext(nsIDOMNode * *_retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* nsIDOMNode snapshotItem (in unsigned long index) raises (XPathException); */ NS_IMETHODIMP nsDOMXPathResult::SnapshotItem(uint32_t index, nsIDOMNode * *_retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_nsIDOMXPathResult_h__ */
f58ffee99aa4ef99e9dc7af5cb04747a3bdd23e2
44243644a043acf539498840d5e5ae8df20a1fe9
/Section 17/parallel/parallel.cpp
5eba8a8f1031d907ada665d600cb16d69d670998
[ "MIT" ]
permissive
tiagogomesti/beg_mod_cpp
37365b88c54eccd86b1befb1f705c56dc7cff367
f5fbeda349cf3f1894b7e2bef495ec0a4a2fa1b5
refs/heads/main
2023-06-07T03:18:49.106866
2021-06-12T08:39:06
2021-06-12T08:39:06
381,865,204
0
0
MIT
2021-07-01T00:24:17
2021-07-01T00:24:16
null
UTF-8
C++
false
false
1,242
cpp
#include <chrono> #include <iostream> #include <random> #include <string_view> #include <vector> #include <execution> class Timer { std::chrono::steady_clock::time_point m_start ; public: Timer():m_start{std::chrono::steady_clock::now()} { } void ShowResult(std::string_view message = "") { auto end = std::chrono::steady_clock::now() ; auto difference = end - m_start ; std::cout << message << ':' << std::chrono::duration_cast<std::chrono::nanoseconds>(difference).count() << '\n' ; } }; constexpr unsigned VEC_SIZE{100} ; std::vector<long> CreateVector() { std::vector<long> vec ; vec.reserve(VEC_SIZE) ; std::default_random_engine engine{std::random_device{}()} ; std::uniform_int_distribution<long> dist{0, VEC_SIZE} ; for(unsigned i = 0 ; i < VEC_SIZE ; ++i) { vec.push_back(dist(engine)) ; } return vec ; } int main() { auto dataset = CreateVector() ; Timer t ; std::sort(dataset.begin(), dataset.end()) ; //std::sort(std::execution::par, dataset.begin(), dataset.end()) ; // //auto result = std::accumulate(dataset.begin(), dataset.end(),0L) ; //auto result = std::reduce(dataset.begin(), dataset.end(),0L) ; t.ShowResult("Accumulate time") ; }
554eb4f5dfeff541e7837c53da7a91cea354a9b4
9daef1f90f0d8d9a7d6a02860d7f44912d9c6190
/Leetcode/Medium/36_valid_sudoku.cpp
4e50d9d4d316bc1b0cb7154feb8537be6a8f6f16
[]
no_license
gogokigen/Cpp17-DataStructure-and-Algorithm
b3a149fe3cb2a2a96f8a013f1fe32407a80f3cb8
5261178e17dce6c67edf436bfa3c0add0c5eb371
refs/heads/master
2023-08-06T10:27:58.347674
2021-02-04T13:27:37
2021-02-04T13:27:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,230
cpp
/******************************************************************* * https://leetcode.com/problems/valid-sudoku/ * Medium * * Conception: * 1. * * Determine if a 9x9 Sudoku board is valid. * * * Example: * * Key: * 1. * * Reference: * 1. https://leetcode.com/articles/valid-sudoku/# * *******************************************************************/ class Solution { public: bool isValidSudoku(vector<vector<char>>& board) { vector<vector<int>> rows(9 , vector<int> (9)); vector<vector<int>> columns(9 , vector<int> (9)); vector<vector<int>> boxes(9 , vector<int> (9)); for(int i = 0; i < 9; i++){ for(int j = 0; j < 9; j++){ char num = board[i][j]; if(num != '.'){ int n = num - '0'; n = n - 1; int box_idx = i / 3 + (j / 3) * 3; rows[i][n] += 1; columns[j][n] += 1; boxes[box_idx][n] += 1; if(rows[i][n] > 1 || columns[j][n] > 1 || boxes[box_idx][n]> 1){ return false; } } } } return true; } };
14a1601ea10629f7206566423dcfc0165fbb4d0f
d3ff0b1019c4a7bc8d7235bb6807ee75287d1405
/src/imgui.cpp
e8aea0929b3331c920433f0a8e4daadd52a140c7
[ "BSD-3-Clause", "LicenseRef-scancode-generic-cla" ]
permissive
traverseda/mahi-python
6d86b4b9d2eac08d99ff076074153f668becfdbc
cc02da6b25599001859695c34a0f9ea672f1842f
refs/heads/master
2022-11-26T14:57:38.170379
2020-07-28T13:47:34
2020-07-28T13:47:34
280,937,183
0
0
null
null
null
null
UTF-8
C++
false
false
68,303
cpp
/* Copyright (c) 2017-2018 Stanislav Pidhorskyi Copyright (c) 2019-2020 Joel Linn Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #define IMGUI_DEFINE_MATH_OPERATORS #include <imgui.h> #include <imgui_internal.h> #include <mutex> #include <pybind11/operators.h> #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include "imgui_helper.h" namespace py = pybind11; // "Smart pointer" that ensures pybind11 will not delete an object reference. template <typename T> struct leaked_ptr { leaked_ptr(T* p) : p(p) {} T* get() const { return p; } private: T* p; }; PYBIND11_DECLARE_HOLDER_TYPE(T, leaked_ptr<T>, true); void py_init_module_imgui_enums(py::module&); void py_init_module_imgui_classes(py::module&); void py_init_module_imgui_funcs(py::module&); void py_init_module_imgui(py::module& m) { py_init_module_imgui_enums(m); py_init_module_imgui_classes(m); py_init_module_imgui_funcs(m); } void py_init_module_imgui_enums(py::module& m) { py::enum_<ImGuiCond_>(m, "Condition", py::arithmetic()) .value("Always", ImGuiCond_::ImGuiCond_Always) .value("Once", ImGuiCond_::ImGuiCond_Once) .value("FirstUseEver", ImGuiCond_::ImGuiCond_FirstUseEver) .value("Appearing", ImGuiCond_::ImGuiCond_Appearing) .export_values(); py::enum_<ImGuiWindowFlags_>(m, "WindowFlags", py::arithmetic()) .value("NoTitleBar", ImGuiWindowFlags_::ImGuiWindowFlags_NoTitleBar) .value("NoResize", ImGuiWindowFlags_::ImGuiWindowFlags_NoResize) .value("NoMove", ImGuiWindowFlags_::ImGuiWindowFlags_NoMove) .value("NoScrollbar", ImGuiWindowFlags_::ImGuiWindowFlags_NoScrollbar) .value("NoScrollWithMouse", ImGuiWindowFlags_::ImGuiWindowFlags_NoScrollWithMouse) .value("NoCollapse", ImGuiWindowFlags_::ImGuiWindowFlags_NoCollapse) .value("AlwaysAutoResize", ImGuiWindowFlags_::ImGuiWindowFlags_AlwaysAutoResize) .value("NoBackground", ImGuiWindowFlags_::ImGuiWindowFlags_NoBackground) .value("NoSavedSettings", ImGuiWindowFlags_::ImGuiWindowFlags_NoSavedSettings) .value("NoMouseInputs", ImGuiWindowFlags_::ImGuiWindowFlags_NoMouseInputs) .value("MenuBar", ImGuiWindowFlags_::ImGuiWindowFlags_MenuBar) .value("HorizontalScrollbar", ImGuiWindowFlags_::ImGuiWindowFlags_HorizontalScrollbar) .value("NoFocusOnAppearing", ImGuiWindowFlags_::ImGuiWindowFlags_NoFocusOnAppearing) .value("NoBringToFrontOnFocus", ImGuiWindowFlags_::ImGuiWindowFlags_NoBringToFrontOnFocus) .value("AlwaysVerticalScrollbar", ImGuiWindowFlags_::ImGuiWindowFlags_AlwaysVerticalScrollbar) .value("AlwaysHorizontalScrollbar", ImGuiWindowFlags_::ImGuiWindowFlags_AlwaysHorizontalScrollbar) .value("AlwaysUseWindowPadding", ImGuiWindowFlags_::ImGuiWindowFlags_AlwaysUseWindowPadding) .value("NoNavInputs", ImGuiWindowFlags_::ImGuiWindowFlags_NoNavInputs) .value("NoNavFocus", ImGuiWindowFlags_::ImGuiWindowFlags_NoNavFocus) .value("UnsavedDocument", ImGuiWindowFlags_::ImGuiWindowFlags_UnsavedDocument) .value("NoNav ", ImGuiWindowFlags_::ImGuiWindowFlags_NoNav) .value("NoDecoration", ImGuiWindowFlags_::ImGuiWindowFlags_NoDecoration) .value("NoInputs", ImGuiWindowFlags_::ImGuiWindowFlags_NoInputs) .export_values(); py::enum_<ImGuiInputTextFlags_>(m, "InputTextFlags", py::arithmetic()) .value("CharsDecimal", ImGuiInputTextFlags_::ImGuiInputTextFlags_CharsDecimal) .value("CharsHexadecimal", ImGuiInputTextFlags_::ImGuiInputTextFlags_CharsHexadecimal) .value("CharsUppercase", ImGuiInputTextFlags_::ImGuiInputTextFlags_CharsUppercase) .value("CharsNoBlank", ImGuiInputTextFlags_::ImGuiInputTextFlags_CharsNoBlank) .value("AutoSelectAll", ImGuiInputTextFlags_::ImGuiInputTextFlags_AutoSelectAll) .value("EnterReturnsTrue", ImGuiInputTextFlags_::ImGuiInputTextFlags_EnterReturnsTrue) //.value("CallbackCompletion", // ImGuiInputTextFlags_::ImGuiInputTextFlags_CallbackCompletion) //.value("CallbackHistory", // ImGuiInputTextFlags_::ImGuiInputTextFlags_CallbackHistory) //.value("CallbackAlways", // ImGuiInputTextFlags_::ImGuiInputTextFlags_CallbackAlways) //.value("CallbackCharFilter", // ImGuiInputTextFlags_::ImGuiInputTextFlags_CallbackCharFilter) .value("AllowTabInput", ImGuiInputTextFlags_::ImGuiInputTextFlags_AllowTabInput) .value("CtrlEnterForNewLine", ImGuiInputTextFlags_::ImGuiInputTextFlags_CtrlEnterForNewLine) .value("NoHorizontalScroll", ImGuiInputTextFlags_::ImGuiInputTextFlags_NoHorizontalScroll) .value("AlwaysInsertMode", ImGuiInputTextFlags_::ImGuiInputTextFlags_AlwaysInsertMode) .value("ReadOnly", ImGuiInputTextFlags_::ImGuiInputTextFlags_ReadOnly) .value("Password", ImGuiInputTextFlags_::ImGuiInputTextFlags_Password) //.value("NoUndoRedo", // ImGuiInputTextFlags_::ImGuiInputTextFlags_NoUndoRedo) .value("Multiline", ImGuiInputTextFlags_::ImGuiInputTextFlags_Multiline) .export_values(); py::enum_<ImGuiDir_>(m, "Direction") .value("None", ImGuiDir_::ImGuiDir_None) .value("Left", ImGuiDir_::ImGuiDir_Left) .value("Right", ImGuiDir_::ImGuiDir_Right) .value("Up", ImGuiDir_::ImGuiDir_Up) .value("Down", ImGuiDir_::ImGuiDir_Down); py::enum_<ImGuiCol_>(m, "Color") .value("Text", ImGuiCol_::ImGuiCol_Text) .value("TextDisabled", ImGuiCol_::ImGuiCol_TextDisabled) .value("WindowBg", ImGuiCol_::ImGuiCol_WindowBg) .value("ChildBg", ImGuiCol_::ImGuiCol_ChildBg) .value("PopupBg", ImGuiCol_::ImGuiCol_PopupBg) .value("Border", ImGuiCol_::ImGuiCol_Border) .value("BorderShadow", ImGuiCol_::ImGuiCol_BorderShadow) .value("FrameBg", ImGuiCol_::ImGuiCol_FrameBg) .value("FrameBgHovered", ImGuiCol_::ImGuiCol_FrameBgHovered) .value("FrameBgActive", ImGuiCol_::ImGuiCol_FrameBgActive) .value("TitleBg", ImGuiCol_::ImGuiCol_TitleBg) .value("TitleBgActive", ImGuiCol_::ImGuiCol_TitleBgActive) .value("TitleBgCollapsed", ImGuiCol_::ImGuiCol_TitleBgCollapsed) .value("MenuBarBg", ImGuiCol_::ImGuiCol_MenuBarBg) .value("ScrollbarBg", ImGuiCol_::ImGuiCol_ScrollbarBg) .value("ScrollbarGrab", ImGuiCol_::ImGuiCol_ScrollbarGrab) .value("ScrollbarGrabHovered", ImGuiCol_::ImGuiCol_ScrollbarGrabHovered) .value("ScrollbarGrabActive", ImGuiCol_::ImGuiCol_ScrollbarGrabActive) .value("CheckMark", ImGuiCol_::ImGuiCol_CheckMark) .value("SliderGrab", ImGuiCol_::ImGuiCol_SliderGrab) .value("SliderGrabActive", ImGuiCol_::ImGuiCol_SliderGrabActive) .value("Button", ImGuiCol_::ImGuiCol_Button) .value("ButtonHovered", ImGuiCol_::ImGuiCol_ButtonHovered) .value("ButtonActive", ImGuiCol_::ImGuiCol_ButtonActive) .value("Header", ImGuiCol_::ImGuiCol_Header) .value("HeaderHovered", ImGuiCol_::ImGuiCol_HeaderHovered) .value("HeaderActive", ImGuiCol_::ImGuiCol_HeaderActive) .value("Separator", ImGuiCol_::ImGuiCol_Separator) .value("SeparatorHovered", ImGuiCol_::ImGuiCol_SeparatorHovered) .value("SeparatorActive", ImGuiCol_::ImGuiCol_SeparatorActive) .value("ResizeGrip", ImGuiCol_::ImGuiCol_ResizeGrip) .value("ResizeGripHovered", ImGuiCol_::ImGuiCol_ResizeGripHovered) .value("ResizeGripActive", ImGuiCol_::ImGuiCol_ResizeGripActive) .value("Tab", ImGuiCol_::ImGuiCol_Tab) .value("TabHovered", ImGuiCol_::ImGuiCol_TabHovered) .value("TabActive", ImGuiCol_::ImGuiCol_TabActive) .value("TabUnfocused", ImGuiCol_::ImGuiCol_TabUnfocused) .value("TabUnfocusedActive", ImGuiCol_::ImGuiCol_TabUnfocusedActive) .value("PlotLines", ImGuiCol_::ImGuiCol_PlotLines) .value("PlotLinesHovered", ImGuiCol_::ImGuiCol_PlotLinesHovered) .value("PlotHistogram", ImGuiCol_::ImGuiCol_PlotHistogram) .value("PlotHistogramHovered", ImGuiCol_::ImGuiCol_PlotHistogramHovered) .value("TextSelectedBg", ImGuiCol_::ImGuiCol_TextSelectedBg) .value("DragDropTarget", ImGuiCol_::ImGuiCol_DragDropTarget) .value("NavHighlight", ImGuiCol_::ImGuiCol_NavHighlight) .value("NavWindowingHighlight", ImGuiCol_::ImGuiCol_NavWindowingHighlight) .value("NavWindowingDimBg", ImGuiCol_::ImGuiCol_NavWindowingDimBg) .value("ModalWindowDimBg", ImGuiCol_::ImGuiCol_ModalWindowDimBg) // Obsolete names (will be removed) .value("ChildWindowBg", ImGuiCol_::ImGuiCol_ChildBg) .value("ModalWindowDarkening", ImGuiCol_::ImGuiCol_ModalWindowDimBg) .export_values(); py::enum_<ImGuiStyleVar_>(m, "StyleVar") .value("Alpha", ImGuiStyleVar_::ImGuiStyleVar_Alpha) .value("WindowPadding", ImGuiStyleVar_::ImGuiStyleVar_WindowPadding) .value("WindowRounding", ImGuiStyleVar_::ImGuiStyleVar_WindowRounding) .value("WindowBorderSize", ImGuiStyleVar_::ImGuiStyleVar_WindowBorderSize) .value("WindowMinSize", ImGuiStyleVar_::ImGuiStyleVar_WindowMinSize) .value("WindowTitleAlign", ImGuiStyleVar_::ImGuiStyleVar_WindowTitleAlign) .value("ChildRounding", ImGuiStyleVar_::ImGuiStyleVar_ChildRounding) .value("ChildBorderSize", ImGuiStyleVar_::ImGuiStyleVar_ChildBorderSize) .value("PopupRounding", ImGuiStyleVar_::ImGuiStyleVar_PopupRounding) .value("PopupBorderSize", ImGuiStyleVar_::ImGuiStyleVar_PopupBorderSize) .value("FramePadding", ImGuiStyleVar_::ImGuiStyleVar_FramePadding) .value("FrameRounding", ImGuiStyleVar_::ImGuiStyleVar_FrameRounding) .value("FrameBorderSize", ImGuiStyleVar_::ImGuiStyleVar_FrameBorderSize) .value("ItemSpacing", ImGuiStyleVar_::ImGuiStyleVar_ItemSpacing) .value("ItemInnerSpacing", ImGuiStyleVar_::ImGuiStyleVar_ItemInnerSpacing) .value("IndentSpacing", ImGuiStyleVar_::ImGuiStyleVar_IndentSpacing) .value("ScrollbarSize", ImGuiStyleVar_::ImGuiStyleVar_ScrollbarSize) .value("ScrollbarRounding", ImGuiStyleVar_::ImGuiStyleVar_ScrollbarRounding) .value("GrabMinSize", ImGuiStyleVar_::ImGuiStyleVar_GrabMinSize) .value("GrabRounding", ImGuiStyleVar_::ImGuiStyleVar_GrabRounding) .value("TabRounding", ImGuiStyleVar_::ImGuiStyleVar_TabRounding) .value("ButtonTextAlign", ImGuiStyleVar_::ImGuiStyleVar_ButtonTextAlign) .value("SelectableTextAlign", ImGuiStyleVar_::ImGuiStyleVar_SelectableTextAlign) .export_values(); py::enum_<ImGuiFocusedFlags_>(m, "FocusedFlags") .value("None", ImGuiFocusedFlags_None) .value("ChildWindows", ImGuiFocusedFlags_ChildWindows) .value("RootWindow", ImGuiFocusedFlags_RootWindow) .value("AnyWindow", ImGuiFocusedFlags_AnyWindow) .value("RootAndChildWindows", ImGuiFocusedFlags_RootAndChildWindows) .export_values(); py::enum_<ImGuiHoveredFlags_>(m, "HoveredFlags") .value("None", ImGuiHoveredFlags_None) .value("ChildWindows", ImGuiHoveredFlags_ChildWindows) .value("RootWindow", ImGuiHoveredFlags_RootWindow) .value("AnyWindow", ImGuiHoveredFlags_AnyWindow) .value("AllowWhenBlockedByPopup", ImGuiHoveredFlags_AllowWhenBlockedByPopup) .value("AllowWhenBlockedByActiveItem", ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) .value("AllowWhenOverlapped", ImGuiHoveredFlags_AllowWhenOverlapped) .value("AllowWhenDisabled", ImGuiHoveredFlags_AllowWhenDisabled) .value("RectOnly", ImGuiHoveredFlags_RectOnly) .export_values(); py::enum_<ImDrawCornerFlags_>(m, "CornerFlags", py::arithmetic()) .value("TopLeft", ImDrawCornerFlags_TopLeft) .value("TopRight", ImDrawCornerFlags_TopRight) .value("BotRight", ImDrawCornerFlags_BotRight) .value("BotLeft", ImDrawCornerFlags_BotLeft) .value("Top", ImDrawCornerFlags_Top) .value("Bot", ImDrawCornerFlags_Bot) .value("Left", ImDrawCornerFlags_Left) .value("Right", ImDrawCornerFlags_Right) .value("All", ImDrawCornerFlags_All) .export_values(); } void py_init_module_imgui_classes(py::module& m) { py::class_<Bool>(m, "Bool") .def(py::init()) .def(py::init<bool>()) .def_readwrite("value", &Bool::value); py::class_<Float>(m, "Float") .def(py::init()) .def(py::init<float>()) .def_readwrite("value", &Float::value); py::class_<Int>(m, "Int") .def(py::init()) .def(py::init<int>()) .def_readwrite("value", &Int::value); py::class_<String>(m, "String") .def(py::init()) .def(py::init<std::string>()) .def_readwrite("value", &String::value); py::class_<ImVec2>(m, "Vec2") .def(py::init()) .def(py::init<float, float>()) .def_readwrite("x", &ImVec2::x) .def_readwrite("y", &ImVec2::y) .def(py::self * float()) .def(py::self / float()) .def(py::self + py::self) .def(py::self - py::self) .def(py::self * py::self) .def(py::self / py::self) .def(py::self += py::self) .def(py::self -= py::self) .def(py::self *= float()) .def(py::self /= float()) .def( "__mul__", [](float b, const ImVec2& a) { return a * b; }, py::is_operator()); py::class_<ImVec4>(m, "Vec4") .def(py::init()) .def(py::init<float, float, float, float>()) .def_readwrite("x", &ImVec4::x) .def_readwrite("y", &ImVec4::y) .def_readwrite("z", &ImVec4::z) .def_readwrite("w", &ImVec4::w) .def(py::self + py::self) .def(py::self - py::self) .def( "__mul__", [](const ImVec4& a, float b) { return ImVec4(a.x * b, a.y * b, a.z * b, a.w * b); }, py::is_operator()) .def( "__rmul__", [](const ImVec4& a, float b) { return ImVec4(a.x * b, a.y * b, a.z * b, a.w * b); }, py::is_operator()); py::class_<ImGuiStyle>(m, "Style") .def(py::init()) .def_readwrite("alpha", &ImGuiStyle::Alpha) .def_readwrite("window_padding", &ImGuiStyle::WindowPadding) .def_readwrite("window_rounding", &ImGuiStyle::WindowRounding) .def_readwrite("window_border_size", &ImGuiStyle::WindowBorderSize) .def_readwrite("window_min_size", &ImGuiStyle::WindowMinSize) .def_readwrite("window_title_align", &ImGuiStyle::WindowTitleAlign) .def_readwrite("window_menu_button_position", &ImGuiStyle::WindowMenuButtonPosition) .def_readwrite("child_rounding", &ImGuiStyle::ChildRounding) .def_readwrite("child_border_size", &ImGuiStyle::ChildBorderSize) .def_readwrite("popup_rounding", &ImGuiStyle::PopupRounding) .def_readwrite("popup_border_size", &ImGuiStyle::PopupBorderSize) .def_readwrite("frame_padding", &ImGuiStyle::FramePadding) .def_readwrite("frame_rounding", &ImGuiStyle::FrameRounding) .def_readwrite("frame_border_size", &ImGuiStyle::FrameBorderSize) .def_readwrite("item_spacing", &ImGuiStyle::ItemSpacing) .def_readwrite("item_inner_spacing", &ImGuiStyle::ItemInnerSpacing) .def_readwrite("touch_extra_spacing", &ImGuiStyle::TouchExtraPadding) .def_readwrite("indent_spacing", &ImGuiStyle::IndentSpacing) .def_readwrite("columns_min_spacing", &ImGuiStyle::ColumnsMinSpacing) .def_readwrite("scroll_bar_size", &ImGuiStyle::ScrollbarSize) .def_readwrite("scroll_bar_rounding", &ImGuiStyle::ScrollbarRounding) .def_readwrite("grab_min_size", &ImGuiStyle::GrabMinSize) .def_readwrite("grab_rounding", &ImGuiStyle::GrabRounding) .def_readwrite("tab_rounding", &ImGuiStyle::TabRounding) .def_readwrite("tab_border_size", &ImGuiStyle::TabBorderSize) .def_readwrite("color_button_position", &ImGuiStyle::ColorButtonPosition) .def_readwrite("button_text_align", &ImGuiStyle::ButtonTextAlign) .def_readwrite("selectable_text_align", &ImGuiStyle::SelectableTextAlign) .def_readwrite("display_window_padding", &ImGuiStyle::DisplayWindowPadding) .def_readwrite("display_safe_area_padding", &ImGuiStyle::DisplaySafeAreaPadding) .def_readwrite("mouse_cursor_scale", &ImGuiStyle::MouseCursorScale) .def_readwrite("anti_aliased_lines", &ImGuiStyle::AntiAliasedLines) .def_readwrite("anti_aliased_fill", &ImGuiStyle::AntiAliasedFill) .def_readwrite("curve_tessellation_tol", &ImGuiStyle::CurveTessellationTol) .def("get_color", [](ImGuiStyle& self, ImGuiCol_ a) { return self.Colors[(int)a]; }) .def("set_color", [](ImGuiStyle& self, ImGuiCol_ a, ImVec4 c) { self.Colors[(int)a] = c; }); #define DEF_IO_PROPERTY_PCHAR_BUT_NULL(__py_name__, __c_name__) \ .def_property( \ #__py_name__, \ [](const ImGuiIO& self) -> const char* { return self.__c_name__; }, \ [](ImGuiIO& self, const char* s) { \ if (s) { \ throw std::invalid_argument("Setting this value to anything but " \ "None is currently unsupported."); \ } \ /* disable if desired */ \ self.__c_name__ = nullptr; \ }) py::class_<ImGuiIO, leaked_ptr<ImGuiIO>>(m, "IO") .def_readwrite("config_flags", &ImGuiIO::ConfigFlags) .def_readwrite("backend_flags", &ImGuiIO::BackendFlags) .def_readwrite("display_size", &ImGuiIO::DisplaySize) .def_readwrite("delta_time", &ImGuiIO::DeltaTime) .def_readwrite("ini_saving_rate", &ImGuiIO::IniSavingRate) DEF_IO_PROPERTY_PCHAR_BUT_NULL(ini_filename, IniFilename) DEF_IO_PROPERTY_PCHAR_BUT_NULL(log_filename, LogFilename) .def_readwrite("mouse_double_click_time", &ImGuiIO::MouseDoubleClickTime) .def_readwrite("mouse_double_click_max_dist", &ImGuiIO::MouseDoubleClickMaxDist) .def_readwrite("mouse_drag_threshold", &ImGuiIO::MouseDragThreshold) //.def_readwrite("key_map", &ImGuiIO::KeyMap[ImGuiKey_COUNT]) .def_readwrite("key_repeat_delay", &ImGuiIO::KeyRepeatDelay) .def_readwrite("key_repeat_rate", &ImGuiIO::KeyRepeatRate) .def_readwrite("user_data", &ImGuiIO::UserData) // ====================================================================== //.def_readwrite("fonts" &ImGuiIO::Fonts) .def_readwrite("font_global_scale", &ImGuiIO::FontGlobalScale) .def_readwrite("font_allow_user_scaling", &ImGuiIO::FontAllowUserScaling) //.def_readwrite("font_default", &ImGuiIO::FontDefault) .def_readwrite("display_framebuffer_scale", &ImGuiIO::DisplayFramebufferScale) // ====================================================================== .def_readwrite("config_docking_no_split", &ImGuiIO::ConfigDockingNoSplit) .def_readwrite("config_docking_with_shift", &ImGuiIO::ConfigDockingWithShift) .def_readwrite("config_docking_always_tab_bar", &ImGuiIO::ConfigDockingAlwaysTabBar) .def_readwrite("config_docking_transparent_payload", &ImGuiIO::ConfigDockingTransparentPayload) // ====================================================================== .def_readwrite("config_viewports_no_auto_merge", &ImGuiIO::ConfigViewportsNoAutoMerge) .def_readwrite("config_viewports_no_task_bar_icon", &ImGuiIO::ConfigViewportsNoTaskBarIcon) .def_readwrite("config_viewports_no_decoration", &ImGuiIO::ConfigViewportsNoDecoration) .def_readwrite("config_viewports_no_default_parent", &ImGuiIO::ConfigViewportsNoDefaultParent) // ====================================================================== .def_readwrite("mouse_draw_cursor", &ImGuiIO::MouseDrawCursor) .def_readwrite("config_macosx_behaviours", &ImGuiIO::ConfigMacOSXBehaviors) .def_readwrite("config_input_text_cursor_blink", &ImGuiIO::ConfigInputTextCursorBlink) .def_readwrite("config_windows_resize_from_edges", &ImGuiIO::ConfigWindowsResizeFromEdges) .def_readwrite("config_windows_move_from_title_bar_only", &ImGuiIO::ConfigWindowsMoveFromTitleBarOnly) .def_readwrite("config_windows_memory_compact_timer", &ImGuiIO::ConfigWindowsMemoryCompactTimer) // ====================================================================== .def_readonly("backend_platform_name", &ImGuiIO::BackendPlatformName) .def_readonly("backend_renderer_name", &ImGuiIO::BackendRendererName) //.def_readwrite("backend_platform_user_data", //&ImGuiIO::BackendPlatformUserData) //.def_readwrite("backend_renderer_user_data", //&ImGuiIO::BackendRendererUserData) //.def_readwrite("backend_language_user_data", //&ImGuiIO::BackendLanguageUserData) // ====================================================================== // GetClipboardTextFn // SetClipboardTextFn // ClipboardUserData // ====================================================================== .def_readwrite("mouse_pos", &ImGuiIO::MousePos) //.def_readwrite("", &ImGuiIO::MouseDown[5]) .def_readwrite("mouse_wheel", &ImGuiIO::MouseWheel) .def_readwrite("mouse_wheel_h", &ImGuiIO::MouseWheelH) .def_readwrite("mouse_hovered_viewport", &ImGuiIO::MouseHoveredViewport) .def_readwrite("key_ctrl", &ImGuiIO::KeyCtrl) .def_readwrite("key_shift", &ImGuiIO::KeyShift) .def_readwrite("key_alt", &ImGuiIO::KeyAlt) .def_readwrite("key_super", &ImGuiIO::KeySuper) //.def_readwrite("keys_down", &ImGuiIO::KeysDown[512]) //.def_readwrite("nav_inputs", &ImGuiIO::NavInputs[ImGuiNavInput_COUNT]) // ====================================================================== .def("add_input_character", &ImGuiIO::AddInputCharacter, py::arg("c")) .def("add_input_character_utf8", &ImGuiIO::AddInputCharactersUTF8, py::arg("str")) .def("clear_input_characters", &ImGuiIO::ClearInputCharacters) // ====================================================================== .def_readwrite("want_capture_mouse", &ImGuiIO::WantCaptureMouse) .def_readwrite("want_capture_keyboard", &ImGuiIO::WantCaptureKeyboard) .def_readwrite("want_text_input", &ImGuiIO::WantTextInput) .def_readwrite("want_set_mouse_pos", &ImGuiIO::WantSetMousePos) .def_readwrite("want_save_ini_settings", &ImGuiIO::WantSaveIniSettings) .def_readwrite("nav_active", &ImGuiIO::NavActive) .def_readwrite("nav_visible", &ImGuiIO::NavVisible) .def_readwrite("framerate", &ImGuiIO::Framerate) .def_readwrite("metrics_render_vertices", &ImGuiIO::MetricsRenderVertices) .def_readwrite("metrics_render_indices", &ImGuiIO::MetricsRenderIndices) .def_readwrite("metrics_render_windows", &ImGuiIO::MetricsRenderWindows) .def_readwrite("metrics_active_windows", &ImGuiIO::MetricsActiveWindows) .def_readwrite("metrics_active_allocations", &ImGuiIO::MetricsActiveAllocations) .def_readwrite("mouse_delta", &ImGuiIO::MouseDelta) // ====================================================================== // INTERNAL ; } void py_init_module_imgui_funcs(py::module& m) { m.def("get_io", []() -> leaked_ptr<ImGuiIO> { // Does NOT copy the object to python scope and // does NOT free when out of scope. // The ImGuiIO pointer is valid as long as the ImGui context is valid. return leaked_ptr<ImGuiIO>(&ImGui::GetIO()); }); m.def("get_style", &ImGui::GetStyle); m.def("set_style", [](const ImGuiStyle& a) { ImGui::GetStyle() = a; }); m.def("style_colors_classic", []() { ImGui::StyleColorsClassic(); }); m.def("style_colors_dark", []() { ImGui::StyleColorsDark(); }); m.def("style_colors_light", []() { ImGui::StyleColorsLight(); }); m.def( "show_demo_window", []() { ImGui::ShowDemoWindow(); }, "create demo/test window (previously called ShowTestWindow). demonstrate " "most ImGui features."); m.def( "show_about_window", []() { ImGui::ShowAboutWindow(); }, "create About window. display Dear ImGui version, credits and " "build/system information."); m.def( "show_metrics_window", []() { ImGui::ShowMetricsWindow(); }, "create metrics window. display ImGui internals: draw commands (with " "individual draw calls and vertices), window list, basic internal state, " "etc."); m.def( "show_style_editor", []() { ImGui::ShowStyleEditor(); }, "add style editor block (not a window). you can pass in a reference " "ImGuiStyle structure to compare to, revert to and save to (else it uses " "the default style)"); m.def( "show_style_selector", [](const char* label) { ImGui::ShowStyleSelector(label); }, "add style selector block (not a window), essentially a combo listing " "the default styles."); m.def( "show_font_selector", [](const char* label) { ImGui::ShowFontSelector(label); }, "add font selector block (not a window), essentially a combo listing the " "loaded fonts."); m.def( "show_user_guide", []() { ImGui::ShowUserGuide(); }, "add basic help/info block (not a window): how to manipulate ImGui as a " "end-user (mouse/keyboard controls)."); m.def( "begin", [](const std::string& name, Bool& opened, ImGuiWindowFlags flags) -> bool { return ImGui::Begin(name.c_str(), opened.null ? nullptr : &opened.value, flags); }, "Push a new ImGui window to add widgets to", py::arg("name"), py::arg("opened") = null, py::arg("flags") = ImGuiWindowFlags_(0)); m.def("end", &ImGui::End); m.def( "begin_child", [](const std::string& str_id, const ImVec2& size, bool border, ImGuiWindowFlags extra_flags) -> bool { return ImGui::BeginChild(str_id.c_str(), size, border); }, "begin a scrolling region. size==0.0f: use remaining window size, " "size<0.0f: use remaining window size minus abs(size). size>0.0f: fixed " "size. each axis can use a different mode, e.g. ImVec2(0,400).", py::arg("str_id"), py::arg("size") = ImVec2(0, 0), py::arg("border") = false, py::arg("extra_flags") = ImGuiWindowFlags_(0)); m.def("end_child", &ImGui::EndChild); m.def("begin_main_menu_bar", &ImGui::BeginMainMenuBar, "create and append to a full screen menu-bar. only call " "EndMainMenuBar() if this returns true!"); m.def("end_main_menu_bar", &ImGui::EndMainMenuBar); m.def("begin_menu_bar", &ImGui::BeginMenuBar, "append to menu-bar of current window (requires " "ImGuiWindowFlags_MenuBar flag set on parent window). only call " "EndMenuBar() if this returns true!"); m.def("end_menu_bar", &ImGui::EndMenuBar); m.def( "begin_menu", [](const std::string& name, Bool& enabled) -> bool { return ImGui::BeginMenu( name.c_str(), (bool*)(enabled.null ? nullptr : &enabled.value)); }, "create a sub-menu entry. only call EndMenu() if this returns true!", py::arg("name"), py::arg("enabled") = Bool(true)); m.def( "menu_item", [](const std::string& label, const std::string& shortcut, Bool& selected, bool enabled) -> bool { return ImGui::MenuItem(label.c_str(), shortcut.c_str(), selected.null ? nullptr : &selected.value, enabled); }, "return true when activated + toggle (*p_selected) if p_selected != NULL", py::arg("name"), py::arg("shortcut"), py::arg("selected") = Bool(false), py::arg("enabled") = true); m.def("end_menu", &ImGui::EndMenu); m.def("begin_tooltip", &ImGui::BeginTooltip); m.def("end_tooltip", &ImGui::EndTooltip); m.def("set_tooltip", [](const char* text) { ImGui::SetTooltip("%s", text); }); m.def( "open_popup", [](std::string str_id) { ImGui::OpenPopup(str_id.c_str()); }, "call to mark popup as open (don't call every frame!). popups are closed " "when user click outside, or if CloseCurrentPopup() is called within a " "BeginPopup()/EndPopup() block. By default, Selectable()/MenuItem() are " "calling CloseCurrentPopup(). Popup identifiers are relative to the " "current ID-stack (so OpenPopup and BeginPopup needs to be at the same " "level)."); m.def( "open_popup_on_item_click", [](std::string str_id = "", int mouse_button = 1) { ImGui::OpenPopupOnItemClick(str_id.c_str(), mouse_button); }, "helper to open popup when clicked on last item. return true when just " "opened."); m.def( "begin_popup", [](std::string str_id, ImGuiWindowFlags flags) -> bool { return ImGui::BeginPopup(str_id.c_str(), flags); }, "", py::arg("name"), py::arg("flags") = ImGuiWindowFlags_(0)); m.def( "begin_popup_modal", [](std::string name = "") -> bool { return ImGui::BeginPopupModal(name.c_str()); }, ""); // add more arguments later: m.def( "begin_popup_context_item", []() { ImGui::BeginPopupContextItem(); }, "helper to open and begin popup when clicked on last item. if you can " "pass a NULL str_id only if the previous item had an id. If you want to " "use that on a non-interactive item such as Text() you need to pass in " "an explicit ID here."); m.def( "begin_popup_context_window", []() { ImGui::BeginPopupContextWindow(); }, "helper to open and begin popup when clicked on current window."); m.def( "begin_popup_context_void", []() { ImGui::BeginPopupContextVoid(); }, "helper to open and begin popup when clicked in void (where there are no " "imgui windows)."); m.def("end_popup", &ImGui::EndPopup); m.def( "is_popup_open", [](std::string str_id = "") -> bool { return ImGui::IsPopupOpen(str_id.c_str()); }, ""); m.def("close_current_popup", &ImGui::CloseCurrentPopup); m.def("get_content_region_max", &ImGui::GetContentRegionMax); m.def("get_content_region_avail", &ImGui::GetContentRegionAvail); // OBSOLETED in 1.70 (from May 2019) m.def("get_content_region_avail_width", &ImGui::GetContentRegionAvailWidth); m.def("get_window_content_region_min", &ImGui::GetWindowContentRegionMin); m.def("get_window_content_region_max", &ImGui::GetWindowContentRegionMax); m.def("get_window_content_region_width", &ImGui::GetWindowContentRegionWidth); m.def("get_font_size", &ImGui::GetFontSize); m.def("set_window_font_scale", &ImGui::SetWindowFontScale); m.def("get_window_pos", &ImGui::GetWindowPos); m.def("get_window_size", &ImGui::GetWindowSize); m.def("get_window_width", &ImGui::GetWindowWidth); m.def("get_window_height", &ImGui::GetWindowHeight); m.def("is_window_collapsed", &ImGui::IsWindowCollapsed); m.def("is_window_appearing", &ImGui::IsWindowAppearing); m.def("is_window_focused", &ImGui::IsWindowFocused); m.def("is_window_hovered", &ImGui::IsWindowHovered); m.def("set_window_font_scale", &ImGui::SetWindowFontScale); m.def("set_next_window_pos", &ImGui::SetNextWindowPos, py::arg("pos"), py::arg("cond") = 0, py::arg("pivot") = ImVec2(0, 0)); m.def("set_next_window_size", &ImGui::SetNextWindowSize, py::arg("size"), py::arg("cond") = 0); m.def( "set_next_window_size_constraints", [](const ImVec2& size_min, const ImVec2& size_max) { ImGui::SetNextWindowSizeConstraints(size_min, size_max); }, py::arg("size_min"), py::arg("size_max") = 0); m.def("set_next_window_content_size", &ImGui::SetNextWindowContentSize, py::arg("size")); m.def("set_next_window_collapsed", &ImGui::SetNextWindowCollapsed, py::arg("collapsed"), py::arg("cond") = 0); m.def("set_next_window_focus", &ImGui::SetNextWindowFocus); m.def("set_next_window_bg_alpha", &ImGui::SetNextWindowBgAlpha, py::arg("alpha")); m.def("set_window_pos", py::overload_cast<const ImVec2&, ImGuiCond>(&ImGui::SetWindowPos), py::arg("pos"), py::arg("cond") = 0); m.def("set_window_size", py::overload_cast<const ImVec2&, ImGuiCond>(&ImGui::SetWindowSize), py::arg("size"), py::arg("cond") = 0); m.def("set_window_collapsed", py::overload_cast<bool, ImGuiCond>(&ImGui::SetWindowCollapsed), py::arg("collapsed"), py::arg("cond") = 0); m.def("set_window_pos", py::overload_cast<const char*, const ImVec2&, ImGuiCond>( &ImGui::SetWindowPos), py::arg("name"), py::arg("pos"), py::arg("cond") = 0); m.def("set_window_size", py::overload_cast<const char*, const ImVec2&, ImGuiCond>( &ImGui::SetWindowSize), py::arg("name"), py::arg("size"), py::arg("cond") = 0); m.def("set_window_collapsed", py::overload_cast<const char*, bool, ImGuiCond>( &ImGui::SetWindowCollapsed), py::arg("name"), py::arg("collapsed"), py::arg("cond") = 0); m.def( "set_window_focus", [](const char* name) { ImGui::SetWindowFocus(name); }, py::arg("name")); m.def("get_scroll_x", &ImGui::GetScrollX); m.def("get_scroll_y", &ImGui::GetScrollY); m.def("get_scroll_max_x", &ImGui::GetScrollMaxX); m.def("get_scroll_max_y", &ImGui::GetScrollMaxY); m.def( "set_scroll_x", [](float scroll_x) { ImGui::SetScrollX(scroll_x); }, py::arg("scroll_x")); m.def( "set_scroll_y", [](float scroll_y) { ImGui::SetScrollY(scroll_y); }, py::arg("scroll_y")); // OBSOLETED in 1.66 (from Sep 2018) m.def("set_scroll_here", &ImGui::SetScrollHere, py::arg("center_y_ratio") = 0.5f); m.def("set_scroll_here_x", &ImGui::SetScrollHereX, py::arg("center_x_ratio") = 0.5f); m.def("set_scroll_here_y", &ImGui::SetScrollHereY, py::arg("center_y_ratio") = 0.5f); m.def( "set_scroll_from_pos_x", [](float pos_x, float center_x_ratio) { ImGui::SetScrollFromPosX(pos_x, center_x_ratio); }, py::arg("pos_x"), py::arg("center_x_ratio") = 0.5f); m.def( "set_scroll_from_pos_y", [](float pos_y, float center_y_ratio) { ImGui::SetScrollFromPosY(pos_y, center_y_ratio); }, py::arg("pos_y"), py::arg("center_y_ratio") = 0.5f); m.def("set_keyboard_focus_here", &ImGui::SetKeyboardFocusHere, py::arg("offset") = 0.0f); m.def("push_style_color", [](ImGuiCol_ idx, const ImVec4& col) { ImGui::PushStyleColor((ImGuiCol)idx, col); }); m.def("pop_style_color", &ImGui::PopStyleColor, py::arg("count") = 1); m.def("push_style_var", [](ImGuiStyleVar_ idx, float val) { ImGui::PushStyleVar((ImGuiStyleVar)idx, val); }); m.def("push_style_var", [](ImGuiStyleVar_ idx, ImVec2 val) { ImGui::PushStyleVar((ImGuiStyleVar)idx, val); }); m.def("pop_style_var", &ImGui::PopStyleVar, py::arg("count") = 1); m.def("push_item_width", &ImGui::PushItemWidth); m.def("pop_item_width", &ImGui::PopItemWidth); m.def("set_next_item_width", &ImGui::SetNextItemWidth); m.def("calc_item_width", &ImGui::CalcItemWidth); m.def("calc_text_size", &ImGui::CalcTextSize, py::arg("text"), py::arg("text_end") = nullptr, py::arg("hide_text_after_double_hash") = false, py::arg("wrap_width") = 0.0f); m.def("push_text_wrap_pos", &ImGui::PushTextWrapPos, py::arg("wrap_pos_x") = 0.0f); m.def("pop_text_wrap_pos", &ImGui::PopTextWrapPos); m.def("push_allow_keyboard_focus", &ImGui::PushAllowKeyboardFocus); m.def("pop_allow_keyboard_focus", &ImGui::PopAllowKeyboardFocus); m.def("push_button_repeat", &ImGui::PushButtonRepeat); m.def("pop_button_repeat", &ImGui::PopButtonRepeat); m.def("separator", &ImGui::Separator); m.def("same_line", &ImGui::SameLine, py::arg("local_pos_x") = 0.0f, py::arg("spacing_w") = -1.0f); m.def("new_line", &ImGui::NewLine); m.def("spacing", &ImGui::Spacing); m.def("dummy", &ImGui::Dummy); m.def("indent", &ImGui::Indent, py::arg("indent_w") = 0.0f); m.def("unindent", &ImGui::Unindent, py::arg("indent_w") = 0.0f); m.def("begin_group", &ImGui::BeginGroup); m.def("end_group", &ImGui::EndGroup); m.def("get_cursor_pos", &ImGui::GetCursorPos); m.def("get_cursor_pos_x", &ImGui::GetCursorPosX); m.def("get_cursor_pos_y", &ImGui::GetCursorPosY); m.def("set_cursor_pos", &ImGui::SetCursorPos); m.def("set_cursor_pos_x", &ImGui::SetCursorPosX); m.def("set_cursor_pos_y", &ImGui::SetCursorPosY); m.def("get_cursor_start_pos", &ImGui::GetCursorStartPos); m.def("get_cursor_screen_pos", &ImGui::GetCursorScreenPos); m.def("set_cursor_screen_pos", &ImGui::SetCursorScreenPos); m.def("align_text_to_frame_padding", &ImGui::AlignTextToFramePadding); m.def("get_text_line_height", &ImGui::GetTextLineHeight); m.def("get_text_line_height_with_spacing", &ImGui::GetTextLineHeightWithSpacing); m.def("get_frame_height", &ImGui::GetFrameHeight); m.def("get_frame_height_with_spacing", &ImGui::GetFrameHeightWithSpacing); m.def("columns", &ImGui::Columns, py::arg("count") = 1, py::arg("id") = nullptr, py::arg("border") = true); m.def("next_column", &ImGui::NextColumn); m.def("get_column_index", &ImGui::GetColumnIndex); m.def("get_column_offset", &ImGui::GetColumnOffset, py::arg("column_index") = -1); m.def("set_column_offset", &ImGui::SetColumnOffset, py::arg("column_index"), py::arg("offset_x")); m.def("get_column_width", &ImGui::GetColumnWidth, py::arg("column_index") = -1); m.def("set_column_width", &ImGui::SetColumnWidth, py::arg("column_index"), py::arg("column_width")); m.def("get_columns_count", &ImGui::GetColumnsCount); m.def("begin_tab_bar", &ImGui::BeginTabBar, py::arg("str_id"), py::arg("flags") = 0); m.def("end_tab_bar", &ImGui::EndTabBar); m.def( "begin_tab_item", [](const std::string& label, Bool& opened, ImGuiTabItemFlags flags) -> bool { return ImGui::BeginTabItem( label.c_str(), opened.null ? nullptr : &opened.value, flags); }, "create a Tab. Returns true if the Tab is selected.", py::arg("label"), py::arg("opened") = null, py::arg("flags") = 0); m.def("end_tab_item", &ImGui::EndTabItem); m.def("set_tab_item_closed", &ImGui::SetTabItemClosed, py::arg("tab_or_docked_window_label")); m.def( "push_id_str", [](const char* str_id_begin, const char* str_id_end) { ImGui::PushID(str_id_begin, str_id_end); }, py::arg("str_id_begin"), py::arg("str_id_end") = nullptr); m.def("push_id_int", [](int int_id) { ImGui::PushID(int_id); }); m.def("pop_id", &ImGui::PopID); m.def( "get_id_str", [](const char* str_id_begin, const char* str_id_end) { ImGui::GetID(str_id_begin, str_id_end); }, py::arg("str_id_begin"), py::arg("str_id_end") = nullptr); m.def("text", [](const char* text) { ImGui::Text("%s", text); }); m.def("text_colored", [](const ImVec4& col, const char* text) { ImGui::TextColored(col, "%s", text); }); m.def("text_disabled", [](const char* text) { ImGui::TextDisabled("%s", text); }); m.def("text_wrapped", [](const char* text) { ImGui::TextWrapped("%s", text); }); m.def("label_text", [](const char* label, const char* text) { ImGui::LabelText(label, "%s", text); }); m.def("bullet_text", [](const char* text) { ImGui::BulletText("%s", text); }); m.def("bullet", &ImGui::Bullet); m.def("button", &ImGui::Button, py::arg("label"), py::arg("size") = ImVec2(0, 0)); m.def("small_button", &ImGui::SmallButton); m.def("invisible_button", &ImGui::InvisibleButton); m.def( "tree_node", [](const char* label) { return ImGui::TreeNode(label); }, py::arg("label")); m.def("tree_pop", &ImGui::TreePop); // OBSOLETED in 1.71 (from June 2019) m.def("set_next_tree_node_open", &ImGui::SetNextTreeNodeOpen, py::arg("is_open"), py::arg("cond") = 0); m.def("set_next_item_open", &ImGui::SetNextItemOpen, py::arg("is_open"), py::arg("cond") = 0); m.def( "collapsing_header", [](const char* label, ImGuiTreeNodeFlags flags) { return ImGui::CollapsingHeader(label, flags); }, py::arg("label"), py::arg("flags") = 0); m.def("checkbox", [](const char* label, Bool& v) { return ImGui::Checkbox(label, &v.value); }); m.def("radio_button", [](const char* label, bool active) { return ImGui::RadioButton(label, active); }); m.def("begin_combo", &ImGui::BeginCombo, py::arg("label"), py::arg("preview_value"), py::arg("flags") = 0); m.def("end_combo", &ImGui::EndCombo, "only call EndCombo() if BeginCombo() returns true!"); m.def("combo", [](const char* label, Int& current_item, const std::vector<std::string>& items) { if (items.size() < 10) { const char* items_[10]; for (int i = 0; i < (int)items.size(); ++i) { items_[i] = items[i].c_str(); } return ImGui::Combo(label, &current_item.value, items_, (int)items.size()); } else { const char** items_ = new const char*[items.size()]; for (int i = 0; i < (int)items.size(); ++i) { items_[i] = items[i].c_str(); } bool result = ImGui::Combo(label, &current_item.value, items_, (int)items.size()); delete[] items_; return result; } }); m.def( "input_text", [](const char* label, String& text, size_t buf_size, ImGuiInputTextFlags flags) { bool result = false; if (buf_size > 255) { char* buff = new char[buf_size + 1]; strncpy(buff, text.value.c_str(), buf_size); result = ImGui::InputText(label, buff, buf_size, flags); if (result) { text.value = buff; } delete[] buff; } else { char buff[256]; strncpy(buff, text.value.c_str(), 255); result = ImGui::InputText(label, buff, buf_size, flags); if (result) { text.value = buff; } } return result; }, py::arg("label"), py::arg("text"), py::arg("buf_size"), py::arg("flags") = 0); m.def( "input_text_multiline", [](const char* label, String& text, size_t buf_size, const ImVec2& size, ImGuiInputTextFlags flags) { bool result = false; if (buf_size > 255) { char* buff = new char[buf_size + 1]; strncpy(buff, text.value.c_str(), buf_size); result = ImGui::InputTextMultiline(label, buff, buf_size, size, flags); if (result) { text.value = buff; } delete[] buff; } else { char buff[256]; strncpy(buff, text.value.c_str(), 255); result = ImGui::InputTextMultiline(label, buff, buf_size, size, flags); if (result) { text.value = buff; } } return result; }, py::arg("label"), py::arg("text"), py::arg("buf_size"), py::arg("size") = ImVec2(0, 0), py::arg("flags") = 0); m.def( "input_text_with_hint", [](const char* label, const char* hint, String& text, size_t buf_size, ImGuiInputTextFlags flags) { bool result = false; if (buf_size > 255) { char* buff = new char[buf_size]; strncpy(buff, text.value.c_str(), buf_size); result = ImGui::InputTextWithHint(label, hint, buff, buf_size, flags); if (result) { text.value = buff; } delete[] buff; } else { char buff[256]; strncpy(buff, text.value.c_str(), 256); result = ImGui::InputTextWithHint(label, hint, buff, buf_size, flags); if (result) { text.value = buff; } } return result; }, py::arg("label"), py::arg("hint"), py::arg("text"), py::arg("buf_size"), py::arg("flags") = 0); m.def( "input_float", [](const char* label, Float& v, float step, float step_fast, const char* display_format, ImGuiInputTextFlags flags) { return ImGui::InputFloat(label, &v.value, step, step_fast, display_format, flags); }, py::arg("label"), py::arg("v"), py::arg("step") = 0.0f, py::arg("step_fast") = 0.0f, py::arg("display_format") = "%.3f", py::arg("flags") = 0); m.def( "input_float2", [](const char* label, Float& v1, Float& v2, const char* display_format, ImGuiInputTextFlags flags) { float v[2] = {v1.value, v2.value}; bool result = ImGui::InputFloat2(label, v, display_format, flags); v1.value = v[0]; v2.value = v[1]; return result; }, py::arg("label"), py::arg("v1"), py::arg("v2"), py::arg("display_format") = "%.3f", py::arg("flags") = 0); m.def( "input_float3", [](const char* label, Float& v1, Float& v2, Float& v3, const char* display_format, ImGuiInputTextFlags flags) { float v[3] = {v1.value, v2.value, v3.value}; bool result = ImGui::InputFloat3(label, v, display_format, flags); v1.value = v[0]; v2.value = v[1]; v3.value = v[2]; return result; }, py::arg("label"), py::arg("v1"), py::arg("v2"), py::arg("v3"), py::arg("display_format") = "%.3f", py::arg("flags") = 0); m.def( "input_float4", [](const char* label, Float& v1, Float& v2, Float& v3, Float& v4, const char* display_format, ImGuiInputTextFlags flags) { float v[4] = {v1.value, v2.value, v3.value, v4.value}; bool result = ImGui::InputFloat4(label, v, display_format, flags); v1.value = v[0]; v2.value = v[1]; v3.value = v[2]; v4.value = v[3]; return result; }, py::arg("label"), py::arg("v1"), py::arg("v2"), py::arg("v3"), py::arg("v4"), py::arg("display_format") = "%.3f", py::arg("flags") = 0); m.def( "input_int", [](const char* label, Int& v, int step, int step_fast, ImGuiInputTextFlags flags) { return ImGui::InputInt(label, &v.value, step, step_fast, flags); }, py::arg("label"), py::arg("v"), py::arg("step") = 1, py::arg("step_fast") = 100, py::arg("flags") = 0); m.def( "input_int2", [](const char* label, Int& v1, Int& v2, ImGuiInputTextFlags flags) { int v[2] = {v1.value, v2.value}; bool result = ImGui::InputInt2(label, v, flags); v1.value = v[0]; v2.value = v[1]; return result; }, py::arg("label"), py::arg("v1"), py::arg("v2"), py::arg("flags") = 0); m.def( "input_int3", [](const char* label, Int& v1, Int& v2, Int& v3, ImGuiInputTextFlags flags) { int v[3] = {v1.value, v2.value, v3.value}; bool result = ImGui::InputInt3(label, v, flags); v1.value = v[0]; v2.value = v[1]; v3.value = v[2]; return result; }, py::arg("label"), py::arg("v1"), py::arg("v2"), py::arg("v3"), py::arg("flags") = 0); m.def( "input_int4", [](const char* label, Int& v1, Int& v2, Int& v3, Int& v4, ImGuiInputTextFlags flags) { int v[4] = {v1.value, v2.value, v3.value, v4.value}; bool result = ImGui::InputInt4(label, v, flags); v1.value = v[0]; v2.value = v[1]; v3.value = v[2]; v4.value = v[3]; return result; }, py::arg("label"), py::arg("v1"), py::arg("v2"), py::arg("v3"), py::arg("v4"), py::arg("flags") = 0); m.def("color_edit", [](const char* label, ImVec4& col) -> bool { return ImGui::ColorEdit4(label, &col.x); }); m.def("color_picker", [](const char* label, ImVec4& col) -> bool { return ImGui::ColorPicker4(label, &col.x); }); m.def( "slider_float", [](const char* label, Float& v, float v_min, float v_max, const char* display_format, float power) { return ImGui::SliderFloat(label, &v.value, v_min, v_max, display_format, power); }, py::arg("label"), py::arg("v"), py::arg("v_min"), py::arg("v_max"), py::arg("display_format") = "%.3f", py::arg("power") = 1.0f); m.def( "slider_float2", [](const char* label, Float& v1, Float& v2, float v_min, float v_max, const char* display_format, float power) { float v[2] = {v1.value, v2.value}; bool result = ImGui::SliderFloat2(label, v, v_min, v_max, display_format, power); v1.value = v[0]; v2.value = v[1]; return result; }, py::arg("label"), py::arg("v1"), py::arg("v2"), py::arg("v_min"), py::arg("v_max"), py::arg("display_format") = "%.3f", py::arg("power") = 1.0f); m.def( "slider_float3", [](const char* label, Float& v1, Float& v2, Float& v3, float v_min, float v_max, const char* display_format, float power) { float v[3] = {v1.value, v2.value, v3.value}; bool result = ImGui::SliderFloat3(label, v, v_min, v_max, display_format, power); v1.value = v[0]; v2.value = v[1]; v3.value = v[2]; return result; }, py::arg("label"), py::arg("v1"), py::arg("v2"), py::arg("v3"), py::arg("v_min"), py::arg("v_max"), py::arg("display_format") = "%.3f", py::arg("power") = 1.0f); m.def( "slider_float4", [](const char* label, Float& v1, Float& v2, Float& v3, Float& v4, float v_min, float v_max, const char* display_format, float power) { float v[4] = {v1.value, v2.value, v3.value, v4.value}; bool result = ImGui::SliderFloat4(label, v, v_min, v_max, display_format, power); v1.value = v[0]; v2.value = v[1]; v3.value = v[2]; v4.value = v[3]; return result; }, py::arg("label"), py::arg("v1"), py::arg("v2"), py::arg("v3"), py::arg("v4"), py::arg("v_min"), py::arg("v_max"), py::arg("display_format") = "%.3f", py::arg("power") = 1.0f); m.def( "v_slider_float", [](const char* label, const ImVec2& size, Float& v, float v_min, float v_max, const char* display_format, float power) { return ImGui::VSliderFloat(label, size, &v.value, v_min, v_max, display_format, power); }, py::arg("label"), py::arg("size"), py::arg("v"), py::arg("v_min"), py::arg("v_max"), py::arg("display_format") = "%.3f", py::arg("power") = 1.0f); m.def( "slider_angle", [](const char* label, Float& v_rad, float v_degrees_min, float v_degrees_max, const char* display_format) { return ImGui::SliderAngle(label, &v_rad.value, v_degrees_min, v_degrees_max, display_format); }, py::arg("label"), py::arg("v_rad"), py::arg("v_degrees_min") = -360.0f, py::arg("v_degrees_max") = +360.0f, py::arg("display_format") = "%.0f deg"); m.def( "slider_int", [](const char* label, Int& v, int v_min, int v_max, const char* display_format) { return ImGui::SliderInt(label, &v.value, v_min, v_max, display_format); }, py::arg("label"), py::arg("v"), py::arg("v_min"), py::arg("v_max"), py::arg("display_format") = "%d"); m.def( "slider_int2", [](const char* label, Int& v1, Int& v2, int v_min, int v_max, const char* display_format) { int v[2] = {v1.value, v2.value}; bool result = ImGui::SliderInt2(label, v, v_min, v_max, display_format); v1.value = v[0]; v2.value = v[1]; return result; }, py::arg("label"), py::arg("v1"), py::arg("v2"), py::arg("v_min"), py::arg("v_max"), py::arg("display_format") = "%d"); m.def( "slider_int3", [](const char* label, Int& v1, Int& v2, Int& v3, int v_min, int v_max, const char* display_format) { int v[3] = {v1.value, v2.value, v3.value}; bool result = ImGui::SliderInt3(label, v, v_min, v_max, display_format); v1.value = v[0]; v2.value = v[1]; v3.value = v[2]; return result; }, py::arg("label"), py::arg("v1"), py::arg("v2"), py::arg("v3"), py::arg("v_min"), py::arg("v_max"), py::arg("display_format") = "%d"); m.def( "slider_int4", [](const char* label, Int& v1, Int& v2, Int& v3, Int& v4, int v_min, int v_max, const char* display_format) { int v[4] = {v1.value, v2.value, v3.value, v4.value}; bool result = ImGui::SliderInt4(label, v, v_min, v_max, display_format); v1.value = v[0]; v2.value = v[1]; v3.value = v[2]; v4.value = v[3]; return result; }, py::arg("label"), py::arg("v1"), py::arg("v2"), py::arg("v3"), py::arg("v4"), py::arg("v_min"), py::arg("v_max"), py::arg("display_format") = "%d"); m.def( "v_slider_int", [](const char* label, const ImVec2& size, Int& v, int v_min, int v_max, const char* display_format) { return ImGui::VSliderInt(label, size, &v.value, v_min, v_max, display_format); }, py::arg("label"), py::arg("size"), py::arg("v"), py::arg("v_min"), py::arg("v_max"), py::arg("display_format") = "%d"); // m.def( "drag_float", [](const char* label, Float& v, float v_speed, float v_min, float v_max, const char* display_format, float power) { return ImGui::DragFloat(label, &v.value, v_speed, v_min, v_max, display_format, power); }, py::arg("label"), py::arg("v"), py::arg("v_speed") = 1.0f, py::arg("v_min"), py::arg("v_max"), py::arg("display_format") = "%.3f", py::arg("power") = 1.0f); m.def( "drag_float2", [](const char* label, Float& v1, Float& v2, float v_speed, float v_min, float v_max, const char* display_format, float power) { float v[2] = {v1.value, v2.value}; bool result = ImGui::DragFloat2(label, v, v_speed, v_min, v_max, display_format, power); v1.value = v[0]; v2.value = v[1]; return result; }, py::arg("label"), py::arg("v1"), py::arg("v2"), py::arg("v_speed") = 1.0f, py::arg("v_min"), py::arg("v_max"), py::arg("display_format") = "%.3f", py::arg("power") = 1.0f); m.def( "drag_float3", [](const char* label, Float& v1, Float& v2, Float& v3, float v_speed, float v_min, float v_max, const char* display_format, float power) { float v[3] = {v1.value, v2.value, v3.value}; bool result = ImGui::DragFloat3(label, v, v_speed, v_min, v_max, display_format, power); v1.value = v[0]; v2.value = v[1]; v3.value = v[2]; return result; }, py::arg("label"), py::arg("v1"), py::arg("v2"), py::arg("v3"), py::arg("v_speed") = 1.0f, py::arg("v_min"), py::arg("v_max"), py::arg("display_format") = "%.3f", py::arg("power") = 1.0f); m.def( "drag_float4", [](const char* label, Float& v1, Float& v2, Float& v3, Float& v4, float v_speed, float v_min, float v_max, const char* display_format, float power) { float v[4] = {v1.value, v2.value, v3.value, v4.value}; bool result = ImGui::DragFloat4(label, v, v_speed, v_min, v_max, display_format, power); v1.value = v[0]; v2.value = v[1]; v3.value = v[2]; v4.value = v[3]; return result; }, py::arg("label"), py::arg("v1"), py::arg("v2"), py::arg("v3"), py::arg("v4"), py::arg("v_speed") = 1.0f, py::arg("v_min"), py::arg("v_max"), py::arg("display_format") = "%.3f", py::arg("power") = 1.0f); m.def( "drag_int", [](const char* label, Int& v, float v_speed, int v_min, int v_max, const char* display_format) { return ImGui::DragInt(label, &v.value, v_speed, v_min, v_max, display_format); }, py::arg("label"), py::arg("v"), py::arg("v_speed") = 1.0f, py::arg("v_min"), py::arg("v_max"), py::arg("display_format") = "%d"); m.def( "drag_int2", [](const char* label, Int& v1, Int& v2, float v_speed, int v_min, int v_max, const char* display_format) { int v[2] = {v1.value, v2.value}; bool result = ImGui::DragInt2(label, v, v_speed, v_min, v_max, display_format); v1.value = v[0]; v2.value = v[1]; return result; }, py::arg("label"), py::arg("v1"), py::arg("v2"), py::arg("v_speed") = 1.0f, py::arg("v_min"), py::arg("v_max"), py::arg("display_format") = "%d"); m.def( "drag_int3", [](const char* label, Int& v1, Int& v2, Int& v3, float v_speed, int v_min, int v_max, const char* display_format) { int v[3] = {v1.value, v2.value, v3.value}; bool result = ImGui::DragInt3(label, v, v_speed, v_min, v_max, display_format); v1.value = v[0]; v2.value = v[1]; v3.value = v[2]; return result; }, py::arg("label"), py::arg("v1"), py::arg("v2"), py::arg("v3"), py::arg("v_speed") = 1.0f, py::arg("v_min"), py::arg("v_max"), py::arg("display_format") = "%d"); m.def( "drag_int4", [](const char* label, Int& v1, Int& v2, Int& v3, Int& v4, float v_speed, int v_min, int v_max, const char* display_format) { int v[4] = {v1.value, v2.value, v3.value, v4.value}; bool result = ImGui::DragInt4(label, v, v_speed, v_min, v_max, display_format); v1.value = v[0]; v2.value = v[1]; v3.value = v[2]; v4.value = v[3]; return result; }, py::arg("label"), py::arg("v1"), py::arg("v2"), py::arg("v3"), py::arg("v4"), py::arg("v_speed") = 1.0f, py::arg("v_min"), py::arg("v_max"), py::arg("display_format") = "%d"); m.def( "plot_lines", [](const char* label, const std::vector<float>& values, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0), int stride = sizeof(float)) { ImGui::PlotLines(label, values.data(), (int)values.size(), values_offset, overlay_text, scale_min, scale_max, graph_size, stride); }, py::arg("label"), py::arg("values"), py::arg("values_offset") = 0, py::arg("overlay_text") = nullptr, py::arg("scale_min") = FLT_MAX, py::arg("scale_max") = FLT_MAX, py::arg("graph_size") = ImVec2(0, 0), py::arg("stride") = sizeof(float)); m.def("progress_bar", &ImGui::ProgressBar, py::arg("fraction"), py::arg("size_arg") = ImVec2(-1, 0), py::arg("overlay") = nullptr); m.def("color_button", &ImGui::ColorButton, py::arg("desc_id"), py::arg("col"), py::arg("flags") = 0, py::arg("size") = ImVec2(0, 0), "display a colored square/button, hover for details, return true when " "pressed."); m.def( "selectable", [](std::string label, bool selected = false, ImGuiSelectableFlags flags = 0, ImVec2 size = ImVec2(0, 0)) -> bool { return ImGui::Selectable(label.c_str(), selected, flags, size); }, py::arg("label"), py::arg("selected") = false, py::arg("flags") = 0, py::arg("size") = ImVec2(0, 0)); m.def( "selectable", [](std::string label, Bool& selected, ImGuiSelectableFlags flags = 0, ImVec2 size = ImVec2(0, 0)) -> bool { return ImGui::Selectable(label.c_str(), &selected.value, flags, size); }, py::arg("label"), py::arg("selected"), py::arg("flags") = 0, py::arg("size") = ImVec2(0, 0)); m.def( "list_box_header", [](std::string label, ImVec2 size = ImVec2(0, 0)) { ImGui::ListBoxHeader(label.c_str(), size); }, py::arg("label"), py::arg("size")); m.def("list_box_footer", &ImGui::ListBoxFooter); m.def("set_item_default_focus", &ImGui::SetItemDefaultFocus); m.def("set_keyboard_focus_here", &ImGui::SetKeyboardFocusHere); m.def("is_item_hovered", &ImGui::IsItemHovered, py::arg("flags") = 0); m.def("is_item_active", &ImGui::IsItemActive); m.def("is_item_focused", &ImGui::IsItemFocused); m.def("is_item_clicked", &ImGui::IsItemClicked); m.def("is_item_visible", &ImGui::IsItemVisible); m.def("is_item_edited", &ImGui::IsItemEdited); m.def("is_item_activated", &ImGui::IsItemActivated); m.def("is_item_deactivated", &ImGui::IsItemDeactivated); m.def("is_item_deactivated_after_edit", &ImGui::IsItemDeactivatedAfterEdit); m.def("is_item_toggled_open", &ImGui::IsItemToggledOpen); m.def("is_any_item_hovered", &ImGui::IsAnyItemHovered); m.def("is_any_item_active", &ImGui::IsAnyItemActive); m.def("is_any_item_focused", &ImGui::IsAnyItemFocused); m.def("get_item_rect_min", &ImGui::GetItemRectMin); m.def("get_item_rect_max", &ImGui::GetItemRectMax); m.def("get_item_rect_size", &ImGui::GetItemRectSize); m.def("set_item_allow_overlap", &ImGui::SetItemAllowOverlap); m.def("get_time", &ImGui::GetTime); m.def("get_frame_count", &ImGui::GetFrameCount); m.def("get_key_index", &ImGui::GetKeyIndex); m.def("is_key_down", &ImGui::IsKeyDown); m.def("is_key_pressed", &ImGui::IsKeyPressed); m.def("is_key_released", &ImGui::IsKeyReleased); m.def("get_key_pressed_amount", &ImGui::GetKeyPressedAmount); m.def("is_mouse_down", &ImGui::IsMouseDown); m.def("is_any_mouse_down", &ImGui::IsAnyMouseDown); m.def("is_mouse_clicked", &ImGui::IsMouseClicked); m.def("is_mouse_double_clicked", &ImGui::IsMouseDoubleClicked); m.def("is_mouse_released", &ImGui::IsMouseReleased); m.def("is_mouse_dragging", &ImGui::IsMouseDragging); m.def("is_mouse_hovering_rect", &ImGui::IsMouseHoveringRect); m.def("is_mouse_pos_valid", &ImGui::IsMousePosValid); m.def("get_mouse_pos", &ImGui::GetMousePos); m.def("get_mouse_pos_on_opening_current_popup", &ImGui::GetMousePosOnOpeningCurrentPopup); m.def("get_mouse_drag_delta", &ImGui::GetMouseDragDelta); m.def("reset_mouse_drag_delta", &ImGui::ResetMouseDragDelta); m.def("capture_keyboard_from_app", &ImGui::CaptureKeyboardFromApp); m.def("capture_mouse_from_app", &ImGui::CaptureMouseFromApp); py::enum_<ImGuiDragDropFlags_>(m, "DragDropFlags") .value("SourceNoPreviewTooltip", ImGuiDragDropFlags_SourceNoPreviewTooltip) .value("SourceNoDisableHover", ImGuiDragDropFlags_SourceNoDisableHover) .value("SourceNoHoldToOpenOthers", ImGuiDragDropFlags_SourceNoHoldToOpenOthers) .value("SourceAllowNullID", ImGuiDragDropFlags_SourceAllowNullID) .value("SourceExtern", ImGuiDragDropFlags_SourceExtern) .value("SourceAutoExpirePayload", ImGuiDragDropFlags_SourceAutoExpirePayload) .value("AcceptBeforeDelivery", ImGuiDragDropFlags_AcceptBeforeDelivery) .value("AcceptNoDrawDefaultRect", ImGuiDragDropFlags_AcceptNoDrawDefaultRect) .value("AcceptNoPreviewTooltip", ImGuiDragDropFlags_AcceptNoPreviewTooltip) .value("AcceptPeekOnly", ImGuiDragDropFlags_AcceptPeekOnly) .export_values(); m.def("begin_drag_drop_source", &ImGui::BeginDragDropSource); // todo: // m.def("set_drag_drop_payload", &ImGui::SetDragDropPayload); m.def("set_drag_drop_payload_string", [](std::string data) { ImGui::SetDragDropPayload("string", data.c_str(), data.size()); }); m.def("end_drag_drop_source", &ImGui::EndDragDropSource); m.def("begin_drag_drop_target", &ImGui::BeginDragDropTarget); // todo: // m.def("accept_drag_drop_payload", &ImGui::AcceptDragDropPayload); m.def("accept_drag_drop_payload_string_preview", [](ImGuiDragDropFlags flags = 0) -> std::string { auto payload = ImGui::AcceptDragDropPayload("string", flags); if (!payload->IsDataType("string") || !payload->Data) return ""; if (payload->IsPreview()) return std::string(static_cast<char*>(payload->Data), payload->DataSize); else return ""; }); m.def("accept_drag_drop_payload_string", [](ImGuiDragDropFlags flags = 0) -> std::string { auto payload = ImGui::AcceptDragDropPayload("string", flags); if (!payload->IsDataType("string") || !payload->Data) return ""; if (payload->IsDelivery()) return std::string(static_cast<char*>(payload->Data), payload->DataSize); else return ""; }); m.def("end_drag_drop_target", &ImGui::EndDragDropTarget); m.def("get_drag_drop_payload", []() -> std::string { auto payload = ImGui::GetDragDropPayload(); if (!payload->IsDataType("string") || !payload->Data) return ""; if (payload->IsDelivery()) return std::string(static_cast<char*>(payload->Data), payload->DataSize); else return ""; }); m.def("push_clip_rect", &ImGui::PushClipRect); m.def("pop_clip_rect", &ImGui::PopClipRect); m.def( "add_font_from_file_ttf", [](std::string filename, float size_pixels = 32.0f) { return ImGui::GetIO().Fonts->AddFontFromFileTTF(filename.c_str(), size_pixels); }, py::arg("filename"), py::arg("size_pixels"), py::return_value_policy::reference); m.def("push_font", &ImGui::PushFont); m.def("pop_font", &ImGui::PopFont); m.def("get_font", &ImGui::GetFont); py::class_<ImFont>(m, "Font").def(py::init()); m.def( "set_display_framebuffer_scale", [](float scale) { ImGui::GetIO().DisplayFramebufferScale = ImVec2(scale, scale); }, py::arg("scale")); m.def("get_display_framebuffer_scale", []() { return ImGui::GetIO().DisplayFramebufferScale; }); m.def( "set_font_global_scale", [](float scale) { ImGui::GetIO().FontGlobalScale = scale; }, py::arg("scale")); m.def("get_font_global_scale", []() { return ImGui::GetIO().FontGlobalScale; }); }
8f70909888b41cb5cb81dea5af9fdd33328cd6cd
37b30edf9f643225fdf697b11fd70f3531842d5f
/components/shared_highlighting/core/common/shared_highlighting_features.cc
e14e462010e647823093a2765bd6197337c09cbc
[ "BSD-3-Clause" ]
permissive
pauladams8/chromium
448a531f6db6015cd1f48e7d8bfcc4ec5243b775
bc6d983842a7798f4508ae5fb17627d1ecd5f684
refs/heads/main
2023-08-05T11:01:20.812453
2021-09-17T16:13:54
2021-09-17T16:13:54
407,628,666
1
0
BSD-3-Clause
2021-09-17T17:35:31
2021-09-17T17:35:30
null
UTF-8
C++
false
false
1,262
cc
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/shared_highlighting/core/common/shared_highlighting_features.h" #include "base/feature_list.h" namespace shared_highlighting { const base::Feature kPreemptiveLinkToTextGeneration{ "PreemptiveLinkToTextGeneration", base::FEATURE_ENABLED_BY_DEFAULT}; constexpr base::FeatureParam<int> kPreemptiveLinkGenTimeoutLengthMs{ &kPreemptiveLinkToTextGeneration, "TimeoutLengthMs", 500}; const base::Feature kSharedHighlightingUseBlocklist{ "SharedHighlightingUseBlocklist", base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kSharedHighlightingV2{"SharedHighlightingV2", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kSharedHighlightingAmp{"SharedHighlightingAmp", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kSharedHighlightingLayoutObjectFix{ "SharedHighlightingLayoutObjectFix", base::FEATURE_ENABLED_BY_DEFAULT}; int GetPreemptiveLinkGenTimeoutLengthMs() { return kPreemptiveLinkGenTimeoutLengthMs.Get(); } } // namespace shared_highlighting
57713a36dba9626926b355517ce999bbd98abbdc
1928074ebb26f792c65f7fea9d3487ed67d23872
/Codeforces/CF660E.cpp
c21913788278a5320ead9dfa5894f3586775d863
[]
no_license
hahaschool/playground
b9867fc8aaafa879609192668e2dbbc4e0a0a2cf
e2dec3435339f0ac225494f45452df605a1f5f99
refs/heads/master
2020-04-06T06:36:10.467586
2017-06-12T16:42:52
2017-06-12T16:42:52
51,774,356
0
0
null
null
null
null
UTF-8
C++
false
false
2,346
cpp
// // CF660E.cpp // playground // // Created by 張正昊 on 5/9/2016. // Copyright © 2016 Adam Chang. All rights reserved. // #include <stdio.h> #include <iostream> #include <algorithm> #include <queue> #include <vector> #include <cstdlib> #include <string> #include <cstring> #include <ctime> #include <iomanip> #include <cmath> #include <set> #include <stack> #include <cmath> #include <map> #include <complex> #include <functional> #include <numeric> #include <bitset> #define REP(i,t) for(int i = 0;i < t; i++) #define REP_1(i,t) for(int i = 1;i <= t; i++) #define CASE_LOOP int ___;scanf(" %d",&___);for(int __ = 1; __ <= ___; __++) #define FOR_EDGE(i,u) for (int i = head[u]; i; i = nxt[i]) #define ADHOC_CIN(typ,name) typ name;cin >> name; #define ADHOC_SCANINT(name) int name;scanf(" %d",&name); using namespace std; typedef long long LL; const int MAXN = 1000005; const LL MODER = 1000000007; LL getmod(LL a){ if(a<0||a>=MODER) a %= MODER; if(a<0) a+=MODER; return a; } LL summod(LL a,LL b){ return getmod(getmod(a)+getmod(b)); } LL mulmod(LL a,LL b){ return getmod(getmod(a)*getmod(b)); } LL powmod(LL a,LL p){ LL ret = 1; while(p){ if(p&1) ret = mulmod(ret, a); a = mulmod(a, a); p >>= 1; } return ret; } LL invmod(LL a){ return powmod(a, MODER-2); } LL n,m; LL fac[MAXN],facinv[MAXN]; void prep(){ fac[0] = facinv[0] = 1; REP_1(i, MAXN-1){ fac[i] = mulmod(fac[i-1], i); facinv[i] = mulmod(facinv[i-1], invmod(i)); } } LL bin(LL n,LL r){ return mulmod(mulmod(fac[n], facinv[r]), facinv[n-r]); } LL solve(){ LL ret = 0; //Both Formula works. //REP_1(i, n) ret = summod(ret, mulmod(powmod(m, i), mulmod(powmod(m-1, n), mulmod(invmod(powmod(m-1, i)), bin(n,i-1))))); REP_1(i, n) ret = summod(ret, mulmod(mulmod(powmod(m-1, i-1), mulmod(powmod(m, n),invmod(powmod(m, i-1)))), bin(n,i))); ret = summod(ret, powmod(m, n)); return ret; } int main(int argc, const char * argv[]){ #ifdef LOCAL_DEBUG freopen("testdata.in", "r", stdin); clock_t clk = clock(); #endif prep(); while (cin >> n >> m) { cout << solve() << endl; } #ifdef LOCAL_DEBUG puts("-----END OF OUTPUT-----"); printf("Time Elapsed: %luMS\n",(clock() - clk)/CLK_TCK/10); #endif return 0; }
7ffa838da731b180633893de29798ee9657bdb4b
14c93742dafd5d7a1f594e9d49826d1f1a66d581
/include/sb/application.h
43976d7cdaad648ebae08c9c6596f9c214014e8b
[ "MIT" ]
permissive
teemid/learning-opengl
17d48f1a672fdd0f9f9d9ae102c80db20d1eda38
ebcd7e00e394b565c93e8e4e5af980e558651213
refs/heads/master
2020-03-15T01:59:08.096215
2018-05-02T21:21:01
2018-05-02T21:21:01
131,907,033
0
0
null
null
null
null
UTF-8
C++
false
false
211
h
#ifndef OPENGL_APPLICATION_H #define OPENGL_APPLICATION_H class Application { public: virtual void startup() { }; virtual void render(double currentTime) = 0; virtual void shutdown() { }; }; #endif
26a36a5817f031ad3f6a2fcff4cd087979aee5b8
01a42b69633daf62a2eb3bb70c5b1b6e2639aa5f
/SCUM_Pate_02_functions.cpp
9b4871dd10df08d608a0b7ac165b7efdb3ef624f
[]
no_license
Kehczar/scum_sdk
45db80e46dac736cc7370912ed671fa77fcb95cf
8d1770b44321a9d0b277e4029551f39b11f15111
refs/heads/master
2022-07-25T10:06:20.892750
2020-05-21T11:45:36
2020-05-21T11:45:36
265,826,541
1
0
null
null
null
null
UTF-8
C++
false
false
4,719
cpp
// Scum 3.79.22573 (UE 4.24) #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace Classes { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function ConZ.FoodItem.OnRep_Temperature // () void APate_02_C::OnRep_Temperature() { static auto fn = UObject::FindObject<UFunction>("Function ConZ.FoodItem.OnRep_Temperature"); APate_02_C_OnRep_Temperature_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ConZ.FoodItem.OnRep_ItemOpened // () void APate_02_C::OnRep_ItemOpened() { static auto fn = UObject::FindObject<UFunction>("Function ConZ.FoodItem.OnRep_ItemOpened"); APate_02_C_OnRep_ItemOpened_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ConZ.FoodItem.OnRep_IsCooking // () void APate_02_C::OnRep_IsCooking() { static auto fn = UObject::FindObject<UFunction>("Function ConZ.FoodItem.OnRep_IsCooking"); APate_02_C_OnRep_IsCooking_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ConZ.FoodItem.OnAudioComponentExpired // () void APate_02_C::OnAudioComponentExpired() { static auto fn = UObject::FindObject<UFunction>("Function ConZ.FoodItem.OnAudioComponentExpired"); APate_02_C_OnAudioComponentExpired_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ConZ.FoodItem.IsCooking // () // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool APate_02_C::IsCooking() { static auto fn = UObject::FindObject<UFunction>("Function ConZ.FoodItem.IsCooking"); APate_02_C_IsCooking_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function ConZ.FoodItem.GetVolume // () // Parameters: // float ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) float APate_02_C::GetVolume() { static auto fn = UObject::FindObject<UFunction>("Function ConZ.FoodItem.GetVolume"); APate_02_C_GetVolume_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function ConZ.FoodItem.GetThermalConductivityFactor // () // Parameters: // float ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) float APate_02_C::GetThermalConductivityFactor() { static auto fn = UObject::FindObject<UFunction>("Function ConZ.FoodItem.GetThermalConductivityFactor"); APate_02_C_GetThermalConductivityFactor_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function ConZ.FoodItem.GetTemperature // () // Parameters: // float ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) float APate_02_C::GetTemperature() { static auto fn = UObject::FindObject<UFunction>("Function ConZ.FoodItem.GetTemperature"); APate_02_C_GetTemperature_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function ConZ.FoodItem.GetEnvironmentTemperature // () // Parameters: // float ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) float APate_02_C::GetEnvironmentTemperature() { static auto fn = UObject::FindObject<UFunction>("Function ConZ.FoodItem.GetEnvironmentTemperature"); APate_02_C_GetEnvironmentTemperature_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function ConZ.FoodItem.GetCookingAmount // () // Parameters: // float ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) float APate_02_C::GetCookingAmount() { static auto fn = UObject::FindObject<UFunction>("Function ConZ.FoodItem.GetCookingAmount"); APate_02_C_GetCookingAmount_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } } #ifdef _MSC_VER #pragma pack(pop) #endif
bfd8a1dba97064d75def8e13c0a0061802c412e7
966c376e708193a26687211b36b6bd5886b9f92f
/Kumar Ayush/2016_Ass2/Booking Agent/booking_agent.h
af46c5d70198b2f34ecacad1249ac97548ab0cef
[]
no_license
palmerteam123/Networks_Lab_2016_Repo
7fc0f9a509cf617972d950dc411954b740366d46
75bcc1bdbe40db0e13fa748c63617cd64ff1e657
refs/heads/master
2021-01-10T06:04:03.703396
2016-03-12T17:11:13
2016-03-12T17:11:13
51,336,597
0
0
null
null
null
null
UTF-8
C++
false
false
12,976
h
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <iostream> #include <arpa/inet.h> #include <netinet/in.h> #include <netdb.h> #include <sys/wait.h> #include <fstream> #include <stdio.h> #include <termios.h> #include <ctype.h> #include <sstream> #include "../request.h" #include "../train.h" // booking_agent.h #ifndef BOOKING_AGENT_H #define BOOKING_AGENT_H #define MAX_SIZE 1024 using namespace std; static struct termios old; static struct termios _new; vector<string> split(string str, char delimiter) { vector<string> internal; stringstream ss(str); // Turn the string into a stream. string tok; while(getline(ss, tok, delimiter)) { internal.push_back(tok); } return internal; } /* Initialize _new terminal i/o settings */ void initTermios(int echo) { tcgetattr(0, &old); /* grab old terminal i/o settings */ _new = old; /* make _new settings same as old settings */ _new.c_lflag &= ~ICANON; /* disable buffered i/o */ _new.c_lflag &= echo ? ECHO : ~ECHO; /* set echo mode */ tcsetattr(0, TCSANOW, &_new); /* use these _new terminal i/o settings now */ } /* Restore old terminal i/o settings */ void resetTermios(void) { tcsetattr(0, TCSANOW, &old); } /* Read 1 character - echo defines echo mode */ char getch_(int echo) { char ch; initTermios(echo); ch = getchar(); resetTermios(); return ch; } /* Read 1 character without echo */ char getch(void) { return getch_(0); } /* Read 1 character with echo */ char getche(void) { return getch_(1); } string itoa(int a) { string ss=""; //create empty string while(a) { int x=a%10; a/=10; char i='0'; i=i+x; ss=i+ss; //append new character at the front of the string! } return ss; } class Booking_Agent { private: Request req_list[20]; Book_Details* book_detail_list[20]; int req_list_counter,book_detail_list_counter; int sockfd,portno; char serverIP[20]; struct sockaddr_in serv_addr; void error(const char* error_mssg) { perror(error_mssg); exit(1); } public: Booking_Agent(char serverIP[20],int portno) { req_list_counter=0; book_detail_list_counter=0; strcpy(this->serverIP,serverIP); sockfd = socket(AF_INET, SOCK_STREAM, 0); if(sockfd<0) error("Error in opening Booking_Agent Socket"); this->portno=portno; bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(portno); /* either this struct hostent* server; server = gethostbyname(serverIP); // if serverIP is a DNS name // need to insert a new mapping in /etc/hosts file if (server == NULL) { fprintf(stderr,"ERROR, no such host\n"); exit(0); } bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length); */ // OR this // if serverIP is an IP address in dot notation inet_pton(AF_INET, serverIP, &(serv_addr.sin_addr)); } private: void parseInputCSV(const char* filename) { //cout << 323; // parse the csv file and build the object // Read the file ---------- /* FILE* fp = fopen(filename, "r"); if (fp == NULL) error("Can't open CSV file ! "); fseek(fp, 0, SEEK_END); long size = ftell(fp); fseek(fp, 0, SEEK_SET); //char *pData = new char[size + 1]; char* pData = (char*)malloc((size+1)*sizeof(char)); fread(pData, sizeof(char), size, fp); fclose(fp); */ string line[100]; int i=0; ifstream myfile( filename); if (myfile) // same as: if (myfile.good()) { while (getline( myfile, line[i] )) // same as: while (getline( myfile, line ).good()) { i++; } myfile.close(); } int lineCount=i; // line[lineCount]=NULL for(i=0;i<lineCount;i++) { // cout << "line[i]" << line[i] << endl; vector<string> tokens = split(line[i],','); int _id_=stoi(tokens[0],NULL,10); int _train_no_=stoi(tokens[1],NULL,10); int _coach_type_; if(tokens[2]=="AC") _coach_type_=Coach::AC; else if(tokens[2]=="Sleeper") _coach_type_=Coach::Sleeper; int _num_of_berths_=stoi(tokens[3],NULL); int prefer[_num_of_berths_+1]; if(tokens[4]=="NA") prefer[0]=-1; else { vector<string> tok = split(tokens[4],'-'); //prefer = (int*)malloc(_num_of_berths_*sizeof(int)); int n = _num_of_berths_-1; prefer[_num_of_berths_] = -1; while(n >= 0) { if(tok[n] == "SU") prefer[n]=Berth::SU; else if(tok[n] == "SL") prefer[n]=Berth::SL; else if(tok[n] == "UB") prefer[n]=Berth::UB; else if(tok[n] == "MB") prefer[n]=Berth::MB; else if(tok[n] == "LB") prefer[n]=Berth::LB; else error("Erroneous parsing here !"); n--; } } int ages[_num_of_berths_]; vector<string> tok1 = split(tokens[5],'-'); //ages = (int*)malloc(_num_of_berths_*sizeof(int)); int n = _num_of_berths_- 1; while(n >= 0) { ages[n]=stoi(tok1[n],NULL); n--; } /* // do for every line : char* str1=strtok(line[i],","); char* str2=strtok(NULL,","); char* str3=strtok(NULL,","); char* str4=strtok(NULL,","); char* str5=strtok(NULL,","); char* str6=strtok(NULL,","); //cout << "\n\n " << str1 << "\n\n " << str2 << "\n\n " << str3 << "\n\n " << str4 << "\n\n " << str5 << "\n\n " << str6 << endl; int _id_; sscanf(str1,"%d",&_id_); int _train_no_; sscanf(str2,"%d",&_train_no_); int _coach_type_; if(strcmp(str3,"AC")==0) _coach_type_=Coach::AC; else if(strcmp(str3,"Sleeper")==0) _coach_type_=Coach::Sleeper; else error("Erroneous parsing Coach type !"); int _num_of_berths_; sscanf(str4,"%d",&_num_of_berths_); //cout << "_num_of_berths_" << _num_of_berths_ << endl; int* prefer; if(strcmp(str5,"NA")==0) prefer=NULL; else { int counter=0; //prefer=new int[_num_of_berths_]; prefer = (int*)malloc(_num_of_berths_*sizeof(int)); char* prf = strtok(str5,"-"); while(prf!=NULL) { if(strcmp(prf,"SU")==0) prefer[counter]=Berth::SU; else if(strcmp(prf,"SL")==0) prefer[counter]=Berth::SL; else if(strcmp(prf,"UB")==0) prefer[counter]=Berth::UB; else if(strcmp(prf,"MB")==0) prefer[counter]=Berth::MB; else if(strcmp(prf,"LB")==0) prefer[counter]=Berth::LB; else error("Erroneous parsing here !"); //cout<<"counter : " << counter << " prefer_str : " << prf << " age : " << prefer[counter] << endl; counter++; prf = strtok(NULL,"-"); } //cout << counter << " ---- " << _num_of_berths_ << endl; if(counter != _num_of_berths_) error("Berth Preference counter mismatch !"); } //cout << " str6 :" << str6 << endl; int counter=0; //int* ages=new int[_num_of_berths_]; int* ages = (int*)malloc(_num_of_berths_*sizeof(int)); char* age_str = strtok(str6,"-"); while(age_str!=NULL) { sscanf(age_str,"%d",&ages[counter]); //cout<<"counter : " << counter << " age_str : " << age_str << " age : " << ages[counter] << endl; counter++; age_str = strtok(NULL,"-"); } //cout << counter << " ---- " << _num_of_berths_ << endl; if(counter != _num_of_berths_) error("Age counter mismatch !"); // just now */ // Request obj= Request();//(_id_,_coach_type_,_train_no_,_num_of_berths_,_timestamp_,prefer,ages); int indx=req_list_counter++; time_t _timestamp_ = time(0); req_list[indx].book_ID=_id_; req_list[indx].train_no=_train_no_; req_list[indx].num_of_berths=_num_of_berths_; req_list[indx].timestamp = time(0); // cout << req_list[indx].book_ID<<endl; for(int i=0;i<=_num_of_berths_;i++) { if(prefer[0]!=-1) req_list[indx].berth_preferences[i]=prefer[i]; req_list[indx].pass_ages[i]=ages[i]; } if(prefer[0]==-1) req_list[indx].berth_preferences[0]=-1; // cout << "obj size : " << sizeof(obj) << endl; //cout << "req_list b4 pushing ... " << req_list_counter<< endl; // req_list[req_list_counter++] = obj; //cout << "req_list after pushing ... " << req_list_counter << endl; //if(prefer!=NULL) free(prefer);//delete[] prefer; //free(ages);//delete[] ages; } // Parsed the file content ---------- //free(pData);//delete[] pData; return; } void dealWithServer() { // cout<<420; if (connect(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) error("Error in connecting to TCP Server !"); else cout<<" Connected to the TCP Server "<< serverIP<<endl; // system("clear"); // cout << req_list_counter << endl; for(int i=0; i<req_list_counter ; i++) { int write_count=write(sockfd,(char*)&req_list[i],sizeof(req_list[i])); if(write_count<=0) error("Error in sending object to TCP Server !\n\n"); else cout << "sent the request object to the Booking server \n"; book_detail_list[i] = new Book_Details(); int read_count=read(sockfd,(char*)book_detail_list[i],sizeof(Book_Details)); if(read_count<=0) error("Error in receiving response from TCP Server !\n"); else cout << "\nreceived Server Response \n"<< endl; //cout<<book_detail_list[i]->book_ID<<endl; //cout<<book_detail_list[i]->num_of_berths<<endl; //cout<<book_detail_list[i]->train_no<<endl; for(int j=0;j<book_detail_list[i]->num_of_berths;j++) { //cout << "yo\n"; //cout<<book_detail_list[i]->coaches[j]<<endl; //cout << "yo\n"; //cout<<book_detail_list[i]->seat_no[j]<<endl; //cout << "yo\n"; //cout<<book_detail_list[i]->position[j]<<endl; //cout << "yo\n"; } usleep(500); } close(sockfd); } string pos_repr(int* pos_arr,int n) { string str=""; int i=0; switch(pos_arr[i]) { case Berth::UB: str=str+"UB"; break; case Berth::LB: str=str+"LB"; break; case Berth::MB: str=str+"MB"; break; case Berth::SL: str=str+"SL"; break; case Berth::SU: str=str+"SU"; break; } for(i=1;i<n;i++) { switch(pos_arr[i]) { case Berth::UB: str=str+"-UB"; break; case Berth::LB: str=str+"-LB"; break; case Berth::MB: str=str+"-MB"; break; case Berth::SL: str=str+"-SL"; break; case Berth::SU: str=str+"-SU"; break; } } return str; } string coach_repr(char coach_arr[20][MAX_SIZE],int n) { char str[MAX_SIZE]; strcpy(str,coach_arr[0]); for(int i=0;i<n;i++) { strcat(str,"-"); strcpy(str,coach_arr[i]); } return str; } string seat_repr(int* seat_arr,int n) { string str=itoa(seat_arr[0]); for(int i=0;i<n;i++){ str=str+"-"; str=str+itoa(seat_arr[i]); } return str; } void writeOutputCSV(const char* filename) { // Open the file ---------- ofstream fp; //cout << 0; fp.open (filename, ios::out | ios::app ); //cout << 1; if (fp.fail() || fp.bad()) error("Can't create CSV file for writing output ! "); //cout << 2; for(int i=0; i < req_list_counter ; i++) { //cout << 3; // fp << "----------------------------------------------------\n"; fp << book_detail_list[i]->book_ID << "," << book_detail_list[i]->train_no << "/" << seat_repr(book_detail_list[i]->seat_no,book_detail_list[i]->num_of_berths) << "/" << pos_repr(book_detail_list[i]->position,book_detail_list[i]->num_of_berths) << "/" << coach_repr(book_detail_list[i]->coaches,book_detail_list[i]->num_of_berths) << "\n"; // fp << "----------------------------------------------------\n\n\n"; //cout << 4; //for(;;) //cout <<3; } //cout << 5; fp.close(); } public: void run() { parseInputCSV("booking.csv"); cout<<"done parsing"<<endl; // now, the list req_list contains all the records parsed from the CSV file dealWithServer(); // send the req_list cout<<"done dealing"<<endl; writeOutputCSV("tickets.csv"); cout<<"done writing"<<endl; } }; #endif
bd544fe3bacd9ca5cb2d77c02d2c79337239e84b
3ebb34045c7a71509e47b761850f8a6c9709f6d9
/02-procesos/MemoriaCompartida.h
b03529fd9cda8b9ec8ae39ba0d67408353cb3e58
[]
no_license
nhuallpa/7559-concurrencia
cde0bc1a986b35cc0c85d38dda84261827d6ef4e
e29a44f9fe6b14e24483d506fbdb8bbba6d0a89f
refs/heads/master
2020-03-07T16:36:23.021395
2019-12-17T11:32:06
2019-12-17T11:32:06
127,587,391
0
0
null
null
null
null
UTF-8
C++
false
false
2,125
h
#ifndef MEMORIACOMPARTIDA_H_ #define MEMORIACOMPARTIDA_H_ #define SHM_OK 0 #define ERROR_FTOK -1 #define ERROR_SHMGET -2 #define ERROR_SHMAT -3 #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <string> template <class T> class MemoriaCompartida { private: int shmId; T* ptrDatos; int cantidadProcesosAdosados () const; public: MemoriaCompartida (); ~MemoriaCompartida (); int crear ( const std::string& archivo,const char letra ); void liberar (); void escribir ( const T& dato ); T leer () const; }; template <class T> MemoriaCompartida<T> :: MemoriaCompartida() : shmId(0), ptrDatos(NULL) { } template <class T> MemoriaCompartida<T> :: ~MemoriaCompartida() { } template <class T> int MemoriaCompartida<T> :: crear ( const std::string& archivo,const char letra ) { // generacion de la clave key_t clave = ftok ( archivo.c_str(),letra ); if ( clave == -1 ) return ERROR_FTOK; else { // creacion de la memoria compartida this->shmId = shmget ( clave,sizeof(T),0644|IPC_CREAT ); if ( this->shmId == -1 ) return ERROR_SHMGET; else { // attach del bloque de memoria al espacio de direcciones del proceso void* ptrTemporal = shmat ( this->shmId,NULL,0 ); std::cout<<"mem"<<ptrTemporal<<std::endl; if ( ptrTemporal == (void *) -1 ) { return ERROR_SHMAT; } else { this->ptrDatos = static_cast<T*> (ptrTemporal); return SHM_OK; } } } } template <class T> void MemoriaCompartida<T> :: liberar () { // detach del bloque de memoria shmdt ( static_cast<void*> (this->ptrDatos) ); int procAdosados = this->cantidadProcesosAdosados (); if ( procAdosados == 0 ) { shmctl ( this->shmId,IPC_RMID,NULL ); } } template <class T> void MemoriaCompartida<T> :: escribir ( const T& dato ) { * (this->ptrDatos) = dato; } template <class T> T MemoriaCompartida<T> :: leer () const { return ( *(this->ptrDatos) ); } template <class T> int MemoriaCompartida<T> :: cantidadProcesosAdosados () const { shmid_ds estado; shmctl ( this->shmId,IPC_STAT,&estado ); return estado.shm_nattch; } #endif /* MEMORIACOMPARTIDA_H_ */
b8889099ceb58099c0b48f0b7b8312b3d3b46484
162038e68323bcd222b3b9bccfc41e0bdc6ea3f1
/Retro-Game/character.h
7b0f2b2d63b8b01a7723e97416a7918d3daf5d03
[]
no_license
Kanchevd/OldSchoolGame
818342b91e4a456f5a201d0e2a987c4ebdbccefa
4d768d4b5720a4c991aaa1d662ede370a6fdda87
refs/heads/master
2022-08-16T17:01:04.699534
2022-07-06T10:15:29
2022-07-06T10:15:29
168,710,720
0
0
null
null
null
null
UTF-8
C++
false
false
1,168
h
// File Made by Daniel Kanchev #ifndef CHARACTER_H #define CHARACTER_H #include <string> #include <iostream> #include <stdlib.h> using namespace std; class Character { public: //Constructor Character(); //Destructor virtual ~Character(); //Object Methods void initialize(string name); void dealDamage(int damageTaken); void restHP(int heal); bool isDead(); void setMaxHP(int newMax); void setMinDamage(int newMin); void setMaxDamage(int newMax); int Attack(); void setCurrHP(int newHP); void changeName(string newName); //Accessors inline const string& getname() const { return this->name; } inline const int& get_currHP() const { return this->currHP; } inline const int& get_maxHP() const { return this->maxHP; } inline const int& getMinDamage() const { return this->minDamage; } inline const bool& isPlayerCheck() const { return this->isPlayer; } inline const int& getMaxDamage() const { return this->maxDamage; } protected: //Object Attributes string name; int currHP; int maxHP; int maxDamage; int minDamage; bool isPlayer; }; #endif
10f23ac6154ba7a7fe39de0e71967c63825d81ff
962211a59766a896b7a8809256fe901e8990c623
/sounds/ex1.cpp
10f92f0b0ac71a6cc2cf23aef2e65898bc1ba8a4
[]
no_license
anastasiyakorsik/4_sem
18386c129006c0320e590f0202345d403d07fae2
d6f5c9a431210821d23345dec135f9ae0db17145
refs/heads/main
2023-04-15T12:53:05.867868
2021-04-16T16:39:18
2021-04-16T16:39:18
338,243,332
0
0
null
null
null
null
UTF-8
C++
false
false
1,212
cpp
#include <SFML\Audio.hpp> #include <SFML\Graphics.hpp> #include <vector> #include <iostream> const int N = 3; class MusicPlayer { public: MusicPlayer() { for (int i = 0; i < N; i++) music.push_back(new sf::Music); } ~MusicPlayer() { for (int i = 0; i < N; i++) delete music[i]; } std::vector <sf::Music*> music; void SetMusic(const std::vector<std::string>& musicFiles) { for (int i = 0; i < N; i++) music[i]->openFromFile(musicFiles[i]); } void Play() { if (cur_song < N && (cur_song == 0 || music[cur_song - 1]->getStatus() == sf::Music::Stopped)) { std::cout << "New Song: " << music[cur_song]->getDuration().asSeconds() << "\n"; music[cur_song]->play(); cur_song++; } } int cur_song = 0; }; int main() { std::vector<std::string> files({"ringtone.ogg", "sound1.ogg", "s3.ogg" }); MusicPlayer buffer; buffer.SetMusic(files); sf::RenderWindow window(sf::VideoMode(400, 400), "Sound"); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } buffer.Play(); window.display(); window.clear(); } }
49dd0b235ce0457cc9170a53879476532c9b1086
cf82c683957818fbdf54ad75bf7dea124de5ef70
/Egal/egal.cpp
aad9b88484fb5bd29a2691cb289c544f3edf730c
[ "MIT" ]
permissive
ciupmeister/cplusplus
c10effd2e75a80a79a7e7d2c7e11c3647160cd90
0e95cd01d20b22404aa4166c71d5a9e834a5a21b
refs/heads/master
2021-05-10T12:08:31.064850
2017-07-19T21:43:14
2017-07-19T21:43:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,225
cpp
#include <fstream> #include <iostream> #include <vector> #include <unordered_map> using namespace std; const int maxn = 100005; int n, m, heavy[maxn], leaf[maxn], ansnr[maxn], ansfr[maxn], key[maxn]; vector <int> g[maxn]; unordered_map<int, int> fr[maxn]; inline void dfs(int node, int father) { int heaviest = -1; heavy[node] = 1; for(vector <int> :: iterator it = g[node].begin(), fin = g[node].end() ; it != fin ; ++ it) { if(*it == father) continue; dfs(*it, node); heavy[node] += heavy[*it]; if(heaviest == -1) heaviest = *it; else if(heavy[heaviest] < heavy[*it]) heaviest = *it; } if(heaviest == -1) { leaf[node] = ++ m; ++ fr[leaf[node]][key[node]]; ansnr[node] = key[node]; ansfr[node] = 1; return ; } leaf[node] = leaf[heaviest]; ++ fr[leaf[node]][key[node]]; ansfr[node] = fr[leaf[node]][key[node]]; ansnr[node] = key[node]; for(vector <int> :: iterator it = g[node].begin(), fin = g[node].end() ; it != fin ; ++ it) { if(*it == father || *it == heaviest) continue; for(unordered_map<int, int> :: iterator k = fr[leaf[*it]].begin(), fk = fr[leaf[*it]].end() ; k != fk ; ++ k) fr[leaf[node]][k->first] += k->second; } for(vector <int> :: iterator it = g[node].begin(), fin = g[node].end() ; it != fin ; ++ it) { if(*it == father) continue; for(unordered_map<int, int> :: iterator k = fr[leaf[*it]].begin(), fk = fr[leaf[*it]].end() ; k != fk ; ++ k) if(fr[leaf[node]][k->first] > ansfr[node] || (fr[leaf[node]][k->first] == ansfr[node] && k->first < ansnr[node])) { ansnr[node] = k->first; ansfr[node] = fr[leaf[node]][k->first]; } } } int main() { ifstream fin("egal.in"); ofstream fout("egal.out"); fin >> n; for(int i = 1 ; i < n ; ++ i) { int x, y; fin >> x >> y; g[x].push_back(y); g[y].push_back(x); } for(int i = 1 ; i <= n ; ++ i) fin >> key[i]; dfs(1, 0); for(int i = 1 ; i <= n ; ++ i) fout << ansnr[i] << ' ' << ansfr[i] << '\n'; }
98588d99ec5d3bd38da34b57089da431ba4402de
a9235b4ffcd0a2def4f0dc9ede6a4cd3e29303e7
/C++/Helloworld.cpp
f7bb5618d725bd7835e2bc7ece29c607b950a5cd
[]
no_license
Tejas-Dalvi-99/HacktoberFest2021_
ed32c08092f5c9ac3736d5eb2551d66ad37a4568
305fddac66f93ca57559c0908b5086fae095599d
refs/heads/main
2023-09-03T08:23:14.680231
2021-10-29T16:18:24
2021-10-29T16:18:24
422,639,694
1
0
null
null
null
null
UTF-8
C++
false
false
87
cpp
#include<iostream> using namespace std; int main() { cout<<"Hello World"; return 0; }
a3b1380856b53c22c36ffaf9657010212fc41372
02a51e20e1f17d18ab98834a1ae0bd8ef8c28615
/Matrix/matrix.h
3a54b3fde2842ffde2f1a73a487527aa31a2bbf3
[]
no_license
gusario/C-Projects
e06458ace7ffa3aa3a534fe34b76266c298acab7
a5665f81c2dfc6afb547fff305091d940e88f6ab
refs/heads/master
2020-04-02T03:18:36.606671
2018-10-20T23:32:18
2018-10-20T23:32:18
153,957,518
1
0
null
null
null
null
UTF-8
C++
false
false
1,145
h
// // matrix.h // Matrix // // Created by David Nurdinov on 04/04/2018. // Copyright © 2018 David Nurdinov. All rights reserved. // #ifndef matrix_h #define matrix_h #include <iostream> using namespace std; class cMatrix { friend ostream &operator<<(ostream & out, const cMatrix & matrix); private: int width; int height; double **values; public: cMatrix(); cMatrix(int h, int w); cMatrix(const cMatrix& other); ~cMatrix(); void print(); cMatrix operator +(const cMatrix& other); void operator *=(double k); cMatrix operator*(double k); void operator =(const cMatrix& other); inline int getHeight(){return height;} inline int getWidth(){return width;} double getElement(int h, int w); //TODO: void setElement(int h, int w, double value);//DONE void operator *=(const cMatrix& other); //DONE cMatrix operator*(const cMatrix &other);//DONE bool operator ==(const cMatrix& other);//DONE cMatrix transpose();//DONE double getChet(); //EXTRA double determinant();//Almost DONE cMatrix inverse();//NOT DONE }; #endif /* matrix_h */
977b4faa794ae8f719b2ffe92e4bf89dea317221
ff159114378c138a15a96aa44f64ff57e75ecba2
/ABC089/D.cpp
4e964e35d01504e46fac9c89a3049e06ecaec2d9
[]
no_license
dwmkFD/AtCoderSubmit
5876e25b3107f79e8831ac35faed7ef249648c29
0dcba96aa29f83ae41ee7f29042050e9ce6e916c
refs/heads/master
2023-07-12T22:06:45.541303
2023-06-26T03:57:42
2023-06-26T03:57:42
177,874,409
0
0
null
null
null
null
UTF-8
C++
false
false
3,356
cpp
#include <algorithm> #include <iostream> #include <numeric> #include <vector> #include <string> #include <bitset> #include <tuple> #include <cmath> #include <map> template<typename T> bool chmax( T &a, const T &b ) { if ( a <= b ) { a = b; return ( true ); } else { return ( false ); } } template<typename T> bool chmin( T &a, const T &b ) { if ( a >= b ) { a = b; return ( true ); } else { return ( false ); } } using namespace std; using ll = long long; using ull = unsigned long long; using Pll = pair<ll, ll>; using Pull = pair<ull, ull>; #define eb emplace_back #define pb push_back #define mp make_pair #define mt make_tuple #define F first #define S second #define rep( i, n ) for ( int i = 0; i < (int)( n ); ++i ) #define reps( i, n ) for ( int i = 1; i <= (int)( n ); ++i ) #define rrep( i, n ) for ( int i = (int)( ( n ) - 1 ); i >= 0; --i ) #define rreps( i, n ) for ( int i = (int)( ( n ) ); i > 0; --i ) #define arep( i, v ) for ( auto &&i : ( v ) ) template<typename T> T gcd( const T a, const T b ) { return ( b ? gcd( b, a % b ) : a ); } #define ALL( c ) ( c ).begin(), ( c ).end() #define RALL( c ) ( c ).rbegin(), ( c ).rend() #define UNIQUE( c ) ( c ).erase( unique( ( c ).begin(), ( c ).end() ), ( c ).end() ) constexpr ll MOD = 1000000007LL; #define y0 y3487465 #define y1 y8687969 #define j0 j1347829 #define j1 j234892 #define next asdnext #define prev asdprev template<typename T = ll> class UnionFind { public: UnionFind( T n ) { rep( i, n ) { par.resize( n ); siz.resize( n ); par[i] = i; siz[i] = 1; } } T find( T x ) { if ( x == par[x] ) return ( x ); else return( par[x] = find( par[x] ) ); } void unite( T x, T y ) { T xx = find( x ); T yy = find( y ); if ( xx == yy ) return; if ( siz[xx] <= siz[yy] ) swap( xx, yy ); par[yy] = xx; siz[xx] += siz[yy]; } private: vector<T> par, siz; }; template<typename T = ll> T power( T a, T b, T m = MOD ) { T res = 1; while ( b > 0 ) { if ( b & 1 ) res = res * a % m; a = a * a % m; b >>= 1; } return ( res ); } /* constexpr ll MAX = 500010; ll fact[MAX]; ll inv[MAX]; ll inv_fact[MAX]; template<typename T> void initComb( T n, T m = MOD ) { fact[0] = fact[1] = inv_fact[0] = inv_fact[1] = 1; inv[1] = 1; for ( int i = 2; i < n; i++ ) { fact[i] = ( fact[i - 1] * i ) % m; inv[i] = m - inv[m % i] * ( m / i ) % m; inv_fact[i] = inv_fact[i - 1] * inv[i] % m; } } template<typename T> T comb( T n, T r, T m = MOD ) { if ( n < r ) return ( 0 ); if ( n < 0 || r < 0 ) return ( 0 ); return ( fact[n] * ( inv_fact[r] * inv_fact[n - r] % m ) % m ); } */ void replace( string &s, string t, string r ) { string::size_type p = 0; while ( ( p = s.find( t, p ) ) != string::npos ) { s.replace( p, t.length(), r ); p += r.length(); } } int main() { ll H, W, D; cin >> H >> W >> D; map<ll, Pll> m; rep( i, H ) { rep( j, W ) { ll tmp; cin >> tmp; m[tmp] = mp( i, j ); } } vector<ll> d( H * W + 1, 0 ); for ( int i = D + 1; i <= H * W; i++ ) { d[i] = d[i - D] + abs( m[i].F - m[i - D].F ) + abs( m[i].S - m[i - D].S ); } ll Q; cin >> Q; vector<Pll> vlr( Q ); rep( i, Q ) cin >> vlr[i].F >> vlr[i].S; rep( i, Q ) { cout << ( d[vlr[i].S] - d[vlr[i].F] ) << endl; } return ( 0 ); }
f1821560d4d1c882b745386a02c4ed690be7f420
25e99a0af5751865bce1702ee85cc5c080b0715c
/c++/code/mybooksources/Chapter06/code/WebSocketServer/net/TcpServer.h
19daa52f2e03e131da83424dc45720be70f1acdb
[]
no_license
jasonblog/note
215837f6a08d07abe3e3d2be2e1f183e14aa4a30
4471f95736c60969a718d854cab929f06726280a
refs/heads/master
2023-05-31T13:02:27.451743
2022-04-04T11:28:06
2022-04-04T11:28:06
35,311,001
130
67
null
2023-02-10T21:26:36
2015-05-09T02:04:40
C
GB18030
C++
false
false
3,526
h
#pragma once #include <atomic> //#include <cstdatomic> // 老gcc头文件 #include <map> #include <memory> //#include "EventLoop.h" #include "TcpConnection.h" namespace net { class Acceptor; class EventLoop; class EventLoopThreadPool; /// /// TCP server, supports single-threaded and thread-pool models. /// /// This is an interface class, so don't expose too much details. class TcpServer { public: typedef std::function<void(EventLoop*)> ThreadInitCallback; enum Option { kNoReusePort, kReusePort, }; //TcpServer(EventLoop* loop, const InetAddress& listenAddr); TcpServer(EventLoop* loop, const InetAddress& listenAddr, const std::string& nameArg, Option option = kReusePort); //TODO: 默认修改成kReusePort ~TcpServer(); // force out-line dtor, for scoped_ptr members. const std::string& hostport() const { return hostport_; } const std::string& name() const { return name_; } EventLoop* getLoop() const { return loop_; } /// Set the number of threads for handling input. /// /// Always accepts new connection in loop's thread. /// Must be called before @c start /// @param numThreads /// - 0 means all I/O in loop's thread, no thread will created. /// this is the default value. /// - 1 means all I/O in another thread. /// - N means a thread pool with N threads, new connections /// are assigned on a round-robin basis. //void setThreadNum(int numThreads); void setThreadInitCallback(const ThreadInitCallback& cb) { threadInitCallback_ = cb; } /// valid after calling start() //std::shared_ptr<EventLoopThreadPool> threadPool() //{ return threadPool_; } /// Starts the server if it's not listenning. /// /// It's harmless to call it multiple times. /// Thread safe. void start(int workerThreadCount = 4); void stop(); /// Set connection callback. /// Not thread safe. void setConnectionCallback(const ConnectionCallback& cb) { connectionCallback_ = cb; } /// Set message callback. /// Not thread safe. void setMessageCallback(const MessageCallback& cb) { messageCallback_ = cb; } /// Set write complete callback. /// Not thread safe. void setWriteCompleteCallback(const WriteCompleteCallback& cb) { writeCompleteCallback_ = cb; } void removeConnection(const TcpConnectionPtr& conn); private: /// Not thread safe, but in loop void newConnection(int sockfd, const InetAddress& peerAddr); /// Thread safe. /// Not thread safe, but in loop void removeConnectionInLoop(const TcpConnectionPtr& conn); typedef std::map<string, TcpConnectionPtr> ConnectionMap; private: EventLoop* loop_; // the acceptor loop const string hostport_; const string name_; std::shared_ptr<Acceptor> acceptor_; // avoid revealing Acceptor std::shared_ptr<EventLoopThreadPool> eventLoopThreadPool_; ConnectionCallback connectionCallback_; MessageCallback messageCallback_; WriteCompleteCallback writeCompleteCallback_; ThreadInitCallback threadInitCallback_; std::atomic<int> started_; int nextConnId_; // always in loop thread ConnectionMap connections_; }; }
15601c3920c5eca7239796923ffa4e951b1fd634
a349dbf18493cd9bbb2bc9288671f2c981aa8233
/Tree/Construct Tree from Inorder & Postorder.cpp
92a39ebee26a72bac6b8fb9d885223df0edb5adc
[]
no_license
Ashish-kumar7/geeks-for-geeks-solutions
dd67fb596162d866a8043460f07e2052dc38446d
045dc4041323b4f912fcb50ae087eb5865fbacb3
refs/heads/master
2022-10-27T14:43:09.588551
2022-10-02T10:41:56
2022-10-02T10:41:56
228,147,267
38
50
null
2022-10-19T05:32:24
2019-12-15T07:40:36
C++
UTF-8
C++
false
false
929
cpp
Node * treehelper(int in[],int pos[], int inS, int inE , int posS, int posE) { if(inS >inE) { return NULL; } int rootdata=pos[posE]; int rootindex; for(int i=inS;i<=inE;i++) { if(in[i]==rootdata) { rootindex=i; break; } } int rootindex1; for(int j=posS;j<=posE;j++) { if(pos[j]==rootdata) { rootindex1=j; break; } } int LinS=inS; int LinE=rootindex-1; int LposS=posS; int LposE=LinE-LinS+LposS; int RinS=rootindex+1; int RinE=inE; int RposS=LposE+1; int RposE=rootindex1-1; Node * node1= new Node(rootdata); node1->left=treehelper(in,pos,LinS,LinE,LposS,LposE); node1->right=treehelper(in,pos,RinS,RinE,RposS,RposE); return node1; } Node *buildTree(int in[], int pos[], int n) { return treehelper(in,pos,0,n-1,0,n-1); }
6b7e3f5ea18eea4a6b99b18dcc70f12438a67dec
71215bbfe377511deb4aa6d7d059dcd42474271a
/src/tests.cpp
a8bc6c8549088893597716d1957d3fec8687977a
[]
no_license
FuSoftware/QImpact
e5ca8a54ca5a73355e175c083ab3a10e47e03da5
70e8946ec6fa56d9c8a6666507cc510c99ddb81d
refs/heads/master
2021-05-12T08:33:31.576438
2018-01-12T20:20:41
2018-01-12T20:20:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,564
cpp
#include "tests.h" #include <QDebug> #include <QSqlRecord> #include <QSqlError> #include "models/sql/sqltablelist.h" #include "models/sql/sqltable.h" #include "controllers/sqlcontroller.h" #include "view/database/qproducttablewidget.h" QString Tests::DB_PATH = "/tmp/qimpact/db_test.db"; void Tests::testSql(QString path, QVector<QString> schema_queries, QVector<QString> use_queries) { SqlController *c = new SqlController(path); bool ok = c->open(); if(!ok) return; for(int i=0;i<schema_queries.size();i++) c->runQuery(schema_queries[i]); for(int i=0;i<use_queries.size();i++) { QSqlQuery q = c->runQuery(use_queries[i]); if(q.isSelect()) { QString out = ""; while(q.next()) { QSqlRecord rec = q.record(); for(int i=0;i<rec.count();i++) out += rec.value(i).toString() + ", "; } qDebug() << out; } } c->close(); } void Tests::testDbTable(QString path) { QVector<QString> schema_queries; QVector<QString> use_queries; //Delete possible existing table schema_queries.append(QString("DROP TABLE db_test;")); //Re-create the test table schema_queries.append(QString("CREATE TABLE db_test (id INTEGER, name TEXT, age REAL);")); //Add records schema_queries.append(QString("INSERT INTO db_test (id, name, age) " "VALUES" "(0, 'Jean', 40.5)," "(1, 'Marc', 25.1)," "(2, 'Luc', 30.6)," "(3, 'Michel', 21.9)")); //Read the records use_queries.append(QString("SELECT * FROM db_test WHERE id = 3;")); use_queries.append(QString("SELECT * FROM db_test WHERE name LIKE 'Marc';")); use_queries.append(QString("SELECT * FROM db_test WHERE age > 30.1;")); testSql(path, schema_queries, use_queries); } void Tests::testProductTable() { SqlController *c = new SqlController(Tests::DB_PATH); bool ok = c->open(); if(!ok) return; SqlTable *t = SQL_TABLE_LIST::SQL_TABLE_PRODUCTS; //c->runQuery(t->drop()); //c->runQuery(t->create()); //c->runQuery(QString("INSERT INTO %1 (%2) VALUES(%3)").arg(t->getName(), "ID, LABEL, QUANTITY, WEIGHT", "'PA', 'Produit A', 95, 0.8")); QSqlTableModel *m = c->getTable(t->getName()); QProductTableWidget *w = new QProductTableWidget(); w->setTable(m); w->show(); }
20081ea3455a23a8a4d99fefb5ade1491b33f480
27d8e9a313aff26f24effb372dc78f9ad3a4f70c
/tests/pkgs.at.cxx
2083a0448118fd826c8d1726efff4829a185e14e
[]
no_license
imgcre/rt_charger
2fb8d6e16dbc128d86d3a6b8cf39245c58f3d10a
89dd15caec5eb38107f4498f01d6e7a3756ba554
refs/heads/master
2023-05-13T21:06:25.085636
2021-06-12T19:36:33
2021-06-12T19:36:33
366,671,036
0
0
null
null
null
null
UTF-8
C++
false
false
562
cxx
#include <rtthread.h> #include <rtdevice.h> #include <at.h> #include <board.h> constexpr auto kPwrPin = GET_PIN(B, 2); static int init_at() { rt_pin_mode(kPwrPin, PIN_MODE_OUTPUT); rt_pin_write(kPwrPin, PIN_HIGH); struct serial_configure conf = RT_SERIAL_CONFIG_DEFAULT; rt_base_t bufsz = 512; conf.bufsz = bufsz; conf.baud_rate = BAUD_RATE_115200; auto serial = rt_device_find("uart2"); rt_device_control(serial, RT_DEVICE_CTRL_CONFIG, &conf); at_client_init("uart2", bufsz); return RT_EOK; } INIT_APP_EXPORT(init_at);
be083004e5c444219114e6e4d49a2174d7400460
8cd0983fb401b527c185917395590787d3e9286c
/src/cookie.cpp
e05e1fd9d23005c85d907111e56373fcd2dca51d
[ "curl", "LicenseRef-scancode-unknown-license-reference" ]
permissive
kartiksura/curl-asio
b52bbdd506f2310eac2b40147fe317b64f2ad6ed
8410a3535ce30b0abccd08d7d33563d5599f5274
refs/heads/master
2020-12-25T06:03:34.946568
2014-05-22T23:13:53
2014-05-22T23:13:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
955
cpp
#include <curl-asio/cookie.h> namespace curl { const std::string &cookie::name() const { return name_; } const std::string &cookie::value() const { return value_; } const cookie::time_point &cookie::expiry() const { return expiry_; } const std::string &cookie::path() const { return path_; } const std::string &cookie::domain() const { return domain_; } bool cookie::secure() const { return secure_; } bool cookie::http_only() const { return http_only_; } void cookie::set_name(const std::string &name) { name_ = name; } void cookie::set_value(const std::string &value) { value_ = value; } void cookie::set_expiry(const time_point &expiry) { expiry_ = expiry; } void cookie::set_path(const std::string &path) { path_ = path; } void cookie::set_domain(const std::string &domain) { domain_ = domain; } void cookie::set_secure(bool secure) { secure = secure_; } void cookie::set_http_only(bool http_only) { http_only_ = http_only; } } // namespace curl
ef56aa1511ab1dfc875bdc123e6be6f0dcdda353
8ade3d20f78abfa461af79cd346882beaca07edc
/universal/smartpay/src/admin.h
c1731529745918491120c31eac1fcfc583329339
[]
no_license
eboladev/smarterp
337867fa215eb6042cdfdb894b8cbd2e766b98c3
94e7af29485885fb3f1e9a900dea54903a817b0a
refs/heads/master
2020-12-29T00:55:51.144001
2014-05-30T05:07:22
2014-05-30T05:07:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
592
h
#ifndef ADMIN_H #define ADMIN_H #include <QtGui> #include <QtSql> #include <QMainWindow> namespace Ui { class Admin; } class Admin : public QMainWindow { Q_OBJECT public: explicit Admin(QWidget *parent = 0, QSqlDatabase database = QSqlDatabase()); ~Admin(); private slots: void on_SaveAndNew_clicked(); void on_SaveChanges_clicked(); void on_Delete_clicked(); void on_treeView_clicked(const QModelIndex &index); private: Ui::Admin *ui; QSqlDatabase db; void loadUsers(); QSqlQueryModel *model; void clearTexts(); bool isAdding; QString currentID; }; #endif // ADMIN_H
cdfd06d407fea457b083225735b8d558a184f9c8
88407be67288c3efe796e099b1ac8e0bfd40443f
/Dependencies/include/Ogre/OgreMain/OgrePlatform.h
8b16e2db732a4e2604707cde27904502c1753b7a
[]
no_license
hubi037/GameDev
29b0fa1a2e4ebe1c1eba61ee5afd3c153a368dbb
7ceb736dbaddbc52a544f2f1ca3af4c53958fe79
refs/heads/master
2020-05-18T09:02:05.707152
2013-06-23T12:19:03
2013-06-23T12:19:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,533
h
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2013 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #ifndef __Platform_H_ #define __Platform_H_ #include "OgreConfig.h" namespace Ogre { /* Initial platform/compiler-related stuff to set. */ #define OGRE_PLATFORM_WIN32 1 #define OGRE_PLATFORM_LINUX 2 #define OGRE_PLATFORM_APPLE 3 #define OGRE_PLATFORM_APPLE_IOS 4 #define OGRE_PLATFORM_ANDROID 5 #define OGRE_PLATFORM_NACL 6 #define OGRE_PLATFORM_WINRT 7 #define OGRE_COMPILER_MSVC 1 #define OGRE_COMPILER_GNUC 2 #define OGRE_COMPILER_BORL 3 #define OGRE_COMPILER_WINSCW 4 #define OGRE_COMPILER_GCCE 5 #define OGRE_COMPILER_CLANG 6 #define OGRE_ENDIAN_LITTLE 1 #define OGRE_ENDIAN_BIG 2 #define OGRE_ARCHITECTURE_32 1 #define OGRE_ARCHITECTURE_64 2 /* Finds the compiler type and version. */ #if defined( __GCCE__ ) # define OGRE_COMPILER OGRE_COMPILER_GCCE # define OGRE_COMP_VER _MSC_VER //# include <staticlibinit_gcce.h> // This is a GCCE toolchain workaround needed when compiling with GCCE #elif defined( __WINSCW__ ) # define OGRE_COMPILER OGRE_COMPILER_WINSCW # define OGRE_COMP_VER _MSC_VER #elif defined( _MSC_VER ) # define OGRE_COMPILER OGRE_COMPILER_MSVC # define OGRE_COMP_VER _MSC_VER #elif defined( __clang__ ) # define OGRE_COMPILER OGRE_COMPILER_CLANG # define OGRE_COMP_VER (((__clang_major__)*100) + \ (__clang_minor__*10) + \ __clang_patchlevel__) #elif defined( __GNUC__ ) # define OGRE_COMPILER OGRE_COMPILER_GNUC # define OGRE_COMP_VER (((__GNUC__)*100) + \ (__GNUC_MINOR__*10) + \ __GNUC_PATCHLEVEL__) #elif defined( __BORLANDC__ ) # define OGRE_COMPILER OGRE_COMPILER_BORL # define OGRE_COMP_VER __BCPLUSPLUS__ # define __FUNCTION__ __FUNC__ #else # pragma error "No known compiler. Abort! Abort!" #endif /* See if we can use __forceinline or if we need to use __inline instead */ #if OGRE_COMPILER == OGRE_COMPILER_MSVC # if OGRE_COMP_VER >= 1200 # define FORCEINLINE __forceinline # endif #elif defined(__MINGW32__) # if !defined(FORCEINLINE) # define FORCEINLINE __inline # endif #else # define FORCEINLINE __inline #endif /* Finds the current platform */ #if defined( __WIN32__ ) || defined( _WIN32 ) # if defined(WINAPI_FAMILY) # define __OGRE_HAVE_DIRECTXMATH 1 # include <winapifamily.h> # if WINAPI_FAMILY == WINAPI_FAMILY_APP|| WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP # define DESKTOP_APP 1 # define PHONE 2 # define OGRE_PLATFORM OGRE_PLATFORM_WINRT # define _CRT_SECURE_NO_WARNINGS # define _SCL_SECURE_NO_WARNINGS # if WINAPI_FAMILY == WINAPI_FAMILY_APP # define OGRE_WINRT_TARGET_TYPE DESKTOP_APP # endif # if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP # define OGRE_WINRT_TARGET_TYPE PHONE # define ENABLE_SHADERS_CACHE_LOAD 1 # endif # else # define OGRE_PLATFORM OGRE_PLATFORM_WIN32 # endif # else # define OGRE_PLATFORM OGRE_PLATFORM_WIN32 # endif #elif defined(__FLASHCC__) # define OGRE_PLATFORM OGRE_PLATFORM_FLASHCC #elif defined( __APPLE_CC__) // Device Simulator // Both requiring OS version 4.0 or greater # if __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ >= 40000 || __IPHONE_OS_VERSION_MIN_REQUIRED >= 40000 # define OGRE_PLATFORM OGRE_PLATFORM_APPLE_IOS # else # define OGRE_PLATFORM OGRE_PLATFORM_APPLE # endif #elif defined(__ANDROID__) # define OGRE_PLATFORM OGRE_PLATFORM_ANDROID #elif defined( __native_client__ ) # define OGRE_PLATFORM OGRE_PLATFORM_NACL # ifndef OGRE_STATIC_LIB # error OGRE must be built as static for NaCl (OGRE_STATIC=true in CMake) # endif # ifdef OGRE_BUILD_RENDERSYSTEM_D3D9 # error D3D9 is not supported on NaCl (OGRE_BUILD_RENDERSYSTEM_D3D9 false in CMake) # endif # ifdef OGRE_BUILD_RENDERSYSTEM_GL # error OpenGL is not supported on NaCl (OGRE_BUILD_RENDERSYSTEM_GL=false in CMake) # endif # ifndef OGRE_BUILD_RENDERSYSTEM_GLES2 # error GLES2 render system is required for NaCl (OGRE_BUILD_RENDERSYSTEM_GLES2=false in CMake) # endif #else # define OGRE_PLATFORM OGRE_PLATFORM_LINUX #endif /* Find the arch type */ #if defined(__x86_64__) || defined(_M_X64) || defined(__powerpc64__) || defined(__alpha__) || defined(__ia64__) || defined(__s390__) || defined(__s390x__) # define OGRE_ARCH_TYPE OGRE_ARCHITECTURE_64 #else # define OGRE_ARCH_TYPE OGRE_ARCHITECTURE_32 #endif // For generating compiler warnings - should work on any compiler // As a side note, if you start your message with 'Warning: ', the MSVC // IDE actually does catch a warning :) #define OGRE_QUOTE_INPLACE(x) # x #define OGRE_QUOTE(x) OGRE_QUOTE_INPLACE(x) #define OGRE_WARN( x ) message( __FILE__ "(" QUOTE( __LINE__ ) ") : " x "\n" ) // For marking functions as deprecated #if OGRE_COMPILER == OGRE_COMPILER_MSVC # define OGRE_DEPRECATED(func) __declspec(deprecated) func #elif OGRE_COMPILER == OGRE_COMPILER_GNUC || OGRE_COMPILER == OGRE_COMPILER_CLANG # define OGRE_DEPRECATED(func) func __attribute__ ((deprecated)) #else # pragma message("WARNING: You need to implement OGRE_DEPRECATED for this compiler") # define OGRE_DEPRECATED(func) func #endif //---------------------------------------------------------------------------- // Windows Settings #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT // If we're not including this from a client build, specify that the stuff // should get exported. Otherwise, import it. # if defined( OGRE_STATIC_LIB ) // Linux compilers don't have symbol import/export directives. # define _OgreExport # define _OgrePrivate # else # if defined( OGRE_NONCLIENT_BUILD ) # define _OgreExport __declspec( dllexport ) # else # if defined( __MINGW32__ ) # define _OgreExport # else # define _OgreExport __declspec( dllimport ) # endif # endif # define _OgrePrivate # endif // Win32 compilers use _DEBUG for specifying debug builds. // for MinGW, we set DEBUG # if defined(_DEBUG) || defined(DEBUG) # define OGRE_DEBUG_MODE 1 # else # define OGRE_DEBUG_MODE 0 # endif // Disable unicode support on MingW for GCC 3, poorly supported in stdlibc++ // STLPORT fixes this though so allow if found // MinGW C++ Toolkit supports unicode and sets the define __MINGW32_TOOLBOX_UNICODE__ in _mingw.h // GCC 4 is also fine #if defined(__MINGW32__) # if OGRE_COMP_VER < 400 # if !defined(_STLPORT_VERSION) # include<_mingw.h> # if defined(__MINGW32_TOOLBOX_UNICODE__) || OGRE_COMP_VER > 345 # define OGRE_UNICODE_SUPPORT 1 # else # define OGRE_UNICODE_SUPPORT 0 # endif # else # define OGRE_UNICODE_SUPPORT 1 # endif # else # define OGRE_UNICODE_SUPPORT 1 # endif #else # define OGRE_UNICODE_SUPPORT 1 #endif #endif // OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT //---------------------------------------------------------------------------- // Linux/Apple/iOs/Android/NaCl Settings #if OGRE_PLATFORM == OGRE_PLATFORM_LINUX || OGRE_PLATFORM == OGRE_PLATFORM_APPLE || OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS || \ OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_NACL || OGRE_PLATFORM == OGRE_PLATFORM_FLASHCC // Enable GCC symbol visibility # if defined( OGRE_GCC_VISIBILITY ) # define _OgreExport __attribute__ ((visibility("default"))) # define _OgrePrivate __attribute__ ((visibility("hidden"))) # else # define _OgreExport # define _OgrePrivate # endif // A quick define to overcome different names for the same function # define stricmp strcasecmp # ifdef DEBUG # define OGRE_DEBUG_MODE 1 # else # define OGRE_DEBUG_MODE 0 # endif // Always enable unicode support for the moment // Perhaps disable in old versions of gcc if necessary #define OGRE_UNICODE_SUPPORT 1 #endif //---------------------------------------------------------------------------- // Android Settings #if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID # ifdef OGRE_UNICODE_SUPPORT # undef OGRE_UNICODE_SUPPORT # endif # define OGRE_UNICODE_SUPPORT 1 # define CLOCKS_PER_SEC 1000 // A quick define to overcome different names for the same function # define stricmp strcasecmp # ifdef DEBUG # define OGRE_DEBUG_MODE 1 # else # define OGRE_DEBUG_MODE 0 # endif #endif //---------------------------------------------------------------------------- // FlashCC Settings #if OGRE_PLATFORM == OGRE_PLATFORM_FLASHCC # ifdef OGRE_UNICODE_SUPPORT # undef OGRE_UNICODE_SUPPORT # endif # define OGRE_UNICODE_SUPPORT 0 # ifdef DEBUG # define OGRE_DEBUG_MODE 1 # else # define OGRE_DEBUG_MODE 0 # endif #endif //---------------------------------------------------------------------------- // Endian Settings // check for BIG_ENDIAN config flag, set OGRE_ENDIAN correctly #ifdef OGRE_CONFIG_BIG_ENDIAN # define OGRE_ENDIAN OGRE_ENDIAN_BIG #else # define OGRE_ENDIAN OGRE_ENDIAN_LITTLE #endif //---------------------------------------------------------------------------- // Library suffixes // "_d" for debug builds, nothing otherwise #if OGRE_DEBUG_MODE # define OGRE_BUILD_SUFFIX "_d" #else # define OGRE_BUILD_SUFFIX "" #endif // Integer formats of fixed bit width typedef unsigned int uint32; typedef unsigned short uint16; typedef unsigned char uint8; typedef int int32; typedef short int16; typedef signed char int8; // define uint64 type #if OGRE_COMPILER == OGRE_COMPILER_MSVC typedef unsigned __int64 uint64; typedef __int64 int64; #else typedef unsigned long long uint64; typedef long long int64; #endif // Disable these warnings (too much noise) #if OGRE_COMPILER == OGRE_COMPILER_MSVC # define _CRT_SECURE_NO_WARNINGS # define _SCL_SECURE_NO_WARNINGS // Turn off warnings generated by long std templates // This warns about truncation to 255 characters in debug/browse info # pragma warning (disable : 4786) // Turn off warnings generated by long std templates // This warns about truncation to 255 characters in debug/browse info # pragma warning (disable : 4503) // disable: "<type> needs to have dll-interface to be used by clients' // Happens on STL member variables which are not public therefore is ok # pragma warning (disable : 4251) // disable: "non dll-interface class used as base for dll-interface class" // Happens when deriving from Singleton because bug in compiler ignores // template export # pragma warning (disable : 4275) // disable: "C++ Exception Specification ignored" // This is because MSVC 6 did not implement all the C++ exception // specifications in the ANSI C++ draft. # pragma warning( disable : 4290 ) // disable: "no suitable definition provided for explicit template // instantiation request" Occurs in VC7 for no justifiable reason on all // #includes of Singleton # pragma warning( disable: 4661) // disable: deprecation warnings when using CRT calls in VC8 // These show up on all C runtime lib code in VC8, disable since they clutter // the warnings with things we may not be able to do anything about (e.g. // generated code from nvparse etc). I doubt very much that these calls // will ever be actually removed from VC anyway, it would break too much code. # pragma warning( disable: 4996) // disable: "conditional expression constant", always occurs on // OGRE_MUTEX_CONDITIONAL when no threading enabled # pragma warning (disable : 201) // disable: "unreferenced formal parameter" // Many versions of VC have bugs which generate this error in cases where they shouldn't # pragma warning (disable : 4100) // disable: "behavior change: an object of POD type constructed with an initializer of the form () will be default-initialized" // We have this issue in OgreMemorySTLAlloc.h - so we see it over and over # pragma warning (disable : 4345) #endif } #endif