blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
e2001ab66f1e9ec7ba810a235605715b839add8f
107e972a4ff9edadf5bb119a1efd73e871ae48d5
/Daisy_Image_Win32Project_MM/Daisy_Image_Win32Project_MM/stdafx.cpp
508bdc6739e494899824002f54d94ee1abd0e919
[ "MIT" ]
permissive
mmalinova/Computer_Graphics
10aeab77fa54b3a2ade4cdddeee2286defa5b9e6
716e3d46a744050b1e6aec0a226e0214e0a4eead
refs/heads/main
2023-02-11T12:37:26.198528
2021-01-08T19:27:30
2021-01-08T19:27:30
303,166,892
0
0
null
null
null
null
UTF-8
C++
false
false
351
cpp
// stdafx.cpp : source file that includes just the standard includes // Daisy_Image_Win32Project_MM.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file #pragma comment(lib, "GdiPlus.lib")
[ "noreply@github.com" ]
noreply@github.com
b36d2976126c5c6e8bdaee34d7eeeb640b83169d
15e0315c5d92040e66853409d145c457c652c3dc
/fs_3/istream.h
17a840d015d552a7b8dba6d8d4012a3e7fcc0c7e
[]
no_license
nbermudezs/ArduinoFS
d47429f1bb15ece28b377855e94ba5dce9589e73
62f7534b242aa0633061e3980906fe0b7dd6b7c7
refs/heads/master
2021-01-01T05:33:06.307193
2013-05-31T21:13:18
2013-05-31T21:13:18
9,890,550
2
0
null
null
null
null
UTF-8
C++
false
false
8,809
h
/* Arduino SdFat Library * Copyright (C) 2012 by William Greiman * * This file is part of the Arduino SdFat 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 3 of the License, 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 the Arduino SdFat Library. If not, see * <http://www.gnu.org/licenses/>. */ #ifndef istream_h #define istream_h /** * \file * \brief \ref istream class */ #include <ios.h> /** * \class istream * \brief Input Stream */ class istream : public virtual ios { public: istream() {} /** call manipulator * \param[in] pf function to call * \return the stream */ istream& operator>>(istream& (*pf)(istream& str)) { return pf(*this); } /** call manipulator * \param[in] pf function to call * \return the stream */ istream& operator>>(ios_base& (*pf)(ios_base& str)) { pf(*this); return *this; } /** call manipulator * \param[in] pf function to call * \return the stream */ istream& operator>>(ios& (*pf)(ios& str)) { pf(*this); return *this; } /** * Extract a character string * \param[out] str location to store the string. * \return Is always *this. Failure is indicated by the state of *this. */ istream& operator>>(char *str) { getStr(str); return *this; } /** * Extract a character * \param[out] ch location to store the character. * \return Is always *this. Failure is indicated by the state of *this. */ istream& operator>>(char& ch) { getChar(&ch); return *this; } /** * Extract a character string * \param[out] str location to store the string. * \return Is always *this. Failure is indicated by the state of *this. */ istream& operator>>(signed char *str) { getStr(reinterpret_cast<char*>(str)); return *this; } /** * Extract a character * \param[out] ch location to store the character. * \return Is always *this. Failure is indicated by the state of *this. */ istream& operator>>(signed char& ch) { getChar(reinterpret_cast<char*>(&ch)); return *this; } /** * Extract a character string * \param[out] str location to store the string. * \return Is always *this. Failure is indicated by the state of *this. */ istream& operator>>(unsigned char *str) { getStr(reinterpret_cast<char*>(str)); return *this; } /** * Extract a character * \param[out] ch location to store the character. * \return Is always *this. Failure is indicated by the state of *this. */ istream& operator>>(unsigned char& ch) { getChar(reinterpret_cast<char*>(&ch)); return *this; } /** * Extract a value of type bool. * \param[out] arg location to store the value. * \return Is always *this. Failure is indicated by the state of *this. */ istream& operator>>(bool& arg) { getBool(&arg); return *this; } /** * Extract a value of type short. * \param[out] arg location to store the value. * \return Is always *this. Failure is indicated by the state of *this. */ istream &operator>>(short& arg) { // NOLINT getNumber(&arg); return *this; } /** * Extract a value of type unsigned short. * \param[out] arg location to store the value. * \return Is always *this. Failure is indicated by the state of *this. */ istream &operator>>(unsigned short& arg) { // NOLINT getNumber(&arg); return *this; } /** * Extract a value of type int. * \param[out] arg location to store the value. * \return Is always *this. Failure is indicated by the state of *this. */ istream &operator>>(int& arg) { getNumber(&arg); return *this; } /** * Extract a value of type unsigned int. * \param[out] arg location to store the value. * \return Is always *this. Failure is indicated by the state of *this. */ istream &operator>>(unsigned int& arg) { getNumber(&arg); return *this; } /** * Extract a value of type long. * \param[out] arg location to store the value. * \return Is always *this. Failure is indicated by the state of *this. */ istream &operator>>(long& arg) { // NOLINT getNumber(&arg); return *this; } /** * Extract a value of type unsigned long. * \param[out] arg location to store the value. * \return Is always *this. Failure is indicated by the state of *this. */ istream &operator>>(unsigned long& arg) { // NOLINT getNumber(&arg); return *this; } /** * Extract a value of type double. * \param[out] arg location to store the value. * \return Is always *this. Failure is indicated by the state of *this. */ istream &operator>> (double& arg) { getDouble(&arg); return *this; } /** * Extract a value of type float. * \param[out] arg location to store the value. * \return Is always *this. Failure is indicated by the state of *this. */ istream &operator>> (float& arg) { double v; getDouble(&v); arg = v; return *this; } /** * Extract a value of type void*. * \param[out] arg location to store the value. * \return Is always *this. Failure is indicated by the state of *this. */ istream& operator>> (void*& arg) { uint32_t val; getNumber(&val); arg = reinterpret_cast<void*>(val); return *this; } /** * \return The number of characters extracted by the last unformatted * input function. */ streamsize gcount() const {return gcount_;} int get(); istream& get(char& ch); istream& get(char *str, streamsize n, char delim = '\n'); istream& getline(char *str, streamsize count, char delim = '\n'); istream& ignore(streamsize n = 1, int delim= -1); int peek(); // istream& read(char *str, streamsize count); // streamsize readsome(char *str, streamsize count); /** * \return the stream position */ pos_type tellg() {return tellpos();} /** * Set the stream position * \param[in] pos The absolute position in which to move the read pointer. * \return Is always *this. Failure is indicated by the state of *this. */ istream& seekg(pos_type pos) { if (!seekpos(pos)) setstate(failbit); return *this; } /** * Set the stream position. * * \param[in] off An offset to move the read pointer relative to way. * \a off is a signed 32-bit int so the offset is limited to +- 2GB. * \param[in] way One of ios::beg, ios::cur, or ios::end. * \return Is always *this. Failure is indicated by the state of *this. */ istream& seekg(off_type off, seekdir way) { if (!seekoff(off, way)) setstate(failbit); return *this; } void skipWhite(); protected: /// @cond SHOW_PROTECTED /** * Internal - do not use * \return */ virtual int16_t getch() = 0; /** * Internal - do not use * \param[out] pos * \return */ int16_t getch(PfsPos_t* pos) { getpos(pos); return getch(); } /** * Internal - do not use * \param[out] pos */ virtual void getpos(PfsPos_t* pos) = 0; /** * Internal - do not use * \param[in] pos */ virtual bool seekoff(off_type off, seekdir way) = 0; virtual bool seekpos(pos_type pos) = 0; virtual void setpos(PfsPos_t* pos) = 0; virtual pos_type tellpos() = 0; /// @endcond private: size_t gcount_; void getBool(bool *b); void getChar(char* ch); bool getDouble(double* value); template <typename T> void getNumber(T* value); bool getNumber(uint32_t posMax, uint32_t negMax, uint32_t* num); void getStr(char *str); int16_t readSkip(); }; //------------------------------------------------------------------------------ template <typename T> void istream::getNumber(T* value) { uint32_t tmp; if ((T)-1 < 0) { // number is signed, max positive value uint32_t const m = ((uint32_t)-1) >> (33 - sizeof(T) * 8); // max absolute value of negative number is m + 1. if (getNumber(m, m + 1, &tmp)) { *value = (T)tmp; } } else { // max unsigned value for T uint32_t const m = (T)-1; if (getNumber(m, m, &tmp)) { *value = (T)tmp; } } } #endif // istream_h
[ "moy_contrabass@hotmail.com" ]
moy_contrabass@hotmail.com
a67a69aad24e41a4e89d5b709c59bd93847210f1
a84ae7b277b8460bd79ca0874ae4d868e7c7b89d
/Round613/A.cpp
288282974d93de6814cfa169126e031d48e05ee8
[]
no_license
copydev/CodeForces
238a3d7ce1d415e9e22d5f8f50421808c88986b7
2a91104b156be12eb6ed11845605c0419b43a503
refs/heads/master
2022-12-10T22:36:50.384398
2020-09-07T11:51:36
2020-09-07T11:51:36
293,514,367
0
0
null
null
null
null
UTF-8
C++
false
false
317
cpp
#include <bits/stdc++.h> using namespace std; #define ll long long #define REP(i,n) for(ll i = 0;i<n;++i) int main() { ll n; cin>>n; string s; cin>>s; ll left =0, right = 0; REP(i,n){ if(s[i] == 'L'){ left++; } else{ right++; } } ll ans = 1 + left + right; cout<<ans<<endl; return 0; }
[ "idtypes@gmail.com" ]
idtypes@gmail.com
6c7cd60c3434748d868f02d5b9a8ee13965fee29
717cfbb815d7232f69b7836e6b8a19ab1c8214ec
/sstd_tools/build_install/boost_filesystem/static_boost/mpl/aux_/config/eti.hpp
ba50980ea01e11df4d5fa148fd9266a0bbf9bcc9
[]
no_license
ngzHappy/QtQmlBook
b1014fb862aa6b78522e06ec59b94b13951edd56
296fabfd4dc47b884631598c05a2f123e1e5a3b5
refs/heads/master
2020-04-09T04:34:41.261770
2019-02-26T13:13:15
2019-02-26T13:13:15
160,028,971
4
0
null
null
null
null
UTF-8
C++
false
false
1,250
hpp
 #ifndef BOOST_MPL_AUX_CONFIG_ETI_HPP_INCLUDED #define BOOST_MPL_AUX_CONFIG_ETI_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2001-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Id$ // $Date$ // $Revision$ #include <static_boost/mpl/aux_/config/msvc.hpp> #include <static_boost/mpl/aux_/config/workaround.hpp> // flags for MSVC 6.5's so-called "early template instantiation bug" #if !defined(BOOST_MPL_CFG_MSVC_60_ETI_BUG) \ && !defined(BOOST_MPL_PREPROCESSING_MODE) \ && BOOST_WORKAROUND(BOOST_MSVC, < 1300) # define BOOST_MPL_CFG_MSVC_60_ETI_BUG #endif #if !defined(BOOST_MPL_CFG_MSVC_70_ETI_BUG) \ && !defined(BOOST_MPL_PREPROCESSING_MODE) \ && BOOST_WORKAROUND(BOOST_MSVC, == 1300) # define BOOST_MPL_CFG_MSVC_70_ETI_BUG #endif #if !defined(BOOST_MPL_CFG_MSVC_ETI_BUG) \ && !defined(BOOST_MPL_PREPROCESSING_MODE) \ && ( defined(BOOST_MPL_CFG_MSVC_60_ETI_BUG) \ || defined(BOOST_MPL_CFG_MSVC_70_ETI_BUG) \ ) # define BOOST_MPL_CFG_MSVC_ETI_BUG #endif #endif // BOOST_MPL_AUX_CONFIG_ETI_HPP_INCLUDED
[ "zhaixueqiang@hotmail.com" ]
zhaixueqiang@hotmail.com
2cab5a9accd451a1982350fc8c46f6e686561f40
0ea75f3fc067140d59214875e49eb987c8268667
/CSCI3010-Object Oriented Programming/HW2/test.cpp
c8f5be087cf960af4ec7bc0bc3fa2ffc86adc077
[]
no_license
adamtenhoeve/CU-Undergrad
64a5c0c2e1467e4c1a01a742df1b716167b2ec6d
a8770cd56baa38265d98bd06d72ea9e76ce8c7f8
refs/heads/master
2023-06-26T11:30:37.456237
2021-07-30T20:28:52
2021-07-30T20:28:52
294,558,186
0
0
null
null
null
null
UTF-8
C++
false
false
8,128
cpp
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file #include "catch.hpp" #include "Item.h" #include "Store.h" #include "TextUI.h" #include <vector> using namespace std; // Name: Adam Ten Hoeve // First test case checks the basic functionallity of the Item class TEST_CASE ("Checking functions of the Item class", "[Item]") { // Declare 3 basic items Item i1(1, "cheese", 10.25, 4); Item i2(2, "butter", 4.5, 6); Item i3(3, "Moose", 20, 1); // Test all the get functions so that they return the correct, associated variable. SECTION("Testing get_id") { REQUIRE(i1.get_id() == 1); REQUIRE(i2.get_id() == 2); REQUIRE(i3.get_id() == 3); } SECTION("Testing get_quantity") { REQUIRE(i1.get_quantity() == 4); REQUIRE(i2.get_quantity() == 6); REQUIRE(i3.get_quantity() == 1); } SECTION("Testing get_cost") { REQUIRE(i1.get_cost() == 10.25); REQUIRE(i2.get_cost() == 4.5); REQUIRE(i3.get_cost() == 20); } SECTION("Testing get_type") { REQUIRE(i1.get_type() == "cheese"); REQUIRE(i2.get_type() == "butter"); REQUIRE(i3.get_type() == "Moose"); } // Test the IncreaseQuantity funciton to make sure that it increase from where it was by the set amount. SECTION("Testing IncreaseQuantity") { i1.IncreaseQuantity(3); REQUIRE(i1.get_quantity() == 7); i1.IncreaseQuantity(4); REQUIRE(i1.get_quantity() == 11); } // Make sure the DecreaseQuantity function decrease the item quantity from where it was by the set amount. SECTION("Testing DecreaseQuantity") { i1.DecreaseQuantity(3); REQUIRE(i1.get_quantity() == 1); i1.DecreaseQuantity(4); REQUIRE(i1.get_quantity() == -3); i3.DecreaseQuantity(1); REQUIRE(i3.get_quantity() == 0); } // Makes sure it has the right output for the text output used in the other classes. SECTION("Testing ToString") { REQUIRE(i1.ToString() == "cheese: 10.25 - 4"); REQUIRE(i2.ToString() == "butter: 4.50 - 6"); REQUIRE(i3.ToString() == "Moose: 20.00 - 1"); } // Makes clones of one of the items, then checks its output string to make sure it is the same but with a quantity of 1. SECTION("Testing Clone") { Item *temp = i1.Clone(); REQUIRE(temp -> ToString() == "cheese: 10.25 - 1"); Item *temp2 = i3.Clone(); REQUIRE(temp2 -> ToString() == "Moose: 20.00 - 1"); } } ////////////////////////// TESTING SHOPPINGCART CLASS /////////////////////////////////////////////////////////////// // Testing the add and remove functions. Do so with the displaycart function. TEST_CASE("Testing the DisplayCart function in ShoppingCart", "[ShoppingCart]") { // Declare 3 items used above and a shopping cart. Item i1(1, "cheese", 10.25, 4); Item i2(2, "butter", 4.5, 6); Item i3(3, "Moose", 20, 1); ShoppingCart sc; // Add items to the shopping cart and guarantee that they are there in the correct amounts. SECTION("Testing AddItem and DisplayCart") { REQUIRE(sc.DisplayCart() == ""); sc.AddItem(&i1); REQUIRE(sc.DisplayCart() == "cheese: 10.25 - 4\n"); sc.AddItem(&i2); REQUIRE(sc.DisplayCart() == "cheese: 10.25 - 4\nbutter: 4.50 - 6\n"); } // Remove items from the shopping cart and make sure amounts stay consistent SECTION("Testing RemoveItem and DisplayCart") { REQUIRE(sc.DisplayCart() == ""); sc.RemoveItem(&i1); REQUIRE(sc.DisplayCart() == ""); sc.AddItem(&i1); sc.AddItem(&i2); REQUIRE(sc.DisplayCart() == "cheese: 10.25 - 3\nbutter: 4.50 - 6\n"); sc.RemoveItem(&i2); REQUIRE(sc.DisplayCart() == "cheese: 10.25 - 3\nbutter: 4.50 - 5\n"); } } // Make sure the clearcart function works by adding items to the cart, then calling the function and checking if the cart is empty. TEST_CASE("Testing the ClearCart function in ShoppingCart", "[ShoppingCart]") { Item i1(1, "cheese", 10.25, 4); Item i2(2, "butter", 4.5, 6); Item i3(3, "Moose", 20, 1); ShoppingCart sc; sc.AddItem(&i1); sc.AddItem(&i2); sc.AddItem(&i3); REQUIRE(sc.DisplayCart() == "cheese: 10.25 - 4\nbutter: 4.50 - 6\nMoose: 20.00 - 1\n"); sc.ClearCart(); REQUIRE(sc.DisplayCart() == ""); } // Check that the get_items function returns the correct items in a vector of items TEST_CASE("Testing the get_items() function in ShoppingCart", "[ShoppingCart]") { Item i1(1, "cheese", 10.25, 4); Item i2(2, "butter", 4.5, 6); Item i3(3, "Moose", 20, 1); ShoppingCart sc; vector<Item*> temp; vector<Item*> test; temp = sc.get_items(); REQUIRE(temp.empty()); sc.AddItem(&i1); test.push_back(&i1); sc.AddItem(&i2); test.push_back(&i2); REQUIRE(sc.get_items() == test); sc.RemoveItem(&i1); REQUIRE(sc.get_items() == test); } //////////////////////////////////// STORE TEST CASES //////////////////////////////////////////////////////// // Make sure the DisplayInventory displays all items in the correct syntax. TEST_CASE("Testing DisplayInventory for Store class") { string filename = "store.txt"; Store store(filename); REQUIRE(store.DisplayInventory() == "Tea: 2.00 - 6\nTall Candle: 7.00 - 13\nKettle: 15.00 - 1\n"); } // Check that the Items() function retuns a map of the same items in the proper order. TEST_CASE("Testing Items() function in the Store Class") { string filename = "store.txt"; Store store(filename); map<int, string> testMap; testMap.insert({1, "Tea: 2.00 - 6"}); testMap.insert({2, "Tall Candle: 7.00 - 13"}); testMap.insert({3, "Kettle: 15.00 - 1"}); REQUIRE(store.Items() == testMap); } // Seeing if the interfunctionallity between the Store and ShoppingCart classes works. TEST_CASE("Testing AddItemToCart, RemoveItemFromCart and CartItems functions in the Store Class") { string filename = "store.txt"; Store store(filename); store.AddItemToCart(1); store.AddItemToCart(2); // Check to make sure items added through Store are in shopping cart. REQUIRE(store.DisplayInventory() == "Tea: 2.00 - 5\nTall Candle: 7.00 - 12\nKettle: 15.00 - 1\n"); store.AddItemToCart(3); REQUIRE(store.DisplayInventory() == "Tea: 2.00 - 5\nTall Candle: 7.00 - 12\nKettle: 15.00 - 0\n"); map<int, string> testMap; testMap.insert({1, "Tea: 2.00 - 1"}); testMap.insert({2, "Tall Candle: 7.00 - 1"}); testMap.insert({3, "Kettle: 15.00 - 1"}); // Check that the items are the correct items, with the correct amounts and syntax. REQUIRE(store.CartItems() == testMap); // Remove items from the cart and check that everything is still hunky-dory. store.RemoveItemFromCart(1); store.RemoveItemFromCart(3); testMap.erase(1); testMap.erase(3); REQUIRE(store.CartItems() == testMap); } // Checking if the Store is able to display all the items in the cart and remove all of the items in the cart. TEST_CASE("Testing DisplayCart and ClearCart functions in Store class", "[Store]") { string filename = "store.txt"; Store store(filename); REQUIRE(store.DisplayCart() == ""); // Add initial items to the cart store.AddItemToCart(1); store.AddItemToCart(2); REQUIRE(store.DisplayCart() == "Tea: 2.00 - 1\nTall Candle: 7.00 - 1\n"); // Add the second of an item to the cart store.AddItemToCart(1); REQUIRE(store.DisplayCart() == "Tea: 2.00 - 2\nTall Candle: 7.00 - 1\n"); store.ClearCart(); REQUIRE(store.DisplayCart() == ""); } // Does the function correctly calculate the price of multiple items. TEST_CASE("Testing Checkout function in Store class", "[Store]") { string filename = "store.txt"; Store store(filename); // Test basic functionality. store.AddItemToCart(1); REQUIRE(store.Checkout() == 2.1769); // Test multiple of the same item. store.AddItemToCart(1); store.AddItemToCart(2); store.AddItemToCart(2); REQUIRE(store.Checkout() == 17.4152); } // Make sure that the class returns the correct name of the store, given in the text file. TEST_CASE("Testing get_name function in Store class", "[Store]") { string filename = "store.txt"; Store store(filename); REQUIRE(store.get_name() == "My Store"); }
[ "noreply@github.com" ]
noreply@github.com
912ce32b5363c60b24600527263b46ca052ad727
404547b1ec3237f02342fe65e957f32851ce1495
/Game/ge_combatmove.h
33c51b40dbe8458f5775d5a8ab2f5cbf5554da5d
[]
no_license
Adanos-Gotoman/GenomeSDK-R
c5e3a5d57c4fb721b15bb7f572454f2a3021561a
cf87f21fca83b37d2e186fb69b083b72932f9c8c
refs/heads/master
2023-03-16T07:05:00.799421
2021-02-19T16:07:09
2021-02-19T16:07:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,397
h
#ifndef GE_COMBATMOVE_H_INCLUDED #define GE_COMBATMOVE_H_INCLUDED enum gECombatAction { gECombatAction_Attack = 0x00000001, gECombatAction_Parade = 0x00000002, gECombatAction_Stumble = 0x00000003, gECombatAction_ForceDWORD = GE_FORCE_DWORD }; enum gECombatMove { gECombatMove_None = 0x00000000, gECombatMove_Attack = 0x00000001, gECombatMove_AttackSec = 0x00000002, gECombatMove_Attack3 = 0x00000003, //FIXME: Ranged Attack? gECombatMove_AttackLeft = 0x00000004, gECombatMove_AttackRight = 0x00000005, gECombatMove_StrafeAttackLeft = 0x00000006, gECombatMove_StrafeAttackRight = 0x00000007, gECombatMove_CounterAttack = 0x00000008, // StormAttack gECombatMove_CounterParade = 0x00000009, gECombatMove_Parade = 0x0000000A, gECombatMove_AttackStumble = 0x0000000B, gECombatMove_AttackStumbleLeft = 0x0000000C, gECombatMove_AttackStumbleRight = 0x0000000D, gECombatMove_ParadeStumble = 0x0000000E, gECombatMove_ParadeStumbleHeavy = 0x0000000F, gECombatMove_Finishing = 0x00000010, gECombatMove_Wait = 0x00000011, gECombatMove_GoTo = 0x00000012, gECombatMove_StormTo = 0x00000013, gECombatMove_GoFwd = 0x00000014, gECombatMove_GoBack = 0x00000015, gECombatMove_GoLeft = 0x00000016, gECombatMove_GoRight = 0x00000017, gECombatMove_JumpBack = 0x00000018, gECombatMove_Stumble = 0x00000019, gECombatMove_StumbleLight = 0x0000001A, gECombatMove_StumbleHeavy = 0x0000001B, gECombatMove_StumbleOverlay = 0x0000001C, gECombatMove_StumbleOverlayLight = 0x0000001D, gECombatMove_StumbleOverlayHeavy = 0x0000001E, gECombatMove_StumbleBack = 0x0000001F, gECombatMove_StumbleDown = 0x00000020, gECombatMove_StumbleDownBack = 0x00000021, gECombatMove_StumbleDead = 0x00000022, gECombatMove_StumbleDeadBack = 0x00000023, gECombatMove_StrafeLeft = 0x00000024, gECombatMove_StrafeRight = 0x00000025, gECombatMove_Aim = 0x00000026, gECombatMove_Sniper = 0x00000027, gECombatMove_Reload = 0x00000028, gECombatMove_ForceDWORD = GE_FORCE_DWORD }; enum gECombatMoveSide { gECombatMoveSide_Left = 0x00000000, gECombatMoveSide_Right = 0x00000001, gECombatMoveSide_ForceDWORD = GE_FORCE_DWORD }; enum gECombatParadeType { gECombatParadeType_None = 0x00000000, gECombatParadeType_Fist = 0x00000001, gECombatParadeType_Weapon = 0x00000002, gECombatParadeType_Magic = 0x00000004, gECombatParadeType_Ranged = 0x00000008, gECombatParadeType_Monster = 0x00000010, gECombatParadeType_Shield = gECombatParadeType_Fist | gECombatParadeType_Weapon | gECombatParadeType_Ranged | gECombatParadeType_Monster, gECombatParadeType_ForceDWORD = GE_FORCE_DWORD }; class gCCombatMove; struct gSCombatMoveInstance { gCCombatMove * m_pMove; gCCombatSystem_PS * m_pSystem; gCCombatStyle * m_pStyle; GEFloat __FIXME; // ...more members in derived structs }; GE_ASSERT_SIZEOF( gSCombatMoveInstance, 0x0010 ) struct gSComboData { public: virtual ~gSComboData( void ); public: gSCombatMoveInstance * m_pInstance; GEFloat m_fBegin; GEFloat m_fEnd; // ...more members in derived structs }; GE_ASSERT_SIZEOF( gSComboData, 0x0010 ) struct gSFAIMoveDesc { gCCombatAI * m_pCombatAI; int m_enumFIXME; GEFloat m_fWeight; }; GE_ASSERT_SIZEOF( gSFAIMoveDesc, 0x000C ) class GE_DLLIMPORT gCCombatMove : public gCCombatObject { public: virtual bCPropertyObjectTypeBase * GetObjectType( void ) const; public: virtual bEResult Create( void ); protected: virtual void Destroy( void ); public: virtual bEResult PostInitializeProperties( void ); public: virtual ~gCCombatMove( void ); public: virtual gECombatAction GetCombatAction( void ) const; public: virtual gECombatParadeType GetParadeType( gCCombatStyle * ) const; public: virtual gECombatParadeType GetAttackType( gCCombatStyle * ) const; public: virtual gCCombatMove * GetMove( gCCombatSystem_PS *, gECombatMove ) const; public: virtual eCGeometryEntity * GetWeapon( gCCombatSystem_PS * ) const; public: virtual GEBool CanStartComboMove( gSCombatMoveInstance *, gECombatMove ) const; public: virtual GEBool StartStumble( gSCombatMoveInstance *, gCCombatSystem_PS * ); public: virtual GEBool StartCombo( gSCombatMoveInstance *, gECombatMove ); public: virtual void StopCombo( gSCombatMoveInstance * ); public: virtual gSCombatMoveInstance * Start( gCCombatSystem_PS *, gCCombatStyle *, gSComboData * ); public: virtual void Stop( gSCombatMoveInstance * ); public: virtual void Interupt( gSCombatMoveInstance * ); public: virtual void Finish( gSCombatMoveInstance * ); public: virtual GEBool Update( gSCombatMoveInstance * ); public: virtual GEBool IsInParade( gSCombatMoveInstance *, gECombatParadeType, bCVector const & ); public: virtual GEBool IsInAttack( gCCombatSystem_PS *, eCGeometryEntity *, GEFloat & ); public: virtual GEBool IsInteruptable( gSCombatMoveInstance * ) const; public: virtual GEFloat GetFAIWeight( gCCombatSystem_PS *, gCCombatSystem_PS *, gSFAIMoveDesc &, gSComboData * ); public: virtual gSComboData * CreateComboData( gSCombatMoveInstance * ); public: virtual GEBool CanCounterMove( gCCombatSystem_PS *, gCCombatSystem_PS *, gECombatMove ) const; public: virtual void OnAction( gSAction const &, gSCombatMoveInstance * ); public: virtual void GetDependencies( bTObjArray< bCString > &, bTObjArray< bCString > &, bTObjArray< eCTemplateEntityProxy > & ); private: static bCPropertyObjectTypeBase thisType; protected: gCCombatSpecies * m_pCombatSpecies; protected: GEBool CanParade( gECombatParadeType, gECombatParadeType ) const; gCCombatMove * GetMoveOfStyle( gCCombatSystem_PS *, bCString const &, gECombatMove ) const; void Invalidate( void ); void SetCombatSpecies( gCCombatSpecies * ); public: static bCObjectBase * GE_STDCALL CreateObject( void ); static bCPropertyObjectTypeBase & GE_STDCALL GetThisType( void ); static void GE_STDCALL StaticConstructor( bCPropertyObjectTypeBase & ); public: gCCombatSpecies * GetCombatSpecies( void ) const; public: gCCombatMove & operator = ( gCCombatMove const & ); public: gCCombatMove( gCCombatMove const & ); gCCombatMove( void ); }; GE_ASSERT_SIZEOF( gCCombatMove, 0x0014 ) #endif
[ "gothicgame29@gmail.com" ]
gothicgame29@gmail.com
2f6f09fc43de10ed4d87e1f6159645f69a031236
30e1dc84fe8c54d26ef4a1aff000a83af6f612be
/src/external/boost/boost_1_68_0/libs/spirit/example/qi/compiler_tutorial/calc8/compiler.cpp
7d2195c83518e978dee7820a4819ed0ba9ba1a94
[ "BSL-1.0", "BSD-3-Clause" ]
permissive
Sitispeaks/turicreate
0bda7c21ee97f5ae7dc09502f6a72abcb729536d
d42280b16cb466a608e7e723d8edfbe5977253b6
refs/heads/main
2023-05-19T17:55:21.938724
2021-06-14T17:53:17
2021-06-14T17:53:17
385,034,849
1
0
BSD-3-Clause
2021-07-11T19:23:21
2021-07-11T19:23:20
null
UTF-8
C++
false
false
11,770
cpp
/*============================================================================= Copyright (c) 2001-2011 Joel de Guzman 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) =============================================================================*/ #include "compiler.hpp" #include "vm.hpp" #include <boost/foreach.hpp> #include <boost/variant/apply_visitor.hpp> #include <boost/assert.hpp> #include <boost/lexical_cast.hpp> #include <set> namespace client { namespace code_gen { void program::op(int a) { code.push_back(a); } void program::op(int a, int b) { code.push_back(a); code.push_back(b); } void program::op(int a, int b, int c) { code.push_back(a); code.push_back(b); code.push_back(c); } int const* program::find_var(std::string const& name) const { std::map<std::string, int>::const_iterator i = variables.find(name); if (i == variables.end()) return 0; return &i->second; } void program::add_var(std::string const& name) { std::size_t n = variables.size(); variables[name] = n; } void program::print_variables(std::vector<int> const& stack) const { typedef std::pair<std::string, int> pair; BOOST_FOREACH(pair const& p, variables) { std::cout << " " << p.first << ": " << stack[p.second] << std::endl; } } void program::print_assembler() const { std::vector<int>::const_iterator pc = code.begin(); std::vector<std::string> locals(variables.size()); typedef std::pair<std::string, int> pair; BOOST_FOREACH(pair const& p, variables) { locals[p.second] = p.first; std::cout << " local " << p.first << ", @" << p.second << std::endl; } std::map<std::size_t, std::string> lines; std::set<std::size_t> jumps; while (pc != code.end()) { std::string line; std::size_t address = pc - code.begin(); switch (*pc++) { case op_neg: line += " op_neg"; break; case op_not: line += " op_not"; break; case op_add: line += " op_add"; break; case op_sub: line += " op_sub"; break; case op_mul: line += " op_mul"; break; case op_div: line += " op_div"; break; case op_eq: line += " op_eq"; break; case op_neq: line += " op_neq"; break; case op_lt: line += " op_lt"; break; case op_lte: line += " op_lte"; break; case op_gt: line += " op_gt"; break; case op_gte: line += " op_gte"; break; case op_and: line += " op_and"; break; case op_or: line += " op_or"; break; case op_load: line += " op_load "; line += boost::lexical_cast<std::string>(locals[*pc++]); break; case op_store: line += " op_store "; line += boost::lexical_cast<std::string>(locals[*pc++]); break; case op_int: line += " op_int "; line += boost::lexical_cast<std::string>(*pc++); break; case op_true: line += " op_true"; break; case op_false: line += " op_false"; break; case op_jump: { line += " op_jump "; std::size_t pos = (pc - code.begin()) + *pc++; if (pos == code.size()) line += "end"; else line += boost::lexical_cast<std::string>(pos); jumps.insert(pos); } break; case op_jump_if: { line += " op_jump_if "; std::size_t pos = (pc - code.begin()) + *pc++; if (pos == code.size()) line += "end"; else line += boost::lexical_cast<std::string>(pos); jumps.insert(pos); } break; case op_stk_adj: line += " op_stk_adj "; line += boost::lexical_cast<std::string>(*pc++); break; } lines[address] = line; } std::cout << "start:" << std::endl; typedef std::pair<std::size_t, std::string> line_info; BOOST_FOREACH(line_info const& l, lines) { std::size_t pos = l.first; if (jumps.find(pos) != jumps.end()) std::cout << pos << ':' << std::endl; std::cout << l.second << std::endl; } std::cout << "end:" << std::endl; } bool compiler::operator()(unsigned int x) const { program.op(op_int, x); return true; } bool compiler::operator()(bool x) const { program.op(x ? op_true : op_false); return true; } bool compiler::operator()(ast::variable const& x) const { int const* p = program.find_var(x.name); if (p == 0) { std::cout << x.id << std::endl; error_handler(x.id, "Undeclared variable: " + x.name); return false; } program.op(op_load, *p); return true; } bool compiler::operator()(ast::operation const& x) const { if (!boost::apply_visitor(*this, x.operand_)) return false; switch (x.operator_) { case ast::op_plus: program.op(op_add); break; case ast::op_minus: program.op(op_sub); break; case ast::op_times: program.op(op_mul); break; case ast::op_divide: program.op(op_div); break; case ast::op_equal: program.op(op_eq); break; case ast::op_not_equal: program.op(op_neq); break; case ast::op_less: program.op(op_lt); break; case ast::op_less_equal: program.op(op_lte); break; case ast::op_greater: program.op(op_gt); break; case ast::op_greater_equal: program.op(op_gte); break; case ast::op_and: program.op(op_and); break; case ast::op_or: program.op(op_or); break; default: BOOST_ASSERT(0); return false; } return true; } bool compiler::operator()(ast::unary const& x) const { if (!boost::apply_visitor(*this, x.operand_)) return false; switch (x.operator_) { case ast::op_negative: program.op(op_neg); break; case ast::op_not: program.op(op_not); break; case ast::op_positive: break; default: BOOST_ASSERT(0); return false; } return true; } bool compiler::operator()(ast::expression const& x) const { if (!boost::apply_visitor(*this, x.first)) return false; BOOST_FOREACH(ast::operation const& oper, x.rest) { if (!(*this)(oper)) return false; } return true; } bool compiler::operator()(ast::assignment const& x) const { if (!(*this)(x.rhs)) return false; int const* p = program.find_var(x.lhs.name); if (p == 0) { std::cout << x.lhs.id << std::endl; error_handler(x.lhs.id, "Undeclared variable: " + x.lhs.name); return false; } program.op(op_store, *p); return true; } bool compiler::operator()(ast::variable_declaration const& x) const { int const* p = program.find_var(x.assign.lhs.name); if (p != 0) { std::cout << x.assign.lhs.id << std::endl; error_handler(x.assign.lhs.id, "Duplicate variable: " + x.assign.lhs.name); return false; } bool r = (*this)(x.assign.rhs); if (r) // don't add the variable if the RHS fails { program.add_var(x.assign.lhs.name); program.op(op_store, *program.find_var(x.assign.lhs.name)); } return r; } bool compiler::operator()(ast::statement const& x) const { return boost::apply_visitor(*this, x); } bool compiler::operator()(ast::statement_list const& x) const { BOOST_FOREACH(ast::statement const& s, x) { if (!(*this)(s)) return false; } return true; } bool compiler::operator()(ast::if_statement const& x) const { if (!(*this)(x.condition)) return false; program.op(op_jump_if, 0); // we shall fill this (0) in later std::size_t skip = program.size()-1; // mark its position if (!(*this)(x.then)) return false; program[skip] = program.size()-skip; // now we know where to jump to (after the if branch) if (x.else_) // We got an alse { program[skip] += 2; // adjust for the "else" jump program.op(op_jump, 0); // we shall fill this (0) in later std::size_t exit = program.size()-1; // mark its position if (!(*this)(*x.else_)) return false; program[exit] = program.size()-exit; // now we know where to jump to (after the else branch) } return true; } bool compiler::operator()(ast::while_statement const& x) const { std::size_t loop = program.size(); // mark our position if (!(*this)(x.condition)) return false; program.op(op_jump_if, 0); // we shall fill this (0) in later std::size_t exit = program.size()-1; // mark its position if (!(*this)(x.body)) return false; program.op(op_jump, int(loop-1) - int(program.size())); // loop back program[exit] = program.size()-exit; // now we know where to jump to (to exit the loop) return true; } bool compiler::start(ast::statement_list const& x) const { program.clear(); // op_stk_adj 0 for now. we'll know how many variables we'll have later program.op(op_stk_adj, 0); if (!(*this)(x)) { program.clear(); return false; } program[1] = program.nvars(); // now store the actual number of variables return true; } }}
[ "noreply@github.com" ]
noreply@github.com
ccfd1bd12057441f5d8a794cce7d925d964e2792
31509eba310cb145b38dbc6df8e7da6b4b225032
/processPointClouds.h
05719b8e29ba87487a2978ffc31bec3822e1802a
[]
no_license
SVPuranik12/SFND_Project_Lidar
10740dd1a649ae54fa346fd1c46d2da1a2b03fab
05413b64d769f58ca07abcbd0b8aa7a9555e650e
refs/heads/master
2022-11-23T14:30:00.711949
2020-07-27T14:53:20
2020-07-27T14:53:20
282,928,397
0
0
null
null
null
null
UTF-8
C++
false
false
2,218
h
// PCL lib Functions for processing point clouds #ifndef PROCESSPOINTCLOUDS_H_ #define PROCESSPOINTCLOUDS_H_ #include <pcl/io/pcd_io.h> #include <pcl/common/common.h> #include <pcl/filters/extract_indices.h> #include <pcl/filters/voxel_grid.h> #include <pcl/filters/crop_box.h> #include <pcl/kdtree/kdtree.h> #include <pcl/segmentation/sac_segmentation.h> #include <pcl/segmentation/extract_clusters.h> #include <pcl/common/transforms.h> #include <iostream> #include <string> #include <vector> #include <ctime> #include <chrono> #include "render/box.h" #include <unordered_set> #include <random> //#include "kdtree.h" #include "KDTree.h" template<typename PointT> class ProcessPointClouds { public: //constructor ProcessPointClouds(); //deconstructor ~ProcessPointClouds(); void numPoints(typename pcl::PointCloud<PointT>::Ptr cloud); typename pcl::PointCloud<PointT>::Ptr FilterCloud(typename pcl::PointCloud<PointT>::Ptr cloud, float filterRes, Eigen::Vector4f minPoint, Eigen::Vector4f maxPoint); std::pair<typename pcl::PointCloud<PointT>::Ptr, typename pcl::PointCloud<PointT>::Ptr> SeparateClouds(pcl::PointIndices::Ptr inliers, typename pcl::PointCloud<PointT>::Ptr cloud); std::pair<typename pcl::PointCloud<PointT>::Ptr, typename pcl::PointCloud<PointT>::Ptr> SegmentPlane(typename pcl::PointCloud<PointT>::Ptr cloud, int maxIterations, float distanceThreshold); void clusterHelper(int index, const std::vector<std::vector<float>>& points, std::vector<int>& cluster, std::vector<bool>& processed, KdTree* tree, float distanceTol); std::vector<std::vector<int>> euclideanCluster(const std::vector<std::vector<float>>& points, KdTree* tree, float distanceTol); std::vector<typename pcl::PointCloud<PointT>::Ptr> Clustering(typename pcl::PointCloud<PointT>::Ptr cloud, float clusterTolerance, int minSize, int maxSize); Box BoundingBox(typename pcl::PointCloud<PointT>::Ptr cluster); void savePcd(typename pcl::PointCloud<PointT>::Ptr cloud, std::string file); typename pcl::PointCloud<PointT>::Ptr loadPcd(std::string file); std::vector<boost::filesystem::path> streamPcd(std::string dataPath); }; #endif /* PROCESSPOINTCLOUDS_H_ */
[ "shashankpuranik12@gmail.com" ]
shashankpuranik12@gmail.com
972bac11a6663813d86e76770f2e67f1b5187767
23bc99fcf78c2c3f216e1ed3e7435579168094b1
/棋牌/PlatForm/Client/MainFrame/GameListTip.cpp
cfcc5dabac176818f10fa741b99dcf44794a3846
[]
no_license
15831944/liuwanbing
0b080a7d074dba30f81c6c2fbac136fd724d6793
4c527deb62446b0d24b1c5e6b65bc95ce949d942
refs/heads/master
2021-06-01T13:21:52.320236
2016-07-26T13:18:26
2016-07-26T13:18:26
null
0
0
null
null
null
null
GB18030
C++
false
false
4,821
cpp
// GameListTip.cpp : implementation file // #include "stdafx.h" #include "GameListTip.h" //#include "LongonDialog.h" DWORD CGameListTip::m_sCount = 0; // CGameListTip dialog IMPLEMENT_DYNAMIC(CGameListTip, CDialog) CGameListTip::CGameListTip(CWnd* pParent /*=NULL*/) : CDialog(CGameListTip::IDD, pParent) { } CGameListTip::~CGameListTip() { } void CGameListTip::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CGameListTip, CDialog) ON_BN_CLICKED(IDC_BUTTON_NEXT, &CGameListTip::OnBnClickedButtonNext) ON_WM_PAINT() ON_WM_CTLCOLOR() ON_WM_CREATE() ON_WM_SHOWWINDOW() ON_MESSAGE(WM_EXCHANGE_SKIN,OnExchangeSkin) END_MESSAGE_MAP() // CGameListTip message handlers //初始化 void CGameListTip::Init() { TCHAR Path[MAX_PATH]; wsprintf(Path,"%sdialog\\GameListTip.bmp",m_skinmgr.GetSkinPath()); m_backPic.SetLoadInfo(Path,CGameImageLink::m_bAutoLock); m_bnNext.Create(TEXT(""),WS_CHILD|WS_CLIPSIBLINGS|WS_VISIBLE,CRect(0,0,0,0),this,IDC_BUTTON_NEXT); wsprintf(Path,"%sdialog\\GameListTipBn.bmp",m_skinmgr.GetSkinPath()); m_bnNext.LoadButtonBitmap(Path,false); GetDlgItem(IDC_BUTTON_NEXT)->SetWindowText("(1/3)下一步"); CRect rc; GetClientRect(&rc); GetDlgItem(IDC_BUTTON_NEXT)->MoveWindow(rc.right/2-100,50+61,88,30); LoadSkin(); } BOOL CGameListTip::OnInitDialog() { Init(); return true; } LRESULT CGameListTip::OnExchangeSkin(WPARAM wpara,LPARAM lpara) { Init(); Invalidate(); return LRESULT(0); } void CGameListTip::OnBnClickedButtonNext() { CRect rect; GetWindowRect(&rect); m_sCount++; CString strPath = CBcfFile::GetAppPath(); strPath += "\\ListTip.ini"; switch (m_sCount%3) { case 0: //是否以后不再提示 if((((CButton *)GetDlgItem(IDC_CHECK_NOTIFY))->GetCheck()==BST_CHECKED)) { CString csIsNotify; csIsNotify.Format("%d",0); WritePrivateProfileString("IsNotify", "notify", csIsNotify, strPath); } OnOK(); break; case 1: LoadSkin(1); GetDlgItem(IDC_BUTTON_NEXT)->SetWindowText("(2/3)下一步"); break; case 2: LoadSkin(2); GetDlgItem(IDC_BUTTON_NEXT)->SetWindowText("(3/3)我知道了"); GetDlgItem(IDC_CHECK_NOTIFY)->ShowWindow(SW_SHOW); GetDlgItem(IDC_CHECK_NOTIFY)->SetWindowText("以后不再提示"); break; default: break; } // TODO: Add your control notification handler code here //MoveWindow(m_sCount*50+50, m_sCount*50+100, rect.Width(), rect.Height()); Invalidate(); } void CGameListTip::OnPaint() { // device context for painting // TODO: Add your message handler code here // Do not call CDialog::OnPaint() for painting messages CPaintDC dc(this); dc.SetBkMode(TRANSPARENT); CGameImageHelper TopListBarBottomHandle(&m_bkimage); AFCStretchImage(&dc, 0,0, m_bkimage.GetWidth(),m_bkimage.GetHeight(), m_bkimage, 0,0, m_bkimage.GetWidth(),m_bkimage.GetHeight(), m_bkimage.GetPixel(0,0)); } HBRUSH CGameListTip::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) { HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor); if(pWnd-> GetDlgCtrlID() == IDC_STATIC_INFOMATION) { pDC-> SetBkMode(TRANSPARENT); pDC-> SetTextColor(RGB(0,0,0)); return HBRUSH(GetStockObject(HOLLOW_BRUSH)); } if(pWnd-> GetDlgCtrlID() == IDC_CHECK_NOTIFY ) { pDC-> SetBkMode(TRANSPARENT); pDC-> SetTextColor(RGB(0,0,0)); return HBRUSH(GetStockObject(HOLLOW_BRUSH)); } return hbr; } int CGameListTip::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CDialog::OnCreate(lpCreateStruct) == -1) return -1; return 0; } void CGameListTip::OnShowWindow(BOOL bShow, UINT nStatus) { CDialog::OnShowWindow(bShow, nStatus); CRect rect; GetWindowRect(&rect); MoveWindow(50+164, 100+35, rect.Width(), rect.Height()); UpdateWindow(); } void CGameListTip::LoadSkin(int index) { CRect rect; int r,g,b; int cx,cy; CString s=CBcfFile::GetAppPath ();/////本地路径 CString strSkin = m_skinmgr.GetSkinBcfFileName(); CBcfFile f( s + strSkin); CString key="LogonDialog"; TCHAR path[MAX_PATH]; CString skinfolder; m_bkBrush = CreateSolidBrush(m_bkcolor); if ("skin0.bcf" == strSkin) skinfolder=f.GetKeyVal("skin0","skinfolder",m_skinmgr.GetSkinPath()); else skinfolder=f.GetKeyVal("skin1","skinfolder",m_skinmgr.GetSkinPath()); wsprintf(path,"%sdialog\\GameListTip%d.bmp",skinfolder,index); m_bkimage.SetLoadInfo(path,CGameImageLink::m_bAutoLock); CGameImageHelper ImageHandle(&m_bkimage); HRGN hRgn=AFCBmpToRgn(ImageHandle,m_bkimage.GetPixel(0,0),RGB(1,1,1)); if (hRgn!=NULL) { SetWindowRgn(hRgn,TRUE); DeleteObject(hRgn); } cx=ImageHandle.GetWidth(); cy=ImageHandle.GetHeight(); }
[ "970006421@qq.com" ]
970006421@qq.com
0f4b7ab143e4e8a7bd568526ca1b89a0859ee22c
fb803cd009ed4e39b150328b8548d9813b6a84d4
/realMap/camera.h
9f7f7fca42c35fbfcd27931721735d540f358df2
[]
no_license
Jeylu/realMap
c22ea29564add7351f2e32f9eb272b80090745f3
086588954dcaed5c083a193d2afa8ace87ae6f4e
refs/heads/master
2021-05-08T21:53:46.387783
2018-01-31T07:51:07
2018-01-31T07:51:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,397
h
#pragma once #include "stdafx.h" using namespace std; using namespace cv; class Camera { public: static const int m_camNum = 6; VideoCapture cap[6]; vector<string> m_camPath; vector<Point2f> m_pointList; vector<Point2f> m_pointListTrans; vector<Mat> m_transformList; vector<VideoCapture> m_capList; vector<Point2i> m_frameSizeList; const static int imgHeight = 1080; const static int imgWidth = 1920; double m_imgScale = 1; int m_key = 0; char* filename = "sdf"; vector<Mat> m_camMask; vector<Mat> m_camFrame; vector<Mat> m_camCurrrentFrame; vector<list<Mat> > m_camFrameList; Mat result, transMat; void init(); void init_generate(); vector<Point2f> getPointListTrans(vector<Point2f> pointList, vector <Mat> transformList); vector<Mat> getTransformList(vector <Point2f> pointList, vector <Point2f> pointListTrans); Mat getTransMat(vector<Mat> transformList); void saveTransformList(); void inittt(vector<Mat> & m_transformList); void warpMat(Mat & src, Mat & result, Mat transform, Mat mask); Mat drawCross(Mat & img, int distance = 100); static void on_mouse(int event, int x, int y, int flags, void* ustc); private: };
[ "musthan@126.com" ]
musthan@126.com
d85b0d6cc3112886ffdbcab4fd94f794fe4dfc67
350a99c4955c1d7bd56345b0f38ea26c10ff03ad
/Data_structure_labs/week_4/task_1.cpp
43662bde234fc2be68dd5ca5466eac9c419a8ac4
[]
no_license
shadid-reza/Lab_work_3rd_semester
b981ac249de21d5f37596cc4e61c5da76deb44c4
46a2c784b7cf5814ce72c858bb9f80c86f8b1777
refs/heads/main
2023-09-06T07:56:36.592862
2021-10-28T22:44:56
2021-10-28T22:44:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,693
cpp
//https://docs.google.com/document/d/1oJNfN1ZwwDoLR8_nfuyUOa1j--0I2lTTDjrIrluKTew/edit (linked list) #include <bits/stdc++.h> using namespace std; struct node { int data; struct node *next; }; struct node *head, *tail = NULL; void insert_front(int key) { struct node *temp = new node(); temp->data = key; temp->next = head; // the new head head = temp; // if tail in the 2nd pos then making it if (head->next == NULL) { tail = head; } } void insert_back(int key) { struct node *newnode = new node(); // filling up new node newnode->data = key; newnode->next = NULL; if (head == NULL) { head = newnode; tail = newnode; } else { tail->next = newnode; tail = newnode; } } void insert_after_node(int key, int v) { struct node *newnode = new node(); struct node *temp = head; int flag = 1; if (head == NULL) { cout << "No list to traverse through" << endl; return; } while (1) { if (temp->data == v) { break; } else if (temp->next == NULL) { flag = 0; break; } else { temp = temp->next; } } if (flag == 0) cout << "ERROR message : the node does not exist " << endl; else { newnode->next = temp->next; temp->next = newnode; newnode->data = key; } if (temp == tail) { tail = newnode; } } void update_node(int key, int v) { struct node *temp = head; int flag = 1; if (head == NULL) { cout << "No list to traverse through" << endl; return; } while (1) { if (temp->data == v) { if (temp == tail) { temp->data = key; tail = temp; } else { temp->data = key; break; } } else if (temp->next == NULL) { flag = 0; break; } else { temp = temp->next; } } if (flag == 0) cout << "ERROR message : the node does not exist " << endl; } void remove_head() { struct node *temp = head; head = head->next; free(temp); } void remove_element(int key) { struct node *temp = head; int flag = 1; if (head == NULL) { cout << "No list to traverse through" << endl; return; } //if in head if (temp->data == key) { remove_head(); return; } while (1) { if (temp->next == NULL) { flag = 0; break; } else if (temp->next->data == key) { if (temp->next->next == NULL) { temp->next = NULL; tail = temp; break; } else { temp->next = temp->next->next; break; } } else { temp = temp->next; } } if (flag == 0) cout << "ERROR message : the node does not exist " << endl; } void remove_end() { if (head == NULL) { cout << "NO element to remove" << endl; return; } if (head->next == NULL) { head = NULL; } else { struct node *temp = head; while (temp->next->next != NULL) { temp = temp->next; } struct node *endnode = temp->next; temp->next = NULL; free(endnode); tail = temp; } } void print() { struct node *temp = head; if (temp == NULL) { cout << "Linked list is empty" << endl; return; } cout << "Linked list is : "; while (temp != NULL) { cout << temp->data << " "; temp = temp->next; } cout << endl; } int main() { while (1) { int x; cout << "Press 1 to insert at front\nPress 2 to insert at back\nPress 3 to insert after a node\nPress 4 to update a node\nPress 5 to remove a node\nPress 6 to remove the last node\nPress 7 to exit.\n " << endl; cin >> x; if (x == 1) { int temp; cout << "value ?? " << endl; cin >> temp; insert_front(temp); print(); } else if (x == 2) { int temp; cout << "value ?? " << endl; cin >> temp; insert_back(temp); print(); } else if (x == 3) { int temp, compare; cout << "values are ?? " << endl; cin >> temp >> compare; insert_after_node(temp, compare); print(); } else if (x == 4) { int temp, update; cout << "values are ?? " << endl; cin >> temp >> update; update_node(temp, update); print(); } else if (x == 5) { int temp; cout << "remove value ?? " << endl; cin >> temp; remove_element(temp); print(); } else if (x == 6) { remove_end(); print(); } else if (x == 7) { break; } else { cout << "Please enter a valid input from the list" << endl; } cout << "---------------------------------------------------" << endl; } return 0; }
[ "hmshadidreza@gmail.com" ]
hmshadidreza@gmail.com
7ec965316a9e05233366c792d3ea25b4e7e1613b
9d364070c646239b2efad7abbab58f4ad602ef7b
/platform/external/chromium_org/base/single_thread_task_runner.h
5667a4b55f631274d074fc2b19b58729292aa6cf
[ "BSD-3-Clause" ]
permissive
denix123/a32_ul
4ffe304b13c1266b6c7409d790979eb8e3b0379c
b2fd25640704f37d5248da9cc147ed267d4771c2
refs/heads/master
2021-01-17T20:21:17.196296
2016-08-16T04:30:53
2016-08-16T04:30:53
65,786,970
0
2
null
2020-03-06T22:00:52
2016-08-16T04:15:54
null
UTF-8
C++
false
false
581
h
// Copyright (c) 2012 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 BASE_SINGLE_THREAD_TASK_RUNNER_H_ #define BASE_SINGLE_THREAD_TASK_RUNNER_H_ #include "base/base_export.h" #include "base/sequenced_task_runner.h" namespace base { class BASE_EXPORT SingleThreadTaskRunner : public SequencedTaskRunner { public: bool BelongsToCurrentThread() const { return RunsTasksOnCurrentThread(); } protected: virtual ~SingleThreadTaskRunner() {} }; } #endif
[ "allegrant@mail.ru" ]
allegrant@mail.ru
09d30eed2f924491ca5d1087ad4b91fb8c1cec11
66b550bbc708c37f19e446e97f4903ecd9553960
/opal-3.16.2/samples/deprecated/opalecho/precompile.cxx
ec14b8d594cdc6ed4a02d87ad8fa0aa9ca333907
[ "MIT" ]
permissive
wwl33695/myopal
d9da9f052addb663f9ed4446b07fc3724d101615
d302113c8ad8156b3392ce514cde491cf42d51af
refs/heads/master
2020-04-05T12:18:29.749874
2019-04-30T10:18:00
2019-04-30T10:18:00
156,864,740
0
0
null
null
null
null
UTF-8
C++
false
false
860
cxx
/* * precompile.cxx * * Copyright (C) 2009 Post Increment * * The contents of this file are subject to the Mozilla Public License * Version 1.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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See * the License for the specific language governing rights and limitations * under the License. * * The Original Code is Opal * * The Initial Developer of the Original Code is Post Increment * * Contributor(s): ______________________________________. * * $Revision:$ * $Author:$ * $Date:$ */ #include "precompile.h" // End of File ///////////////////////////////////////////////////////////////
[ "wwl33695@126.com" ]
wwl33695@126.com
bc3bd30d003faac14fc1c510722a3043c36c54aa
b3758ac921997a94ee7057181f75a0e287a26427
/Source/ViewMedium.cc
c5b76ae63f79c6bb6e268f62c68cd2f0db90acf1
[]
no_license
yasunakajima/garfpp_recomb
7edc3e998769a5cbfbd57a1c79df8a828c8eac64
cc9905b14341afdf9e4b88dcdbdedb89ce86d0a4
refs/heads/master
2021-01-13T01:25:09.868764
2014-09-28T09:27:47
2014-09-28T09:27:47
21,710,622
0
1
null
null
null
null
UTF-8
C++
false
false
13,468
cc
#include <iostream> #include <string> #include <sstream> #include <cmath> #include <TAxis.h> #include "Plotting.hh" #include "Medium.hh" #include "ViewMedium.hh" namespace Garfield { ViewMedium::ViewMedium() : debug(false), canvas(0), hasExternalCanvas(false), medium(0), eMin(0.), eMax(1000.), bMin(0.), bMax(1.e5), vMin(0.), vMax(0.), nFunctions(0), nGraphs(0) { className = "ViewMedium"; functions.clear(); graphs.clear(); plottingEngine.SetDefaultStyle(); } ViewMedium::~ViewMedium() { if (!hasExternalCanvas && canvas != 0) delete canvas; } void ViewMedium::SetCanvas(TCanvas* c) { if (c == 0) return; if (!hasExternalCanvas && canvas != 0) { delete canvas; canvas = 0; } canvas = c; hasExternalCanvas = true; } void ViewMedium::SetMedium(Medium* m) { if (m == 0) { std::cerr << className << "::SetMedium:\n"; std::cerr << " Medium pointer is null.\n"; return; } medium = m; } void ViewMedium::SetElectricFieldRange(const double emin, const double emax) { if (emin >= emax || emin < 0.) { std::cerr << className << "::SetElectricFieldRange:\n"; std::cerr << " Incorrect field range.\n"; return; } eMin = emin; eMax = emax; } void ViewMedium::SetMagneticFieldRange(const double bmin, const double bmax) { if (bmin >= bmax || bmin < 0.) { std::cerr << className << "::SetMagneticFieldRange:\n"; std::cerr << " Incorrect field range.\n"; return; } bMin = bmin; bMax = bmax; } void ViewMedium::SetFunctionRange(const double vmin, const double vmax) { if (vmin >= vmax || vmin < 0.) { std::cerr << className << "::SetFunctionRange:\n"; std::cerr << " Incorrect range.\n"; return; } vMin = vmin; vMax = vmax; } void ViewMedium::SetFunctionRange() { vMin = vMax = 0.; } void ViewMedium::PlotElectronVelocity() { bool keep = false; SetupCanvas(); AddFunction(eMin, eMax, vMin, vMax, keep, "electric field [V/cm]", "drift velocity [cm/ns]", 0); canvas->Update(); } void ViewMedium::PlotHoleVelocity() { bool keep = false; SetupCanvas(); AddFunction(eMin, eMax, vMin, vMax, keep, "electric field [V/cm]", "drift velocity [cm/ns]", 10); canvas->Update(); } void ViewMedium::PlotIonVelocity() { bool keep = false; SetupCanvas(); AddFunction(eMin, eMax, vMin, vMax, keep, "electric field [V/cm]", "drift velocity [cm/ns]", 20); canvas->Update(); } void ViewMedium::PlotElectronDiffusion() { bool keep = false; SetupCanvas(); AddFunction(eMin, eMax, vMin, vMax, keep, "electric field [V/cm]", "diffusion coefficient [#sqrt{cm}]", 1); keep = true; AddFunction(eMin, eMax, vMin, vMax, keep, "electric field [V/cm]", "diffusion coefficient [#sqrt{cm}]", 2); canvas->Update(); } void ViewMedium::PlotHoleDiffusion() { bool keep = false; SetupCanvas(); AddFunction(eMin, eMax, vMin, vMax, keep, "electric field [V/cm]", "diffusion coefficient [#sqrt{cm}]", 11); keep = true; AddFunction(eMin, eMax, vMin, vMax, keep, "electric field [V/cm]", "diffusion coefficient [#sqrt{cm}]", 12); canvas->Update(); } void ViewMedium::PlotIonDiffusion() { bool keep = false; SetupCanvas(); AddFunction(eMin, eMax, vMin, vMax, keep, "electric field [V/cm]", "diffusion coefficient [#sqrt{cm}]", 21); keep = true; AddFunction(eMin, eMax, vMin, vMax, keep, "electric field [V/cm]", "diffusion coefficient [#sqrt{cm}]", 22); canvas->Update(); } void ViewMedium::PlotElectronTownsend() { bool keep = false; SetupCanvas(); AddFunction(eMin, eMax, 0., 0., keep, "electric field [V/cm]", "Townsend coefficient [1/cm]", 3); canvas->Update(); } void ViewMedium::PlotHoleTownsend() { bool keep = false; SetupCanvas(); AddFunction(eMin, eMax, 0., 0., keep, "electric field [V/cm]", "Townsend coefficient [1/cm]", 13); canvas->Update(); } void ViewMedium::PlotElectronAttachment() { bool keep = false; SetupCanvas(); AddFunction(eMin, eMax, 0., 0., keep, "electric field [V/cm]", "Attachment coefficient [1/cm]", 4); canvas->Update(); } void ViewMedium::PlotHoleAttachment() { bool keep = false; SetupCanvas(); AddFunction(eMin, eMax, 0., 0., keep, "electric field [V/cm]", "Attachment coefficient [1/cm]", 14); canvas->Update(); } void ViewMedium::PlotElectronCrossSections() { SetupCanvas(); } void ViewMedium::SetupCanvas() { if (canvas == 0) { canvas = new TCanvas(); canvas->SetTitle("Medium View"); if (hasExternalCanvas) hasExternalCanvas = false; } canvas->cd(); gPad->SetLeftMargin(0.15); } void ViewMedium::AddFunction(const double xmin, const double xmax, const double ymin, const double ymax, const bool keep, const std::string xlabel, const std::string ylabel, const int type) { // Make sure the medium pointer is set. if (medium == 0) { std::cerr << className << "::AddFunction:\n"; std::cerr << " Medium is not defined.\n"; return; } // Look for an unused function name. int idx = 0; std::string fname = "fMediumView_0"; while (gROOT->GetListOfFunctions()->FindObject(fname.c_str())) { ++idx; std::stringstream ss; ss << "fMediumView_"; ss << idx; fname = ss.str(); } if (!keep) { functions.clear(); nFunctions = 0; graphs.clear(); nGraphs = 0; } // Create a TF1 and add it to the list of functions. TF1 fNew(fname.c_str(), this, &ViewMedium::EvaluateFunction, xmin, xmax, 1, "ViewMedium", "EvaluateFunction"); fNew.SetNpx(1000); functions.push_back(fNew); ++nFunctions; const std::string title = medium->GetName() + ";" + xlabel + ";" + ylabel; functions.back().SetRange(xmin, xmax); if ((fabs(ymax - ymin) > 0.)) { functions.back().SetMinimum(ymin); functions.back().SetMaximum(ymax); } functions.back().GetXaxis()->SetTitle(xlabel.c_str()); functions.back().GetXaxis()->SetTitleOffset(1.2); functions.back().GetYaxis()->SetTitle(ylabel.c_str()); functions.back().SetTitle(title.c_str()); functions.back().SetParameter(0, type); // Set the color and marker style. int color; int marker = 20; if (type == 2 || type == 4) { color = plottingEngine.GetRootColorLine1(); } else if (type == 12 || type == 14 || type == 22) { color = plottingEngine.GetRootColorLine2(); } else if (type < 10) { color = plottingEngine.GetRootColorElectron(); } else if (type < 20) { color = plottingEngine.GetRootColorHole(); } else { color = plottingEngine.GetRootColorIon(); } functions.back().SetLineColor(color); // Get the field grid. std::vector<double> efields; std::vector<double> bfields; std::vector<double> bangles; medium->GetFieldGrid(efields, bfields, bangles); const int nEfields = efields.size(); const int nBfields = bfields.size(); const int nBangles = bangles.size(); bool withGraph = true; if (nEfields <= 0 || nBfields <= 0 || nBangles <= 0) { withGraph = false; } // TODO: plots for different B fields // bool withBfield = false; // if (nBfields > 1) { // withBfield = true; // } else if (nBfields == 1 && bfields[0] > 0.) { // withBfield = true; // } if (withGraph) { TGraph graph(nEfields); graph.SetMarkerStyle(marker); graph.SetMarkerColor(color); bool ok = true; for (int i = 0; i < nEfields; ++i) { double value = 0.; switch (type) { case 0: // Electron drift velocity along E ok = medium->GetElectronVelocityE(i, 0, 0, value); value = medium->ScaleVelocity(value); break; case 1: // Electron transverse diffusion ok = medium->GetElectronTransverseDiffusion(i, 0, 0, value); value = medium->ScaleDiffusion(value); break; case 2: // Electron longitudinal diffusion ok = medium->GetElectronLongitudinalDiffusion(i, 0, 0, value); value = medium->ScaleDiffusion(value); break; case 3: // Electron Townsend coefficient ok = medium->GetElectronTownsend(i, 0, 0, value); value = medium->ScaleTownsend(exp(value)); break; case 4: // Electron attachment coefficient ok = medium->GetElectronAttachment(i, 0, 0, value); value = medium->ScaleAttachment(exp(value)); break; case 10: // Hole drift velocity along E ok = medium->GetHoleVelocityE(i, 0, 0, value); value = medium->ScaleVelocity(value); break; case 11: // Hole transverse diffusion ok = medium->GetHoleTransverseDiffusion(i, 0, 0, value); value = medium->ScaleDiffusion(value); break; case 12: // Hole longitudinal diffusion ok = medium->GetHoleLongitudinalDiffusion(i, 0, 0, value); value = medium->ScaleDiffusion(value); break; case 13: // Hole Townsend coefficient ok = medium->GetHoleTownsend(i, 0, 0, value); value = medium->ScaleTownsend(exp(value)); break; case 14: // Hole attachment coefficient ok = medium->GetHoleAttachment(i, 0, 0, value); value = medium->ScaleAttachment(exp(value)); break; case 20: // Ion drift velocity ok = medium->GetIonMobility(i, 0, 0, value); value *= medium->UnScaleElectricField(efields[i]); break; case 21: // Ion transverse diffusion ok = medium->GetIonTransverseDiffusion(i, 0, 0, value); value = medium->ScaleDiffusion(value); break; case 22: // Ion longitudinal diffusion ok = medium->GetIonLongitudinalDiffusion(i, 0, 0, value); value = medium->ScaleDiffusion(value); break; default: ok = false; break; } if (!ok) { withGraph = false; break; } graph.SetPoint(i, medium->UnScaleElectricField(efields[i]), value); } if (ok) { graphs.push_back(graph); ++nGraphs; } else { std::cerr << className << "::AddFunction:\n"; std::cerr << " Error retrieving data table.\n"; std::cerr << " Suppress plotting of graph.\n"; } } if (keep && nFunctions > 1) { functions[0].GetYaxis()->SetTitleOffset(1.5); functions[0].Draw(""); for (int i = 1; i < nFunctions; ++i) { functions[i].Draw("lsame"); } } else { functions.back().GetYaxis()->SetTitleOffset(1.5); functions.back().Draw(""); } if (nGraphs > 0) { for (int i = 0; i < nGraphs; ++i) { graphs[i].Draw("p"); } } } double ViewMedium::EvaluateFunction(double* pos, double* par) { if (medium == 0) return 0.; int type = int(par[0]); const double x = pos[0]; double y = 0.; // Auxiliary variables double a = 0., b = 0., c = 0.; switch (type) { case 0: // Electron drift velocity if (!medium->ElectronVelocity(x, 0, 0, 0, 0, 0, a, b, c)) return 0.; y = fabs(a); break; case 1: // Electron transverse diffusion if (!medium->ElectronDiffusion(x, 0, 0, 0, 0, 0, a, b)) return 0.; y = b; break; case 2: // Electron longitudinal diffusion if (!medium->ElectronDiffusion(x, 0, 0, 0, 0, 0, a, b)) return 0.; y = a; break; case 3: // Electron Townsend coefficient if (!medium->ElectronTownsend(x, 0, 0, 0, 0, 0, a)) return 0.; y = a; break; case 4: // Electron attachment coefficient if (!medium->ElectronAttachment(x, 0, 0, 0, 0, 0, a)) return 0.; y = a; break; case 10: // Hole drift velocity if (!medium->HoleVelocity(x, 0, 0, 0, 0, 0, a, b, c)) return 0.; y = a; break; case 11: // Hole transverse diffusion if (!medium->HoleDiffusion(x, 0, 0, 0, 0, 0, a, b)) return 0.; y = b; break; case 12: // Hole longitudinal diffusion if (!medium->HoleDiffusion(x, 0, 0, 0, 0, 0, a, b)) return 0.; y = a; break; case 13: // Hole Townsend coefficient if (!medium->HoleTownsend(x, 0, 0, 0, 0, 0, a)) return 0.; y = a; break; case 14: // Hole attachment coefficient if (!medium->HoleAttachment(x, 0, 0, 0, 0, 0, a)) return 0.; y = a; break; case 20: // Ion drift velocity if (!medium->IonVelocity(x, 0, 0, 0, 0, 0, a, b, c)) return 0.; y = fabs(a); break; case 21: // Ion transverse diffusion if (!medium->IonDiffusion(x, 0, 0, 0, 0, 0, a, b)) return 0.; y = b; break; case 22: // Ion longitudinal diffusion if (!medium->IonDiffusion(x, 0, 0, 0, 0, 0, a, b)) return 0.; y = a; break; default: std::cerr << className << "::EvaluateFunction:\n"; std::cerr << " Unknown type of transport coefficient requested.\n"; std::cerr << " Program bug!\n"; return 0.; } return y; } }
[ "YNakajima@lbl.gov" ]
YNakajima@lbl.gov
167f7ab8ca5bcf5f4f0218d6e5124c9ee54bbe22
0af3c13b9d4e18c6bd846e8b82d14cd6bbed8c1f
/znRender/BufferBase.cpp
761b666fad9b23c465446e5478cc3b3e163fd3ee
[]
no_license
tbcmangos/ZenonEngine
b5042f47e2d59c7ae688a2edda9d87f46cf3564d
6ec3e7936f0d68c9ad370a9b757111cd3536311f
refs/heads/master
2022-11-26T04:27:54.799487
2020-08-06T20:34:44
2020-08-06T20:34:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,209
cpp
#include "stdafx.h" // General #include "BufferBase.h" CBufferBase::CBufferBase(IRenderDevice& RenderDevice, IBuffer::BufferType ByfferType) : m_RenderDevice(RenderDevice) , m_BufferType(ByfferType) {} CBufferBase::~CBufferBase() {} // // IBuffer // IBuffer::BufferType CBufferBase::GetBufferType() const { return m_BufferType; } uint32 CBufferBase::GetElementCount() const { return m_Count; } uint32 CBufferBase::GetElementStride() const { return m_Stride; } uint32 CBufferBase::GetElementOffset() const { return m_Offset; } void CBufferBase::Load(const std::shared_ptr<IByteBuffer>& ByteBuffer) { IBuffer::BufferType bufferType; uint32 count, offset, stride; size_t dataSize; std::vector<uint8> data; ByteBuffer->read(&bufferType); ByteBuffer->read(&count); ByteBuffer->read(&offset); ByteBuffer->read(&stride); // Data of buffer { ByteBuffer->read(&dataSize); data.resize(dataSize); ByteBuffer->readBytes(data.data(), dataSize); } m_BufferType = bufferType; InitializeBufferBase(data.data(), count, offset, stride); } void CBufferBase::Save(const std::shared_ptr<IByteBuffer>& ByteBuffer) const { ByteBuffer->write(&m_BufferType); ByteBuffer->write(&m_Count); ByteBuffer->write(&m_Offset); ByteBuffer->write(&m_Stride); // Data of buffer { size_t dataSize = m_Data.size(); ByteBuffer->write(&dataSize); ByteBuffer->writeBytes(m_Data.data(), dataSize); } } void CBufferBase::Load(const std::shared_ptr<IXMLReader>& Reader) { _ASSERT(false); } void CBufferBase::Save(const std::shared_ptr<IXMLWriter>& Writer) const { _ASSERT(false); } // // Protected // void CBufferBase::InitializeBufferBase(const void * data, uint32 count, uint32 offset, uint32 stride) { m_Offset = offset; m_Stride = stride; m_Count = count; SetData(data, stride * count); DoInitializeBuffer(); } const std::vector<uint8>& CBufferBase::GetData() const { return m_Data; } std::vector<uint8>& CBufferBase::GetDataEx() { return m_Data; } void CBufferBase::SetData(const void * data, size_t dataSize) { if (!m_Data.empty()) m_Data.clear(); if (data != nullptr) m_Data.assign((const uint8*)data, (const uint8*)data + dataSize); else m_Data.resize(dataSize); }
[ "alexstenfard@gmail.com" ]
alexstenfard@gmail.com
9471d47fa2ada87b774d71eef74264a76c741384
9c330f622b362479000b04e71ca5c27d62716bad
/Engine/Scoreboard.cpp
78c4db5ba58e1b15a571f855903cc9eeeab8559b
[]
no_license
CashewCraft/Engine
c5d9a103351d7694a2a3d01cb0fff6acb18f3520
b47f6a0182382b3984fba3cb0eb504ef01665e61
refs/heads/master
2020-05-29T15:46:45.509536
2019-01-10T00:53:15
2019-01-10T00:53:15
189,230,707
0
0
null
null
null
null
UTF-8
C++
false
false
1,738
cpp
#include "Scoreboard.h" SDL_Texture *Scoreboard::Numbers[10] {}; Scoreboard *Scoreboard::ins = nullptr; void Scoreboard::Init() { ins = this; //Generate_Hook(std::bind(&Scoreboard::IncrScore, this, 1), SDL_KEYDOWN, SDLK_p); Title = new UIpane(TextGenerator::GenText("BADABOOM", 1024, SDL_Colour{ 107, 3, 57 }, "Score"), Vector2(0, 0.5), Vector2(0.3, 0.2), Vector2(0.1, -0.5)); Linked->AddChild(Title); Tim = new UIpane(TextGenerator::GenText("BADABOOM", 1024, SDL_Colour{ 107, 3, 57 }, "Time!"), Vector2(0.5, 0.5), Vector2(0.15, 0.1), Vector2(-0.5, -0.5)); Linked->AddChild(Tim); if (Numbers[0] == nullptr) { for (int i = 0; i < 10; i++) { Numbers[i] = TextGenerator::GenText("BADABOOM", 1024, SDL_Colour{ 214, 3, 57 }, std::to_string(i)); } } Title->AddChild(new UIpane(Numbers[0], Vector2(-0.525, -0.5), Vector2(0.2, 1), Vector2(0.15, 0.15))); } void Scoreboard::Release() { delete Tim->Anim.GetCurrSprite(); delete Title->Anim.GetCurrSprite(); ins = nullptr; } void Scoreboard::IncrScore(int amt) { StateManager::Score += amt; SetNumbers(Title, StateManager::Score, Vector2(-0.525, -0.5), Vector2(0.2, 1), Vector2(0.15, 0.15)); } void Scoreboard::SetNumbers(Object *par, unsigned int num, Vector2 Anchor, Vector2 Size, Vector2 Offset) { par->PurgeChildren(); std::string ToString = std::to_string(num); for (int i = 0; i < ToString.length(); i++) { par->AddChild(new UIpane(Numbers[ToString[i] - '0'], Anchor, Size, Vector2(Offset.x - i, Offset.y))); } } void Scoreboard::Update() { Timer -= Time::deltaTime(); SetNumbers(Tim, Timer, Vector2(0.5, -0.5), Vector2(0.2, 1), Vector2(-0.55, -0.025)); if (Timer <= 0) { StateManager::NewScene = true; StateManager::SceneName = "MM"; } }
[ "joshmj2@gmail.com" ]
joshmj2@gmail.com
40e8b3d7bd74aa5a88e35a8f9ab850e384edd512
b2de3db05251efa3f29b2ec600df2f754aeadc92
/OneLine/3.2/21.mergeTwoLists.cpp
755a51055a630ae0e1f555ab39d4847a059c3a5c
[]
no_license
Lu1Hang/study-in-leetcode
af0ff1adfbd0c255f5012b17f524b12a41a007a4
cfe8a5654a728b6b04db2274d08500d078eccb6b
refs/heads/main
2023-04-19T07:18:55.310284
2021-04-14T06:46:31
2021-04-14T06:46:31
342,490,212
0
2
null
2021-04-14T09:33:30
2021-02-26T06:57:48
Java
UTF-8
C++
false
false
671
cpp
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if (l1==NULL) return l2; if (l2==NULL) return l1; if (l1->val < l2->val) { l1->next =mergeTwoLists(l1->next , l2); return l1; } else { l2-> next = mergeTwoLists(l2->next ,l1); return l2; } } };
[ "noreply@github.com" ]
noreply@github.com
3b836cd7b22f68f2d04aa60a92396e41b57af9a2
1e6abf920fee17350ec18bc38aeb935505a23513
/r2-argument-parser.cpp
580471ef54815f0210f2a0d440056124c0305669
[]
no_license
Raze/r2tk
3cef02a28a047edb78b4a149654a8c57faff7b05
9d330d7eaaf6c64860008fddddd45b8acd66c23e
refs/heads/master
2021-01-01T19:21:09.033362
2013-04-17T06:14:50
2013-04-17T06:14:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,126
cpp
/* SOURCE * * File: r2-argument-parser.cpp * Created by: Rasmus Jarl (Raze Dux) and Lars Woxberg (Rarosu) * Created on: August 07 2011, 01:49 * * License: * Copyright (C) 2011 Rasmus Jarl * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Comments: * * Updates: * */ #include "r2-argument-parser.hpp" namespace r2 { void Option::AddParameter(const std::string& p_parameter) { m_parameters.push_back(p_parameter); } namespace Exception { const std::string ArgumentParser::K_CATEGORY("Argument Parser Error"); ArgumentParser::ArgumentParser(const std::string& p_message, const std::string& p_file, const int p_line_number) throw() : Runtime(p_message, K_CATEGORY, p_file, p_line_number) {} ArgumentParser::ArgumentParser(const std::string& p_message) throw() : Runtime(p_message, K_CATEGORY) {} ArgumentParser::~ArgumentParser() throw() {} } ArgumentParser::ArgumentParser() { } void ArgumentParser::OptionOccurrence::Appear() { m_option->Appear(m_times++); } void ArgumentParser::Run(int argc, char* argv[]) { m_path = argv[0]; // temporary variable for how many arguments last option still needs. int parameters_needed = 0; // The current Option expecting parameters. OptionOccurrence* parameter_occurence = 0; for(unsigned int argument_index = 1; argument_index < argc; ++argument_index) { std::string current_argument = argv[argument_index]; if(current_argument[0] == '-') { // Is Short or Name. // Can't an option have no parameters? This if-statement includes all options, doesn't it? // If an option is currently require a parameter and a option is stated. // Ah, makes sense. parameters_needed might need another name, but I have no better idea atm :) // Neither do I. if(parameters_needed != 0) { // cast exception. throw r2ExceptionArgumentParserM(std::string("Argument parser expected parameters after option: ") + parameter_occurence->m_option->m_name); } if(current_argument[1] != '-') { // Is Short. std::string shorts = current_argument.substr(1); for(unsigned int short_index = 0; short_index < shorts.size(); ++short_index) { // isn't this already checked outside this if-statement? // For loop for each short in a line. i.e -flck // Ah, gotcha if(parameters_needed != 0) { // Cast exception. // Paramater expected. throw r2ExceptionArgumentParserM(std::string("Short cannot be combined (has required parameters): ") + parameter_occurence->m_option->m_short + ((parameter_occurence->m_option->m_name.length() > 0) ? ("(" + parameter_occurence->m_option->m_name + ")") : "" )); } char current_short = shorts[short_index]; // Check if we recognize the option std::map<char, int>::iterator position = m_shorts.find(current_short); if(position != m_shorts.end()) { OptionOccurrence* current_occurence = &m_option_occurrences[position->second]; // Get Occurrence. parameters_needed = current_occurence->m_option->ParametersNeeded(); // Get Options Parameter needed. if(parameters_needed != 0) { parameter_occurence = current_occurence; } else { current_occurence->Appear(); // Call on the options Appear(current_times). } } else { // Cast exception... // Short isn't found. throw r2ExceptionArgumentParserM(std::string("Could not find short: ") + current_argument); } } } else { // Is Name. // stripe the '--' from the argument. // Check if we recognize the option std::string name = current_argument.substr(1); std::map<std::string, int>::iterator position = m_names.find(name); if (position != m_names.end()) { // option exists OptionOccurrence* current_occurence = &m_option_occurrences[position->second]; // Get Occurrence. parameters_needed = current_occurence->m_option->ParametersNeeded(); // Get Options Parameter needed. if(parameters_needed != 0) { parameter_occurence = current_occurence; // Set parameter_occurence to current_occurence if it needs parameters } else { current_occurence->Appear(); // Call on the options Appear(current_times). } } else { throw r2ExceptionArgumentParserM(std::string("Could not find option: ") + name); } } } else if(parameters_needed) { parameter_occurence->m_option->AddParameter(current_argument); --parameters_needed; if(parameters_needed == 0) { parameter_occurence->Appear(); // Call on the options Appear(current_times), when all it's parameters are found. } } else m_args.push_back(current_argument); } } void ArgumentParser::Add(Option* p_option) { r2AssertM(p_option != 0, "Trying to add NULL Option pointer to the Argument Parser"); p_option->SetParser(this); // Add the Option. m_option_occurrences.push_back(OptionOccurrence(p_option)); // If the option has a short name add it as the key to the Option's position in m_options. if(p_option->HasShort()) m_shorts.insert(std::pair<char, int>(p_option->Short(), m_option_occurrences.size() - 1)); // If the option has a name add it as the key to the Option's position in m_options. if(p_option->HasName()) m_names.insert(std::pair<std::string, int>(p_option->Name(), m_option_occurrences.size() - 1)); } }
[ "Raze.Dux@gmail.com" ]
Raze.Dux@gmail.com
068c2c3eac3f5482834e5dfc4f432ed24d24b571
94b556db906f4e23d64aab15dfff95122129cb0d
/src/CinderGstWebRTC.h
2c90f31c96de3080bcdd51357fd1408932f5a881
[]
no_license
PetrosKataras/Cinder-GstWebRTC
61d285503f1254decea177cba688c006db2adad4
88b9183aeab9a922edf7de93b06768d1403a71a4
refs/heads/master
2021-06-20T15:57:47.300348
2021-05-01T12:27:14
2021-05-01T12:27:14
211,371,693
23
1
null
null
null
null
UTF-8
C++
false
false
4,853
h
#pragma once #include <thread> #include "cinder/app/App.h" #include "cinder/Signals.h" #include "AsyncSurfaceReader.h" //> GST #include <gst/gst.h> #include <gst/sdp/sdp.h> #define GST_USE_UNSTABLE_API #include <gst/webrtc/webrtc.h> //> Signalling #include <libsoup/soup.h> /* * Based on https://github.com/centricular/gstwebrtc-demos/blob/master/sendrecv/gst/webrtc-sendrecv.c * Cinder's output is acting as an appsrc that is linked to the video * pipeline that is created through PipelineData::videoPipelineDescr * The video pipeline description describes the en/decoding path * for sending/receiving through GstWebRTC and it allows us to use HW acceleration * ( when available ) thanks to GStreamer's pipeline architecture. */ class CinderGstWebRTC { public: struct PipelineData { std::string videoPipelineDescr; int width{ -1 }; int height{ -1 }; std::string remotePeerId; uint localPeerId{ 0 }; std::string serverURL; std::string stunServer; }; CinderGstWebRTC( const PipelineData pipelineData, const ci::app::WindowRef& window = nullptr ); ~CinderGstWebRTC(); void startCapture(); void endCapture(); void streamCapture(); ci::gl::TextureRef getStreamTexture(); const bool dataChannelReady() const; void sendStringMsg( const std::string msg ); ci::signals::Signal<void()>& getDataChannelOpenedSignal() { return mDataChannelOpenSignal; }; ci::signals::Signal<void( std::string )>& getDataChannelMsgSignal() { return mDataChannelMsgSignal; }; private: enum ConnectionState { CONNECTION_STATE_UNKNOWN = 0, CONNECTION_STATE_ERROR = 1, /* generic error */ SERVER_CONNECTING = 1000, SERVER_CONNECTION_ERROR, SERVER_CONNECTED, /* Ready to register */ SERVER_REGISTERING = 2000, SERVER_REGISTRATION_ERROR, SERVER_REGISTERED, /* Ready to call a peer */ SERVER_CLOSED, /* server connection closed by us or the server */ PEER_CONNECTING = 3000, PEER_CONNECTION_ERROR, PEER_CONNECTED, PEER_CALL_NEGOTIATING = 4000, PEER_CALL_STARTED, PEER_CALL_STOPPING, PEER_CALL_STOPPED, PEER_CALL_ERROR, }; bool initializeGStreamer(); void startGMainLoopThread(); void startGMainLoop( GMainLoop* loop ); void connectToServerAsync(); void setPipelineEncoderName( std::string& pd ); static void onServerConnected( SoupSession* session, GAsyncResult* result, gpointer userData ); static void registerWithServer( gpointer userData ); static void onServerClosed( SoupWebsocketConnection* wsconn, gpointer userData ); static void onServerMsg( SoupWebsocketConnection* wsConn, SoupWebsocketDataType type, GBytes* message, gpointer userData ); static bool setupCall( gpointer userData ); static bool startPipeline( gpointer userData ); static void onNegotionNeeded( GstElement* element, gpointer userData ); static void onIceCandidate( GstElement* webrtc, guint mlineindex, gchar* candidate, gpointer userData ); static void onIceGatheringState( GstElement* webrtc, GParamSpec* pspec, gpointer userData ); static void onIceConnectionState( GstElement* webrtc, GParamSpec* pspec, gpointer userData ); #if defined( ENABLE_INCOMING_VIDEO_STREAM ) // stub - not implemented yet.. static void onIncomingStream( GstElement* webrtc, GstPad* pad, GstElement* pipeline ); static void onIncomingDecodebinStream( GstElement* decodebin, GstPad* pad, GstElement* pipeline ); static void handleMediaStreams( GstPad* pad, GstElement* pipeline, const char* convertName, const char* sinkName ); #endif static void onOfferCreated( GstPromise* promise, gpointer userData ); static void sendSdpOffer( GstWebRTCSessionDescription* offer, gpointer userData ); static void connectDataChannelSignals( GObject* dataChannel, gpointer userData ); static void onDataChannelError( GObject* dc, gpointer userData ); static void onDataChannelOpen( GObject* dc, gpointer userData ); static void onDataChannelClose( GObject* dc, gpointer userData ); static void onDataChannelMsg( GObject* dc, gchar* str, gpointer userData ); static void onDataChannel( GstElement* webrtc, GObject* dc, gpointer userData ); static std::string getConnectionStateString( const ConnectionState connectionState ); private: ci::SurfaceRef mCaptureSurface; std::unique_ptr<AsyncSurfaceReader> mAsyncSurfaceReader; ci::app::WindowRef mWindow; int mButtonMask{ 0 }; int mMouseButtonInitiator{ 0 }; std::thread mGMainLoopThread; GMainLoop* mGMainLoop; PipelineData mPipelineData; GstClockTime mTimestamp{ 0 }; GstElement* mAppsrc{ nullptr }; GstElement* mWebRTC{ nullptr }; GObject* mDataChannel{ nullptr }; SoupWebsocketConnection* mWSConn{ nullptr }; GstElement* mPipeline{ nullptr }; ci::signals::Signal<void()> mDataChannelOpenSignal; ci::signals::Signal<void( std::string )> mDataChannelMsgSignal; ConnectionState state{ CONNECTION_STATE_UNKNOWN }; std::pair<std::string, std::string> mEncoder; };
[ "petroskataras@gmail.com" ]
petroskataras@gmail.com
7bb4a4d3532a3daa1a4cb6a85b1cd384ad25c9bc
06d8b77df9db207f087a2b511817e05bed8f5b02
/snake/src/menu.cc
8733f252aa418137a3a5e82fe259fdee99d26ed9
[]
no_license
superxcgm/terminal_game_center
fb8f10bc8c8f870b9aafe5aa049a825bde05b7b3
d97075e2444ecc579237eac135f58f698887b508
refs/heads/master
2021-06-26T16:00:38.089710
2021-06-11T02:03:29
2021-06-11T02:03:29
96,505,624
3
2
null
2021-06-08T08:48:36
2017-07-07T06:17:44
C++
UTF-8
C++
false
false
2,740
cc
#include "./menu.h" /* NOLINT */ #include <ncurses.h> #define VERSION "0.5" Menu::Menu(const Rect &r) : res_snake_("res/snake.res"), res_control_menu_("res/control_menu.res"), rect_(r) {} void Menu::DrawBorder(char ch) { // todo: use windows to refactor move(0, 0); hline(ch, rect_.get_width()); /* top */ move(rect_.bottom(), 0); hline(ch, rect_.get_width()); /* bottom */ move(0, 0); vline(ch, rect_.get_height()); /* left */ move(0, rect_.right()); vline(ch, rect_.get_height()); /* right */ } void Menu::DrawControlMenu(int flag, int base, const Config &config) { const int left_offset = 7; const int width = 53; int i; /* 0=>base, 1=>control part */ switch (flag) { case 0: for (i = 0; i < res_control_menu_.line_count(); ++i) mvaddstr(base + i, left_offset, res_control_menu_.get_line(i).c_str()); break; case 1: if (config.is_real_wall()) { attron(A_BOLD); } mvaddstr(base + 5, left_offset + width / 2, "Borders On"); if (config.is_real_wall()) { attroff(A_BOLD); } if (!config.is_real_wall()) { attron(A_BOLD); } mvaddstr(base + 6, left_offset + width / 2, "Borders Off"); if (!config.is_real_wall()) { attroff(A_BOLD); } for (i = 1; i <= 9; ++i) { if (i == config.get_level()) { attron(A_BOLD); } mvaddch(base + 8, left_offset + width / 2 + (i - 1) * 2, i + '0'); if (i == config.get_level()) { attroff(A_BOLD); } } break; default:break; } refresh(); } Config Menu::DrawMain() { int control_menu_base; clear(); res_snake_.Draw(3, 3); addstr(" V" VERSION); /* strcat */ DrawBorder('*'); control_menu_base = 3 + res_snake_.line_count() + 3; Config config; DrawControlMenu(0, control_menu_base, config); /* 0=>base, 1=>control part */ DrawControlMenu(1, control_menu_base, config); refresh(); while (true) { int ch = getch(); switch (ch) { case KEY_LEFT:config.DecreaseLevel(); DrawControlMenu(1, control_menu_base, config); break; case KEY_RIGHT:config.IncreaseLevel(); DrawControlMenu(1, control_menu_base, config); break; case KEY_UP:config.set_real_border(true); DrawControlMenu(1, control_menu_base, config); break; case KEY_DOWN:config.set_real_border(false); DrawControlMenu(1, control_menu_base, config); break; case 'q': /* quit */ case 'Q':curs_set(1); /* display cursor */ endwin(); exit(0); case ' ': case '\n':return config; /* reenter menu_ */ default:break; } } }
[ "superxcgm@gmail.com" ]
superxcgm@gmail.com
294edb62054ac61e929d90b057e66e5469414732
5b24f3f1010c85d31c709be432b7f9122ed28389
/src/viewmenu2.cpp
353a6ba5ccfc89f4cc51372c505d1bffd4844500
[]
no_license
mazbrili/colin
ce3219fdb57476d0b9b2cf1093a80274ae0e0fd5
dbb4e348018d2335aebfc62357fbfe57f14798ac
refs/heads/master
2020-06-12T03:49:53.328571
2020-04-08T09:38:21
2020-04-08T09:38:21
188,362,792
0
0
null
null
null
null
UTF-8
C++
false
false
2,244
cpp
/*********************************************************** * $Id$ * * Colin * * Copyright (C) 2011 Matthias Rauter (matthias.rauter@student.uibk.ac.at) * * 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 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details." * * You should have received a copy of the GNU General Public License * along with this program; if not, see * * http://www.gnu.org/licenses/. * * Author: Matthias Rauter * ***********************************************************/ #include "viewmenu2.h" #include "shortcutsettings.h" viewMenu2::viewMenu2(cWidget *c, QWidget *parent) : QMenu(parent) { centralWidget = c; QAction *a = addAction(tr("fullscreen")); a->setCheckable(true); addAction(QIcon(":/icons/zoom_all.png"), tr("show all"), c, SLOT(showAll())); //QMenu *countM = new QMenu(tr("set Widget Count"), this); //g = new QActionGroup(this); //for(int i=2; i<13; i++) //{ // QAction *a = g->addAction(countM->addAction(QString("%1").arg(i) + " widgets")); // a->setData(QVariant(i)); //} //addMenu(countM); neededHeight = 0; vp = new viewPortPresenter(c, this); vp->setFixedSize(250, 250); setFixedWidth(254); //connect(g, SIGNAL(triggered(QAction*)), // this, SLOT(setWidgetCount(QAction*))); connect(a, SIGNAL(toggled(bool)), this, SLOT(emitFullScreen(bool))); } void viewMenu2::showEvent(QShowEvent *) { if(neededHeight==0) { setFixedHeight(height()+254); neededHeight = height(); vp->setGeometry(2, height()-252, 250, 250); } } //void viewMenu2::setWidgetCount(QAction *a) //{ // centralWidget->setViewCount(a->data().toInt()); //} void viewMenu2::emitFullScreen(const bool &on) { emit fullScreenRequested(on); }
[ "colin@192177b4-43b2-45e3-8045-46fbca82b43a" ]
colin@192177b4-43b2-45e3-8045-46fbca82b43a
15fcd0b8e3d5cb4d4c12e5239dd994e0596932fa
65d48c570511a80ba6024ecd002e00345aa2c420
/Manager.cpp
7daa5166ce9efb6b66eb99c0b271d972a261db77
[]
no_license
wkcn/HR
cccb650bf2a08614a4d2e447e2626d64bc66fe0e
911419c7e1169da0aa20b183aec0e023e50b7cf9
refs/heads/master
2021-01-22T01:06:07.684485
2015-06-21T03:28:13
2015-06-21T03:28:13
37,445,436
0
0
null
null
null
null
UTF-8
C++
false
false
418
cpp
#include "Manager.h" Manager::Manager(int id,const string &name,int age,STAFF_STATE state):Staff(id,name,age,state){ _events = 0; } Manager::~Manager(){ } Achievement Manager::GetAchievement(){ return Achievement(0,_events); } STAFF_KIND Manager::GetKind(){ return MANAGER; } void Manager::SetEvents(int events){ this -> _events = events; } int Manager::GetEvents(){ return _events; }
[ "wkcn@live.cn" ]
wkcn@live.cn
77eac5e252a881eac964093d3f412d9dc491e6d7
04f9d6828588293522ce83fabcf56066fa0bb9a4
/mxchip_advanced/src/wifi.cpp
a2b98098452a6f0ec69aedf23aaa62eca69176a0
[ "LicenseRef-scancode-generic-cla", "MIT" ]
permissive
badsaarow/mxchip_az3166_firmware
31552ba2b94f30a8485eb6eb56668a889fbec0fd
b0fb6cdd4bb72470494ae7f60dc32badcd95e03c
refs/heads/master
2023-08-25T06:29:35.245467
2023-08-11T02:09:32
2023-08-11T02:09:32
191,081,947
0
0
MIT
2023-08-11T02:09:34
2019-06-10T02:23:17
C
UTF-8
C++
false
false
3,755
cpp
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. #include "../inc/globals.h" #include "../inc/wifi.h" #include "AZ3166WiFi.h" #include "../inc/config.h" bool WiFiController::initApWiFi() { LOG_VERBOSE("WiFiController::initApWiFi"); byte mac[6] = {0}; WiFi.macAddress(mac); unsigned length = snprintf(apName, STRING_BUFFER_32 - 1, "AZ3166_%c%c%c%c%c%c", mac[0] % 26 + 65, mac[1]% 26 + 65, mac[2]% 26 + 65, mac[3]% 26 + 65, mac[4]% 26 + 65, mac[5]% 26 + 65); apName[length] = char(0); length = snprintf(macAddress, STRING_BUFFER_16, "%02X%02X%02X%02X%02X%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); macAddress[length] = char(0); LOG_VERBOSE("MAC address %s", macAddress); memcpy(password, macAddress + 8, 4); password[4] = 0; // passcode below is not widely compatible. See the password is used as pincode for onboarding int ret = WiFi.beginAP(apName, ""); if ( ret != WL_CONNECTED) { Screen.print(0, "AP Failed:"); Screen.print(2, "Reboot device"); Screen.print(3, "and try again"); LOG_ERROR("AP creation failed"); return false; } LOG_VERBOSE("AP started"); return true; } bool WiFiController::initWiFi() { LOG_VERBOSE("WiFiController::initWiFi"); Screen.clean(); Screen.print("WiFi \r\n \r\nConnecting..."); if(WiFi.begin() == WL_CONNECTED) { LOG_VERBOSE("WiFi WL_CONNECTED"); digitalWrite(LED_WIFI, 1); isConnected = true; } else { Screen.print("WiFi\r\nNot Connected\r\nEnter AP Mode?\r\n"); } return isConnected; } void WiFiController::shutdownWiFi() { LOG_VERBOSE("WiFiController::shutdownWiFi"); WiFi.disconnect(); isConnected = false; } void WiFiController::shutdownApWiFi() { LOG_VERBOSE("WiFiController::shutdownApWiFi"); WiFi.disconnectAP(); isConnected = false; } bool WiFiController::getIsConnected() { return WiFi.status() == WL_CONNECTED; } String * WiFiController::getWifiNetworks(int &count) { LOG_VERBOSE("WiFiController::getWifiNetworks"); String foundNetworks = ""; // keep track of network SSID so as to remove duplicates from mesh and repeater networks int numSsid = WiFi.scanNetworks(); count = 0; if (numSsid == -1) { return NULL; } else { String *networks = new String[numSsid + 1]; // +1 if all unique if (networks == NULL /* unlikely */) { return NULL; } if (numSsid > 0) { networks[0] = WiFi.SSID(0); count = 1; } // TODO: can we make this better? for (int thisNet = 1; thisNet < numSsid; thisNet++) { const char* ssidName = WiFi.SSID(thisNet); if (strlen(ssidName) == 0) continue; networks[count] = ssidName; // prefill int lookupPosition = 0; for(; lookupPosition < count; lookupPosition++) { if (networks[count] == networks[lookupPosition]) break; } if (lookupPosition < count) { // ditch if found continue; } count++; // save if not found } return networks; } } void WiFiController::displayNetworkInfo() { LOG_VERBOSE("WiFiController::displayNetworkInfo"); char buff[STRING_BUFFER_128] = {0}; IPAddress ip = WiFi.localIP(); byte mac[6] = {0}; WiFi.macAddress(mac); unsigned length = snprintf(buff, STRING_BUFFER_128, "WiFi:\r\n%s\r\n%s\r\nmac:%02X%02X%02X%02X%02X%02X", WiFi.SSID(), ip.get_address(), mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); buff[length] = char(0); Screen.print(0, buff); }
[ "ogbastem@microsoft.com" ]
ogbastem@microsoft.com
f57a62c7695bbf682734884cc973431b500a1e9d
eea7cdec678b346bdc9cb19c91fdb2fe47cc9a4b
/Source/C++/Uri_1035.cpp
feafc794c99a58810eb64a7a77ba9b7dbf3397f1
[ "MIT" ]
permissive
felippegh/URI-JsPy
c10a442db7abf7d721dff30103c0b2f1dbf94c93
9ff647a7d42d34bdd128af5edd79a43b8d3453dd
refs/heads/master
2023-03-16T14:49:34.105063
2021-03-11T03:25:37
2021-03-11T03:25:37
40,746,117
1
0
null
null
null
null
UTF-8
C++
false
false
449
cpp
/* *Solved by: Felippe George Haeitmann *Email: felippegeorge@utexas.edu *Problem source: urionlinejudge.com.br * **/ #include<stdio.h> #include<stdlib.h> int main(){ int a ,b ,c, d; scanf("%d %d %d %d",&a, &b, &c, &d); if((b > c) && (d > a) && ((c + d) > (a + b)) && (c > 0) && (d > 0) && (a % 2 == 0) ){ printf("Valores aceitos\n"); }else{ printf("Valores nao aceitos\n"); } return 0; }
[ "felippegeorge@utexas.edu" ]
felippegeorge@utexas.edu
a1c3a3ee49b3693727b583d3a760b0294e5013dc
53cf2ee9811057fb22552f5c41cad8d411635fb8
/UVa/uva 11426 age sort.cpp
dd41871a4236155f02bed08f603ee678509a1fff
[]
no_license
eunice730711/Programming-Competition
7352cbde57e5fbf0f2e360645d0f3453ddba871b
f6057c95556d71da5e2a06a3e1b22f1f2712ba8b
refs/heads/master
2020-12-03T20:04:14.142134
2018-04-26T09:28:52
2018-04-26T09:28:52
66,542,701
0
0
null
null
null
null
UTF-8
C++
false
false
516
cpp
#include<stdio.h> #include<stdlib.h> #include<iostream> using namespace std; int main() { int n=0; while(cin>>n&&n!=0) { int arr[105]={0},temp=0; for(int i=0;i<n;i++) { scanf("%d",&temp); arr[temp]+=1; } for(int i=1;i<=100;i++) { while(arr[i]!=0) { printf("%d ",i); arr[i]-=1; } } printf("\n"); } return 0; }
[ "eunice730711@gmail.com" ]
eunice730711@gmail.com
e08419f04ead53b52957b2ab2bf1eb5188cd57dc
1f597367db4fd8965a1dcb6b6c33e775df9f8336
/src/variables.cpp
b865d2ccf5c9a94f0f6010eea8998af2cc126bc7
[]
no_license
amrufathy/Interpreter
8c5452de3319db99869202d1854be35bb672e3eb
fc96a33f240202b988d6fe3f8d60acf87f2c03aa
refs/heads/master
2020-05-16T22:51:11.659121
2015-07-17T19:50:31
2015-07-17T19:50:31
33,833,788
0
1
null
null
null
null
UTF-8
C++
false
false
1,023
cpp
#include "variables.h" /// Add a name and value to the list bool Variables::add(const char* name, double value) { /*VAR newVar; strncpy(newVar.name, name, 30); newVar.value = value; int index = getIndex(name); if (index == -1) variables.push_back(newVar); // variable does not exist else variables[index] = newVar; // variable exists*/ return HASH.add(name,value); } /// Get value of variable with known name bool Variables::getValue(const char* name, double* value) {/* int index = getIndex(name); if (index != -1){ *value = variables[index].value; return true; }*/ return HASH.getValue(name,value); } /** * Returns the index of the given name in the variable list. * Returns -1 if name is not present in the list. * Name is case sensitive. */ int Variables::getIndex(const char* name) {/* for (unsigned i = 0; i < variables.size(); i++){ if(!strcmp(name, variables[i].name)) return i; }*/ return -1; }
[ "amru_fathy@yahoo.com" ]
amru_fathy@yahoo.com
f72bca3810a943cff51ddd630bf3d29f2a9983bb
f84b6f345115f63cd78562030299ccdafd1fef54
/src/ble/tests/TestBleUUID.cpp
d374c7475f55bfc56a765f3164e1bad6d15928e2
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
JordanField/connectedhomeip
436bde7b804ffbbaafd254e3d782cabf569a8186
8dcf5d70cd54209511be6b1180156a00dd8e0cf8
refs/heads/master
2023-09-04T02:30:33.821611
2021-10-30T14:14:43
2021-10-30T14:14:43
423,137,284
0
0
Apache-2.0
2021-10-31T12:08:08
2021-10-31T12:08:08
null
UTF-8
C++
false
false
3,483
cpp
/* * * Copyright (c) 2020 Project CHIP Authors * Copyright (c) 2016-2017 Nest Labs, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file * This file implements a process to effect a functional test for * the CHIP BLE layer library error string support interfaces. * */ #include <ble/BleUUID.h> #include <lib/support/UnitTestRegistration.h> #include <nlunit-test.h> using namespace chip; using namespace chip::Ble; namespace { void CheckStringToUUID_ChipUUID(nlTestSuite * inSuite, void * inContext) { // Test positive scenario - CHIP Service UUID ChipBleUUID uuid; NL_TEST_ASSERT(inSuite, StringToUUID("0000FFF6-0000-1000-8000-00805F9B34FB", uuid)); NL_TEST_ASSERT(inSuite, UUIDsMatch(&uuid, &CHIP_BLE_SVC_ID)); } void CheckStringToUUID_ChipUUID_RandomCase(nlTestSuite * inSuite, void * inContext) { // Test that letter case doesn't matter ChipBleUUID uuid; NL_TEST_ASSERT(inSuite, StringToUUID("0000FfF6-0000-1000-8000-00805f9B34Fb", uuid)); NL_TEST_ASSERT(inSuite, UUIDsMatch(&uuid, &CHIP_BLE_SVC_ID)); } void CheckStringToUUID_ChipUUID_NoSeparators(nlTestSuite * inSuite, void * inContext) { // Test that separators don't matter ChipBleUUID uuid; NL_TEST_ASSERT(inSuite, StringToUUID("0000FFF600001000800000805F9B34FB", uuid)); NL_TEST_ASSERT(inSuite, UUIDsMatch(&uuid, &CHIP_BLE_SVC_ID)); } void CheckStringToUUID_TooLong(nlTestSuite * inSuite, void * inContext) { // Test that even one more digit is too much ChipBleUUID uuid; NL_TEST_ASSERT(inSuite, !StringToUUID("0000FFF600001000800000805F9B34FB0", uuid)); } void CheckStringToUUID_TooShort(nlTestSuite * inSuite, void * inContext) { // Test that even one less digit is too little ChipBleUUID uuid; NL_TEST_ASSERT(inSuite, !StringToUUID("0000FFF600001000800000805F9B34F", uuid)); } void CheckStringToUUID_InvalidChar(nlTestSuite * inSuite, void * inContext) { // Test that non-hex digits don't pass ChipBleUUID uuid; NL_TEST_ASSERT(inSuite, !StringToUUID("0000GFF6-0000-1000-8000-00805F9B34FB0", uuid)); } // clang-format off const nlTest sTests[] = { NL_TEST_DEF("CheckStringToUUID_ChipUUID", CheckStringToUUID_ChipUUID), NL_TEST_DEF("CheckStringToUUID_ChipUUID_RandomCase", CheckStringToUUID_ChipUUID_RandomCase), NL_TEST_DEF("CheckStringToUUID_ChipUUID_NoSeparators", CheckStringToUUID_ChipUUID_NoSeparators), NL_TEST_DEF("CheckStringToUUID_TooLong", CheckStringToUUID_TooLong), NL_TEST_DEF("CheckStringToUUID_TooShort", CheckStringToUUID_TooShort), NL_TEST_DEF("CheckStringToUUID_InvalidChar", CheckStringToUUID_InvalidChar), NL_TEST_SENTINEL() }; // clang-format on } // namespace int TestBleUUID() { nlTestSuite theSuite = { "BleUUID", &sTests[0], NULL, NULL }; nlTestRunner(&theSuite, nullptr); return nlTestRunnerStats(&theSuite); } CHIP_REGISTER_TEST_SUITE(TestBleUUID)
[ "noreply@github.com" ]
noreply@github.com
6122d56aa0f3124fafac108e57eee527be75a6aa
e1954e2c4889d06b0f44e597c6887df6e8204cc6
/app_gmatch/GMatchTrimmer.h
7aa8a9f3d6d0334fef13030a067d360db48a8c88
[ "Apache-2.0" ]
permissive
ZekeTian/PSP
e2acb31da60b744c116ca947674ad84bb989da26
e65f263ef62040c5d74610e34228e6a870a21a51
refs/heads/master
2023-06-25T14:02:10.866244
2021-07-19T08:40:36
2021-07-19T08:40:36
385,596,464
2
0
null
null
null
null
UTF-8
C++
false
false
827
h
#ifndef GMATCHTRIMMER_H_ #define GMATCHTRIMMER_H_ #include "comm-struct.h" #include "subg-dev.h" /** * 裁剪器,可以对顶点的邻接表进行预处理(一般是用于去除一些无用的顶点) */ class GMatchTrimmer : public Trimmer<GMatchVertex> { virtual void trim(GMatchVertex &v) { // 获取查询图中所有查询点的标签集合 hash_set<Label> &query_vertex_label = *(hash_set<Label> *)global_query_vertex_label; // 邻接表剪枝 vector<AdjItem> &val = v.value.adj; vector<AdjItem> new_val; for (int i = 0; i < val.size(); i++) { if (query_vertex_label.find(val[i].l) != query_vertex_label.end()) { new_val.push_back(val[i]); } } val.swap(new_val); } }; #endif
[ "zeke.tian@outlook.com" ]
zeke.tian@outlook.com
23b07f4824b4c98b94b9429a63be22d402c5f800
4f4d7a81c759b56fcab3a01055aadf7ed5867847
/TaskTests/FileIoTests.cpp
06147163a5c9ab98b393ed50cc4d64537b02ac38
[]
no_license
mtso/task
7ea3291d99eb85b538a25bb8ddcb6a28d6dc63dc
01bd3b22442b41de929ac0fb6e2263e2fda4f123
refs/heads/master
2021-01-19T02:20:51.724177
2016-12-07T19:16:56
2016-12-07T19:16:56
73,460,273
2
2
null
2016-12-07T04:38:23
2016-11-11T08:37:49
C++
UTF-8
C++
false
false
1,764
cpp
// Visual Studio Boilerplate #include "stdafx.h" // Pre-compiled header (optimizes unit testing header file) #include "CppUnitTest.h" // Unit testing API #include "FileStore.h" #include "TaskEntryStatus.h" using namespace task; // Namespace of Assert:: using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace FileIoTests // Testing Project namespace { TEST_CLASS(FileIoTests) // Groups the method tests together { public: TEST_METHOD(TestLoadAndStore) { FileStore fileIo; std::vector<TaskEntry> tasks; string user("test"); string description("Test task"); uint64_t time_created = 1479694012629l; uint64_t time_due = 1480298812629l; TaskEntryStatus status = TaskEntryStatus::BACKLOG; TaskEntry task(user, description, time_created, time_due, status); tasks.push_back(task); Assert::AreEqual(true, fileIo.store("..\\.task\\tasklog-test", tasks)); std::vector<TaskEntry> loadedTasks; Assert::AreEqual(true, fileIo.load("..\\.task\\tasklog-test", loadedTasks)); Assert::AreEqual((size_t) 1, loadedTasks.size()); Assert::AreEqual(user, loadedTasks[0].getCreator()); Assert::AreEqual(description, loadedTasks[0].getDescription()); Assert::AreEqual(time_created, loadedTasks[0].getTimeCreatedMs()); Assert::AreEqual(time_due, loadedTasks[0].getTimeDueMs()); Assert::AreEqual(string("backlog"), getStatusString(loadedTasks[0].getStatus())); std::vector<TaskEntry> emptyTasks; Assert::AreEqual(true, fileIo.store("..\\.task\\tasklog-test", emptyTasks)); } }; }
[ "shenjinzhu86@gmail.com" ]
shenjinzhu86@gmail.com
1ab1d9ae82525eaa15bf271d47c7ce84d36ab25a
023d8ef0754691477e60b180aefece27821955cf
/2DGame/Stalactite.cpp
d5f6331a95741d819cdd5edb00bc7e7e2b4403a6
[]
no_license
alteos98/FIB-VJ_2DGame
09ff261b7812dc0ff3c5317982daa62f188e6d4b
f2258203312f6ec6e7fa6d2af0300c4c739899b0
refs/heads/master
2021-11-23T14:33:49.535518
2021-11-19T15:00:57
2021-11-19T15:00:57
172,998,526
0
0
null
null
null
null
UTF-8
C++
false
false
2,823
cpp
#include <cmath> #include <iostream> #include <GL/glew.h> #include <GL/glut.h> #include "Stalactite.h" #include "Game.h" enum StalactiteAnims { BASE }; Stalactite::Stalactite() { leftX = rightX = downY = NULL; } Stalactite::~Stalactite() { } void Stalactite::init(const glm::ivec2 & stalactitePos, ShaderProgram & shaderProgram, glm::ivec2 stalactiteSize) { this->stalactiteSize = stalactiteSize; this->stalactitePos = stalactitePos; this->fallingVelocity = 10; this->falling = false; spritesheet.loadFromFile("images/spikes/spikes.png", TEXTURE_PIXEL_FORMAT_RGBA); sprite = Sprite::createSprite(stalactiteSize, glm::vec2(1.f, 1.f / 2.f), &spritesheet, &shaderProgram); sprite->setNumberAnimations(1); sprite->setAnimationSpeed(BASE, 1); sprite->addKeyframe(BASE, glm::vec2(0.f, 1.f / 2.f)); sprite->changeAnimation(BASE); sprite->setPosition(glm::vec2(float(stalactitePos.x), float(stalactitePos.y))); } void Stalactite::update(int deltaTime) { if (falling) { stalactitePos.y += 1 * fallingVelocity; } sprite->setPosition(glm::vec2(float(stalactitePos.x), float(stalactitePos.y))); sprite->update(deltaTime); } void Stalactite::render() { sprite->render(); } void Stalactite::changeAnimation(int i) { sprite->changeAnimation(i); } // MY FUNCTIONS bool Stalactite::hasToFall(glm::ivec2 & playerPos) { return (playerPos.x > leftX && playerPos.x < rightX && playerPos.y < downY && playerPos.y > stalactitePos.y); } bool Stalactite::outOfMap() { if (stalactitePos.y > SCREEN_HEIGHT) return true; else return false; } // SETTERS void Stalactite::setTileMap(TileMap *tileMap) { map = tileMap; } void Stalactite::setPosition(const glm::vec2 &pos) { stalactitePos = pos; sprite->setPosition(glm::vec2(float(stalactitePos.x), float(stalactitePos.y))); } void Stalactite::setMargin(int marginX, int marginY) { leftX = stalactitePos.x - marginX; rightX = stalactitePos.x + stalactiteSize.x + marginX; downY = stalactitePos.y + stalactiteSize.y + marginY; } void Stalactite::setLeftX(int leftX) { this->leftX = leftX; } void Stalactite::setRightX(int rightX) { this->rightX = rightX; } void Stalactite::setDownY(int downY) { this->downY = downY; } void Stalactite::setFallingVelocity(int fallingVelocity) { this->fallingVelocity = fallingVelocity; } void Stalactite::setFalling(bool b) { this->falling = b; } // GETTERS glm::ivec2 Stalactite::getPosition() { return stalactitePos; } int Stalactite::getWidth() { return stalactiteSize.x; } int Stalactite::getHeight() { return stalactiteSize.y; } int Stalactite::getLeftX() { return leftX; } int Stalactite::getRightX() { return rightX; } int Stalactite::getDownY() { return downY; } int Stalactite::getFallingVelocity() { return fallingVelocity; } bool Stalactite::getFalling() { return falling; }
[ "alteos98@gmail.com" ]
alteos98@gmail.com
f4d596da70a3f70078be8cda7db6c1b443344772
5885fd1418db54cc4b699c809cd44e625f7e23fc
/latin-2017-cf101889/virtual/j.cpp
41c71deee54f727ff3b6377564a6390426e12cf0
[]
no_license
ehnryx/acm
c5f294a2e287a6d7003c61ee134696b2a11e9f3b
c706120236a3e55ba2aea10fb5c3daa5c1055118
refs/heads/master
2023-08-31T13:19:49.707328
2023-08-29T01:49:32
2023-08-29T01:49:32
131,941,068
2
0
null
null
null
null
UTF-8
C++
false
false
1,217
cpp
#include <bits/stdc++.h> using namespace std; #define _USE_MATH_DEFINES typedef long long ll; typedef long double ld; typedef pair<int,int> pii; typedef complex<ld> pt; typedef vector<pt> pol; const char nl = '\n'; const int INF = 0x3f3f3f3f; const ll INFLL = 0x3f3f3f3f3f3f3f3f; const ll MOD = 1e9+7; const ld EPS = 1e-10; const int N = 1e5+10; mt19937 rng(chrono::high_resolution_clock::now().time_since_epoch().count()); int can[N]; bool vis[N]; string s; int n; bool dfs(int sz) { if (can[sz] != -1) return can[sz]; memset(vis, 0, sizeof vis); for (int i = 0; i < sz; i++) { bool shit = 0; for (int j = i; !vis[j]; j = (j + sz)%n) { if (s[j] == 'P') { shit = 1; break; } vis[j] = 1; } if (!shit) { return (can[sz] = 1); } } return (can[sz] = 0); } //#define FILEIO int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cout << fixed << setprecision(10); #ifdef FILEIO freopen("test.in", "r", stdin); freopen("test.out", "w", stdout); #endif memset(can, -1, sizeof can); cin >> s; n = s.size(); int ans = 0; for (int i = 1; i < n; i++) { ans += dfs(__gcd(i, n)); } cout << ans << endl; return 0; }
[ "henryxia9999@gmail.com" ]
henryxia9999@gmail.com
8049b7504476463df39801f12e797deb281ab42e
16bf41aa22d340df3d52875d3306b9d46dfacfcc
/src/graphics/index_buffer.h
ec926c661e121e8dca9f8c82262f0a263fe391c0
[ "Zlib" ]
permissive
HolyBlackCat/modular-forms
a66705a63127c14debc19e91ff178a9df16ee356
6703e9c37589e26e46a1eeb52d0852f1aead59b9
refs/heads/master
2021-08-06T17:29:04.672127
2020-05-15T14:02:53
2020-05-15T14:02:53
175,769,333
0
1
null
null
null
null
UTF-8
C++
false
false
6,136
h
#pragma once #include <cstdint> #include <type_traits> #include <utility> #include <cglfl/cglfl.hpp> #include "graphics/vertex_buffer.h" #include "macros/finally.h" #include "meta/misc.h" #include "program/errors.h" namespace Graphics { class IndexBuffers { IndexBuffers() = delete; ~IndexBuffers() = delete; inline static GLuint binding = 0; public: static void Bind(GLuint handle) { if (binding == handle) return; glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, handle); binding = handle; } static void ForgetBoundBuffer() { binding = 0; } static GLuint Binding() { return binding; } }; template <typename T> inline constexpr bool is_valid_index_type_v = std::is_same_v<T, std::uint8_t> || std::is_same_v<T, std::uint16_t> || std::is_same_v<T, std::uint32_t>; template <typename T> class IndexBuffer { // Note that some OpenGL versions don't support 32-bit indices. In this case using them will cause a runtime error. static_assert(is_valid_index_type_v<T>, "Invalid index buffer element type."); struct Data { GLuint handle = 0; int size = 0; }; Data data; public: IndexBuffer() {} IndexBuffer(decltype(nullptr)) { glGenBuffers(1, &data.handle); if (!data.handle) Program::Error("Unable to create an index buffer."); // Not needed because there is no code below this point: // FINALLY_ON_THROW( glDeleteBuffers(1, &handle); ) } IndexBuffer(int count, const T *source = 0, Usage usage = static_draw) : IndexBuffer(nullptr) // Binds the buffer. { SetData(count, source, usage); } IndexBuffer(IndexBuffer &&other) noexcept : data(std::exchange(other.data, {})) {} IndexBuffer &operator=(IndexBuffer other) noexcept { std::swap(data, other.data); return *this; } ~IndexBuffer() { if (Bound()) IndexBuffers::ForgetBoundBuffer(); // GL unbinds the buffer automatically. if (data.handle) glDeleteBuffers(1, &data.handle); // Deleting 0 is a no-op, but GL could be unloaded at this point. } explicit operator bool() const { return bool(data.handle); } GLuint Handle() const { return data.handle; } void Bind() const { DebugAssert("Attempt to use a null index buffer.", *this); if (!*this) return; IndexBuffers::Bind(data.handle); } static void Unbind() { IndexBuffers::Bind(0); } [[nodiscard]] bool Bound() const { return data.handle && data.handle == IndexBuffers::Binding(); } int Size() const // This size is measured in elements, not bytes. { return data.size; } void SetData(int count, const T *source = 0, Usage usage = static_draw) // Binds the buffer. { DebugAssert("Attempt to use a null index buffer.", *this); if (!*this) return; Bind(); glBufferData(GL_ELEMENT_ARRAY_BUFFER, count * sizeof(T), source, usage); data.size = count; } void SetDataPart(int elem_offset, int elem_count, const T *source) // Binds the buffer. { SetDataPartBytes(elem_offset * sizeof(T), elem_count * sizeof(T), (const uint8_t *)source); } void SetDataPartBytes(int offset, int bytes, const uint8_t *source) // Binds the buffer. { DebugAssert("Attempt to use a null index buffer.", *this); if (!*this) return; Bind(); glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, offset, bytes, source); } static GLenum IndexTypeEnum() { if constexpr (std::is_same_v<T, std::uint8_t>) return GL_UNSIGNED_BYTE; else if constexpr (std::is_same_v<T, std::uint16_t>) return GL_UNSIGNED_SHORT; else if constexpr (std::is_same_v<T, std::uint32_t>) return GL_UNSIGNED_INT; else // This shouldn't happen, since we already have a static assertion that validates the template paramer. static_assert(Meta::value<false, T>, "Invalid index buffer element type."); } void DrawFromBoundBuffer(DrawMode m, int offset, int count) const // Binds the buffer. { DebugAssert("Attempt to use a null index buffer.", *this); if (!*this) return; Bind(); glDrawElements(m, count, IndexTypeEnum(), (void *)(uintptr_t)(offset * sizeof(T))); } void DrawFromBoundBuffer(DrawMode m, int count) const // Binds the buffer. { DrawFromBoundBuffer(m, 0, count); } void DrawFromBoundBuffer(DrawMode m) const // Binds the buffer. { DrawFromBoundBuffer(m, 0, Size()); } template <typename V> void Draw(const VertexBuffer<V> &buffer, DrawMode m, int offset, int count) const // Binds this buffer (and well as the passed vertex buffer). { buffer.BindDraw(); DrawFromBoundBuffer(m, offset, count); } template <typename V> void Draw(const VertexBuffer<V> &buffer, DrawMode m, int count) const // Binds this buffer (and well as the passed vertex buffer). { buffer.BindDraw(); DrawFromBoundBuffer(m, count); } template <typename V> void Draw(const VertexBuffer<V> &buffer, DrawMode m) const // Binds this buffer (and well as the passed vertex buffer). { buffer.BindDraw(); DrawFromBoundBuffer(m); } }; }
[ "blckcat@inbox.ru" ]
blckcat@inbox.ru
8c52b9bd0c4ed5a49a05b5f28e95830e7a133aab
75106d4dbd34c722969a396177e6571dc91ed4fc
/KW/Practices/OJ_Practice_Notes/KW/题目记录与通过代码/LeetCode_栈/682.棒球比赛.cpp
a3f00e52bfbb7bd5b1696295cfc2739a4536cd58
[]
no_license
2018PythonLearning/Python_Exercise
75ce52d878a2b84c436a5fb0d7db0ddba5f61938
15e78ce0ba6f3d485d4168d05da8fc8729390fc3
refs/heads/master
2021-05-11T01:16:55.238556
2020-09-07T13:06:57
2020-09-07T13:06:57
118,325,183
0
0
null
null
null
null
UTF-8
C++
false
false
549
cpp
class Solution { public: int calPoints(vector<string>& ops) { stack<int> s; int x, y; stringstream ss; for (int i = 0; i < ops.size(); i++) { if (ops[i] == "+") { x = s.top(); s.pop(); y = s.top(); s.push(x); s.push(x + y); } else if (ops[i] == "D") { s.push(s.top() * 2); } else if (ops[i] == "C") { s.pop(); } else { ss.clear(); ss << ops[i]; ss >> x; s.push(x); } } x = 0; while (s.size() != 0) { x += s.top(); s.pop(); } return x; } };
[ "1740133524@qq.com" ]
1740133524@qq.com
eee6d40d5e6c9f751d06b5e8af8816c03f8afb48
8c121b5c3dc564eb75f7cb8a1e881941d9792db9
/old_contest/at_coder_abc137_D.cpp
053b5949f96de390c0077ee4651cc122404810d9
[]
no_license
kayaru28/programming_contest
2f967a4479f5a1f2c30310c00c143e711445b12d
40bb79adce823c19bbd988f77b515052c710ea42
refs/heads/master
2022-12-13T18:32:37.818967
2022-11-26T16:36:20
2022-11-26T16:36:20
147,929,424
0
0
null
null
null
null
UTF-8
C++
false
false
1,538
cpp
#include <iostream> #include <stdio.h> #include <algorithm> #include <map> #include <math.h> using namespace std; #include <vector> #define rep(i,n) for (ll i = 0; i < (n) ; i++) #define INF 1e9 #define llINF 1e18 #define base10_4 10000 //1e4 #define base10_5 100000 //1e5 #define base10_6 1000000 //1e6 #define base10_7 10000000 //1e7 #define base10_8 100000000 //1e8 #define base10_9 1000000000 //1e9 #define MOD 1000000007 #define pb push_back #define ll long long #define ull unsigned long long #define vint vector<int> #define vll vector<ll> //#include <stack> #include <queue> //https://cpprefjp.github.io/reference/queue/priority_queue/pop.html // #include <iomanip> // cout << fixed << setprecision(15) << y << endl; string ans_Yes = "Yes"; string ans_No = "No"; string ans_yes = "yes"; string ans_no = "no"; vll A; vll B; vll valmap[base10_6]; ll C; ll N; ll M; ll K; ll ltmp; string stmp; double dtmp; int main(){ ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> N; cin >> M; rep(ni,N){ cin >> ltmp; A.push_back(ltmp); cin >> ltmp; B.push_back(ltmp); valmap[A[ni]].push_back(B[ni]); } ll ans = 0; std::priority_queue<ll> que; for( ll mi = 1 ; mi <=M ; mi++ ){ rep(vi,valmap[mi].size()){ que.push(valmap[mi][vi]); } if(que.size()>0){ ll getv = que.top(); ans += getv; que.pop(); } } cout << ans << endl; }
[ "istorytale090415@gmail.com" ]
istorytale090415@gmail.com
8eff6bd2b9192eb04ee43a4a407cd25bc0b0e618
7fb7d37a183fae068dfd78de293d4487977c241e
/chrome/browser/extensions/api/commands/extension_command_service_factory.h
155901642c3a1d06367e052ac271ef7c7afc74a0
[ "BSD-3-Clause" ]
permissive
robclark/chromium
f643a51bb759ac682341e3bb82cc153ab928cd34
f097b6ea775c27e5352c94ddddd264dd2af21479
refs/heads/master
2021-01-20T00:56:40.515459
2012-05-20T16:04:38
2012-05-20T18:56:07
4,587,416
1
0
null
null
null
null
UTF-8
C++
false
false
1,375
h
// Copyright (c) 2012 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 CHROME_BROWSER_EXTENSIONS_API_COMMANDS_EXTENSION_COMMAND_SERVICE_FACTORY_H_ #define CHROME_BROWSER_EXTENSIONS_API_COMMANDS_EXTENSION_COMMAND_SERVICE_FACTORY_H_ #pragma once #include "base/memory/singleton.h" #include "chrome/browser/profiles/profile_keyed_service_factory.h" class ExtensionCommandService; // Singleton that associate ExtensionCommandService objects with Profiles. class ExtensionCommandServiceFactory : public ProfileKeyedServiceFactory { public: static ExtensionCommandService* GetForProfile(Profile* profile); static ExtensionCommandServiceFactory* GetInstance(); // Overridden from ProfileKeyedBaseFactory: virtual bool ServiceIsCreatedWithProfile() OVERRIDE; private: friend struct DefaultSingletonTraits<ExtensionCommandServiceFactory>; ExtensionCommandServiceFactory(); virtual ~ExtensionCommandServiceFactory(); // ProfileKeyedServiceFactory: virtual ProfileKeyedService* BuildServiceInstanceFor( Profile* profile) const OVERRIDE; virtual bool ServiceRedirectedInIncognito() OVERRIDE; DISALLOW_COPY_AND_ASSIGN(ExtensionCommandServiceFactory); }; #endif // CHROME_BROWSER_EXTENSIONS_API_COMMANDS_EXTENSION_COMMAND_SERVICE_FACTORY_H_
[ "finnur@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98" ]
finnur@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98
a7e8bf1c39eb56a0da49a7d1eaae8c0e73abf641
795963c77fd920b5ba91e9045777c2137af37285
/C++/316.cpp
397f72a9987868283ef6dc5913e365e5f5dd7a7a
[]
no_license
kedixa/LeetCode
dce74c9395d366db559302b48b0b21cd4f869119
08acab1cebfac2aed4816cf9d8186a22304488a9
refs/heads/master
2020-07-04T05:11:33.019564
2018-03-08T13:30:18
2018-03-08T13:30:18
66,902,234
1
0
null
null
null
null
UTF-8
C++
false
false
1,363
cpp
class Solution { public: string removeDuplicateLetters(string s) { // next[i]表示字符s[i]下次一出现的位置,不存在则为-1 // 找到第一个使得next[i] 为-1的位置,在s[0..i]中找一个最小的字符加入到结果字符串中 // 删除经过此过程后不可能再被选取的字符,重复以上过程,直到没有字符可以选取 vector<int> vec(26, -1); // 记录每个字母出现的位置 int len = s.length(); if(len < 2) return s; vector<int> next(len, -1); for(int i = len - 1; i >= 0; i--) { next[i] = vec[s[i] - 'a']; vec[s[i] - 'a'] = i; } string str; // 保存结果 do { int pos = find(next.begin(), next.end(), -1) - next.begin(); if(pos == len) break; int midx = 0; while(next[midx] == -2) ++midx; for(int i = 0; i <= pos; i++) { if(next[i] != -2 && s[i] < s[midx]) midx = i; } str += s[midx]; for(int i = 0; i < midx; i++) next[i] = -2; int tmp; while(midx != -1) { tmp = next[midx]; next[midx] = -2; midx = tmp; } } while(true); return str; } };
[ "1204837541@qq.com" ]
1204837541@qq.com
258e85defddf458f05632f2d6ad2a0a8a97f3845
499f9aab16bca70504d5c71e5c3dab935c3dd4d9
/LiquidMenu.h
35263536e1086aaa6c4a47857e934052fd0ff556
[ "MIT" ]
permissive
Mcublog/LiquidMenu
85ad6ff95f65f455e03c2639abe8deb6af92f992
bab36c6e09e6f013c34f3483784f842b5bb92992
refs/heads/master
2020-07-26T00:46:42.369128
2020-05-07T08:23:24
2020-05-07T08:23:32
208,475,623
0
0
MIT
2019-09-14T17:15:56
2019-09-14T17:15:56
null
UTF-8
C++
false
false
34,890
h
/* The MIT License (MIT) Copyright (c) 2016 Vasil Kalchev 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. */ /** @file Include file for LiquidMenu library. @author Vasil Kalchev @date 2016 @version 1.4.0 @copyright The MIT License @todo: Change/Remove variables/screens/menus maybe @todo: screen wide glyphs @todo: dynamic memory @todo: variadic templates */ #pragma once #include <stdint.h> #if defined(__AVR__) #include <avr/pgmspace.h> #endif #include <stdio.h> #include <stdlib.h> #include "LiquidMenu_config.h" #include "LiquidMenu_debug.h" #if I2C #include <LiquidCrystal_I2C.h> #define DisplayClass LiquidCrystal_I2C #pragma message ("LiquidMenu: Configured for I2C. Edit 'LiquidMenu_config.h' file to change it.") #else #include <LiquidCrystal.h> #define DisplayClass LiquidCrystal #pragma message ("LiquidMenu: Configured for Parallel. Edit 'LiquidMenu_config.h' file to change it.") #endif #if LIQUIDMENU_DEBUG #warning "LiquidMenu: Debugging messages are enabled." #endif typedef bool (*boolFnPtr)(); typedef int8_t (*int8tFnPtr)(); typedef uint8_t (*uint8tFnPtr)(); typedef int16_t (*int16tFnPtr)(); typedef uint16_t (*uint16tFnPtr)(); typedef int32_t (*int32tFnPtr)(); typedef uint32_t (*uint32tFnPtr)(); typedef float (*floatFnPtr)(); typedef double (*doubleFnPtr)(); typedef char (*charFnPtr)(); typedef char * (*charPtrFnPtr)(); typedef const char * (*constcharPtrFnPtr)(); const char LIQUIDMENU_VERSION[] = "1.4"; ///< The version of the library. /// Data type enum. /** Used to store the data type of `void*` so that they can be cast back later. */ enum class DataType : uint8_t { NOT_USED = 0, BOOL = 1, BOOLEAN = 1, INT8_T = 8, UINT8_T = 9, BYTE = 9, INT16_T = 16, UINT16_T = 17, INT32_T = 32, UINT32_T = 33, FLOAT = 50, DOUBLE = 50, CHAR = 60, CHAR_PTR = 61, CONST_CHAR_PTR = 62, PROG_CONST_CHAR_PTR = 65, GLYPH = 70, BOOL_GETTER = 201, BOOLEAN_GETTER = 201, INT8_T_GETTER = 208, UINT8_T_GETTER = 209, BYTE_GETTER = 209, INT16_T_GETTER = 216, UINT16_T_GETTER = 217, INT32_T_GETTER = 232, UINT32_T_GETTER = 233, FLOAT_GETTER = 240, DOUBLE_GETTER = 240, CHAR_GETTER = 250, CHAR_PTR_GETTER = 251, CONST_CHAR_PTR_GETTER = 252 }; /// Position enum. /* Used to store and set the relative or absolute position of the focus indicator. */ enum class Position : uint8_t { RIGHT = 1, NORMAL = 1, LEFT = 2, CUSTOM = 3, }; /// @name recognizeType overloaded function /** Used to recognize the data type of a variable received in a template function. @see DataType */ ///@{ /** @param variable - variable to be checked @returns the data type in `DataType` enum format */ DataType recognizeType(bool variable); /** @param variable - variable to be checked @returns the data type in `DataType` enum format */ DataType recognizeType(char variable); /** @param variable - variable to be checked @returns the data type in `DataType` enum format */ DataType recognizeType(char* variable); /** @param variable - variable to be checked @returns the data type in `DataType` enum format */ DataType recognizeType(const char* variable); /** @param variable - variable to be checked @returns the data type in `DataType` enum format */ DataType recognizeType(int8_t variable); /** @param variable - variable to be checked @returns the data type in `DataType` enum format */ DataType recognizeType(uint8_t variable); /** @param variable - variable to be checked @returns the data type in `DataType` enum format */ DataType recognizeType(int16_t variable); /** @param variable - variable to be checked @returns the data type in `DataType` enum format */ DataType recognizeType(uint16_t variable); /** @param variable - variable to be checked @returns the data type in `DataType` enum format */ DataType recognizeType(int32_t variable); /** @param variable - variable to be checked @returns the data type in `DataType` enum format */ DataType recognizeType(uint32_t variable); /** @param variable - variable to be checked @returns the data type in `DataType` enum format */ DataType recognizeType(float variable); /** @param variable - variable to be checked @returns the data type in `DataType` enum format */ DataType recognizeType(double variable); /** @param variable - variable to be checked @returns the data type in `DataType` enum format */ DataType recognizeType(boolFnPtr variable); /** @param variable - variable to be checked @returns the data type in `DataType` enum format */ DataType recognizeType(int8tFnPtr variable); /** @param variable - variable to be checked @returns the data type in `DataType` enum format */ DataType recognizeType(uint8tFnPtr variable); /** @param variable - variable to be checked @returns the data type in `DataType` enum format */ DataType recognizeType(int16tFnPtr variable); /** @param variable - variable to be checked @returns the data type in `DataType` enum format */ DataType recognizeType(uint16tFnPtr variable); /** @param variable - variable to be checked @returns the data type in `DataType` enum format */ DataType recognizeType(int32tFnPtr variable); /** @param variable - variable to be checked @returns the data type in `DataType` enum format */ DataType recognizeType(uint32tFnPtr varible); /** @param variable - variable to be checked @returns the data type in `DataType` enum format */ DataType recognizeType(floatFnPtr variable); /** @param variable - variable to be checked @returns the data type in `DataType` enum format */ DataType recognizeType(doubleFnPtr variable); /** @param variable - variable to be checked @returns the data type in `DataType` enum format */ DataType recognizeType(charFnPtr variable); /** @param variable - variable to be checked @returns the data type in `DataType` enum format */ DataType recognizeType(charPtrFnPtr variable); /** @param variable - variable to be checked @returns the data type in `DataType` enum format */ DataType recognizeType(constcharPtrFnPtr variable); ///@} /// Prints the number passed to it in a specific way. /** Used for convenience when printing the class's address for indentification. @param address - number to be printed */ void print_me(uintptr_t address); /// Represents the individual lines printed on the display. /** This is the lowest class in the hierarchy, it holds pointers to the variables/constants that will be printed, where the line is positioned, where the focus indicator is positioned and pointers to the callback functions. This classes' objects go into a LiquidScreen object which controls them. The public methods are for configuration only. */ class LiquidLine { friend class LiquidScreen; public: /// @name Constructors ///@{ /// The main constructor. /** This is the main constructor that gets called every time. @param column - the column at which the line starts @param row - the row at which the line is printed */ LiquidLine(uint8_t column, uint8_t row) : _row(row), _column(column), _focusRow(row - 1), _focusColumn(column - 1), _focusPosition(Position::NORMAL), _variableCount(0), _focusable(false) { for (uint8_t i = 0; i < MAX_VARIABLES; i++) { _variable[i] = nullptr; _variableType[i] = DataType::NOT_USED; } for (uint8_t f = 0; f < MAX_FUNCTIONS; f++) { _function[f] = 0; } _floatDecimalPlaces = 2; } /// Constructor for one variable/constant. /** @param column - the column at which the line starts @param row - the row at which the line is printed @param &variableA - variable/constant to be printed */ template <typename A> LiquidLine(uint8_t column, uint8_t row, A &variableA) : LiquidLine(column, row) { add_variable(variableA); } /// Constructor for two variables/constants. /** @param column - the column at which the line starts @param row - the row at which the line is printed @param &variableA - variable/constant to be printed @param &variableB - variable/constant to be printed */ template <typename A, typename B> LiquidLine(uint8_t column, uint8_t row, A &variableA, B &variableB) : LiquidLine(column, row, variableA) { add_variable(variableB); } /// Constructor for three variables/constants. /** @param column - the column at which the line starts @param row - the row at which the line is printed @param &variableA - variable/constant to be printed @param &variableB - variable/constant to be printed @param &variableC - variable/constant to be printed */ template <typename A, typename B, typename C> LiquidLine(uint8_t column, uint8_t row, A &variableA, B &variableB, C &variableC) : LiquidLine(column, row, variableA, variableB) { add_variable(variableC); } /// Constructor for four variables/constants. /** @param column - the column at which the line starts @param row - the row at which the line is printed @param &variableA - variable/constant to be printed @param &variableB - variable/constant to be printed @param &variableC - variable/constant to be printed @param &variableD - variable/constant to be printed */ template <typename A, typename B, typename C, typename D> LiquidLine(uint8_t column, uint8_t row, A &variableA, B &variableB, C &variableC, D &variableD) : LiquidLine(column, row, variableA, variableB, variableC) { add_variable(variableD); } ///@} /// @name Public methods ///@{ /// Adds a variable to the line. /** @param &variable - reference to the variable @returns true on success and false if the maximum amount of variables has been reached @note The maximum amount of variable per line is specified in LiquidMenu_config.h as `MAX_VARIABLES`. The default is 5. @see LiquidMenu_config.h @see MAX_VARIABLES */ template <typename T> bool add_variable(T &variable) { print_me(reinterpret_cast<uintptr_t>(this)); if (_variableCount < MAX_VARIABLES) { _variable[_variableCount] = (void*)&variable; _variableType[_variableCount] = recognizeType(variable); # if LIQUIDMENU_DEBUG DEBUG(F("Added variable ")); // Check if the variable is actually a getter functions // and don't diplay it if so. if ((uint8_t)_variableType[_variableCount] < 200) { // 200+ are getters DEBUG(reinterpret_cast<uintptr_t>(variable)); DEBUGLN(F("")); } # endif _variableCount++; return true; } # if LIQUIDMENU_DEBUG DEBUG(F("Adding variable ")); // Check if the variable is actually a getter functions // and don't diplay it if so. if ((uint8_t)_variableType[_variableCount] < 200) { // 200+ are getters DEBUG(reinterpret_cast<uintptr_t>(variable)); } # endif DEBUGLN(F(" failed, edit LiquidMenu_config.h to allow for more variables")); return false; } /// Attaches a callback function to the line. /** The number is used for identification. The callback function can later be called when the line is focused with `LiquidMenu::call_function(uint8_t number) const`. @param number - function number used for identification @param *function - pointer to the function @returns true on success and false if maximum amount of functions has been reached @note Function numbering starts from 1. @note The maximum amount of functions per line is specified in LiquidMenu_config.h as `MAX_FUNCTIONS`. The default is 8. @see LiquidMenu_config.h @see MAX_FUNCTIONS @see bool LiquidMenu::call_function(uint8_t number) const */ bool attach_function(uint8_t number, void (*function)(void)); /// Sets the decimal places for floating point variables. /** @param decimalPlaces - number of decimal places to show */ void set_decimalPlaces(uint8_t decimalPlaces); /// Configures the focus indicator position for the line. /** The valid positions are `LEFT`, `RIGHT` and `CUSTOM`. The `CUSTOM` position is absolute so it also needs the column and row that it will be printed on. @param position - `LEFT`, `RIGHT` or `CUSTOM` @param column - if using `CUSTOM` this specifies the column @param row - if using `CUSTOM` this specifies the row @returns true on success and false if the position specified is invalid @note The `Position` is enum class. Use `Position::(member)` when specifying the position. @see Position */ bool set_focusPosition(Position position, uint8_t column = 0, uint8_t row = 0); /// Converts a byte variable into a glyph index. /** If a custom character (glyph) was created using `DisplayClass::createChar(byte index, byte character[8])` it can be displayed as a normal variable using this method. @param number - the variable number that will be converted to an index @returns true on success and false if the variable with that number is not a `byte`. */ bool set_asGlyph(uint8_t number); /// Converts a const char pointer variable into const char pointer PROGMEM one. /** Use this function to tell the object that the attached const char pointer variable is saved in flash memory rather than in RAM like a normal variable. @param number - the variable number that will be converted @returns true on success and false if the variable with that number is not a `const char[]`. */ bool set_asProgmem(uint8_t number); ///@} private: /// Prints the line to the display. /** Sets the cursor to the starting position. Then goes through a loop calling `print_variable(DisplayClass *p_liquidCrystal, uint8_t number)`. And finally displays the focus indicator if the line is focused. @param *p_liquidCrystal - pointer to the DisplayClass object @param isFocused - true if this line is focused */ void print(DisplayClass *p_liquidCrystal, bool isFocused); /// Prints a variable to the display. /** Casts the variable pointer specified by the number to its data type and prints it to the display. @param *p_liquidCrystal - pointer to the DisplayClass object @param number - number identifying the variable */ void print_variable(DisplayClass *p_liquidCrystal, uint8_t number); /// Calls an attached function specified by the number. /** @param number - number identifying the function @returns true if there is a function at the specified number @note Function numbering starts from 1. @see bool LiquidLine::attach_function(uint8_t number, void (*function)(void)) */ bool call_function(uint8_t number) const; uint8_t _row, _column, _focusRow, _focusColumn; Position _focusPosition; uint8_t _floatDecimalPlaces; uint8_t _variableCount; ///< Count of the variables void (*_function[MAX_FUNCTIONS])(void); ///< Pointers to the functions const void *_variable[MAX_VARIABLES]; ///< Pointers to the variables DataType _variableType[MAX_VARIABLES]; ///< Data type of the variables bool _focusable; ///< Determines whether the line is focusable }; /// Represents a screen shown on the display. /** A screen is made up of LiquidLine objects. It holds pointers to them and calls their functions when it is active. It also knows on which line the focus is. This classes' objects go into a LiquidMenu object which controls them. The public methods are for configuration only. @see LiquidLine */ class LiquidScreen { friend class LiquidMenu; public: /// @name Constructors ///@{ /// The main constructor. /** This is the main constructor that gets called every time. */ LiquidScreen(); /// Constructor for 1 LiquidLine object. /** @param &liquidLine - pointer to a LiquidLine object */ explicit LiquidScreen(LiquidLine &liquidLine); /// Constructor for 2 LiquidLine object. /** @param &liquidLine1 - pointer to a LiquidLine object @param &liquidLine2 - pointer to a LiquidLine object */ LiquidScreen(LiquidLine &liquidLine1, LiquidLine &liquidLine2); /// Constructor for 3 LiquidLine object. /** @param &liquidLine1 - pointer to a LiquidLine object @param &liquidLine2 - pointer to a LiquidLine object @param &liquidLine3 - pointer to a LiquidLine object */ LiquidScreen(LiquidLine &liquidLine1, LiquidLine &liquidLine2, LiquidLine &liquidLine3); /// Constructor for 4 LiquidLine object. /** @param &liquidLine1 - pointer to a LiquidLine object @param &liquidLine2 - pointer to a LiquidLine object @param &liquidLine3 - pointer to a LiquidLine object @param &liquidLine4 - pointer to a LiquidLine object */ LiquidScreen(LiquidLine &liquidLine1, LiquidLine &liquidLine2, LiquidLine &liquidLine3, LiquidLine &liquidLine4); ///@} /// @name Public methods ///@{ /// Adds a LiquidLine object to the screen. /** @param &liquidLine - pointer to a LiquidLine object @returns true on success and false if the maximum amount of lines has been reached @note The maximum amount of lines per screen is specified in LiquidMenu_config.h as `MAX_LINES`. The default is 8. @see LiquidMenu_config.h @see MAX_LINES */ bool add_line(LiquidLine &liquidLine); /// Sets the focus position for the whole screen at once. /** The valid positions are `LEFT` and `RIGHT`. `CUSTOM` is not valid for this function because it needs individual column and row for every line. @param position - `LEFT` or `RIGHT` @returns true on success and false if the position specified is invalid @note The `Position` is enum class. Use `Position::(member)` when specifying the position. @see Position */ bool set_focusPosition(Position position); /// Specifies the line size of the display (required for scrolling). /** This is required when you want to add more lines (LiquidLine objects) to a screen (LiquidScreen object) than the display's line size. The lines will be scrolled. @param lineCount - the line size of the display @warning Set this after adding all the "lines" to the "screen"! @warning Scrolling currently only works with "focusable" lines! */ void set_displayLineCount(uint8_t lineCount); /// Hides the screen. /** Hiding a screen means that it will be skipped when cycling the screens. @param hide - true for hiding and false for unhiding @note It can still be shown using the `change_screen` methods. @see LiquidMenu::change_screen(LiquidScreen p_liquidScreen) @see LiquidMenu::change_screen(uint8_t number) */ void hide(bool hide); uint8_t get_current_focus(); ///@} private: /// Prints the lines pointed by the screen. /** Calls the `LiquidLine::print(DisplayClass *p_liquidCrystal, bool isFocused)` for every line pointed by the screen. @param *p_liquidCrystal - pointer to the DisplayClass object */ void print(DisplayClass *p_liquidCrystal) const; /// Switches the focus. /** Switches the focus to the next or previous line according to the passed parameter. @param forward - true for forward, false for backward */ void switch_focus(bool forward = true); /// Calls an attached function specified by the number. /** Calls the function specified by the number argument for the focused line. @param number - number of the function in the array @returns true if there is a function at the specified number @note Function numbering starts from 1. @see bool LiquidLine::attach_function(uint8_t number, void (*function)(void)) */ bool call_function(uint8_t number) const; LiquidLine *_p_liquidLine[MAX_LINES]; ///< The LiquidLine objects uint8_t _lineCount; ///< Count of the LiquidLine objects uint8_t _focus; ///< Index of the focused line uint8_t _displayLineCount; ///< The number of lines the display supports bool _hidden; ///< If hidden skips this screen when cycling }; /// Represents a collection of screens forming a menu. /** A menu is made up of LiquidScreen objects. It holds pointers to them and calls their functions depending on which one is active. This is the class used for control. It is possible to use multiple menus, it that case this classes' objects go into a LiquidSystem object which controls them using the same public methods. @see LiquidScreen */ class LiquidMenu { friend class LiquidSystem; public: /// @name Constructors ///@{ /// The main constructor. /** This is the main constructor that gets called every time. @param &liquidCrystal - pointer to the DisplayClass object @param startingScreen - the number of the screen that will be shown first */ LiquidMenu(DisplayClass &liquidCrystal, uint8_t startingScreen = 1); /// Constructor for 1 LiquidScreen object. /** @param &liquidCrystal - pointer to the DisplayClass object @param &liquidScreen - pointer to a LiquidScreen object @param startingScreen - the number of the screen that will be shown first */ LiquidMenu(DisplayClass &liquidCrystal, LiquidScreen &liquidScreen, uint8_t startingScreen = 1); /// Constructor for 2 LiquidScreen objects. /** @param &liquidCrystal - pointer to the DisplayClass object @param &liquidScreen1 - pointer to a LiquidScreen object @param &liquidScreen2 - pointer to a LiquidScreen object @param startingScreen - the number of the screen that will be shown first */ LiquidMenu(DisplayClass &liquidCrystal, LiquidScreen &liquidScreen1, LiquidScreen &liquidScreen2, uint8_t startingScreen = 1); /// Constructor for 3 LiquidScreen objects. /** @param &liquidCrystal - pointer to the DisplayClass object @param &liquidScreen1 - pointer to a LiquidScreen object @param &liquidScreen2 - pointer to a LiquidScreen object @param &liquidScreen3 - pointer to a LiquidScreen object @param startingScreen - the number of the screen that will be shown first */ LiquidMenu(DisplayClass &liquidCrystal, LiquidScreen &liquidScreen1, LiquidScreen &liquidScreen2, LiquidScreen &liquidScreen3, uint8_t startingScreen = 1); /// Constructor for 4 LiquidScreen objects. /** @param &liquidCrystal - pointer to the DisplayClass object @param &liquidScreen1 - pointer to a LiquidScreen object @param &liquidScreen2 - pointer to a LiquidScreen object @param &liquidScreen3 - pointer to a LiquidScreen object @param &liquidScreen4 - pointer to a LiquidScreen object @param startingScreen - the number of the screen that will be shown first */ LiquidMenu(DisplayClass &liquidCrystal, LiquidScreen &liquidScreen1, LiquidScreen &liquidScreen2, LiquidScreen &liquidScreen3, LiquidScreen &liquidScreen4, uint8_t startingScreen = 1); ///@} /// @name Public methods ///@{ /// Adds a LiquidScreen object to the menu. /** @param &liquidScreen - pointer to a LiquidScreen object @returns true on success and false if the maximum amount of screens has been reached @note The maximum amount of screens per menu is specified in LiquidMenu_config.h as `MAX_SCREENS`. The default is 16. @see LiquidMenu_config.h @see MAX_SCREENS */ bool add_screen(LiquidScreen &liquidScreen); /// Returns a reference to the current screen. /** Call this method to obtain a reference to the current screen. @returns a reference to the current screen. */ LiquidScreen* get_currentScreen() const; uint8_t get_current_screen(); /// Switches to the next screen. void next_screen(); /// Switches to the next screen. /** @note Prefix increment operator overloading. */ void operator++(); /// Switches to the next screen. /** @note Postfix increment operator overloading. */ void operator++(int); /// Switches to the previous screen. void previous_screen(); /// Switches to the previous screen. /** @note Prefix decrement operator overloading. */ void operator--(); /// Switches to the previous screen. /** @note Postfix decrement operator overloading. */ void operator--(int); /// Switches to the specified screen. /** @param *p_liquidScreen - pointer to the LiquidScreen object @returns true on success and false if the screen is not found */ bool change_screen(LiquidScreen &p_liquidScreen); /// Switches to the specified screen. /** @param number - the number of the screen @returns true on success and false if the number of the screen is invalid. */ bool change_screen(uint8_t number); /// Switches to the specified screen. /** @param &p_liquidScreen - pointer to the screen @returns true on success and false if the screen is not found */ bool operator=(LiquidScreen &p_liquidScreen); /// Switches to the specified screen. /** @param number - the number of the screen @returns true on success and false if the number of the screen is invalid. */ bool operator=(uint8_t number); /// Switches the focus /** Switches the focus to the next or previous line according to the passed parameter. @param forward - true for forward, false for backward */ void switch_focus(bool forward = true); /// Sets the focus position for the whole menu at once. /** The valid positions are `LEFT` and `RIGHT`. `CUSTOM` is not valid for this function because it needs individual column and row for every line. @param position - `LEFT` or `RIGHT` @returns true on success and false if the position specified is invalid @note The `Position` is enum class. Use `Position::(member)` when specifying the position. @see Position */ bool set_focusPosition(Position position); /// Changes the focus indicator's symbol. /** The symbol is changed for a particular position. @param position - the position for which the symbol will be changed @param symbol[] - the symbol @returns true on success and false if the position specified is invalid @note The `Position` is enum class. Use `Position::(member)` when specifying the position. @see Position */ bool set_focusSymbol(Position position, uint8_t symbol[8]); /// Calls an attached function specified by the number. /** Calls the function specified by the number argument for the current screen and for the focused line. @param number - number of the function in the array @returns true if there is a function at the specified number @note Function numbering starts from 1. @see bool LiquidLine::attach_function(uint8_t number, void (*function)(void)) */ bool call_function(uint8_t number) const; /// Prints the current screen to the display. /** Call this method when there is a change in some of the attached variables. */ void update() const; /// Prints the current screen to the display (without clearing). /** Call this method when there is a change in some of the variable attached and the new symbols cover all of the old symbols. @note This method doesn't clear the display. */ void softUpdate() const; /// Initializes the menu object. /** Call this method to fully initialize the menu object. @note Needed when using an I2C display library. */ void init() const; ///@} private: DisplayClass *_p_liquidCrystal; ///< Pointer to the DisplayClass object LiquidScreen *_p_liquidScreen[MAX_SCREENS]; ///< The LiquidScreen objects uint8_t _screenCount; ///< Count of the LiquidScreen objects uint8_t _currentScreen; }; /// Represents a collection of menus forming a menu system. /** A menu system is made up of LiquidMenu objects. It holds pointers to them and calls their functions depending on which one is active. This class is uses the same public methods as LiquidMenu with the addition of a method for adding a LiquidMenu object and a method for changing the currently active menu. This class is optional, it is used only if there is a need for multiple menus. @see LiquidMenu */ class LiquidSystem { public: /// @name Constructors ///@{ /// The main constructor. /** This is the main constructor that gets called every time. @param startingMenu - the number of the menu that will be shown first */ explicit LiquidSystem(uint8_t startingMenu = 1); /// Constructor for 2 LiquidMenu objects. /** @param &liquidMenu1 - pointer to a LiquidMenu object @param &liquidMenu2 - pointer to a LiquidMenu object @param startingMenu - the number of the menu that will be shown first */ LiquidSystem(LiquidMenu &liquidMenu1, LiquidMenu &liquidMenu2, uint8_t startingMenu = 1); /// Constructor for 3 LiquidMenu objects. /** @param &liquidMenu1 - pointer to a LiquidMenu object @param &liquidMenu2 - pointer to a LiquidMenu object @param &liquidMenu3 - pointer to a LiquidMenu object @param startingMenu - the number of the menu that will be shown first */ LiquidSystem(LiquidMenu &liquidMenu1, LiquidMenu &liquidMenu2, LiquidMenu &liquidMenu3, uint8_t startingMenu = 1); /// Constructor for 4 LiquidMenu objects. /** @param &liquidMenu1 - pointer to a LiquidMenu object @param &liquidMenu2 - pointer to a LiquidMenu object @param &liquidMenu3 - pointer to a LiquidMenu object @param &liquidMenu4 - pointer to a LiquidMenu object @param startingMenu - the number of the menu that will be shown first */ LiquidSystem(LiquidMenu &liquidMenu1, LiquidMenu &liquidMenu2, LiquidMenu &liquidMenu3, LiquidMenu &liquidMenu4, uint8_t startingMenu = 1); ///@} /// @name Public methods ///@{ /// Adds a LiquidMenu object to the menu system. /** @param &liquidMenu - pointer to a LiquidMenu object @returns true on success and false if the maximum amount of menus has been reached @note The maximum amount of menus per menu system is specified in LiquidMenu_config.h as `MAX_MENUS`. The default is 12. @see LiquidMenu_config.h @see MAX_MENUS */ bool add_menu(LiquidMenu &liquidMenu); /// Switches to the specified menu. /** @param *p_liquidMenu - pointer to the LiquidMenu object @returns true on success and false if the menu is not found */ bool change_menu(LiquidMenu &p_liquidMenu); /// Returns a reference to the current screen. /** Call this method to obtain a reference to the current screen. @returns a reference to the current screen. */ LiquidScreen* get_currentScreen() const; /// Switches to the next screen. void next_screen(); /// Switches to the next screen. /** @note Prefix increment operator overloading. */ void operator++(); /// Switches to the next screen. /** @note Postfix increment operator overloading. */ void operator++(int); /// Switches to the previous screen. void previous_screen(); /// Switches to the previous screen. /** @note Prefix decrement operator overloading. */ void operator--(); /// Switches to the previous screen. /** @note Postfix decrement operator overloading. */ void operator--(int); /// Switches to the specified screen. /** @param *p_liquidScreen - pointer to the LiquidScreen object @returns true on success and false if the screen is not found */ bool change_screen(LiquidScreen &p_liquidScreen); /// Switches to the specified screen. /** @param number - the number of the screen @returns true on success and false if the number of the screen is invalid. */ bool change_screen(uint8_t number); /// Switches to the specified screen. /** @param &p_liquidScreen - pointer to the screen @returns true on success and false if the screen is not found */ bool operator=(LiquidScreen &p_liquidScreen); /// Switches to the specified screen. /** @param number - the number of the screen @returns true on success and false if the number of the screen is invalid. */ bool operator=(uint8_t number); /// Switches the focus /** Switches the focus to the next or previous line according to the passed parameter. @param forward - true for forward, false for backward */ void switch_focus(bool forward = true); /// Sets the focus position for the whole menu at once. /** The valid positions are `LEFT` and `RIGHT`. `CUSTOM` is not valid for this function because it needs individual column and row for every line. @param position - `LEFT` or `RIGHT` @returns true on success and false if the position specified is invalid @note The `Position` is enum class. Use `Position::(member)` when specifying the position. @see Position */ bool set_focusPosition(Position position); /// Changes the focus indicator's symbol. /** The symbol is changed for a particular position. @param position - the position for which the symbol will be changed @param symbol[] - the symbol @returns true on success and false if the position specified is invalid @note The `Position` is enum class. Use `Position::(member)` when specifying the position. @see Position */ bool set_focusSymbol(Position position, uint8_t symbol[8]); /// Calls an attached function specified by the number. /** Calls the function specified by the number argument for the current screen and for the focused line. @param number - number of the function in the array @returns true if there is a function at the specified number @note Function numbering starts from 1. @see bool LiquidLine::attach_function(uint8_t number, void (*function)(void)) */ bool call_function(uint8_t number) const; /// Prints the current screen to the display. /** Call this method when there is a change in some of the variable attached. */ void update() const; /// Prints the current screen to the display (without clearing). /** Call this method when there is a change in some of the variable attached and the new symbols cover all of the old symbols. @note This method doesn't clear the display. */ void softUpdate() const; ///@} private: LiquidMenu *_p_liquidMenu[MAX_MENUS]; ///< The LiquidMenu objects uint8_t _menuCount; ///< Count of the LiquidMenu objects uint8_t _currentMenu; };
[ "noreply@github.com" ]
noreply@github.com
de7c9caf7fa4de0cf5e6ebdc90bbd0fa7d087bea
4e620cf9a0142b1d2a3846bc9ee47fe870e43d5d
/serial/StateTable.h
e191f5968b0894ca9a834753eb80fb6a2e2d5059
[]
no_license
AndreV2890/LeapCar
37b8cf129723ad97eb1ccf092977aa83252893ca
2f3f8f828b439cf7904c8e7d9abc29005cec6802
refs/heads/master
2021-01-22T05:38:45.411166
2017-05-26T08:03:17
2017-05-26T08:03:17
92,486,046
0
0
null
null
null
null
UTF-8
C++
false
false
1,661
h
/* * StateTable.h * * Created on: 28 apr 2016 * Author: andrea */ #ifndef SERIAL_STATETABLE_H_ #define SERIAL_STATETABLE_H_ #include "Buffer.h" #include "Timer.h" enum State_ST {wait_for_ACK, wait_for_msg, null, MAX_STATE}; enum Signal_ST {ack_id_correct, ack_id_incorrect, msg_to_send, end_timer, signal_tick, MAX_SIGNAL}; enum action_ST {do_nothing, remove_msg, send_start, send_reset}; class StateTable{ public: //The type ActiveState represents the pair actionToDo and nextState contained inside each entry of the //State Table typedef struct{ action_ST actionToDo; State_ST nextState; }ActionState; //To represent the current state State_ST current_state; //State Table ActionState myTable[MAX_STATE][MAX_SIGNAL] = { { {action_ST::remove_msg,State_ST::wait_for_msg}, {action_ST::do_nothing,State_ST::wait_for_ACK}, {action_ST::do_nothing,State_ST::wait_for_ACK}, {action_ST::send_reset, State_ST::wait_for_ACK}, {action_ST::do_nothing,State_ST::wait_for_ACK} }, { {action_ST::do_nothing,State_ST::wait_for_msg}, {action_ST::do_nothing,State_ST::wait_for_msg}, {action_ST::send_start,State_ST::wait_for_ACK}, {action_ST::do_nothing, State_ST::wait_for_msg}, {action_ST::do_nothing,State_ST::wait_for_msg} }, }; //Pointer to timer object to manage the time (useful for checking signals) Timer* timer; //Functions for the State Machine void init(); void dispatch(Signal_ST, char*, Buffer*, char*); void tran(State_ST); }; #endif /* SERIAL_STATETABLE_H_ */
[ "andrea.vincentini28@gmail.com" ]
andrea.vincentini28@gmail.com
17c0f26375c723a261e5dc44bcae6ff20ca8bab0
b257bd5ea374c8fb296dbc14590db56cb7e741d8
/Extras/DevExpress VCL/Library/RS17/Win64/dxCheckGroupBox.hpp
a472b4c87ed098ccc9bd01577fa3978390ba000d
[]
no_license
kitesoft/Roomer-PMS-1
3d362069e3093f2a49570fc1677fe5682de3eabd
c2f4ac76b4974e4a174a08bebdb02536a00791fd
refs/heads/master
2021-09-14T07:13:32.387737
2018-05-04T12:56:58
2018-05-04T12:56:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,950
hpp
// CodeGear C++Builder // Copyright (c) 1995, 2012 by Embarcadero Technologies, Inc. // All rights reserved // (DO NOT EDIT: machine generated header) 'dxCheckGroupBox.pas' rev: 24.00 (Win64) #ifndef DxcheckgroupboxHPP #define DxcheckgroupboxHPP #pragma delphiheader begin #pragma option push #pragma option -w- // All warnings off #pragma option -Vx // Zero-length empty class member #pragma pack(push,8) #include <System.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <Winapi.Windows.hpp> // Pascal unit #include <Winapi.Messages.hpp> // Pascal unit #include <System.Types.hpp> // Pascal unit #include <System.SysUtils.hpp> // Pascal unit #include <System.Classes.hpp> // Pascal unit #include <Vcl.Controls.hpp> // Pascal unit #include <Vcl.Graphics.hpp> // Pascal unit #include <Vcl.Forms.hpp> // Pascal unit #include <cxGroupBox.hpp> // Pascal unit #include <cxEdit.hpp> // Pascal unit #include <cxCheckBox.hpp> // Pascal unit #include <cxLookAndFeelPainters.hpp> // Pascal unit #include <cxContainer.hpp> // Pascal unit #include <cxControls.hpp> // Pascal unit #include <System.UITypes.hpp> // Pascal unit #include <cxLookAndFeels.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Dxcheckgroupbox { //-- type declarations ------------------------------------------------------- enum TdxCheckGroupBoxCheckBoxAction : unsigned char { cbaNone, cbaToggleChildrenEnabledState }; class DELPHICLASS TdxCheckGroupBoxProperties; class PASCALIMPLEMENTATION TdxCheckGroupBoxProperties : public Cxgroupbox::TcxCustomGroupBoxProperties { typedef Cxgroupbox::TcxCustomGroupBoxProperties inherited; protected: virtual bool __fastcall CanValidate(void); public: virtual bool __fastcall IsResetEditClass(void); __published: __property ImmediatePost = {default=0}; __property ValidationOptions = {default=1}; __property OnChange; __property OnEditValueChanged; __property OnValidate; public: /* TcxCustomEditProperties.Create */ inline __fastcall virtual TdxCheckGroupBoxProperties(System::Classes::TPersistent* AOwner) : Cxgroupbox::TcxCustomGroupBoxProperties(AOwner) { } /* TcxCustomEditProperties.Destroy */ inline __fastcall virtual ~TdxCheckGroupBoxProperties(void) { } }; typedef System::TMetaClass* TdxCustomCheckGroupBoxCheckBoxClass; class DELPHICLASS TdxCustomCheckGroupBoxCheckBox; class DELPHICLASS TdxCustomCheckGroupBox; class PASCALIMPLEMENTATION TdxCustomCheckGroupBoxCheckBox : public System::Classes::TPersistent { typedef System::Classes::TPersistent inherited; private: TdxCheckGroupBoxCheckBoxAction FCheckAction; TdxCustomCheckGroupBox* FCheckGroupBox; bool FVisible; bool __fastcall GetChecked(void); void __fastcall SetChecked(const bool AValue); void __fastcall SetVisible(const bool AValue); public: __fastcall virtual TdxCustomCheckGroupBoxCheckBox(TdxCustomCheckGroupBox* AOwner)/* overload */; virtual void __fastcall Assign(System::Classes::TPersistent* Source); __property TdxCheckGroupBoxCheckBoxAction CheckAction = {read=FCheckAction, write=FCheckAction, default=1}; __property bool Checked = {read=GetChecked, write=SetChecked, default=1}; __property bool Visible = {read=FVisible, write=SetVisible, default=1}; public: /* TPersistent.Destroy */ inline __fastcall virtual ~TdxCustomCheckGroupBoxCheckBox(void) { } }; class PASCALIMPLEMENTATION TdxCustomCheckGroupBox : public Cxgroupbox::TcxCustomGroupBox { typedef Cxgroupbox::TcxCustomGroupBox inherited; private: TdxCustomCheckGroupBoxCheckBox* FCheckBox; bool FFocusable; HIDESBASE TdxCheckGroupBoxProperties* __fastcall GetActiveProperties(void); TdxCheckGroupBoxProperties* __fastcall GetProperties(void); void __fastcall SetCheckBox(TdxCustomCheckGroupBoxCheckBox* AValue); HIDESBASE void __fastcall SetProperties(TdxCheckGroupBoxProperties* Value); HIDESBASE MESSAGE void __fastcall CMDialogChar(Winapi::Messages::TWMKey &Message); HIDESBASE MESSAGE void __fastcall WMKillFocus(Winapi::Messages::TWMKillFocus &Message); HIDESBASE MESSAGE void __fastcall WMLButtonUp(Winapi::Messages::TWMMouse &Message); HIDESBASE MESSAGE void __fastcall WMSetFocus(Winapi::Messages::TWMSetFocus &Message); protected: virtual bool __fastcall CanFocusOnClick(int X, int Y)/* overload */; void __fastcall DoCheckBoxCheckedChanged(void); void __fastcall EnableChildControls(Vcl::Controls::TControl* AControl, bool AEnabled); __classmethod virtual TdxCustomCheckGroupBoxCheckBoxClass __fastcall GetCheckBoxClass(); virtual bool __fastcall GetCheckBoxVisible(void); virtual void __fastcall Initialize(void); virtual bool __fastcall InternalCanFocusOnClick(void); virtual void __fastcall InternalSetEditValue(const System::Variant &Value, bool AValidateEditValue); virtual void __fastcall Loaded(void); __property TdxCustomCheckGroupBoxCheckBox* CheckBox = {read=FCheckBox, write=SetCheckBox}; __property bool Focusable = {read=FFocusable, write=FFocusable, default=1}; __property TabStop = {default=1}; public: __fastcall virtual TdxCustomCheckGroupBox(System::Classes::TComponent* AOwner)/* overload */; __fastcall virtual ~TdxCustomCheckGroupBox(void); DYNAMIC bool __fastcall CanFocus(void); __classmethod virtual Cxedit::TcxCustomEditPropertiesClass __fastcall GetPropertiesClass(); virtual void __fastcall PrepareEditValue(const System::Variant &ADisplayValue, /* out */ System::Variant &EditValue, bool AEditFocused); __property TdxCheckGroupBoxProperties* ActiveProperties = {read=GetActiveProperties}; __property TdxCheckGroupBoxProperties* Properties = {read=GetProperties, write=SetProperties}; public: /* TcxCustomEdit.Create */ inline __fastcall virtual TdxCustomCheckGroupBox(System::Classes::TComponent* AOwner, bool AIsInplace)/* overload */ : Cxgroupbox::TcxCustomGroupBox(AOwner, AIsInplace) { } public: /* TWinControl.CreateParented */ inline __fastcall TdxCustomCheckGroupBox(HWND ParentWindow) : Cxgroupbox::TcxCustomGroupBox(ParentWindow) { } /* Hoisted overloads: */ protected: inline bool __fastcall CanFocusOnClick(void){ return Cxgroupbox::TcxCustomGroupBox::CanFocusOnClick(); } }; typedef System::TMetaClass* TdxCheckGroupBoxCheckBoxClass; class DELPHICLASS TdxCheckGroupBoxCheckBox; class PASCALIMPLEMENTATION TdxCheckGroupBoxCheckBox : public TdxCustomCheckGroupBoxCheckBox { typedef TdxCustomCheckGroupBoxCheckBox inherited; __published: __property CheckAction = {default=1}; __property Checked = {default=1}; __property Visible = {default=1}; public: /* TdxCustomCheckGroupBoxCheckBox.Create */ inline __fastcall virtual TdxCheckGroupBoxCheckBox(TdxCustomCheckGroupBox* AOwner)/* overload */ : TdxCustomCheckGroupBoxCheckBox(AOwner) { } public: /* TPersistent.Destroy */ inline __fastcall virtual ~TdxCheckGroupBoxCheckBox(void) { } }; class DELPHICLASS TdxCheckGroupBox; class PASCALIMPLEMENTATION TdxCheckGroupBox : public TdxCustomCheckGroupBox { typedef TdxCustomCheckGroupBox inherited; protected: __classmethod virtual TdxCustomCheckGroupBoxCheckBoxClass __fastcall GetCheckBoxClass(); __published: __property Alignment = {default=0}; __property Anchors = {default=3}; __property BiDiMode; __property Caption = {default=0}; __property CaptionBkColor; __property CheckBox; __property Color; __property Constraints; __property Ctl3D; __property DockSite = {default=0}; __property DragCursor = {default=-12}; __property DragKind = {default=0}; __property DragMode = {default=0}; __property Enabled = {default=1}; __property Focusable = {default=1}; __property Font; __property LookAndFeel; __property PanelStyle; __property ParentBackground = {default=1}; __property ParentBiDiMode = {default=1}; __property ParentColor = {default=1}; __property ParentCtl3D = {default=1}; __property ParentFont = {default=1}; __property ParentShowHint = {default=1}; __property PopupMenu; __property Properties; __property RedrawOnResize = {default=1}; __property ShowHint; __property Style; __property StyleDisabled; __property StyleFocused; __property StyleHot; __property TabOrder = {default=-1}; __property TabStop = {default=1}; __property Transparent = {default=0}; __property UseDockManager = {default=0}; __property Visible = {default=1}; __property OnClick; __property OnContextPopup; __property OnCustomDraw; __property OnCustomDrawCaption; __property OnCustomDrawContentBackground; __property OnDblClick; __property OnDockDrop; __property OnDockOver; __property OnDragDrop; __property OnDragOver; __property OnEndDock; __property OnEndDrag; __property OnEnter; __property OnExit; __property OnGetSiteInfo; __property OnMeasureCaptionHeight; __property OnMouseDown; __property OnMouseEnter; __property OnMouseLeave; __property OnMouseMove; __property OnMouseUp; __property OnResize; __property OnStartDock; __property OnStartDrag; __property OnUnDock; public: /* TdxCustomCheckGroupBox.Create */ inline __fastcall virtual TdxCheckGroupBox(System::Classes::TComponent* AOwner)/* overload */ : TdxCustomCheckGroupBox(AOwner) { } /* TdxCustomCheckGroupBox.Destroy */ inline __fastcall virtual ~TdxCheckGroupBox(void) { } public: /* TcxCustomEdit.Create */ inline __fastcall virtual TdxCheckGroupBox(System::Classes::TComponent* AOwner, bool AIsInplace)/* overload */ : TdxCustomCheckGroupBox(AOwner, AIsInplace) { } public: /* TWinControl.CreateParented */ inline __fastcall TdxCheckGroupBox(HWND ParentWindow) : TdxCustomCheckGroupBox(ParentWindow) { } }; //-- var, const, procedure --------------------------------------------------- } /* namespace Dxcheckgroupbox */ #if !defined(DELPHIHEADER_NO_IMPLICIT_NAMESPACE_USE) && !defined(NO_USING_NAMESPACE_DXCHECKGROUPBOX) using namespace Dxcheckgroupbox; #endif #pragma pack(pop) #pragma option pop #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // DxcheckgroupboxHPP
[ "bas@roomerpms.com" ]
bas@roomerpms.com
7c82fa7e2a1fb902a33fa38dedd1b7b797290fc6
e70b8c9a6f71492db211d6ac8bf90860ca30a76e
/Math/15420번_Blowing Candles.cpp
dd8dc12a44b8abb26ae1a6ac9f34d4e843574024
[]
no_license
orihehe/BOJ
b289031abf5736c7f9d933fa52a889d73de39614
6c78d53f8ec1a9251f252f913d5f8e3a6fdb14fc
refs/heads/master
2020-04-04T09:56:25.511131
2019-11-04T13:19:17
2019-11-04T13:19:17
155,836,795
3
1
null
null
null
null
UTF-8
C++
false
false
2,150
cpp
/* BOJ 15420 - Blowing Candles https://www.acmicpc.net/problem/15420 컨벡스 헐로 볼록껍질을 만든 후 인접한 두 점을 지나는 직선과 가장 먼 점의 거리의 최솟값을 구해준다. */ #include <cstdio> #include <algorithm> #include <vector> #include <cmath> #define pii pair<int,int> #define ll long long using namespace std; /* 🐣🐥 */ ll ccw(pii a, pii b, pii c) { return 1LL * (a.first - c.first)*(b.second - c.second) - 1LL * (b.first - c.first)*(a.second - c.second); } pii arr[200001]; vector<pii> sta; long double a, b, c; long double dist(pii x) { long double ret = a * x.first + b * x.second + c; if (ret < 0) ret = -ret; return ret; } int main() { int n, r; scanf("%d %d", &n, &r); for (int i = 0; i < n; i++) { scanf("%d %d", &arr[i].first, &arr[i].second); } sort(arr, arr + n); sort(arr + 1, arr + n, [](pii a, pii b) { if (ccw(a, b, arr[0])) return ccw(a, b, arr[0]) > 0; return a < b; }); sta.push_back(arr[0]); sta.push_back(arr[1]); for (int i = 2; i < n; i++) { while (sta.size() >= 2 && ccw(sta.back(), arr[i], sta[sta.size() - 2]) <= 0) sta.pop_back(); sta.push_back(arr[i]); } n = sta.size(); if (n == 2) return !printf("0"); long double ans = 400000001; for (int i = 0; i < n; i++) { if (sta[i].first == sta[(i + 1) % n].first) { a = 1; b = 0; c = -sta[i].first; } else if (sta[i].second == sta[(i + 1) % n].second) { a = 0; b = 1; c = -sta[i].second; } else { a = (long double)(sta[i].second - sta[(i + 1) % n].second) / (sta[i].first - sta[(i + 1) % n].first); b = -1; c = sta[i].second - a * sta[i].first; } long double loc = 0; int l = 0, r = n - 3, mid; while (l <= r) { mid = (l + r) / 2; loc = max(loc, dist(sta[(i + 2 + mid) % n])); loc = max(loc, dist(sta[(i + 3 + mid) % n])); if (dist(sta[(i + 2 + mid) % n]) > dist(sta[(i + 3 + mid) % n])) { r = mid - 1; } else { l = mid + 1; } } loc = max(loc, dist(sta[(i + 2 + mid) % n])); loc = max(loc, dist(sta[(i + 3 + mid) % n])); ans = min(ans, loc / sqrt(a * a + b * b)); } printf("%.10Lf", ans); return 0; }
[ "38060133+orihehe@users.noreply.github.com" ]
38060133+orihehe@users.noreply.github.com
e41f394366f630670d5798ff0ff564fab5082e1c
14dbecb6cecc1bbff01ed6b8be22e50c97bdb889
/CAB_SDN-cython-api/tools/test_bucket_tree.cpp
ff2ca472e16ba9cf49fe9233313ff48d286b3c45
[]
no_license
jacketsu/CAB_SDN
887611f7ea483766745392d2a82e9b1947fc3959
d05b02442c445a214fafcb078393f0dbc1d81319
refs/heads/master
2021-05-09T15:16:09.413790
2018-01-27T19:01:48
2018-01-27T19:01:48
119,088,249
14
1
null
null
null
null
UTF-8
C++
false
false
2,757
cpp
#include <utility> #include <fstream> #include <boost/timer.hpp> #include <boost/filesystem.hpp> #include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/filter/gzip.hpp> #include "BucketTree.h" using namespace std; int bucket_tree_match(const addr_5tup & pkt, const bucket_tree & bTree, const rule_list & rList, bucket * b ) { bucket * matched_bucket = nullptr; matched_bucket = bTree.search_bucket(pkt,bTree.root); if(matched_bucket == nullptr) { return -1; } for(auto i : matched_bucket->related_rules) { if(rList.list[i].packet_hit(pkt)) { b = matched_bucket; return i; } } return -1; } int linear_match(const addr_5tup & pkt , const rule_list & r) { for(size_t i = 0; i != r.list.size(); ++i) { if( r.list[i].packet_hit(pkt)) { return i; } } return -1; } int main(int argc, char* argv[]) { if(argc < 3) { std::cerr << "Usage: TestBTree {/path/to/rule/file} {/path/to/trace/file}" << std::endl; return 1; } //load rules string ruleFP(argv[1]); rule_list rList(ruleFP); boost::timer t; std::cerr << "loaded rules : " << rList.list.size() <<" "<<t.elapsed()<<std::endl; //build bucket tree t.restart(); bucket_tree bTree(rList, uint32_t(15)); std::cerr << "built bucket tree : " <<" "<<t.elapsed() << std::endl; //load trace and test ifstream traceF(argv[2]); if(!traceF.is_open()) { cerr << "can not open trace file." << endl; return 3; } boost::iostreams::filtering_istream traceFF; traceFF.push(boost::iostreams::gzip_decompressor()); traceFF.push(traceF); string buf; while(getline(traceFF,buf)) { addr_5tup pkt(buf,false); bucket *matched_bucket = nullptr; int bkt_matched_id = bucket_tree_match(pkt,bTree,rList,matched_bucket); int lnr_matched_id = linear_match(pkt,rList); if(bkt_matched_id != lnr_matched_id) { cout << "packet " << pkt.str_readable() << endl << endl; if(lnr_matched_id != -1) { cout <<"\tlinear search match hit "<< rList.list[lnr_matched_id].get_str() << endl; } else { cout <<"\tlinear search not found."<<endl; } if(bkt_matched_id != -1) { cout <<"\tbucket search match hit "<< rList.list[bkt_matched_id].get_str() << endl; cout <<"\t\tbucket matched " << matched_bucket->get_str() <<endl; } else { cout <<"\tbucket search not found."<<endl; } } } }
[ "jacketsu@hotmail.com" ]
jacketsu@hotmail.com
2ccb1846ed98116c17fd88a0d0245593dcd9cf36
9500d3c808215edc1ca906206343c282d99f9979
/ED-03A/Monitoria09 - Exercicios/Ponteiros/Q3.cpp
38f9d399af70dd58214ecdcdb89a7c764da512c1
[]
no_license
HenrickyL/Monitoria_2020-1
2ea7f6646113e1737d0955c7f86f07d483049d6d
e55ad9d2e9326a5881af8420cc1449339f58a6a8
refs/heads/master
2021-04-04T03:24:35.501039
2020-10-21T00:08:01
2020-10-21T00:08:01
248,421,031
0
0
null
null
null
null
UTF-8
C++
false
false
627
cpp
#include <iostream> using namespace std; //min e max void mm(int A[], int n, int *min, int *max){ //pensar no valor inicial de min e max *min = A[0]; *max = A[0]; //percorrer o vetor for(int i =0; i< n; i++){ //verificação if(A[i] < *min ){ // minimo *min = A[i]; // se for menor troca }else if( A[i] > *max){ *max = A[i]; } } } int main(){ int n; cout << "Digite o tamanho do vetor:"; cin >> n ; int v[n]; cout << "Digite os elementos:\n"; for(int i = 0 ; i<n; i++){ cin >> v[i]; } int min, max; mm(v, n, &min, &max); cout << "\nMax: " << max << "\nMin: " << min << "\n"; return 0; }
[ "henrickyL1@gmail.com" ]
henrickyL1@gmail.com
928ac4ff08e836026e75dc7d49957d190bda8378
091492c575d6750876cb3d49e3f096e48eff629a
/AngryBirds_Box2D/Engine/GameEngine/ContainerLink.h
d5a259b5c8042cf03c4ce2eac9e867d8c5b88887
[]
no_license
omarzohdi/Box2D-AngryBirds-Physics
4764ae536aa8267b228dfb51b10df09d589d4c74
dbf7844532f2e91607f04a83ec875cd731b25b00
refs/heads/master
2020-12-31T06:09:08.424881
2016-05-07T21:50:36
2016-05-07T21:50:36
58,285,797
1
0
null
null
null
null
UTF-8
C++
false
false
342
h
#ifndef CONTAINERLINK_H #define CONTAINERLINK_H #include "EnumName.h" class ContainerLink // abstract class { public: ContainerLink(); virtual ~ContainerLink(); virtual EnumName getName() = 0; protected: virtual void Initialize(); public: // Data: ------------------------ ContainerLink *next; ContainerLink *prev; }; #endif
[ "omarzohdi@gmail.com" ]
omarzohdi@gmail.com
fc13d8f5a7fc6dc35908dc348e53d8b688f0dc6a
3b19128dc228501860e3d6019681c5c374631ca5
/FindRaspDetailComplecIndex.h
126b270b5dbbf87b9691d298116bda6695f61432
[]
no_license
a-ouchakov/DesignerOrders
e4a37f7b66431e22e58dd2af360b523f27f32aae
d4e37fb060db2eff153d1cfbebba2ab70d0ac504
refs/heads/master
2020-04-05T23:18:04.361183
2014-10-22T07:28:27
2014-10-22T07:28:27
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
4,880
h
//--------------------------------------------------------------------------- #ifndef FindRaspDetailComplecIndexH #define FindRaspDetailComplecIndexH //--------------------------------------------------------------------------- #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> #include "RzButton.hpp" #include "RzPanel.hpp" #include <ExtCtrls.hpp> #include "cxClasses.hpp" #include "cxControls.hpp" #include "cxCurrencyEdit.hpp" #include "cxCustomData.hpp" #include "cxData.hpp" #include "cxDataStorage.hpp" #include "cxDBData.hpp" #include "cxEdit.hpp" #include "cxFilter.hpp" #include "cxGraphics.hpp" #include "cxGrid.hpp" #include "cxGridBandedTableView.hpp" #include "cxGridCustomTableView.hpp" #include "cxGridCustomView.hpp" #include "cxGridDBBandedTableView.hpp" #include "cxGridDBTableView.hpp" #include "cxGridLevel.hpp" #include "cxGridTableView.hpp" #include "cxStyles.hpp" #include "RzEdit.hpp" #include <ADODB.hpp> #include <DB.hpp> #include <Mask.hpp> #include "cxDBTL.hpp" #include "cxInplaceContainer.hpp" #include "cxMaskEdit.hpp" #include "cxTL.hpp" #include "cxTLData.hpp" #include <ImgList.hpp> #include "cxCalendar.hpp" #include "cxLookAndFeelPainters.hpp" #include "cxLookAndFeels.hpp" #include "cxTLdxBarBuiltInMenu.hpp" #include "dxSkinsCore.hpp" #include "dxSkinsDefaultPainters.hpp" #include "cxCheckComboBox.hpp" #include "dxSkinBlack.hpp" #include "dxSkinBlue.hpp" #include "dxSkinBlueprint.hpp" #include "dxSkinCaramel.hpp" #include "dxSkinCoffee.hpp" #include "dxSkinDarkRoom.hpp" #include "dxSkinDarkSide.hpp" #include "dxSkinDevExpressDarkStyle.hpp" #include "dxSkinDevExpressStyle.hpp" #include "dxSkinFoggy.hpp" #include "dxSkinGlassOceans.hpp" #include "dxSkinHighContrast.hpp" #include "dxSkiniMaginary.hpp" #include "dxSkinLilian.hpp" #include "dxSkinLiquidSky.hpp" #include "dxSkinLondonLiquidSky.hpp" #include "dxSkinMcSkin.hpp" #include "dxSkinMoneyTwins.hpp" #include "dxSkinOffice2007Black.hpp" #include "dxSkinOffice2007Blue.hpp" #include "dxSkinOffice2007Green.hpp" #include "dxSkinOffice2007Pink.hpp" #include "dxSkinOffice2007Silver.hpp" #include "dxSkinOffice2010Black.hpp" #include "dxSkinOffice2010Blue.hpp" #include "dxSkinOffice2010Silver.hpp" #include "dxSkinPumpkin.hpp" #include "dxSkinSeven.hpp" #include "dxSkinSevenClassic.hpp" #include "dxSkinSharp.hpp" #include "dxSkinSharpPlus.hpp" #include "dxSkinSilver.hpp" #include "dxSkinSpringTime.hpp" #include "dxSkinStardust.hpp" #include "dxSkinSummer2008.hpp" #include "dxSkinTheAsphaltWorld.hpp" #include "dxSkinValentine.hpp" #include "dxSkinVS2010.hpp" #include "dxSkinWhiteprint.hpp" #include "dxSkinXmas2008Blue.hpp" //--------------------------------------------------------------------------- class TFrFindRaspDetailComplecIndex : public TForm { __published: // IDE-managed Components TRzPanel *RzPanel1; TRzPanel *RzPanel2; TcxDBTreeList *tlRaspDetailIndex; TRzPanel *RzPanel3; TRzToolButton *RzToolButton1; TRzToolButton *RzToolButton2; TRzSpacer *RzSpacer3; TRzSpacer *RzSpacer4; TRzSpacer *RzSpacer5; TTimer *TmIndex; TDataSource *DSIndex; TADOQuery *QIndex; TImageList *ImageList1; TIntegerField *QIndexIdn; TIntegerField *QIndexPIdn; TStringField *QIndexNameRaspDetail; TIntegerField *QIndexfType; TcxDBTreeListColumn *tlRaspDetailIndexNameRaspDetail; TBCDField *QIndexCostWithNDS; TcxDBTreeListColumn *tlRaspDetailIndexCostWithNDS; TRzGroupBox *RzGroupBoxMenedger1; TRzToolButton *btClose; TRzToolButton *btGiveIndex; TRzSpacer *RzSpacer8; TRzSpacer *RzSpacer1; TRzToolButton *btDoubleIndex; TRzSpacer *RzSpacer6; TRzGroupBox *RzGroupBox1; TRzEdit *edIndex; TBCDField *QIndexCostWithoutNDS; TcxDBTreeListColumn *tlRaspDetailIndexCostWithoutNDS; TRzSpacer *RzSpacer2; TTimer *TmIndexChange; void __fastcall btCloseClick(TObject *Sender); void __fastcall btGiveIndexClick(TObject *Sender); void __fastcall RzToolButton1Click(TObject *Sender); void __fastcall RzToolButton2Click(TObject *Sender); void __fastcall edIndexChange(TObject *Sender); void __fastcall TmIndexTimer(TObject *Sender); void __fastcall FormKeyDown(TObject *Sender, WORD &Key, TShiftState Shift); void __fastcall btDoubleIndexClick(TObject *Sender); void __fastcall TmIndexChangeTimer(TObject *Sender); void __fastcall DSIndexDataChange(TObject *Sender, TField *Field); private: // User declarations public: // User declarations __fastcall TFrFindRaspDetailComplecIndex(TComponent* Owner); bool fOkButton;//Флаг выбора ПИ для переноса в комплект bool fDoubleButton;//Флаг выбора ПИ для копирования }; //--------------------------------------------------------------------------- extern PACKAGE TFrFindRaspDetailComplecIndex *FrFindRaspDetailComplecIndex; //--------------------------------------------------------------------------- #endif
[ "aushakov@mcrf.ru" ]
aushakov@mcrf.ru
736299226bd6d4ae1e0e3bac3618de462a617823
c8d14e34155119466bdaac18b2756bb683ac4be3
/src/global_min.cpp
384b9fcf1ecea24674d5c996b9c52e2fc97b9b0e
[]
no_license
metod11/November_main_last
f56ceb5cdf9e408303f1cfbe0223af5c0d13d5a8
0db527ea967c5abcee4d3ce05d2e70d257da5f2f
refs/heads/master
2020-09-10T18:17:58.867732
2019-11-14T22:23:30
2019-11-14T22:23:30
221,557,196
0
0
null
null
null
null
UTF-8
C++
false
false
6,749
cpp
#include "global_min.hpp" #include <thread> #include <mutex> // Автор: Козырев Дмитрий std::vector<std::pair<Real, Vector>> calc_f_with_threads(Function f, const std::vector<Vector> & inData) { // Создаем вектор под ответ: std::vector<std::pair<Real, Vector>> outData(inData.size()); // Количество ядер: uint32_t nCores = std::max(1u, std::thread::hardware_concurrency()); // Вектор из тредов: std::vector<std::thread> t; // Мьютексы на чтение и запись: std::mutex inRead, outWrite; uint32_t globalIndex = 0; // Создаем столько тредов, сколько ядер: for (uint32_t i = 0; i < nCores; i++) { t.push_back(std::thread([&] { while (1) { inRead.lock(); uint32_t i = globalIndex; if (globalIndex >= inData.size()) { inRead.unlock(); return; } auto x = inData[i]; globalIndex++; inRead.unlock(); auto res = f(x); outWrite.lock(); outData[i] = {res, x}; outWrite.unlock(); } return; })); } // Присоединяем все треды к материнскому треду, гарантируя то, что все они будут выполнены for (uint32_t i = 0; i < nCores; ++i) { t[i].join(); } assert(globalIndex == inData.size()); return outData; } // Автор: Козырев Дмитрий std::vector<std::pair<Real, Vector>> find_local_mins_with_threads(Function f, const StopCondition& stop_condition, const std::vector<std::pair<Real, Vector>>& inData) { // Создаем вектор под ответ: std::vector<std::pair<Real, Vector>> outData(inData.size()); // Количество ядер: uint32_t nCores = std::max(1u, std::thread::hardware_concurrency()); // Вектор из тредов: std::vector<std::thread> t; // Мьютексы на чтение и запись: std::mutex inRead, outWrite; uint32_t globalIndex = 0; // Создаем столько тредов, сколько ядер: for (uint32_t thread_id = 0; thread_id < nCores; thread_id++) { t.push_back(std::thread([&] { while (1) { inRead.lock(); uint32_t i = globalIndex; if (globalIndex >= inData.size()) { inRead.unlock(); return; } auto it = inData[i]; globalIndex++; inRead.unlock(); // После чтения вызываем методы минимизации: auto iter_data = bfgs(f, it.second, stop_condition); auto x1 = iter_data.x_curr; auto f1 = iter_data.f_curr; iter_data = hessian_free(f, it.second, stop_condition); auto x2 = iter_data.x_curr; auto f2 = iter_data.f_curr; iter_data = nesterov(f, it.second, stop_condition); auto x3 = iter_data.x_curr; auto f3 = iter_data.f_curr; iter_data = dfp(f, it.second, stop_condition); auto x4 = iter_data.x_curr; auto f4 = iter_data.f_curr; iter_data = powell(f, it.second, stop_condition); auto x5 = iter_data.x_curr; auto f5 = iter_data.f_curr; // Записываем ответ: outWrite.lock(); outData[i] = std::min({ it, std::make_pair(f1, x1), std::make_pair(f2, x2), std::make_pair(f3, x3), std::make_pair(f4, x4), std::make_pair(f5, x5) }); outWrite.unlock(); } return; })); } // Присоединяем все треды к материнскому треду, гарантируя то, что все они будут выполнены for (uint32_t i = 0; i < nCores; ++i) { t[i].join(); } assert(globalIndex == inData.size()); return outData; } // Автор: Козырев Дмитрий std::vector<std::pair<Real, Vector>> find_absmin(Function f, const StopCondition& stop_condition, uint32_t dim, uint32_t nBestPoints, uint32_t nAllPoints, Vector min, Vector max) { // Несколько проверок на входные данные: assert(dim > 0u && dim == min.size() && dim == max.size()); assert(nBestPoints <= nAllPoints && nBestPoints > 0u); for (uint32_t i = 0; i < dim; ++i) { assert(min[i] <= max[i]); } // Объект-генератор сетки: SobolSeqGenerator net; net.Init(nAllPoints, dim, "new-joe-kuo-6.21201.txt"); // ----- Первый этап: вычисление значений функции в узлах сетки с отбором точек-кандидатов ----- // Лимит на группу из одновременно обрабатываемых точек: const uint32_t GROUP_SIZE = 1024u; // Формирование списка лучших кандидатов std::set<std::pair<Real, Vector>> candidates; // Сначала складываем точки группами по GROUP_SIZE: std::vector<Vector> group; for (uint32_t i = 0; i < nAllPoints; ++i) { // Получение текущего узла сетки: const auto net_point = net.GeneratePoint().coordinate; // Преобразование узла к точке в ограниченной min и max области: Vector curr(dim); for (uint32_t i = 0; i < dim; ++i) { curr[i] = net_point[i] * (max[i] - min[i]) + min[i]; } if (i == nAllPoints - 1 || group.size() == GROUP_SIZE) { // Запускаем многопоточное вычисление значений во всех точках for (auto& it : calc_f_with_threads(f, group)) { candidates.insert(it); if (candidates.size() > nBestPoints) { candidates.erase(std::prev(candidates.end())); } } group.clear(); } else { group.push_back(curr); } } // ----- Второй этап: запуск алгоритмов поиска локального минимума из выбранных точек ----- // Подготовка (перекладываем точки из set в vector - возможен рост скорости при последовательном размещении в памяти точек): std::vector<std::pair<Real, Vector>> temp; for (auto & it : candidates) { temp.push_back(it); } // Многопоточная обработка кандидатов: auto answer = find_local_mins_with_threads(f, stop_condition, temp); // Итоговая сортировка всех найденных точек по неубыванию значения функции в них: std::sort(answer.begin(), answer.end()); return answer; }
[ "urmud@yandex.ru" ]
urmud@yandex.ru
8f89157e4867d1f81f67c98c7c358952b9661aaa
0b9f3cebf60c7cc606a7c6fac9a4df43bdf2e506
/src/rpcserver.cpp
9e78cd8f22b37d667fc2d3fe9643023d2c6f89b1
[ "MIT" ]
permissive
vitalitycoin/Vitality
a0965d171a8edc91e65e43140d49ccd0d50433d0
28c2e679f84a488560385c2b35a81e4c1da7dab0
refs/heads/master
2020-03-14T14:29:30.883290
2018-04-30T22:54:02
2018-04-30T22:54:02
131,654,684
2
0
null
null
null
null
UTF-8
C++
false
false
40,877
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2017-2018 The Vitality developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpcserver.h" #include "base58.h" #include "init.h" #include "main.h" #include "ui_interface.h" #include "util.h" #ifdef ENABLE_WALLET #include "wallet.h" #endif #include "json/json_spirit_writer_template.h" #include <boost/algorithm/string.hpp> #include <boost/asio.hpp> #include <boost/asio/ssl.hpp> #include <boost/bind.hpp> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/iostreams/concepts.hpp> #include <boost/iostreams/stream.hpp> #include <boost/shared_ptr.hpp> #include <boost/thread.hpp> using namespace boost; using namespace boost::asio; using namespace json_spirit; using namespace std; static std::string strRPCUserColonPass; static bool fRPCRunning = false; static bool fRPCInWarmup = true; static std::string rpcWarmupStatus("RPC server started"); static CCriticalSection cs_rpcWarmup; //! These are created by StartRPCThreads, destroyed in StopRPCThreads static asio::io_service* rpc_io_service = NULL; static map<string, boost::shared_ptr<deadline_timer> > deadlineTimers; static ssl::context* rpc_ssl_context = NULL; static boost::thread_group* rpc_worker_group = NULL; static boost::asio::io_service::work* rpc_dummy_work = NULL; static std::vector<CSubNet> rpc_allow_subnets; //!< List of subnets to allow RPC connections from static std::vector<boost::shared_ptr<ip::tcp::acceptor> > rpc_acceptors; void RPCTypeCheck(const Array& params, const list<Value_type>& typesExpected, bool fAllowNull) { unsigned int i = 0; BOOST_FOREACH (Value_type t, typesExpected) { if (params.size() <= i) break; const Value& v = params[i]; if (!((v.type() == t) || (fAllowNull && (v.type() == null_type)))) { string err = strprintf("Expected type %s, got %s", Value_type_name[t], Value_type_name[v.type()]); throw JSONRPCError(RPC_TYPE_ERROR, err); } i++; } } void RPCTypeCheck(const Object& o, const map<string, Value_type>& typesExpected, bool fAllowNull) { BOOST_FOREACH (const PAIRTYPE(string, Value_type) & t, typesExpected) { const Value& v = find_value(o, t.first); if (!fAllowNull && v.type() == null_type) throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first)); if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type)))) { string err = strprintf("Expected type %s for %s, got %s", Value_type_name[t.second], t.first, Value_type_name[v.type()]); throw JSONRPCError(RPC_TYPE_ERROR, err); } } } static inline int64_t roundint64(double d) { return (int64_t)(d > 0 ? d + 0.5 : d - 0.5); } CAmount AmountFromValue(const Value& value) { double dAmount = value.get_real(); if (dAmount <= 0.0 || dAmount > 100000000.0) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); CAmount nAmount = roundint64(dAmount * COIN); if (!MoneyRange(nAmount)) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); return nAmount; } Value ValueFromAmount(const CAmount& amount) { return (double)amount / (double)COIN; } uint256 ParseHashV(const Value& v, string strName) { string strHex; if (v.type() == str_type) strHex = v.get_str(); if (!IsHex(strHex)) // Note: IsHex("") is false throw JSONRPCError(RPC_INVALID_PARAMETER, strName + " must be hexadecimal string (not '" + strHex + "')"); uint256 result; result.SetHex(strHex); return result; } uint256 ParseHashO(const Object& o, string strKey) { return ParseHashV(find_value(o, strKey), strKey); } vector<unsigned char> ParseHexV(const Value& v, string strName) { string strHex; if (v.type() == str_type) strHex = v.get_str(); if (!IsHex(strHex)) throw JSONRPCError(RPC_INVALID_PARAMETER, strName + " must be hexadecimal string (not '" + strHex + "')"); return ParseHex(strHex); } vector<unsigned char> ParseHexO(const Object& o, string strKey) { return ParseHexV(find_value(o, strKey), strKey); } /** * Note: This interface may still be subject to change. */ string CRPCTable::help(string strCommand) const { string strRet; string category; set<rpcfn_type> setDone; vector<pair<string, const CRPCCommand*> > vCommands; for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi) vCommands.push_back(make_pair(mi->second->category + mi->first, mi->second)); sort(vCommands.begin(), vCommands.end()); BOOST_FOREACH (const PAIRTYPE(string, const CRPCCommand*) & command, vCommands) { const CRPCCommand* pcmd = command.second; string strMethod = pcmd->name; // We already filter duplicates, but these deprecated screw up the sort order if (strMethod.find("label") != string::npos) continue; if ((strCommand != "" || pcmd->category == "hidden") && strMethod != strCommand) continue; #ifdef ENABLE_WALLET if (pcmd->reqWallet && !pwalletMain) continue; #endif try { Array params; rpcfn_type pfn = pcmd->actor; if (setDone.insert(pfn).second) (*pfn)(params, true); } catch (std::exception& e) { // Help text is returned in an exception string strHelp = string(e.what()); if (strCommand == "") { if (strHelp.find('\n') != string::npos) strHelp = strHelp.substr(0, strHelp.find('\n')); if (category != pcmd->category) { if (!category.empty()) strRet += "\n"; category = pcmd->category; string firstLetter = category.substr(0, 1); boost::to_upper(firstLetter); strRet += "== " + firstLetter + category.substr(1) + " ==\n"; } } strRet += strHelp + "\n"; } } if (strRet == "") strRet = strprintf("help: unknown command: %s\n", strCommand); strRet = strRet.substr(0, strRet.size() - 1); return strRet; } Value help(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "help ( \"command\" )\n" "\nList all commands, or get help for a specified command.\n" "\nArguments:\n" "1. \"command\" (string, optional) The command to get help on\n" "\nResult:\n" "\"text\" (string) The help text\n"); string strCommand; if (params.size() > 0) strCommand = params[0].get_str(); return tableRPC.help(strCommand); } Value stop(const Array& params, bool fHelp) { // Accept the deprecated and ignored 'detach' boolean argument if (fHelp || params.size() > 1) throw runtime_error( "stop\n" "\nStop Vitality server."); // Shutdown will take long enough that the response should get back StartShutdown(); return "Vitality server stopping"; } /** * Call Table */ static const CRPCCommand vRPCCommands[] = { // category name actor (function) okSafeMode threadSafe reqWallet // --------------------- ------------------------ ----------------------- ---------- ---------- --------- /* Overall control/query calls */ {"control", "getinfo", &getinfo, true, false, false}, /* uses wallet if enabled */ {"control", "help", &help, true, true, false}, {"control", "stop", &stop, true, true, false}, /* P2P networking */ {"network", "getnetworkinfo", &getnetworkinfo, true, false, false}, {"network", "addnode", &addnode, true, true, false}, {"network", "getaddednodeinfo", &getaddednodeinfo, true, true, false}, {"network", "getconnectioncount", &getconnectioncount, true, false, false}, {"network", "getnettotals", &getnettotals, true, true, false}, {"network", "getpeerinfo", &getpeerinfo, true, false, false}, {"network", "ping", &ping, true, false, false}, /* Block chain and UTXO */ {"blockchain", "getblockchaininfo", &getblockchaininfo, true, false, false}, {"blockchain", "getbestblockhash", &getbestblockhash, true, false, false}, {"blockchain", "getblockcount", &getblockcount, true, false, false}, {"blockchain", "getblock", &getblock, true, false, false}, {"blockchain", "getblockhash", &getblockhash, true, false, false}, {"blockchain", "getblockheader", &getblockheader, false, false, false}, {"blockchain", "getchaintips", &getchaintips, true, false, false}, {"blockchain", "getdifficulty", &getdifficulty, true, false, false}, {"blockchain", "getmempoolinfo", &getmempoolinfo, true, true, false}, {"blockchain", "getrawmempool", &getrawmempool, true, false, false}, {"blockchain", "gettxout", &gettxout, true, false, false}, {"blockchain", "gettxoutsetinfo", &gettxoutsetinfo, true, false, false}, {"blockchain", "verifychain", &verifychain, true, false, false}, {"blockchain", "invalidateblock", &invalidateblock, true, true, false}, {"blockchain", "reconsiderblock", &reconsiderblock, true, true, false}, /* Mining */ {"mining", "getblocktemplate", &getblocktemplate, true, false, false}, {"mining", "getmininginfo", &getmininginfo, true, false, false}, {"mining", "getnetworkhashps", &getnetworkhashps, true, false, false}, {"mining", "prioritisetransaction", &prioritisetransaction, true, false, false}, {"mining", "submitblock", &submitblock, true, true, false}, {"mining", "reservebalance", &reservebalance, true, true, false}, #ifdef ENABLE_WALLET /* Coin generation */ {"generating", "getgenerate", &getgenerate, true, false, false}, {"generating", "gethashespersec", &gethashespersec, true, false, false}, {"generating", "setgenerate", &setgenerate, true, true, false}, #endif /* Raw transactions */ {"rawtransactions", "createrawtransaction", &createrawtransaction, true, false, false}, {"rawtransactions", "decoderawtransaction", &decoderawtransaction, true, false, false}, {"rawtransactions", "decodescript", &decodescript, true, false, false}, {"rawtransactions", "getrawtransaction", &getrawtransaction, true, false, false}, {"rawtransactions", "sendrawtransaction", &sendrawtransaction, false, false, false}, {"rawtransactions", "signrawtransaction", &signrawtransaction, false, false, false}, /* uses wallet if enabled */ /* Utility functions */ {"util", "createmultisig", &createmultisig, true, true, false}, {"util", "validateaddress", &validateaddress, true, false, false}, /* uses wallet if enabled */ {"util", "verifymessage", &verifymessage, true, false, false}, {"util", "estimatefee", &estimatefee, true, true, false}, {"util", "estimatepriority", &estimatepriority, true, true, false}, /* Not shown in help */ {"hidden", "invalidateblock", &invalidateblock, true, true, false}, {"hidden", "reconsiderblock", &reconsiderblock, true, true, false}, {"hidden", "setmocktime", &setmocktime, true, false, false}, /* Vitality features */ {"Vitality", "masternode", &masternode, true, true, false}, {"Vitality", "masternodelist", &masternodelist, true, true, false}, {"Vitality", "mnbudget", &mnbudget, true, true, false}, {"Vitality", "mnbudgetvoteraw", &mnbudgetvoteraw, true, true, false}, {"Vitality", "mnfinalbudget", &mnfinalbudget, true, true, false}, {"Vitality", "mnsync", &mnsync, true, true, false}, {"Vitality", "spork", &spork, true, true, false}, #ifdef ENABLE_WALLET {"Vitality", "obfuscation", &obfuscation, false, false, true}, /* not threadSafe because of SendMoney */ /* Wallet */ {"wallet", "addmultisigaddress", &addmultisigaddress, true, false, true}, {"wallet", "autocombinerewards", &autocombinerewards, false, false, true}, {"wallet", "backupwallet", &backupwallet, true, false, true}, {"wallet", "dumpprivkey", &dumpprivkey, true, false, true}, {"wallet", "dumpwallet", &dumpwallet, true, false, true}, {"wallet", "bip38encrypt", &bip38encrypt, true, false, true}, {"wallet", "bip38decrypt", &bip38decrypt, true, false, true}, {"wallet", "encryptwallet", &encryptwallet, true, false, true}, {"wallet", "getaccountaddress", &getaccountaddress, true, false, true}, {"wallet", "getaccount", &getaccount, true, false, true}, {"wallet", "getaddressesbyaccount", &getaddressesbyaccount, true, false, true}, {"wallet", "getbalance", &getbalance, false, false, true}, {"wallet", "getnewaddress", &getnewaddress, true, false, true}, {"wallet", "getrawchangeaddress", &getrawchangeaddress, true, false, true}, {"wallet", "getreceivedbyaccount", &getreceivedbyaccount, false, false, true}, {"wallet", "getreceivedbyaddress", &getreceivedbyaddress, false, false, true}, {"wallet", "getstakingstatus", &getstakingstatus, false, false, true}, {"wallet", "getstakesplitthreshold", &getstakesplitthreshold, false, false, true}, {"wallet", "gettransaction", &gettransaction, false, false, true}, {"wallet", "getunconfirmedbalance", &getunconfirmedbalance, false, false, true}, {"wallet", "getwalletinfo", &getwalletinfo, false, false, true}, {"wallet", "importprivkey", &importprivkey, true, false, true}, {"wallet", "importwallet", &importwallet, true, false, true}, {"wallet", "importaddress", &importaddress, true, false, true}, {"wallet", "keypoolrefill", &keypoolrefill, true, false, true}, {"wallet", "listaccounts", &listaccounts, false, false, true}, {"wallet", "listaddressgroupings", &listaddressgroupings, false, false, true}, {"wallet", "listlockunspent", &listlockunspent, false, false, true}, {"wallet", "listreceivedbyaccount", &listreceivedbyaccount, false, false, true}, {"wallet", "listreceivedbyaddress", &listreceivedbyaddress, false, false, true}, {"wallet", "listsinceblock", &listsinceblock, false, false, true}, {"wallet", "listtransactions", &listtransactions, false, false, true}, {"wallet", "listunspent", &listunspent, false, false, true}, {"wallet", "lockunspent", &lockunspent, true, false, true}, {"wallet", "move", &movecmd, false, false, true}, {"wallet", "multisend", &multisend, false, false, true}, {"wallet", "sendfrom", &sendfrom, false, false, true}, {"wallet", "sendmany", &sendmany, false, false, true}, {"wallet", "sendtoaddress", &sendtoaddress, false, false, true}, {"wallet", "sendtoaddressix", &sendtoaddressix, false, false, true}, {"wallet", "setaccount", &setaccount, true, false, true}, {"wallet", "setstakesplitthreshold", &setstakesplitthreshold, false, false, true}, {"wallet", "settxfee", &settxfee, true, false, true}, {"wallet", "signmessage", &signmessage, true, false, true}, {"wallet", "walletlock", &walletlock, true, false, true}, {"wallet", "walletpassphrasechange", &walletpassphrasechange, true, false, true}, {"wallet", "walletpassphrase", &walletpassphrase, true, false, true}, #endif // ENABLE_WALLET }; CRPCTable::CRPCTable() { unsigned int vcidx; for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++) { const CRPCCommand* pcmd; pcmd = &vRPCCommands[vcidx]; mapCommands[pcmd->name] = pcmd; } } const CRPCCommand* CRPCTable::operator[](string name) const { map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name); if (it == mapCommands.end()) return NULL; return (*it).second; } bool HTTPAuthorized(map<string, string>& mapHeaders) { string strAuth = mapHeaders["authorization"]; if (strAuth.substr(0, 6) != "Basic ") return false; string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64); string strUserPass = DecodeBase64(strUserPass64); return TimingResistantEqual(strUserPass, strRPCUserColonPass); } void ErrorReply(std::ostream& stream, const Object& objError, const Value& id) { // Send error reply from json-rpc error object int nStatus = HTTP_INTERNAL_SERVER_ERROR; int code = find_value(objError, "code").get_int(); if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST; else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND; string strReply = JSONRPCReply(Value::null, objError, id); stream << HTTPReply(nStatus, strReply, false) << std::flush; } CNetAddr BoostAsioToCNetAddr(boost::asio::ip::address address) { CNetAddr netaddr; // Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses if (address.is_v6() && (address.to_v6().is_v4_compatible() || address.to_v6().is_v4_mapped())) address = address.to_v6().to_v4(); if (address.is_v4()) { boost::asio::ip::address_v4::bytes_type bytes = address.to_v4().to_bytes(); netaddr.SetRaw(NET_IPV4, &bytes[0]); } else { boost::asio::ip::address_v6::bytes_type bytes = address.to_v6().to_bytes(); netaddr.SetRaw(NET_IPV6, &bytes[0]); } return netaddr; } bool ClientAllowed(const boost::asio::ip::address& address) { CNetAddr netaddr = BoostAsioToCNetAddr(address); BOOST_FOREACH (const CSubNet& subnet, rpc_allow_subnets) if (subnet.Match(netaddr)) return true; return false; } template <typename Protocol> class AcceptedConnectionImpl : public AcceptedConnection { public: AcceptedConnectionImpl( asio::io_service& io_service, ssl::context& context, bool fUseSSL) : sslStream(io_service, context), _d(sslStream, fUseSSL), _stream(_d) { } virtual std::iostream& stream() { return _stream; } virtual std::string peer_address_to_string() const { return peer.address().to_string(); } virtual void close() { _stream.close(); } typename Protocol::endpoint peer; asio::ssl::stream<typename Protocol::socket> sslStream; private: SSLIOStreamDevice<Protocol> _d; iostreams::stream<SSLIOStreamDevice<Protocol> > _stream; }; void ServiceConnection(AcceptedConnection* conn); //! Forward declaration required for RPCListen template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr<basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, bool fUseSSL, boost::shared_ptr<AcceptedConnection> conn, const boost::system::error_code& error); /** * Sets up I/O resources to accept and handle a new connection. */ template <typename Protocol, typename SocketAcceptorService> static void RPCListen(boost::shared_ptr<basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, const bool fUseSSL) { // Accept connection boost::shared_ptr<AcceptedConnectionImpl<Protocol> > conn(new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL)); acceptor->async_accept( conn->sslStream.lowest_layer(), conn->peer, boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>, acceptor, boost::ref(context), fUseSSL, conn, _1)); } /** * Accept and handle incoming connection. */ template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr<basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, const bool fUseSSL, boost::shared_ptr<AcceptedConnection> conn, const boost::system::error_code& error) { // Immediately start accepting new connections, except when we're cancelled or our socket is closed. if (error != asio::error::operation_aborted && acceptor->is_open()) RPCListen(acceptor, context, fUseSSL); AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast<AcceptedConnectionImpl<ip::tcp>*>(conn.get()); if (error) { // TODO: Actually handle errors LogPrintf("%s: Error: %s\n", __func__, error.message()); } // Restrict callers by IP. It is important to // do this before starting client thread, to filter out // certain DoS and misbehaving clients. else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address())) { // Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake. if (!fUseSSL) conn->stream() << HTTPError(HTTP_FORBIDDEN, false) << std::flush; conn->close(); } else { ServiceConnection(conn.get()); conn->close(); } } static ip::tcp::endpoint ParseEndpoint(const std::string& strEndpoint, int defaultPort) { std::string addr; int port = defaultPort; SplitHostPort(strEndpoint, port, addr); return ip::tcp::endpoint(asio::ip::address::from_string(addr), port); } void StartRPCThreads() { rpc_allow_subnets.clear(); rpc_allow_subnets.push_back(CSubNet("127.0.0.0/8")); // always allow IPv4 local subnet rpc_allow_subnets.push_back(CSubNet("::1")); // always allow IPv6 localhost if (mapMultiArgs.count("-rpcallowip")) { const vector<string>& vAllow = mapMultiArgs["-rpcallowip"]; BOOST_FOREACH (string strAllow, vAllow) { CSubNet subnet(strAllow); if (!subnet.IsValid()) { uiInterface.ThreadSafeMessageBox( strprintf("Invalid -rpcallowip subnet specification: %s. Valid are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24).", strAllow), "", CClientUIInterface::MSG_ERROR); StartShutdown(); return; } rpc_allow_subnets.push_back(subnet); } } std::string strAllowed; BOOST_FOREACH (const CSubNet& subnet, rpc_allow_subnets) strAllowed += subnet.ToString() + " "; LogPrint("rpc", "Allowing RPC connections from: %s\n", strAllowed); strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]; if (((mapArgs["-rpcpassword"] == "") || (mapArgs["-rpcuser"] == mapArgs["-rpcpassword"])) && Params().RequireRPCPassword()) { unsigned char rand_pwd[32]; GetRandBytes(rand_pwd, 32); uiInterface.ThreadSafeMessageBox(strprintf( _("To use Vitalityd, or the -server option to Vitality-qt, you must set an rpcpassword in the configuration file:\n" "%s\n" "It is recommended you use the following random password:\n" "rpcuser=Vitalityrpc\n" "rpcpassword=%s\n" "(you do not need to remember this password)\n" "The username and password MUST NOT be the same.\n" "If the file does not exist, create it with owner-readable-only file permissions.\n" "It is also recommended to set alertnotify so you are notified of problems;\n" "for example: alertnotify=echo %%s | mail -s \"Vitality Alert\" admin@foo.com\n"), GetConfigFile().string(), EncodeBase58(&rand_pwd[0], &rand_pwd[0] + 32)), "", CClientUIInterface::MSG_ERROR | CClientUIInterface::SECURE); StartShutdown(); return; } assert(rpc_io_service == NULL); rpc_io_service = new asio::io_service(); rpc_ssl_context = new ssl::context(*rpc_io_service, ssl::context::sslv23); const bool fUseSSL = GetBoolArg("-rpcssl", false); if (fUseSSL) { rpc_ssl_context->set_options(ssl::context::no_sslv2 | ssl::context::no_sslv3); filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert")); if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile; if (filesystem::exists(pathCertFile)) rpc_ssl_context->use_certificate_chain_file(pathCertFile.string()); else LogPrintf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string()); filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem")); if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile; if (filesystem::exists(pathPKFile)) rpc_ssl_context->use_private_key_file(pathPKFile.string(), ssl::context::pem); else LogPrintf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string()); string strCiphers = GetArg("-rpcsslciphers", "TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH"); SSL_CTX_set_cipher_list(rpc_ssl_context->impl(), strCiphers.c_str()); } std::vector<ip::tcp::endpoint> vEndpoints; bool bBindAny = false; int defaultPort = GetArg("-rpcport", BaseParams().RPCPort()); if (!mapArgs.count("-rpcallowip")) // Default to loopback if not allowing external IPs { vEndpoints.push_back(ip::tcp::endpoint(asio::ip::address_v6::loopback(), defaultPort)); vEndpoints.push_back(ip::tcp::endpoint(asio::ip::address_v4::loopback(), defaultPort)); if (mapArgs.count("-rpcbind")) { LogPrintf("WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n"); } } else if (mapArgs.count("-rpcbind")) // Specific bind address { BOOST_FOREACH (const std::string& addr, mapMultiArgs["-rpcbind"]) { try { vEndpoints.push_back(ParseEndpoint(addr, defaultPort)); } catch (const boost::system::system_error&) { uiInterface.ThreadSafeMessageBox( strprintf(_("Could not parse -rpcbind value %s as network address"), addr), "", CClientUIInterface::MSG_ERROR); StartShutdown(); return; } } } else { // No specific bind address specified, bind to any vEndpoints.push_back(ip::tcp::endpoint(asio::ip::address_v6::any(), defaultPort)); vEndpoints.push_back(ip::tcp::endpoint(asio::ip::address_v4::any(), defaultPort)); // Prefer making the socket dual IPv6/IPv4 instead of binding // to both addresses seperately. bBindAny = true; } bool fListening = false; std::string strerr; std::string straddress; BOOST_FOREACH (const ip::tcp::endpoint& endpoint, vEndpoints) { try { asio::ip::address bindAddress = endpoint.address(); straddress = bindAddress.to_string(); LogPrintf("Binding RPC on address %s port %i (IPv4+IPv6 bind any: %i)\n", straddress, endpoint.port(), bBindAny); boost::system::error_code v6_only_error; boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(*rpc_io_service)); acceptor->open(endpoint.protocol()); acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); // Try making the socket dual IPv6/IPv4 when listening on the IPv6 "any" address acceptor->set_option(boost::asio::ip::v6_only( !bBindAny || bindAddress != asio::ip::address_v6::any()), v6_only_error); acceptor->bind(endpoint); acceptor->listen(socket_base::max_connections); RPCListen(acceptor, *rpc_ssl_context, fUseSSL); rpc_acceptors.push_back(acceptor); fListening = true; rpc_acceptors.push_back(acceptor); // If dual IPv6/IPv4 bind successful, skip binding to IPv4 separately if (bBindAny && bindAddress == asio::ip::address_v6::any() && !v6_only_error) break; } catch (boost::system::system_error& e) { LogPrintf("ERROR: Binding RPC on address %s port %i failed: %s\n", straddress, endpoint.port(), e.what()); strerr = strprintf(_("An error occurred while setting up the RPC address %s port %u for listening: %s"), straddress, endpoint.port(), e.what()); } } if (!fListening) { uiInterface.ThreadSafeMessageBox(strerr, "", CClientUIInterface::MSG_ERROR); StartShutdown(); return; } rpc_worker_group = new boost::thread_group(); for (int i = 0; i < GetArg("-rpcthreads", 4); i++) rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service)); fRPCRunning = true; } void StartDummyRPCThread() { if (rpc_io_service == NULL) { rpc_io_service = new asio::io_service(); /* Create dummy "work" to keep the thread from exiting when no timeouts active, * see http://www.boost.org/doc/libs/1_51_0/doc/html/boost_asio/reference/io_service.html#boost_asio.reference.io_service.stopping_the_io_service_from_running_out_of_work */ rpc_dummy_work = new asio::io_service::work(*rpc_io_service); rpc_worker_group = new boost::thread_group(); rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service)); fRPCRunning = true; } } void StopRPCThreads() { if (rpc_io_service == NULL) return; // Set this to false first, so that longpolling loops will exit when woken up fRPCRunning = false; // First, cancel all timers and acceptors // This is not done automatically by ->stop(), and in some cases the destructor of // asio::io_service can hang if this is skipped. boost::system::error_code ec; BOOST_FOREACH (const boost::shared_ptr<ip::tcp::acceptor>& acceptor, rpc_acceptors) { acceptor->cancel(ec); if (ec) LogPrintf("%s: Warning: %s when cancelling acceptor", __func__, ec.message()); } rpc_acceptors.clear(); BOOST_FOREACH (const PAIRTYPE(std::string, boost::shared_ptr<deadline_timer>) & timer, deadlineTimers) { timer.second->cancel(ec); if (ec) LogPrintf("%s: Warning: %s when cancelling timer", __func__, ec.message()); } deadlineTimers.clear(); rpc_io_service->stop(); cvBlockChange.notify_all(); if (rpc_worker_group != NULL) rpc_worker_group->join_all(); delete rpc_dummy_work; rpc_dummy_work = NULL; delete rpc_worker_group; rpc_worker_group = NULL; delete rpc_ssl_context; rpc_ssl_context = NULL; delete rpc_io_service; rpc_io_service = NULL; } bool IsRPCRunning() { return fRPCRunning; } void SetRPCWarmupStatus(const std::string& newStatus) { LOCK(cs_rpcWarmup); rpcWarmupStatus = newStatus; } void SetRPCWarmupFinished() { LOCK(cs_rpcWarmup); assert(fRPCInWarmup); fRPCInWarmup = false; } bool RPCIsInWarmup(std::string* outStatus) { LOCK(cs_rpcWarmup); if (outStatus) *outStatus = rpcWarmupStatus; return fRPCInWarmup; } void RPCRunHandler(const boost::system::error_code& err, boost::function<void(void)> func) { if (!err) func(); } void RPCRunLater(const std::string& name, boost::function<void(void)> func, int64_t nSeconds) { assert(rpc_io_service != NULL); if (deadlineTimers.count(name) == 0) { deadlineTimers.insert(make_pair(name, boost::shared_ptr<deadline_timer>(new deadline_timer(*rpc_io_service)))); } deadlineTimers[name]->expires_from_now(posix_time::seconds(nSeconds)); deadlineTimers[name]->async_wait(boost::bind(RPCRunHandler, _1, func)); } class JSONRequest { public: Value id; string strMethod; Array params; JSONRequest() { id = Value::null; } void parse(const Value& valRequest); }; void JSONRequest::parse(const Value& valRequest) { // Parse request if (valRequest.type() != obj_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object"); const Object& request = valRequest.get_obj(); // Parse id now so errors from here on will have the id id = find_value(request, "id"); // Parse method Value valMethod = find_value(request, "method"); if (valMethod.type() == null_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method"); if (valMethod.type() != str_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string"); strMethod = valMethod.get_str(); if (strMethod != "getblocktemplate") LogPrint("rpc", "ThreadRPCServer method=%s\n", SanitizeString(strMethod)); // Parse params Value valParams = find_value(request, "params"); if (valParams.type() == array_type) params = valParams.get_array(); else if (valParams.type() == null_type) params = Array(); else throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array"); } static Object JSONRPCExecOne(const Value& req) { Object rpc_result; JSONRequest jreq; try { jreq.parse(req); Value result = tableRPC.execute(jreq.strMethod, jreq.params); rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id); } catch (Object& objError) { rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id); } catch (std::exception& e) { rpc_result = JSONRPCReplyObj(Value::null, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id); } return rpc_result; } static string JSONRPCExecBatch(const Array& vReq) { Array ret; for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++) ret.push_back(JSONRPCExecOne(vReq[reqIdx])); return write_string(Value(ret), false) + "\n"; } static bool HTTPReq_JSONRPC(AcceptedConnection* conn, string& strRequest, map<string, string>& mapHeaders, bool fRun) { // Check authorization if (mapHeaders.count("authorization") == 0) { conn->stream() << HTTPError(HTTP_UNAUTHORIZED, false) << std::flush; return false; } if (!HTTPAuthorized(mapHeaders)) { LogPrintf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string()); /* Deter brute-forcing If this results in a DoS the user really shouldn't have their RPC port exposed. */ MilliSleep(250); conn->stream() << HTTPError(HTTP_UNAUTHORIZED, false) << std::flush; return false; } JSONRequest jreq; try { // Parse request Value valRequest; if (!read_string(strRequest, valRequest)) throw JSONRPCError(RPC_PARSE_ERROR, "Parse error"); // Return immediately if in warmup { LOCK(cs_rpcWarmup); if (fRPCInWarmup) throw JSONRPCError(RPC_IN_WARMUP, rpcWarmupStatus); } string strReply; // singleton request if (valRequest.type() == obj_type) { jreq.parse(valRequest); Value result = tableRPC.execute(jreq.strMethod, jreq.params); // Send reply strReply = JSONRPCReply(result, Value::null, jreq.id); // array of requests } else if (valRequest.type() == array_type) strReply = JSONRPCExecBatch(valRequest.get_array()); else throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error"); conn->stream() << HTTPReplyHeader(HTTP_OK, fRun, strReply.size()) << strReply << std::flush; } catch (Object& objError) { ErrorReply(conn->stream(), objError, jreq.id); return false; } catch (std::exception& e) { ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id); return false; } return true; } void ServiceConnection(AcceptedConnection* conn) { bool fRun = true; while (fRun && !ShutdownRequested()) { int nProto = 0; map<string, string> mapHeaders; string strRequest, strMethod, strURI; // Read HTTP request line if (!ReadHTTPRequestLine(conn->stream(), nProto, strMethod, strURI)) break; // Read HTTP message headers and body ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto, MAX_SIZE); // HTTP Keep-Alive is false; close connection immediately if ((mapHeaders["connection"] == "close") || (!GetBoolArg("-rpckeepalive", true))) fRun = false; // Process via JSON-RPC API if (strURI == "/") { if (!HTTPReq_JSONRPC(conn, strRequest, mapHeaders, fRun)) break; // Process via HTTP REST API } else if (strURI.substr(0, 6) == "/rest/" && GetBoolArg("-rest", false)) { if (!HTTPReq_REST(conn, strURI, mapHeaders, fRun)) break; } else { conn->stream() << HTTPError(HTTP_NOT_FOUND, false) << std::flush; break; } } } json_spirit::Value CRPCTable::execute(const std::string& strMethod, const json_spirit::Array& params) const { // Find method const CRPCCommand* pcmd = tableRPC[strMethod]; if (!pcmd) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found"); #ifdef ENABLE_WALLET if (pcmd->reqWallet && !pwalletMain) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)"); #endif // Observe safe mode string strWarning = GetWarnings("rpc"); if (strWarning != "" && !GetBoolArg("-disablesafemode", false) && !pcmd->okSafeMode) throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning); try { // Execute Value result; { if (pcmd->threadSafe) result = pcmd->actor(params, false); #ifdef ENABLE_WALLET else if (!pwalletMain) { LOCK(cs_main); result = pcmd->actor(params, false); } else { while (true) { TRY_LOCK(cs_main, lockMain); if (!lockMain) { MilliSleep(50); continue; } while (true) { TRY_LOCK(pwalletMain->cs_wallet, lockWallet); if (!lockMain) { MilliSleep(50); continue; } result = pcmd->actor(params, false); break; } break; } } #else // ENABLE_WALLET else { LOCK(cs_main); result = pcmd->actor(params, false); } #endif // !ENABLE_WALLET } return result; } catch (std::exception& e) { throw JSONRPCError(RPC_MISC_ERROR, e.what()); } } std::vector<std::string> CRPCTable::listCommands() const { std::vector<std::string> commandList; typedef std::map<std::string, const CRPCCommand*> commandMap; std::transform( mapCommands.begin(), mapCommands.end(), std::back_inserter(commandList), boost::bind(&commandMap::value_type::first,_1) ); return commandList; } std::string HelpExampleCli(string methodname, string args) { return "> Vitality-cli " + methodname + " " + args + "\n"; } std::string HelpExampleRpc(string methodname, string args) { return "> curl --user myusername --data-binary '{\"jsonrpc\": \"1.0\", \"id\":\"curltest\", " "\"method\": \"" + methodname + "\", \"params\": [" + args + "] }' -H 'content-type: text/plain;' http://127.0.0.1:15414/\n"; } const CRPCTable tableRPC;
[ "38859629+vitalitycoin@users.noreply.github.com" ]
38859629+vitalitycoin@users.noreply.github.com
2110376604735676904a0a83851820197d73ecca
5b5f0ed802cace2076b67badc1add111e421ede2
/SW역량테스트/day2/backjoon13414/backjoon13414/main.cpp
f57e81c76e50f849d0aafca556d6c92124a9e990
[]
no_license
opp0615/Algorithm
b45474be89792d9ea2a3e17eb52ed45507cc50c9
a94fa1637f3ea1504a49ea87e819f78a3e713571
refs/heads/master
2020-03-15T02:53:17.575538
2019-05-23T12:37:12
2019-05-23T12:37:12
131,928,812
0
0
null
null
null
null
UHC
C++
false
false
801
cpp
#include <iostream> #include <map> #include <string> #include<vector> #include<algorithm> using namespace std; int main() { int K = 0; int L = 0; cin >> L >> K; map<string, int> m; vector<pair<int, string>> result; for (int i = 0; i < K; i++) { string studentnubmer; cin >> studentnubmer; m[studentnubmer] = i; } for (map<string, int>::iterator iter = m.begin(); iter != m.end(); iter++) { //cout << iter->first << ", " << iter->second << endl; result.push_back(make_pair(iter->second, iter->first)); } //정렬 sort(result.begin(), result.end()); int count = 0; for (vector<pair<int, string>>::iterator iter = result.begin(); iter != result.end(); iter++) { //L번째 까지 출력 if (count >= L) break; cout << iter->second << endl; count++; } }
[ "opp0615@naver.com" ]
opp0615@naver.com
e91f3f790e2e159e1c1200c158722dfce0c917f1
88ae8695987ada722184307301e221e1ba3cc2fa
/components/bookmarks/managed/managed_bookmark_service.h
919e55f1567223d66b54a8d37834aebc63c25e14
[ "BSD-3-Clause" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
3,475
h
// Copyright 2015 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_BOOKMARKS_MANAGED_MANAGED_BOOKMARK_SERVICE_H_ #define COMPONENTS_BOOKMARKS_MANAGED_MANAGED_BOOKMARK_SERVICE_H_ #include <memory> #include <string> #include "base/functional/callback_forward.h" #include "base/memory/raw_ptr.h" #include "components/bookmarks/browser/base_bookmark_model_observer.h" #include "components/bookmarks/browser/bookmark_client.h" #include "components/bookmarks/browser/bookmark_node.h" #include "components/keyed_service/core/keyed_service.h" class PrefService; namespace bookmarks { class BookmarkModel; class ManagedBookmarksTracker; // ManagedBookmarkService manages the bookmark folder controlled by enterprise // policy. class ManagedBookmarkService : public KeyedService, public BaseBookmarkModelObserver { public: using GetManagementDomainCallback = base::RepeatingCallback<std::string()>; ManagedBookmarkService(PrefService* prefs, GetManagementDomainCallback callback); ManagedBookmarkService(const ManagedBookmarkService&) = delete; ManagedBookmarkService& operator=(const ManagedBookmarkService&) = delete; ~ManagedBookmarkService() override; // Called upon creation of the BookmarkModel. void BookmarkModelCreated(BookmarkModel* bookmark_model); // Returns a task that will be used to load a managed root node. This task // will be invoked in the Profile's IO task runner. LoadManagedNodeCallback GetLoadManagedNodeCallback(); // Returns true if the |node| can have its title updated. bool CanSetPermanentNodeTitle(const BookmarkNode* node); // Returns true if |node| should sync. bool CanSyncNode(const BookmarkNode* node); // Returns true if |node| can be edited by the user. // TODO(joaodasilva): the model should check this more aggressively, and // should give the client a means to temporarily disable those checks. // http://crbug.com/49598 bool CanBeEditedByUser(const BookmarkNode* node); // Top-level managed bookmarks folder, defined by an enterprise policy; may be // null. const BookmarkNode* managed_node() { return managed_node_; } private: // KeyedService implementation. void Shutdown() override; // BaseBookmarkModelObserver implementation. void BookmarkModelChanged() override; // BookmarkModelObserver implementation. void BookmarkModelLoaded(BookmarkModel* bookmark_model, bool ids_reassigned) override; void BookmarkModelBeingDeleted(BookmarkModel* bookmark_model) override; // Cleanup, called when service is shutdown or when BookmarkModel is being // destroyed. void Cleanup(); // Pointer to the PrefService. Must outlive ManagedBookmarkService. raw_ptr<PrefService> prefs_; // Pointer to the BookmarkModel; may be null. Only valid between the calls to // BookmarkModelCreated() and to BookmarkModelBeingDestroyed(). raw_ptr<BookmarkModel> bookmark_model_; // Managed bookmarks are defined by an enterprise policy. The lifetime of the // BookmarkPermanentNode is controlled by BookmarkModel. std::unique_ptr<ManagedBookmarksTracker> managed_bookmarks_tracker_; GetManagementDomainCallback managed_domain_callback_; raw_ptr<BookmarkPermanentNode> managed_node_; }; } // namespace bookmarks #endif // COMPONENTS_BOOKMARKS_MANAGED_MANAGED_BOOKMARK_SERVICE_H_
[ "jengelh@inai.de" ]
jengelh@inai.de
1c657e50c5b701319e9ebbf75b13cafb863d5e76
7af67fec3e45fbb85b2c0e107e7a4c234e3b7de8
/asio/include/asio/impl/spawn.hpp
ae05141c81ed0c3bb5812f62bacbcf69caadab18
[ "BSL-1.0" ]
permissive
AraHaan/asio
6e23e707ac0ec75d411f59643fe5e4b95da65135
89b0a4138a92883ae2514be68018a6c837a5b65f
refs/heads/master
2023-08-14T02:36:43.636650
2023-08-01T11:56:36
2023-08-01T12:01:43
97,129,746
1
0
null
2023-08-02T14:20:45
2017-07-13T14:10:06
C++
UTF-8
C++
false
false
45,415
hpp
// // impl/spawn.hpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2023 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // 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 ASIO_IMPL_SPAWN_HPP #define ASIO_IMPL_SPAWN_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/associated_allocator.hpp" #include "asio/associated_cancellation_slot.hpp" #include "asio/associated_executor.hpp" #include "asio/async_result.hpp" #include "asio/bind_executor.hpp" #include "asio/detail/atomic_count.hpp" #include "asio/detail/bind_handler.hpp" #include "asio/detail/handler_alloc_helpers.hpp" #include "asio/detail/handler_cont_helpers.hpp" #include "asio/detail/handler_invoke_helpers.hpp" #include "asio/detail/memory.hpp" #include "asio/detail/noncopyable.hpp" #include "asio/detail/type_traits.hpp" #include "asio/detail/utility.hpp" #include "asio/detail/variadic_templates.hpp" #include "asio/system_error.hpp" #if defined(ASIO_HAS_STD_TUPLE) # include <tuple> #endif // defined(ASIO_HAS_STD_TUPLE) #if defined(ASIO_HAS_BOOST_CONTEXT_FIBER) # include <boost/context/fiber.hpp> #endif // defined(ASIO_HAS_BOOST_CONTEXT_FIBER) #include "asio/detail/push_options.hpp" namespace asio { namespace detail { #if !defined(ASIO_NO_EXCEPTIONS) inline void spawned_thread_rethrow(void* ex) { if (*static_cast<exception_ptr*>(ex)) rethrow_exception(*static_cast<exception_ptr*>(ex)); } #endif // !defined(ASIO_NO_EXCEPTIONS) #if defined(ASIO_HAS_BOOST_COROUTINE) // Spawned thread implementation using Boost.Coroutine. class spawned_coroutine_thread : public spawned_thread_base { public: #if defined(BOOST_COROUTINES_UNIDIRECT) || defined(BOOST_COROUTINES_V2) typedef boost::coroutines::pull_coroutine<void> callee_type; typedef boost::coroutines::push_coroutine<void> caller_type; #else typedef boost::coroutines::coroutine<void()> callee_type; typedef boost::coroutines::coroutine<void()> caller_type; #endif spawned_coroutine_thread(caller_type& caller) : caller_(caller), on_suspend_fn_(0), on_suspend_arg_(0) { } template <typename F> static spawned_thread_base* spawn(ASIO_MOVE_ARG(F) f, const boost::coroutines::attributes& attributes, cancellation_slot parent_cancel_slot = cancellation_slot(), cancellation_state cancel_state = cancellation_state()) { spawned_coroutine_thread* spawned_thread = 0; callee_type callee(entry_point<typename decay<F>::type>( ASIO_MOVE_CAST(F)(f), &spawned_thread), attributes); spawned_thread->callee_.swap(callee); spawned_thread->parent_cancellation_slot_ = parent_cancel_slot; spawned_thread->cancellation_state_ = cancel_state; return spawned_thread; } template <typename F> static spawned_thread_base* spawn(ASIO_MOVE_ARG(F) f, cancellation_slot parent_cancel_slot = cancellation_slot(), cancellation_state cancel_state = cancellation_state()) { return spawn(ASIO_MOVE_CAST(F)(f), boost::coroutines::attributes(), parent_cancel_slot, cancel_state); } void resume() { callee_(); if (on_suspend_fn_) { void (*fn)(void*) = on_suspend_fn_; void* arg = on_suspend_arg_; on_suspend_fn_ = 0; fn(arg); } } void suspend_with(void (*fn)(void*), void* arg) { if (throw_if_cancelled_) if (!!cancellation_state_.cancelled()) throw_error(asio::error::operation_aborted, "yield"); has_context_switched_ = true; on_suspend_fn_ = fn; on_suspend_arg_ = arg; caller_(); } void destroy() { callee_type callee; callee.swap(callee_); if (terminal_) callee(); } private: template <typename Function> class entry_point { public: template <typename F> entry_point(ASIO_MOVE_ARG(F) f, spawned_coroutine_thread** spawned_thread_out) : function_(ASIO_MOVE_CAST(F)(f)), spawned_thread_out_(spawned_thread_out) { } void operator()(caller_type& caller) { Function function(ASIO_MOVE_CAST(Function)(function_)); spawned_coroutine_thread spawned_thread(caller); *spawned_thread_out_ = &spawned_thread; spawned_thread_out_ = 0; spawned_thread.suspend(); #if !defined(ASIO_NO_EXCEPTIONS) try #endif // !defined(ASIO_NO_EXCEPTIONS) { function(&spawned_thread); spawned_thread.terminal_ = true; spawned_thread.suspend(); } #if !defined(ASIO_NO_EXCEPTIONS) catch (const boost::coroutines::detail::forced_unwind&) { throw; } catch (...) { exception_ptr ex = current_exception(); spawned_thread.terminal_ = true; spawned_thread.suspend_with(spawned_thread_rethrow, &ex); } #endif // !defined(ASIO_NO_EXCEPTIONS) } private: Function function_; spawned_coroutine_thread** spawned_thread_out_; }; caller_type& caller_; callee_type callee_; void (*on_suspend_fn_)(void*); void* on_suspend_arg_; }; #endif // defined(ASIO_HAS_BOOST_COROUTINE) #if defined(ASIO_HAS_BOOST_CONTEXT_FIBER) // Spawned thread implementation using Boost.Context's fiber. class spawned_fiber_thread : public spawned_thread_base { public: typedef boost::context::fiber fiber_type; spawned_fiber_thread(ASIO_MOVE_ARG(fiber_type) caller) : caller_(ASIO_MOVE_CAST(fiber_type)(caller)), on_suspend_fn_(0), on_suspend_arg_(0) { } template <typename StackAllocator, typename F> static spawned_thread_base* spawn(allocator_arg_t, ASIO_MOVE_ARG(StackAllocator) stack_allocator, ASIO_MOVE_ARG(F) f, cancellation_slot parent_cancel_slot = cancellation_slot(), cancellation_state cancel_state = cancellation_state()) { spawned_fiber_thread* spawned_thread = 0; fiber_type callee(allocator_arg_t(), ASIO_MOVE_CAST(StackAllocator)(stack_allocator), entry_point<typename decay<F>::type>( ASIO_MOVE_CAST(F)(f), &spawned_thread)); callee = fiber_type(ASIO_MOVE_CAST(fiber_type)(callee)).resume(); spawned_thread->callee_ = ASIO_MOVE_CAST(fiber_type)(callee); spawned_thread->parent_cancellation_slot_ = parent_cancel_slot; spawned_thread->cancellation_state_ = cancel_state; return spawned_thread; } template <typename F> static spawned_thread_base* spawn(ASIO_MOVE_ARG(F) f, cancellation_slot parent_cancel_slot = cancellation_slot(), cancellation_state cancel_state = cancellation_state()) { return spawn(allocator_arg_t(), boost::context::fixedsize_stack(), ASIO_MOVE_CAST(F)(f), parent_cancel_slot, cancel_state); } void resume() { callee_ = fiber_type(ASIO_MOVE_CAST(fiber_type)(callee_)).resume(); if (on_suspend_fn_) { void (*fn)(void*) = on_suspend_fn_; void* arg = on_suspend_arg_; on_suspend_fn_ = 0; fn(arg); } } void suspend_with(void (*fn)(void*), void* arg) { if (throw_if_cancelled_) if (!!cancellation_state_.cancelled()) throw_error(asio::error::operation_aborted, "yield"); has_context_switched_ = true; on_suspend_fn_ = fn; on_suspend_arg_ = arg; caller_ = fiber_type(ASIO_MOVE_CAST(fiber_type)(caller_)).resume(); } void destroy() { fiber_type callee = ASIO_MOVE_CAST(fiber_type)(callee_); if (terminal_) fiber_type(ASIO_MOVE_CAST(fiber_type)(callee)).resume(); } private: template <typename Function> class entry_point { public: template <typename F> entry_point(ASIO_MOVE_ARG(F) f, spawned_fiber_thread** spawned_thread_out) : function_(ASIO_MOVE_CAST(F)(f)), spawned_thread_out_(spawned_thread_out) { } fiber_type operator()(ASIO_MOVE_ARG(fiber_type) caller) { Function function(ASIO_MOVE_CAST(Function)(function_)); spawned_fiber_thread spawned_thread( ASIO_MOVE_CAST(fiber_type)(caller)); *spawned_thread_out_ = &spawned_thread; spawned_thread_out_ = 0; spawned_thread.suspend(); #if !defined(ASIO_NO_EXCEPTIONS) try #endif // !defined(ASIO_NO_EXCEPTIONS) { function(&spawned_thread); spawned_thread.terminal_ = true; spawned_thread.suspend(); } #if !defined(ASIO_NO_EXCEPTIONS) catch (const boost::context::detail::forced_unwind&) { throw; } catch (...) { exception_ptr ex = current_exception(); spawned_thread.terminal_ = true; spawned_thread.suspend_with(spawned_thread_rethrow, &ex); } #endif // !defined(ASIO_NO_EXCEPTIONS) return ASIO_MOVE_CAST(fiber_type)(spawned_thread.caller_); } private: Function function_; spawned_fiber_thread** spawned_thread_out_; }; fiber_type caller_; fiber_type callee_; void (*on_suspend_fn_)(void*); void* on_suspend_arg_; }; #endif // defined(ASIO_HAS_BOOST_CONTEXT_FIBER) #if defined(ASIO_HAS_BOOST_CONTEXT_FIBER) typedef spawned_fiber_thread default_spawned_thread_type; #elif defined(ASIO_HAS_BOOST_COROUTINE) typedef spawned_coroutine_thread default_spawned_thread_type; #else # error No spawn() implementation available #endif // Helper class to perform the initial resume on the correct executor. class spawned_thread_resumer { public: explicit spawned_thread_resumer(spawned_thread_base* spawned_thread) : spawned_thread_(spawned_thread) { #if !defined(ASIO_HAS_MOVE) spawned_thread->detach(); spawned_thread->attach(&spawned_thread_); #endif // !defined(ASIO_HAS_MOVE) } #if defined(ASIO_HAS_MOVE) spawned_thread_resumer(spawned_thread_resumer&& other) ASIO_NOEXCEPT : spawned_thread_(other.spawned_thread_) { other.spawned_thread_ = 0; } #else // defined(ASIO_HAS_MOVE) spawned_thread_resumer( const spawned_thread_resumer& other) ASIO_NOEXCEPT : spawned_thread_(other.spawned_thread_) { spawned_thread_->detach(); spawned_thread_->attach(&spawned_thread_); } #endif // defined(ASIO_HAS_MOVE) ~spawned_thread_resumer() { if (spawned_thread_) spawned_thread_->destroy(); } void operator()() { #if defined(ASIO_HAS_MOVE) spawned_thread_->attach(&spawned_thread_); #endif // defined(ASIO_HAS_MOVE) spawned_thread_->resume(); } private: spawned_thread_base* spawned_thread_; }; // Helper class to ensure spawned threads are destroyed on the correct executor. class spawned_thread_destroyer { public: explicit spawned_thread_destroyer(spawned_thread_base* spawned_thread) : spawned_thread_(spawned_thread) { spawned_thread->detach(); #if !defined(ASIO_HAS_MOVE) spawned_thread->attach(&spawned_thread_); #endif // !defined(ASIO_HAS_MOVE) } #if defined(ASIO_HAS_MOVE) spawned_thread_destroyer(spawned_thread_destroyer&& other) ASIO_NOEXCEPT : spawned_thread_(other.spawned_thread_) { other.spawned_thread_ = 0; } #else // defined(ASIO_HAS_MOVE) spawned_thread_destroyer( const spawned_thread_destroyer& other) ASIO_NOEXCEPT : spawned_thread_(other.spawned_thread_) { spawned_thread_->detach(); spawned_thread_->attach(&spawned_thread_); } #endif // defined(ASIO_HAS_MOVE) ~spawned_thread_destroyer() { if (spawned_thread_) spawned_thread_->destroy(); } void operator()() { if (spawned_thread_) { spawned_thread_->destroy(); spawned_thread_ = 0; } } private: spawned_thread_base* spawned_thread_; }; // Base class for all completion handlers associated with a spawned thread. template <typename Executor> class spawn_handler_base { public: typedef Executor executor_type; typedef cancellation_slot cancellation_slot_type; spawn_handler_base(const basic_yield_context<Executor>& yield) : yield_(yield), spawned_thread_(yield.spawned_thread_) { spawned_thread_->detach(); #if !defined(ASIO_HAS_MOVE) spawned_thread_->attach(&spawned_thread_); #endif // !defined(ASIO_HAS_MOVE) } #if defined(ASIO_HAS_MOVE) spawn_handler_base(spawn_handler_base&& other) ASIO_NOEXCEPT : yield_(other.yield_), spawned_thread_(other.spawned_thread_) { other.spawned_thread_ = 0; } #else // defined(ASIO_HAS_MOVE) spawn_handler_base(const spawn_handler_base& other) ASIO_NOEXCEPT : yield_(other.yield_), spawned_thread_(other.spawned_thread_) { spawned_thread_->detach(); spawned_thread_->attach(&spawned_thread_); } #endif // defined(ASIO_HAS_MOVE) ~spawn_handler_base() { if (spawned_thread_) (post)(yield_.executor_, spawned_thread_destroyer(spawned_thread_)); } executor_type get_executor() const ASIO_NOEXCEPT { return yield_.executor_; } cancellation_slot_type get_cancellation_slot() const ASIO_NOEXCEPT { return spawned_thread_->get_cancellation_slot(); } void resume() { spawned_thread_resumer resumer(spawned_thread_); spawned_thread_ = 0; resumer(); } protected: const basic_yield_context<Executor>& yield_; spawned_thread_base* spawned_thread_; }; // Completion handlers for when basic_yield_context is used as a token. template <typename Executor, typename Signature> class spawn_handler; template <typename Executor, typename R> class spawn_handler<Executor, R()> : public spawn_handler_base<Executor> { public: typedef void return_type; struct result_type {}; spawn_handler(const basic_yield_context<Executor>& yield, result_type&) : spawn_handler_base<Executor>(yield) { } void operator()() { this->resume(); } static return_type on_resume(result_type&) { } }; template <typename Executor, typename R> class spawn_handler<Executor, R(asio::error_code)> : public spawn_handler_base<Executor> { public: typedef void return_type; typedef asio::error_code* result_type; spawn_handler(const basic_yield_context<Executor>& yield, result_type& result) : spawn_handler_base<Executor>(yield), result_(result) { } void operator()(asio::error_code ec) { if (this->yield_.ec_) { *this->yield_.ec_ = ec; result_ = 0; } else result_ = &ec; this->resume(); } static return_type on_resume(result_type& result) { if (result) throw_error(*result); } private: result_type& result_; }; template <typename Executor, typename R> class spawn_handler<Executor, R(exception_ptr)> : public spawn_handler_base<Executor> { public: typedef void return_type; typedef exception_ptr* result_type; spawn_handler(const basic_yield_context<Executor>& yield, result_type& result) : spawn_handler_base<Executor>(yield), result_(result) { } void operator()(exception_ptr ex) { result_ = &ex; this->resume(); } static return_type on_resume(result_type& result) { if (result) rethrow_exception(*result); } private: result_type& result_; }; template <typename Executor, typename R, typename T> class spawn_handler<Executor, R(T)> : public spawn_handler_base<Executor> { public: typedef T return_type; typedef return_type* result_type; spawn_handler(const basic_yield_context<Executor>& yield, result_type& result) : spawn_handler_base<Executor>(yield), result_(result) { } void operator()(T value) { result_ = &value; this->resume(); } static return_type on_resume(result_type& result) { return ASIO_MOVE_CAST(return_type)(*result); } private: result_type& result_; }; template <typename Executor, typename R, typename T> class spawn_handler<Executor, R(asio::error_code, T)> : public spawn_handler_base<Executor> { public: typedef T return_type; struct result_type { asio::error_code* ec_; return_type* value_; }; spawn_handler(const basic_yield_context<Executor>& yield, result_type& result) : spawn_handler_base<Executor>(yield), result_(result) { } void operator()(asio::error_code ec, T value) { if (this->yield_.ec_) { *this->yield_.ec_ = ec; result_.ec_ = 0; } else result_.ec_ = &ec; result_.value_ = &value; this->resume(); } static return_type on_resume(result_type& result) { if (result.ec_) throw_error(*result.ec_); return ASIO_MOVE_CAST(return_type)(*result.value_); } private: result_type& result_; }; template <typename Executor, typename R, typename T> class spawn_handler<Executor, R(exception_ptr, T)> : public spawn_handler_base<Executor> { public: typedef T return_type; struct result_type { exception_ptr* ex_; return_type* value_; }; spawn_handler(const basic_yield_context<Executor>& yield, result_type& result) : spawn_handler_base<Executor>(yield), result_(result) { } void operator()(exception_ptr ex, T value) { result_.ex_ = &ex; result_.value_ = &value; this->resume(); } static return_type on_resume(result_type& result) { if (result.ex_) rethrow_exception(*result.ex_); return ASIO_MOVE_CAST(return_type)(*result.value_); } private: result_type& result_; }; #if defined(ASIO_HAS_VARIADIC_TEMPLATES) \ && defined(ASIO_HAS_STD_TUPLE) template <typename Executor, typename R, typename... Ts> class spawn_handler<Executor, R(Ts...)> : public spawn_handler_base<Executor> { public: typedef std::tuple<Ts...> return_type; typedef return_type* result_type; spawn_handler(const basic_yield_context<Executor>& yield, result_type& result) : spawn_handler_base<Executor>(yield), result_(result) { } template <typename... Args> void operator()(ASIO_MOVE_ARG(Args)... args) { return_type value(ASIO_MOVE_CAST(Args)(args)...); result_ = &value; this->resume(); } static return_type on_resume(result_type& result) { return ASIO_MOVE_CAST(return_type)(*result); } private: result_type& result_; }; template <typename Executor, typename R, typename... Ts> class spawn_handler<Executor, R(asio::error_code, Ts...)> : public spawn_handler_base<Executor> { public: typedef std::tuple<Ts...> return_type; struct result_type { asio::error_code* ec_; return_type* value_; }; spawn_handler(const basic_yield_context<Executor>& yield, result_type& result) : spawn_handler_base<Executor>(yield), result_(result) { } template <typename... Args> void operator()(asio::error_code ec, ASIO_MOVE_ARG(Args)... args) { return_type value(ASIO_MOVE_CAST(Args)(args)...); if (this->yield_.ec_) { *this->yield_.ec_ = ec; result_.ec_ = 0; } else result_.ec_ = &ec; result_.value_ = &value; this->resume(); } static return_type on_resume(result_type& result) { if (result.ec_) throw_error(*result.ec_); return ASIO_MOVE_CAST(return_type)(*result.value_); } private: result_type& result_; }; template <typename Executor, typename R, typename... Ts> class spawn_handler<Executor, R(exception_ptr, Ts...)> : public spawn_handler_base<Executor> { public: typedef std::tuple<Ts...> return_type; struct result_type { exception_ptr* ex_; return_type* value_; }; spawn_handler(const basic_yield_context<Executor>& yield, result_type& result) : spawn_handler_base<Executor>(yield), result_(result) { } template <typename... Args> void operator()(exception_ptr ex, ASIO_MOVE_ARG(Args)... args) { return_type value(ASIO_MOVE_CAST(Args)(args)...); result_.ex_ = &ex; result_.value_ = &value; this->resume(); } static return_type on_resume(result_type& result) { if (result.ex_) rethrow_exception(*result.ex_); return ASIO_MOVE_CAST(return_type)(*result.value_); } private: result_type& result_; }; #endif // defined(ASIO_HAS_VARIADIC_TEMPLATES) // && defined(ASIO_HAS_STD_TUPLE) template <typename Executor, typename Signature> inline bool asio_handler_is_continuation(spawn_handler<Executor, Signature>*) { return true; } } // namespace detail template <typename Executor, typename Signature> class async_result<basic_yield_context<Executor>, Signature> { public: typedef typename detail::spawn_handler<Executor, Signature> handler_type; typedef typename handler_type::return_type return_type; #if defined(ASIO_HAS_VARIADIC_TEMPLATES) # if defined(ASIO_HAS_VARIADIC_LAMBDA_CAPTURES) template <typename Initiation, typename... InitArgs> static return_type initiate(ASIO_MOVE_ARG(Initiation) init, const basic_yield_context<Executor>& yield, ASIO_MOVE_ARG(InitArgs)... init_args) { typename handler_type::result_type result = typename handler_type::result_type(); yield.spawned_thread_->suspend_with( [&]() { ASIO_MOVE_CAST(Initiation)(init)( handler_type(yield, result), ASIO_MOVE_CAST(InitArgs)(init_args)...); }); return handler_type::on_resume(result); } # else // defined(ASIO_HAS_VARIADIC_LAMBDA_CAPTURES) template <typename Initiation, typename... InitArgs> struct suspend_with_helper { typename handler_type::result_type& result_; ASIO_MOVE_ARG(Initiation) init_; const basic_yield_context<Executor>& yield_; std::tuple<ASIO_MOVE_ARG(InitArgs)...> init_args_; template <std::size_t... I> void do_invoke(detail::index_sequence<I...>) { ASIO_MOVE_CAST(Initiation)(init_)( handler_type(yield_, result_), ASIO_MOVE_CAST(InitArgs)(std::get<I>(init_args_))...); } void operator()() { this->do_invoke(detail::make_index_sequence<sizeof...(InitArgs)>()); } }; template <typename Initiation, typename... InitArgs> static return_type initiate(ASIO_MOVE_ARG(Initiation) init, const basic_yield_context<Executor>& yield, ASIO_MOVE_ARG(InitArgs)... init_args) { typename handler_type::result_type result = typename handler_type::result_type(); yield.spawned_thread_->suspend_with( suspend_with_helper<Initiation, InitArgs...>{ result, ASIO_MOVE_CAST(Initiation)(init), yield, std::tuple<ASIO_MOVE_ARG(InitArgs)...>( ASIO_MOVE_CAST(InitArgs)(init_args)...)}); return handler_type::on_resume(result); } # endif // defined(ASIO_HAS_VARIADIC_LAMBDA_CAPTURES) #else // defined(ASIO_HAS_VARIADIC_TEMPLATES) template <typename Initiation> static return_type initiate(Initiation init, const basic_yield_context<Executor>& yield) { typename handler_type::result_type result = typename handler_type::result_type(); struct on_suspend { Initiation& init_; const basic_yield_context<Executor>& yield_; typename handler_type::result_type& result_; void do_call() { ASIO_MOVE_CAST(Initiation)(init_)( handler_type(yield_, result_)); } static void call(void* arg) { static_cast<on_suspend*>(arg)->do_call(); } } o = { init, yield, result }; yield.spawned_thread_->suspend_with(&on_suspend::call, &o); return handler_type::on_resume(result); } #define ASIO_PRIVATE_ON_SUSPEND_MEMBERS(n) \ ASIO_PRIVATE_ON_SUSPEND_MEMBERS_##n #define ASIO_PRIVATE_ON_SUSPEND_MEMBERS_1 \ T1& x1; #define ASIO_PRIVATE_ON_SUSPEND_MEMBERS_2 \ T1& x1; T2& x2; #define ASIO_PRIVATE_ON_SUSPEND_MEMBERS_3 \ T1& x1; T2& x2; T3& x3; #define ASIO_PRIVATE_ON_SUSPEND_MEMBERS_4 \ T1& x1; T2& x2; T3& x3; T4& x4; #define ASIO_PRIVATE_ON_SUSPEND_MEMBERS_5 \ T1& x1; T2& x2; T3& x3; T4& x4; T5& x5; #define ASIO_PRIVATE_ON_SUSPEND_MEMBERS_6 \ T1& x1; T2& x2; T3& x3; T4& x4; T5& x5; T6& x6; #define ASIO_PRIVATE_ON_SUSPEND_MEMBERS_7 \ T1& x1; T2& x2; T3& x3; T4& x4; T5& x5; T6& x6; T7& x7; #define ASIO_PRIVATE_ON_SUSPEND_MEMBERS_8 \ T1& x1; T2& x2; T3& x3; T4& x4; T5& x5; T6& x6; T7& x7; T8& x8; #define ASIO_PRIVATE_INITIATE_DEF(n) \ template <typename Initiation, ASIO_VARIADIC_TPARAMS(n)> \ static return_type initiate(Initiation init, \ const basic_yield_context<Executor>& yield, \ ASIO_VARIADIC_BYVAL_PARAMS(n)) \ { \ typename handler_type::result_type result \ = typename handler_type::result_type(); \ \ struct on_suspend \ { \ Initiation& init; \ const basic_yield_context<Executor>& yield; \ typename handler_type::result_type& result; \ ASIO_PRIVATE_ON_SUSPEND_MEMBERS(n) \ \ void do_call() \ { \ ASIO_MOVE_CAST(Initiation)(init)( \ handler_type(yield, result), \ ASIO_VARIADIC_MOVE_ARGS(n)); \ } \ \ static void call(void* arg) \ { \ static_cast<on_suspend*>(arg)->do_call(); \ } \ } o = { init, yield, result, ASIO_VARIADIC_BYVAL_ARGS(n) }; \ \ yield.spawned_thread_->suspend_with(&on_suspend::call, &o); \ \ return handler_type::on_resume(result); \ } \ /**/ ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_INITIATE_DEF) #undef ASIO_PRIVATE_INITIATE_DEF #undef ASIO_PRIVATE_ON_SUSPEND_MEMBERS #undef ASIO_PRIVATE_ON_SUSPEND_MEMBERS_1 #undef ASIO_PRIVATE_ON_SUSPEND_MEMBERS_2 #undef ASIO_PRIVATE_ON_SUSPEND_MEMBERS_3 #undef ASIO_PRIVATE_ON_SUSPEND_MEMBERS_4 #undef ASIO_PRIVATE_ON_SUSPEND_MEMBERS_5 #undef ASIO_PRIVATE_ON_SUSPEND_MEMBERS_6 #undef ASIO_PRIVATE_ON_SUSPEND_MEMBERS_7 #undef ASIO_PRIVATE_ON_SUSPEND_MEMBERS_8 #endif // defined(ASIO_HAS_VARIADIC_TEMPLATES) }; namespace detail { template <typename Executor, typename Function, typename Handler> class spawn_entry_point { public: template <typename F, typename H> spawn_entry_point(const Executor& ex, ASIO_MOVE_ARG(F) f, ASIO_MOVE_ARG(H) h) : executor_(ex), function_(ASIO_MOVE_CAST(F)(f)), handler_(ASIO_MOVE_CAST(H)(h)), work_(handler_, executor_) { } void operator()(spawned_thread_base* spawned_thread) { const basic_yield_context<Executor> yield(spawned_thread, executor_); this->call(yield, void_type<typename result_of<Function( basic_yield_context<Executor>)>::type>()); } private: void call(const basic_yield_context<Executor>& yield, void_type<void>) { #if !defined(ASIO_NO_EXCEPTIONS) try #endif // !defined(ASIO_NO_EXCEPTIONS) { function_(yield); if (!yield.spawned_thread_->has_context_switched()) (post)(yield); detail::binder1<Handler, exception_ptr> handler(handler_, exception_ptr()); work_.complete(handler, handler.handler_); } #if !defined(ASIO_NO_EXCEPTIONS) # if defined(ASIO_HAS_BOOST_CONTEXT_FIBER) catch (const boost::context::detail::forced_unwind&) { throw; } # endif // defined(ASIO_HAS_BOOST_CONTEXT_FIBER) # if defined(ASIO_HAS_BOOST_COROUTINE) catch (const boost::coroutines::detail::forced_unwind&) { throw; } # endif // defined(ASIO_HAS_BOOST_COROUTINE) catch (...) { exception_ptr ex = current_exception(); if (!yield.spawned_thread_->has_context_switched()) (post)(yield); detail::binder1<Handler, exception_ptr> handler(handler_, ex); work_.complete(handler, handler.handler_); } #endif // !defined(ASIO_NO_EXCEPTIONS) } template <typename T> void call(const basic_yield_context<Executor>& yield, void_type<T>) { #if !defined(ASIO_NO_EXCEPTIONS) try #endif // !defined(ASIO_NO_EXCEPTIONS) { T result(function_(yield)); if (!yield.spawned_thread_->has_context_switched()) (post)(yield); detail::binder2<Handler, exception_ptr, T> handler(handler_, exception_ptr(), ASIO_MOVE_CAST(T)(result)); work_.complete(handler, handler.handler_); } #if !defined(ASIO_NO_EXCEPTIONS) # if defined(ASIO_HAS_BOOST_CONTEXT_FIBER) catch (const boost::context::detail::forced_unwind&) { throw; } # endif // defined(ASIO_HAS_BOOST_CONTEXT_FIBER) # if defined(ASIO_HAS_BOOST_COROUTINE) catch (const boost::coroutines::detail::forced_unwind&) { throw; } # endif // defined(ASIO_HAS_BOOST_COROUTINE) catch (...) { exception_ptr ex = current_exception(); if (!yield.spawned_thread_->has_context_switched()) (post)(yield); detail::binder2<Handler, exception_ptr, T> handler(handler_, ex, T()); work_.complete(handler, handler.handler_); } #endif // !defined(ASIO_NO_EXCEPTIONS) } Executor executor_; Function function_; Handler handler_; handler_work<Handler, Executor> work_; }; struct spawn_cancellation_signal_emitter { cancellation_signal* signal_; cancellation_type_t type_; void operator()() { signal_->emit(type_); } }; template <typename Handler, typename Executor, typename = void> class spawn_cancellation_handler { public: spawn_cancellation_handler(const Handler&, const Executor& ex) : ex_(ex) { } cancellation_slot slot() { return signal_.slot(); } void operator()(cancellation_type_t type) { spawn_cancellation_signal_emitter emitter = { &signal_, type }; (dispatch)(ex_, emitter); } private: cancellation_signal signal_; Executor ex_; }; template <typename Handler, typename Executor> class spawn_cancellation_handler<Handler, Executor, typename enable_if< is_same< typename associated_executor<Handler, Executor>::asio_associated_executor_is_unspecialised, void >::value >::type> { public: spawn_cancellation_handler(const Handler&, const Executor&) { } cancellation_slot slot() { return signal_.slot(); } void operator()(cancellation_type_t type) { signal_.emit(type); } private: cancellation_signal signal_; }; template <typename Executor> class initiate_spawn { public: typedef Executor executor_type; explicit initiate_spawn(const executor_type& ex) : executor_(ex) { } executor_type get_executor() const ASIO_NOEXCEPT { return executor_; } template <typename Handler, typename F> void operator()(ASIO_MOVE_ARG(Handler) handler, ASIO_MOVE_ARG(F) f) const { typedef typename decay<Handler>::type handler_type; typedef typename decay<F>::type function_type; typedef spawn_cancellation_handler< handler_type, Executor> cancel_handler_type; typename associated_cancellation_slot<handler_type>::type slot = asio::get_associated_cancellation_slot(handler); cancel_handler_type* cancel_handler = slot.is_connected() ? &slot.template emplace<cancel_handler_type>(handler, executor_) : 0; cancellation_slot proxy_slot( cancel_handler ? cancel_handler->slot() : cancellation_slot()); cancellation_state cancel_state(proxy_slot); (dispatch)(executor_, spawned_thread_resumer( default_spawned_thread_type::spawn( spawn_entry_point<Executor, function_type, handler_type>( executor_, ASIO_MOVE_CAST(F)(f), ASIO_MOVE_CAST(Handler)(handler)), proxy_slot, cancel_state))); } #if defined(ASIO_HAS_BOOST_CONTEXT_FIBER) template <typename Handler, typename StackAllocator, typename F> void operator()(ASIO_MOVE_ARG(Handler) handler, allocator_arg_t, ASIO_MOVE_ARG(StackAllocator) stack_allocator, ASIO_MOVE_ARG(F) f) const { typedef typename decay<Handler>::type handler_type; typedef typename decay<F>::type function_type; typedef spawn_cancellation_handler< handler_type, Executor> cancel_handler_type; typename associated_cancellation_slot<handler_type>::type slot = asio::get_associated_cancellation_slot(handler); cancel_handler_type* cancel_handler = slot.is_connected() ? &slot.template emplace<cancel_handler_type>(handler, executor_) : 0; cancellation_slot proxy_slot( cancel_handler ? cancel_handler->slot() : cancellation_slot()); cancellation_state cancel_state(proxy_slot); (dispatch)(executor_, spawned_thread_resumer( spawned_fiber_thread::spawn(allocator_arg_t(), ASIO_MOVE_CAST(StackAllocator)(stack_allocator), spawn_entry_point<Executor, function_type, handler_type>( executor_, ASIO_MOVE_CAST(F)(f), ASIO_MOVE_CAST(Handler)(handler)), proxy_slot, cancel_state))); } #endif // defined(ASIO_HAS_BOOST_CONTEXT_FIBER) private: executor_type executor_; }; } // namespace detail template <typename Executor, typename F, ASIO_COMPLETION_TOKEN_FOR(typename detail::spawn_signature< typename result_of<F(basic_yield_context<Executor>)>::type>::type) CompletionToken> inline ASIO_INITFN_AUTO_RESULT_TYPE_PREFIX(CompletionToken, typename detail::spawn_signature< typename result_of<F(basic_yield_context<Executor>)>::type>::type) spawn(const Executor& ex, ASIO_MOVE_ARG(F) function, ASIO_MOVE_ARG(CompletionToken) token, #if defined(ASIO_HAS_BOOST_COROUTINE) typename constraint< !is_same< typename decay<CompletionToken>::type, boost::coroutines::attributes >::value >::type, #endif // defined(ASIO_HAS_BOOST_COROUTINE) typename constraint< is_executor<Executor>::value || execution::is_executor<Executor>::value >::type) ASIO_INITFN_AUTO_RESULT_TYPE_SUFFIX(( async_initiate<CompletionToken, typename detail::spawn_signature< typename result_of<F(basic_yield_context<Executor>)>::type>::type>( declval<detail::initiate_spawn<Executor> >(), token, ASIO_MOVE_CAST(F)(function)))) { return async_initiate<CompletionToken, typename detail::spawn_signature< typename result_of<F(basic_yield_context<Executor>)>::type>::type>( detail::initiate_spawn<Executor>(ex), token, ASIO_MOVE_CAST(F)(function)); } template <typename ExecutionContext, typename F, ASIO_COMPLETION_TOKEN_FOR(typename detail::spawn_signature< typename result_of<F(basic_yield_context< typename ExecutionContext::executor_type>)>::type>::type) CompletionToken> inline ASIO_INITFN_AUTO_RESULT_TYPE_PREFIX(CompletionToken, typename detail::spawn_signature< typename result_of<F(basic_yield_context< typename ExecutionContext::executor_type>)>::type>::type) spawn(ExecutionContext& ctx, ASIO_MOVE_ARG(F) function, ASIO_MOVE_ARG(CompletionToken) token, #if defined(ASIO_HAS_BOOST_COROUTINE) typename constraint< !is_same< typename decay<CompletionToken>::type, boost::coroutines::attributes >::value >::type, #endif // defined(ASIO_HAS_BOOST_COROUTINE) typename constraint< is_convertible<ExecutionContext&, execution_context&>::value >::type) ASIO_INITFN_AUTO_RESULT_TYPE_SUFFIX(( async_initiate<CompletionToken, typename detail::spawn_signature< typename result_of<F(basic_yield_context< typename ExecutionContext::executor_type>)>::type>::type>( declval<detail::initiate_spawn< typename ExecutionContext::executor_type> >(), token, ASIO_MOVE_CAST(F)(function)))) { return (spawn)(ctx.get_executor(), ASIO_MOVE_CAST(F)(function), ASIO_MOVE_CAST(CompletionToken)(token)); } template <typename Executor, typename F, ASIO_COMPLETION_TOKEN_FOR(typename detail::spawn_signature< typename result_of<F(basic_yield_context<Executor>)>::type>::type) CompletionToken> inline ASIO_INITFN_AUTO_RESULT_TYPE_PREFIX(CompletionToken, typename detail::spawn_signature< typename result_of<F(basic_yield_context<Executor>)>::type>::type) spawn(const basic_yield_context<Executor>& ctx, ASIO_MOVE_ARG(F) function, ASIO_MOVE_ARG(CompletionToken) token, #if defined(ASIO_HAS_BOOST_COROUTINE) typename constraint< !is_same< typename decay<CompletionToken>::type, boost::coroutines::attributes >::value >::type, #endif // defined(ASIO_HAS_BOOST_COROUTINE) typename constraint< is_executor<Executor>::value || execution::is_executor<Executor>::value >::type) ASIO_INITFN_AUTO_RESULT_TYPE_SUFFIX(( async_initiate<CompletionToken, typename detail::spawn_signature< typename result_of<F(basic_yield_context<Executor>)>::type>::type>( declval<detail::initiate_spawn<Executor> >(), token, ASIO_MOVE_CAST(F)(function)))) { return (spawn)(ctx.get_executor(), ASIO_MOVE_CAST(F)(function), ASIO_MOVE_CAST(CompletionToken)(token)); } #if defined(ASIO_HAS_BOOST_CONTEXT_FIBER) template <typename Executor, typename StackAllocator, typename F, ASIO_COMPLETION_TOKEN_FOR(typename detail::spawn_signature< typename result_of<F(basic_yield_context<Executor>)>::type>::type) CompletionToken> inline ASIO_INITFN_AUTO_RESULT_TYPE_PREFIX(CompletionToken, typename detail::spawn_signature< typename result_of<F(basic_yield_context<Executor>)>::type>::type) spawn(const Executor& ex, allocator_arg_t, ASIO_MOVE_ARG(StackAllocator) stack_allocator, ASIO_MOVE_ARG(F) function, ASIO_MOVE_ARG(CompletionToken) token, typename constraint< is_executor<Executor>::value || execution::is_executor<Executor>::value >::type) ASIO_INITFN_AUTO_RESULT_TYPE_SUFFIX(( async_initiate<CompletionToken, typename detail::spawn_signature< typename result_of<F(basic_yield_context<Executor>)>::type>::type>( declval<detail::initiate_spawn<Executor> >(), token, allocator_arg_t(), ASIO_MOVE_CAST(StackAllocator)(stack_allocator), ASIO_MOVE_CAST(F)(function)))) { return async_initiate<CompletionToken, typename detail::spawn_signature< typename result_of<F(basic_yield_context<Executor>)>::type>::type>( detail::initiate_spawn<Executor>(ex), token, allocator_arg_t(), ASIO_MOVE_CAST(StackAllocator)(stack_allocator), ASIO_MOVE_CAST(F)(function)); } template <typename ExecutionContext, typename StackAllocator, typename F, ASIO_COMPLETION_TOKEN_FOR(typename detail::spawn_signature< typename result_of<F(basic_yield_context< typename ExecutionContext::executor_type>)>::type>::type) CompletionToken> inline ASIO_INITFN_AUTO_RESULT_TYPE_PREFIX(CompletionToken, typename detail::spawn_signature< typename result_of<F(basic_yield_context< typename ExecutionContext::executor_type>)>::type>::type) spawn(ExecutionContext& ctx, allocator_arg_t, ASIO_MOVE_ARG(StackAllocator) stack_allocator, ASIO_MOVE_ARG(F) function, ASIO_MOVE_ARG(CompletionToken) token, typename constraint< is_convertible<ExecutionContext&, execution_context&>::value >::type) ASIO_INITFN_AUTO_RESULT_TYPE_SUFFIX(( async_initiate<CompletionToken, typename detail::spawn_signature< typename result_of<F(basic_yield_context< typename ExecutionContext::executor_type>)>::type>::type>( declval<detail::initiate_spawn< typename ExecutionContext::executor_type> >(), token, allocator_arg_t(), ASIO_MOVE_CAST(StackAllocator)(stack_allocator), ASIO_MOVE_CAST(F)(function)))) { return (spawn)(ctx.get_executor(), allocator_arg_t(), ASIO_MOVE_CAST(StackAllocator)(stack_allocator), ASIO_MOVE_CAST(F)(function), ASIO_MOVE_CAST(CompletionToken)(token)); } template <typename Executor, typename StackAllocator, typename F, ASIO_COMPLETION_TOKEN_FOR(typename detail::spawn_signature< typename result_of<F(basic_yield_context<Executor>)>::type>::type) CompletionToken> inline ASIO_INITFN_AUTO_RESULT_TYPE_PREFIX(CompletionToken, typename detail::spawn_signature< typename result_of<F(basic_yield_context<Executor>)>::type>::type) spawn(const basic_yield_context<Executor>& ctx, allocator_arg_t, ASIO_MOVE_ARG(StackAllocator) stack_allocator, ASIO_MOVE_ARG(F) function, ASIO_MOVE_ARG(CompletionToken) token, typename constraint< is_executor<Executor>::value || execution::is_executor<Executor>::value >::type) ASIO_INITFN_AUTO_RESULT_TYPE_SUFFIX(( async_initiate<CompletionToken, typename detail::spawn_signature< typename result_of<F(basic_yield_context<Executor>)>::type>::type>( declval<detail::initiate_spawn<Executor> >(), token, allocator_arg_t(), ASIO_MOVE_CAST(StackAllocator)(stack_allocator), ASIO_MOVE_CAST(F)(function)))) { return (spawn)(ctx.get_executor(), allocator_arg_t(), ASIO_MOVE_CAST(StackAllocator)(stack_allocator), ASIO_MOVE_CAST(F)(function), ASIO_MOVE_CAST(CompletionToken)(token)); } #endif // defined(ASIO_HAS_BOOST_CONTEXT_FIBER) #if defined(ASIO_HAS_BOOST_COROUTINE) namespace detail { template <typename Executor, typename Function, typename Handler> class old_spawn_entry_point { public: template <typename F, typename H> old_spawn_entry_point(const Executor& ex, ASIO_MOVE_ARG(F) f, ASIO_MOVE_ARG(H) h) : executor_(ex), function_(ASIO_MOVE_CAST(F)(f)), handler_(ASIO_MOVE_CAST(H)(h)) { } void operator()(spawned_thread_base* spawned_thread) { const basic_yield_context<Executor> yield(spawned_thread, executor_); this->call(yield, void_type<typename result_of<Function( basic_yield_context<Executor>)>::type>()); } private: void call(const basic_yield_context<Executor>& yield, void_type<void>) { function_(yield); ASIO_MOVE_OR_LVALUE(Handler)(handler_)(); } template <typename T> void call(const basic_yield_context<Executor>& yield, void_type<T>) { ASIO_MOVE_OR_LVALUE(Handler)(handler_)(function_(yield)); } Executor executor_; Function function_; Handler handler_; }; inline void default_spawn_handler() {} } // namespace detail template <typename Function> inline void spawn(ASIO_MOVE_ARG(Function) function, const boost::coroutines::attributes& attributes) { typedef typename decay<Function>::type function_type; typename associated_executor<function_type>::type ex( (get_associated_executor)(function)); asio::spawn(ex, ASIO_MOVE_CAST(Function)(function), attributes); } template <typename Handler, typename Function> void spawn(ASIO_MOVE_ARG(Handler) handler, ASIO_MOVE_ARG(Function) function, const boost::coroutines::attributes& attributes, typename constraint< !is_executor<typename decay<Handler>::type>::value && !execution::is_executor<typename decay<Handler>::type>::value && !is_convertible<Handler&, execution_context&>::value>::type) { typedef typename decay<Handler>::type handler_type; typedef typename decay<Function>::type function_type; typedef typename associated_executor<handler_type>::type executor_type; executor_type ex((get_associated_executor)(handler)); (dispatch)(ex, detail::spawned_thread_resumer( detail::spawned_coroutine_thread::spawn( detail::old_spawn_entry_point<executor_type, function_type, void (*)()>( ex, ASIO_MOVE_CAST(Function)(function), &detail::default_spawn_handler), attributes))); } template <typename Executor, typename Function> void spawn(basic_yield_context<Executor> ctx, ASIO_MOVE_ARG(Function) function, const boost::coroutines::attributes& attributes) { typedef typename decay<Function>::type function_type; (dispatch)(ctx.get_executor(), detail::spawned_thread_resumer( detail::spawned_coroutine_thread::spawn( detail::old_spawn_entry_point<Executor, function_type, void (*)()>(ctx.get_executor(), ASIO_MOVE_CAST(Function)(function), &detail::default_spawn_handler), attributes))); } template <typename Function, typename Executor> inline void spawn(const Executor& ex, ASIO_MOVE_ARG(Function) function, const boost::coroutines::attributes& attributes, typename constraint< is_executor<Executor>::value || execution::is_executor<Executor>::value >::type) { asio::spawn(asio::strand<Executor>(ex), ASIO_MOVE_CAST(Function)(function), attributes); } template <typename Function, typename Executor> inline void spawn(const strand<Executor>& ex, ASIO_MOVE_ARG(Function) function, const boost::coroutines::attributes& attributes) { asio::spawn(asio::bind_executor( ex, &detail::default_spawn_handler), ASIO_MOVE_CAST(Function)(function), attributes); } #if !defined(ASIO_NO_TS_EXECUTORS) template <typename Function> inline void spawn(const asio::io_context::strand& s, ASIO_MOVE_ARG(Function) function, const boost::coroutines::attributes& attributes) { asio::spawn(asio::bind_executor( s, &detail::default_spawn_handler), ASIO_MOVE_CAST(Function)(function), attributes); } #endif // !defined(ASIO_NO_TS_EXECUTORS) template <typename Function, typename ExecutionContext> inline void spawn(ExecutionContext& ctx, ASIO_MOVE_ARG(Function) function, const boost::coroutines::attributes& attributes, typename constraint<is_convertible< ExecutionContext&, execution_context&>::value>::type) { asio::spawn(ctx.get_executor(), ASIO_MOVE_CAST(Function)(function), attributes); } #endif // defined(ASIO_HAS_BOOST_COROUTINE) } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_IMPL_SPAWN_HPP
[ "chris@kohlhoff.com" ]
chris@kohlhoff.com
f1af8b4a6eef74a4b0ad0d7ddde14e8bd0f44143
75335980656b8916cfac1ae0bc6fcb932f34ef08
/03.Usart/02.Transmit_Function/main.cpp~
d12e9eba9f8fac64b32e8ce6c97d89f55b28e98e
[]
no_license
sarincr/AVR_Microcontroller_Exercises
9803b2d50671ef191ff100d1901dad777558811a
ec7b14bb2c50f297a6a90453387447f084ce036c
refs/heads/master
2021-06-25T01:42:24.417013
2020-11-17T15:29:15
2020-11-17T15:29:15
147,956,668
3
0
null
null
null
null
UTF-8
C++
false
false
691
#include <avr/io.h> #include <string.h> #define F_CPU 16000000 #define BUAD 9600 #define BUAD_RATE_CALC ((F_CPU/16/BUAD) - 1) void serialSetup(void); void serialSend(char* sendString); char ar[]= "hello worlds"; void serialSetup() { UBRR0H = (BUAD_RATE_CALC >> 8); UBRR0L = BUAD_RATE_CALC; UCSR0B = (1 << TXEN0)| (1 << TXCIE0) | (1 << RXEN0) | (1 << RXCIE0); UCSR0C = (1 << UCSZ01) | (1 << UCSZ00); } void serialSend(char* sendString) { for (int i = 0; i < strlen(sendString); i++){ while (( UCSR0A & (1<<UDRE0)) == 0){}; UDR0 = sendString[i]; } } int main(void) { serialSetup(); while(1) { serialSend(ar); } }
[ "sarincrg@gmail.com" ]
sarincrg@gmail.com
28aa62c28b6d03a186fff27a54dabdca4513852f
33392bbfbc4abd42b0c67843c7c6ba9e0692f845
/quantitative_finance/L2/tests/BinomialTreeEngine/data/bt_testcases.hpp
2ed16387d7fe68ce6da9a4b3a3ba9c3567103a80
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
Xilinx/Vitis_Libraries
bad9474bf099ed288418430f695572418c87bc29
2e6c66f83ee6ad21a7c4f20d6456754c8e522995
refs/heads/main
2023-07-20T09:01:16.129113
2023-06-08T08:18:19
2023-06-08T08:18:19
210,433,135
785
371
Apache-2.0
2023-07-06T21:35:46
2019-09-23T19:13:46
C++
UTF-8
C++
false
false
1,538
hpp
/* * Copyright 2019 Xilinx, Inc. * * 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 BT_TESTCASES_H #define BT_TESTCASES_H static const std::string TestCasesFileName = "bt_testcases.csv"; static const std::string TestCasesFileEmulationName = "bt_testcases_emulation.csv"; static const std::string SVGridFileName = "bt_testcases_sv_grid.csv"; static const std::string BinomialTreeEuropeanPutName = "european_put"; static const std::string BinomialTreeEuropeanCallName = "european_call"; static const std::string BinomialTreeAmericanPutName = "american_put"; static const std::string BinomialTreeAmericanCallName = "american_call"; #define BINOMIAL_TESTCASE_NUM_S_GRID_VALUES (7) #define BINOMIAL_TESTCASE_NUM_V_GRID_VALUES (7) template <typename DT> struct BinomialTestCase { std::string name; DT K; DT rf; DT T; DT N; }; template <typename DT> struct BinomialTestSVGrid { DT s[BINOMIAL_TESTCASE_NUM_S_GRID_VALUES]; DT v[BINOMIAL_TESTCASE_NUM_V_GRID_VALUES]; }; #endif // BT_TESTCASES_H
[ "sdausr@xilinx.com" ]
sdausr@xilinx.com
0b945d8e259efdf03924a420cda4ef05ec82c7ce
f520acd3459ddd213c5e9013db46f0e914765bdf
/home_page_old/project/2014_spring/project_5/ESDC2014/source/motion_platform/Mbed/buzzer.cpp
1d4f09ada2c2d52fb6c47f87fd2c326c2bcf05e0
[]
no_license
Tony-YI/home_page
3450c54c59930dbf5b5e3d5195b90bb88ba750d6
8b991af6b230881fd4c429cf332a8f7c734834fa
refs/heads/master
2021-01-19T02:03:45.848339
2018-01-06T06:32:21
2018-01-06T06:32:21
17,402,709
1
1
null
null
null
null
UTF-8
C++
false
false
2,316
cpp
/****************************************************** ****┏┓ ┏┓ **┏┛┻━━━━━━┛┻┓ **┃ ┃ **┃ ━━━ ┃ **┃ ┳┛ ┗┳ ┃ **┃ ┃ **┃ ''' ┻ ''' ┃ **┃ ┃ **┗━━┓ ┏━━┛ *******┃ ┃ *******┃ ┃ *******┃ ┃ *******┃ ┗━━━━━━━━┓ *******┃ ┃━┓ *******┃ NO BUG ┏━┛ *******┃ ┃ *******┗━┓ ┓ ┏━┏━┓ ━┛ ***********┃ ┛ ┛ ┃ ┛ ┛ ***********┃ ┃ ┃ ┃ ┃ ┃ ***********┗━┛━┛ ┗━┛━┛ This part is added by project ESDC2014 of CUHK team. All the code with this header are under GPL open source license. This program is running on Mbed Platform 'mbed LPC1768' avaliable in 'http://mbed.org'. **********************************************************/ #include "buzzer.h" extern "C" void mbed_reset(); Buzzer::Buzzer(MyDigitalOut* buzzer) { this->_buzzer = buzzer; boot(); } Buzzer::~Buzzer(){} void Buzzer::ON() { *_buzzer = 0; } void Buzzer::OFF() { *_buzzer = 1; } void Buzzer::setFlag() { flag=1; } void Buzzer::cleanFlag() { flag=0; } void Buzzer::check_time_out() { if(flag == 1) { ON(); wait(3); mbed_reset(); } else { OFF(); } } void Buzzer::time_out_init() { setFlag(); time_out.detach(); time_out.attach(this, &Buzzer::check_time_out, TIME_OUT); } void Buzzer::target_not_found() { ON(); wait(0.1); OFF(); wait(0.1); ON(); wait(0.2); OFF(); } void Buzzer::boot() { ON(); wait(0.1); OFF(); wait(0.1); ON(); wait(0.1); OFF(); wait(0.1); ON(); wait(0.2); OFF(); } void Buzzer::take_photo() { ON(); wait(0.2); OFF(); } void Buzzer::notice(uint8_t type) { switch (type) { case BUZZER_TARGET_NOT_FOUND: target_not_found(); break; case BUZZER_TAKE_PHOTO: take_photo(); break; } }
[ "455054421@qq.com" ]
455054421@qq.com
4e4e1a76670818af2c9a7abd9ead47270824bb9d
fbe5129f71933d89be2cd45f4df61e6585d8f43e
/modules/wfirst_fisher/fomswg2detf.cpp
097ae8a7b0ca975406f51f6ffc79b2b582c86e15
[]
no_license
npadmana/nptools
47ec2d207f4367b76e97ebc35c5cc26b27bc5471
7f06a7c2727ac226dfc59e201b5de2501c13659c
refs/heads/master
2020-05-01T01:39:10.549756
2011-11-12T02:32:20
2011-11-12T02:32:20
1,779,187
0
0
null
null
null
null
UTF-8
C++
false
false
1,036
cpp
/* Convert the Stage III FoMSWG matrices to DETF */ #include <iostream> #include <boost/format.hpp> #include <boost/foreach.hpp> #include <tclap/CmdLine.h> #include "fisher_utils.h" #include "fomswg.h" #include "wfirst_detf.h" using namespace std; using namespace Eigen; int main(int argc, char **argv) { TCLAP::CmdLine cmd("Convert FoMSWG fisher matrice to DETF format",' ', "0.0"); TCLAP::UnlabeledMultiArg<string> fns("fns", "fisher matrix input and output files", true, "filenames"); cmd.add(fns); cmd.parse(argc, argv); MatrixXd ff1(nfswg, nfswg), ff(nfswg, nfswg); MatrixXd dfish1(ndetf, ndetf), dfish(ndetf-ndetf_nuis, ndetf-ndetf_nuis); // dfish accumulates only the non-SN parameters MatrixXd trans(nfswg, ndetf); dfish.setZero(); // Transform matrix trans = mkTransformMatrix(); ff1 = readFomSWG(fns.getValue()[0]); dfish1 = trans.transpose() * ff1 * trans; dfish1 = marginalizeSNparam(dfish1); writeDETFFisher(fns.getValue()[1], dfish1); dfish += dfish1; }
[ "nikhil.padmanabhan@yale.edu" ]
nikhil.padmanabhan@yale.edu
0033b8d6833aeb0bce0937cfad791aa2c788492d
44944e4c9ddeb8538bc3f305f531ad204a4af87b
/TextMazeGame/maze_game.cpp
eae98524808aa9b6db0830dae82822da53493085
[]
no_license
MelonDang/TextMazeGame
661097410fe698337ad1be7706e433418b2af627
c4b7f610439f24ca80e7a36b0f6355c90d63c449
refs/heads/master
2023-02-25T17:54:22.211284
2021-02-01T04:45:42
2021-02-01T04:45:42
334,785,227
0
0
null
null
null
null
UHC
C++
false
false
5,048
cpp
#pragma warning (disable : 4996) #include "maze_game.h" /* * 0 : 벽 * 1 : 길 * 2 : 시작점 * 3 : 도착점 * 4 : 폭탄 */ void MazeGame::InitMaze() { player_pos_.x = start_pos_.x; player_pos_.y = start_pos_.y; std::strcpy(maze_[0], "21100000000000000000"); std::strcpy(maze_[1], "00111111111100000000"); std::strcpy(maze_[2], "00100010000111111100"); std::strcpy(maze_[3], "01100010000000000100"); std::strcpy(maze_[4], "01000011110001111100"); std::strcpy(maze_[5], "01000000001111000000"); std::strcpy(maze_[6], "00000000001000000000"); std::strcpy(maze_[7], "00100000001111111000"); std::strcpy(maze_[8], "00001110000000001000"); std::strcpy(maze_[9], "01111011111111111000"); std::strcpy(maze_[10], "01000000000000000000"); std::strcpy(maze_[11], "01111100111111100000"); std::strcpy(maze_[12], "00000111100000111110"); std::strcpy(maze_[13], "01111100000000000010"); std::strcpy(maze_[14], "01000000001111111110"); std::strcpy(maze_[15], "01111111001000000000"); std::strcpy(maze_[16], "00000010011000000000"); std::strcpy(maze_[17], "01111110011111000000"); std::strcpy(maze_[18], "01000000000001100000"); std::strcpy(maze_[19], "11000000000000111113"); } void MazeGame::moveUp() { char up = maze_[player_pos_.y - 1][player_pos_.x]; if (up == '0' || up == '4' || player_pos_.y - 1 < 0) { return; } --player_pos_.y; } void MazeGame::moveDown() { char down = maze_[player_pos_.y + 1][player_pos_.x]; if (down == '0' || down == '4' || player_pos_.y + 1 > 19) { return; } ++player_pos_.y; } void MazeGame::moveLeft() { char left = maze_[player_pos_.y][player_pos_.x - 1]; if (left == '0' || left == '4' || player_pos_.x - 1 < 0) { return; } --player_pos_.x; } void MazeGame::moveRight() { char right = maze_[player_pos_.y][player_pos_.x + 1]; if (right == '0' || right == '4' || player_pos_.x + 1 > 19) { return; } ++player_pos_.x; } void MazeGame::movePlayer(const char input) { switch (input) { case 'w': case 'W': moveUp(); break; case 's': case 'S': moveDown(); break; case 'a': case 'A': moveLeft(); break; case 'd': case 'D': moveRight(); break; } } void MazeGame::createBomb() { if (plant_bombs_count_ >= MAX_BOMB_COUNT) { return; } for (int i = 0; i < plant_bombs_count_; ++i) { if (bombs_pos_[i].x == player_pos_.x && bombs_pos_[i].y == player_pos_.y) { return; } } if (player_pos_.x == start_pos_.x && player_pos_.y == start_pos_.y) { return; } else if (player_pos_.x == end_pos_.x && player_pos_.y == end_pos_.y) { return; } maze_[player_pos_.y][player_pos_.x] = '4'; bombs_pos_[plant_bombs_count_] = player_pos_; plant_bombs_count_ += 1; } void MazeGame::fireBomb() { for (int i = 0; i < plant_bombs_count_; ++i) { if (bombs_pos_[i].x == player_pos_.x && bombs_pos_[i].y == player_pos_.y) { player_pos_ = { 0, }; } //캐릭터위치에서 터질경우 if (bombs_pos_[i].y - 1 >= 0) { //위쪽이 터질 경우 if (maze_[bombs_pos_[i].y - 1][bombs_pos_[i].x] == '0') { maze_[bombs_pos_[i].y - 1][bombs_pos_[i].x] = '1'; } else if (bombs_pos_[i].x == player_pos_.x && bombs_pos_[i].y - 1 == player_pos_.y) { player_pos_ = { 0, }; } } if (bombs_pos_[i].y + 1 <= 19) { //아래쪽이 터질 경우 if (maze_[bombs_pos_[i].y + 1][bombs_pos_[i].x] == '0') { maze_[bombs_pos_[i].y + 1][bombs_pos_[i].x] = '1'; } else if (bombs_pos_[i].x == player_pos_.x && bombs_pos_[i].y + 1 == player_pos_.y) { player_pos_ = { 0, }; } } if (bombs_pos_[i].x - 1 >= 0) { //왼쪽이 터질 경우 if (maze_[bombs_pos_[i].y][bombs_pos_[i].x - 1] == '0') { maze_[bombs_pos_[i].y][bombs_pos_[i].x - 1] = '1'; } else if (bombs_pos_[i].x - 1 == player_pos_.x && bombs_pos_[i].y == player_pos_.y) { player_pos_ = { 0, }; } } if (bombs_pos_[i].x + 1 <= 19) { //오른쪽이 터질경우 if (maze_[bombs_pos_[i].y][bombs_pos_[i].x + 1] == '0') { maze_[bombs_pos_[i].y][bombs_pos_[i].x + 1] = '1'; } else if (bombs_pos_[i].x + 1 == player_pos_.x && bombs_pos_[i].y == player_pos_.y) { player_pos_ = { 0, }; } } maze_[bombs_pos_[i].y][bombs_pos_[i].x] = '1'; } plant_bombs_count_ = 0; } bool MazeGame::IsArrived() { return player_pos_.x == end_pos_.x && player_pos_.y == end_pos_.y; } void MazeGame::InputKey(const char input) { if (input == 't' || input == 'T') { createBomb(); } else if (input == 'u' || input == 'U') { fireBomb(); } else { movePlayer(input); } } void MazeGame::UpdateMaze() { for (int i = 0; i < 20; ++i) { for (int j = 0; j < 20; ++j) { if (player_pos_.x == j && player_pos_.y == i) { printf("☆"); } else if (maze_[i][j] == '0') { printf("■"); } else if (maze_[i][j] == '1') { printf(" "); } else if (maze_[i][j] == '2') { printf("○"); } else if (maze_[i][j] == '3') { printf("◎"); } else if (maze_[i][j] == '4') { printf("♨"); } } printf("\n"); } }
[ "melondang3575@gmail.com" ]
melondang3575@gmail.com
9a5136a79113b6504c09d4faaadb6921206a18e9
b061893565193458aeaadf7586d8f3b355a85823
/ADA/ada code/lec1-recurtion/lec1-recurtion/Numbers.h
24e491f6b6dc82977f35abb3b971ae9dd68b60f5
[]
no_license
Javakin/5-semester
aacadfb66d04a4d3b31839fd1482a33b8097808a
852b670b9bcb637311021da5c6740ccdf150e26e
refs/heads/master
2020-12-14T07:31:09.820089
2017-03-02T14:40:03
2017-03-02T14:40:03
68,608,678
1
0
null
null
null
null
UTF-8
C++
false
false
95
h
#pragma once class Numbers { public: Numbers(); int NatNumSum(int number); ~Numbers(); };
[ "danielharaldson@yahoo.com" ]
danielharaldson@yahoo.com
038abbe9322d6611f474b5674c8a1ed638efa807
230965ad63ce46b2884c2a1652b54bdb19b23679
/NeuralCreature/NeuralCreature/RenderManager.cpp
8810583fe14bbad72fc8764c35ce056bbd5ec21c
[]
no_license
jonsor/NeuralJetsonCreature
e6b98301606779c9be1006a95bb6afd058136e31
6b503ee096b5150d3b9bc7ea5f9388de7d509112
refs/heads/master
2021-01-19T04:34:18.450584
2018-04-11T05:38:06
2018-04-11T05:38:06
84,433,043
2
0
null
2017-03-22T14:14:55
2017-03-09T11:11:02
C++
ISO-8859-15
C++
false
false
1,835
cpp
/** RenderManager.cpp Purpose: Sets up and manages the render library OpenGL. @author Sjur Barndon, Jonas Sørsdal @version 1.0 23.03.2017 */ #include "stdafx.h" #include "RenderManager.h" /** Initializes a GLFW render window for the application to draw to. @param width The height of the window in pixels. @param height The width of the window in pixels. */ GLFWwindow* RenderManager::initWindow(GLuint width, GLuint height) { initGLFW(); GLFWwindow* window = glfwCreateWindow(width, height, "Neural Creature", nullptr, nullptr); if (window == nullptr) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return nullptr; } glfwMakeContextCurrent(window); return window; } /** Sets up and initilalizes the GLFW library. */ void RenderManager::initGLFW() { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); glfwWindowHint(GLFW_SAMPLES, 4); // 4x antialiasing glfwSwapInterval(1); } /** Sets up and initializes the Glew library. @param window The applications GLFW render window. */ void RenderManager::initGLEW(GLFWwindow* window) { glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { std::cout << "Failed to initialize GLEW" << std::endl; return; } initView(window); } /** Sets up the viewport and a few other OpenGL options. @param window The applications GLFW render window. */ void RenderManager::initView(GLFWwindow* window) { //Set Viewport int width, height; glfwGetFramebufferSize(window, &width, &height); glViewport(0, 0, width, height); //OpenGL Options glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glEnable(GL_DEPTH_TEST); } RenderManager::~RenderManager() { }
[ "sjurbarndon@gmail.com" ]
sjurbarndon@gmail.com
17876b4657e84fecce0b6f5a515a7b2251da0700
90047daeb462598a924d76ddf4288e832e86417c
/third_party/WebKit/public/web/WebPagePopup.h
bf9fcbec2077ac446de4711b7fd3354255b3fd36
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft" ]
permissive
massbrowser/android
99b8c21fa4552a13c06bbedd0f9c88dd4a4ad080
a9c4371682c9443d6e1d66005d4db61a24a9617c
refs/heads/master
2022-11-04T21:15:50.656802
2017-06-08T12:31:39
2017-06-08T12:31:39
93,747,579
2
2
BSD-3-Clause
2022-10-31T10:34:25
2017-06-08T12:36:07
null
UTF-8
C++
false
false
1,908
h
/* * Copyright (C) 2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef WebPagePopup_h #define WebPagePopup_h #include "../platform/WebCommon.h" #include "WebWidget.h" namespace blink { class WebWidgetClient; class WebPagePopup : public WebWidget { public: BLINK_EXPORT static WebPagePopup* Create(WebWidgetClient*); virtual WebPoint PositionRelativeToOwner() = 0; }; } // namespace blink #endif
[ "xElvis89x@gmail.com" ]
xElvis89x@gmail.com
3558ebe757082e8929f191bcbf83360479748cf7
067690553cf7fa81b5911e8dd4fb405baa96b5b7
/9466/9466.cpp14.cpp
84a40bb41cb017c4373ff288343a893778a7441f
[ "MIT" ]
permissive
isac322/BOJ
4c79aab453c884cb253e7567002fc00e605bc69a
35959dd1a63d75ebca9ed606051f7a649d5c0c7b
refs/heads/master
2021-04-18T22:30:05.273182
2019-02-21T11:36:58
2019-02-21T11:36:58
43,806,421
14
9
null
null
null
null
UTF-8
C++
false
false
807
cpp
#include <cstdio> #include <algorithm> using namespace std; int map[100000]; int t, n, cnt; bool inStack[100000], visit[100000]; int root; bool dfs(int here) { if (visit[here]) return false; inStack[here] = true; int next = map[here]; bool ret; if (visit[next]) { cnt++; ret = false; } else if (inStack[next]) { root = next; ret = next != here; } else if (dfs(next)) { ret = root != here; } else { cnt++; ret = false; } inStack[here] = false; visit[here] = true; return ret; } int main() { scanf("%d", &t); while (t--) { scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", map + i); map[i]--; } fill_n(inStack, n, false); fill_n(visit, n, false); cnt = 0; for (int i = 0; i < n; i++) { root = n; dfs(i); } printf("%d\n", cnt); } }
[ "isac322@naver.com" ]
isac322@naver.com
8962c03322cb207ce0b9c08f2e9bf6c749e32cf9
e5e8b5f43dab1603b9ca91e91b1d5d87f5161c0c
/trafficRecorder/libgo/processer.cpp
5051d08218df315be09cdc4acce0da4bc381b904
[]
no_license
sunxiao2010n/https_tunnel_proxy
5b261443930251a3a3d990be5280d4a17d7d12b4
f97247697c5fd74d6107d9153945edabc4a1eeda
refs/heads/master
2020-03-31T16:52:18.513999
2019-07-26T10:56:14
2019-07-26T10:56:14
152,395,757
5
0
null
null
null
null
UTF-8
C++
false
false
3,267
cpp
#include <libgo/processer.h> #include <libgo/scheduler.h> #include <libgo/error.h> #include <assert.h> namespace co { atomic_t<uint32_t> Processer::s_id_{0}; Processer::Processer() : id_(++s_id_) { runnable_list_.check_ = (void*)&s_id_; } void Processer::AddTaskRunnable(Task *tk) { DebugPrint(dbg_scheduler, "task(%s) add into proc(%u)", tk->DebugInfo(), id_); tk->state_ = TaskState::runnable; runnable_list_.push(tk); } uint32_t Processer::Run(uint32_t &done_count) { ContextScopedGuard guard; (void)guard; done_count = 0; uint32_t c = 0; DebugPrint(dbg_scheduler, "Run [Proc(%d) do_count:%u] --------------------------", id_, (uint32_t)runnable_list_.size()); for (;;) { if (c >= runnable_list_.size()) break; Task *tk = runnable_list_.pop(); if (!tk) break; ++c; current_task_ = tk; DebugPrint(dbg_switch, "enter task(%s)", tk->DebugInfo()); if (!tk->SwapIn()) { fprintf(stderr, "swapcontext error:%s\n", strerror(errno)); current_task_ = nullptr; runnable_list_.erase(tk); tk->DecrementRef(); ThrowError(eCoErrorCode::ec_swapcontext_failed); } DebugPrint(dbg_switch, "leave task(%s) state=%d", tk->DebugInfo(), (int)tk->state_); current_task_ = nullptr; switch (tk->state_) { case TaskState::runnable: runnable_list_.push(tk); break; case TaskState::io_block: g_Scheduler.io_wait_.SchedulerSwitch(tk); break; case TaskState::sleep: g_Scheduler.sleep_wait_.SchedulerSwitch(tk); break; case TaskState::sys_block: assert(tk->block_); if (!tk->block_->AddWaitTask(tk)) runnable_list_.push(tk); break; case TaskState::done: default: ++done_count; DebugPrint(dbg_task, "task(%s) done.", tk->DebugInfo()); if (tk->eptr_) { std::exception_ptr ep = tk->eptr_; tk->DecrementRef(); std::rethrow_exception(ep); } else tk->DecrementRef(); break; } } return c; } void Processer::CoYield() { Task *tk = GetCurrentTask(); assert(tk); tk->proc_ = this; DebugPrint(dbg_yield, "yield task(%s) state=%d", tk->DebugInfo(), (int)tk->state_); ++tk->yield_count_; if (!tk->SwapOut()) { fprintf(stderr, "swapcontext error:%s\n", strerror(errno)); ThrowError(eCoErrorCode::ec_yield_failed); } } Task* Processer::GetCurrentTask() { return current_task_; } std::size_t Processer::StealHalf(Processer & other) { std::size_t runnable_task_count = runnable_list_.size(); SList<Task> tasks = runnable_list_.pop_back((runnable_task_count + 1) / 2); std::size_t c = tasks.size(); DebugPrint(dbg_scheduler, "proc[%u] steal proc[%u] work returns %d.", other.id_, id_, (int)c); if (!c) return 0; other.runnable_list_.push(std::move(tasks)); return c; } } //namespace co
[ "sunxiao2010n@163.com" ]
sunxiao2010n@163.com
cfd4be7a73612f4c28202d77e459660464467223
9f5242ec43c65ba0d032044cf655723a77ddc689
/src/compat/glibc_compat.cpp
34be6d711f6263a0e5c1d1dfab1ef6e650397e21
[ "MIT" ]
permissive
TScoin/Transend
22bb1691dc9b86ca7b9ceb4d9dd1be23eae29e7f
6f8f75dbba962dfe9fc9d85b79cebf20625f871d
refs/heads/master
2021-01-25T13:28:20.681340
2018-10-04T22:45:40
2018-10-04T22:45:40
123,572,575
14
8
MIT
2018-03-14T19:50:15
2018-03-02T11:43:38
C++
UTF-8
C++
false
false
833
cpp
// Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/transend-config.h" #endif #include <cstddef> #if defined(HAVE_SYS_SELECT_H) #include <sys/select.h> #endif // Prior to GLIBC_2.14, memcpy was aliased to memmove. extern "C" void* memmove(void* a, const void* b, size_t c); extern "C" void* memcpy(void* a, const void* b, size_t c) { return memmove(a, b, c); } extern "C" void __chk_fail(void) __attribute__((__noreturn__)); extern "C" FDELT_TYPE __fdelt_warn(FDELT_TYPE a) { if (a >= FD_SETSIZE) __chk_fail(); return a / __NFDBITS; } extern "C" FDELT_TYPE __fdelt_chk(FDELT_TYPE) __attribute__((weak, alias("__fdelt_warn")));
[ "detroit_dentist@transendcoin.com" ]
detroit_dentist@transendcoin.com
d0fdf05820367f4720410cffc35e059d6d202c74
545cbbb97b48f86fd8c2fbea918dd0a78afcd00c
/EulerMain/Solutions/Problem0017.cpp
35237e2629a90152fca58d3726347c800da3d59f
[]
no_license
kmacbeth/projecteuler
a6a4eba2c6874aa7dc044409bc7dfb73767bf6b0
866a2361eb11eae6e27346d671abecb2f4123bfb
refs/heads/master
2022-08-21T15:53:11.947849
2018-01-05T18:20:18
2018-01-05T18:20:18
266,804,050
0
0
null
null
null
null
UTF-8
C++
false
false
2,425
cpp
#include "Problem0017.h" namespace Euler { /** * Problem: Number letter counts * * If the numbers 1 to 5 are written out in words: one, two, three, four, five, * then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. * * If all the numbers from 1 to 1000 (one thousand) inclusive were written out * in words, how many letters would be used? * * NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and * forty-two) contains 23 letters and 115 (one hundred and fifteen) * contains 20 letters. The use of "and" when writing out numbers is in * compliance with British usage. */ void Problem17::Solve() { /** * All numbers name less than 20. */ std::string k20FirstNumberNames[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; /** * All numbers name for every 10. */ std::string k10TenthNumberNames[] = { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; uint32_t result = 0; for(uint32_t i = 1; i < 1001; ++i) { std::stringstream number; if(i == 1000) { number << "onethousand"; } // Hundreds if(i % 1000 > 99) { number << k20FirstNumberNames[(i % 1000) / 100] << "hundred"; if(i % 100 > 0) { number << "and"; } } // Below one hundred if(i % 100 > 0) { if(i % 100 < 20) { number << k20FirstNumberNames[i % 100]; } else { number << k10TenthNumberNames[(i % 100) / 10]; if(i % 10 > 0) { number << k20FirstNumberNames[i % 10]; } } } // Accumulate strings length result += number.str().length(); } SetAnswer(result); } }
[ "martin.lafreniere@gmail.com" ]
martin.lafreniere@gmail.com
15e8cbe52fc64a25a80bae1da759d7fea3f99230
a6c493fc02f380852a334612e7a97604853c07f5
/646.最长数对链.cpp
95c141387fa99c016d37acc4e94ad70a21a3253d
[]
no_license
PanAndy/leetcode-c-
e66b1f82bdf360e027feb9d363743ddb5695c1b7
5d03bb555e3c28f0348a5205ecae30e4b28cee8a
refs/heads/master
2021-04-10T21:07:40.667185
2020-08-04T09:54:24
2020-08-04T09:54:24
248,966,072
0
0
null
null
null
null
UTF-8
C++
false
false
815
cpp
/* * @lc app=leetcode.cn id=646 lang=cpp * * [646] 最长数对链 */ // @lc code=start #include<iostream> #include<vector> #include<algorithm> using namespace std; class Solution { public: int findLongestChain(vector<vector<int>>& pairs) { int n = pairs.size(); if(n==0)return 0; sort(pairs.begin(), pairs.end(), cmp); vector<int> dp(n, 1); int ans = 0; for(int i=0;i<n;i++) { for(int j=0;j<i;j++) { if(pairs[i][0] > pairs[j][1]) dp[i] = max(dp[i], dp[j]+1); } ans = max(ans, dp[i]); } return ans; } static bool cmp(vector<int> &a, vector<int> &b) { return a[0] == b[0] ? a[1] < b[1] : a[0] < b[0]; } }; // @lc code=end
[ "1163962054@qq.com" ]
1163962054@qq.com
d882a8f1750014dfe10b5a6ccbdbd254534f8d35
9cf37e2f2878d44aacfa1023fde75873f394ae49
/code/data_structures/segment_tree_iterative.h
0fbedcc2503aedad452c89807533ac57535f0ec3
[]
no_license
LeticiaFCS/Competitive-Programming-Notebook
938e1eec25b9181f971d1281e3721b1d56643351
f52b6c9660a77a1fc2aef776b6cd146e03228f3b
refs/heads/master
2022-12-21T09:51:28.509805
2020-09-17T19:37:07
2020-09-17T19:37:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
898
h
#include <bits/stdc++.h> using namespace std; class SegTreeIterative{ private: typedef long long Node; Node neutral = 0; vector<Node> st; int n; inline Node join(Node a, Node b){ return a + b; } public: template <class MyIterator> SegTreeIterative(MyIterator begin, MyIterator end){ int sz = end - begin; for (n = 1; n < sz; n <<= 1); st.assign(n << 1, neutral); for (int i = 0; i < sz; i++, begin++) st[i + n] = (*begin); for (int i = n + sz - 1; i > 1; i--) st[i >> 1] = join(st[i >> 1], st[i]); } //0-indexed void update(int i, Node x){ st[i += n] = x; for (i >>= 1; i; i >>= 1) st[i] = join(st[i << 1], st[1 + (i << 1)]); } //0-indexed [l, r] Node query(int l, int r){ Node ans = neutral; for (l += n, r += n + 1; l < r; l >>= 1, r >>= 1){ if (l & 1) ans = join(ans, st[l++]); if (r & 1) ans = join(ans, st[--r]); } return ans; } };
[ "paulomirandamss12@gmail.com" ]
paulomirandamss12@gmail.com
a517ab2027a5b207d94e8e806b4adf7243880ddc
d6a0942ed0d761e032f8c1bcafcf4f54387d7bff
/src/qt/dreamteam3.cpp
dca833f268371ff9f6c8c1aebd6f006b0b20578e
[ "MIT" ]
permissive
DreamTeamCoin3/dreamteam3
a6cc144b6672e86b98a1507b0e08a89da6cdb0da
7c329f177e32c6919d52a0dd64835a6b9eec63f5
refs/heads/master
2021-06-27T17:31:50.901731
2020-11-03T21:48:19
2020-11-03T21:48:19
178,424,442
5
4
MIT
2020-11-03T21:48:21
2019-03-29T14:52:12
C++
UTF-8
C++
false
false
23,452
cpp
// Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/dreamteam3-config.h" #endif #include "bitcoingui.h" #include "clientmodel.h" #include "guiconstants.h" #include "guiutil.h" #include "intro.h" #include "net.h" #include "networkstyle.h" #include "optionsmodel.h" #include "splashscreen.h" #include "utilitydialog.h" #include "winshutdownmonitor.h" #ifdef ENABLE_WALLET #include "paymentserver.h" #include "walletmodel.h" #endif #include "masternodeconfig.h" #include "init.h" #include "main.h" #include "rpcserver.h" #include "ui_interface.h" #include "util.h" #ifdef ENABLE_WALLET #include "wallet.h" #endif #include <stdint.h> #include <boost/filesystem/operations.hpp> #include <boost/thread.hpp> #include <QApplication> #include <QDebug> #include <QLibraryInfo> #include <QLocale> #include <QMessageBox> #include <QProcess> #include <QSettings> #include <QThread> #include <QTimer> #include <QTranslator> #if defined(QT_STATICPLUGIN) #include <QtPlugin> #if QT_VERSION < 0x050000 Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) Q_IMPORT_PLUGIN(qtaccessiblewidgets) #else #if QT_VERSION < 0x050400 Q_IMPORT_PLUGIN(AccessibleFactory) #endif #if defined(QT_QPA_PLATFORM_XCB) Q_IMPORT_PLUGIN(QXcbIntegrationPlugin); #elif defined(QT_QPA_PLATFORM_WINDOWS) Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin); #elif defined(QT_QPA_PLATFORM_COCOA) Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin); #endif #endif #endif #if QT_VERSION < 0x050000 #include <QTextCodec> #endif // Declare meta types used for QMetaObject::invokeMethod Q_DECLARE_METATYPE(bool*) Q_DECLARE_METATYPE(CAmount) static void InitMessage(const std::string& message) { LogPrintf("init message: %s\n", message); } /* Translate string to current locale using Qt. */ static std::string Translate(const char* psz) { return QCoreApplication::translate("dreamteam3-core", psz).toStdString(); } static QString GetLangTerritory() { QSettings settings; // Get desired locale (e.g. "de_DE") // 1) System default language QString lang_territory = QLocale::system().name(); // 2) Language from QSettings QString lang_territory_qsettings = settings.value("language", "").toString(); if (!lang_territory_qsettings.isEmpty()) lang_territory = lang_territory_qsettings; // 3) -lang command line argument lang_territory = QString::fromStdString(GetArg("-lang", lang_territory.toStdString())); return lang_territory; } /** Set up translations */ static void initTranslations(QTranslator& qtTranslatorBase, QTranslator& qtTranslator, QTranslator& translatorBase, QTranslator& translator) { // Remove old translators QApplication::removeTranslator(&qtTranslatorBase); QApplication::removeTranslator(&qtTranslator); QApplication::removeTranslator(&translatorBase); QApplication::removeTranslator(&translator); // Get desired locale (e.g. "de_DE") // 1) System default language QString lang_territory = GetLangTerritory(); // Convert to "de" only by truncating "_DE" QString lang = lang_territory; lang.truncate(lang_territory.lastIndexOf('_')); // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator // Load e.g. qt_de.qm if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) QApplication::installTranslator(&qtTranslatorBase); // Load e.g. qt_de_DE.qm if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) QApplication::installTranslator(&qtTranslator); // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in dreamteam3.qrc) if (translatorBase.load(lang, ":/translations/")) QApplication::installTranslator(&translatorBase); // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in dreamteam3.qrc) if (translator.load(lang_territory, ":/translations/")) QApplication::installTranslator(&translator); } /* qDebug() message handler --> debug.log */ #if QT_VERSION < 0x050000 void DebugMessageHandler(QtMsgType type, const char* msg) { const char* category = (type == QtDebugMsg) ? "qt" : NULL; LogPrint(category, "GUI: %s\n", msg); } #else void DebugMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString& msg) { Q_UNUSED(context); const char* category = (type == QtDebugMsg) ? "qt" : NULL; LogPrint(category, "GUI: %s\n", msg.toStdString()); } #endif /** Class encapsulating DreamTeam3 Core startup and shutdown. * Allows running startup and shutdown in a different thread from the UI thread. */ class BitcoinCore : public QObject { Q_OBJECT public: explicit BitcoinCore(); public slots: void initialize(); void shutdown(); void restart(QStringList args); signals: void initializeResult(int retval); void shutdownResult(int retval); void runawayException(const QString& message); private: boost::thread_group threadGroup; /// Flag indicating a restart bool execute_restart; /// Pass fatal exception message to UI thread void handleRunawayException(std::exception* e); }; /** Main DreamTeam3 application object */ class BitcoinApplication : public QApplication { Q_OBJECT public: explicit BitcoinApplication(int& argc, char** argv); ~BitcoinApplication(); #ifdef ENABLE_WALLET /// Create payment server void createPaymentServer(); #endif /// Create options model void createOptionsModel(); /// Create main window void createWindow(const NetworkStyle* networkStyle); /// Create splash screen void createSplashScreen(const NetworkStyle* networkStyle); /// Request core initialization void requestInitialize(); /// Request core shutdown void requestShutdown(); /// Get process return value int getReturnValue() { return returnValue; } /// Get window identifier of QMainWindow (BitcoinGUI) WId getMainWinId() const; public slots: void initializeResult(int retval); void shutdownResult(int retval); /// Handle runaway exceptions. Shows a message box with the problem and quits the program. void handleRunawayException(const QString& message); signals: void requestedInitialize(); void requestedRestart(QStringList args); void requestedShutdown(); void stopThread(); void splashFinished(QWidget* window); private: QThread* coreThread; OptionsModel* optionsModel; ClientModel* clientModel; BitcoinGUI* window; QTimer* pollShutdownTimer; #ifdef ENABLE_WALLET PaymentServer* paymentServer; WalletModel* walletModel; #endif int returnValue; void startThread(); }; #include "dreamteam3.moc" BitcoinCore::BitcoinCore() : QObject() { } void BitcoinCore::handleRunawayException(std::exception* e) { PrintExceptionContinue(e, "Runaway exception"); emit runawayException(QString::fromStdString(strMiscWarning)); } void BitcoinCore::initialize() { execute_restart = true; try { qDebug() << __func__ << ": Running AppInit2 in thread"; int rv = AppInit2(threadGroup); if (rv) { /* Start a dummy RPC thread if no RPC thread is active yet * to handle timeouts. */ StartDummyRPCThread(); } emit initializeResult(rv); } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } } void BitcoinCore::restart(QStringList args) { if (execute_restart) { // Only restart 1x, no matter how often a user clicks on a restart-button execute_restart = false; try { qDebug() << __func__ << ": Running Restart in thread"; threadGroup.interrupt_all(); threadGroup.join_all(); PrepareShutdown(); qDebug() << __func__ << ": Shutdown finished"; emit shutdownResult(1); CExplicitNetCleanup::callCleanup(); QProcess::startDetached(QApplication::applicationFilePath(), args); qDebug() << __func__ << ": Restart initiated..."; QApplication::quit(); } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } } } void BitcoinCore::shutdown() { try { qDebug() << __func__ << ": Running Shutdown in thread"; threadGroup.interrupt_all(); threadGroup.join_all(); Shutdown(); qDebug() << __func__ << ": Shutdown finished"; emit shutdownResult(1); } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } } BitcoinApplication::BitcoinApplication(int& argc, char** argv) : QApplication(argc, argv), coreThread(0), optionsModel(0), clientModel(0), window(0), pollShutdownTimer(0), #ifdef ENABLE_WALLET paymentServer(0), walletModel(0), #endif returnValue(0) { setQuitOnLastWindowClosed(false); } BitcoinApplication::~BitcoinApplication() { if (coreThread) { qDebug() << __func__ << ": Stopping thread"; emit stopThread(); coreThread->wait(); qDebug() << __func__ << ": Stopped thread"; } delete window; window = 0; #ifdef ENABLE_WALLET delete paymentServer; paymentServer = 0; #endif // Delete Qt-settings if user clicked on "Reset Options" QSettings settings; if (optionsModel && optionsModel->resetSettings) { settings.clear(); settings.sync(); } delete optionsModel; optionsModel = 0; } #ifdef ENABLE_WALLET void BitcoinApplication::createPaymentServer() { paymentServer = new PaymentServer(this); } #endif void BitcoinApplication::createOptionsModel() { optionsModel = new OptionsModel(); } void BitcoinApplication::createWindow(const NetworkStyle* networkStyle) { window = new BitcoinGUI(networkStyle, 0); pollShutdownTimer = new QTimer(window); connect(pollShutdownTimer, SIGNAL(timeout()), window, SLOT(detectShutdown())); pollShutdownTimer->start(200); } void BitcoinApplication::createSplashScreen(const NetworkStyle* networkStyle) { SplashScreen* splash = new SplashScreen(0, networkStyle); // We don't hold a direct pointer to the splash screen after creation, so use // Qt::WA_DeleteOnClose to make sure that the window will be deleted eventually. splash->setAttribute(Qt::WA_DeleteOnClose); splash->show(); connect(this, SIGNAL(splashFinished(QWidget*)), splash, SLOT(slotFinish(QWidget*))); } void BitcoinApplication::startThread() { if (coreThread) return; coreThread = new QThread(this); BitcoinCore* executor = new BitcoinCore(); executor->moveToThread(coreThread); /* communication to and from thread */ connect(executor, SIGNAL(initializeResult(int)), this, SLOT(initializeResult(int))); connect(executor, SIGNAL(shutdownResult(int)), this, SLOT(shutdownResult(int))); connect(executor, SIGNAL(runawayException(QString)), this, SLOT(handleRunawayException(QString))); connect(this, SIGNAL(requestedInitialize()), executor, SLOT(initialize())); connect(this, SIGNAL(requestedShutdown()), executor, SLOT(shutdown())); connect(window, SIGNAL(requestedRestart(QStringList)), executor, SLOT(restart(QStringList))); /* make sure executor object is deleted in its own thread */ connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater())); connect(this, SIGNAL(stopThread()), coreThread, SLOT(quit())); coreThread->start(); } void BitcoinApplication::requestInitialize() { qDebug() << __func__ << ": Requesting initialize"; startThread(); emit requestedInitialize(); } void BitcoinApplication::requestShutdown() { qDebug() << __func__ << ": Requesting shutdown"; startThread(); window->hide(); window->setClientModel(0); pollShutdownTimer->stop(); #ifdef ENABLE_WALLET window->removeAllWallets(); delete walletModel; walletModel = 0; #endif delete clientModel; clientModel = 0; // Show a simple window indicating shutdown status ShutdownWindow::showShutdownWindow(window); // Request shutdown from core thread emit requestedShutdown(); } void BitcoinApplication::initializeResult(int retval) { qDebug() << __func__ << ": Initialization result: " << retval; // Set exit result: 0 if successful, 1 if failure returnValue = retval ? 0 : 1; if (retval) { #ifdef ENABLE_WALLET PaymentServer::LoadRootCAs(); paymentServer->setOptionsModel(optionsModel); #endif clientModel = new ClientModel(optionsModel); window->setClientModel(clientModel); #ifdef ENABLE_WALLET if (pwalletMain) { walletModel = new WalletModel(pwalletMain, optionsModel); window->addWallet(BitcoinGUI::DEFAULT_WALLET, walletModel); window->setCurrentWallet(BitcoinGUI::DEFAULT_WALLET); connect(walletModel, SIGNAL(coinsSent(CWallet*, SendCoinsRecipient, QByteArray)), paymentServer, SLOT(fetchPaymentACK(CWallet*, const SendCoinsRecipient&, QByteArray))); } #endif // If -min option passed, start window minimized. if (GetBoolArg("-min", false)) { window->showMinimized(); } else { window->show(); } emit splashFinished(window); #ifdef ENABLE_WALLET // Now that initialization/startup is done, process any command-line // DreamTeam3: URIs or payment requests: connect(paymentServer, SIGNAL(receivedPaymentRequest(SendCoinsRecipient)), window, SLOT(handlePaymentRequest(SendCoinsRecipient))); connect(window, SIGNAL(receivedURI(QString)), paymentServer, SLOT(handleURIOrFile(QString))); connect(paymentServer, SIGNAL(message(QString, QString, unsigned int)), window, SLOT(message(QString, QString, unsigned int))); QTimer::singleShot(100, paymentServer, SLOT(uiReady())); #endif } else { quit(); // Exit main loop } } void BitcoinApplication::shutdownResult(int retval) { qDebug() << __func__ << ": Shutdown result: " << retval; quit(); // Exit main loop after shutdown finished } void BitcoinApplication::handleRunawayException(const QString& message) { QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. DreamTeam3 can no longer continue safely and will quit.") + QString("\n\n") + message); ::exit(1); } WId BitcoinApplication::getMainWinId() const { if (!window) return 0; return window->winId(); } #ifndef BITCOIN_QT_TEST int main(int argc, char* argv[]) { SetupEnvironment(); /// 1. Parse command-line options. These take precedence over anything else. // Command-line options take precedence: ParseParameters(argc, argv); // Do not refer to data directory yet, this can be overridden by Intro::pickDataDirectory /// 2. Basic Qt initialization (not dependent on parameters or configuration) #if QT_VERSION < 0x050000 // Internal string conversion is all UTF-8 QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); #endif Q_INIT_RESOURCE(dreamteam3_locale); Q_INIT_RESOURCE(dreamteam3); BitcoinApplication app(argc, argv); #if QT_VERSION > 0x050100 // Generate high-dpi pixmaps QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); #endif #if QT_VERSION >= 0x050600 QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif #ifdef Q_OS_MAC QApplication::setAttribute(Qt::AA_DontShowIconsInMenus); #endif // Register meta types used for QMetaObject::invokeMethod qRegisterMetaType<bool*>(); // Need to pass name here as CAmount is a typedef (see http://qt-project.org/doc/qt-5/qmetatype.html#qRegisterMetaType) // IMPORTANT if it is no longer a typedef use the normal variant above qRegisterMetaType<CAmount>("CAmount"); /// 3. Application identification // must be set before OptionsModel is initialized or translations are loaded, // as it is used to locate QSettings QApplication::setOrganizationName(QAPP_ORG_NAME); QApplication::setOrganizationDomain(QAPP_ORG_DOMAIN); QApplication::setApplicationName(QAPP_APP_NAME_DEFAULT); GUIUtil::SubstituteFonts(GetLangTerritory()); /// 4. Initialization of translations, so that intro dialog is in user's language // Now that QSettings are accessible, initialize translations QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; initTranslations(qtTranslatorBase, qtTranslator, translatorBase, translator); uiInterface.Translate.connect(Translate); #ifdef Q_OS_MAC #if __clang_major__ < 4 QString s = QSysInfo::kernelVersion(); std::string ver_info = s.toStdString(); // ver_info will be like 17.2.0 for High Sierra. Check if true and exit if build via cross-compile if (ver_info[0] == '1' && ver_info[1] == '7') { QMessageBox::critical(0, "Unsupported", BitcoinGUI::tr("High Sierra not supported with this build") + QString("\n\n")); ::exit(1); } #endif #endif // Show help message immediately after parsing command-line options (for "-lang") and setting locale, // but before showing splash screen. if (mapArgs.count("-?") || mapArgs.count("-help") || mapArgs.count("-version")) { HelpMessageDialog help(NULL, mapArgs.count("-version")); help.showOrPrint(); return 1; } /// 5. Now that settings and translations are available, ask user for data directory // User language is set up: pick a data directory if (!Intro::pickDataDirectory()) return 0; /// 6. Determine availability of data directory and parse dreamteam3.conf /// - Do not call GetDataDir(true) before this step finishes if (!boost::filesystem::is_directory(GetDataDir(false))) { QMessageBox::critical(0, QObject::tr("DreamTeam3 Core"), QObject::tr("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"]))); return 1; } try { ReadConfigFile(mapArgs, mapMultiArgs); } catch (std::exception& e) { QMessageBox::critical(0, QObject::tr("DreamTeam3 Core"), QObject::tr("Error: Cannot parse configuration file: %1. Only use key=value syntax.").arg(e.what())); return 0; } /// 7. Determine network (and switch to network specific options) // - Do not call Params() before this step // - Do this after parsing the configuration file, as the network can be switched there // - QSettings() will use the new application name after this, resulting in network-specific settings // - Needs to be done before createOptionsModel // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) if (!SelectParamsFromCommandLine()) { QMessageBox::critical(0, QObject::tr("DreamTeam3 Core"), QObject::tr("Error: Invalid combination of -regtest and -testnet.")); return 1; } #ifdef ENABLE_WALLET // Parse URIs on command line -- this can affect Params() PaymentServer::ipcParseCommandLine(argc, argv); #endif QScopedPointer<const NetworkStyle> networkStyle(NetworkStyle::instantiate(QString::fromStdString(Params().NetworkIDString()))); assert(!networkStyle.isNull()); // Allow for separate UI settings for testnets QApplication::setApplicationName(networkStyle->getAppName()); // Re-initialize translations after changing application name (language in network-specific settings can be different) initTranslations(qtTranslatorBase, qtTranslator, translatorBase, translator); #ifdef ENABLE_WALLET /// 7a. parse masternode.conf string strErr; if (!masternodeConfig.read(strErr)) { QMessageBox::critical(0, QObject::tr("DreamTeam3 Core"), QObject::tr("Error reading masternode configuration file: %1").arg(strErr.c_str())); return 0; } /// 8. URI IPC sending // - Do this early as we don't want to bother initializing if we are just calling IPC // - Do this *after* setting up the data directory, as the data directory hash is used in the name // of the server. // - Do this after creating app and setting up translations, so errors are // translated properly. if (PaymentServer::ipcSendCommandLine()) exit(0); // Start up the payment server early, too, so impatient users that click on // dreamteam3: links repeatedly have their payment requests routed to this process: app.createPaymentServer(); #endif /// 9. Main GUI initialization // Install global event filter that makes sure that long tooltips can be word-wrapped app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); #if QT_VERSION < 0x050000 // Install qDebug() message handler to route to debug.log qInstallMsgHandler(DebugMessageHandler); #else #if defined(Q_OS_WIN) // Install global event filter for processing Windows session related Windows messages (WM_QUERYENDSESSION and WM_ENDSESSION) qApp->installNativeEventFilter(new WinShutdownMonitor()); #endif // Install qDebug() message handler to route to debug.log qInstallMessageHandler(DebugMessageHandler); #endif // Load GUI settings from QSettings app.createOptionsModel(); // Subscribe to global signals from core uiInterface.InitMessage.connect(InitMessage); if (GetBoolArg("-splash", true) && !GetBoolArg("-min", false)) app.createSplashScreen(networkStyle.data()); try { app.createWindow(networkStyle.data()); app.requestInitialize(); #if defined(Q_OS_WIN) && QT_VERSION >= 0x050000 WinShutdownMonitor::registerShutdownBlockReason(QObject::tr("DreamTeam3 Core didn't yet exit safely..."), (HWND)app.getMainWinId()); #endif app.exec(); app.requestShutdown(); app.exec(); } catch (std::exception& e) { PrintExceptionContinue(&e, "Runaway exception"); app.handleRunawayException(QString::fromStdString(strMiscWarning)); } catch (...) { PrintExceptionContinue(NULL, "Runaway exception"); app.handleRunawayException(QString::fromStdString(strMiscWarning)); } return app.getReturnValue(); } #endif // BITCOIN_QT_TEST
[ "root@localhost" ]
root@localhost
5d71cb3ea50c0a8539a75962c1573fb1e6acbaf4
31ac07ecd9225639bee0d08d00f037bd511e9552
/externals/OCCTLib/inc/Handle_Storage_HSeqOfCallBack.hxx
339274366dd08a0f1e973070d93bf48004be72e1
[]
no_license
litao1009/SimpleRoom
4520e0034e4f90b81b922657b27f201842e68e8e
287de738c10b86ff8f61b15e3b8afdfedbcb2211
refs/heads/master
2021-01-20T19:56:39.507899
2016-07-29T08:01:57
2016-07-29T08:01:57
64,462,604
1
0
null
null
null
null
UTF-8
C++
false
false
782
hxx
// This file is generated by WOK (CPPExt). // Please do not edit this file; modify original file instead. // The copyright and license terms as defined for the original file apply to // this header file considered to be the "object code" form of the original source. #ifndef _Handle_Storage_HSeqOfCallBack_HeaderFile #define _Handle_Storage_HSeqOfCallBack_HeaderFile #ifndef _Standard_HeaderFile #include <Standard.hxx> #endif #ifndef _Standard_DefineHandle_HeaderFile #include <Standard_DefineHandle.hxx> #endif #ifndef _Handle_MMgt_TShared_HeaderFile #include <Handle_MMgt_TShared.hxx> #endif class Standard_Transient; class Handle(Standard_Type); class Handle(MMgt_TShared); class Storage_HSeqOfCallBack; DEFINE_STANDARD_HANDLE(Storage_HSeqOfCallBack,MMgt_TShared) #endif
[ "litao1009@gmail.com" ]
litao1009@gmail.com
2808aa4cd34cd51c64aab1bf82b3bfdf1e2c3493
992bd8e162834d1e10ba073df690615929ed5809
/C++ practice/STL/lesson2.h
3bb5c5576a1c43fe70cfbd0530113f128b27c0da
[]
no_license
MyCuteGuineaPig/practice
f35b335ccd98e53dce81465e509a42b2adfe65b2
9e1cb91c1bce4648a004a5492af05b5f964bb057
refs/heads/master
2023-03-01T01:12:21.691650
2021-01-28T05:25:12
2021-01-28T05:25:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,973
h
#ifndef LESSON2_H #define LESSON2_H /* 1. sequence containers(array and linked list) -vector, deque, list, forward list, arrary 2. Associate containers // typically run the binary tree - set, multiset, - map, multimap 3. unordered Containers(hash table) - unordered set / multiset - unordered map/ multimap */ #include <vector> #include <deque> #include <list> #include <set> // set and multiset #include <map> // map and multimap #include <unordered_set> // unordered set// multiset #include <unordered_map> // unordered map// mutlimap #include <iterator> #include <algorithm> #include <numeric> // some numeric algorithm #include <functional> #include <iostream> #include <array> void lesson_2(){ vector<int>vec; // initial vector size = 0 vec.push_back(4); vec.push_back(1); vec.push_back(8); cout <<vec[2] << endl; // 8 no range check cout << vec.at(2)<<endl; // 8 throw range_error exception of out of range //traverse vector for (unsigned i=0; i<vec.size();i++) cout << vec[i] << " "; for (vector<int>::iterator itr = vec.begin(); itr!=vec.end(); itr++) cout << * itr << endl; // this way is faster than vec[i], aslo this is the universal way to choose container //for (it:vec) C++ 11 // cout << it << endl; //vector is a dynamically allocated contiguous array in memory // none of other container is contiguous array in memory int *p = &vec[0]; p[2] =6; // so we can use p just as regular array p[2] =6 if (vec.empty()) {cout<<"vector size is 0 "<<endl;} cout <<"vec size "<<vec.size()<<endl; // 3 vector<int>vec2(vec); // copy constructor vec2, {4,1,8} vec.clear(); //remove all items in vec, vec.size() == 0 vec2.swap(vec); // v2 becomes empty, vec hs 3 items // Notes; No penalty of abstraction, very efficient /* property of vector 1. fast insert/remove at the end O(1) 2. slow insert/remove at the beginning or in the middle O(n) 要把insert 之后的往后推一位 3. slow search O(n) */ cout<<"-------------------------------DEQUE-----------------------"<<endl; // vector can only grow in the end and deque can grow in the end and in the beginning //deque<int> deq = {4,5,7}; deque<int>deq; deq.push_front(2); // {2,4,5,7} deq.push_front(3); // {2,4,6,7,3} // Deque has the same interface as vector cout << deq[1]<<endl;; // 4 /* Properties 1. fast insert/remove at the beginning and the end 2. slow insert/ remove in the middle 3. slow search O(n); */ //list is double linked list //fast remove and replace in the place //list<int>mylist = {5,2,9}; list<int>mylist; mylist.push_back(5); mylist.push_back(2); mylist.push_back(9); mylist.push_back(6); mylist.push_front(4); // {4,5,2,9,6} list<int>::iterator itr = find(mylist.begin(),mylist.end(),2); //itr-->2 mylist.insert(itr, 8); //{4,5,8,2,9,6}, 在这个iterator 前面insert //insertation O(1), faster than vector/deque itr++; // itr->9; mylist.erase(itr); // {4,8,5,2,6} // O(1) very fast /* 1. fast insert/remove at any place O(1) 2.slow search O(n) slower than vector, // vector is contiguous allocated, each elements in the list is stored at different place 3. no random access, no [] opearator list has two more pointers than elements, so list will use much more memory mylist1.splice(itr,mylist2, itr_a,itr_b), itr_a and itr_b is iterator defined for list2 so I can cut the function from list2 itr_a to itr_b insert to list1 O(1), no other vector can take advantage of that */ /*forward list you can only traverse from the beginning to end, only one way not from end to beginning */ /*Array Array container if I have a array and do begin, end, size, swap disadvantage 1. cannot change size, 2. different type array<int,3> a = {3,4,5}; array<int,4> b = {3,4,5}; A function if take a cannot take b, because they are two different types */ //int a[3] = {3,4,5} array<int,3> a = {3,4,5}; // size is 3 a.begin(); } #endif
[ "beckswu@gmail.com" ]
beckswu@gmail.com
6737ca36761a8364e83bfbd4c07615479bee8b3a
22c2aef230cf5cd2409f1e8459fee4f995415c7d
/boj_code/1100/1181.cpp
f56eae35fee0a14c947977b56f5bc7ce710e7666
[]
no_license
sinkyoungdeok/Algorithm
54c11050fd5d3ab7a0bc009d38065a590d21e129
0d14e417686db1aa7cc2ade39c55db7d8e16fece
refs/heads/master
2020-04-29T11:41:04.457631
2019-10-13T14:25:54
2019-10-13T14:25:54
176,108,085
3
0
null
null
null
null
UTF-8
C++
false
false
722
cpp
#include <cstdio> #include <algorithm> #include <iostream> #include <string> #include <cmath> #include <cstring> #include <queue> #include <vector> using namespace std; struct A { string name; int len; }; class comp { public: bool operator() (A a1, A a2) { if (a1.len > a2.len) return true; else if (a1.len == a2.len) { return a1.name > a2.name; } else return false; } }; int main() { priority_queue<A, vector<A>, comp> pq; int n; cin >> n; while (n--) { A a; cin >> a.name; a.len = a.name.length(); pq.push(a); } string prevname; while (!pq.empty()) { A tmp = pq.top(); pq.pop(); if(tmp.name != prevname) cout << tmp.name << endl; prevname = tmp.name; } return 0; }
[ "noreply@github.com" ]
noreply@github.com
40ca07231121102cbf55e644b2221852fb4f5583
dd5b0394f8ccdac8c60a6d96b3c7ddf33a3ed3e4
/src/components/header/Color.h
09c8404638628dc1383a04d2c2a529baa22f9847
[]
no_license
mad-anne/SI_lab_2
5b3bc471243e335a87b1af0827abdaa1fde1f365
b1f2eadcbebca43866f7974e98aac054ba8c2eb7
refs/heads/master
2021-01-19T07:18:15.704796
2017-04-19T08:37:07
2017-04-19T08:37:07
87,534,597
0
0
null
null
null
null
UTF-8
C++
false
false
331
h
// // Created by Anna Siwik on 2017-04-07. // #ifndef SI_LAB_2_COLOR_H #define SI_LAB_2_COLOR_H #include "../interface/IValue.h" class Color : public IValue { public: Color(int); ~Color(); IValue* deepCopy() const override; const int getValue() const override; }; #endif //SI_LAB_2_COLOR_H
[ "221026@student.pwr.edu.pl" ]
221026@student.pwr.edu.pl
d29ec116a95b103bc574fa34c816779a8cf07f48
a54f23240f3c2dd0d35610e388e392ee1bfe38ce
/cpp_src/vendor/yaml-cpp/nodebuilder.cpp
505296b69ae8d43a1de6b7b0a4d6e52f0741b062
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
oruchreis/reindexer
9ace9725658d30c747043946bec1b5745aebbb3a
3f1be27b389907f2bdd8ad8e4367773bd539571c
refs/heads/master
2023-05-25T04:32:59.452507
2023-01-06T12:47:11
2023-05-22T13:33:56
252,735,504
0
1
Apache-2.0
2020-04-03T13:10:22
2020-04-03T13:10:22
null
UTF-8
C++
false
false
2,999
cpp
#include <cassert> #include "nodebuilder.h" #include "yaml-cpp/node/detail/node.h" #include "yaml-cpp/node/impl.h" #include "yaml-cpp/node/node.h" #include "yaml-cpp/node/type.h" namespace YAML { struct Mark; NodeBuilder::NodeBuilder() : m_pMemory(new detail::memory_holder), m_pRoot(nullptr), m_stack{}, m_anchors{}, m_keys{}, m_mapDepth(0) { m_anchors.push_back(nullptr); // since the anchors start at 1 } NodeBuilder::~NodeBuilder() = default; Node NodeBuilder::Root() { if (!m_pRoot) return Node(); return Node(*m_pRoot, m_pMemory); } void NodeBuilder::OnDocumentStart(const Mark&) {} void NodeBuilder::OnDocumentEnd() {} void NodeBuilder::OnNull(const Mark& mark, anchor_t anchor) { detail::node& node = Push(mark, anchor); node.set_null(); Pop(); } void NodeBuilder::OnAlias(const Mark& /* mark */, anchor_t anchor) { detail::node& node = *m_anchors[anchor]; Push(node); Pop(); } void NodeBuilder::OnScalar(const Mark& mark, const std::string& tag, anchor_t anchor, const std::string& value) { detail::node& node = Push(mark, anchor); node.set_scalar(value); node.set_tag(tag); Pop(); } void NodeBuilder::OnSequenceStart(const Mark& mark, const std::string& tag, anchor_t anchor, EmitterStyle::value style) { detail::node& node = Push(mark, anchor); node.set_tag(tag); node.set_type(NodeType::Sequence); node.set_style(style); } void NodeBuilder::OnSequenceEnd() { Pop(); } void NodeBuilder::OnMapStart(const Mark& mark, const std::string& tag, anchor_t anchor, EmitterStyle::value style) { detail::node& node = Push(mark, anchor); node.set_type(NodeType::Map); node.set_tag(tag); node.set_style(style); m_mapDepth++; } void NodeBuilder::OnMapEnd() { assert(m_mapDepth > 0); m_mapDepth--; Pop(); } detail::node& NodeBuilder::Push(const Mark& mark, anchor_t anchor) { detail::node& node = m_pMemory->create_node(); node.set_mark(mark); RegisterAnchor(anchor, node); Push(node); return node; } void NodeBuilder::Push(detail::node& node) { const bool needsKey = (!m_stack.empty() && m_stack.back()->type() == NodeType::Map && m_keys.size() < m_mapDepth); m_stack.push_back(&node); if (needsKey) m_keys.emplace_back(&node, false); } void NodeBuilder::Pop() { assert(!m_stack.empty()); if (m_stack.size() == 1) { m_pRoot = m_stack[0]; m_stack.pop_back(); return; } detail::node& node = *m_stack.back(); m_stack.pop_back(); detail::node& collection = *m_stack.back(); if (collection.type() == NodeType::Sequence) { collection.push_back(node, m_pMemory); } else if (collection.type() == NodeType::Map) { assert(!m_keys.empty()); PushedKey& key = m_keys.back(); if (key.second) { collection.insert(*key.first, node, m_pMemory); m_keys.pop_back(); } else { key.second = true; } } else { assert(false); m_stack.clear(); } } void NodeBuilder::RegisterAnchor(anchor_t anchor, detail::node& node) { if (anchor) { assert(anchor == m_anchors.size()); m_anchors.push_back(&node); } } } // namespace YAML
[ "57798122+graveart@users.noreply.github.com" ]
57798122+graveart@users.noreply.github.com
0e0c91edc76735aa6888854d714e026d4788763d
582f2cc0cdbff7240741e2a5c3ece1f1dcee282c
/Codeforces/PastContests/1277/C.cpp
7e64fc3c2660bc6ab0240f8c304974435f0c9964
[]
no_license
moondemon68/cp
7593057a124cdef51341bf75fb780a9b03b8ea12
3b5ebd39783253348763ea58f7e84608679c17c3
refs/heads/master
2022-02-23T21:04:30.962383
2022-02-04T16:31:41
2022-02-04T16:31:41
149,121,917
0
1
null
null
null
null
UTF-8
C++
false
false
1,352
cpp
#include <bits/stdc++.h> #define fi first #define se second #define pb push_back #define mp make_pair #define MOD 1000000007 #define INF 1234567890 #define pii pair<int,int> #define LL long long using namespace std; int main () { //clock_t start = clock(); ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int tc; cin >> tc; while (tc--) { string s; cin >> s; vector<pair<char,int>> v; s+='*'; s+='*'; s+='*'; s+='*'; int ans=0; for (int i=0;i<s.size()-4;i++) { if (s[i] == 't' && s[i+1] == 'w' && s[i+2] == 'o' && s[i+3] == 'n' && s[i+4] == 'e') { ans++; s[i+2] = '^'; } } for (int i=0;i<s.size()-2;i++) { if (s[i] == 't' && s[i+1] == 'w' && s[i+2] == 'o') { ans++; s[i+1] = '^'; } } for (int i=0;i<s.size()-2;i++) { if (s[i] == 'o' && s[i+1] == 'n' && s[i+2] == 'e') { ans++; s[i+1] = '^'; } } cout << ans << endl; for (int i=0;i<s.size();i++) if (s[i] == '^') cout << i+1 << " "; cout << endl; } //cerr << fixed << setprecision(3) << (clock()-start)*1./CLOCKS_PER_SEC << endl; return 0; }
[ "moondemon68@gmail.com" ]
moondemon68@gmail.com
9a216c0729452d4425345a92e4066308ae3108df
eb830e9f5005ef0732b0ee980c8cdd9246b2cb6c
/testCode/memento.cpp
6861a1248eb6604bd602c1b712b55024d167e728
[]
no_license
gehfand729/ProgramTeam
4e8d2f05248e69baefe1b680ec5a526abb186e57
925716cd88731169f256f78de19e7c6a7e41ff08
refs/heads/main
2023-01-31T03:49:28.741076
2020-12-16T02:12:50
2020-12-16T02:12:50
304,517,837
0
2
null
2020-12-15T08:00:02
2020-10-16T04:19:15
null
UTF-8
C++
false
false
1,245
cpp
//작성자 : 20183487 이승찬 #include <iostream> #include <vector> #include <string> using namespace std; class Memento { int life; public: Memento(int nLife) : life(nLife) {} friend class NState; }; class NState { vector<shared_ptr<Memento>>changes; int current; public: int life = 0; explicit NState(const int nLife) :life(nLife) { changes.emplace_back(make_shared<Memento>(nLife)); current = 0; } shared_ptr<Memento>save(int sLife) { life = sLife; auto m = make_shared<Memento>(life); changes.push_back(m); ++current; return m; } void restore(const shared_ptr<Memento>& m) { if (m) { life = m->life; changes.push_back(m); current = changes.size() - 1; } } shared_ptr<Memento> undo() { if (current > 0) { --current; auto m = changes[current]; life = m->life; return m; } return {}; } }; int main() { NState test{ 100 }; cout << test.life << endl; test.save(20); cout << test.life << endl; test.undo(); cout << test.life << endl; }
[ "noreply@github.com" ]
noreply@github.com
b8c41067a4016a00fe9de68a969ee48e4155b503
b6289bea68145582d3f0ac20c6a76f8e2cf02011
/timing.h
a3b3b181e2e08efc619967d11646281d3c194adf
[]
no_license
mfs409/memcached-fetch-and-phi
703512e1a460fbda2aa214954eb6ca133aeba1bb
2d5c33e1e95c43dead54347901b3ce1c4cd28da4
refs/heads/master
2021-01-12T02:30:10.246798
2017-01-04T20:03:25
2017-01-04T20:03:25
78,041,758
0
0
null
null
null
null
UTF-8
C++
false
false
1,067
h
// -*-c++-*- // // Copyright (C) 2011, 2014 // University of Rochester Department of Computer Science // and // Lehigh University Department of Computer Science and Engineering // // License: Modified BSD // Please see the file LICENSE for licensing information #pragma once #include <unistd.h> /** * sleep_ms simply wraps the POSIX usleep call. Note that usleep expects a * number of microseconds, not milliseconds */ inline void sleep_ms(uint32_t ms) { usleep(ms*1000); } /** * Yield the CPU */ inline void yield_cpu() { std::this_thread::yield(); } /** * The Linux clock_gettime is reasonably fast, has good resolution, and is not * affected by TurboBoost. Using MONOTONIC_RAW also means that the timer is * not subject to NTP adjustments, which is preferably since an adjustment in * mid-experiment could produce some funky results. */ inline uint64_t getElapsedTime() { struct timespec t; clock_gettime(CLOCK_REALTIME, &t); uint64_t tt = (((long long)t.tv_sec) * 1000000000L) + ((long long)t.tv_nsec); return tt; }
[ "spear@cse.lehigh.edu" ]
spear@cse.lehigh.edu
12cb74c4edeeebca5e46db42718e59bbdbae1424
745a45b6bcf85fe497fc1acd06ef0b68b934626a
/suif/suif2b/basesuif/iokernel/helper.h
9f44276fc16478a1eb9b517cd7b79d2358980690
[]
no_license
jrk/suif2
e7c9f5e644f30422f7735837734e34248115cd2c
6f4dee1a906cfd00d3b57a7ead6f9fc807d7455d
refs/heads/master
2021-01-23T11:54:36.487230
2011-03-23T03:18:28
2011-03-23T03:18:28
1,514,729
1
0
null
null
null
null
UTF-8
C++
false
false
1,198
h
#ifndef IOKERNEL__HELPER_H #define IOKERNEL__HELPER_H #include "iokernel_forwarders.h" #include <stdio.h> String cut_off( String& start, char cut_char ); template<class T> void delete_list_and_elements( T* &t ) { if ( t ) { typename T::iterator current = t->begin(), end = t->end(); while ( current != end ) { delete (*current); current++; } } delete t; t = 0; } template<class T> void delete_list_elements( T* t ) { if ( t ) { typename T::iterator current = t->begin(), end = t->end(); while ( current != end ) { delete (*current); current++; } t->clear(); } } template<class T> void delete_map_and_value( T* &t ) { if ( t ) { typename T::iterator current = t->begin(), end = t->end(); while ( current != end ) { delete (*current).second; current++; } } delete t; t = 0; } template<class T> void delete_map_values( T* t ) { if ( t ) { typename T::iterator current = t->begin(), end = t->end(); while ( current != end ) { delete (*current).second; current++; } } t->clear(); } #endif
[ "jrk@csail.mit.edu" ]
jrk@csail.mit.edu
f56643bd506896019a478c8c0127d25e05e2d2f5
51590e5ef46b32c796e0eb6af726bef05674763f
/ThirdParty/PhysxCharController/PhysXCharacterKinematic/src/CctInternalStructs.h
40a74b5577d68ea6529691e19618f82ce79bffec
[ "BSD-3-Clause" ]
permissive
fly-man-/halcyon
f0a874a1226836a0d82474991537bda427a636bf
7acca5a677d755389864b9b08d01114d71f212cf
refs/heads/master
2021-01-21T11:54:14.181972
2019-03-07T05:15:11
2019-03-25T01:36:46
187,301,765
1
3
BSD-3-Clause
2019-05-18T01:46:13
2019-05-18T01:45:08
C#
UTF-8
C++
false
false
2,884
h
// This code contains NVIDIA Confidential Information and is disclosed to you // under a form of NVIDIA software license agreement provided separately to you. // // Notice // NVIDIA Corporation and its licensors retain all intellectual property and // proprietary rights in and to this software and related documentation and // any modifications thereto. Any use, reproduction, disclosure, or // distribution of this software and related documentation without an express // license agreement from NVIDIA Corporation is strictly prohibited. // // ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES // NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO // THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, // MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. // // Information and code furnished is believed to be accurate and reliable. // However, NVIDIA Corporation assumes no responsibility for the consequences of use of such // information or for any infringement of patents or other rights of third parties that may // result from its use. No license is granted by implication or otherwise under any patent // or patent rights of NVIDIA Corporation. Details are subject to change without notice. // This code supersedes and replaces all information previously supplied. // NVIDIA Corporation products are not authorized for use as critical // components in life support devices or systems without express written approval of // NVIDIA Corporation. // // Copyright (c) 2008-2012 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PX_CHARACTER_INTERNAL_STRUCTS_H #define PX_CHARACTER_INTERNAL_STRUCTS_H #include "CctCharacterController.h" #include "CctController.h" namespace physx { class PxObstacle; // (*) namespace Cct { class ObstacleContext; enum UserObjectType { USER_OBJECT_CCT = 0, USER_OBJECT_BOX_OBSTACLE = 1, USER_OBJECT_CAPSULE_OBSTACLE = 2, }; PX_FORCE_INLINE PxU32 encodeUserObject(PxU32 index, UserObjectType type) { PX_ASSERT(index<=0xffff); PX_ASSERT(type<=0xffff); return (PxU16(index)<<16)|PxU32(type); } PX_FORCE_INLINE UserObjectType decodeType(PxU32 code) { return UserObjectType(code & 0xffff); } PX_FORCE_INLINE PxU32 decodeIndex(PxU32 code) { return code>>16; } struct PxInternalCBData_OnHit : InternalCBData_OnHit { Controller* controller; const ObstacleContext* obstacles; const PxObstacle* touchedObstacle; }; struct PxInternalCBData_FindTouchedGeom : InternalCBData_FindTouchedGeom { PxScene* scene; Cm::RenderBuffer* renderBuffer; // Render buffer from controller manager, not the one from the scene Ps::HashSet<PxShape*>* cctShapeHashSet; }; } } #endif
[ "david.daeschler@gmail.com" ]
david.daeschler@gmail.com
bd4a529fc4f841061afb946939959bc3172a3cfb
e1e43f3e90aa96d758be7b7a8356413a61a2716f
/commsfwutils/commsbufs/version1/mbufmgr/TS_mbufmgr/TestSuiteCTMbufmgr.cpp
7673d4011dea3d8ac976ad84e9ff71855cb6010e
[]
no_license
SymbianSource/oss.FCL.sf.os.commsfw
76b450b5f52119f6bf23ae8a5974c9a09018fdfa
bc8ac1a6d5273cbfa7852bbb8ce27d6ddc076984
refs/heads/master
2021-01-18T23:55:06.285537
2010-10-03T23:21:43
2010-10-03T23:21:43
72,773,202
0
1
null
null
null
null
UTF-8
C++
false
false
3,196
cpp
// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies). // All rights reserved. // This component and the accompanying materials are made available // under the terms of "Eclipse Public License v1.0" // which accompanies this distribution, and is available // at the URL "http://www.eclipse.org/legal/epl-v10.html". // // Initial Contributors: // Nokia Corporation - initial contribution. // // Contributors: // // Description: // Contains definition of CTestStepCTMbufmgr which is the base class // for all the Mbufmgr Test Step classes // #include <networking/log.h> #include <networking/teststep.h> #include "TestStepCTMbufmgr.h" #include <networking/testsuite.h> #include "TestSuiteCTMbufmgr.h" #include "Test01CreateDeleteMBufMgr.h" #include "Test02AllocDealloc.h" #include "Test03AllocLeave.h" #include "Test04CopyInOut.h" #include "Test05CopyInOutOffset.h" #include "Test06SplitL.h" #include "Test07TrimStart.h" #include "Test08TrimEnd.h" #include "Test09Align.h" #include "Test10CopyL.h" #include "Test11AsyncAlloc.h" #include "Test12General.h" #include "Test13Performance.h" #include "Test14HeapFreeCheck.h" #include "Test15Concurrency.h" #include "test16memoryfull.h" #include "test17requestsizelimits.h" #include "test18exhaustmidsizepools.h" #include "test19prepend.h" #include "Test20Alloc.h" EXPORT_C CTestSuiteCTMbufmgr* NewTestSuiteCTMbufmgr( void ) { return new (ELeave) CTestSuiteCTMbufmgr; } CTestSuiteCTMbufmgr::~CTestSuiteCTMbufmgr() { } // Add a test step into the suite void CTestSuiteCTMbufmgr::AddTestStepL( CTestStepCTMbufmgr* ptrTestStep ) { // Test steps contain a pointer back to the suite which owns them ptrTestStep->iEsockSuite = this; // Add the step using the base class method CTestSuite::AddTestStepL(ptrTestStep); } // Make a version string available for test system TPtrC CTestSuiteCTMbufmgr::GetVersion( void ) { #ifdef _DEBUG _LIT(KTxtVersion,"1.007 (udeb)"); #else _LIT(KTxtVersion,"1.007"); #endif return KTxtVersion(); } // Second phase constructor for MBufMgr test suite // This creates all the MBufMgr test steps and // stores them inside CTestSuiteCTMbufmgr void CTestSuiteCTMbufmgr::InitialiseL( void ) { // Add test steps AddTestStepL( new(ELeave) CTest01CreateDeleteMBufMgr ); AddTestStepL( new(ELeave) CTest02AllocDealloc ); AddTestStepL( new(ELeave) CTest03AllocLeave ); AddTestStepL( new(ELeave) CTest04CopyInOut ); AddTestStepL( new(ELeave) CTest05CopyInOutOffset ); AddTestStepL( new(ELeave) CTest06Split ); AddTestStepL( new(ELeave) CTest07TrimStart ); AddTestStepL( new(ELeave) CTest08TrimEnd ); AddTestStepL( new(ELeave) CTest09Align ); AddTestStepL( new(ELeave) CTest10Copy ); AddTestStepL( new(ELeave) CTest11AsyncAlloc ); AddTestStepL( new(ELeave) CTest12General ); AddTestStepL( new(ELeave) CTest13Performance ); AddTestStepL( new(ELeave) CTest14HeapFreeCheck ); AddTestStepL( new(ELeave) CTest15Concurrency ); AddTestStepL( new(ELeave) CTest16MemoryFull ); AddTestStepL( new(ELeave) CTest17RequestSizeLimits ); AddTestStepL( new(ELeave) CTest18ExhaustMidSizePools ); AddTestStepL( new(ELeave) CTest19Prepend ); AddTestStepL( new(ELeave) CTest20Alloc ); return; }
[ "kirill.dremov@nokia.com" ]
kirill.dremov@nokia.com
a4d20d5331f8deda263656ae59e9c055d4a4a2c0
f3cbedbc9a54c4e614c9d2044e8437ae773e32da
/DP-demo-GPU/stdafx.cpp
d0717d095c3dd24e71a6481c5c40dacdafb34749
[]
no_license
td1tfx/DP-demo-GPU
028c3c3b49332e654b3e20a7b1b89f5768b64fa5
edf8a4781c504a1a7423a009de01d30cb7a4d32d
refs/heads/master
2021-09-01T12:57:39.491072
2017-12-27T04:14:48
2017-12-27T04:14:48
115,162,424
0
0
null
null
null
null
UTF-8
C++
false
false
290
cpp
// stdafx.cpp : source file that includes just the standard includes // DP-demo-GPU.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "td1tfx@163.com" ]
td1tfx@163.com
10ef095d14897fe7b90f5d875579bc06b02aaca0
4c6ee3c60a0bcd35a1775274bc60f7d41dfbf11b
/swo/ue10/ml5/inc/ml5/gui/window.h
3c7f1a650a299db8c7cb61553cc84ee192a90e19
[]
no_license
TangoTwo/nv-hgb
01e19deab3b2b12668f8c4faab9622355698885c
fabe9751b0687a8c783118a9a592808666994446
refs/heads/master
2020-04-03T11:45:45.175196
2019-02-02T16:31:46
2019-02-02T16:31:46
155,231,000
1
0
null
null
null
null
UTF-8
C++
false
false
4,243
h
// $Id: window.h 494 2018-12-06 18:05:32Z p20068 $ // $URL: https://svn01.fh-hagenberg.at/se/minilib/ml5/product/inc/ml5/gui/window.h $ // $Revision: 494 $ // $Date: 2018-12-06 19:05:32 +0100 (Do., 06 Dez 2018) $ // Creator: peter.kulczycki<AT>fh-hagenberg.at // Creation: June 1, 2018 // $Author: p20068 $ // Copyright: (c) 2018 Peter Kulczycki (peter.kulczycki<AT>fh-hagenberg.at) // (c) 2018 Michael Hava (michael.hava<AT>fh-hagenberg.at) // License: This document contains proprietary information belonging to // University of Applied Sciences Upper Austria, Campus Hagenberg. It // is distributed under the Boost Software License, Version 1.0 (see // http://www.boost.org/LICENSE_1_0.txt). #pragma once #include "./impl/impl_frame.h" namespace ml5 { class ML5_DLL_EXPORT window : public object, MI5_DERIVE (window, object) { MI5_INJECT (window) friend class application; friend class impl::canvas; friend class impl::frame; public: using title_item_t = impl::frame::title_item_t; using mitem_cont_t = impl::frame::mitem_cont_t; static void show_message_box (std::string const & text); window () = default; window (window const &) = delete; window (window &&) = delete; explicit window (std::string title); virtual ~window () = 0; window & operator = (window const &) = delete; window & operator = (window &&) = delete; void add_menu (std::string const & title, mitem_cont_t const & items) const; void cursor_off () const; void cursor_on () const; application & get_app () const; int get_height () const; wxSize get_size () const; int get_width () const; void refresh () const; void restart_timer (std::chrono::milliseconds interval) const; void set_status_text (std::string const & text) const; void start_timer (std::chrono::milliseconds interval) const; void stop_timer () const; protected: virtual void on_exit (); virtual void on_init (); virtual void on_key (key_event const & event); virtual void on_menu (menu_event const & event); virtual void on_mouse_double_down (mouse_event const & event); virtual void on_mouse_down (mouse_event const & event); virtual void on_mouse_left_double_down (mouse_event const & event); virtual void on_mouse_left_down (mouse_event const & event); virtual void on_mouse_left_up (mouse_event const & event); virtual void on_mouse_move (mouse_event const & event); virtual void on_mouse_right_double_down (mouse_event const & event); virtual void on_mouse_right_down (mouse_event const & event); virtual void on_mouse_right_up (mouse_event const & event); virtual void on_mouse_up (mouse_event const & event); virtual void on_mouse_wheel (mouse_event const & event); virtual void on_paint (paint_event const & event); virtual void on_size (size_event const & event); virtual void on_timer (timer_event const & event); impl::canvas & get_canvas () const; impl::frame & get_frame () const; private: void set_app (application & app); void set_frame (impl::frame * p_frame); ML5_DEFINE_WIN_PROPERTY (allow_resize, bool, true) ML5_DEFINE_WIN_PROPERTY (background_brush, wxBrush, *wxWHITE_BRUSH) ML5_DEFINE_WIN_PROPERTY (initial_size, wxSize, wxDefaultSize) ML5_DEFINE_WIN_PROPERTY (paint_via_opengl, bool, false) ML5_DEFINE_WIN_PROPERTY (title, std::string, "MiniLib 5") application * m_p_app {nullptr}; impl::frame * m_p_frame {nullptr}; }; } // namespace ml5
[ "vest.niklas@gmail.com" ]
vest.niklas@gmail.com
35a9ad6a8d05669ddf41b750b493625334e916e7
f879452c6b342c5908794f3f62448d76daee3a7c
/index_tests/macros/foo.cc
00cb44ed8e3ddbbc2245ff8aa4c3b270e5ae354e
[]
no_license
zhongweiy/ccls
7468969b568780c8db40e4b4b6a8fd9536d95aad
775c72b0e6a092bf45919d6c99b6d335d53bb1fd
refs/heads/master
2020-03-22T14:05:18.926236
2018-07-07T06:34:16
2018-07-07T06:41:24
140,152,703
0
0
null
2018-07-08T09:04:08
2018-07-08T09:04:08
null
UTF-8
C++
false
false
2,525
cc
#define A 5 #define DISALLOW(type) type(type&&) = delete; struct Foo { DISALLOW(Foo); }; int x = A; /* OUTPUT: { "includes": [], "skipped_by_preprocessor": [], "usr2func": [{ "usr": 13788753348312146871, "detailed_name": "Foo::Foo(Foo &&) = delete", "qual_name_offset": 0, "short_name": "Foo", "kind": 9, "storage": 0, "declarations": [], "spell": "5:12-5:15|15041163540773201510|2|2", "extent": "5:12-5:16|15041163540773201510|2|0", "declaring_type": 15041163540773201510, "bases": [], "derived": [], "vars": [], "uses": [], "callees": [] }], "usr2type": [{ "usr": 17, "detailed_name": "", "qual_name_offset": 0, "short_name": "", "kind": 0, "declarations": [], "alias_of": 0, "bases": [], "derived": [], "types": [], "funcs": [], "vars": [], "instances": [10677751717622394455], "uses": [] }, { "usr": 15041163540773201510, "detailed_name": "Foo", "qual_name_offset": 0, "short_name": "Foo", "kind": 23, "declarations": ["5:12-5:15|0|1|4"], "spell": "4:8-4:11|0|1|2", "extent": "4:1-6:2|0|1|0", "alias_of": 0, "bases": [], "derived": [], "types": [], "funcs": [13788753348312146871], "vars": [], "instances": [], "uses": ["5:12-5:15|15041163540773201510|2|4"] }], "usr2var": [{ "usr": 2056319845419860263, "detailed_name": "DISALLOW", "qual_name_offset": 0, "short_name": "DISALLOW", "hover": "#define DISALLOW(type) type(type&&) = delete;", "declarations": [], "spell": "2:9-2:17|0|1|2", "extent": "2:9-2:46|0|1|0", "type": 0, "uses": ["5:3-5:11|0|1|4"], "kind": 255, "storage": 0 }, { "usr": 7651988378939587454, "detailed_name": "A", "qual_name_offset": 0, "short_name": "A", "hover": "#define A 5", "declarations": [], "spell": "1:9-1:10|0|1|2", "extent": "1:9-1:12|0|1|0", "type": 0, "uses": ["8:9-8:10|0|1|4"], "kind": 255, "storage": 0 }, { "usr": 10677751717622394455, "detailed_name": "int x", "qual_name_offset": 4, "short_name": "x", "hover": "int x = A", "declarations": [], "spell": "8:5-8:6|0|1|2", "extent": "8:1-8:10|0|1|0", "type": 17, "uses": [], "kind": 13, "storage": 0 }] } */
[ "i@maskray.me" ]
i@maskray.me
37aa28c1d1200b94dde50659c7f41e7e1748332e
9618b499f750fa437a84be10553d6d066ae09e4d
/chapter_3/libchapter3/src/VertexAttribute.cpp
00bfc2135381a29ee4f25b7a5e16c6147712b867
[ "MIT" ]
permissive
ps-group/cg_course_examples
63d524f77575e15dfc52164aab065e682313ceb7
921b6218d71731bcb79ddddcc92c9d04a72c62ab
refs/heads/master
2021-01-21T15:17:58.322071
2018-05-07T05:58:56
2018-05-07T05:58:56
44,232,033
6
9
null
null
null
null
UTF-8
C++
false
false
909
cpp
#include "libchapter3_private.h" #include "VertexAttribute.h" CVertexAttribute::CVertexAttribute(int location) : m_location(location) { } void CVertexAttribute::EnablePointer() { glEnableVertexAttribArray(GLuint(m_location)); } void CVertexAttribute::DisablePointer() { glDisableVertexAttribArray(GLuint(m_location)); } void CVertexAttribute::SetVec3Offset(size_t offset, size_t stride, bool needClamp) { const GLboolean normalize = needClamp ? GL_TRUE : GL_FALSE; glVertexAttribPointer(GLuint(m_location), 3, GL_FLOAT, normalize, GLsizei(stride), reinterpret_cast<const void *>(offset)); } void CVertexAttribute::SetVec2Offset(size_t offset, size_t stride) { const GLboolean normalize = GL_FALSE; glVertexAttribPointer(GLuint(m_location), 2, GL_FLOAT, normalize, GLsizei(stride), reinterpret_cast<const void *>(offset)); }
[ "sshambir@yandex.ru" ]
sshambir@yandex.ru
90de1ab8b492bfe301fee013695b57d9b1d84535
4f6f26102b38bc178c69ff4149ca9a471b88d729
/ext/vrpn/vrpn_Event_Mouse.h
7e6e62d3e639df208ce288b1a3f73fc2f697c8d3
[ "BSL-1.0", "LicenseRef-scancode-public-domain", "BSD-3-Clause", "BSD-2-Clause", "Libpng", "Zlib", "CC0-1.0", "LicenseRef-scancode-warranty-disclaimer", "FTL", "Apache-2.0", "MIT" ]
permissive
sgct/sgct
8c51122bad722901709b1ff877d949f4b66c8681
654a594e2d6e8f8784b1f73b02ae96ff33be0848
refs/heads/master
2023-08-31T13:13:35.820892
2023-08-25T22:43:50
2023-08-31T02:03:39
235,854,091
8
7
NOASSERTION
2023-08-18T08:24:55
2020-01-23T18:00:51
C
UTF-8
C++
false
false
2,366
h
/**************************************************************************************************/ /* */ /* Copyright (C) 2004 Bauhaus University Weimar */ /* Released into the public domain on 6/23/2007 as part of the VRPN project */ /* by Jan P. Springer. */ /* */ /**************************************************************************************************/ /* */ /* module : vrpn_Event_Mouse.h */ /* project : */ /* description: mouse input using the event interface */ /* */ /**************************************************************************************************/ #ifndef _VRPN_EVENT_MOUSE_H_ #define _VRPN_EVENT_MOUSE_H_ #include "vrpn_Button.h" // for vrpn_Button_Server #include "vrpn_Configure.h" // for VRPN_API // includes, project #include "vrpn_Event_Analog.h" // for vrpn_Event_Analog #include "vrpn_Shared.h" // for timeval class VRPN_API vrpn_Connection; class VRPN_API vrpn_Event_Mouse: public vrpn_Event_Analog, public vrpn_Button_Server { public: // creates a vrpn_Event_Mouse vrpn_Event_Mouse ( const char *name, vrpn_Connection *c = 0, const char* evdev_name = "/dev/input/event0" ); // default dtor ~vrpn_Event_Mouse(); // This routine is called each time through the server's main loop. It will // read from the mouse. void mainloop (void); private: // This routine interpret data from the device void process_mouse_data (); // set all buttons and analogs to 0 void clear_values(); private: struct timeval timestamp; }; #endif // _VRPN_EVENT_MOUSE_H_
[ "miroslav.andel@gmail.com" ]
miroslav.andel@gmail.com
f704a15e84a81879e5c8af704da0df0c0307cbc2
973996e18022fc176ec68876bbceb5ae54aa9cac
/Topcoder/SRM_771/c.cpp
fdb3eb2c64c1a09e5b09c05cde269f7fb4d75174
[ "MIT" ]
permissive
Shahraaz/CP_P_S5
80bda6a39f197428bbe6952c6735fe9a17c01cb8
b068ad02d34338337e549d92a14e3b3d9e8df712
refs/heads/master
2021-08-16T11:09:59.341001
2021-06-22T05:14:10
2021-06-22T05:14:10
197,088,137
1
0
null
null
null
null
UTF-8
C++
false
false
2,593
cpp
//Optimise #include <bits/stdc++.h> using namespace std; #define Debug #ifdef Debug #define db(...) ZZ(#__VA_ARGS__, __VA_ARGS__); #define pc(...) PC(#__VA_ARGS__, __VA_ARGS__); template <typename T, typename U> ostream &operator<<(ostream &out, const pair<T, U> &p) { out << '[' << p.first << ", " << p.second << ']'; return out; } template <typename Arg> void PC(const char *name, Arg &&arg) { std::cerr << name << " { "; for (const auto &v : arg) cerr << v << ' '; cerr << " }\n"; } template <typename Arg1> void ZZ(const char *name, Arg1 &&arg1) { std::cerr << name << " = " << arg1 << endl; } template <typename Arg1, typename... Args> void ZZ(const char *names, Arg1 &&arg1, Args &&... args) { const char *comma = strchr(names + 1, ','); std::cerr.write(names, comma - names) << " = " << arg1; ZZ(comma, args...); } #else #define db(...) #define pc(...) #endif using ll = long long; #define f first #define s second #define pb push_back const long long mod = 1000000007; const int nax = 2e5 + 10; class AllEven { long long cache[1 << 10][20][2][2]; string s; ll dp(int mask, int pos, bool smaller, bool started) { if (pos == s.size()) return (mask == 0) && (started); ll &ret = cache[mask][pos][smaller][started]; if (ret >= 0) return ret; int mx = 9; if (!smaller) mx = s[pos] - '0'; ret = 0; if (started) for (int i = 0; i <= mx; ++i) ret += dp(mask ^ (1 << i), pos + 1, smaller || (i < s[pos] - '0'), 1); else { ret += dp(mask, pos + 1, 1, 0); for (int i = 1; i <= mx; ++i) ret += dp(mask ^ (1 << i), pos + 1, smaller || (i < s[pos] - '0'), 1); } return ret; } long long solve(ll x) { if (x == 0) return 0; memset(cache, -1, sizeof cache); s = to_string(x); return dp(0, 0, 0, 0); } public: long long countInRange(long long lo, long long hi) { return solve(hi) - (lo ? solve(lo - 1) : 0); } }; #ifndef LOCAL // <%:testing-code%> #endif #ifdef LOCAL int main() { ios_base::sync_with_stdio(0); cin.tie(0); int t = 1; auto TimeStart = chrono::steady_clock::now(); #ifdef multitest cin >> t; #endif #ifdef TIME cerr << "\n\nTime elapsed: " << chrono::duration<double>(chrono::steady_clock::now() - TimeStart).count() << " seconds.\n"; #endif return 0; } #endif //Powered by KawigiEdit 2.1.4 (beta) modified by pivanof!
[ "ShahraazHussain@gmail.com" ]
ShahraazHussain@gmail.com
94397282ed6c9512335909ecad198000acb5b002
8e57405aa788e066f60d907d4e5fa78f9386c973
/divDy1/4.3/polyMesh/pointZones
e6ef586bac4ff0fa07d319192de5920061f19dd7
[]
no_license
daihui-lu/dynamicMesh
06394bdf1538d6ce95ff9d836ecf7ff2b2917820
7cf4fc5f0c84b19dc330083cf4899677017383fc
refs/heads/master
2020-03-22T03:55:07.843849
2018-07-02T15:38:58
2018-07-02T15:38:58
139,460,206
0
0
null
null
null
null
UTF-8
C++
false
false
873
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 5.0 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class regIOobject; location "4.3/polyMesh"; object pointZones; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // 0 () // ************************************************************************* //
[ "daihui.lu2016@gmail.com" ]
daihui.lu2016@gmail.com
825b84b80b8690de73d7d1025cb3b3b391f98c0f
40684ab19ae0e3448176cb5d2fb310794004fb2e
/C語言初學指引範例/ch13/ch13_04.cpp
1821f8b9022c634a1f27fc26eb9db8c7f8cc422c
[]
no_license
nicecoolwinter/learn_c
bbae1895173a81e7c759f0d2c0a7c899294e29e0
aa31897008b3042f9e49f52beee21dd5ba7a5ec6
refs/heads/master
2021-01-17T17:16:21.257333
2016-09-24T12:25:49
2016-09-24T12:25:49
69,100,753
0
1
null
null
null
null
BIG5
C++
false
false
733
cpp
/******************************* 檔名:ch13_04.cpp 功能:手動設定成員變數初值 *******************************/ #include <stdlib.h> #include <stdio.h> class myclass { public: int VarA; void ShowVar(); private: int VarB; }; void myclass::ShowVar() { printf("VarA=%d\n", VarA); printf("VarB=%d\n", VarB); } void main(void) { int i; myclass X[3]; printf("設定初值前\n"); for (i = 0; i < 3; i++) { X[i].ShowVar(); } for (i = 0; i < 3; i++) { X[i].VarA = 0; //X[i].VarB=0; //無法取用私用成員變數 } printf("設定初值後\n"); for (i = 0; i < 3; i++) { X[i].ShowVar(); } /* system("pause"); */ }
[ "gigi" ]
gigi
09b758fe6e3c0fc58c82489ddbdfea4721f2b3c1
83d0a37574b644b80aed0865dd63d95c7c118624
/src/win32/win32gliface.h
6320e290345c239c4988b2fd5f0aca31468cf321
[]
no_license
alexey-lysiuk/gzdoom
905623e346f2f00723499cf0d09bdaf3c052d3f4
ae4b3fd9c853a30541f85d745e45e8b76e5c87ef
refs/heads/macOS
2023-08-05T05:21:20.926659
2016-10-02T16:28:34
2016-10-10T11:53:29
10,887,143
66
12
null
2019-07-14T19:02:35
2013-06-23T15:45:00
C++
UTF-8
C++
false
false
3,467
h
#ifndef __WIN32GLIFACE_H__ #define __WIN32GLIFACE_H__ #include "hardware.h" #include "win32iface.h" #include "v_video.h" #include "tarray.h" extern IVideo *Video; extern BOOL AppActive; EXTERN_CVAR (Float, dimamount) EXTERN_CVAR (Color, dimcolor) EXTERN_CVAR(Int, vid_defwidth); EXTERN_CVAR(Int, vid_defheight); EXTERN_CVAR(Int, vid_renderer); EXTERN_CVAR(Int, vid_adapter); extern HINSTANCE g_hInst; extern HWND Window; extern IVideo *Video; struct FRenderer; FRenderer *gl_CreateInterface(); class Win32GLVideo : public IVideo { public: Win32GLVideo(int parm); virtual ~Win32GLVideo(); EDisplayType GetDisplayType () { return DISPLAY_Both; } void SetWindowedScale (float scale); void StartModeIterator (int bits, bool fs); bool NextMode (int *width, int *height, bool *letterbox); bool GoFullscreen(bool yes); DFrameBuffer *CreateFrameBuffer (int width, int height, bool fs, DFrameBuffer *old); virtual bool SetResolution (int width, int height, int bits); void DumpAdapters(); bool InitHardware (HWND Window, int multisample); void Shutdown(); bool SetFullscreen(const char *devicename, int w, int h, int bits, int hz); HDC m_hDC; protected: struct ModeInfo { ModeInfo (int inX, int inY, int inBits, int inRealY, int inRefresh) : next (NULL), width (inX), height (inY), bits (inBits), refreshHz (inRefresh), realheight (inRealY) {} ModeInfo *next; int width, height, bits, refreshHz, realheight; } *m_Modes; ModeInfo *m_IteratorMode; int m_IteratorBits; bool m_IteratorFS; bool m_IsFullscreen; int m_trueHeight; int m_DisplayWidth, m_DisplayHeight, m_DisplayBits, m_DisplayHz; HMODULE hmRender; char m_DisplayDeviceBuffer[CCHDEVICENAME]; char *m_DisplayDeviceName; HMONITOR m_hMonitor; HWND m_Window; HGLRC m_hRC; HWND InitDummy(); void ShutdownDummy(HWND dummy); bool SetPixelFormat(); bool SetupPixelFormat(int multisample); void GetDisplayDeviceName(); void MakeModesList(); void AddMode(int x, int y, int bits, int baseHeight, int refreshHz); void FreeModes(); public: int GetTrueHeight() { return m_trueHeight; } }; class Win32GLFrameBuffer : public BaseWinFB { DECLARE_CLASS(Win32GLFrameBuffer, BaseWinFB) public: Win32GLFrameBuffer() {} // Actually, hMonitor is a HMONITOR, but it's passed as a void * as there // look to be some cross-platform bits in the way. Win32GLFrameBuffer(void *hMonitor, int width, int height, int bits, int refreshHz, bool fullscreen); virtual ~Win32GLFrameBuffer(); // unused but must be defined virtual void Blank (); virtual bool PaintToWindow (); virtual HRESULT GetHR(); virtual bool CreateResources (); virtual void ReleaseResources (); void SetVSync (bool vsync); void SwapBuffers(); void NewRefreshRate (); int GetClientWidth(); int GetClientHeight(); int GetTrueHeight() { return static_cast<Win32GLVideo *>(Video)->GetTrueHeight(); } bool Lock(bool buffered); bool Lock (); void Unlock(); bool IsLocked (); bool IsFullscreen(); void PaletteChanged(); int QueryNewPalette(); void InitializeState(); protected: bool CanUpdate(); void ResetGammaTable(); void SetGammaTable(WORD * tbl); float m_Gamma, m_Brightness, m_Contrast; WORD m_origGamma[768]; BOOL m_supportsGamma; bool m_Fullscreen; int m_Width, m_Height, m_Bits, m_RefreshHz; int m_Lock; char m_displayDeviceNameBuffer[CCHDEVICENAME]; char *m_displayDeviceName; friend class Win32GLVideo; }; #endif //__WIN32GLIFACE_H__
[ "coelckers@zdoom.fake" ]
coelckers@zdoom.fake
4083237f0e7ce2d9ada5784963edbe7d767c4748
ac56437cd07aa7b5dfad305d0ee130ab45611cb4
/labs/laba_8 (1).cpp
cac69e2f8e98d598593abbedad36d79fdd4977e9
[]
no_license
dreamiquel/kashtanov.labs
58e8e2f32b36e487031ea6a951cf0ea683c3e9e4
9055556a55a5c7ea6beff38b315a52912658d54b
refs/heads/main
2023-06-03T16:11:26.266501
2021-06-20T16:28:21
2021-06-20T16:28:21
376,084,737
0
0
null
null
null
null
UTF-8
C++
false
false
822
cpp
#include <stdlib.h> #include <time.h> #include <windows.h> #include <iostream> using namespace std; int main() { SetConsoleCP(1251); SetConsoleOutputCP(1251); int** Matrix, n = 0; cout << "Введите порядок квадратной матрицы n = "; cin >> n; Matrix = new int* [n]; for (int i = 0; i < n; i++) Matrix[i] = new int[n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { if (j == 0 || i == 0) Matrix[i][j] = 1; else if (i == n - 1 || j == n - 1) Matrix[i][j] = 1; else Matrix[i][j] = 0; } cout << endl; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << Matrix[i][j] << " "; cout << endl; } for (int i = 0; i < n; i++) delete[] Matrix[i]; delete[] Matrix; Matrix = 0; return 0; }
[ "noreply@github.com" ]
noreply@github.com
44f2fd3c7ee393659d5be43bae7761e0b44083bb
ba9322f7db02d797f6984298d892f74768193dcf
/slb/src/model/AddAccessControlListEntryRequest.cc
66a4a457e5cb9ea3a300db5ab0dc16e6f630e303
[ "Apache-2.0" ]
permissive
sdk-team/aliyun-openapi-cpp-sdk
e27f91996b3bad9226c86f74475b5a1a91806861
a27fc0000a2b061cd10df09cbe4fff9db4a7c707
refs/heads/master
2022-08-21T18:25:53.080066
2022-07-25T10:01:05
2022-07-25T10:01:05
183,356,893
3
0
null
2019-04-25T04:34:29
2019-04-25T04:34:28
null
UTF-8
C++
false
false
3,615
cc
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/slb/model/AddAccessControlListEntryRequest.h> using AlibabaCloud::Slb::Model::AddAccessControlListEntryRequest; AddAccessControlListEntryRequest::AddAccessControlListEntryRequest() : RpcServiceRequest("slb", "2014-05-15", "AddAccessControlListEntry") {} AddAccessControlListEntryRequest::~AddAccessControlListEntryRequest() {} std::string AddAccessControlListEntryRequest::getAccess_key_id()const { return access_key_id_; } void AddAccessControlListEntryRequest::setAccess_key_id(const std::string& access_key_id) { access_key_id_ = access_key_id; setParameter("Access_key_id", access_key_id); } std::string AddAccessControlListEntryRequest::getAclId()const { return aclId_; } void AddAccessControlListEntryRequest::setAclId(const std::string& aclId) { aclId_ = aclId; setParameter("AclId", aclId); } long AddAccessControlListEntryRequest::getResourceOwnerId()const { return resourceOwnerId_; } void AddAccessControlListEntryRequest::setResourceOwnerId(long resourceOwnerId) { resourceOwnerId_ = resourceOwnerId; setParameter("ResourceOwnerId", std::to_string(resourceOwnerId)); } std::string AddAccessControlListEntryRequest::getResourceOwnerAccount()const { return resourceOwnerAccount_; } void AddAccessControlListEntryRequest::setResourceOwnerAccount(const std::string& resourceOwnerAccount) { resourceOwnerAccount_ = resourceOwnerAccount; setParameter("ResourceOwnerAccount", resourceOwnerAccount); } std::string AddAccessControlListEntryRequest::getRegionId()const { return regionId_; } void AddAccessControlListEntryRequest::setRegionId(const std::string& regionId) { regionId_ = regionId; setParameter("RegionId", regionId); } std::string AddAccessControlListEntryRequest::getOwnerAccount()const { return ownerAccount_; } void AddAccessControlListEntryRequest::setOwnerAccount(const std::string& ownerAccount) { ownerAccount_ = ownerAccount; setParameter("OwnerAccount", ownerAccount); } std::string AddAccessControlListEntryRequest::getAclEntrys()const { return aclEntrys_; } void AddAccessControlListEntryRequest::setAclEntrys(const std::string& aclEntrys) { aclEntrys_ = aclEntrys; setParameter("AclEntrys", aclEntrys); } long AddAccessControlListEntryRequest::getOwnerId()const { return ownerId_; } void AddAccessControlListEntryRequest::setOwnerId(long ownerId) { ownerId_ = ownerId; setParameter("OwnerId", std::to_string(ownerId)); } std::string AddAccessControlListEntryRequest::getAccessKeyId()const { return accessKeyId_; } void AddAccessControlListEntryRequest::setAccessKeyId(const std::string& accessKeyId) { accessKeyId_ = accessKeyId; setParameter("AccessKeyId", accessKeyId); } std::string AddAccessControlListEntryRequest::getTags()const { return tags_; } void AddAccessControlListEntryRequest::setTags(const std::string& tags) { tags_ = tags; setParameter("Tags", tags); }
[ "yixiong.jxy@alibaba-inc.com" ]
yixiong.jxy@alibaba-inc.com
ea8a8f3969c19854a2c68ea21941bbeb3b7aa3c3
d5264e6ec7905da4875a9862ff00f3fa2ed8376c
/media/libaudiohal/4.0/include/libaudiohal/4.0/EffectsFactoryHalHidl.h
680b7a13227782a1aeb3608556d92010b0973c10
[ "LicenseRef-scancode-unicode", "Apache-2.0" ]
permissive
ValidusOs/frameworks_av
156688bd4f6e5d15dca1dc69a30ba174f0125ab5
f0397be7a8f5e9c8ca5986fce56b84edcc7e6be0
refs/heads/9.0
2021-06-05T12:15:49.821982
2018-12-27T01:48:08
2019-08-17T07:07:43
114,925,058
2
11
NOASSERTION
2019-08-12T08:53:27
2017-12-20T19:48:23
C++
UTF-8
C++
false
false
2,662
h
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ANDROID_HARDWARE_EFFECTS_FACTORY_HAL_HIDL_4_0_H #define ANDROID_HARDWARE_EFFECTS_FACTORY_HAL_HIDL_4_0_H #include <android/hardware/audio/effect/4.0/IEffectsFactory.h> #include <android/hardware/audio/effect/4.0/types.h> #include <media/audiohal/EffectsFactoryHalInterface.h> #include "ConversionHelperHidl.h" namespace android { namespace V4_0 { using ::android::hardware::audio::effect::V4_0::EffectDescriptor; using ::android::hardware::audio::effect::V4_0::IEffectsFactory; using ::android::hardware::hidl_vec; class EffectsFactoryHalHidl : public EffectsFactoryHalInterface, public ConversionHelperHidl { public: // Returns the number of different effects in all loaded libraries. virtual status_t queryNumberEffects(uint32_t *pNumEffects); // Returns a descriptor of the next available effect. virtual status_t getDescriptor(uint32_t index, effect_descriptor_t *pDescriptor); virtual status_t getDescriptor(const effect_uuid_t *pEffectUuid, effect_descriptor_t *pDescriptor); // Creates an effect engine of the specified type. // To release the effect engine, it is necessary to release references // to the returned effect object. virtual status_t createEffect(const effect_uuid_t *pEffectUuid, int32_t sessionId, int32_t ioId, sp<EffectHalInterface> *effect); virtual status_t dumpEffects(int fd); status_t allocateBuffer(size_t size, sp<EffectBufferHalInterface>* buffer) override; status_t mirrorBuffer(void* external, size_t size, sp<EffectBufferHalInterface>* buffer) override; private: friend class EffectsFactoryHalInterface; sp<IEffectsFactory> mEffectsFactory; hidl_vec<EffectDescriptor> mLastDescriptors; // Can not be constructed directly by clients. EffectsFactoryHalHidl(); virtual ~EffectsFactoryHalHidl(); status_t queryAllDescriptors(); }; } // namespace V4_0 } // namespace android #endif // ANDROID_HARDWARE_EFFECTS_FACTORY_HAL_HIDL_4_0_H
[ "krocard@google.com" ]
krocard@google.com
59ca2b16dd3770328ada94b9706539d5d4519c47
721ecafc8ab45066f3661cbde2257f6016f5b3a8
/uva/random/12506.cpp
e625e651596f3fc83d0dae805328df752bc96e8c
[]
no_license
dr0pdb/competitive
8651ba9722ec260aeb40ef4faf5698e6ebd75d4b
fd0d17d96f934d1724069c4e737fee37a5874887
refs/heads/master
2022-04-08T02:14:39.203196
2020-02-15T19:05:38
2020-02-15T19:05:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,372
cpp
#include<bits/stdc++.h> #define FOR(i,a,b) for(long long i = (long long)(a); i < (long long)(b); i++) #define RFOR(i,a,b) for(long long i = (long long)(a); i >= (long long)(b); i--) #define MIN3(a,b,c) (a)<(b)?((a)<(c)?(a):(c)):((b)<(c)?(b):(c)) #define MAX(a,b) (a)>(b)?(a):(b) #define MIN2(a,b) (a)<(b)?(a):(b) using namespace std; typedef pair<int, int> ii; typedef pair<int, ii> iii; typedef vector<ii> vii; typedef vector<int> vi; typedef long long ll; #define ull unsigned long long typedef long double ld; typedef vector<ll> vll; typedef pair<ll,ll> lll; #define deb(x ) cerr << #x << " here "<< x << endl; #define endl "\n" #define printCase() "Case #" << caseNum << ": " inline bool is_palindrome(const string& s){ return std::equal(s.begin(), s.end(), s.rbegin()); } const ll MOD = 1000000007; const ll INF = 1e9+5; const double eps = 1e-7; const double PI = acos(-1.0); #define coud(a,d) cout << fixed << showpoint << setprecision(d) << a; inline void debug_vi(vi a) {FOR(i, 0, a.size()) cout<<a[i]<<" ";} inline void debug_vll(vll a) {FOR(i, 0, a.size()) cout<<a[i]<<" ";} #define ff first #define ss second /*----------------------------------------------------------------------*/ #define maxx 1000001 #define intt int intt trie[maxx][26], finish[maxx], cnt[maxx]; intt nxt = 1; void insert (string s){ intt node = 0; for (intt i = 0; s[i] != '\0'; i++) { if(trie[node][s[i] - 'a'] == 0) { node = trie[node][s[i] - 'a'] = nxt; cnt[node]++; nxt++; } else { node = trie[node][s[i] - 'a']; cnt[node]++; } } // cnt[node]++; finish[node]=1; finish[nxt - 1] = 1; } intt ans = 0; void dfs(intt idx, int depth) { if(idx && cnt[idx] == 0) return; else if(cnt[idx] == 1) { ans += depth; return; } FOR(i, 0, 26) { if(trie[idx][i]) dfs(trie[idx][i], 1 + depth); } } int main(){ std::ios::sync_with_stdio(false);cin.tie(NULL); cout.tie(NULL); //freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); int t,n; string s; cin>>t; while(t--) { memset(trie, 0, sizeof(trie)); memset(cnt, 0, sizeof(cnt)); memset(finish, 0, sizeof(finish)); nxt = 1; ans = 0; cin>>n; FOR(i, 0, n) { cin>>s; insert(s); } dfs(0, 0); cout<<ans<<endl; } return 0; }
[ "srv.twry@gmail.com" ]
srv.twry@gmail.com
70f0b91eb31ae9626b1245be00571cf30e240243
8c48768d473fbf29aee7987c400d1dd8e666fe96
/Lista 04/Ex18.cpp
3fe343c4e39e51aa504ebff4cf0ccd13e5020699
[]
no_license
YgorCruz/Listas-de-C
4d99511ff9679380ec9cb56a9a014975c2af2fb7
25af7274238fc78191667d3598fabcaaa57e6dcd
refs/heads/master
2020-12-01T15:06:19.394565
2019-12-28T22:19:23
2019-12-28T22:19:23
230,674,420
0
0
null
null
null
null
ISO-8859-1
C++
false
false
280
cpp
#include <stdio.h> #include <stdlib.h> #include <locale.h> main(){ int n1,n2; setlocale(LC_ALL,"Portuguese"); printf("Digite número par : "); scanf("%i",&n1); printf("Digite outro número par : "); scanf("%i",&n2); for(int c = n1; c <= n2;c++ ){ printf("%i\n",c); } }
[ "cruz.ygor@hotmail.com" ]
cruz.ygor@hotmail.com
19fc261b14e5fe554b210a19fe2540cc016d5693
240b92b4e1fa451f6238c911ebc972a034fc3ea6
/Cerradura.cpp
baa55bd41fb051e589c9057f657f16ee9aed7d34
[]
no_license
LuisCarlosR2002/Maraton
1ec3f8631520eeed4a6fef2e78c6d40101d3d75d
cf445505bba7ea3cbb67f703793b78ab75cb009b
refs/heads/main
2023-06-25T08:16:11.199731
2021-07-23T04:38:14
2021-07-23T04:38:14
388,664,902
0
0
null
null
null
null
UTF-8
C++
false
false
461
cpp
#include<bits/stdc++.h> using namespace std; int main(int argc, char** argv) { int pos=0,x=0,y=0,z=0,res=0; while(cin>>pos>>x>>y>>z){ res=1080; if(x>pos){ res+=((40-x)+pos)*9; } else{ res+=(pos-x)*9; } if(y>x){ res+=(y-x)*9; } else{ res+=((40-x)+y)*9; } if(z>y){ res+=((40-z)+y)*9; } else{ res+=(y-z)*9; } if(pos==0 && x==0 && y==0 && z==0){ break; } cout<<res<<endl; } return 0; }
[ "rosero21318@gmail.com" ]
rosero21318@gmail.com
e7c2f18d142b2cfee78410e1568d95d09e405f74
ef8722d034bfe2259afbdcac63f2210435e0b5f9
/src/tempoPitch.cpp
866ef85d5214fd84a44bade8061c18404eb6a7fd
[]
no_license
agangzz/euterpe
6a6af465c046aecf0ef5971b9c4e9e8a1ac16f8a
f1f52ed8c3c4140222cae735fb85f90cb013d56c
refs/heads/master
2021-01-22T03:30:54.634255
2016-02-21T14:10:46
2016-02-21T14:10:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,296
cpp
// 面倒なのでとりあえずコピペで済ます。簡単に整理はする。 typedef double FLOAT; #include "tempoPitch.h" #include <cmath> #include <unistd.h> //bool flag; TempoPitch::TempoPitch(){ exec_count = 0; exec_count_total = 0; second = 0; pthread_attr_init(&attr_FIFO); pthread_attr_init(&attr_RR); pthread_attr_setschedpolicy(&attr_FIFO, SCHED_FIFO); pthread_attr_setschedpolicy(&attr_RR, SCHED_RR); } TempoPitch::~TempoPitch(){ // deleteとかかく } // ------------------------------------------------------------------------------------ // 単なる // return pow(2.0, static_cast<double>(key)/12.0); // ではなくFFTが高速になるような値をちゃんと選ぶ。 double SetPitch(int key){ return pow(2.0, static_cast<double>(key)/12.0); } int reset_frame(int key, int frame){ static int bunshi[] = { 1, //-12 135, //-11 9, //-10 75, //-9 5, //-8 27*25, //-7 45, //-6 3, //-5 81*5, //-4 27, //-3 9*25, //-2 15, //-1 1, // 0 27*5, //+1 9, //+2 243*5, //+3 5, //+4 27*25, //+5 45, //+6 3, //+7 81*5, //+8 27, //+9 9*25, //+10 15, //+11 2 //+12 }; static int bunbo[] = { 1, //-12 8, //-11 4, //-10 7, //-9 3, //-8 10, //-7 6, //-6 2, //-5 9, //-4 5, //-3 8, //-2 4, //-1 0, // 0 7, //+1 3, //+2 10, //+3 2, //+4 9, //+5 5, //+6 1, //+7 8, //+8 4, //+9 7, //+10 3, //+11 0 //+12 }; int ret = (frame >> bunbo[key + 12]) * bunshi[key + 12]; if (ret != 0){ return ret; }else{ fprintf(stderr, "%d %d %d %d", ret, frame, bunbo[key + 12], bunshi[key + 12]); std::cerr << "error" << std::endl; exit(1); } } // ------------------------------------------------------------------------------------ void TempoPitch::update_cframe2(){ int tmp = reset_frame((int)(panel->key.get()), frame); if (cframe2 != tmp){ cframe2 = tmp; std::cerr << tmp << " " << (int)(SetPitch(panel->key.get()) * frame) << " " << (int)(panel->key.get()) << " " << frame << " " << std::endl; // 全部作っておいてリンクだけ買える方針で。 fftw_destroy_plan(iniL2); iniL2 = fftw_plan_dft_r2c_1d(cframe2, iinL, ioutL, FFTW_ESTIMATE);// for (int h=0; h<cframe2; h++){ iw[h] = (0.5 - 0.5 * cos( 2.0 * M_PI * h / cframe2)); } } } // ------------------------------------------------------------------------------------ // FFTW setting void TempoPitch::FFTWalloc(){ inL = new FLOAT[frame * bs]; sigBuf.init(bs, frame); // inL outL = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*(frame/2+1)*bs); cmpSpec.init(bs, frame / 2 + 1); //outL plans.alloc(bs); inv_plans.alloc(bs); // たくさん使うのはestimateじゃなくて実測のやつにするべき。 for (int j=0; j<bs; j++){ plans[j] = fftw_plan_dft_r2c_1d(frame, inL+j*frame, outL+j*(frame/2+1), FFTW_ESTIMATE ); inv_plans[j] = fftw_plan_dft_c2r_1d(frame, outL+j*(frame/2+1), inL+j*frame, FFTW_ESTIMATE ); } // ピッチ変換用? iinL = new FLOAT[frame * 4]; ioutL = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*(frame*2+1)); iniL = fftw_plan_dft_r2c_1d(frame, iinL, ioutL, FFTW_ESTIMATE); iiniL = fftw_plan_dft_c2r_1d(frame, ioutL, iinL, FFTW_ESTIMATE); iniL2 = fftw_plan_dft_r2c_1d(frame, iinL, ioutL, FFTW_ESTIMATE); } // ------------------------------------------------------------------------------------ void TempoPitch::init(int frame_, int shift_, int ch_, int bs_, int coeff_, int freq_, GUI *panel_){ frame = frame_; shift = shift_; bs = bs_; coeff = coeff_; panel = panel_; if(ch_ != 1){ DBGMSG("channel must be monaural"); exit(1); } //////// memory allocation refL = new FLOAT[coeff+1]; stateL = new FLOAT[coeff]; ampL = new FLOAT[(frame/2+1)*bs]; sigL = new FLOAT[frame+(bs-1)*shift]; //このへんのはこれでOK?もしかするとバッファが全然足りないのでは? bufL = new FLOAT[frame]; read_buffer.alloc(frame * 2); FFTWalloc(); generateWindow(); iframe_=0; tframe_=1; cframe2=frame; update_cframe2(); } // ------------------------------------------------------------------------------------ void TempoPitch::generateWindow(void){ w. alloc(frame); iw.alloc(frame * 4); a. alloc(frame); for (int h=0; h<frame; h++){ w[h] = 0.5 - 0.5 * cos(2.0 * M_PI * h / frame); iw[h] = w[h]; a[h] = w[h] / frame / (frame/shift) * 8 / 3; //frameで割るのはFTTWの仕様の為 } } // ------------------------------------------------------------------------------------ //包絡を維持した変換 void TempoPitch::pitch_modify(void){ SigRef2(iinL,cframe2,coeff,refL); //包絡(->iinL)と残差(->refL)を計算 fftw_execute(iniL2); //残差をフーリエ変換(リサンプリング) if (frame > cframe2){ for (int h = cframe2 / 2 + 1; h < frame / 2 + 1; h++){ ioutL[h][0] = ioutL[h][1] = 0.0; } } fftw_execute(iiniL);//リサンプリングされた残差を逆フーリエ変換 for(int h = 0; h < coeff; h++){ stateL[h]=0; } for(int h = 0; h < frame; h++){ iinL[h] = refsig(coeff, refL, stateL, iinL[h]) / frame; //包絡と残差を再合成 refsigって何の略? } } // ------------------------------------------------------------------------------------ void TempoPitch::update_callback_(void){ if(false){ while(1){ MUTEX.lock(); exec_count++; exec_count_total++; inverseFFT(); iFFTaddition(); iteration2(); MUTEX.unlock(); } } } // ------------------------------------------------------------------------------------ // apply inverse FFT for each frame void TempoPitch::inverseFFT(void){ for (int j = 0; j < bs; j++){ fftw_execute( inv_plans[j] ); for (int h = 0; h < frame; h++){ inL[j * frame + h] *= a[h]; } } } void TempoPitch::iFFTaddition(void){ for (int i = 0; i < frame + (bs - 1) * shift; i++){ sigL[i] = i < frame - shift ? bufL[i] : 0.; } for (int j = 0; j < bs; j++){ int offset1 = (tframe_ + j >= bs) ? (tframe_ + j - bs) * frame : (tframe_ + j) * frame; for (int h = 0; h < frame; h++){ sigL[j * shift + h] += inL[offset1 + h]; } } } void TempoPitch::iteration2(void){ for (int j = 0; j < bs; j++){ int offset2 = (j - tframe_) * shift + ((j < tframe_) ? bs * shift : 0 ); for (int h = 0; h < frame; h++){ inL[j * frame + h] = w[h] * sigL[h + offset2]; //窓関数をかける } fftw_execute(plans[j]); //フーリエ変換の実行 int offset1 = j * (frame / 2 + 1); for (int h = 0; h < frame / 2 + 1; h++){ double tmp = sqrt(outL[offset1+h][0]*outL[offset1+h][0]+outL[offset1+h][1]*outL[offset1+h][1]); if (tmp < 1e-100){ outL[offset1 + h][0] = 0.0; //二乗パワー更新(0のとき) outL[offset1 + h][1] = 0.0; //二乗パワー更新(0のとき) }else{ tmp = ampL[offset1+h]/tmp; outL[offset1 + h][0] *= tmp; //二乗パワー更新 outL[offset1 + h][1] *= tmp; //二乗パワー更新 } } } } // ------------------------------------------------------------------------------------------------------------- void TempoPitch::callback_(void){ while(1){ MUTEX.lock(); update_cframe2(); //////// block shift if (++iframe_ == bs) iframe_ = 0; //bsってのはブロックサイズ? if (++tframe_ == bs) tframe_ = 0; MUTEX.unlock(); read_data_from_the_input(cframe2); if(cframe2 != frame){ pitch_modify(); } fftw_execute(iniL); int s = (frame < cframe2 ? frame : cframe2) / 2 + 1; s = frame / 2 + 1; MUTEX.lock(); for (int h = 0; h < s; h++){ //回転させるということ? outL[iframe_ * (frame / 2 + 1) + h][0] = ioutL[h][0]; outL[iframe_ * (frame / 2 + 1) + h][1] = ioutL[h][1]; ampL[iframe_ * (frame / 2 + 1) + h] = sqrt(ioutL[h][0] * ioutL[h][0] + ioutL[h][1] * ioutL[h][1]); //ここで計算する必要性は? } for (int h = s; h < frame/2 + 1; h++){ /* outL[iframe_ * (frame / 2 + 1) + h][0] = 0.0; outL[iframe_ * (frame / 2 + 1) + h][1] = 0.0; ampL[iframe_ * (frame / 2 + 1) + h]=0.0; */ /* outL[iframe_ * (frame / 2 + 1) + h][0] = ioutL[s-1][0] / (2 * h/frame); outL[iframe_ * (frame / 2 + 1) + h][1] = ioutL[s-1][0] / (2 * h/frame); ampL[iframe_ * (frame / 2 + 1) + h]=sqrt(ioutL[s-1][0] * ioutL[s-1][0] + ioutL[s-1][1] * ioutL[s-1][1])/ (2 * h/frame); //ここで計算する必要性は? */ } MUTEX.unlock(); MUTEX.lock(); const int NNN = 1; for(int i = 0; i < NNN - 1; ++i){ exec_count++; exec_count_total++; inverseFFT(); iFFTaddition(); iteration2(); } exec_count++; exec_count_total++; inverseFFT(); iFFTaddition(); //お休みのしくみを入れる。 if(output->size() < 16000 * 0.5){ // 0.3秒以下では必ず出力、それ以上たまったら計算ぶんまわすフェーズに入る lastIteration(); } iteration2(); MUTEX.unlock(); } } // ------------------------------------------------------------------------------------ void TempoPitch::read_data_from_the_input(int modified_frame_length){ while(!input->read_data(&(read_buffer[0]), modified_frame_length)){ usleep(1000); } for(int i = 0; i < modified_frame_length; i++){ iinL[i] = read_buffer[i] * iw[i]; } //FLOAT tempo = (float)( panel->tempo.get() )/ 100.0; input->rewind_stream_a_little((int)( (modified_frame_length - shift * 1 /*tempo*/) )); } // ------------------------------------------------------------------------------------ void TempoPitch::lastIteration(void){ for (int h = 0; h < frame; h++){ bufL[h] += inL[tframe_ * frame + h]; //ループ終了分の結果 } push_data_to_the_output(); // shift for(int h = 0; h < frame; h++){ bufL[h] = h < frame - shift ? bufL[h + shift] : 0; } } void TempoPitch::push_data_to_the_output(void){ float *tmp = new float[shift]; for(int i = 0; i < shift; i++){ tmp[i] = static_cast<float>(bufL[i]); } output->push_data(tmp, shift); delete[] tmp; //kokode error ga okiteru? }
[ "tachi-hi@users.noreply.github.com" ]
tachi-hi@users.noreply.github.com
c16a65d053146580552c1dfcb4829f3c591341ab
6c77cf237697f252d48b287ae60ccf61b3220044
/aws-cpp-sdk-elasticloadbalancingv2/source/model/RedirectActionConfig.cpp
c69d92854e0d713cb9241f4ccb57962b9e5c1df9
[ "MIT", "Apache-2.0", "JSON" ]
permissive
Gohan/aws-sdk-cpp
9a9672de05a96b89d82180a217ccb280537b9e8e
51aa785289d9a76ac27f026d169ddf71ec2d0686
refs/heads/master
2020-03-26T18:48:43.043121
2018-11-09T08:44:41
2018-11-09T08:44:41
145,232,234
1
0
Apache-2.0
2018-08-30T13:42:27
2018-08-18T15:42:39
C++
UTF-8
C++
false
false
5,062
cpp
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/elasticloadbalancingv2/model/RedirectActionConfig.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::Utils::Xml; using namespace Aws::Utils; namespace Aws { namespace ElasticLoadBalancingv2 { namespace Model { RedirectActionConfig::RedirectActionConfig() : m_protocolHasBeenSet(false), m_portHasBeenSet(false), m_hostHasBeenSet(false), m_pathHasBeenSet(false), m_queryHasBeenSet(false), m_statusCode(RedirectActionStatusCodeEnum::NOT_SET), m_statusCodeHasBeenSet(false) { } RedirectActionConfig::RedirectActionConfig(const XmlNode& xmlNode) : m_protocolHasBeenSet(false), m_portHasBeenSet(false), m_hostHasBeenSet(false), m_pathHasBeenSet(false), m_queryHasBeenSet(false), m_statusCode(RedirectActionStatusCodeEnum::NOT_SET), m_statusCodeHasBeenSet(false) { *this = xmlNode; } RedirectActionConfig& RedirectActionConfig::operator =(const XmlNode& xmlNode) { XmlNode resultNode = xmlNode; if(!resultNode.IsNull()) { XmlNode protocolNode = resultNode.FirstChild("Protocol"); if(!protocolNode.IsNull()) { m_protocol = StringUtils::Trim(protocolNode.GetText().c_str()); m_protocolHasBeenSet = true; } XmlNode portNode = resultNode.FirstChild("Port"); if(!portNode.IsNull()) { m_port = StringUtils::Trim(portNode.GetText().c_str()); m_portHasBeenSet = true; } XmlNode hostNode = resultNode.FirstChild("Host"); if(!hostNode.IsNull()) { m_host = StringUtils::Trim(hostNode.GetText().c_str()); m_hostHasBeenSet = true; } XmlNode pathNode = resultNode.FirstChild("Path"); if(!pathNode.IsNull()) { m_path = StringUtils::Trim(pathNode.GetText().c_str()); m_pathHasBeenSet = true; } XmlNode queryNode = resultNode.FirstChild("Query"); if(!queryNode.IsNull()) { m_query = StringUtils::Trim(queryNode.GetText().c_str()); m_queryHasBeenSet = true; } XmlNode statusCodeNode = resultNode.FirstChild("StatusCode"); if(!statusCodeNode.IsNull()) { m_statusCode = RedirectActionStatusCodeEnumMapper::GetRedirectActionStatusCodeEnumForName(StringUtils::Trim(statusCodeNode.GetText().c_str()).c_str()); m_statusCodeHasBeenSet = true; } } return *this; } void RedirectActionConfig::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const { if(m_protocolHasBeenSet) { oStream << location << index << locationValue << ".Protocol=" << StringUtils::URLEncode(m_protocol.c_str()) << "&"; } if(m_portHasBeenSet) { oStream << location << index << locationValue << ".Port=" << StringUtils::URLEncode(m_port.c_str()) << "&"; } if(m_hostHasBeenSet) { oStream << location << index << locationValue << ".Host=" << StringUtils::URLEncode(m_host.c_str()) << "&"; } if(m_pathHasBeenSet) { oStream << location << index << locationValue << ".Path=" << StringUtils::URLEncode(m_path.c_str()) << "&"; } if(m_queryHasBeenSet) { oStream << location << index << locationValue << ".Query=" << StringUtils::URLEncode(m_query.c_str()) << "&"; } if(m_statusCodeHasBeenSet) { oStream << location << index << locationValue << ".StatusCode=" << RedirectActionStatusCodeEnumMapper::GetNameForRedirectActionStatusCodeEnum(m_statusCode) << "&"; } } void RedirectActionConfig::OutputToStream(Aws::OStream& oStream, const char* location) const { if(m_protocolHasBeenSet) { oStream << location << ".Protocol=" << StringUtils::URLEncode(m_protocol.c_str()) << "&"; } if(m_portHasBeenSet) { oStream << location << ".Port=" << StringUtils::URLEncode(m_port.c_str()) << "&"; } if(m_hostHasBeenSet) { oStream << location << ".Host=" << StringUtils::URLEncode(m_host.c_str()) << "&"; } if(m_pathHasBeenSet) { oStream << location << ".Path=" << StringUtils::URLEncode(m_path.c_str()) << "&"; } if(m_queryHasBeenSet) { oStream << location << ".Query=" << StringUtils::URLEncode(m_query.c_str()) << "&"; } if(m_statusCodeHasBeenSet) { oStream << location << ".StatusCode=" << RedirectActionStatusCodeEnumMapper::GetNameForRedirectActionStatusCodeEnum(m_statusCode) << "&"; } } } // namespace Model } // namespace ElasticLoadBalancingv2 } // namespace Aws
[ "magmarco@amazon.com" ]
magmarco@amazon.com
d24470e76d0a488610fd663191e121c2c4f84a7f
07c3e4c4f82056e76285c81f14ea0fbb263ed906
/Re-Abyss/app/components/Actor/Enemy/CodeZero/State/AngryState.hpp
5d59a7f060a758868e01f0aa3f319b996cfcd5cf
[]
no_license
tyanmahou/Re-Abyss
f030841ca395c6b7ca6f9debe4d0de8a8c0036b5
bd36687ddabad0627941dbe9b299b3c715114240
refs/heads/master
2023-08-02T22:23:43.867123
2023-08-02T14:20:26
2023-08-02T14:20:26
199,132,051
9
1
null
2021-11-22T20:46:39
2019-07-27T07:28:34
C++
UTF-8
C++
false
false
359
hpp
#pragma once #include <abyss/components/Actor/Enemy/CodeZero/State/BaseState.hpp> namespace abyss::Actor::Enemy::CodeZero { class AngryState final : public BaseState { public: void start() override; void end() override; Coro::Fiber<> updateAsync() override; void update() override; private: }; }
[ "tyanmahou@gmail.com" ]
tyanmahou@gmail.com
dcaf04a7bb5ac5408ccc4262c4f6a2e89c17d2f4
19194c2f2c07ab3537f994acfbf6b34ea9b55ae7
/android-33/android/os/PowerManager.def.hpp
2cf46e087da24471d4cf6f174448d689a593337a
[ "GPL-3.0-only" ]
permissive
YJBeetle/QtAndroidAPI
e372609e9db0f96602da31b8417c9f5972315cae
ace3f0ea2678967393b5eb8e4edba7fa2ca6a50c
refs/heads/Qt6
2023-08-05T03:14:11.842336
2023-07-24T08:35:31
2023-07-24T08:35:31
249,539,770
19
4
Apache-2.0
2022-03-14T12:15:32
2020-03-23T20:42:54
C++
UTF-8
C++
false
false
2,625
hpp
#pragma once #include "../../JObject.hpp" namespace android::os { class PowerManager_WakeLock; } class JString; namespace java::time { class Duration; } namespace android::os { class PowerManager : public JObject { public: // Fields static jint ACQUIRE_CAUSES_WAKEUP(); static JString ACTION_DEVICE_IDLE_MODE_CHANGED(); static JString ACTION_DEVICE_LIGHT_IDLE_MODE_CHANGED(); static JString ACTION_LOW_POWER_STANDBY_ENABLED_CHANGED(); static JString ACTION_POWER_SAVE_MODE_CHANGED(); static jint FULL_WAKE_LOCK(); static jint LOCATION_MODE_ALL_DISABLED_WHEN_SCREEN_OFF(); static jint LOCATION_MODE_FOREGROUND_ONLY(); static jint LOCATION_MODE_GPS_DISABLED_WHEN_SCREEN_OFF(); static jint LOCATION_MODE_NO_CHANGE(); static jint LOCATION_MODE_THROTTLE_REQUESTS_WHEN_SCREEN_OFF(); static jint ON_AFTER_RELEASE(); static jint PARTIAL_WAKE_LOCK(); static jint PROXIMITY_SCREEN_OFF_WAKE_LOCK(); static jint RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY(); static jint SCREEN_BRIGHT_WAKE_LOCK(); static jint SCREEN_DIM_WAKE_LOCK(); static jint THERMAL_STATUS_CRITICAL(); static jint THERMAL_STATUS_EMERGENCY(); static jint THERMAL_STATUS_LIGHT(); static jint THERMAL_STATUS_MODERATE(); static jint THERMAL_STATUS_NONE(); static jint THERMAL_STATUS_SEVERE(); static jint THERMAL_STATUS_SHUTDOWN(); // QJniObject forward template<typename ...Ts> explicit PowerManager(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {} PowerManager(QJniObject obj) : JObject(obj) {} // Constructors // Methods void addThermalStatusListener(JObject arg0) const; void addThermalStatusListener(JObject arg0, JObject arg1) const; java::time::Duration getBatteryDischargePrediction() const; jint getCurrentThermalStatus() const; jint getLocationPowerSaveMode() const; jfloat getThermalHeadroom(jint arg0) const; jboolean isBatteryDischargePredictionPersonalized() const; jboolean isDeviceIdleMode() const; jboolean isDeviceLightIdleMode() const; jboolean isIgnoringBatteryOptimizations(JString arg0) const; jboolean isInteractive() const; jboolean isLowPowerStandbyEnabled() const; jboolean isPowerSaveMode() const; jboolean isRebootingUserspaceSupported() const; jboolean isScreenOn() const; jboolean isSustainedPerformanceModeSupported() const; jboolean isWakeLockLevelSupported(jint arg0) const; android::os::PowerManager_WakeLock newWakeLock(jint arg0, JString arg1) const; void reboot(JString arg0) const; void removeThermalStatusListener(JObject arg0) const; }; } // namespace android::os
[ "YJBeetle@gmail.com" ]
YJBeetle@gmail.com
c1f313f46956bee418c7e5b4e4983846e1f9329a
b5dcb2c1ab57f5bcf6c781bea2744583673d22ee
/cpp/新建文件夹/code/2.cpp
c1f9336f7136575d037865c0102bf0df8f9561b7
[]
no_license
happyboyma/project1
b387694aaa694fd0c6debe383a75e2005a51cc1a
c926078a99a6a6c615af69b92528193f67946e73
refs/heads/master
2021-09-07T11:56:55.840724
2018-02-22T13:31:45
2018-02-22T13:31:45
106,287,724
0
0
null
null
null
null
UTF-8
C++
false
false
511
cpp
#include <iostream> using namespace std; int main() { int n = 1; float f = 1.1; double d = 1.2; char c = '*'; cout << "The address of n is " << &n << endl; cout << "The address of f is " << &f << endl; cout << "The address of d is " << &d << endl; cout << "The address of c is " << &c << endl; int* pn = &n; float* pf = &f; double* pd = &d; char* pc = &c; cout << "pn:" << *pn << endl; cout << "pf:" << *pf << endl; cout << "pd:" << *pd << endl; cout << "pc:" << *pc << endl; return 0; }
[ "32641666+happyboyma@users.noreply.github.com" ]
32641666+happyboyma@users.noreply.github.com
7aedb5f31cd997d3628a278897d0c87667d0661e
e188889da5f67128085dacacbe2fae12360284b2
/Implementation of Tower of HANOI in using C++ program.cpp
7cfc4d742052807e644cb310b708a5a16e63f32e
[]
no_license
lohitakshsingla0/Data-Structures-Questions
1614423f31ddd09e3304f3a3e067cf413ba996f9
72251374c9263ccc6fe3cd33ef0d8f1718841a40
refs/heads/master
2021-01-23T17:36:11.550958
2017-12-09T06:32:15
2017-12-09T06:32:15
102,769,760
1
0
null
null
null
null
UTF-8
C++
false
false
456
cpp
#include<iostream> using namespace std; //tower of HANOI function implementation void TOH(int n,char Sour, char Aux,char Des) { if(n==1) { cout<<"Move Disk "<<n<<" from "<<Sour<<" to "<<Des<<endl; return; } TOH(n-1,Sour,Des,Aux); cout<<"Move Disk "<<n<<" from "<<Sour<<" to "<<Des<<endl; TOH(n-1,Aux,Sour,Des); } //main program int main() { int n; cout<<"Enter no. of disks:"; cin>>n; //calling the TOH TOH(n,'A','B','C'); return 0; }
[ "lohitakshsingla0@gmail.com" ]
lohitakshsingla0@gmail.com
13c38af2139b9dd068eb8f69c77e3f030ed4e242
785df77400157c058a934069298568e47950e40b
/TnbCad2d/TnbLib/Cad2d/Intersection/Entities/Segment/Orthogonal/Cad2d_IntsctEntity_OrthSegment.hxx
9b343c73b998c09bcdddbdbd38c9e6272eb6bbf0
[]
no_license
amir5200fx/Tonb
cb108de09bf59c5c7e139435e0be008a888d99d5
ed679923dc4b2e69b12ffe621fc5a6c8e3652465
refs/heads/master
2023-08-31T08:59:00.366903
2023-08-31T07:42:24
2023-08-31T07:42:24
230,028,961
9
3
null
2023-07-20T16:53:31
2019-12-25T02:29:32
C++
UTF-8
C++
false
false
1,887
hxx
#pragma once #ifndef _Cad2d_IntsctEntity_OrthSegment_Header #define _Cad2d_IntsctEntity_OrthSegment_Header #include <Cad2d_IntsctEntity_Segment.hxx> #include <Pnt2d.hxx> #include <Cad2d_Module.hxx> namespace tnbLib { // Forward Declarations class Pln_Curve; class Cad2d_IntsctEntity_OrthSegment : public Cad2d_IntsctEntity_Segment { /*Private Data*/ Standard_Real theParameter_; Pnt2d theCoord_; // private functions and operators [3/22/2022 Amir] friend class boost::serialization::access; template<class Archive> void serialize(Archive& ar, const unsigned int file_version) { ar& boost::serialization::base_object<Cad2d_IntsctEntity_Segment>(*this); ar& theParameter_; ar& theCoord_; } public: //- default constructor Cad2d_IntsctEntity_OrthSegment() : theParameter_(0) , theCoord_(Pnt2d::null) {} //- constructors explicit Cad2d_IntsctEntity_OrthSegment(const Standard_Integer theIndex) : Cad2d_IntsctEntity_Segment(theIndex) , theParameter_(0) , theCoord_(Pnt2d::null) {} Cad2d_IntsctEntity_OrthSegment(const Standard_Integer theIndex, const word& theName) : Cad2d_IntsctEntity_Segment(theIndex, theName) , theParameter_(0) , theCoord_(Pnt2d::null) {} //- public functions and operators Standard_Boolean IsOrthogonal() const override { return Standard_True; } Standard_Real CharParameter() const override { return theParameter_; } static TnbCad2d_EXPORT std::tuple<std::shared_ptr<Pln_Curve>, std::shared_ptr<Pln_Curve>> SubdivideCurve ( const Pln_Curve& theCurve, const Cad2d_IntsctEntity_OrthSegment& theEntity ); //- Macros GLOBAL_ACCESS_PRIM_SINGLE(Standard_Real, Parameter) GLOBAL_ACCESS_SINGLE(Pnt2d, Coord) }; } BOOST_CLASS_EXPORT_KEY(tnbLib::Cad2d_IntsctEntity_OrthSegment); #endif // !_Cad2d_IntsctEntity_OrthSegment_Header
[ "aasoleimani86@gmail.com" ]
aasoleimani86@gmail.com
3cb8e91de1cf8a9f342e23e743cebb0a75f1feb4
987adde7bd3455da593f0201b4fe0437f65b5f27
/CodeSource/IRGeneration/GloabalVariableGenerator.cpp
6ddf75b50d05a70302c7b3fe966d4c9a3c7a1587
[]
no_license
xcode2010/KawaCompiler
d502ca2b290d8443753bb18815dcd696715baffc
3c1b37f86e46084d6d43bbd6771b98808006135d
refs/heads/master
2021-12-05T15:16:56.765143
2015-06-30T08:16:00
2015-06-30T08:16:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,438
cpp
#include "GlobalVariableGenerator.h" //Cree une variable statique Value* GlobalVariableGenerator::createStaticAttribute( Module *module, std::string className , std::string name, std::string type) { std::string varN = NameBuilder::build(className, name); Type *t = TypeGenerator::StrToLLVMType(module, type); GlobalVariable *gv = new GlobalVariable(module, t, false, GlobalValue::CommonLinkage, 0, varN); return gv; } // Retourne une variable statique Value* GlobalVariableGenerator::getStaticAttribut(Module *module, std::string className, std::string name) { std::string varN = NameBuilder::build(className, name); return module->getGlobalVariable(varN); } // Cree un l'index d'un attribut Value* GlobalVariableGenerator::createOfIndexMember(Module *module, std::string name, int index) { Type *t = Type::getInt32Ty(module->getContext()); Constant *c = ConstantInt::get(t ,index); GlobalVariable *gv = new GlobalVariable(module, t, false, GlobalValue::CommonLinkage, c, name); return gv; } // Retourne un objet value contenant un entier Value* GlobalVariableGenerator::getIndexOfMember(Module *module, std::string name) { GlobalVariable *g = module->getGlobalVariable (name); if(!g->getType() != Type::getInt32Ty(module->getContext())) return NULL; Value *v = new LoadInst(g, MEMBER_INDEX); return v; } // Creee une table AdHoc Value* GlobalVariableGenerator::createAdHocTable(Module *module, std::string classStatic, std::string classDynamic, std::vector<Value *> functions) { if() { } int size = functions.size(); Type* i8ptr = Type::getInt8Ty(module->getContext())->getPointerTo(); Type* arty = ArrayType::get(i8ptr, size); std::vector<Constant *> casts; Constant *cast; for(int i = 0; i < list_function.size(); i++) { cast = ConstExpr::getBitCast(functions[i], i8ptr); casts.push_back(cast); } std::string tableName = NameBuilder::createAdHocTableName(classStatic, classDynamic); GlobalVariable *table = new GlobalVariable( module, arty, true, GlobalValue::CommonLinkage, casts, tableName); return table; } // Retourne une table AdHoc Value* GlobalVariableGenerator::getAdHocTable(Module *module, std::string classStatic, std::string classDynamic) { std::string tableName = NameBuilder::createAdHocTable(classStatic, classDynamic); return module->getGlobalVariable(tableName); }
[ "adjibi004@gmail.com" ]
adjibi004@gmail.com
49674e05b68ad28a45a0744d9fedc033d95249b3
fb15a40e4b3735900ba8f54f5b7dac05f6f17311
/src/engine/gameobject/Entity.cpp
013b977e15ad92d0f036b18beba388d01c4a8f00
[]
no_license
tomvidm/Pierogi2D-old
c99d2add1599b1703be7e6f032a0639a434ff6cb
bf165b5138d6c78e92ad0e4ebd42f4ac9f31932b
refs/heads/master
2021-07-17T20:21:06.546797
2017-10-26T05:07:44
2017-10-26T05:07:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
65
cpp
#include "Entity.h" namespace engine { namespace gameobject { }}
[ "tomvidm@gmail.com" ]
tomvidm@gmail.com
473613f937862607be33bbd790c2234adb70db86
df16b684db18d657c340dffe4c4dfd4d9da205ef
/src/Machine.cpp
212538d64f0fd2cc95f6e58947eab4dbc8f74544
[]
no_license
Marneus68/state_machine
a25287d936d0caa2d02d47d3d52365eaf9763e21
d7ebd2eebcceb22a8812cd6ab84c3cc5e8e840ef
refs/heads/master
2016-09-06T12:30:51.827399
2015-04-25T23:03:58
2015-04-25T23:03:58
34,589,560
0
0
null
null
null
null
UTF-8
C++
false
false
572
cpp
#include "Machine.h" #include "IdleState.h" namespace sm { Machine::Machine() { state = new IdleState(this); } Machine::Machine(const Machine & _machine) { state = _machine.state; } Machine::~Machine() { delete state; } Machine & Machine::operator=(Machine & _machine) { state = _machine.state; return *this; } void Machine::changeState(sm::AbstractState * _state) { state = _state; } void Machine::saySomething(void) { state->saySomething(); } } /* sm */
[ "duane.bekaert@gmail.com" ]
duane.bekaert@gmail.com