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
112b1e81849b763723ad3afcdc9b8502a92f2376
af4208aaedcfe4c10ef3e13cc01cbf49d98fcde8
/include/IWallet.h
f39ceba1f23e7a69504d49dae5f70d2d826e8b9b
[ "BSD-3-Clause" ]
permissive
santosha2003/citicash
c2d06359e7a70e0fb2ffe6ae73607bcc491fa028
54216781524b38cd24ad4a7be1ee21aec715f270
refs/heads/master
2020-03-30T09:17:00.061959
2018-10-23T07:06:34
2018-10-23T07:06:34
151,069,306
0
2
NOASSERTION
2018-10-20T18:46:06
2018-10-01T10:10:43
C++
UTF-8
C++
false
false
4,634
h
// Copyright (c) 2014-2016, The Monero Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers #pragma once #include <array> #include <cstdint> #include <istream> #include <limits> #include <ostream> #include <string> #include <system_error> #include <vector> namespace CryptoNote { typedef size_t TransactionId; typedef size_t TransferId; typedef std::array<uint8_t, 32> TransacitonHash; struct Transfer { std::string address; int64_t amount; }; const TransactionId INVALID_TRANSACTION_ID = std::numeric_limits<TransactionId>::max(); const TransferId INVALID_TRANSFER_ID = std::numeric_limits<TransferId>::max(); const uint64_t UNCONFIRMED_TRANSACTION_HEIGHT = std::numeric_limits<uint64_t>::max(); struct Transaction { TransferId firstTransferId; size_t transferCount; int64_t totalAmount; uint64_t fee; TransacitonHash hash; bool isCoinbase; uint64_t blockHeight; uint64_t timestamp; std::string extra; }; class IWalletObserver { public: virtual void initCompleted(std::error_code result) {} virtual void saveCompleted(std::error_code result) {} virtual void synchronizationProgressUpdated(uint64_t current, uint64_t total) {} virtual void actualBalanceUpdated(uint64_t actualBalance) {} virtual void pendingBalanceUpdated(uint64_t pendingBalance) {} virtual void externalTransactionCreated(TransactionId transactionId) {} virtual void sendTransactionCompleted(TransactionId transactionId, std::error_code result) {} virtual void transactionUpdated(TransactionId transactionId) {} }; class IWallet { public: virtual ~IWallet() = 0; virtual void addObserver(IWalletObserver* observer) = 0; virtual void removeObserver(IWalletObserver* observer) = 0; virtual void initAndGenerate(const std::string& password) = 0; virtual void initAndLoad(std::istream& source, const std::string& password) = 0; virtual void shutdown() = 0; virtual void save(std::ostream& destination, bool saveDetailed = true, bool saveCache = true) = 0; virtual std::error_code changePassword(const std::string& oldPassword, const std::string& newPassword) = 0; virtual std::string getAddress() = 0; virtual uint64_t actualBalance() = 0; virtual uint64_t pendingBalance() = 0; virtual size_t getTransactionCount() = 0; virtual size_t getTransferCount() = 0; virtual TransactionId findTransactionByTransferId(TransferId transferId) = 0; virtual bool getTransaction(TransactionId transactionId, Transaction& transaction) = 0; virtual bool getTransfer(TransferId transferId, Transfer& transfer) = 0; virtual TransactionId sendTransaction(const Transfer& transfer, uint64_t fee, const std::string& extra = "", uint64_t mixIn = 0, uint64_t unlockTimestamp = 0) = 0; virtual TransactionId sendTransaction(const std::vector<Transfer>& transfers, uint64_t fee, const std::string& extra = "", uint64_t mixIn = 0, uint64_t unlockTimestamp = 0) = 0; virtual std::error_code cancelTransaction(size_t transferId) = 0; }; }
[ "sumoshi.tanaka@gmail.com" ]
sumoshi.tanaka@gmail.com
b6af67a6afa9923d717fb43b75489540641fd8c8
f1d14ae63f827b5a4cd2691f973340e61f55dc3e
/src/tests/traverse.cpp
6577c02596af3578287135bfadebc63e0c3b0f0d
[]
no_license
jvanns/verbatim
44b705ef45db3e9ddce034340d2f1741eaa4b552
2de560f4a31fd05fa328ddaf7b296d4ec8fe5ee4
refs/heads/master
2021-01-02T08:40:39.169934
2015-08-26T22:31:44
2015-08-26T22:31:44
34,211,237
2
0
null
null
null
null
UTF-8
C++
false
false
1,497
cpp
/* * vim: set smartindent autoindent expandtab tabstop=4 shiftwidth=4: */ // verbatim #include "Traverse.hpp" // libstdc++ #include <iostream> using std::cout; using std::cerr; using std::endl; namespace { /* * Traversal callback no. 1 */ class RegisterPath : public verbatim::Traverse::Callback { public: RegisterPath() : tally(0) {} ~RegisterPath() { cout << "Received " << tally << " paths\n"; } void operator() (const verbatim::Traverse::Path &p) { cout << p.name << endl; ++tally; } private: size_t tally; }; /* * Traversal callback no. 2 */ class AggregateSize : public verbatim::Traverse::Callback { public: AggregateSize() : size(0) {} ~AggregateSize() { cout << "Aggregate file size: " << size / static_cast<double>(1UL << 20) << " MB\n"; } void operator() (const verbatim::Traverse::Path &p) { if (S_ISREG(p.info->st_mode)) size += p.info->st_size; } private: size_t size; }; } // anonymous int main(int argc, char *argv[]) { using verbatim::Traverse; if (!argv[1]) { cerr << "Provide a source 'root' path" << endl; return 1; } Traverse t; RegisterPath callback1; AggregateSize callback2; t.register_callback(&callback1); t.register_callback(&callback2); t.scan(argv[1]); return 0; }
[ "james.vanns@gmail.com" ]
james.vanns@gmail.com
173d3dad90d87171bb04767b601cebf03901c852
0406821f59a5a524ba2fa87fd8a38e4692a8bf0d
/src/com/devsda/gargantua/asignments/2/63.cpp
cda2f8984e5a08b555e7e569353d2ca4ffc4c5b1
[ "MIT" ]
permissive
devvsda/gargantua
bedc3fa2b8d4e9c5dfb6e28546bafd2c367a611c
9e41f87d5c73920611bafdfa15047639cb322809
refs/heads/master
2021-08-30T13:45:12.457326
2017-12-18T06:23:13
2017-12-18T06:23:13
114,602,637
0
0
null
null
null
null
UTF-8
C++
false
false
697
cpp
#include<iostream> using namespace std; void print(char answer[]) { for(int i = 0; i < 6; i++) { cout << answer[i]; } cout << endl; } void printAnagram(string s1, int i, int M, string s2, int j, int N, char answer[], int index) { if(i == M && j == N) { print(answer);// << endl; return; } if(i < M) { answer[index] = s1[i]; printAnagram(s1, i+1, M, s2, j, N, answer, index+1); } if(j < N) { answer[index] = s2[j]; printAnagram(s1, i, M, s2, j+1, N, answer, index+1); } } main() { char answer[6]; printAnagram("XYZ", 0, 3, "ABC", 0, 3, answer, 0); return 0; }
[ "hijhamb@Hiteshs-MacBook-Pro.local" ]
hijhamb@Hiteshs-MacBook-Pro.local
d0d2fd3680455f54ccbaf66e851ea966cb1e9460
fb5b25b4fbe66c532672c14dacc520b96ff90a04
/export/release/windows/obj/src/resources/__res_9.cpp
cd6bd33a3b955cd16ab7e535335be2fb37afa34b
[ "Apache-2.0" ]
permissive
Tyrcnex/tai-mod
c3849f817fe871004ed171245d63c5e447c4a9c3
b83152693bb3139ee2ae73002623934f07d35baf
refs/heads/main
2023-08-15T07:15:43.884068
2021-09-29T23:39:23
2021-09-29T23:39:23
383,313,424
1
0
null
null
null
null
UTF-8
C++
false
false
3,446
cpp
namespace hx { unsigned char __res_9[] = { 0x80, 0x00, 0x00, 0x80, 137,80,78,71,13,10,26,10,0,0, 0,13,73,72,68,82,0,0,0,16, 0,0,0,16,8,3,0,0,0,40, 45,15,83,0,0,0,32,99,72,82, 77,0,0,122,37,0,0,128,131,0, 0,249,255,0,0,128,233,0,0,117, 48,0,0,234,96,0,0,58,152,0, 0,23,111,146,95,197,70,0,0,3, 0,80,76,84,69,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,9,9,9,10,10,10,11,11, 11,12,12,12,13,13,13,14,14,14, 15,15,15,16,16,16,17,17,17,18, 18,18,19,19,19,20,20,20,21,21, 21,22,22,22,23,23,23,24,24,24, 25,25,25,26,26,26,27,27,27,28, 28,28,29,29,29,30,30,30,31,31, 31,32,32,32,33,33,33,34,34,34, 35,35,35,36,36,36,37,37,37,38, 38,38,39,39,39,40,40,40,41,41, 41,42,42,42,43,43,43,44,44,44, 45,45,45,46,46,46,47,47,47,48, 48,48,49,49,49,50,50,50,51,51, 51,52,52,52,53,53,53,54,54,54, 55,55,55,56,56,56,57,57,57,58, 58,58,59,59,59,60,60,60,61,61, 61,62,62,62,63,63,63,64,64,64, 65,65,65,66,66,66,67,67,67,68, 68,68,69,69,69,70,70,70,71,71, 71,72,72,72,73,73,73,74,74,74, 75,75,75,76,76,76,77,77,77,78, 78,78,79,79,79,80,80,80,81,81, 81,82,82,82,83,83,83,84,84,84, 85,85,85,86,86,86,87,87,87,88, 88,88,89,89,89,90,90,90,91,91, 91,92,92,92,93,93,93,94,94,94, 95,95,95,96,96,96,97,97,97,98, 98,98,99,99,99,100,100,100,101,101, 101,102,102,102,103,103,103,104,104,104, 105,105,105,106,106,106,107,107,107,108, 108,108,109,109,109,110,110,110,111,111, 111,112,112,112,113,113,113,114,114,114, 115,115,115,116,116,116,117,117,117,118, 118,118,119,119,119,120,120,120,121,121, 121,122,122,122,123,123,123,124,124,124, 125,125,125,126,126,126,127,127,127,128, 128,128,129,129,129,130,130,130,131,131, 131,132,132,132,133,133,133,134,134,134, 135,135,135,136,136,136,137,137,137,138, 138,138,139,139,139,140,140,140,141,141, 141,142,142,142,143,143,143,144,144,144, 145,145,145,146,146,146,147,147,147,148, 148,148,149,149,149,150,150,150,151,151, 151,152,152,152,153,153,153,154,154,154, 155,155,155,156,156,156,157,157,157,158, 158,158,159,159,159,160,160,160,161,161, 161,162,162,162,163,163,163,164,164,164, 165,165,165,166,166,166,167,167,167,168, 168,168,169,169,169,170,170,170,171,171, 171,172,172,172,173,173,173,174,174,174, 175,175,175,176,176,176,177,177,177,178, 178,178,179,179,179,180,180,180,181,181, 181,182,182,182,183,183,183,184,184,184, 185,185,185,186,186,186,187,187,187,188, 188,188,189,189,189,190,190,190,191,191, 191,192,192,192,193,193,193,194,194,194, 195,195,195,196,196,196,197,197,197,198, 198,198,199,199,199,200,200,200,201,201, 201,202,202,202,203,203,203,204,204,204, 205,205,205,206,206,206,207,207,207,208, 208,208,209,209,209,210,210,210,211,211, 211,212,212,212,213,213,213,214,214,214, 215,215,215,216,216,216,217,217,217,218, 218,218,219,219,219,220,220,220,221,221, 221,222,222,222,223,223,223,224,224,224, 225,225,225,226,226,226,227,227,227,228, 228,228,229,229,229,230,230,230,231,231, 231,232,232,232,233,233,233,234,234,234, 235,235,235,236,236,236,237,237,237,238, 238,238,239,239,239,240,240,240,241,241, 241,242,242,242,243,243,243,244,244,244, 245,245,245,246,246,246,247,247,247,248, 248,248,249,249,249,250,250,250,251,251, 251,252,252,252,253,253,253,254,254,254, 255,255,255,160,81,73,215,0,0,0, 1,116,82,78,83,0,64,230,216,102, 0,0,0,52,73,68,65,84,120,218, 172,206,57,14,0,48,8,3,65,231, 244,254,255,197,41,3,212,208,141,101, 75,72,189,7,217,46,129,225,198,170, 97,254,45,201,58,64,180,52,138,165, 197,238,252,255,13,0,129,199,0,248, 198,82,95,225,0,0,0,0,73,69, 78,68,174,66,96,130,0x00 }; }
[ "72734817+khiodev@users.noreply.github.com" ]
72734817+khiodev@users.noreply.github.com
8fcee52a232744a6ae731c45b3065f07287b2498
569d64661f9e6557022cc45428b89eefad9a6984
/code/gameholder/equip_quality_attribute_config.cpp
8c79618612a62edb0e9aea980080d3eb675ae166
[]
no_license
dgkang/ROG
a2a3c8233c903fa416df81a8261aab2d8d9ac449
115d8d952a32cca7fb7ff01b63939769b7bfb984
refs/heads/master
2020-05-25T02:44:44.555599
2019-05-20T08:33:51
2019-05-20T08:33:51
187,584,950
0
1
null
2019-05-20T06:59:06
2019-05-20T06:59:05
null
UTF-8
C++
false
false
4,473
cpp
//auto created by structual_xml.py #include "gameholder_pch.h" #include "equip_quality_attribute_config.h" void EQUIP_QUALITY_ATTRIBUTE_ROOT_PROP_STRUCT::parse(TiXmlElement* xmlRoot) { if (!xmlRoot) return; if (xmlRoot->Attribute("class_14")) { class_14 = (int32)atoi(xmlRoot->Attribute("class_14")); } else { CnWarn("Can't find '%s' attribute '%s' \n", xmlRoot->Value(), "class_14"); } if (xmlRoot->Attribute("class_10")) { class_10 = (int32)atoi(xmlRoot->Attribute("class_10")); } else { CnWarn("Can't find '%s' attribute '%s' \n", xmlRoot->Value(), "class_10"); } if (xmlRoot->Attribute("class_11")) { class_11 = (int32)atoi(xmlRoot->Attribute("class_11")); } else { CnWarn("Can't find '%s' attribute '%s' \n", xmlRoot->Value(), "class_11"); } if (xmlRoot->Attribute("class_12")) { class_12 = (int32)atoi(xmlRoot->Attribute("class_12")); } else { CnWarn("Can't find '%s' attribute '%s' \n", xmlRoot->Value(), "class_12"); } if (xmlRoot->Attribute("class_13")) { class_13 = (int32)atoi(xmlRoot->Attribute("class_13")); } else { CnWarn("Can't find '%s' attribute '%s' \n", xmlRoot->Value(), "class_13"); } if (xmlRoot->Attribute("class_2")) { class_2 = (int32)atoi(xmlRoot->Attribute("class_2")); } else { CnWarn("Can't find '%s' attribute '%s' \n", xmlRoot->Value(), "class_2"); } if (xmlRoot->Attribute("class_3")) { class_3 = (int32)atoi(xmlRoot->Attribute("class_3")); } else { CnWarn("Can't find '%s' attribute '%s' \n", xmlRoot->Value(), "class_3"); } if (xmlRoot->Attribute("class_1")) { class_1 = (int32)atoi(xmlRoot->Attribute("class_1")); } else { CnWarn("Can't find '%s' attribute '%s' \n", xmlRoot->Value(), "class_1"); } if (xmlRoot->Attribute("class_6")) { class_6 = (int32)atoi(xmlRoot->Attribute("class_6")); } else { CnWarn("Can't find '%s' attribute '%s' \n", xmlRoot->Value(), "class_6"); } if (xmlRoot->Attribute("class_7")) { class_7 = (int32)atoi(xmlRoot->Attribute("class_7")); } else { CnWarn("Can't find '%s' attribute '%s' \n", xmlRoot->Value(), "class_7"); } if (xmlRoot->Attribute("class_4")) { class_4 = (int32)atoi(xmlRoot->Attribute("class_4")); } else { CnWarn("Can't find '%s' attribute '%s' \n", xmlRoot->Value(), "class_4"); } if (xmlRoot->Attribute("class_5")) { class_5 = (int32)atoi(xmlRoot->Attribute("class_5")); } else { CnWarn("Can't find '%s' attribute '%s' \n", xmlRoot->Value(), "class_5"); } if (xmlRoot->Attribute("class_8")) { class_8 = (int32)atoi(xmlRoot->Attribute("class_8")); } else { CnWarn("Can't find '%s' attribute '%s' \n", xmlRoot->Value(), "class_8"); } if (xmlRoot->Attribute("class_9")) { class_9 = (int32)atoi(xmlRoot->Attribute("class_9")); } else { CnWarn("Can't find '%s' attribute '%s' \n", xmlRoot->Value(), "class_9"); } if (xmlRoot->Attribute("id")) { id = (int32)atoi(xmlRoot->Attribute("id")); } else { CnWarn("Can't find '%s' attribute '%s' \n", xmlRoot->Value(), "id"); } } void EQUIP_QUALITY_ATTRIBUTE_ROOT_STRUCT::parse(TiXmlElement* xmlRoot) { if (!xmlRoot) return; for(TiXmlElement* childEle = xmlRoot->FirstChildElement(); childEle; childEle = childEle->NextSiblingElement()) { if (Crown::SDStrcmp(childEle->Value(), "prop") == 0) { EQUIP_QUALITY_ATTRIBUTE_ROOT_PROP_STRUCT StructTplt; StructTplt.clear(); StructTplt.parse(childEle); prop_list.push_back(StructTplt); continue; } } } IMPLEMENT_SINGLETON(EQUIP_QUALITY_ATTRIBUTE_ENTRY) bool EQUIP_QUALITY_ATTRIBUTE_ENTRY::LoadConfig(const char* path) { char file_path[SD_MAX_PATH]; SDSprintf(file_path, "%s%s", path, "equip_quality_attribute.xml"); TiXmlDocument xmlDoc; if (!xmlDoc.LoadFile(file_path)) { CnError("Load file: %s failed\n", file_path); return false; } TiXmlElement* xmlRoot = xmlDoc.RootElement(); if(!xmlRoot) return false; m_Struct.parse(xmlRoot); return true; }
[ "judge23253@sina.com" ]
judge23253@sina.com
b1691ee3100822ca817666d76828167afa59f8ca
f8ba9c8f132abcdef35dadf8d80efcb6da026e57
/pcl_3d_clusters/include/pcl_3d_clusters/point_cloud_processor.h
199e94ba6a03f19fbac0e7366e1a8966a0a6d040
[ "Apache-2.0" ]
permissive
Kukanani/vision_msgs_examples
f0598a1c403fce45d5888603951a880ad3f01f4c
ca1c4936eeaa0912f73a0cfd7f7d22b46b66d866
refs/heads/kinetic-devel
2022-02-23T02:38:43.616942
2022-02-11T14:38:04
2022-02-11T14:38:04
94,136,156
3
1
Apache-2.0
2022-02-11T02:34:44
2017-06-12T20:10:52
C++
UTF-8
C++
false
false
7,907
h
// Copyright (c) 2015, Adam Allevato // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef _POINT_CLOUD_PROCESSOR_H_ #define _POINT_CLOUD_PROCESSOR_H_ #define _USE_MATH_DEFINES #include <cmath> #include <pcl/ModelCoefficients.h> #include <pcl/point_types.h> #include <pcl/io/pcd_io.h> #include <pcl/filters/extract_indices.h> #include <pcl/filters/voxel_grid.h> #include <pcl/filters/conditional_removal.h> #include <pcl/features/normal_3d.h> #include <pcl/kdtree/kdtree.h> #include <pcl/common/transforms.h> #include <pcl/sample_consensus/method_types.h> #include <pcl/sample_consensus/model_types.h> #include <pcl/segmentation/sac_segmentation.h> #include <pcl/segmentation/extract_clusters.h> #include <ros/ros.h> #include <tf/transform_listener.h> #include <pcl_ros/transforms.h> #include <pcl_conversions/pcl_conversions.h> //useful PCL typedefs typedef pcl::PointXYZRGB PointType; typedef pcl::PointCloud<PointType> PC; typedef pcl::PointCloud<PointType>::Ptr PCP; typedef std::vector<pcl::PointIndices> IndexVector; class PointCloudProcessor { private: /*================================================*/ /* CLASS VARS */ /*================================================*/ /// Standard ROS node handle ros::NodeHandle node; /// Publishes planes cut from the scene ros::Publisher allPlanesPublisher; /// Publishes clipped cloud after voxel gridification ros::Publisher voxelPublisher; /** * Publishes the various clusters identified by the Euclidean algorithm. * All of these will lie within the bounded_scene point cloud. * NOTE: concatenated clouds from pre_clustering = bounded_scene - planes */ ros::Publisher allObjectsPublisher; /// Publishes the first (largest) cluster in the scene. ros::Publisher largestObjectPublisher; /// Publishes detected objects in vision_msgs format. ros::Publisher detectionPublisher; /// Listens for new point clouds to process ros::Subscriber pointCloudSub; /*================================================*/ /* SEGMENTATION PARAMS */ /*================================================*/ //The minimum camera-space X for the working area bounding box ///flags for publishing various intermediate point clouds bool _publishAllObjects = true; bool _publishAllPlanes = false; bool _publishLargestObject = false; bool _publishVoxelScene = false; int maxClusters = 10; /** * The maximum number of iterations to perform when looking for planar features. */ int maxPlaneSegmentationIterations = 50; /** * The maximum distance that a point can be from a planar feature to be considered part of that * planar feature. */ float segmentationDistanceThreshold = 0.01; /** * The percentage of the scene to analyze (pass onward to clustering). * The clustering algorithm will continue to remove planar features until this condition * is satisfied. * * 1.0 = the entire scene is one object * 0.0 = nothing will be analyzed */ float percentageToAnalyze = 0.2; /** * The distance between points in the voxel grid (used to clean up the point cloud and make * it well-behaved for further analysis). If this value is too small, the grid will be too fine. * there won't be enough integers to provide indices for each point and you will get errors. */ float voxelLeafSize = 0.005; /** * The maximum distance between points in a cluster (used in the Euclidean * clustering algorithm). */ float clusterTolerance = 0.03; /** * Clusters with less than this number of points won't be analyzed. Usually this is used to * filter out small point clouds like anomalies, noise, bits of whatnot in the scene, etc. */ int minClusterSize = 200; /** * Clusters that have more than this number of points won't be analyzed. The assumption * is that this is either a) too computationally intensive to analyze, or b) this is just a * background object like a wall which should be ignored anyway. */ int maxClusterSize = 2000; ///input is stored here PCP inputCloud; ///used as intermediate step for cloud processing PCP processCloud; std::vector<PCP> clusters; std::string originalCloudFrame = ""; std::string cloudTopicName = ""; /*================================================*/ /* FILTERING STEPS (FUNCTIONS) */ /*================================================*/ public: /** * Create a voxel grid based on point cloud data. See * http://www.pointclouds.org/documentation/tutorials/voxel_grid.php and * http://docs.pointclouds.org/1.7.1/classpcl_1_1_voxel_grid.html. * @param loose unstructured (not on a grid) point cloud * @param gridSize the distance between voxels in the grid * @return the points of the voxel grid created from the input */ PCP& voxelGridify(PCP &loose, float gridSize); /** * Segment out planar clouds. See * http://pointclouds.org/documentation/tutorials/planar_segmentation.php * @param input the point cloud from which to remove planes * @param maxIterations maximum iterations for clustering algorithm. * @param thresholdDistance how close a point must be to hte model in order to be considered * an inlier. * @param percentageGood keep removing planes until the amount of data left is less than this * percentage of the initial data. * @return the point cloud with primary planes removed as specified. */ PCP& removePrimaryPlanes(PCP &input, int maxIterations, float thresholdDistance, float percentageGood); PCP& clipByDistance(PCP &unclipped, float minX, float maxX, float minY, float maxY, float minZ, float maxZ); /** * Euclidean clustering algorithm. See * http://www.pointclouds.org/documentation/tutorials/cluster_extraction.php * @param input the cloud to cluster * @param clusterTolerance the maximum distance between points in a given cluster * @param minClusterSize clusters of size less than this will be discarded * @param maxClusterSize clusters of size greater than this will be discarded * @return a vector of point clouds, each representing a cluster from the clustering * algorithm. */ std::vector<PCP> cluster(PCP &input, float clusterTolerance, int minClusterSize, int maxClusterSize); PointCloudProcessor(); void cb_process(sensor_msgs::PointCloud2ConstPtr point_cloud); }; #endif
[ "adam.d.allevato@gmail.com" ]
adam.d.allevato@gmail.com
4eab5999fc6b7d16a2985ccf05b1e0817817e0c0
a8839567e2fc17888a5b834733ccccfe95de464a
/SRM-672-DIV-2/250/SetPartialOrder.cc
c78815323b31a03f7a11d6e5148319c79e5bacbe
[]
no_license
mfrancisc/TopCoder
f8fa9467c308be108c004593c5d019ad50ab191c
c89209682168534f19b34c1b2db5e2a37cbade63
refs/heads/master
2021-01-17T14:57:17.304595
2016-07-26T22:24:58
2016-07-26T22:24:58
45,060,433
0
0
null
null
null
null
UTF-8
C++
false
false
1,176
cc
// {{{ VimCoder 0.3.6 <----------------------------------------------------- // vim:filetype=cpp:foldmethod=marker:foldmarker={{{,}}} #include <algorithm> #include <bitset> #include <cmath> #include <cstdio> #include <cstdlib> #include <ctime> #include <deque> #include <functional> #include <iomanip> #include <iostream> #include <list> #include <map> #include <numeric> #include <queue> #include <set> #include <sstream> #include <stack> #include <utility> #include <vector> using namespace std; // }}} class SetPartialOrder { public: string compareSets(vector <int> a, vector <int> b) { int countA = a.size(); int countB = b.size(); string result = "INCOMPARABLE"; int found = 0; for (int x = 0; x < a.size(); x++) { for (int y = 0; y< b.size(); y++) { if(a[x] == a[y]) { found++; } } } if(found == countA && countA == countB) { result = "EQUAL"; } if(found == countA && countA < countB) { result = "LESS"; } if(found == countA && countA > countB) { result = "GREATER"; } return result; } };
[ "munteanu.francisc@gmail.com" ]
munteanu.francisc@gmail.com
f113721e3d3a8fd103d3ad8d86f32aa36ca1b45c
75d5f0ceade16fbd1fa84f8e163826e5202ed293
/src/menu_instructions.h
23201814b70507ea6e7b2c462c3e38641fc70b6b
[]
no_license
sudo-hh/CppND-Capstone-Snake-Game
faf45bfd37093b15dd83f4f95ea09703093db683
acced085d9f45eb2ce2fd08098f4d3e78f3aebf0
refs/heads/master
2022-12-02T15:01:52.108784
2020-07-26T19:26:54
2020-07-26T19:26:54
280,624,283
0
0
null
2020-07-26T19:26:55
2020-07-18T09:29:40
C++
UTF-8
C++
false
false
585
h
#ifndef INSTRUCTIONS_H #define INSTRUCTIONS_H #include <stdlib.h> #include <string> #include "menu.h" class MenuInstr : public Menu { public: MenuInstr(); void showMenu(); private: std::vector<std::string> _title; std::string _title_1; std::string _title_2; std::string _title_3; std::vector<std::string> _instructions; std::string _instructions_1; std::string _instructions_2; std::string _instructions_3; std::string _instructions_4; std::string _instructions_5; }; #endif
[ "hectora7@gmail.com" ]
hectora7@gmail.com
92fa9f11c6abc51dfeba13548c7d4aea182d018e
1d4c80f3b429b87fac489e0b32f6a64042cba778
/cv03/convolution.h
2039ca2b6d4926e4ae0a9454521c20d1da529ba3
[]
no_license
SacrificeGhuleh/DZO2019
b01410e928601c80882fdd61be360637f1e8882d
010761c22b730f558904e0bb6f007c627bf51dee
refs/heads/master
2020-07-29T17:06:41.393210
2019-12-07T13:30:39
2019-12-07T13:31:06
209,893,331
0
0
null
null
null
null
UTF-8
C++
false
false
1,222
h
// // Created by zvone on 02-Oct-19. // #ifndef DZO2019_CONVOLUTION_H #define DZO2019_CONVOLUTION_H template<class T_MASK> cv::Mat applyConvolution(const cv::Mat &srcMat) { T_MASK mask; return applyConvolution(mask, srcMat); } template<class T_MASK> cv::Mat applyConvolution(const T_MASK &mask, const cv::Mat &srcMat) { //input mat is greyscale image 8bit int image std::cout << "Applying convolution with mask: " << std::endl; mask.print(); cv::Mat dstMat = srcMat.clone(); for (int matCol = mask.offset; matCol < srcMat.cols - mask.offset; matCol++) { for (int matRow = mask.offset; matRow < srcMat.rows - mask.offset; matRow++) { float pixelSum = 0.f; for (int maskCol = -mask.offset; maskCol <= mask.offset; maskCol++) { for (int maskRow = -mask.offset; maskRow <= mask.offset; maskRow++) { float pixf = static_cast<float>(srcMat.at<uint8_t>(matRow + maskRow, matCol + maskCol)); pixf *= mask.at(mask.offset + maskRow, mask.offset + maskCol); pixelSum += pixf; } } pixelSum /= mask.scale; dstMat.at<uint8_t>(matRow, matCol) = pixelSum; } } return dstMat; } #endif //DZO2019_CONVOLUTION_H
[ "zvonek.r@seznam.cz" ]
zvonek.r@seznam.cz
a8f7e25fc3caeb72cf654824303c7ae52e438b10
8baff36c5c2caa8cb433c377fafcd89b77e56cc7
/Excercises/Alcion - Language C++ (12 years of mine)/F31.cpp
aa6e3684e6e1aad3bcfb1adbd304e31c7db1a640
[]
no_license
cobol5/old-cpp-pascal-experiments
ca2526cc511d977a634c09731e6a8e9ec20a45e0
a2ea6c262f7bf99782f9c3b6a9385da8e9648f0a
refs/heads/master
2022-10-13T18:47:10.345936
2020-06-11T08:39:00
2020-06-11T08:39:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
836
cpp
#include <iostream.h> #include <typeinfo> class Base{}; class Derived: public Base{}; int main() { char C; float X; Derived DerOb; Base* pBase = &DerOb; if(typeid(C)==typeid(X)) cout <<"C and X has same type.\n"; else cout <<"C and X has don't same type.\n"; cout <<typeid(int).name() <<" Before " <<typeid(double).name() <<": " <<(typeid(int).before(typeid(double))? true: false) <<endl; cout <<typeid(double).name() <<" Before " <<typeid(int).name() <<": " <<(typeid(double).before(typeid(int))? true: false) <<endl; if(typeid(pBase)==typeid(DerOb)) cout <<"Base and Derived has same type \n"; else cout <<"Base and Derived has don't same type \n"; cout <<typeid(pBase).name() <<" Before " <<typeid(DerOb).name() <<": " <<(typeid(pBase).before(typeid(DerOb))? true: false) <<endl; return 0; };
[ "strangedik@gmail.com" ]
strangedik@gmail.com
498e88e2d1d948f968630838351fc87643f8dbf3
0d0e78c6262417fb1dff53901c6087b29fe260a0
/cbs/include/tencentcloud/cbs/v20170312/model/ResizeDiskRequest.h
125709bc174a494798b278531232dc2d9b345338
[ "Apache-2.0" ]
permissive
li5ch/tencentcloud-sdk-cpp
ae35ffb0c36773fd28e1b1a58d11755682ade2ee
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
refs/heads/master
2022-12-04T15:33:08.729850
2020-07-20T00:52:24
2020-07-20T00:52:24
281,135,686
1
0
Apache-2.0
2020-07-20T14:14:47
2020-07-20T14:14:46
null
UTF-8
C++
false
false
4,209
h
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef TENCENTCLOUD_CBS_V20170312_MODEL_RESIZEDISKREQUEST_H_ #define TENCENTCLOUD_CBS_V20170312_MODEL_RESIZEDISKREQUEST_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/AbstractModel.h> namespace TencentCloud { namespace Cbs { namespace V20170312 { namespace Model { /** * ResizeDisk่ฏทๆฑ‚ๅ‚ๆ•ฐ็ป“ๆž„ไฝ“ */ class ResizeDiskRequest : public AbstractModel { public: ResizeDiskRequest(); ~ResizeDiskRequest() = default; std::string ToJsonString() const; /** * ่Žทๅ–ไบ‘็กฌ็›˜ID๏ผŒ ้€š่ฟ‡[DescribeDisks](/document/product/362/16315)ๆŽฅๅฃๆŸฅ่ฏขใ€‚ * @return DiskId ไบ‘็กฌ็›˜ID๏ผŒ ้€š่ฟ‡[DescribeDisks](/document/product/362/16315)ๆŽฅๅฃๆŸฅ่ฏขใ€‚ */ std::string GetDiskId() const; /** * ่ฎพ็ฝฎไบ‘็กฌ็›˜ID๏ผŒ ้€š่ฟ‡[DescribeDisks](/document/product/362/16315)ๆŽฅๅฃๆŸฅ่ฏขใ€‚ * @param DiskId ไบ‘็กฌ็›˜ID๏ผŒ ้€š่ฟ‡[DescribeDisks](/document/product/362/16315)ๆŽฅๅฃๆŸฅ่ฏขใ€‚ */ void SetDiskId(const std::string& _diskId); /** * ๅˆคๆ–ญๅ‚ๆ•ฐ DiskId ๆ˜ฏๅฆๅทฒ่ต‹ๅ€ผ * @return DiskId ๆ˜ฏๅฆๅทฒ่ต‹ๅ€ผ */ bool DiskIdHasBeenSet() const; /** * ่Žทๅ–ไบ‘็กฌ็›˜ๆ‰ฉๅฎนๅŽ็š„ๅคงๅฐ๏ผŒๅ•ไฝไธบGB๏ผŒๅฟ…้กปๅคงไบŽๅฝ“ๅ‰ไบ‘็กฌ็›˜ๅคงๅฐใ€‚ไบ‘็›˜ๅคงๅฐๅ–ๅ€ผ่Œƒๅ›ดๅ‚่งไบ‘็กฌ็›˜[ไบงๅ“ๅˆ†็ฑป](/document/product/362/2353)็š„่ฏดๆ˜Žใ€‚ * @return DiskSize ไบ‘็กฌ็›˜ๆ‰ฉๅฎนๅŽ็š„ๅคงๅฐ๏ผŒๅ•ไฝไธบGB๏ผŒๅฟ…้กปๅคงไบŽๅฝ“ๅ‰ไบ‘็กฌ็›˜ๅคงๅฐใ€‚ไบ‘็›˜ๅคงๅฐๅ–ๅ€ผ่Œƒๅ›ดๅ‚่งไบ‘็กฌ็›˜[ไบงๅ“ๅˆ†็ฑป](/document/product/362/2353)็š„่ฏดๆ˜Žใ€‚ */ uint64_t GetDiskSize() const; /** * ่ฎพ็ฝฎไบ‘็กฌ็›˜ๆ‰ฉๅฎนๅŽ็š„ๅคงๅฐ๏ผŒๅ•ไฝไธบGB๏ผŒๅฟ…้กปๅคงไบŽๅฝ“ๅ‰ไบ‘็กฌ็›˜ๅคงๅฐใ€‚ไบ‘็›˜ๅคงๅฐๅ–ๅ€ผ่Œƒๅ›ดๅ‚่งไบ‘็กฌ็›˜[ไบงๅ“ๅˆ†็ฑป](/document/product/362/2353)็š„่ฏดๆ˜Žใ€‚ * @param DiskSize ไบ‘็กฌ็›˜ๆ‰ฉๅฎนๅŽ็š„ๅคงๅฐ๏ผŒๅ•ไฝไธบGB๏ผŒๅฟ…้กปๅคงไบŽๅฝ“ๅ‰ไบ‘็กฌ็›˜ๅคงๅฐใ€‚ไบ‘็›˜ๅคงๅฐๅ–ๅ€ผ่Œƒๅ›ดๅ‚่งไบ‘็กฌ็›˜[ไบงๅ“ๅˆ†็ฑป](/document/product/362/2353)็š„่ฏดๆ˜Žใ€‚ */ void SetDiskSize(const uint64_t& _diskSize); /** * ๅˆคๆ–ญๅ‚ๆ•ฐ DiskSize ๆ˜ฏๅฆๅทฒ่ต‹ๅ€ผ * @return DiskSize ๆ˜ฏๅฆๅทฒ่ต‹ๅ€ผ */ bool DiskSizeHasBeenSet() const; private: /** * ไบ‘็กฌ็›˜ID๏ผŒ ้€š่ฟ‡[DescribeDisks](/document/product/362/16315)ๆŽฅๅฃๆŸฅ่ฏขใ€‚ */ std::string m_diskId; bool m_diskIdHasBeenSet; /** * ไบ‘็กฌ็›˜ๆ‰ฉๅฎนๅŽ็š„ๅคงๅฐ๏ผŒๅ•ไฝไธบGB๏ผŒๅฟ…้กปๅคงไบŽๅฝ“ๅ‰ไบ‘็กฌ็›˜ๅคงๅฐใ€‚ไบ‘็›˜ๅคงๅฐๅ–ๅ€ผ่Œƒๅ›ดๅ‚่งไบ‘็กฌ็›˜[ไบงๅ“ๅˆ†็ฑป](/document/product/362/2353)็š„่ฏดๆ˜Žใ€‚ */ uint64_t m_diskSize; bool m_diskSizeHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_CBS_V20170312_MODEL_RESIZEDISKREQUEST_H_
[ "jimmyzhuang@tencent.com" ]
jimmyzhuang@tencent.com
2742964d177e0794c6fbde9fd7d45f60f85aef8d
9a74de3dfe4288323ddb0d5b57a74aedc3ca63da
/ch06/6-33.cpp
eb27c4bb05ff19c4e30d0c7549bac829bdf49d23
[]
no_license
ss-haze/cpp_primer
afd56dc810278f728c7d462ada009d1f179c36fa
917b99845e80a36c4d82345864ceef3f8628fcac
refs/heads/main
2023-06-05T14:00:38.343255
2021-06-28T15:22:27
2021-06-28T15:22:27
321,345,987
2
0
null
null
null
null
UTF-8
C++
false
false
404
cpp
#include <iostream> #include <vector> #include <string> using std::cout; using std::string; using std::vector; using Iterator = const vector<string>::const_iterator; auto print(Iterator &b, Iterator &e) -> void { if (b == e) return; cout << *b << " "; print(b + 1, e); } int main() { const vector<string> v{"hello", "bye", "yes", "no", "maybe"}; print(v.begin(), v.end()); return 0; }
[ "ss-haze@users.no-reply.github.com" ]
ss-haze@users.no-reply.github.com
897382a6ea858dc3fe65aeda859713f2136f9169
4f49d7c54d4b8ac252bc5a130a75c2ae914411e1
/libcxx/test/std/thread/thread.mutex/thread.lock/thread.lock.guard/variadic_types.pass.cpp
21de6bfe2ccbd0e6454a170a8c7a445acedd1e38
[ "NCSA", "MIT" ]
permissive
stbergmann/llvm-project
835981f319ec02623c3ee73f647c1c354bfe0cb8
f914d64f6ba3506d04ec8e74f859aea17a695497
refs/heads/master
2020-06-11T21:28:40.695770
2016-12-05T14:10:10
2016-12-05T14:17:52
75,629,802
0
0
null
2016-12-05T13:57:47
2016-12-05T13:57:46
null
UTF-8
C++
false
false
2,079
cpp
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // UNSUPPORTED: libcpp-has-no-threads // UNSUPPORTED: c++98, c++03 // FIXME: When modules are enabled we can't affect the contents of <mutex> // by defining a macro // XFAIL: -fmodules // <mutex> // template <class Mutex> // class lock_guard // { // public: // typedef Mutex mutex_type; // ... // }; #define _LIBCPP_ABI_VARIADIC_LOCK_GUARD #include <mutex> #include <type_traits> struct NAT {}; template <class LG> auto test_typedef(int) -> typename LG::mutex_type; template <class LG> auto test_typedef(...) -> NAT; template <class LG> constexpr bool has_mutex_type() { return !std::is_same<decltype(test_typedef<LG>(0)), NAT>::value; } int main() { { using T = std::lock_guard<>; static_assert(!has_mutex_type<T>(), ""); } { using M1 = std::mutex; using T = std::lock_guard<M1>; static_assert(std::is_same<T::mutex_type, M1>::value, ""); } { using M1 = std::recursive_mutex; using T = std::lock_guard<M1>; static_assert(std::is_same<T::mutex_type, M1>::value, ""); } { using M1 = std::mutex; using M2 = std::recursive_mutex; using T = std::lock_guard<M1, M2>; static_assert(!has_mutex_type<T>(), ""); } { using M1 = std::mutex; using M2 = std::recursive_mutex; using T = std::lock_guard<M1, M1, M2>; static_assert(!has_mutex_type<T>(), ""); } { using M1 = std::mutex; using T = std::lock_guard<M1, M1>; static_assert(!has_mutex_type<T>(), ""); } { using M1 = std::recursive_mutex; using T = std::lock_guard<M1, M1, M1>; static_assert(!has_mutex_type<T>(), ""); } }
[ "eric@efcs.ca" ]
eric@efcs.ca
197093e70a4d20ee9edaaf7721eb89813ceddd85
911729e019762ed93b14f49d19c1b7d817c29af6
/include/BaseClass/MHexEdit.h
48c4005ae2668066327a24799f2a4d77d0d6050c
[]
no_license
JackBro/DragonVer1.0
59590809df749540f70b904f83c4093890031fbb
31b3a97f2aa4a66d2ee518b8e6ae4245755009b1
refs/heads/master
2020-06-19T21:02:17.248852
2014-05-08T02:19:33
2014-05-08T02:19:33
74,833,772
0
1
null
2016-11-26T15:29:10
2016-11-26T15:29:10
null
UTF-8
C++
false
false
1,323
h
#if !defined(AFX_MHEXEDIT_H__4A095310_920E_4ACB_8392_7A76A9AFE11B__INCLUDED_) #define AFX_MHEXEDIT_H__4A095310_920E_4ACB_8392_7A76A9AFE11B__INCLUDED_ #if _MSC_VER > 1000 #ifndef __BASECLASS_MHEXEDIT_H__ #define __BASECLASS_MHEXEDIT_H__ #endif // _MSC_VER > 1000 // MHexEdit.h : header file #ifndef BASECLASS_DLL #define BASECLASS_DLL __declspec(dllimport) #endif #include "MBaseEdit.h" ///////////////////////////////////////////////////////////////////////////// // CMHexEdit window class BASECLASS_DLL CMHexEdit : public CMBaseEdit { // Construction public: CMHexEdit(); // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CMHexEdit) //}}AFX_VIRTUAL // Implementation public: virtual ~CMHexEdit(); // Generated message map functions protected: //{{AFX_MSG(CMHexEdit) afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_MHEXEDIT_H__4A095310_920E_4ACB_8392_7A76A9AFE11B__INCLUDED_) #endif
[ "ranger.su@gmail.com" ]
ranger.su@gmail.com
a48d79fdd290fd7bb954649bc5b313d31e3a011e
5faf84491b79aae3aa6d6f7c72cdcb6a20a3b62b
/kernel/fpu_emu/fpu_emu_demo.cc
56ef772a459d24cc50b1254e31727978af027dee
[]
no_license
SAbruzzo/ItaliOs
671a6810885edf41ac58fc4712f4690912fe3803
1d91fcb393a01af3b931ca1fa7c82f88d3c84dca
refs/heads/master
2022-11-30T10:03:17.594652
2020-08-01T18:07:22
2020-08-01T18:07:22
284,313,086
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
521
cc
#include <fpu_emu.h> #include <fpu_emu_demo.h> volatile double pippo; void fpu_demo(){ fpu_emu num; if(check_fpu()) kout << "La fpu รจ presente\n"; else kout << "La fpu non รจ presente\n"; pippo = 0.5; kout<< "carico i valori\n"; num.data.fld(1.570796327); //num.data.fld(0.0); kout << "ho caricato i valori\n"; num.trig.fsin(); //num.data.fld(64.550); //num.data.fld(4.410); //num.math.faddp(); kout << "\nIl risultato รจ: "; kout << num.regi.R[((num.regi.get_sr() & 0x3800) >> 11)].numero<<'\n'; }
[ "silvestre.abruzzo@fyber.com" ]
silvestre.abruzzo@fyber.com
29b71094228d595cf2c3633d3febaa4548c4639d
485faf9d4ec7def9a505149c6a491d6133e68750
/include/viz/RTDraggerNode.H
48258bda160d4086000e7cbdfdd065f9c172b512
[ "LicenseRef-scancode-warranty-disclaimer", "ECL-2.0" ]
permissive
ohlincha/ECCE
af02101d161bae7e9b05dc7fe6b10ca07f479c6b
7461559888d829338f29ce5fcdaf9e1816042bfe
refs/heads/master
2020-06-25T20:59:27.882036
2017-06-16T10:45:21
2017-06-16T10:45:21
94,240,259
1
1
null
null
null
null
UTF-8
C++
false
false
4,371
h
/*------------------------------------------------------------ * This is an example from the Inventor Toolmaker, * chapter 8, example 14. * * Header file for "RTDraggerNode" * * This is the source file for the RTDraggerNode. * It is a compound dragger which allows independent rotation * in the x,y,and z directions as well as translation along a * line. It is an example of how to write a compound dragger. * * It is composed of a TranslateRadialDragger and * 3 SoRotateCylindricalDraggers bound into one dragger. * * Clicking on the TranslateRadialDragger piece results in a * translational motion along the line formed by the center of * the dragger and the point on the dragger that was hit. * * Clicking a cylinder rotator results in a rotation about * either the x,y,or z axis. * * Geometry resources and part names for this dragger: * * Resource Names: Part Names: *rotTransTranslatorTranslator translator.translator *rotTransTranslatorTranslatorActive translator.translatorActive *rotTransTranslatorFeedback translator.feedback *rotTransTranslatorFeedbackActive translator.feedbackActive * *rotTransRotatorRotator XRotator.rotator *rotTransRotatorRotatorActive XRotator.rotatorActive *rotTransRotatorFeedback XRotator.feedback *rotTransRotatorFeedbackActive XRotator.feedbackActive * (and similarly for parts of the YRotator and ZRotator) * *-----------------------------------------------------------*/ #ifndef _RTDRAGGERNODE_ #define _RTDRAGGERNODE_ #include "inv/sensors/SoFieldSensor.H" #include "inv/draggers/SoDragger.H" #include "inv/fields/SoSFVec3f.H" #include "inv/fields/SoSFRotation.H" #include "inv/nodes/SoTranslation.H" class TranslateRadialDragger; class SoRotateCylindricalDragger; class RTDraggerNode : public SoDragger { SO_KIT_HEADER(RTDraggerNode); // Makes the dragger surround other objects SO_KIT_CATALOG_ENTRY_HEADER(surroundScale); // Keeps the dragger evenly sized in all 3 dimensions SO_KIT_CATALOG_ENTRY_HEADER(antiSquish); // The translating dragger... SO_KIT_CATALOG_ENTRY_HEADER(translator); // The X and Z rotators need to be turned so as to orient // correctly. So create a separator part and put an // SoRotation node and the dragger underneath. SO_KIT_CATALOG_ENTRY_HEADER(XRotatorSep); SO_KIT_CATALOG_ENTRY_HEADER(XRotatorRot); SO_KIT_CATALOG_ENTRY_HEADER(XRotator); SO_KIT_CATALOG_ENTRY_HEADER(YRotator); SO_KIT_CATALOG_ENTRY_HEADER(ZRotatorSep); SO_KIT_CATALOG_ENTRY_HEADER(ZRotatorRot); SO_KIT_CATALOG_ENTRY_HEADER(ZRotator); public: // Constructor RTDraggerNode(); SbVec3f old_trans; SbVec3f center; SbRotation old_rot; float save_scale; SoTranslation * tran; SoScale *sca; SbBool Alert; SoSeparator *parent; // These fields reflect state of the dragger at all times. SoSFRotation rotation; SoSFVec3f translation; // This should be called once after SoInteraction::init(). static void initClass(); void reset(); protected: // These sensors insures that the motionMatrix is updated // when the fields are changed from outside. SoFieldSensor *rotFieldSensor; SoFieldSensor *translFieldSensor; static void fieldSensorCB(void *, SoSensor *); // virtual void GLRender(SoGLRenderAction *action); // This function is invoked by the child draggers when they // change their value. static void valueChangedCB(void *, SoDragger *); // Called at the beginning and end of each dragging motion. // Tells the "surroundScale" part to recalculate. static void invalidateSurroundScaleCB(void *, SoDragger *); // This will detach/attach the fieldSensor. // It is called at the end of the constructor (to attach). // and at the start/end of SoBaseKit::readInstance() // and on the new copy at the start/end of SoBaseKit::copy() // Returns the state of the node when this was called. virtual SbBool setUpConnections( SbBool onOff, SbBool doItAlways = FALSE); // This allows us to specify that certain parts do not // write out. We'll use this on the antiSquish and // surroundScale parts. virtual void setDefaultOnNonWritingFields(); private: static const char geomBuffer[]; // Destructor. ~RTDraggerNode(); }; #endif /* _RTDRAGGERNODE_ */
[ "andre.ohlin@umu.se" ]
andre.ohlin@umu.se
fb3533dee5b751d0d69157032e9b27a094cb7356
27935aa7b005dace440841aafb90f375b0e29ccc
/test/conv_dbn_mp.cpp
5db5529b5f943619b7fe98475d849ba3674869f7
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
darcy0511/dll
fe44055d9424f30122391edf31f209d9d3cb593a
deb08c3dce0db6a0dc9ea3fc0dd0b53d62a07c49
refs/heads/master
2021-01-17T04:54:17.408985
2014-12-11T09:58:56
2014-12-11T09:58:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,905
cpp
//======================================================================= // Copyright (c) 2014 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <deque> #include "catch.hpp" #define DLL_SVM_SUPPORT #include "dll/conv_rbm_mp.hpp" #include "dll/conv_dbn.hpp" #include "mnist/mnist_reader.hpp" #include "mnist/mnist_utils.hpp" TEST_CASE( "conv_dbn_mp/mnist_1", "conv_dbn::simple" ) { typedef dll::conv_dbn_desc< dll::dbn_layers< dll::conv_rbm_mp_desc<28, 1, 12, 40, 2, dll::momentum, dll::batch_size<25>>::rbm_t, dll::conv_rbm_mp_desc<6, 40, 4, 20, 2, dll::momentum, dll::batch_size<25>>::rbm_t >>::dbn_t dbn_t; auto dataset = mnist::read_dataset<std::vector, std::vector, double>(100); REQUIRE(!dataset.training_images.empty()); mnist::binarize_dataset(dataset); auto dbn = std::make_unique<dbn_t>(); dbn->pretrain(dataset.training_images, 5); } TEST_CASE( "conv_dbn_mp/mnist_2", "conv_dbn::svm_simple" ) { typedef dll::conv_dbn_desc< dll::dbn_layers< dll::conv_rbm_mp_desc<28, 1, 18, 40, 2, dll::momentum, dll::batch_size<25>>::rbm_t, dll::conv_rbm_mp_desc<9, 40, 6, 40, 2, dll::momentum, dll::batch_size<25>>::rbm_t >>::dbn_t dbn_t; auto dataset = mnist::read_dataset<std::vector, std::vector, double>(200); REQUIRE(!dataset.training_images.empty()); mnist::binarize_dataset(dataset); auto dbn = std::make_unique<dbn_t>(); dbn->pretrain(dataset.training_images, 20); auto result = dbn->svm_train(dataset.training_images, dataset.training_labels); REQUIRE(result); auto test_error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::svm_predictor()); std::cout << "test_error:" << test_error << std::endl; REQUIRE(test_error < 0.2); } TEST_CASE( "conv_dbn_mp/mnist_3", "conv_dbn::svm_concatenate" ) { typedef dll::conv_dbn_desc< dll::dbn_layers< dll::conv_rbm_mp_desc<28, 1, 18, 40, 2, dll::momentum, dll::batch_size<25>>::rbm_t, dll::conv_rbm_mp_desc<9, 40, 6, 40, 2, dll::momentum, dll::batch_size<25>>::rbm_t >, dll::concatenate>::dbn_t dbn_t; auto dataset = mnist::read_dataset<std::vector, std::vector, double>(200); REQUIRE(!dataset.training_images.empty()); mnist::binarize_dataset(dataset); auto dbn = std::make_unique<dbn_t>(); dbn->pretrain(dataset.training_images, 20); auto result = dbn->svm_train(dataset.training_images, dataset.training_labels); REQUIRE(result); auto test_error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::svm_predictor()); std::cout << "test_error:" << test_error << std::endl; REQUIRE(test_error < 0.2); }
[ "baptiste.wicht@gmail.com" ]
baptiste.wicht@gmail.com
99add050cf438c382fc2e3256aefa315c3bf1432
d0687c8520672d54a8ba276ce7d0e69e88e3e471
/Card_Game-Project/Card_Game-71740/SPELL.cpp
68af766fe8dda780e0b18058df1982de43365596
[]
no_license
dani107/OOP
5878f898287adb10524981c270f84db323a1eaee
8e49e46b21b4dffd7ecead940b12c6935942f363
refs/heads/master
2020-03-20T02:12:50.160600
2018-06-12T17:10:44
2018-06-12T17:10:44
137,087,818
0
0
null
null
null
null
UTF-8
C++
false
false
847
cpp
#include "Spell.h" Spell::Spell() { boost=0; } Spell::Spell(char* name,TYPECARD type,ELEMENT element,int boost,int AtkOrDef):Card(name,type) { this->element=element; this->AtkOrDef=AtkOrDef; this->boost=boost; } ELEMENT Spell::getElement()const { return this->element; } int Spell::getBoost()const { return this->boost; } int Spell::getAtkOrDef()const { return this->AtkOrDef; } TYPECARD Spell::getType()const { return SPELL; } void Spell::setElement(ELEMENT element) { this->element=element; } void Spell::setBoost(int boost) { this->boost=boost; } void Spell::setAtkOrDef(int AtkOrDef) { this->AtkOrDef=AtkOrDef; } void Spell::print() { cout<<"Spell name:"; Card::print(); cout<<endl; cout<<"Boost with"<<this->boost<<endl; cout<<"Element who will boost:"<<this->element<<endl; }
[ "dani107@abv.bg" ]
dani107@abv.bg
2150f318696ba27d4bdf6b10d16b994c71e60b6a
b152993f856e9598e67d046e6243350dcd622abe
/chrome/browser/ash/login/oobe_quick_start/connectivity/target_device_connection_broker.h
cc45fdd6f4694b7b0c40e37c18d99e3626ae390c
[ "BSD-3-Clause" ]
permissive
monad-one/chromium
10e4a585fbd2b66b55d5afcba72c50a872708238
691b5c9cfa2a4fc38643509932e62438dc3a0d54
refs/heads/main
2023-05-14T07:36:48.032727
2023-05-10T13:47:48
2023-05-10T13:47:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,490
h
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_ASH_LOGIN_OOBE_QUICK_START_CONNECTIVITY_TARGET_DEVICE_CONNECTION_BROKER_H_ #define CHROME_BROWSER_ASH_LOGIN_OOBE_QUICK_START_CONNECTIVITY_TARGET_DEVICE_CONNECTION_BROKER_H_ #include <vector> #include "base/functional/callback.h" #include "base/memory/raw_ptr.h" #include "base/values.h" #include "chrome/browser/ash/login/oobe_quick_start/connectivity/random_session_id.h" #include "chromeos/ash/services/nearby/public/mojom/quick_start_decoder_types.mojom.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace ash::quick_start { struct FidoAssertionInfo; // TargetDeviceConnectionBroker is the entrypoint for consuming the Quick Start // connectivity component. Calling code is expected to get an instance of this // class using the TargetDeviceConnectionBrokerFactory and interact with the // component using the public interface of this class. // // All references to "target device" imply this device (Chromebook). All // references to "source device" imply the remote Android phone, which is the // source for Gaia and WiFi credentials. class TargetDeviceConnectionBroker { public: using ResultCallback = base::OnceCallback<void(bool success)>; using SharedSecret = std::array<uint8_t, 32>; enum class FeatureSupportStatus { kUndetermined = 0, kNotSupported, kSupported }; enum class ConnectionClosedReason { kComplete, kUserAborted, kAuthenticationFailed, kConnectionLost, kRequestTimedOut, kTargetDeviceUpdate, kUnknownError, }; class AuthenticatedConnection { public: using RequestWifiCredentialsCallback = base::OnceCallback<void(absl::optional<mojom::WifiCredentials>)>; // The ack_successful bool indicates whether the ack was successfully // received by the source device. If true, then the target device will // prepare to resume the Quick Start connection after it updates. using NotifySourceOfUpdateCallback = base::OnceCallback<void(/*ack_successful=*/bool)>; using RequestAccountTransferAssertionCallback = base::OnceCallback<void(absl::optional<FidoAssertionInfo>)>; // Close the connection. virtual void Close( TargetDeviceConnectionBroker::ConnectionClosedReason reason) = 0; // Request wifi credentials from target Android device. The session_id is // used to identify this QuickStart session and is distinct from the // RandomSessionId. virtual void RequestWifiCredentials( int32_t session_id, RequestWifiCredentialsCallback callback) = 0; // Notify Android device that the Chromebook will download an update and // reboot. The session_id should be the same as the one sent in // RequestWifiCredentials(). virtual void NotifySourceOfUpdate( int32_t session_id, NotifySourceOfUpdateCallback callback) = 0; // Begin the account transfer process and retrieve // an Assertion from the source device. The user will be asked to confirm // their lock screen PIN/pattern/etc. on the source device. // This object's client must provide a "challenge" to be sent to the remote // source device. virtual void RequestAccountTransferAssertion( const std::string& challenge_b64url, RequestAccountTransferAssertionCallback callback) = 0; protected: AuthenticatedConnection() = default; virtual ~AuthenticatedConnection() = default; }; // Clients of TargetDeviceConnectionBroker should implement this interface, // and provide a self-reference when calling TargetDeviceConnectionBroker:: // StartAdvertising(). // // This interface is a simplification of // nearby::connections::mojom::ConnectionLifecycleListener, for ease // of client use. class ConnectionLifecycleListener { public: ConnectionLifecycleListener() = default; virtual ~ConnectionLifecycleListener() = default; // A connection has been initiated between this target device and the remote // source device, but needs to be authenticated before messages can be // exchanged. The source device has requested that the pin be displayed so // that the user can check that the codes match, thereby authenticating the // connection. virtual void OnPinVerificationRequested(const std::string& pin) = 0; // A connection has been initiated between this target device and the remote // source device, but needs to be authenticated before messages can be // exchanged. The source device has requested that the QR code be displayed // so that the user can scan the code. After scanning, the source device // will accept the connection, and a cryptographic handshake using a secret // contained in the QR code will be used to authenticate the connection. virtual void OnQRCodeVerificationRequested( const std::vector<uint8_t>& qr_code_data) = 0; // Called after both sides have accepted the connection. // // This connection may be a "resumed" connection that was previously // "paused" before this target device performed a Critical Update and // rebooted. // // The AuthenticatedConnection pointer may be cached, but will become // invalid after OnConnectionClosed() is called. // // Use source_device_id to understand which connection // OnConnectionClosed() refers to. virtual void OnConnectionAuthenticated( base::WeakPtr<AuthenticatedConnection> authenticated_connection) = 0; // Called if the source device rejected the connection. virtual void OnConnectionRejected() = 0; // Called when the source device is disconnected or has become unreachable. virtual void OnConnectionClosed(ConnectionClosedReason reason) = 0; }; TargetDeviceConnectionBroker(); virtual ~TargetDeviceConnectionBroker(); // Checks to see whether the feature can be supported on the device's // hardware. The feature is supported if Bluetooth is supported and an adapter // is present. virtual FeatureSupportStatus GetFeatureSupportStatus() const = 0; using FeatureSupportStatusCallback = base::OnceCallback<void(FeatureSupportStatus status)>; void GetFeatureSupportStatusAsync(FeatureSupportStatusCallback callback); // Will kick off Fast Pair and Nearby Connections advertising. // Clients can use the result of |on_start_advertising_callback| to // immediately understand if advertising succeeded, and can then wait for the // source device to connect and request authentication via // |ConnectionLifecycleListener::OnPinVerificationRequested()| or // |ConnectionLifecycleListener::OnQRCodeVerificationRequested()|. // // If the caller paused a connection previously, the connection to the // source device will resume via OnConnectionAuthenticated(). // Clients should check GetFeatureSupportStatus() before calling // StartAdvertising(). // // If |use_pin_authentication| is true, then the target device will // advertise its preference to use pin authentication instead of QR code // authentication. This should be false unless the user would benefit from // using pin for, e.g. accessibility reasons. virtual void StartAdvertising( ConnectionLifecycleListener* listener, bool use_pin_authentication, ResultCallback on_start_advertising_callback) = 0; // Clients are responsible for calling this once they have accepted their // desired connection, or in error/edge cases, e.g., the user exits the UI. virtual void StopAdvertising( base::OnceClosure on_stop_advertising_callback) = 0; // Returns Dict that can be persisted to a local state Dict pref if the target // device is going to update. This Dict contains the RandomSessionId and // secondary SharedSecret represented as base64-encoded strings. These values // are needed to resume the Quick Start connection after the target device // reboots. virtual base::Value::Dict GetPrepareForUpdateInfo() = 0; protected: void MaybeNotifyFeatureStatus(); void OnConnectionAuthenticated( base::WeakPtr<AuthenticatedConnection> authenticated_connection); void OnConnectionClosed(ConnectionClosedReason reason); // Returns a deep link URL as a vector of bytes that will form the QR code // used to authenticate the connection. std::vector<uint8_t> GetQrCodeData(const RandomSessionId& random_session_id, const SharedSecret shared_secret) const; // Derive a 4-digit decimal pin code from the authentication token. This is // meant to match the Android implementation found here: // http://google3/java/com/google/android/gmscore/integ/modules/smartdevice/src/com/google/android/gms/smartdevice/d2d/nearby/advertisement/VerificationUtils.java;l=37;rcl=511361463 std::string DerivePin(const std::string& authentication_token) const; // Determines whether the advertisement info sent to the source device will // request pin verification or QR code verification. bool use_pin_authentication_ = false; raw_ptr<ConnectionLifecycleListener, ExperimentalAsh> connection_lifecycle_listener_ = nullptr; private: std::vector<FeatureSupportStatusCallback> feature_status_callbacks_; }; } // namespace ash::quick_start #endif // CHROME_BROWSER_ASH_LOGIN_OOBE_QUICK_START_CONNECTIVITY_TARGET_DEVICE_CONNECTION_BROKER_H_
[ "chromium-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
d115c59bb7afeb76188e3af2a25b960ca3f41f3b
88890e950f38afe29981ee4f1e534fe2d905e1f1
/BoltEngine/src/BoltEngine/Layer.cpp
013590053454865af90b81bc3ee703ec7b369ab1
[ "MIT" ]
permissive
GameGenesis/BoltEngine
755c57fb1e95c7c88f213cccc4261f33236b5698
558cd94687fba4d19a345949cc7e03b7f27a8975
refs/heads/master
2023-01-06T00:05:41.850222
2020-10-31T00:44:27
2020-10-31T00:44:27
275,352,157
0
0
null
2020-10-31T00:44:28
2020-06-27T10:49:58
C++
UTF-8
C++
false
false
140
cpp
#include "bepch.h" #include "Layer.h" namespace BoltEngine { Layer::Layer(const std::string& debugName) : m_DebugName(debugName) { } }
[ "kaissiray5@gmail.com" ]
kaissiray5@gmail.com
0f19a014fe021aceaa8ead5347ec2b67d59c916b
2bc417eabc94baf5612ef547e429e15c985afa2a
/SpinEngine/Source/Graphics/Particle.cpp
033a4bb7770a14ac9d78d4e107b2f6158fd28d5d
[]
no_license
TeamSpinningChairs/SpinEngine
30c73bb8e3d98d4162593731dd9101daa0f86e9c
0d766fd7715530a37259cc60942931bdf1d20220
refs/heads/master
2020-05-18T10:43:02.106178
2015-02-13T07:52:11
2015-02-13T07:52:11
30,432,413
0
0
null
null
null
null
UTF-8
C++
false
false
9,812
cpp
/****************************************************************************/ /*! \author Esteban Maldonado \par email: esteban.maldonado@digipen.edu \par Course: GAM 200 \brief The basic particle object for the particle emitter. Copyright: All content @ 2014 DigiPen (USA) Corporation, all rights reserved. */ /****************************************************************************/ #include"Precompiled.h" #include "Particle.h" //const DWORD CUSTOMVERTEX::FVF = CUSTOMFVF; Particle::Particle(Vector3D initial_pos, float lifespan) : current_life(0), lifespan(lifespan), position(D3DXVECTOR3(initial_pos.x, initial_pos.y, initial_pos.z)), initial_position(D3DXVECTOR3(initial_pos.x, initial_pos.y, initial_pos.z)), active(false), spin(0.0f), angle(0.0f) { } Particle::~Particle() { } void Particle::render_particle(IDirect3DDevice9* device, IDirect3DVertexBuffer9** t_buffer, IDirect3DTexture9* texture, D3DXCOLOR color, D3DXCOLOR end_color) { VOID* pVerts; //LOCK THE MEMORY TO MAKE SURE DATA IS PASSED THROUGH (*t_buffer)->Lock(0, sizeof(d3dVertex::CUSTOMVERTEX) * 4/*NUM_VERTS*/, (void**)&pVerts, 0); d3dVertex::CUSTOMVERTEX* temp = reinterpret_cast<d3dVertex::CUSTOMVERTEX*>(pVerts); //set_particle(device); if (color != end_color) { D3DXCOLOR c; D3DXColorLerp(&c, &color, &end_color, (current_life / lifespan)); temp[0].color = temp[1].color = temp[2].color = temp[3].color = c; } else temp[0].color = temp[1].color = temp[2].color = temp[3].color = color; (*t_buffer)->Unlock(); device->SetStreamSource(0, (*t_buffer), 0, sizeof(CUSTOMVERTEX)); if (texture) { device->SetTexture(0, texture); } else { device->SetTexture(0, NULL); } device->DrawPrimitive(/*D3DPT_LINESTRIP*/ D3DPT_TRIANGLESTRIP, 0, 2); //device->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 24, 0, 12); } void Particle::set_particle(IDirect3DDevice9* device, float scal, float end_scal /*float camx, float camy, float camz*/) { //JUST KEEP SCROLLING... //################################ /*int h = 90; int *hp = &h; int **hpp = (&hp); int ***hppp = (&hpp); int hhh = (*(*(*hppp)));*/ //################################ // Before setting the world transform, do the intense mathematics! // a. Calculate the Differences //static float difx, dify, difz; //difx = camx - position.x; //dify = camy - position.y; //difz = camz - position.z; //// b. Calculate the Distances //static float FlatDist, TotalDist; //FlatDist = sqrt(difx * difx + difz * difz); //TotalDist = sqrt(FlatDist * FlatDist + dify * dify); // c. Y Rotation D3DXMatrixIdentity(&matRotateY); //matRotateY._11 = matRotateY._33 = difz / FlatDist; // cosY //matRotateY._31 = difx / FlatDist; // sinY //matRotateY._13 = -matRotateY._31; // -sinY // d. X Rotation D3DXMatrixIdentity(&matRotateX); //matRotateX._22 = matRotateX._33 = FlatDist / TotalDist; // cosX //matRotateX._32 = dify / TotalDist; // sinX //matRotateX._23 = -matRotateX._32; // -sinX D3DXMatrixRotationZ(&matRotateZ, angle); // e. Tranlation static D3DXMATRIX matTranslate; D3DXMatrixTranslation(&matTranslate, position.x, position.y, position.z); // f. Scaling static D3DXMATRIX matScale; D3DXMatrixIdentity(&matScale); if (end_scal != scal)//abs(end_radius - radius) > 0.001) { matScale._11 = matScale._22 = matScale._33 = scal + ((end_scal - scal) * (current_life / lifespan)); } else { matScale._11 = matScale._22 = matScale._33 = scal; } // Now build the world matrix and set it device->SetTransform(D3DTS_WORLD, &(matScale * matRotateX * matRotateY * matRotateZ * matTranslate)); } void Particle::run_particle(float dt, float p_lifetime, float lifetime_invariant, Vector3D pos, float ang_1, float ang_2, float spd1, float spd2, float acc1, float acc2, float spin, float spin_invariance) { // handle lifespan current_life += dt; if (current_life > p_lifetime) { const float new_time = random_number(p_lifetime - lifetime_invariant, p_lifetime + lifetime_invariant); const float new_spin = random_number(spin - spin_invariance, spin + spin_invariance); reset_particle(pos, new_time, ang_1, ang_2, spd1, spd2, acc1, acc2, new_spin); return; } velocity += acceleration * dt; position += velocity * dt; this->angle += this->spin * dt; } void Particle::reset_particle(Vector3D pos, float p_lifetime, float ang_1, float ang_2, float spd1, float spd2, float acc1, float acc2, float spin) { active = false; lifespan = p_lifetime; position.x = pos.x; position.y = pos.y; position.z = pos.z; float angle_new = random_number(std::min(ang_1, ang_2), std::max(ang_1, ang_2)); float speed = random_number(std::min(spd1, spd2), std::max(spd1, spd2)); float acc = random_number(std::min(acc1, acc2), std::max(acc1, acc2)); velocity.x = cos((angle_new / 180.0f) * PI) * speed; velocity.y = sin((angle_new / 180.0f) * PI) * speed;// random_number(-2.0f, 2.0f); velocity.z = 0.0f; acceleration.x = cos((angle_new / 180.0f) * PI) * acc; acceleration.y = sin((angle_new / 180.0f) * PI) * acc; acceleration.z = 0.0f;//random_number(-15.0f, 25.0f); this->spin = spin; this->angle = 0.0f; current_life = 0.0f; } void Particle::run_particle_square(float dt, float p_lifetime, float lifetime_invariant, Vector3D pos, float width, float height, float spd1 /*= 1.0f*/, float spd2, float acc1, float acc2, float angle, float spin, float spin_invariance) { // handle lifespan current_life += dt; if (current_life > p_lifetime) { const float new_time = random_number(p_lifetime - lifetime_invariant, p_lifetime + lifetime_invariant); const float new_spin = random_number(spin - spin_invariance, spin + spin_invariance); reset_particle_square(pos, new_time, width, height, spd1, spd2, acc1, acc2, angle, new_spin); return; } velocity += acceleration * dt; position += velocity * dt; this->angle += this->spin * dt; } void Particle::reset_particle_square(Vector3D pos, float p_lifetime, float width /*= 1.0f*/, float height /*= 1.0f*/, float spd1 /*= 1.0f*/, float spd2 /*= 4.0f*/, float acc1 /*= 1.0f*/, float acc2 /*= 20.0f*/, float angle, float new_spin) { active = false; lifespan = p_lifetime; position.x = pos.x + random_number(-(width / 2.0f), (width / 2.0f)); position.y = pos.y + random_number(-(height / 2.0f), (height / 2.0f)); position.z = pos.z; //float angle_new = random_number(std::min(ang_1, ang_2), std::max(ang_1, ang_2)); float speed = random_number(std::min(spd1, spd2), std::max(spd1, spd2)); float acc = random_number(std::min(acc1, acc2), std::max(acc1, acc2)); velocity.x = cos((angle / 180.0f) * PI) * speed; velocity.y = sin((angle / 180.0f) * PI) * speed;// random_number(-2.0f, 2.0f); velocity.z = 0.0f; acceleration.x = cos((angle / 180.0f) * PI) * acc; acceleration.y = sin((angle / 180.0f) * PI) * acc; acceleration.z = 0.0f;//random_number(-15.0f, 25.0f); this->angle = 0.0f; spin = new_spin; current_life = 0.0f; } void Particle::run_particle_circle(float dt, float p_lifetime, float lifetime_invariant, Vector3D pos, float radius /*= 1.0f*/, float spd1 /*= 1.0f*/, float spd2 /*= 4.0f*/, float acc1 /*= 1.0f*/, float acc2 /*= 20.0f*/, float angle, float spin, float spin_invariance) { // handle lifespan current_life += dt; if (current_life > p_lifetime) { const float new_time = random_number(p_lifetime - lifetime_invariant, p_lifetime + lifetime_invariant); const float new_spin = random_number(spin - spin_invariance, spin + spin_invariance); reset_particle_circle(pos, new_time, radius, spd1, spd2, acc1, acc2, angle, new_spin); return; } velocity += acceleration * dt; position += velocity * dt; this->angle += this->spin * dt; } void Particle::reset_particle_circle(Vector3D pos, float p_lifetime, float radius, float spd1 /*= 1.0f*/, float spd2, float acc1, float acc2, float angle, float new_spin) { //t = 2 * pi*random() // u = random() + random() // r = if u > 1 then 2 - u else u // [r*cos(t), r*sin(t)] active = false; lifespan = p_lifetime; float t = 2.0f * PI * random_number(0, 1.0f) * radius; float u = random_number(0, radius/*1.0f*/) + random_number(0, radius/*1.0f*/); float r = u; if (u > radius/*1.0f*/) { r = radius + radius - u; } position.x = pos.x + (r * cos(t)); position.y = pos.y + (r * sin(t)); position.z = pos.z; //float angle_new = random_number(std::min(ang_1, ang_2), std::max(ang_1, ang_2)); float speed = random_number(std::min(spd1, spd2), std::max(spd1, spd2)); float acc = random_number(std::min(acc1, acc2), std::max(acc1, acc2)); velocity.x = cos((angle / 180.0f) * PI) * speed; velocity.y = sin((angle / 180.0f) * PI) * speed;// random_number(-2.0f, 2.0f); velocity.z = 0.0f; acceleration.x = cos((angle / 180.0f) * PI) * acc; acceleration.y = sin((angle / 180.0f) * PI) * acc; acceleration.z = 0.0f;//random_number(-15.0f, 25.0f); this->angle = 0.0f; this->spin = new_spin; current_life = 0.0f; } void Particle::run_particle_diamond(float dt, float p_lifetime, Vector3D pos, float width /*= 1.0f*/, float height /*= 1.0f*/, float spd1 /*= 1.0f*/, float spd2 /*= 4.0f*/, float acc1 /*= 1.0f*/, float acc2 /*= 20.0f*/, float angle /*= 0.0f*/) { } void Particle::reset_particle_diamond(Vector3D pos, float width /*= 1.0f*/, float height /*= 1.0f*/, float spd1 /*= 1.0f*/, float spd2 /*= 4.0f*/, float acc1 /*= 1.0f*/, float acc2 /*= 20.0f*/, float angle /*= 0.0f*/) { ///point_from_diamond(x,y,width,height) //var r1, r2; r1 = random(1); r2 = random(1); //global.x = argument0 + argument2*0.5*(r2 - r1 + 1); //global.y = argument1 + argument3*0.5*(r1 + r2); }
[ "Filiecs2@gmail.com" ]
Filiecs2@gmail.com
a72d69bd0fe62b03d11f4f96805b3f412dc756da
71d2598984432dabbb464c70e1f94df734783b78
/tags/rel_0.10.0/core/AmThread.cpp
3d0323a81b3978b4e6924f52224a03674b703cb5
[]
no_license
BackupTheBerlios/sems-svn
f55535988e9b9a093d7c8276c326cf7d42def042
fc19cf9f112df2490770411e0974bc65764b10d9
refs/heads/master
2020-06-01T16:32:05.042325
2010-06-03T09:51:35
2010-06-03T09:51:35
40,818,829
0
0
null
null
null
null
UTF-8
C++
false
false
7,516
cpp
/* * $Id$ * * Copyright (C) 2002-2003 Fhg Fokus * * This file is part of sems, a free SIP media server. * * sems is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version * * For a license to use the ser software under conditions * other than those described here, or to purchase support for this * software, please contact iptel.org by e-mail at the following addresses: * info@iptel.org * * sems 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "AmThread.h" #include "log.h" #include <unistd.h> #include "errno.h" #include <string> using std::string; AmMutex::AmMutex() { pthread_mutex_init(&m,NULL); } AmMutex::~AmMutex() { pthread_mutex_destroy(&m); } void AmMutex::lock() { pthread_mutex_lock(&m); } void AmMutex::unlock() { pthread_mutex_unlock(&m); } AmThread::AmThread() : _stopped(true) { } // int thread_nr=0; // AmMutex thread_nr_mut; void * AmThread::_start(void * _t) { AmThread* _this = (AmThread*)_t; _this->_pid = (pid_t) _this->_td; DBG("Thread %lu is starting.\n", (unsigned long int) _this->_pid); _this->_stopped.set(false); _this->run(); _this->_stopped.set(true); //thread_nr_mut.lock(); //INFO("threads = %i\n",--thread_nr); //thread_nr_mut.unlock(); DBG("Thread %lu is ending.\n", (unsigned long int) _this->_pid); return NULL; } void AmThread::start(bool realtime) { // start thread realtime...seems to not improve any thing // // if (realtime) { // pthread_attr_t attributes; // pthread_attr_init(&attributes); // struct sched_param rt_param; // if (pthread_attr_setschedpolicy (&attributes, SCHED_FIFO)) { // ERROR ("cannot set FIFO scheduling class for RT thread"); // } // if (pthread_attr_setscope (&attributes, PTHREAD_SCOPE_SYSTEM)) { // ERROR ("Cannot set scheduling scope for RT thread"); // } // memset (&rt_param, 0, sizeof (rt_param)); // rt_param.sched_priority = 80; // if (pthread_attr_setschedparam (&attributes, &rt_param)) { // ERROR ("Cannot set scheduling priority for RT thread (%s)", strerror (errno)); // } // int res; // _pid = 0; // res = pthread_create(&_td,&attributes,_start,this); // if (res != 0) { // ERROR("pthread create of RT thread failed with code %s\n", strerror(res)); // ERROR("Trying to start normal thread...\n"); // _pid = 0; // res = pthread_create(&_td,NULL,_start,this); // if (res != 0) { // ERROR("pthread create failed with code %i\n", res); // } // } // DBG("Thread %ld is just created.\n", (unsigned long int) _pid); // return; // } pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setstacksize(&attr,1024*1024);// 1 MB int res; _pid = 0; res = pthread_create(&_td,&attr,_start,this); pthread_attr_destroy(&attr); if (res != 0) { ERROR("pthread create failed with code %i\n", res); throw string("thread could not be started"); } // thread_nr_mut.lock(); // INFO("threads = %i\n",++thread_nr); // thread_nr_mut.unlock(); DBG("Thread %lu is just created.\n", (unsigned long int) _pid); } void AmThread::stop() { _m_td.lock(); // gives the thread a chance to clean up DBG("Thread %lu (%lu) calling on_stop, give it a chance to clean up.\n", (unsigned long int) _pid, (unsigned long int) _td); try { on_stop(); } catch(...) {} int res; if ((res = pthread_detach(_td)) != 0) { if (res == EINVAL) { WARN("pthread_detach failed with code EINVAL: thread already in detached state.\n"); } else if (res == ESRCH) { WARN("pthread_detach failed with code ESRCH: thread could not be found.\n"); } else { WARN("pthread_detach failed with code %i\n", res); } } DBG("Thread %lu (%lu) finished detach.\n", (unsigned long int) _pid, (unsigned long int) _td); //pthread_cancel(_td); _m_td.unlock(); } void AmThread::cancel() { _m_td.lock(); int res; if ((res = pthread_cancel(_td)) != 0) { ERROR("pthread_cancel failed with code %i\n", res); } else { DBG("Thread %lu is canceled.\n", (unsigned long int) _pid); _stopped.set(true); } _m_td.unlock(); } void AmThread::join() { if(!is_stopped()) pthread_join(_td,NULL); } int AmThread::setRealtime() { // set process realtime // int policy; // struct sched_param rt_param; // memset (&rt_param, 0, sizeof (rt_param)); // rt_param.sched_priority = 80; // int res = sched_setscheduler(0, SCHED_FIFO, &rt_param); // if (res) { // ERROR("sched_setscheduler failed. Try to run SEMS as root or suid.\n"); // } // policy = sched_getscheduler(0); // std::string str_policy = "unknown"; // switch(policy) { // case SCHED_OTHER: str_policy = "SCHED_OTHER"; break; // case SCHED_RR: str_policy = "SCHED_RR"; break; // case SCHED_FIFO: str_policy = "SCHED_FIFO"; break; // } // DBG("Thread has now policy '%s' - priority 80 (from %d to %d).\n", str_policy.c_str(), // sched_get_priority_min(policy), sched_get_priority_max(policy)); // return 0; return 0; } AmThreadWatcher* AmThreadWatcher::_instance=0; AmMutex AmThreadWatcher::_inst_mut; AmThreadWatcher::AmThreadWatcher() : _run_cond(false) { } AmThreadWatcher* AmThreadWatcher::instance() { _inst_mut.lock(); if(!_instance){ _instance = new AmThreadWatcher(); _instance->start(); } _inst_mut.unlock(); return _instance; } void AmThreadWatcher::add(AmThread* t) { DBG("trying to add thread %lu to thread watcher.\n", (unsigned long int) t->_pid); q_mut.lock(); thread_queue.push(t); _run_cond.set(true); q_mut.unlock(); DBG("added thread %lu to thread watcher.\n", (unsigned long int) t->_pid); } void AmThreadWatcher::on_stop() { } void AmThreadWatcher::run() { for(;;){ _run_cond.wait_for(); // Let some time for to threads // to stop by themselves sleep(10); q_mut.lock(); DBG("Thread watcher starting its work\n"); try { queue<AmThread*> n_thread_queue; while(!thread_queue.empty()){ AmThread* cur_thread = thread_queue.front(); thread_queue.pop(); q_mut.unlock(); DBG("thread %lu is to be processed in thread watcher.\n", (unsigned long int) cur_thread->_pid); if(cur_thread->is_stopped()){ DBG("thread %lu has been destroyed.\n", (unsigned long int) cur_thread->_pid); delete cur_thread; } else { DBG("thread %lu still running.\n", (unsigned long int) cur_thread->_pid); n_thread_queue.push(cur_thread); } q_mut.lock(); } swap(thread_queue,n_thread_queue); }catch(...){ /* this one is IMHO very important, as lock is called in try block! */ ERROR("unexpected exception, state may be invalid!\n"); } bool more = !thread_queue.empty(); q_mut.unlock(); DBG("Thread watcher finished\n"); if(!more) _run_cond.set(false); } }
[ "sayer@8eb893ce-cfd4-0310-b710-fb5ebe64c474" ]
sayer@8eb893ce-cfd4-0310-b710-fb5ebe64c474
9b236fc0880a350a60aa251fadfb25c72350bc91
84257c31661e43bc54de8ea33128cd4967ecf08f
/ppc_85xx/usr/include/c++/4.2.2/gnu/javax/net/ssl/provider/JDBCSessionContext.h
d1e8de9e603c922d7d4c47e29296d9aa87812300
[]
no_license
nateurope/eldk
9c334a64d1231364980cbd7bd021d269d7058240
8895f914d192b83ab204ca9e62b61c3ce30bb212
refs/heads/master
2022-11-15T01:29:01.991476
2020-07-10T14:31:34
2020-07-10T14:31:34
278,655,691
0
0
null
null
null
null
UTF-8
C++
false
false
2,273
h
// DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*- #ifndef __gnu_javax_net_ssl_provider_JDBCSessionContext__ #define __gnu_javax_net_ssl_provider_JDBCSessionContext__ #pragma interface #include <gnu/javax/net/ssl/provider/SessionContext.h> #include <gcj/array.h> extern "Java" { namespace gnu { namespace javax { namespace net { namespace ssl { namespace provider { class JDBCSessionContext; class Session; class Session$ID; } } } } } namespace javax { namespace net { namespace ssl { class SSLSession; } } } namespace java { namespace security { namespace cert { class Certificate; } } namespace sql { class PreparedStatement; class Connection; } } } class gnu::javax::net::ssl::provider::JDBCSessionContext : public ::gnu::javax::net::ssl::provider::SessionContext { public: // actually package-private JDBCSessionContext (); public: virtual ::java::util::Enumeration *getIds (); virtual ::javax::net::ssl::SSLSession *getSession (jbyteArray); public: // actually package-private virtual jboolean addSession (::gnu::javax::net::ssl::provider::Session$ID *, ::gnu::javax::net::ssl::provider::Session *); virtual jboolean containsSessionID (::gnu::javax::net::ssl::provider::Session$ID *); public: // actually protected virtual jboolean removeSession (::gnu::javax::net::ssl::provider::Session$ID *); public: // actually package-private virtual void notifyAccess (::gnu::javax::net::ssl::provider::Session *); private: jbyteArray certs (JArray< ::java::security::cert::Certificate *> *); public: // actually protected ::java::sql::Connection * __attribute__((aligned(__alignof__( ::gnu::javax::net::ssl::provider::SessionContext )))) connection; ::java::sql::PreparedStatement *selectById; ::java::sql::PreparedStatement *insert; ::java::sql::PreparedStatement *selectTimestamp; ::java::sql::PreparedStatement *updateTimestamp; ::java::sql::PreparedStatement *deleteSession; public: static ::java::lang::Class class$; }; #endif /* __gnu_javax_net_ssl_provider_JDBCSessionContext__ */
[ "Andre.Mueller@nateurope.com" ]
Andre.Mueller@nateurope.com
a3759a4eed395ac89213f3549b94b6fa83ca3107
34b697f39aadee27b4217795130136cd7ca1124e
/Software/Fire_Firework_Starter/Fire_Firework_Starter.ino
cad38800470590d65040d673c5726ec0b8c9eada
[]
no_license
misperry/Firework_Controler
6bfa3c4686293aa477734efa505a44f3a50656b6
9a89330e5e990928e6529e63e040700f95cf7ba5
refs/heads/master
2020-06-13T20:56:43.797411
2019-07-02T03:57:41
2019-07-02T03:57:41
194,785,298
0
0
null
null
null
null
UTF-8
C++
false
false
2,872
ino
/* * File Name: Fire_Firework_Starter.ino * Author: misperry * Date: 06/23/2019 * * Description: This is the main Firmware for the Bluetooth Enabled * Firework system. The connections will be as follows on the Fire beetle * * Port 1: IO25 * Port 2: IO26 * Port 3: IO27 * Port 4: IO3 * Port 5: IO0 * Port 6: IO13 * Port 7: IO5 * Port 8: IO2 * * * Also if you send any letter a to f for each character it will increase * the hold-on time of the realy by 500ms. * * i.e. a = 500ms, b = 1000ms, c = 1500ms, etc. */ #include "BluetoothSerial.h" #if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED) #error Bluetooth is not enabled! Please run `make menuconfig` to and enable it #endif BluetoothSerial SerialBT; void setup() { Serial.begin(115200); SerialBT.begin("ESP32test"); //Bluetooth device name Serial.println("The device started, now you can pair it with bluetooth!"); //Declair and initialize the pins pinMode(25, OUTPUT); pinMode(26, OUTPUT); pinMode(27, OUTPUT); pinMode(3, OUTPUT); pinMode(0, OUTPUT); pinMode(13, OUTPUT); pinMode(5, OUTPUT); pinMode(2, OUTPUT); digitalWrite(25, HIGH); digitalWrite(26, HIGH); digitalWrite(27, HIGH); digitalWrite(3, HIGH); digitalWrite(0, HIGH); digitalWrite(13, HIGH); digitalWrite(5, HIGH); digitalWrite(2, HIGH); } void loop() { char cmd = 'N'; int ms_delay = 1500; if (SerialBT.available()) { cmd = SerialBT.read(); Serial.write(cmd); } if (cmd == '1') { digitalWrite(25, LOW); delay(ms_delay); digitalWrite(25, HIGH); cmd = 'N'; } else if (cmd == '2') { digitalWrite(26, LOW); delay(ms_delay); digitalWrite(26, HIGH); cmd = 'N'; } else if (cmd == '3') { digitalWrite(27, LOW); delay(ms_delay); digitalWrite(27, HIGH); cmd = 'N'; } else if (cmd == '4') { digitalWrite(3, LOW); delay(ms_delay); digitalWrite(3, HIGH); cmd = 'N'; } else if (cmd == '5') { digitalWrite(0, LOW); delay(ms_delay); digitalWrite(0, HIGH); cmd = 'N'; } else if (cmd == '6') { digitalWrite(13, LOW); delay(ms_delay); digitalWrite(13, HIGH); cmd = 'N'; } else if (cmd == '7') { digitalWrite(5, LOW); delay(ms_delay); digitalWrite(5, HIGH); cmd = 'N'; } else if (cmd == '8') { digitalWrite(2, LOW); delay(ms_delay); digitalWrite(2, HIGH); cmd = 'N'; } else if (cmd = 'a') { ms_delay = 500; } else if (cmd = 'b') { ms_delay = 1000; } else if (cmd = 'c') { ms_delay = 1500; } else if (cmd = 'd') { ms_delay = 2000; } else if (cmd = 'e') { ms_delay = 2500; } else if (cmd = 'f') { ms_delay = 3000; } else { cmd = 'N'; } delay(20); }
[ "mitch.sperry@gmail.com" ]
mitch.sperry@gmail.com
ea52f62fd247c65ef03d5145f3a92f508fd6d65a
b06f3641828a90c2b72de6f3bbe830a51a4ec0d5
/ofxDaqRecorder/src/ofxDaqDCDCUSB.h
b5aa9500e8bafccda8ef113ec44f6ed254b5c4e9
[]
no_license
raulpober/open-frameworks-daq
1f16bc2253a1dbf7ae4835544105297efa1be5f1
647faa2ccf528a8abbb2eba3ea831958fbeb2167
refs/heads/master
2016-08-04T16:28:32.380914
2012-09-15T20:24:13
2012-09-15T20:24:13
5,323,973
1
1
null
null
null
null
UTF-8
C++
false
false
420
h
#pragma once #include "ofxDaq.h" #include "ofxDaqLog.h" extern "C" { #include "dcdc-usb/dcdc-usb.h" } class ofxDaqDCDCUSB { public: ofxDaqDCDCUSB(bool systemCall); ~ofxDaqDCDCUSB(); float getBatteryVoltage(); protected: struct usb_dev_handle *device; unsigned char data[MAX_TRANSFER_SIZE]; int ret; bool deviceError; bool systemCall; ofxDaqLog daqLog; string name; int id; };
[ "paulr@mpl.ucsd.edu" ]
paulr@mpl.ucsd.edu
8fc0b90b69fce36644df252e4ee220c2e799c132
b7128624d25b8a34431751fe504e3c8ad79ee0ce
/src/protocols/slp6/impl/va/vaent.h
1d6716390167e9600a4f79ac54e98307c3afba03
[ "LicenseRef-scancode-x11-xconsortium-veillard", "BSD-2-Clause" ]
permissive
DOORS-Framework/DOORS
e7a0e9d84064334822f20722ad48d9330ee9368f
999343fc3a40d9c5ec6e8ef7b46cce95bc751fcd
refs/heads/master
2022-03-31T16:07:06.960467
2019-12-23T15:06:31
2019-12-23T15:06:31
209,012,574
0
0
null
null
null
null
UTF-8
C++
false
false
6,865
h
// Editor-info: -*- C++ -*- // Copyright 2003 // Telecoms Lab, Tampere University of Technology. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY TAMPERE UNIVERSITY OF TECHNOLOGY 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 UNIVERSITY // 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. /* $Log: vaent.h,v $ Revision 1.8 2007/10/04 05:41:31 bilhanan devt Revision 1.7 2007/10/02 20:18:52 bilhanan devt Revision 1.6 2007/06/19 08:04:36 bilhanan testing rebinding Revision 1.5 2007/01/15 11:03:20 bilhanan devt Revision 1.4 2007/01/08 14:31:37 bilhanan devt Revision 1.3 2006/12/21 13:13:58 bilhanan devt Revision 1.2 2006/12/13 22:00:58 bilhanan development Revision 1.1 2006/08/10 15:39:07 bilhanan initial commit Revision 1.6 2004/06/17 08:56:31 hartmanj Development. Revision 1.5 2004/05/21 06:09:12 hartmanj MobilitySAP added. Names of some handler functions changed Revision 1.4 2004/05/20 07:00:09 hartmanj Manual fix to last comment Revision 1.3 2004/05/19 13:52:03 hartmanj Update Revision 1.2 2004/05/12 08:33:21 hartmanj Development Revision 1.1 2004/01/28 09:23:31 hartmanj Initial revision. Compiles. */ #ifndef _VAENT_H #define _VAENT_H #include <vector> #include <string> #include <doors/ptb.h> #include <doors/udp6task.h> #include <doors/slppdu.h> #include <doors/serviceurl.h> #include <doors/slpcommon.h> #include "vasap.h" #include "movenotifysap.h" #include "servicereg.h" //#include "serviceregsm.h" //#include "vuaconnsm.h" #include "agentconn.h" class VAEntitySM; class ServiceRegSM; class VUAConnSM; class ServiceReg; class VUAConn; class VAEntity : public PTask, public SLPCommon { public : VAEntity (std::string n, Scheduler *s, VAEntitySM *sm, InetAddr6 &addr); virtual ~VAEntity(); // Closed state bool closed_timeout (Message *); bool allstates_SLPOpen( Message * ); bool allstates_SLPClose( Message * ); // Peer replies bool allstates_SrvRply(Message *msg); bool allstates_srvack(Message *msg); bool allstates_AttrRply(Message *msg); bool allstates_SrvtypeRply(Message *msg); // Peer requests bool allstates_PeerRqst(Message *msg); bool allstates_SrvtypeRqst(Message *msg); // Up req bool allstates_Srv_req(Message *msg); bool allstates_Srvtype_req(Message *msg); bool allstates_Attr_req(Message *msg); bool allstates_registerService(Message *msg); bool allstates_deregisterService(Message *msg); bool allstates_addAttributes(Message *msg); bool allstates_deleteAttributes(Message *msg); // Rebind bool allstates_rebind(Message *msg); // AAPresent bool aapresent_default(Message *msg); bool aapresent_aaadvert(Message *msg); bool aapresent_daadvert(Message *msg); bool aapresent_timeout(Message *msg); // DAPresent bool dapresent_default(Message *msg); bool dapresent_aaadvert(Message *msg); bool dapresent_daadvert(Message *msg); bool dapresent_timeout(Message *msg); // No AA | DA bool alone_default(Message *msg); bool alone_daadvert(Message *msg); bool alone_aaadvert(Message *msg); bool alone_timeout(Message *msg); // Both present bool bothpresent_default(Message *msg); bool bothpresent_daadvert(Message *msg); bool bothpresent_aaadvert(Message *msg); bool bothpresent_timeout(Message *msg); // To access information on AAs and DAs the connection tasks contact // the entity task. Entity task holds the address and state information. bool isDAPresent(void) const; bool isAAPresent(void) const; InetAddr6 getAAAddr(void) const; InetAddr6 getDAAddr(void) const; int getIP6Scope(void) const; int getSLPPort(void) const; InetAddr6 getCurrAddr(void) const; InetAddr6 getHomeAddr(void) const; void constructAddr (); bool checkAddrChange(void); bool isAtHome(); Udp6SAP :: User down; VASAP :: Provider up; SLPPeer peer; ServiceRegSAP :: User sreg_sap; MoveNotifySAP :: Provider mdprovider; AgentConn* getNewAgentConn(); void releaseAgent( AgentConn *agent ); private: void sendAAUpdateToRegs( InetAddr6 &a ); void sendDAUpdateToRegs( InetAddr6 &a ); void sendMovementToRegs( ); void sendAASolicitation ( void ); void sendDASolicitation ( void ); bool checkHandle( Uint32 h ) const; void createServiceReg( Uint32 slphandle ); void createVUAConn( Uint32 slphandle ); void join( ); SLPPeer::SRVRQST *solicitation; Port vuaConns; Port serviceRegs; PortMux MNMux; // port for sending movement notification PortMux vuaConnMux; PortMux serviceRegMux; ServiceRegSM *serviceRegSM; AgentConnSM *agentConnSM; VUAConnSM *vuaConnSM; std::vector<AgentConn*> agentConnList; std::vector<AgentConn*> freeAgents; std::vector<ServiceReg*> serviceregs; bool isDAPresentflag; bool isAAPresentflag; InetAddr6 newAddr; InetAddr6 currAddr; InetAddr6 homeAddr; InetAddr6 aaAddr; InetAddr6 daAddr; Uint16 aaSolXid; Uint16 daSolXid; std::string currAAPrefix; std::string newAAPrefix; std::string homeprefix; std::string linksuffix; std::map<Uint32,std::string> openHandles; VAConfigurator *myconfig; int timerInterval; int maxTimeToSolicit; int timeUsed; bool inNewNetwork; Timer onesecond_timer; Timer normal_timer; Timer closed_timer; Timer configretry_timer; int sinceLastAAAdvert; int AAAdvertTimeoutMax; int sinceLastDAAdvert; int DAAdvertTimeoutMax; OTime config_retry; OTime onesecond_timeout; OTime normal_timeout; }; #endif // VAENT_H
[ "bilhanan@gmail.com" ]
bilhanan@gmail.com
4f8bd808bf7a7cb995e28d5865d38ee8a2c2d8f8
703c2b33c78900aaa608df38630dff2919fcb8d4
/hiredis/common/Random.cpp
4c388330ff111c2f79b49b96700aa9ebebe549aa
[]
no_license
abc463774475/hiredis
5165af7242da8d4f1bbbb5da13516b79573c5908
eae1fc0325663f43095cc3e8540844ef7aaf1c91
refs/heads/master
2021-08-29T14:25:01.603786
2017-03-29T10:40:10
2017-03-29T10:40:10
114,199,107
0
0
null
null
null
null
UTF-8
C++
false
false
6,767
cpp
#include "Random.h" #include <stdlib.h> #include <time.h> /* instance of random number generator */ RandomMersenne *g_generator; uint32_t generate_seed() { // uint32_t mstime = GetTickCount (); // uint32_t stime = (uint32_t)time (0); // uint32_t rnd[2]; // rnd[0] = rand()*rand()*rand(); // rnd[1] = rand()*rand()*rand(); // // uint32_t val = mstime ^ rnd[0]; // val += stime ^ rnd[1]; // // return val; return time(NULL); } void InitRandomNumberGenerator() { srand (time(NULL)); /// Make instance of random number generator g_generator = new RandomMersenne (generate_seed ()); } void CleanupRandomNumberGenerators() { srand (time(NULL)); delete g_generator; g_generator = 0; } uint32_t RandomUInt() { return g_generator->IRandom (0, RAND_MAX); } uint32_t RandomUInt(uint32_t n) { return g_generator->IRandom (0, n); } uint32_t RandomUInt(uint32_t min, uint32_t max) { if (max <= min) { if (max == min) return min; else return 0x80000000; } return (min + g_generator->IRandom (0, (max - min))); } double RandomDouble() { return g_generator->Random (); } double RandomDouble(double n) { return RandomDouble () * n; } float RandomFloat() { return float(RandomDouble ()); } float RandomFloat(float n) { return float(RandomDouble () * double(n)); } //set<UINT> RandomVector(const vector<UINT> &vSource , int needNum ) //{ // if ( needNum <= vSource.size() ) // { // return vSource; // } // vector<uint32_t> vTotal = vSource ; // // std::random_shuffle(vTotal.begin(),vTotal.end()); // // return ; //} void RandomMersenne::Init0(uint32_t seed) { // Detect computer architecture union {double f; uint32_t i[2];} convert; convert.f = 1.0; if (convert.i[1] == 0x3FF00000) Architecture = LITTLE_ENDIAN1; else if (convert.i[0] == 0x3FF00000) Architecture = BIG_ENDIAN1; else Architecture = NONIEEE; // Seed generator mt[0]= seed; for (mti=1; mti < MERS_N; mti++) { mt[mti] = (1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti); } } void RandomMersenne::RandomInit(uint32_t seed) { // Initialize and seed Init0(seed); // Randomize some more for (int i = 0; i < 37; i++) BRandom(); } void RandomMersenne::RandomInitByArray(uint32_t seeds[], int length) { // Seed by more than 32 bits int i, j, k; // Initialize Init0(19650218); if (length <= 0) return; // Randomize mt[] using whole seeds[] array i = 1; j = 0; k = (MERS_N > length ? MERS_N : length); for (; k; k--) { mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL)) + seeds[j] + j; i++; j++; if (i >= MERS_N) {mt[0] = mt[MERS_N-1]; i=1;} if (j >= length) j=0;} for (k = MERS_N-1; k; k--) { mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL)) - i; if (++i >= MERS_N) {mt[0] = mt[MERS_N-1]; i=1;}} mt[0] = 0x80000000UL; // MSB is 1; assuring non-zero initial array // Randomize some more mti = 0; for (int i = 0; i <= MERS_N; i++) BRandom(); } uint32_t RandomMersenne::BRandom() { // Generate 32 random bits uint32_t y; if (mti >= MERS_N) { // Generate MERS_N words at one time const uint32_t LOWER_MASK = (1LU << MERS_R) - 1; // Lower MERS_R bits const uint32_t UPPER_MASK = 0xFFFFFFFF << MERS_R; // Upper (32 - MERS_R) bits static const uint32_t mag01[2] = {0, MERS_A}; int kk; for (kk=0; kk < MERS_N-MERS_M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+MERS_M] ^ (y >> 1) ^ mag01[y & 1];} for (; kk < MERS_N-1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(MERS_M-MERS_N)] ^ (y >> 1) ^ mag01[y & 1];} y = (mt[MERS_N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[MERS_N-1] = mt[MERS_M-1] ^ (y >> 1) ^ mag01[y & 1]; mti = 0; } y = mt[mti++]; #if 1 // Tempering (May be omitted): y ^= y >> MERS_U; y ^= (y << MERS_S) & MERS_B; y ^= (y << MERS_T) & MERS_C; y ^= y >> MERS_L; #endif return y; } double RandomMersenne::Random() { // Output random float number in the interval 0 <= x < 1 union {double f; uint32_t i[2];} convert; uint32_t r = BRandom(); // Get 32 random bits // The fastest way to convert random bits to floating point is as follows: // Set the binary exponent of a floating point number to 1+bias and set // the mantissa to random bits. This will give a random number in the // interval [1,2). Then subtract 1.0 to get a random number in the interval // [0,1). This procedure requires that we know how floating point numbers // are stored. The storing method is tested in function RandomInit and saved // in the variable Architecture. // This shortcut allows the compiler to optimize away the following switch // statement for the most common architectures: convert.i[0] = r << 20; convert.i[1] = (r >> 12) | 0x3FF00000; return convert.f - 1.0; // This somewhat slower method works for all architectures, including // non-IEEE floating point representation: //return (double)r * (1./((double)(uint32_t)(-1L)+1.)); } int RandomMersenne::IRandom(int min, int max) { // Output random integer in the interval min <= x <= max // Relative error on frequencies < 2^-32 if (max <= min) { if (max == min) return min; else return 0x80000000; } // Multiply interval with random and truncate int r = int((max - min + 1) * Random()) + min; if (r > max) r = max; return r; } int RandomMersenne::IRandomX(int min, int max) { // Output random integer in the interval min <= x <= max // Each output value has exactly the same probability. // This is obtained by rejecting certain bit values so that the number // of possible bit values is divisible by the interval length if (max <= min) { if (max == min) return min; else return 0x80000000; } // 64 bit integers available. Use multiply and shift method uint32_t interval; // Length of interval uint64_t longran; // Random bits * interval uint32_t iran; // Longran / 2^32 uint32_t remainder; // Longran % 2^32 interval = uint32_t(max - min + 1); if (interval != LastInterval) { // Interval length has changed. Must calculate rejection limit // Reject when remainder = 2^32 / interval * interval // RLimit will be 0 if interval is a power of 2. No rejection then RLimit = uint32_t(((uint64_t)1 << 32) / interval) * interval - 1; LastInterval = interval; } do { // Rejection loop longran = (uint64_t)BRandom() * interval; iran = (uint32_t)(longran >> 32); remainder = (uint32_t)longran; } while (remainder > RLimit); // Convert back to signed and return result return (int)iran + min; } //vector<uint32_t> RandVecotr(uint32_t _startPos,uint32_t _totalSize , uint32_t _needSize) //{ // //}
[ "hexiaodong198786@126.com" ]
hexiaodong198786@126.com
9d0af23ec17d89ba676f4d42a5158ceacd8bcff0
e9b8905c40f87cfb72f047084f8fc904fe1fec47
/test/test_navigation.cpp
851637334ae8c8edd78369d3c31b54a4d7e7a7b8
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
shivaang12/smart_agv
cb246045cd518b3763bb7048e1b336275457908d
480dadd570ec09d19adf8380c5bcfcc7704d01ae
refs/heads/master
2020-04-08T14:29:01.455025
2018-12-16T21:56:50
2018-12-16T21:56:50
159,438,679
1
0
null
null
null
null
UTF-8
C++
false
false
4,932
cpp
/******************************************************************** * MIT License * * Copyright (c) 2018 Shivang Patel * * 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 test_navigation.cpp * @brief Implementation of unit test for SmartBOT class * * This file contains implemetation of unit test of class SmartBOT. * * @author Shivang Patel */ #include <actionlib_msgs/GoalID.h> #include <geometry_msgs/Pose.h> #include <geometry_msgs/Twist.h> #include <gtest/gtest.h> #include <ros/ros.h> #include <std_msgs/String.h> #include <stdlib.h> #include <iostream> #include <boost/thread.hpp> #include <smartAGV/navigation.hpp> #include "test_class.hpp" void threadSpinning(void) { ros::Rate loop_rate(10); while (ros::ok()) { ros::spinOnce(); loop_rate.sleep(); } } TEST(TestNavigation, testDefault) { ros::NodeHandle n; TestClass testVar; std_msgs::String msg; Navigation nav; ros::Rate loop_rate(2); nav.initialize(n); auto sub = n.subscribe("/mobile_base/commands/velocity", 1000, &TestClass::TestMoveBaseVelocity, &testVar); loop_rate.sleep(); EXPECT_EQ(1, sub.getNumPublishers()); } TEST(TestNavigation, testGoTOFunction) { ros::NodeHandle n; TestClass testVar; std_msgs::String msg; Navigation nav; ros::Rate loop_rate(2); nav.initialize(n); std::cout << "before sub" << '\n'; ros::Subscriber MBsubGoal = n.subscribe( "/move_base/goal", 1000, &TestClass::TestMoveBaseGoal, &testVar); ros::Subscriber MBsubCancel = n.subscribe( "/move_base/cancel", 1000, &TestClass::TestMoveBaseCancelGoal, &testVar); ROS_DEBUG_STREAM( "TEST MBGoal number of publisher = " << MBsubGoal.getNumPublishers()); ROS_DEBUG_STREAM( "TEST MBCancel number of publisher = " << MBsubCancel.getNumPublishers()); geometry_msgs::Pose varGoal; varGoal.position.x = 5; varGoal.position.y = 5; varGoal.position.z = 0.0; varGoal.orientation.x = 0.0; varGoal.orientation.y = 0.0; varGoal.orientation.z = 0.950; varGoal.orientation.w = 0.312; nav.goTO(varGoal); loop_rate.sleep(); geometry_msgs::Pose goalPos = testVar.BotPos; EXPECT_EQ(0, std::memcmp(&varGoal, &goalPos, sizeof(varGoal))); } TEST(TestNavigation, testAbortMoveFunction) { ros::NodeHandle n; TestClass testVar; std_msgs::String msg; Navigation nav; ros::Rate loop_rate(2); ros::Subscriber MBsubGoal = n.subscribe( "/move_base/goal", 1000, &TestClass::TestMoveBaseGoal, &testVar); ros::Subscriber MBsubCancel = n.subscribe( "/move_base/cancel", 1000, &TestClass::TestMoveBaseCancelGoal, &testVar); ROS_DEBUG_STREAM( "TEST MBGoal number of publisher = " << MBsubGoal.getNumPublishers()); ROS_DEBUG_STREAM( "TEST MBCancel number of publisher = " << MBsubCancel.getNumPublishers()); geometry_msgs::Pose varGoal; varGoal.position.x = -5; varGoal.position.y = -5; varGoal.position.z = 0.0; varGoal.orientation.x = 0.0; varGoal.orientation.y = 0.0; varGoal.orientation.z = 0.95; varGoal.orientation.w = 0.1; nav.goTO(varGoal); loop_rate.sleep(); nav.abortMove(); loop_rate.sleep(); EXPECT_STREQ(testVar.goalID.c_str(), testVar.cancelID.c_str()); } TEST(TestNavigation, testCallback) { ros::NodeHandle n; Navigation nav; actionlib::SimpleClientGoalState state = actionlib::SimpleClientGoalState::SUCCEEDED; move_base_msgs::MoveBaseResult::ConstPtr result = NULL; nav.initialize(n); nav.movebaseCallback(state, result); } int main(int argc, char **argv) { ros::init(argc, argv, "test_agv_navigation"); ::testing::InitGoogleTest(&argc, argv); ros::NodeHandle nodeHand; boost::thread th(threadSpinning); int rturn = RUN_ALL_TESTS(); ros::shutdown(); // wait the second thread to finish th.join(); return rturn; }
[ "shivaang14@gmail.com" ]
shivaang14@gmail.com
03456c2470ce417b04dfb48b31c24a29ae400104
67f09d83fd4691c2d45e7899d529b36c900d7356
/MemeCollector/QuickUrlWindow.hpp
6e50bf5cb830174f1d8bfcb2ced083ef555fb017
[]
no_license
artudi54/MemeCollector
c4f6a5d805db169b643b51f73f4ad62c69e5a912
3ee51e101294f70d8602867f2c8b9a7a1662e4d0
refs/heads/master
2021-09-14T12:30:39.475717
2018-05-13T22:32:19
2018-05-13T22:32:19
125,861,473
1
0
null
null
null
null
UTF-8
C++
false
false
374
hpp
#pragma once #include "ui_QuickUrlWindow.h" class QuickUrlWindow : public QDialog, private Ui::QuickUrlWindow { Q_OBJECT public: QuickUrlWindow(QWidget *parent = nullptr, QTableWidget *table = nullptr); virtual ~QuickUrlWindow(); unsigned get_row_number() const; QString get_url_str() const; QString get_optional_name() const; private slots: void accept_input(); };
[ "artudi54@gmail.com" ]
artudi54@gmail.com
74be5db2b6b4d0d160eb9ccb4044fb072f4e2ca8
8d19ab53401030209dd7e5e655bdb0e2952bfa7e
/toonz/sources/common/tvectorimage/outlineApproximation.cpp
adb566332d5046e1d9b935f836c0ef227240a808
[ "BSD-3-Clause" ]
permissive
deruji/opentoonz
825a74af1dbc89c62991458a352650c4ef766fde
ad5f6141388f796c5146876916c812bf1b1f0ff9
refs/heads/master
2021-05-03T09:41:12.454051
2016-04-22T21:08:08
2016-04-22T21:08:08
54,891,799
0
0
null
2016-04-22T21:08:08
2016-03-28T12:49:04
C++
UTF-8
C++
false
false
19,940
cpp
// outlineApproximation.cpp: implementation of the outlineApproximation class. // ////////////////////////////////////////////////////////////////////// #include "tstrokeoutline.h" #include "tstroke.h" #include "tcurves.h" #include "tmathutil.h" #include "tgl.h" //#include "tcolorfunctions.h" typedef std::pair<TQuadratic *, TQuadratic *> outlineEdge; typedef std::vector<outlineEdge> outlineBoundary; const double infDouble = (std::numeric_limits<double>::max)(); /* ONLY FOT TEST TSegment g_tangEnvelope_1; TSegment g_tangEnvelope_2; vector<TQuadratic> g_testOutline; */ namespace Outline { class infinityCurvature { }; class notValidOutline { }; } namespace { /* This formule is derived from Graphic Gems pag. 600 e = h^2 |a|/8 e = pixel size h = step a = acceleration of curve (for a quadratic is a costant value) */ double localComputeStep(const TQuadratic &quad, double pixelSize) { double step = 2; TPointD A = quad.getP0() - 2.0 * quad.getP1() + quad.getP2(); // 2*A is the acceleration of the curve double A_len = norm(A); if (A_len > 0) step = TConsts::sqrt2 * sqrt(pixelSize / A_len); return step; } //--------------------------------------------------------------------------- // selezionano lo spicchio da calcolare nella costruzione dei tappi // (semicirconferenze iniziali e finali) const int QUARTER_BEGIN = 1; const int QUARTER_END = 0; // selezionano il pezzo d'outline da calcolare (sopra/sotto) const int OUTLINE_UP = 1; const int OUTLINE_DOWN = 0; // utili const double ratio_1_3 = 1.0 / 3.0; const double ratio_2_3 = 2.0 / 3.0; //--------------------------------------------------------------------------- // torna la curvature per t=0 template <class T> double curvature_t0(const T *curve) { assert(curve); TPointD v1 = curve->getP1() - curve->getP0(); TPointD v2 = curve->getP2() - curve->getP1(); double v_cross = cross(v1, v2); if (isAlmostZero(v_cross)) return infDouble; return ratio_2_3 * v_cross / pow(norm(v1), ratio_1_3); } //--------------------------------------------------------------------------- // torna la curvature per t=1 double curvature_t1(const TThickQuadratic *curve) { assert(curve); TThickQuadratic tmp; tmp.setThickP0(curve->getThickP2()); tmp.setThickP1(curve->getThickP1()); tmp.setThickP2(curve->getThickP0()); return curvature_t0(&tmp); } //--------------------------------------------------------------------------- // estrae il punto dell'outline per il parametro specificato // N.B: e' sbagliata non tiene conto degli inviluppi TPointD getPointInOutline(const TThickQuadratic *tq, double t, int upOrDown) { assert(tq); const TThickPoint &p = tq->getThickPoint(t); TPointD n = tq->getSpeed(t); if (norm2(n)) { n = normalize(n); n = upOrDown ? rotate90(n) : rotate270(n); } return convert(p) + p.thick * n; } //--------------------------------------------------------------------------- bool checkPointInOutline(const TPointD &pointToTest, const TThickQuadratic *tq, double t, double error) { assert(tq); TThickPoint tpnt = tq->getThickPoint(t); if (fabs(sq(pointToTest.x - tpnt.x) + sq(pointToTest.y - tpnt.y) - sq(tpnt.thick)) < error) return true; return false; } //--------------------------------------------------------------------------- // costruisce un ramo di outline (sopra o sotto) per una quadratica cicciona TQuadratic *makeOutlineForThickQuadratic(const TThickQuadratic *tq, int upOrDown) { assert(tq); // if(!outline) return 0; TThickPoint p0 = tq->getThickP0(), //p1 = tq->getThickP0(), p2 = tq->getThickP2(); TPointD t0 = tq->getP1() - tq->getP0(); TPointD t1 = tq->getP2() - tq->getP1(); if (t0 == t1) return 0; TPointD N0 = tq->getSpeed(0.0), N2 = tq->getSpeed(1.0); if (!norm2(N0) && !norm2(N2)) throw Outline::notValidOutline(); if (norm2(N0)) { N0 = normalize(N0); N0 = upOrDown ? rotate90(N0) : rotate270(N0); } if (norm2(N2)) { N2 = normalize(N2); N2 = upOrDown ? rotate90(N2) : rotate270(N2); } TPointD p0aux = (convert(p0) + p0.thick * N0); TPointD p2aux = (convert(p2) + p2.thick * N2); TQuadratic radius(TPointD(tq->getThickP0().thick, 0.0), TPointD(tq->getThickP1().thick, 0.0), TPointD(tq->getThickP2().thick, 0.0)); TPointD r0 = radius.getSpeed(0.0); TPointD r1 = radius.getSpeed(1.0); TPointD v0, v2; double ct0 = curvature_t0(tq); if (ct0 != infDouble) v0 = (1 + p0.thick * ct0) * t0 + 0.5 * r0.x * N0; else v0 = r0.x * N0; double ct1 = curvature_t1(tq); if (ct1 != infDouble) v2 = (1 + p2.thick * ct1) * t1 + 0.5 * r1.x * N2; else v2 = r1.x * N2; /* try { v0 = (1 + p0.thick * curvature_t0( tq )) * t0 + 0.5 * r0.x * N0; } catch( Outline::infinityCurvature& ) { } try { v2 = (1 + p2.thick * curvature_t1( tq )) * t1 + 0.5 * r1.x * N2; } catch( Outline::infinityCurvature& ) { } */ // g_tangEnvelope_1.setP0( outline.getP0() ); // g_tangEnvelope_1.setP1( outline.getP0() + v0 ); // g_tangEnvelope_2.setP0( outline.getP2() ); // g_tangEnvelope_2.setP1( outline.getP2() + v2 ); // solve sistem p1 = p0 + k * v1 = p2 + m * v2 to find double det = v0.x * v0.y - v2.x * v2.y; if (areAlmostEqual(det, 0.0)) return 0; double xsol; try { xsol = ((p0aux.x - p2aux.x) * v2.y - (p0aux.y - p2aux.y) * v2.x) / det; //tsolveSistem( A, 2, b ); } catch (TMathException &) { return new TQuadratic((upOrDown) ? p0aux : p2aux, (p0aux + p2aux) * 0.5, (upOrDown) ? p2aux : p0aux); } catch (std::exception &e) { string s(e.what()); abort(); } catch (...) { abort(); } return new TQuadratic((upOrDown) ? p0aux : p2aux, p0aux + xsol * v0, (upOrDown) ? p2aux : p0aux); } //--------------------------------------------------------------------------- /* costruisce l'outline per una singola quadratica senza inserire le semicirconferenze iniziali e finali */ void makeOutline(/*std::ofstream& cout,*/ outlineBoundary &outl, const TThickQuadratic &t, double error) { outlineEdge edge; const TThickQuadratic *tq = &t; edge.first = edge.second = 0; try { edge.first = makeOutlineForThickQuadratic(tq, OUTLINE_UP); edge.second = makeOutlineForThickQuadratic(tq, OUTLINE_DOWN); } catch (Outline::notValidOutline &) { delete edge.first; delete edge.second; return; } const TQuadratic *q_up = edge.first; const TQuadratic *q_down = edge.second; const double parameterTest = 0.5; // forza l'uscita per valori troppo piccoli bool isAlmostAPoint = areAlmostEqual(tq->getThickP0(), tq->getThickP1(), 1e-2) && areAlmostEqual(tq->getThickP1(), tq->getThickP2(), 1e-2) /*&& areAlmostEqual( tq.getThickP0(), tq.getThickP2(), 1e-2 )*/; if (isAlmostAPoint || q_up && checkPointInOutline(q_up->getPoint(parameterTest), tq, parameterTest, error) && q_down && checkPointInOutline(q_down->getPoint(parameterTest), tq, parameterTest, error)) { /* if (edge.first) cout << "left: "<< *(edge.first); else cout << "left: "<< 0; if (edge.second) cout << "right: "<<*(edge.second); else cout << "right: "<< 0; cout<<std::endl;*/ outl.push_back(edge); return; } else { delete edge.first; delete edge.second; } TThickQuadratic tq_left, tq_rigth; tq->split(0.5, tq_left, tq_rigth); makeOutline(/*out,*/ outl, tq_left, error); makeOutline(/*cout,*/ outl, tq_rigth, error); } //--------------------------------------------------------------------------- void splitCircularArcIntoQuadraticCurves(const TPointD &Center, const TPointD &Pstart, const TPointD &Pend, vector<TQuadratic *> &quadArray) { // It splits a circular anticlockwise arc into a sequence of quadratic bezier curves // Every quadratic curve can approximate an arc no TLonger than 45 degrees (or 60). // It supposes that Pstart and Pend are onto the circumference (so that their lengths // are equal to tha radius of the circumference), otherwise the resulting curves could // be unpredictable. // The last component in quadCurve[] is an ending void curve /* ---------------------------------------------------------------------------------- */ // If you want to split the arc into arcs no TLonger than 45 degrees (so that the whole // curve will be splitted into 8 pieces) you have to set these constants as follows: // cos_ang ==> cos_45 = 0.5 * sqrt(2); // sin_ang ==> sin_45 = 0.5 * sqrt(2); // tan_semiang ==> tan_22p5 = 0.4142135623730950488016887242097; // N_QUAD = 8; // If you want to split the arc into arcs no TLonger than 60 degrees (so that the whole // curve will be splitted into 6 pieces) you have to set these constants as follows: // cos_ang ==> cos_60 = 0.5; // sin_ang ==> sin_60 = 0.5 * sqrt(3); // tan_semiang ==> tan_30 = 0.57735026918962576450914878050196; // N_QUAD = 6; /* ---------------------------------------------------------------------------------- */ // Defines some useful constant to split the arc into arcs no TLonger than 'ang' degrees // (the whole circumference will be splitted into 360/ang quadratic curves). const double cos_ang = 0.5 * sqrt(2.0); const double sin_ang = 0.5 * sqrt(2.0); const double tan_semiang = 0.4142135623730950488016887242097; const int N_QUAD = 8; // it's 360/ang // First of all, it computes the vectors from the center to the circumference, // in Pstart and Pend, and their cross and dot products TPointD Rstart = Pstart - Center; // its length is R (radius of the circle) TPointD Rend = Pend - Center; // its length is R (radius of the circle) double cross_prod = cross(Rstart, Rend); // it's Rstart x Rend double dot_prod = Rstart * Rend; const double sqr_radius = Rstart * Rstart; TPointD aliasPstart = Pstart; TQuadratic *quad; while ((cross_prod <= 0) || (dot_prod <= cos_ang * sqr_radius)) // the circular arc is TLonger // than a 'ang' degrees arc { if ((int)quadArray.size() == N_QUAD) // this is possible if Pstart or Pend is not onto the circumference return; TPointD Rstart_rot_ang(cos_ang * Rstart.x - sin_ang * Rstart.y, sin_ang * Rstart.x + cos_ang * Rstart.y); TPointD Rstart_rot_90(-Rstart.y, Rstart.x); quad = new TQuadratic(aliasPstart, aliasPstart + tan_semiang * Rstart_rot_90, Center + Rstart_rot_ang); quadArray.push_back(quad); // quad->computeMinStepAtNormalSize (); // And moves anticlockwise the starting point on the circumference by 'ang' degrees Rstart = Rstart_rot_ang; aliasPstart = quad->getP2(); cross_prod = cross(Rstart, Rend); // it's Rstart x Rend dot_prod = Rstart * Rend; // after the rotation of 'ang' degrees, the remaining part of the arc could be a 0 degree // arc, so it must stop and exit from the function if ((cross_prod <= 0) && (dot_prod > 0.95 * sqr_radius)) return; } if ((cross_prod > 0) && (dot_prod > 0)) // the last quadratic curve approximates an arc shorter than a 'ang' degrees arc { TPointD Rstart_rot_90(-Rstart.y, Rstart.x); double deg_index = (sqr_radius - dot_prod) / (sqr_radius + dot_prod); quad = new TQuadratic(aliasPstart, (deg_index < 0) ? 0.5 * (aliasPstart + Pend) : aliasPstart + sqrt(deg_index) * Rstart_rot_90, Pend); quadArray.push_back(quad); } else // the last curve, already computed, is as TLong as a 'ang' degrees arc quadArray.back()->setP2(Pend); } //--------------------------------------------------------------------------- // copia arrayUp e arrayDown nel vettore dell'outline // se le dimensioni sono diverse il vettore con il numero // minore di quadratiche viene riempito con quadratiche degeneri // con i punti di controllo coincidenti nell'ultimo estremo valido void copy(/*std::ofstream& cout,*/ const vector<TQuadratic *> &arrayUp, const vector<TQuadratic *> &arrayDown, outlineBoundary &ob) { int minSize = tmin(arrayUp.size(), arrayDown.size()); assert(minSize > 0); int i; for (i = 0; i < minSize; ++i) { //cout<<"left: "<< *(arrayUp[i])<< "right: "<<*(arrayDown[i])<<std::endl; //cout<"left: "<< arrayUp[i].getP0()<<", "arrayUp[i].getP1()<<", "arrayUp[i].getP2()<< "right: "<< << arrayDown[i].getP0()<<", "arrayDown[i].getP1()<<", "arrayDown[i].getP2()<<endl; ob.push_back(outlineEdge(arrayUp[i], arrayDown[i])); } if (arrayUp.size() != arrayDown.size()) { const vector<TQuadratic *> &vMaxSize = arrayUp.size() > arrayDown.size() ? arrayUp : arrayDown; const vector<TQuadratic *> &vMinSize = arrayUp.size() < arrayDown.size() ? arrayUp : arrayDown; int delta = vMaxSize.size() - vMinSize.size(); if (arrayUp.size() > arrayDown.size()) while (i < minSize + delta) { //cout<<"left: "<< arrayUp[i]<< "right: "<< 0<<std::endl; ob.push_back(outlineEdge(arrayUp[i], (TQuadratic *)0)); i++; } else while (i < minSize + delta) { //cout<<"left: "<< 0 << "right: "<< arrayDown[i]<<std::endl; ob.push_back(outlineEdge((TQuadratic *)0, arrayDown[i])); i++; } } } //--------------------------------------------------------------------------- inline void changeQuadraticDirection(TQuadratic *q) { TPointD p = q->getP2(); q->setP2(q->getP0()); q->setP0(p); } //--------------------------------------------------------------------------- // cambia il verso del vettore di quadratiche (vedi changeDirection di tstroke.cpp) void changeDirection(std::vector<TQuadratic *> &array, bool onlyQuads = false) { UINT chunkCount = array.size(); UINT to = tfloor(chunkCount * 0.5); UINT i; if (chunkCount & 1) changeQuadraticDirection(array[to]); --chunkCount; for (i = 0; i < to; ++i) { changeQuadraticDirection(array[i]); changeQuadraticDirection(array[chunkCount - i]); if (!onlyQuads) std::swap(array[i], array[chunkCount - i]); } } //--------------------------------------------------------------------------- // estrae i punti necessari a costruire la semicirconferenza // iniziale e finale di una curva cicciona TQuadratic getCircleQuarter(const TThickQuadratic *tq, int versus) { TQuadratic out; TPointD v = versus ? -tq->getSpeed(0.0) : tq->getSpeed(1.0); if (norm2(v)) v = normalize(v); TPointD center = versus ? tq->getP0() : tq->getP2(); double radius = versus ? tq->getThickP0().thick : tq->getThickP2().thick; out.setP0(center + (versus ? rotate270(v) : rotate90(v)) * radius); out.setP1(center + v * radius); out.setP2(center + (versus ? rotate90(v) : rotate270(v)) * radius); return out; } //--------------------------------------------------------------------------- void drawQuadratic(const TQuadratic &quad, double pixelSize) { double m_min_step_at_normal_size = localComputeStep(quad, pixelSize); // It draws the curve as a linear piecewise approximation double invSqrtScale = 1.0; // First of all, it computes the control circles of the curve in screen coordinates TPointD scP0 = quad.getP0(); TPointD scP1 = quad.getP1(); TPointD scP2 = quad.getP2(); TPointD A = scP0 - 2 * scP1 + scP2; TPointD B = scP0 - scP1; double h; h = invSqrtScale * m_min_step_at_normal_size; double h2 = h * h; TPointD P = scP0, D2 = 2 * h2 * A, D1 = A * h2 - 2 * B * h; if (h < 0 || isAlmostZero(h)) return; assert(h > 0); // It draws the whole curve, using forward differencing glBegin(GL_LINE_STRIP); // The curve starts from scP0 glVertex2d(scP0.x, scP0.y); for (double t = h; t < 1; t = t + h) { P = P + D1; D1 = D1 + D2; glVertex2d(P.x, P.y); } glVertex2d(scP2.x, scP2.y); // The curve ends in scP2 glEnd(); } //--------------------------------------------------------------------------- } // end of unnamed namespace //----------------------------------------------------------------------------- void makeOutline(const TStroke *stroke, int startQuad, int endQuad, outlineBoundary &ob, double error2) { //std::ofstream cout("c:\\temp\\outline.txt"); assert(stroke); assert(startQuad >= 0); assert(endQuad < stroke->getChunkCount()); assert(startQuad <= endQuad); TThickQuadratic *tq; std::vector<TQuadratic *> arrayUp, arrayDown; TQuadratic arc; if (!stroke->getChunkCount()) return; //if (startQuad==0) { const TThickQuadratic *tq = stroke->getChunk(startQuad); // trova i punti sul cerchio che corrispondono // a due fette di 90 gradi. // Ritorna una quadratica invece di tre singoli punti solo per compattezza. TQuadratic arc = getCircleQuarter(tq, QUARTER_BEGIN); // estrae le quadratiche che corrispondono ad i due archi... splitCircularArcIntoQuadraticCurves(tq->getP0(), arc.getP0(), arc.getP1(), arrayUp); // e le ordina in modo che l'outline sia composta sempre da // una curva superiore ed una inferiore corrispondente changeDirection(arrayUp); splitCircularArcIntoQuadraticCurves(tq->getP0(), arc.getP1(), arc.getP2(), arrayDown); changeDirection(arrayDown, true); // copia le curve nell'outline; se gli array non hanno la stessa dimensione // quello con meno curve viene riempito con curve improprie // che hanno i punti di controllo coincidente con l'ultimo estremo valido //cout<<"quads del semicerchio left:"<<std::endl; copy(/*cout, */ arrayUp, arrayDown, ob); } for (int i = startQuad; i <= endQuad; ++i) { tq = (TThickQuadratic *)stroke->getChunk(i); TThickPoint p0 = tq->getThickP0(); TThickPoint p1 = tq->getThickP1(); TThickPoint p2 = tq->getThickP2(); if (p0.x == p1.x) { if (p1.x == p2.x && ((p1.y > p0.y && p1.y > p2.y) || (p1.y < p0.y && p1.y < p2.y))) tq = new TThickQuadratic(p0, 0.5 * (p0 + p1), p1); } else if (p0.y == p1.y) { if (p0.y == p2.y && ((p1.x > p0.x && p1.x > p2.x) || (p1.x < p0.x && p1.x < p2.x))) tq = new TThickQuadratic(p0, 0.5 * (p0 + p1), p1); } else { double fac1 = 1.0 / (p0.x - p1.x); double fac2 = 1.0 / (p0.y - p1.y); double aux1 = fac1 * (p2.x - p1.x); double aux2 = fac2 * (p2.y - p1.y); double aux3 = fac1 * (p0.x - p2.x); double aux4 = fac2 * (p0.y - p2.y); if ((areAlmostEqual(aux1, aux2) && aux1 >= 0) || (areAlmostEqual(aux3, aux4) && aux3 >= 0 && aux3 <= 1)) tq = new TThickQuadratic(p0, 0.5 * (p0 + p1), p1); } //cout<<"quad# "<<i<<":" <<*tq<<std::endl; makeOutline(/*cout, */ ob, *tq, error2); if (tq != stroke->getChunk(i)) delete tq; } arrayUp.clear(); arrayDown.clear(); // come sopra ultimo pezzo di arco // if (endQuad==stroke->getChunkCount()-1) { arc = getCircleQuarter(tq, QUARTER_END); splitCircularArcIntoQuadraticCurves(tq->getP2(), arc.getP1(), arc.getP0(), arrayUp); changeDirection(arrayUp); splitCircularArcIntoQuadraticCurves(tq->getP2(), arc.getP2(), arc.getP1(), arrayDown); changeDirection(arrayDown, true); //cout<<"quads del semicerchio right:"<<std::endl; copy(/*cout,*/ arrayUp, arrayDown, ob); } } //----------------------------------------------------------------------------- void drawOutline(const outlineBoundary &ob, double pixelSize) { for (UINT i = 0; i < ob.size(); ++i) { drawQuadratic(*ob[i].first, pixelSize); drawQuadratic(*ob[i].second, pixelSize); } } void computeOutlines(const TStroke *stroke, int startQuad, int endQuad, vector<TQuadratic *> &quadArray, double error2) { outlineBoundary ob; makeOutline(stroke, startQuad, endQuad, ob, error2); assert(quadArray.empty()); quadArray.resize(ob.size() * 2); int i, count = 0; for (i = 0; i < (int)ob.size(); i++) if (ob[i].first) quadArray[count++] = ob[i].first; for (i = (int)ob.size() - 1; i >= 0; i--) if (ob[i].second) quadArray[count++] = ob[i].second; quadArray.resize(count); for (i = 0; i < (int)quadArray.size(); i++) quadArray[i]->reverse(); std::reverse(quadArray.begin(), quadArray.end()); } //----------------------------------------------------------------------------- // End Of File //-----------------------------------------------------------------------------
[ "shimizu.toshihiro@gmail.com" ]
shimizu.toshihiro@gmail.com
03bc2737d90c5722353cece5fc5a1920e54e4ebe
c8a7fef50bdcc934dbdc9dbe2df8380cefd9af73
/filesetstream.cpp
b090d329a28514c13b7de3231049374b9c0627bc
[]
no_license
fezzle/jsonaggregator
1e16e9b49b7e1072c4bc66384df07e71f1d241fd
8a0ca0bb626c9dba2b120f9c99e1039d0b588f79
refs/heads/master
2021-04-18T21:48:08.746026
2019-01-12T18:19:42
2019-01-12T18:19:42
126,620,893
0
0
null
null
null
null
UTF-8
C++
false
false
157
cpp
// // filesetstream.cpp // BigData // // Created by Eric on 2016-08-06. // Copyright ยฉ 2016 eric. All rights reserved. // #include "filesetstream.hpp"
[ "ericjame@gmail.com" ]
ericjame@gmail.com
4885bc91d52d7641e471bfdc3c57c5a25975e65d
5ef52919d93c368c525bed4a91dc5c5ffb7e9a66
/prime1.cpp
d0f2c0036bd3e39f708e6f9c71b5cbc0f388ff4a
[]
no_license
brij1823/CodeChef-Easy
4591a47ed0962b73ad8a2b09734a0f294cc77178
0196b7f8ed5c911618ab37a54e1bba0bce60d9f2
refs/heads/master
2020-04-21T00:02:10.888252
2019-02-05T03:28:34
2019-02-05T03:28:34
169,183,996
0
0
null
null
null
null
UTF-8
C++
false
false
579
cpp
#include<iostream> using namespace std; int main() { int test; cin>>test; while(test--) { long long int starter,ending; cin>>starter>>ending; int flag=0; for(int i=starter;i<=ending;i++) { flag=0; for(int j=2;j*j<=i/2;j++) { if(i%j==0) { flag=1; break; } } if(flag==0) { cout<<i<<endl; } } } }
[ "noreply@github.com" ]
noreply@github.com
09aefee933ac78d248b7b883d012b2ca58537a41
266856b193194bdb192c499a40abe94dbcfe7796
/include/poisson_solver.hpp
497959319b4f5062b99a8717b380417deb76ac18
[]
no_license
MoPHA/sympife-vmax
6b964d9052515dc62eb4f226c1b9a888f493ed9d
36faf623207fb0b9a1b8c8f7eea7a3db85f66fb7
refs/heads/master
2023-04-03T07:35:27.697448
2021-04-12T08:41:09
2021-04-12T08:41:09
250,232,048
1
0
null
null
null
null
UTF-8
C++
false
false
1,348
hpp
#ifndef POISSON_SOLVER #define POISSON_SOLVER #include "field_functions.hpp" #include "pfem_extras.hpp" #include "mesh_extras.hpp" #ifdef MFEM_USE_MPI #include <string> #include <map> class PoissonSolver { public: PoissonSolver(ParametersInput & param, VMFields & fields, VMParticlesArray & particles); ~PoissonSolver(); HYPRE_Int GetProblemSize(); void PrintSizes(); void Assemble(); void Update(); void Solve(); void GetErrorEstimates(mfem::Vector & errors); const mfem::ParGridFunction & GetVectorPotential() { return *phi_; } private: ParametersInput * param_; VMFields * fields_; VMParticlesArray * particles_; mfem::Vector * dbcv_; // Corresponding Dirichlet Values mfem::ParBilinearForm * divEpsGrad_; // Laplacian operator mfem::ParLinearForm * rhod_; // Dual of Volumetric Charge Density Source mfem::common::ParDiscreteGradOperator * grad_; // For Computing E from phi mfem::common::ParDiscreteDivOperator * div_; // For Computing rho from D mfem::ParGridFunction * phi_; // Electric Scalar Potential mfem::ConstantCoefficient oneCoef_; // Coefficient equal to 1 std::vector<mfem::DeltaCoefficient*> point_charges_; mfem::Array<int> ess_bdr_tdofs_; // Essential Boundary Condition DoFs }; #endif // MFEM_USE_MPI #endif // POISSON_SOLVER
[ "chonel1@kastler.org.aalto.fi" ]
chonel1@kastler.org.aalto.fi
d7962262e3c74b43abf37b1d020ec6c9c3bb3b80
a61012876e646b2b3734af786be77ccf60d0a6aa
/้€’ๅฝ’/้˜ถไน˜.cpp
bc305a7a4b11dad36a0bbf916d5ee99f8fa0e6d3
[]
no_license
feelingshallow/Data-structure-and-algorithm
7992e05d3f4e67c9dfeaec1c7c128c83576e8705
f5c6edf63b74fefbda3e8824336a410157b6f323
refs/heads/master
2021-06-29T21:21:34.270659
2021-05-23T09:44:55
2021-05-23T09:44:55
229,541,956
1
0
null
null
null
null
UTF-8
C++
false
false
57
cpp
#include <stdio.h> int main(){ printf("hello "); }
[ "1375284880@qq.com" ]
1375284880@qq.com
3e961ea3e3356eeb66310355f649f967e5de987c
980e7663b9df8e6a05991b8ea81e2aceb640af6a
/ligra/unit_tests/undirected_edge_test.cc
983434598da8d254387977ae8c4f785eeee51b78
[ "MIT" ]
permissive
meng-sun/gbbs
7d049adbe3bd5196dea5bc2bcc5819110b3337a6
01c1e97ce814aa75894015d0dfc854a5fc5801af
refs/heads/master
2022-04-25T09:00:29.978128
2020-04-23T19:23:21
2020-04-23T19:23:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
280
cc
#include "ligra/undirected_edge.h" #include <gtest/gtest.h> TEST(UndirectedEdge, Equality) { EXPECT_EQ((UndirectedEdge{1, 2}), (UndirectedEdge{1, 2})); EXPECT_EQ((UndirectedEdge{1, 2}), (UndirectedEdge{2, 1})); EXPECT_NE((UndirectedEdge{1, 2}), (UndirectedEdge{3, 1})); }
[ "tom.hm.tseng@gmail.com" ]
tom.hm.tseng@gmail.com
b959318e660a793227c9d75baf2dbe598fa65d4f
4fa7ef129e2a66befa1da8fe84407e1d29c4db5d
/study/ch36/udpSender/widget.h
9e7fc335ced56db158cfa80ee023a67a0b9a7606
[]
no_license
ShelleyXiao/QtStudy
a5b578ce5e58f84f8abdb3fee831fd6c1850ec57
1e321be381565df19b60b6611b0753ef79252052
refs/heads/master
2020-03-30T01:09:31.841404
2018-10-25T15:06:22
2018-10-25T15:06:22
150,562,314
0
0
null
null
null
null
UTF-8
C++
false
false
373
h
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include <QtNetwork> namespace Ui { class Widget; } class Widget : public QWidget { Q_OBJECT public: explicit Widget(QWidget *parent = 0); ~Widget(); private slots: void on_pushButton_clicked(); private: Ui::Widget *ui; QUdpSocket *sender; }; #endif // WIDGET_H
[ "xiao244164200@qq.com" ]
xiao244164200@qq.com
103649623186c0d11d5e4e05a1f4b1a25e9f400f
1942a0d16bd48962e72aa21fad8d034fa9521a6c
/aws-cpp-sdk-ec2/include/aws/ec2/model/CreateInternetGatewayRequest.h
e6381727b59cbadb975688ed9cd957e9f310fb49
[ "Apache-2.0", "JSON", "MIT" ]
permissive
yecol/aws-sdk-cpp
1aff09a21cfe618e272c2c06d358cfa0fb07cecf
0b1ea31e593d23b5db49ee39d0a11e5b98ab991e
refs/heads/master
2021-01-20T02:53:53.557861
2018-02-11T11:14:58
2018-02-11T11:14:58
83,822,910
0
1
null
2017-03-03T17:17:00
2017-03-03T17:17:00
null
UTF-8
C++
false
false
2,459
h
๏ปฟ/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/ec2/EC2_EXPORTS.h> #include <aws/ec2/EC2Request.h> namespace Aws { namespace EC2 { namespace Model { /** * <p>Contains the parameters for CreateInternetGateway.</p><p><h3>See Also:</h3> * <a * href="http://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateInternetGatewayRequest">AWS * API Reference</a></p> */ class AWS_EC2_API CreateInternetGatewayRequest : public EC2Request { public: CreateInternetGatewayRequest(); Aws::String SerializePayload() const override; /** * <p>Checks whether you have the required permissions for the action, without * actually making the request, and provides an error response. If you have the * required permissions, the error response is <code>DryRunOperation</code>. * Otherwise, it is <code>UnauthorizedOperation</code>.</p> */ inline bool GetDryRun() const{ return m_dryRun; } /** * <p>Checks whether you have the required permissions for the action, without * actually making the request, and provides an error response. If you have the * required permissions, the error response is <code>DryRunOperation</code>. * Otherwise, it is <code>UnauthorizedOperation</code>.</p> */ inline void SetDryRun(bool value) { m_dryRunHasBeenSet = true; m_dryRun = value; } /** * <p>Checks whether you have the required permissions for the action, without * actually making the request, and provides an error response. If you have the * required permissions, the error response is <code>DryRunOperation</code>. * Otherwise, it is <code>UnauthorizedOperation</code>.</p> */ inline CreateInternetGatewayRequest& WithDryRun(bool value) { SetDryRun(value); return *this;} private: bool m_dryRun; bool m_dryRunHasBeenSet; }; } // namespace Model } // namespace EC2 } // namespace Aws
[ "henso@amazon.com" ]
henso@amazon.com
f5321ecb161aa9a15470dea42d07f36f26017461
8b31272b3b8d9c96a235de2cc47d4f69e534ee73
/os/objectscript/win/os/stdafx.cpp
f77509a120b71c1ff6be6e73f5c8a623876410d5
[ "Unlicense", "LicenseRef-scancode-public-domain", "MIT" ]
permissive
marynate/scriptorium
f8b1b2e39d96e377a74d8c34c641cdd48d2b0389
ea8a1770feb0da04f5a327d1f33fa2aec8ca34a0
refs/heads/master
2021-01-15T08:58:45.290656
2016-02-01T12:10:48
2016-02-01T19:21:40
59,019,154
1
0
null
2016-05-17T12:10:27
2016-05-17T12:10:27
null
WINDOWS-1251
C++
false
false
571
cpp
// stdafx.cpp: ะธัั…ะพะดะฝั‹ะน ั„ะฐะนะป, ัะพะดะตั€ะถะฐั‰ะธะน ั‚ะพะปัŒะบะพ ัั‚ะฐะฝะดะฐั€ั‚ะฝั‹ะต ะฒะบะปัŽั‡ะฐะตะผั‹ะต ะผะพะดัƒะปะธ // os-fcgi.pch ะฑัƒะดะตั‚ ะฟั€ะตะดะบะพะผะฟะธะปะธั€ะพะฒะฐะฝะฝั‹ะผ ะทะฐะณะพะปะพะฒะบะพะผ // stdafx.obj ะฑัƒะดะตั‚ ัะพะดะตั€ะถะฐั‚ัŒ ะฟั€ะตะดะฒะฐั€ะธั‚ะตะปัŒะฝะพ ะพั‚ะบะพะผะฟะธะปะธั€ะพะฒะฐะฝะฝั‹ะต ัะฒะตะดะตะฝะธั ะพ ั‚ะธะฟะต #include "stdafx.h" // TODO: ะฃัั‚ะฐะฝะพะฒะธั‚ะต ััั‹ะปะบะธ ะฝะฐ ะปัŽะฑั‹ะต ั‚ั€ะตะฑัƒัŽั‰ะธะตัั ะดะพะฟะพะปะฝะธั‚ะตะปัŒะฝั‹ะต ะทะฐะณะพะปะพะฒะบะธ ะฒ ั„ะฐะนะปะต STDAFX.H // , ะฐ ะฝะต ะฒ ะดะฐะฝะฝะพะผ ั„ะฐะนะปะต
[ "r-lyeh" ]
r-lyeh
2b6f26dc5d97bc64843efc40d9c0683a730904bd
7ce3d057a7761b574c2c3f39d4f9f69f8f73161d
/crc.cpp
ffdd54a3f2dae909d86d59f1e5223cccfc81b313
[ "MIT" ]
permissive
Mixxxxa/Huffman_CRC
1655310dd3945f9b39244da159ae097b94e9d86d
5b0dcba9263549b9a209ed40a0508b6a1da48db4
refs/heads/main
2023-05-15T06:16:52.586072
2021-06-10T19:00:08
2021-06-10T19:00:08
372,004,621
0
0
null
null
null
null
UTF-8
C++
false
false
3,480
cpp
// This is a personal academic project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com #include "crc.h" #include <QDebug> CRC::CRC() : m_polynom(0x65) { } CRC::CRC(const unsigned int polynom) : m_polynom(polynom) { } unsigned int CRC::calculate(const std::vector<bool> &data) const { // ะœะฐัะบะฐ ะดะปั ัƒะบะฐะทะฐะฝะธั ะฝะฐ ะฟั€ะพะฒะตั€ะพั‡ะฝั‹ะน ะฑะธั‚ const auto calcCheckBit = getCheckBitMask(); // ะ‘ะธั‚ะพะฒะฐั ะผะฐัะบะฐ ะดะปั ะพั‚ัะตั‡ะตะฝะธั ะปะธัˆะฝะธั… ะดะฐะฝะฝั‹ั… const auto mask = getMask(); // ะกั‚ะตะฟะตะฝัŒ ะฟะพะปะธะฝะพะผะฐ ะดะปั ะบะพั€ั€ะตะบั‚ะฝะพะณะพ ะดะตะฑะฐะณ-ะฒั‹ะฒะพะดะฐ const unsigned degree = polynomDegree(); unsigned int crc = 0; // ะ”ะปั ะบะฐะถะดะพะณะพ ะฑะธั‚ะฐ ะฒ ะดะฐะฝะฝั‹ั…... for(size_t i = 0; i < data.size(); ++i) { // ะŸะพะปัƒั‡ะฐะตะผ ะฝะพะฒั‹ะน ะผะปะฐะดัˆะธะน ะฑะธั‚ if(data[i]) crc |= 1; // ะ•ัะปะธ ะฝะฐะฑั€ะฐะปะพััŒ ะดะพัั‚ะฐั‚ะพั‡ะฝะพ ะฑะธั‚... if ((crc & calcCheckBit) != 0) { // ะ”ะตะปะธะผ ะธั… ะฝะฐ ะฟะพะปะธะฝะพะผ crc ^= m_polynom; qDebug().noquote() << Qt::bin << QString::number(crc, 2).rightJustified(degree+1, '0'); } // ะ•ัะปะธ ะฑะธั‚ ะฝะต ะฟะพัะปะตะดะฝะธะน, ั‚ะพ ัะดะฒะธะณะฐะตะผ CRC if(i != data.size() - 1) crc <<= 1; } qDebug().noquote() << Qt::bin << QString::number(crc, 2).rightJustified(degree+1, '0'); //ะžั‚ัะตะบะฐะตะผ ะปะธัˆะฝะธะต ะดะฐะฝะฝั‹ะต crc &= mask; return crc; } // ะ’ะพะทะฒั€ะฐั‰ะฐะตั‚ ะฑะธั‚ะพะฒัƒัŽ ะผะฐัะบัƒ ะดะปั ะพั‚ัะตั‡ะตะฝะธั ะปะธัˆะฝะธั… ะดะฐะฝะฝั‹ั… unsigned int CRC::getMask() const { unsigned int mask = 0; const int digits = polynomDegree(); for(int i = 0; i < digits + 1; ++i) mask |= (1 << i); return mask; } // ะ’ะพะทะฒั€ะฐั‰ะฐะตั‚ ะฟั€ะพะฒะตั€ะพั‡ะฝัƒัŽ ะผะฐัะบัƒ ะดะปั ั‚ะตะบัƒั‰ะตะณะพ ะฟะพะปะธะฝะพะผะฐ unsigned int CRC::getCheckBitMask() const { const int degree = polynomDegree(); return (1u << degree); } // ะ’ะพะทะฒั€ะฐั‰ะฐะตั‚ ัั‚ะตะฟะตะฝัŒ ะฟะพะปะธะฝะพะผะฐ unsigned CRC::polynomDegree() const { if (!m_polynom) return 0; // ะ˜ั‰ะตะผ ัั‚ะฐั€ัˆะธะน ะฑะธั‚ ะธ ะฒะพะทะฒั€ะฐั‰ะฐะตะผ ะตะณะพ ะฟะพะปะพะถะตะฝะธะต - 1 unsigned poly = m_polynom; unsigned ret = 1; while (poly >>= 1) ret += 1; return ret - 1; } unsigned int CRC::calculate(const uint8_t *data, size_t len) const { // ะŸะพะปัƒั‡ะฐะตะผ ัั‚ะตะฟะตะฝัŒ ะฟะพะปะธะฝะพะผะฐ const size_t degree = static_cast<size_t>(polynomDegree()); // ะšะพะฝะฒะตั€ั‚ะธั€ัƒะตะผ ะผะฐััะธะฒ ะฑะฐะนั‚ะพะฒ ะฒ ะผะฐััะธะฒ ะฑะธั‚ะพะฒ std::vector<bool> converted; // ะ ะตะทะตั€ะฒะธั€ัƒะตะผ ะผะตัั‚ะพ ะฟะพะด ั‚ั€ะตะฑัƒะตะผะพะต ะบะพะป-ะฒะพ ะฑะธั‚ + W-ะฝัƒะปะตะน converted.reserve(len * CHAR_BIT + degree); // ะŸะตั€ะตะฝะพัะธะผ ะดะฐะฝะฝั‹ะต ะธะท ะฑะฐะนั‚ for (size_t i = 0; i < len; i++) for(int j = CHAR_BIT - 1; j >= 0; --j) converted.push_back(data[i] & (1 << j)); // ะ”ะพะฟะพะปะฝะธั‚ัŒ ะดะฐะฝะฝั‹ะต ะฝัƒะปัะผะธ ะฒ ะบะพะฝั†ะต for(size_t i = 0; i < degree; ++i) converted.push_back(false); // ะกั‡ะธั‚ะฐะตะผ CRC ะดะปั ะผะฐััะธะฒะฐ ะฑะธั‚ะพะฒ return calculate(converted); } unsigned int CRC::polynom() const { return m_polynom; } void CRC::setPolynom(const unsigned int &polynom) { m_polynom = polynom; }
[ "gelvihmihail@gmail.com" ]
gelvihmihail@gmail.com
3de16c9d6161189909b293604e0ad35ea0da88e4
0e9dd80232653b1e06295048a8c9daf6b8d04d5d
/src/interrupt/APIC.cpp
79a877f60dfec35b3b976ac30a52e768d0be4615
[]
no_license
OutOfTheVoid/Kernel
86fa21c9ca99e0395d9a1595d817e478c45300f4
86cbbbe3bcdc1d7731652e33d5ed11ff4f978ca9
refs/heads/master
2023-03-30T06:25:23.054318
2023-03-24T19:20:31
2023-03-24T19:20:31
36,431,218
2
0
null
null
null
null
UTF-8
C++
false
false
10,670
cpp
#include <interrupt/APIC.h> #include <interrupt/IState.h> #include <interrupt/PIC.h> #include <hw/cpu/CPUID.h> #include <hw/cpu/MSR.h> #include <hw/cpu/TSC.h> #include <hw/cpu/IO.h> #include <hw/acpi/MADT.h> #include <system/func/Panic.h> #include <system/func/KPrintF.h> #include <mt/timing/PWaitMS.h> #include <mm/KVMap.h> #include <mm/paging/PageTable.h> #include <cpputil/Linkage.h> #include <cpputil/Unused.h> C_LINKAGE uint32_t interrupt_APIC_MMIOLocation; bool Interrupt::APIC :: Availible = true; uint32_t Interrupt::APIC :: Base = 0; volatile uint32_t * Interrupt::APIC :: BaseVirtual = NULL; double Interrupt::APIC :: BusFrequencey = 0.0; bool Interrupt::APIC :: Initialized = false; void Interrupt::APIC :: Init () { if ( ! HasAPIC () ) system_func_panic ( "System does not report an APIC!" ); // Remap PIC to unused interrupt numbers. Interrupt::PIC :: Remap ( 0x50, 0x58 ); for ( uint32_t i = 0; i < 15; i ++ ) Interrupt::PIC :: SetIRQEnabled ( i, false ); Interrupt::PIC :: Disable (); HW::CPU::IO :: Out8 ( kIMCR_SelectPort, kIMCR_SelectData ); HW::CPU::IO :: Out8 ( kIMCR_DataPort, kIMCR_DataData ); Base = GetAPICBaseAddress (); BaseVirtual = reinterpret_cast <uint32_t *> ( mm_kvmap ( reinterpret_cast <void *> ( Base ), 0x1000, MM::Paging::PageTable :: Flags_NoCache | MM::Paging::PageTable :: Flags_Writeable ) ); if ( BaseVirtual == NULL ) KPANIC ( "Failed to allocate virtual memory to map APIC!" ); SetLocalTimerVector ( false, 0xFF ); ClearErrorStatus (); ClearErrorStatus (); ClearErrorStatus (); ClearErrorStatus (); Enable (); uint64_t Tick = HW::CPU::TSC :: Read (); mt_timing_pwaitms ( 50.0 ); Tick = HW::CPU::TSC :: Read () - Tick; BusFrequencey = Tick * 20; Initialized = true; }; bool Interrupt::APIC :: IsInitialized () { return Initialized; }; double Interrupt::APIC :: GetBusFrequencey () { return BusFrequencey; }; void Interrupt::APIC :: APInit () { Enable (); SetTaskPriority ( 0 ); } void Interrupt::APIC :: ReadRegister ( uint32_t Offset, volatile uint32_t * DataOut, uint32_t DWordLength ) { if ( BaseVirtual == NULL ) KPANIC ( "Attempt to read APIC register without first mapping it into memory!" ); for ( uint32_t I = 0; I < DWordLength; I ++ ) DataOut [ I ] = BaseVirtual [ ( Offset >> 2 ) + I ]; }; void Interrupt::APIC :: WriteRegister ( uint32_t Offset, volatile uint32_t * DataIn, uint8_t DWordLength ) { if ( BaseVirtual == NULL ) KPANIC ( "Attempt to write APIC register without first mapping it into memory!" ); for ( uint32_t I = 0; I < DWordLength; I ++ ) BaseVirtual [ ( Offset >> 2 ) + I ] = DataIn [ I ]; }; uint32_t Interrupt::APIC :: GetAPICBaseAddress () { if ( HW::ACPI::MADT :: Valid () ) return HW::ACPI::MADT :: GetAPICBaseAddress (); uint32_t EAX; uint32_t EDX; HW::CPU::MSR :: GetMSR ( HW::CPU::MSR :: kMSR_APIC_BASE, & EAX, & EDX ); return EAX & 0xFFFFF000; }; void Interrupt::APIC :: Enable () { uint32_t SpuriousInterruptRegister = 0xFF | kSpuriousInterruptVectorFlag_APICEnable; WriteRegister ( kRegisterOffset_SpuriousInterruptVector, & SpuriousInterruptRegister, 1 ); }; void Interrupt::APIC :: Disable () { uint32_t SpuriousInterruptRegister = 0xFF; WriteRegister ( kRegisterOffset_SpuriousInterruptVector, & SpuriousInterruptRegister, 1 ); }; bool Interrupt::APIC :: IsLocalBSP () { uint32_t EAX; uint32_t EDX; HW::CPU::MSR :: GetMSR ( HW::CPU::MSR :: kMSR_APIC_BASE, & EAX, & EDX ); return ( EAX & 0x100 ); }; uint8_t Interrupt::APIC :: GetLocalID () { uint32_t IDRegister; ReadRegister ( kRegisterOffset_ID, & IDRegister, 1 ); return IDRegister >> 24; }; void Interrupt::APIC :: SetLocalID ( uint8_t ID ) { uint32_t IDRegister = static_cast <uint32_t> ( ID ) << 24; WriteRegister ( kRegisterOffset_ID, & IDRegister, 1 ); }; uint8_t Interrupt::APIC :: GetLocalVersion () { uint32_t VersionRegister; ReadRegister ( kRegisterOffset_Version, & VersionRegister, 1 ); return static_cast <uint8_t> ( VersionRegister ); }; uint8_t Interrupt::APIC :: GetLocalLVTCount () { uint32_t VersionRegister; ReadRegister ( kRegisterOffset_Version, & VersionRegister, 1 ); return static_cast <uint8_t> ( VersionRegister >> 16 ); }; void Interrupt::APIC :: SetLocalTimerVector ( bool InitiallyMasked, uint8_t Vector ) { uint32_t LVTEntry = static_cast <uint32_t> ( Vector ) | ( InitiallyMasked ? kLVTFlag_Mask : 0 ); if ( Vector < 16 ) system_func_panic ( "APIC Timer vector set to illegal interrupt vector %i!", Vector ); WriteRegister ( kRegisterOffset_LVTTimer, & LVTEntry, 1 ); }; void Interrupt::APIC :: SetLocalTimerDivide ( uint32_t Divide ) { uint32_t DivideRegister; ReadRegister ( kRegisterOffset_TimerDivideConfig, & DivideRegister, 1 ); DivideRegister &= ~ 0x0000000C; switch ( Divide ) { case kTimerDivision_1: DivideRegister |= 0x07; break; case kTimerDivision_2: DivideRegister |= 0x00; break; case kTimerDivision_4: DivideRegister |= 0x01; break; case kTimerDivision_8: DivideRegister |= 0x02; break; case kTimerDivision_16: DivideRegister |= 0x03; break; case kTimerDivision_32: DivideRegister |= 0x04; break; case kTimerDivision_64: DivideRegister |= 0x05; break; case kTimerDivision_128: DivideRegister |= 0x06; break; default: system_func_panic ( "Attempt to set invalid APIC Timer divison!" ); }; WriteRegister ( kRegisterOffset_TimerDivideConfig, & DivideRegister, 1 ); }; void Interrupt::APIC :: StartTimerOneShot ( uint32_t InitialValue ) { uint32_t LVTEntry; bool UnMask; ReadRegister ( kRegisterOffset_LVTTimer, & LVTEntry, 1 ); if ( ( LVTEntry & kLVTFlag_Mask ) == 0 ) UnMask = true; else UnMask = false; if ( LVTEntry & kLVTFlag_TimerModePeriodic ) { LVTEntry &= ~ kLVTFlag_TimerModePeriodic; WriteRegister ( kRegisterOffset_LVTTimer, & LVTEntry, 1 ); } WriteRegister ( kRegisterOffset_TimerInitialCount, & InitialValue, 1 ); if ( UnMask ) { LVTEntry &= ~ kLVTFlag_Mask; WriteRegister ( kRegisterOffset_LVTTimer, & LVTEntry, 1 ); } }; void Interrupt::APIC :: StartTimerPeriodic ( uint32_t SystemClockPeriod ) { uint32_t LVTEntry; ReadRegister ( kRegisterOffset_LVTTimer, & LVTEntry, 1 ); LVTEntry |= kLVTFlag_TimerModePeriodic; LVTEntry &= ~ kLVTFlag_Mask; WriteRegister ( kRegisterOffset_LVTTimer, & LVTEntry, 1 ); WriteRegister ( kRegisterOffset_TimerInitialCount, & SystemClockPeriod, 1 ); }; uint32_t Interrupt::APIC :: ReadTimer () { uint32_t TimerCountRegister; ReadRegister ( kRegisterOffset_TimerCurrentCount, & TimerCountRegister, 1 ); return TimerCountRegister; }; bool Interrupt::APIC :: PollTimerOneShot () { uint32_t TimerCountRegister; ReadRegister ( kRegisterOffset_TimerCurrentCount, & TimerCountRegister, 1 ); return ( TimerCountRegister == 0 ); }; void Interrupt::APIC :: SendPhysicalInitIPI ( uint8_t TargetID, bool Assert ) { uint32_t InterruptCommandHighRegister = ( static_cast <uint32_t> ( TargetID ) << 24 ); uint32_t InterruptCommandLowRegister = kIPIDestinationShorthand_None | ( Assert ? kIPILevel_Assert : 0 ) | kIPILevel_LTrig | kIPITriggerMode_Edge | kIPIDestinationMode_Physical | kIPIDeliveryMode_INIT; WriteRegister ( kRegisterOffset_InterruptCommand_Upper, & InterruptCommandHighRegister, 1 ); WriteRegister ( kRegisterOffset_InterruptCommand_Lower, & InterruptCommandLowRegister, 1 ); }; void Interrupt::APIC :: SendPhysicalStartupIPI ( uint8_t TargetID, uint32_t EntryPageNum ) { uint32_t InterruptCommandHighRegister = ( static_cast <uint32_t> ( TargetID ) << 24 ); uint32_t InterruptCommandLowRegister = kIPIDestinationShorthand_None | kIPITriggerMode_Edge | kIPILevel_Assert | kIPIDestinationMode_Physical | kIPIDeliveryMode_StartUp | ( EntryPageNum & 0xFF ); WriteRegister ( kRegisterOffset_InterruptCommand_Upper, & InterruptCommandHighRegister, 1 ); WriteRegister ( kRegisterOffset_InterruptCommand_Lower, & InterruptCommandLowRegister, 1 ); }; void Interrupt::APIC :: SendFixedIPI ( uint8_t TargetID, uint8_t Vector ) { uint32_t InterruptCommandHighRegister = ( static_cast <uint32_t> ( TargetID ) << 24 ); uint32_t InterruptCommandLowRegister = kIPIDestinationShorthand_None | kIPILevel_Assert | kIPITriggerMode_Edge | kIPIDestinationMode_Physical | kIPIDeliveryMode_Fixed | Vector; WriteRegister ( kRegisterOffset_InterruptCommand_Upper, & InterruptCommandHighRegister, 1 ); WriteRegister ( kRegisterOffset_InterruptCommand_Lower, & InterruptCommandLowRegister, 1 ); }; void Interrupt::APIC :: SendBroadFixedIPI ( uint8_t Vector ) { uint32_t InterruptCommandHighRegister = 0; uint32_t InterruptCommandLowRegister = kIPIDestinationShorthand_AllExcludingSelf | kIPILevel_Assert | kIPITriggerMode_Edge | kIPIDestinationMode_Physical | kIPIDeliveryMode_Fixed | Vector; WriteRegister ( kRegisterOffset_InterruptCommand_Upper, & InterruptCommandHighRegister, 1 ); WriteRegister ( kRegisterOffset_InterruptCommand_Lower, & InterruptCommandLowRegister, 1 ); }; void Interrupt::APIC :: SendBroadNMI () { uint32_t InterruptCommandHighRegister = 0; uint32_t InterruptCommandLowRegister = kIPIDestinationShorthand_AllExcludingSelf | kIPIDeliveryMode_NMI | kIPITriggerMode_Edge | kIPILevel_Assert; WriteRegister ( kRegisterOffset_InterruptCommand_Upper, & InterruptCommandHighRegister, 1 ); WriteRegister ( kRegisterOffset_InterruptCommand_Lower, & InterruptCommandLowRegister, 1 ); }; bool Interrupt::APIC :: IPIAccepted () { uint32_t InterruptCommandLowRegister; ReadRegister ( kRegisterOffset_InterruptCommand_Lower, & InterruptCommandLowRegister, 1 ); return ( InterruptCommandLowRegister & kIPIDeliverStatus_Pending ) != 0; }; void Interrupt::APIC :: ClearErrorStatus () { uint32_t NewStatus = 0; WriteRegister ( kRegisterOffset_ErrorStatus, & NewStatus, 1 ); WriteRegister ( kRegisterOffset_ErrorStatus, & NewStatus, 1 ); }; void Interrupt::APIC :: EndOfInterrupt () { uint32_t Zero = 0; WriteRegister ( kRegisterOffset_EOI, & Zero, 1 ); }; void Interrupt::APIC :: SetTaskPriority ( uint32_t Priority ) { WriteRegister ( kRegisterOffset_TaskPriority, & Priority, 1 ); }; bool Interrupt::APIC :: HasAPIC () { if ( Availible == false ) return false; if ( HW::ACPI::MADT :: Valid () ) return true; uint32_t CPUIDRegs [ 4 ]; HW::CPU::CPUID :: GetCPUID ( HW::CPU::CPUID :: kCode_Extensions, CPUIDRegs ); Availible = CPUIDRegs [ HW::CPU::CPUID :: kRegister_EDX ] & HW::CPU::CPUID :: kDFlag_Extensions_APIC; return Availible; };
[ "liam.tab@gmail.com" ]
liam.tab@gmail.com
9b6cbd5f1aefe515b8d1e7125f67abb03d0a7d9d
4b2da0b07ec5452fa914ce2b77411e039343be67
/src/utilstrencodings.cpp
dfbfdf0dfe89aa19a2f541cf7448b93cd1ff5d49
[ "MIT" ]
permissive
zoowcash/zoowcash
5cbc19f9edfbf6007d44ce2c06e757fc4c3ccf92
d38dccfc7672be33bec3f865a69675ff7eeaae94
refs/heads/master
2020-05-22T05:05:05.886886
2019-05-12T08:21:25
2019-05-12T08:21:25
186,229,183
0
0
null
null
null
null
UTF-8
C++
false
false
24,012
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2017 The Bitcoin Core developers // Copyright (c) 2019 The zoowcash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <utilstrencodings.h> #include <tinyformat.h> #include <cstdlib> #include <cstring> #include <errno.h> #include <limits> static const std::string CHARS_ALPHA_NUM = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; static const std::string SAFE_CHARS[] = { CHARS_ALPHA_NUM + " .,;-_/:?@()", // SAFE_CHARS_DEFAULT CHARS_ALPHA_NUM + " .,;-_?@", // SAFE_CHARS_UA_COMMENT CHARS_ALPHA_NUM + ".-_", // SAFE_CHARS_FILENAME }; std::string SanitizeString(const std::string& str, int rule) { std::string strResult; for (std::string::size_type i = 0; i < str.size(); i++) { if (SAFE_CHARS[rule].find(str[i]) != std::string::npos) strResult.push_back(str[i]); } return strResult; } const signed char p_util_hexdigit[256] = { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1, -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, }; signed char HexDigit(char c) { return p_util_hexdigit[(unsigned char)c]; } bool IsHex(const std::string& str) { for(std::string::const_iterator it(str.begin()); it != str.end(); ++it) { if (HexDigit(*it) < 0) return false; } return (str.size() > 0) && (str.size()%2 == 0); } bool IsHexNumber(const std::string& str) { size_t starting_location = 0; if (str.size() > 2 && *str.begin() == '0' && *(str.begin()+1) == 'x') { starting_location = 2; } for (auto c : str.substr(starting_location)) { if (HexDigit(c) < 0) return false; } // Return false for empty string or "0x". return (str.size() > starting_location); } std::vector<unsigned char> ParseHex(const char* psz) { // convert hex dump to vector std::vector<unsigned char> vch; while (true) { while (isspace(*psz)) psz++; signed char c = HexDigit(*psz++); if (c == (signed char)-1) break; unsigned char n = (c << 4); c = HexDigit(*psz++); if (c == (signed char)-1) break; n |= c; vch.push_back(n); } return vch; } std::vector<unsigned char> ParseHex(const std::string& str) { return ParseHex(str.c_str()); } void SplitHostPort(std::string in, int &portOut, std::string &hostOut) { size_t colon = in.find_last_of(':'); // if a : is found, and it either follows a [...], or no other : is in the string, treat it as port separator bool fHaveColon = colon != in.npos; bool fBracketed = fHaveColon && (in[0]=='[' && in[colon-1]==']'); // if there is a colon, and in[0]=='[', colon is not 0, so in[colon-1] is safe bool fMultiColon = fHaveColon && (in.find_last_of(':',colon-1) != in.npos); if (fHaveColon && (colon==0 || fBracketed || !fMultiColon)) { int32_t n; if (ParseInt32(in.substr(colon + 1), &n) && n > 0 && n < 0x10000) { in = in.substr(0, colon); portOut = n; } } if (in.size()>0 && in[0] == '[' && in[in.size()-1] == ']') hostOut = in.substr(1, in.size()-2); else hostOut = in; } std::string EncodeBase64(const unsigned char* pch, size_t len) { static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; std::string strRet = ""; strRet.reserve((len+2)/3*4); int mode=0, left=0; const unsigned char *pchEnd = pch+len; while (pch<pchEnd) { int enc = *(pch++); switch (mode) { case 0: // we have no bits strRet += pbase64[enc >> 2]; left = (enc & 3) << 4; mode = 1; break; case 1: // we have two bits strRet += pbase64[left | (enc >> 4)]; left = (enc & 15) << 2; mode = 2; break; case 2: // we have four bits strRet += pbase64[left | (enc >> 6)]; strRet += pbase64[enc & 63]; mode = 0; break; } } if (mode) { strRet += pbase64[left]; strRet += '='; if (mode == 1) strRet += '='; } return strRet; } std::string EncodeBase64(const std::string& str) { return EncodeBase64((const unsigned char*)str.c_str(), str.size()); } std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid) { static const int decode64_table[256] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; if (pfInvalid) *pfInvalid = false; std::vector<unsigned char> vchRet; vchRet.reserve(strlen(p)*3/4); int mode = 0; int left = 0; while (1) { int dec = decode64_table[(unsigned char)*p]; if (dec == -1) break; p++; switch (mode) { case 0: // we have no bits and get 6 left = dec; mode = 1; break; case 1: // we have 6 bits and keep 4 vchRet.push_back((left<<2) | (dec>>4)); left = dec & 15; mode = 2; break; case 2: // we have 4 bits and get 6, we keep 2 vchRet.push_back((left<<4) | (dec>>2)); left = dec & 3; mode = 3; break; case 3: // we have 2 bits and get 6 vchRet.push_back((left<<6) | dec); mode = 0; break; } } if (pfInvalid) switch (mode) { case 0: // 4n base64 characters processed: ok break; case 1: // 4n+1 base64 character processed: impossible *pfInvalid = true; break; case 2: // 4n+2 base64 characters processed: require '==' if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1) *pfInvalid = true; break; case 3: // 4n+3 base64 characters processed: require '=' if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1) *pfInvalid = true; break; } return vchRet; } std::string DecodeBase64(const std::string& str) { std::vector<unsigned char> vchRet = DecodeBase64(str.c_str()); return std::string((const char*)vchRet.data(), vchRet.size()); } std::string EncodeBase32(const unsigned char* pch, size_t len) { static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567"; std::string strRet=""; strRet.reserve((len+4)/5*8); int mode=0, left=0; const unsigned char *pchEnd = pch+len; while (pch<pchEnd) { int enc = *(pch++); switch (mode) { case 0: // we have no bits strRet += pbase32[enc >> 3]; left = (enc & 7) << 2; mode = 1; break; case 1: // we have three bits strRet += pbase32[left | (enc >> 6)]; strRet += pbase32[(enc >> 1) & 31]; left = (enc & 1) << 4; mode = 2; break; case 2: // we have one bit strRet += pbase32[left | (enc >> 4)]; left = (enc & 15) << 1; mode = 3; break; case 3: // we have four bits strRet += pbase32[left | (enc >> 7)]; strRet += pbase32[(enc >> 2) & 31]; left = (enc & 3) << 3; mode = 4; break; case 4: // we have two bits strRet += pbase32[left | (enc >> 5)]; strRet += pbase32[enc & 31]; mode = 0; } } static const int nPadding[5] = {0, 6, 4, 3, 1}; if (mode) { strRet += pbase32[left]; for (int n=0; n<nPadding[mode]; n++) strRet += '='; } return strRet; } std::string EncodeBase32(const std::string& str) { return EncodeBase32((const unsigned char*)str.c_str(), str.size()); } std::vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid) { static const int decode32_table[256] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; if (pfInvalid) *pfInvalid = false; std::vector<unsigned char> vchRet; vchRet.reserve((strlen(p))*5/8); int mode = 0; int left = 0; while (1) { int dec = decode32_table[(unsigned char)*p]; if (dec == -1) break; p++; switch (mode) { case 0: // we have no bits and get 5 left = dec; mode = 1; break; case 1: // we have 5 bits and keep 2 vchRet.push_back((left<<3) | (dec>>2)); left = dec & 3; mode = 2; break; case 2: // we have 2 bits and keep 7 left = left << 5 | dec; mode = 3; break; case 3: // we have 7 bits and keep 4 vchRet.push_back((left<<1) | (dec>>4)); left = dec & 15; mode = 4; break; case 4: // we have 4 bits, and keep 1 vchRet.push_back((left<<4) | (dec>>1)); left = dec & 1; mode = 5; break; case 5: // we have 1 bit, and keep 6 left = left << 5 | dec; mode = 6; break; case 6: // we have 6 bits, and keep 3 vchRet.push_back((left<<2) | (dec>>3)); left = dec & 7; mode = 7; break; case 7: // we have 3 bits, and keep 0 vchRet.push_back((left<<5) | dec); mode = 0; break; } } if (pfInvalid) switch (mode) { case 0: // 8n base32 characters processed: ok break; case 1: // 8n+1 base32 characters processed: impossible case 3: // +3 case 6: // +6 *pfInvalid = true; break; case 2: // 8n+2 base32 characters processed: require '======' if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1) *pfInvalid = true; break; case 4: // 8n+4 base32 characters processed: require '====' if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1) *pfInvalid = true; break; case 5: // 8n+5 base32 characters processed: require '===' if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1) *pfInvalid = true; break; case 7: // 8n+7 base32 characters processed: require '=' if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1) *pfInvalid = true; break; } return vchRet; } std::string DecodeBase32(const std::string& str) { std::vector<unsigned char> vchRet = DecodeBase32(str.c_str()); return std::string((const char*)vchRet.data(), vchRet.size()); } static bool ParsePrechecks(const std::string& str) { if (str.empty()) // No empty string allowed return false; if (str.size() >= 1 && (isspace(str[0]) || isspace(str[str.size()-1]))) // No padding allowed return false; if (str.size() != strlen(str.c_str())) // No embedded NUL characters allowed return false; return true; } bool ParseInt32(const std::string& str, int32_t *out) { if (!ParsePrechecks(str)) return false; char *endp = nullptr; errno = 0; // strtol will not set errno if valid long int n = strtol(str.c_str(), &endp, 10); if(out) *out = (int32_t)n; // Note that strtol returns a *long int*, so even if strtol doesn't report an over/underflow // we still have to check that the returned value is within the range of an *int32_t*. On 64-bit // platforms the size of these types may be different. return endp && *endp == 0 && !errno && n >= std::numeric_limits<int32_t>::min() && n <= std::numeric_limits<int32_t>::max(); } bool ParseInt64(const std::string& str, int64_t *out) { if (!ParsePrechecks(str)) return false; char *endp = nullptr; errno = 0; // strtoll will not set errno if valid long long int n = strtoll(str.c_str(), &endp, 10); if(out) *out = (int64_t)n; // Note that strtoll returns a *long long int*, so even if strtol doesn't report an over/underflow // we still have to check that the returned value is within the range of an *int64_t*. return endp && *endp == 0 && !errno && n >= std::numeric_limits<int64_t>::min() && n <= std::numeric_limits<int64_t>::max(); } bool ParseUInt32(const std::string& str, uint32_t *out) { if (!ParsePrechecks(str)) return false; if (str.size() >= 1 && str[0] == '-') // Reject negative values, unfortunately strtoul accepts these by default if they fit in the range return false; char *endp = nullptr; errno = 0; // strtoul will not set errno if valid unsigned long int n = strtoul(str.c_str(), &endp, 10); if(out) *out = (uint32_t)n; // Note that strtoul returns a *unsigned long int*, so even if it doesn't report an over/underflow // we still have to check that the returned value is within the range of an *uint32_t*. On 64-bit // platforms the size of these types may be different. return endp && *endp == 0 && !errno && n <= std::numeric_limits<uint32_t>::max(); } bool ParseUInt64(const std::string& str, uint64_t *out) { if (!ParsePrechecks(str)) return false; if (str.size() >= 1 && str[0] == '-') // Reject negative values, unfortunately strtoull accepts these by default if they fit in the range return false; char *endp = nullptr; errno = 0; // strtoull will not set errno if valid unsigned long long int n = strtoull(str.c_str(), &endp, 10); if(out) *out = (uint64_t)n; // Note that strtoull returns a *unsigned long long int*, so even if it doesn't report an over/underflow // we still have to check that the returned value is within the range of an *uint64_t*. return endp && *endp == 0 && !errno && n <= std::numeric_limits<uint64_t>::max(); } bool ParseDouble(const std::string& str, double *out) { if (!ParsePrechecks(str)) return false; if (str.size() >= 2 && str[0] == '0' && str[1] == 'x') // No hexadecimal floats allowed return false; std::istringstream text(str); text.imbue(std::locale::classic()); double result; text >> result; if(out) *out = result; return text.eof() && !text.fail(); } std::string FormatParagraph(const std::string& in, size_t width, size_t indent) { std::stringstream out; size_t ptr = 0; size_t indented = 0; while (ptr < in.size()) { size_t lineend = in.find_first_of('\n', ptr); if (lineend == std::string::npos) { lineend = in.size(); } const size_t linelen = lineend - ptr; const size_t rem_width = width - indented; if (linelen <= rem_width) { out << in.substr(ptr, linelen + 1); ptr = lineend + 1; indented = 0; } else { size_t finalspace = in.find_last_of(" \n", ptr + rem_width); if (finalspace == std::string::npos || finalspace < ptr) { // No place to break; just include the entire word and move on finalspace = in.find_first_of("\n ", ptr); if (finalspace == std::string::npos) { // End of the string, just add it and break out << in.substr(ptr); break; } } out << in.substr(ptr, finalspace - ptr) << "\n"; if (in[finalspace] == '\n') { indented = 0; } else if (indent) { out << std::string(indent, ' '); indented = indent; } ptr = finalspace + 1; } } return out.str(); } std::string i64tostr(int64_t n) { return strprintf("%d", n); } std::string itostr(int n) { return strprintf("%d", n); } int64_t atoi64(const char* psz) { #ifdef _MSC_VER return _atoi64(psz); #else return strtoll(psz, nullptr, 10); #endif } int64_t atoi64(const std::string& str) { #ifdef _MSC_VER return _atoi64(str.c_str()); #else return strtoll(str.c_str(), nullptr, 10); #endif } int atoi(const std::string& str) { return atoi(str.c_str()); } /** Upper bound for mantissa. * 10^18-1 is the largest arbitrary decimal that will fit in a signed 64-bit integer. * Larger integers cannot consist of arbitrary combinations of 0-9: * * 999999999999999999 1^18-1 * 9223372036854775807 (1<<63)-1 (max int64_t) * 9999999999999999999 1^19-1 (would overflow) */ static const int64_t UPPER_BOUND = 1000000000000000000LL - 1LL; /** Helper function for ParseFixedPoint */ static inline bool ProcessMantissaDigit(char ch, int64_t &mantissa, int &mantissa_tzeros) { if(ch == '0') ++mantissa_tzeros; else { for (int i=0; i<=mantissa_tzeros; ++i) { if (mantissa > (UPPER_BOUND / 10LL)) return false; /* overflow */ mantissa *= 10; } mantissa += ch - '0'; mantissa_tzeros = 0; } return true; } bool ParseFixedPoint(const std::string &val, int decimals, int64_t *amount_out) { int64_t mantissa = 0; int64_t exponent = 0; int mantissa_tzeros = 0; bool mantissa_sign = false; bool exponent_sign = false; int ptr = 0; int end = val.size(); int point_ofs = 0; if (ptr < end && val[ptr] == '-') { mantissa_sign = true; ++ptr; } if (ptr < end) { if (val[ptr] == '0') { /* pass single 0 */ ++ptr; } else if (val[ptr] >= '1' && val[ptr] <= '9') { while (ptr < end && val[ptr] >= '0' && val[ptr] <= '9') { if (!ProcessMantissaDigit(val[ptr], mantissa, mantissa_tzeros)) return false; /* overflow */ ++ptr; } } else return false; /* missing expected digit */ } else return false; /* empty string or loose '-' */ if (ptr < end && val[ptr] == '.') { ++ptr; if (ptr < end && val[ptr] >= '0' && val[ptr] <= '9') { while (ptr < end && val[ptr] >= '0' && val[ptr] <= '9') { if (!ProcessMantissaDigit(val[ptr], mantissa, mantissa_tzeros)) return false; /* overflow */ ++ptr; ++point_ofs; } } else return false; /* missing expected digit */ } if (ptr < end && (val[ptr] == 'e' || val[ptr] == 'E')) { ++ptr; if (ptr < end && val[ptr] == '+') ++ptr; else if (ptr < end && val[ptr] == '-') { exponent_sign = true; ++ptr; } if (ptr < end && val[ptr] >= '0' && val[ptr] <= '9') { while (ptr < end && val[ptr] >= '0' && val[ptr] <= '9') { if (exponent > (UPPER_BOUND / 10LL)) return false; /* overflow */ exponent = exponent * 10 + val[ptr] - '0'; ++ptr; } } else return false; /* missing expected digit */ } if (ptr != end) return false; /* trailing garbage */ /* finalize exponent */ if (exponent_sign) exponent = -exponent; exponent = exponent - point_ofs + mantissa_tzeros; /* finalize mantissa */ if (mantissa_sign) mantissa = -mantissa; /* convert to one 64-bit fixed-point value */ exponent += decimals; if (exponent < 0) return false; /* cannot represent values smaller than 10^-decimals */ if (exponent >= 18) return false; /* cannot represent values larger than or equal to 10^(18-decimals) */ for (int i=0; i < exponent; ++i) { if (mantissa > (UPPER_BOUND / 10LL) || mantissa < -(UPPER_BOUND / 10LL)) return false; /* overflow */ mantissa *= 10; } if (mantissa > UPPER_BOUND || mantissa < -UPPER_BOUND) return false; /* overflow */ if (amount_out) *amount_out = mantissa; return true; }
[ "47944643+zoowcoin@users.noreply.github.com" ]
47944643+zoowcoin@users.noreply.github.com
bd349dab4e1539f8342b9a335fae9cc5c268f537
56a55eefda48f88005bc29500b31de90e5699c3e
/Chapter12-OG/ch12_imageprocessing/ch12_imageprocessing.cpp
8428cab5d1507ff687b72348568c8e57c3a12a78
[]
no_license
ppetraki/OpenGL-Programming-Guide-8th-Edition-Code
437ec6cb29e08fe9c4c471dafc7ab2dc02f30118
c1cd2d2304484c41ab1f5f52c360801ef6383bdd
refs/heads/master
2020-07-09T09:56:13.224605
2019-08-28T20:06:15
2019-08-28T20:06:15
203,943,640
1
0
null
2019-08-23T07:06:33
2019-08-23T07:06:33
null
UTF-8
C++
false
false
5,383
cpp
/* $URL$ $Rev$ $Author$ $Date$ $Id$ */ // #define USE_GL3W #include <vermilion.h> #include "vapp.h" #include "vutils.h" #include "vbm.h" #include "vmath.h" #include <stdio.h> BEGIN_APP_DECLARATION(ImageProcessingComputeExample) // Override functions from base class virtual void Initialize(const char * title); virtual void Display(bool auto_redraw); virtual void Finalize(void); virtual void Reshape(int width, int height); // Member variables GLuint compute_prog; GLuint compute_shader; // Texture to process GLuint input_image; // Texture for compute shader to write into GLuint intermediate_image; GLuint output_image; // Program, vao and vbo to render a full screen quad GLuint render_prog; GLuint render_vao; GLuint render_vbo; END_APP_DECLARATION() DEFINE_APP(ImageProcessingComputeExample, "Compute Shader Image Processing Example") void ImageProcessingComputeExample::Initialize(const char * title) { base::Initialize(title); // Initialize our compute program compute_prog = glCreateProgram(); static const char compute_shader_source[] = "#version 430 core\n" "\n" "layout (local_size_x = 512) in;\n" "\n" "layout (rgba32f, binding = 0) uniform image2D input_image;\n" "layout (rgba32f, binding = 1) uniform image2D output_image;\n" "\n" "shared vec4 scanline[1024];\n" "\n" "void main(void)\n" "{\n" " ivec2 pos = ivec2(gl_GlobalInvocationID.xy);\n" " scanline[pos.x] = imageLoad(input_image, pos);\n" " barrier();\n" " imageStore(output_image, pos.yx, scanline[min(pos.x + 1, 1023)] - scanline[max(pos.x - 1, 0)]);\n" "}\n" ; vglAttachShaderSource(compute_prog, GL_COMPUTE_SHADER, compute_shader_source); glLinkProgram(compute_prog); // Load a texture to process input_image = vglLoadTexture("../../media/testImage.dds", 0, NULL); glGenTextures(1, &intermediate_image); glBindTexture(GL_TEXTURE_2D, intermediate_image); //glTexStorage2D(GL_TEXTURE_2D, 8, GL_RGBA32F, 512, 512); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, 512, 512, 0, GL_RGBA, GL_FLOAT, NULL); // This is the texture that the compute program will write into glGenTextures(1, &output_image); glBindTexture(GL_TEXTURE_2D, output_image); glTexStorage2D(GL_TEXTURE_2D, 8, GL_RGBA32F, 512, 512); // Now create a simple program to visualize the result render_prog = glCreateProgram(); static const char render_vs[] = "#version 430 core\n" "\n" "in vec4 vert;\n" "\n" "void main(void)\n" "{\n" " gl_Position = vert;\n" "}\n"; static const char render_fs[] = "#version 430 core\n" "\n" "layout (location = 0) out vec4 color;\n" "\n" "layout (binding = 0) uniform sampler2D output_image;\n" "\n" "void main(void)\n" "{\n" " color = abs(texture(output_image, vec2(1.0, -1.0) * vec2(gl_FragCoord.xy) / vec2(textureSize(output_image, 0)))) * 1.0;\n" "}\n"; vglAttachShaderSource(render_prog, GL_VERTEX_SHADER, render_vs); vglAttachShaderSource(render_prog, GL_FRAGMENT_SHADER, render_fs); glLinkProgram(render_prog); // This is the VAO containing the data to draw the quad (including its associated VBO) glGenVertexArrays(1, &render_vao); glBindVertexArray(render_vao); glEnableVertexAttribArray(0); glGenBuffers(1, &render_vbo); glBindBuffer(GL_ARRAY_BUFFER, render_vbo); static const float verts[] = { -1.0f, -1.0f, 0.5f, 1.0f, 1.0f, -1.0f, 0.5f, 1.0f, 1.0f, 1.0f, 0.5f, 1.0f, -1.0f, 1.0f, 0.5f, 1.0f, }; glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL); } void ImageProcessingComputeExample::Display(bool auto_redraw) { // Activate the compute program and bind the output texture image glUseProgram(compute_prog); glBindImageTexture(0, input_image, 0, GL_FALSE, 0, GL_READ_ONLY, GL_RGBA32F); glBindImageTexture(1, intermediate_image, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA32F); glDispatchCompute(1, 512, 1); glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT); glBindImageTexture(0, intermediate_image, 0, GL_FALSE, 0, GL_READ_ONLY, GL_RGBA32F); glBindImageTexture(1, output_image, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA32F); glDispatchCompute(1, 512, 1); // Now bind the texture for rendering _from_ glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, output_image); // Clear, select the rendering program and draw a full screen quad glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(render_prog); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); base::Display(); } void ImageProcessingComputeExample::Finalize(void) { glUseProgram(0); glDeleteProgram(compute_prog); glDeleteProgram(render_prog); glDeleteTextures(1, &output_image); glDeleteVertexArrays(1, &render_vao); } void ImageProcessingComputeExample::Reshape(int width, int height) { glViewport(0, 0, width, height); }
[ "wlk1229@sina.com" ]
wlk1229@sina.com
35cb11241c960d010a30d852a51231f79fed7157
39eac74fa6a244d15a01873623d05f480f45e079
/EMNConfidentialInfoDlg.h
47ea5889b478bd97131c26f143001f4cb43edfff
[]
no_license
15831944/Practice
a8ac8416b32df82395bb1a4b000b35a0326c0897
ae2cde9c8f2fb6ab63bd7d8cd58701bd3513ec94
refs/heads/master
2021-06-15T12:10:18.730367
2016-11-30T15:13:53
2016-11-30T15:13:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
817
h
#pragma once // CEMNConfidentialInfoDlg dialog // (d.thompson 2009-05-18) - PLID 29909 - Created #include "PatientsRc.h" class CEMNConfidentialInfoDlg : public CNxDialog { DECLARE_DYNAMIC(CEMNConfidentialInfoDlg) public: CEMNConfidentialInfoDlg(CWnd* pParent); // standard constructor virtual ~CEMNConfidentialInfoDlg(); //This is both input (load the dialog) and output (retrieve from the dialog) CString m_strConfidentialInfo; //Input: If set, the entire dialog is unchangeable. bool m_bReadOnly; // Dialog Data enum { IDD = IDD_EMN_CONFIDENTIAL_INFO_DLG }; protected: CNxIconButton m_btnOK; CNxIconButton m_btnCancel; CNxEdit m_nxeditInfo; virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support virtual BOOL OnInitDialog(); virtual void OnOK(); DECLARE_MESSAGE_MAP() };
[ "h.shah@WALD" ]
h.shah@WALD
f3b562b50ce1caff39e4a0b9a420adecfbc1dcea
55dd5a4506aba80a4dc0f4de99ebab7f9f9f5447
/Training/c++/Assignment/edit/Teacher.h
b657408d072dbb447a620bdfb5c2395d3063959c
[]
no_license
imjkdutta/Important_Training
8426b9c4ea0c4601cb9cae15e5e2bb1121adcbb4
f21cdde5ac35a1b186d01023b2659092bf8eb84b
refs/heads/master
2021-09-17T15:44:30.173030
2018-07-03T10:15:43
2018-07-03T10:15:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
425
h
#include"header.h" #ifndef TEACHER_H #define TEACHER_H class Teacher { private : char *first_name; char *last_name; int age; char *address; char *city; long int phone_no; public: Teacher(); Teacher(const char *first,const char *last, int a,const char *add, const char *ci,long int ph); ~Teacher(); void getdata(); void display(); void GradeStudent(); void SitInClass(); }; #endif
[ "dk.jiban@globaledgesoft.com" ]
dk.jiban@globaledgesoft.com
762620a4cead5a3f3044b87f8ee2df4e0940b328
8a4a69e5b39212b955eb52cc005311a440189c9b
/src/mame/includes/aliens.h
7497d0d35730e49f8b1ac81e02a871ebfd6ba1f9
[]
no_license
Ced2911/mame-lx
7d503b63eb5ae52f1e49763fc156dffa18517ec9
e58a80fefc46bdb879790c6bcfe882a9aff6f3ae
refs/heads/master
2021-01-01T17:37:22.723553
2012-02-04T10:05:52
2012-02-04T10:05:52
3,058,666
1
7
null
null
null
null
UTF-8
C++
false
false
1,078
h
/************************************************************************* Aliens *************************************************************************/ class aliens_state : public driver_device { public: aliens_state(const machine_config &mconfig, device_type type, const char *tag) : driver_device(mconfig, type, tag) { } /* memory pointers */ UINT8 * m_ram; // UINT8 * m_paletteram; // currently this uses generic palette handling /* video-related */ int m_layer_colorbase[3]; int m_sprite_colorbase; /* misc */ int m_palette_selected; /* devices */ device_t *m_maincpu; device_t *m_audiocpu; device_t *m_k007232; device_t *m_k052109; device_t *m_k051960; }; /*----------- defined in video/aliens.c -----------*/ extern void aliens_tile_callback(running_machine &machine, int layer,int bank,int *code,int *color, int *flags, int *priority); extern void aliens_sprite_callback(running_machine &machine, int *code,int *color,int *priority_mask,int *shadow); VIDEO_START( aliens ); SCREEN_UPDATE_IND16( aliens );
[ "cc2911@facebook.com" ]
cc2911@facebook.com
32fc097afcd8546462de1588dbf27f44b6ee81fe
9a3b9d80afd88e1fa9a24303877d6e130ce22702
/src/Providers/UNIXProviders/ReplacementFRU/UNIX_ReplacementFRUMain.cpp
cb25cc88cb59ead65c8974b06408661d8e439d63
[ "MIT" ]
permissive
brunolauze/openpegasus-providers
3244b76d075bc66a77e4ed135893437a66dd769f
f24c56acab2c4c210a8d165bb499cd1b3a12f222
refs/heads/master
2020-04-17T04:27:14.970917
2015-01-04T22:08:09
2015-01-04T22:08:09
19,707,296
0
0
null
null
null
null
UTF-8
C++
false
false
2,266
cpp
//%LICENSE//////////////////////////////////////////////////////////////// // // Licensed to The Open Group (TOG) under one or more contributor license // agreements. Refer to the OpenPegasusNOTICE.txt file distributed with // this work for additional information regarding copyright ownership. // Each contributor licenses this file to you under the OpenPegasus Open // Source License; you may not use this file except in compliance with the // License. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // ////////////////////////////////////////////////////////////////////////// // //%///////////////////////////////////////////////////////////////////////// #include <Pegasus/Common/Config.h> #include <Pegasus/Common/String.h> #include <Pegasus/Common/PegasusVersion.h> #include <UNIX_Common.h> PEGASUS_USING_PEGASUS; PEGASUS_USING_STD; using PROVIDER_LIB_NS::CIMHelper; #include <ReplacementFRU/UNIX_ReplacementFRUProvider.h> extern "C" PEGASUS_EXPORT CIMProvider* PegasusCreateProvider(const String& providerName) { if (String::equalNoCase(providerName, CIMHelper::EmptyString)) return NULL; else if (String::equalNoCase(providerName, "UNIX_ReplacementFRUProvider")) return new UNIX_ReplacementFRUProvider(); return NULL; }
[ "brunolauze@msn.com" ]
brunolauze@msn.com
b24a4618c08bd6197440ac3874e5341f408298ca
ef4410c9f3a33ac168c36fed8a4cb1a5d5c55495
/libnetdutils/include/netdutils/OperationLimiter.h
992a84985d7287a5fb26dbab7905e8581b1d21f7
[ "Apache-2.0" ]
permissive
BTLGxWeeabo/system_netd
0b6e2bbed4b95bd6a0671f0eaadd96c204e9ff1b
2587abb70d82e67c81d597d7af42c0bb22305fb4
refs/heads/queso
2022-04-20T20:27:30.245975
2020-04-23T01:27:16
2020-04-23T01:27:16
257,959,734
1
0
NOASSERTION
2020-04-23T01:27:17
2020-04-22T16:36:10
null
UTF-8
C++
false
false
3,224
h
/* * Copyright (C) 2018 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 NETUTILS_OPERATIONLIMITER_H #define NETUTILS_OPERATIONLIMITER_H #include <mutex> #include <unordered_map> #include <android-base/logging.h> #include <android-base/thread_annotations.h> namespace android { namespace netdutils { // Tracks the number of operations in progress on behalf of a particular key or // ID, rejecting further attempts to start new operations after a configurable // limit has been reached. // // The intended usage pattern is: // OperationLimiter<UserId> connections_per_user; // ... // // Before opening a new connection // if (!limiter.start(user)) { // return error; // } else { // // open the connection // // ...do some work... // // close the connection // limiter.finish(user); // } // // This class is thread-safe. template<typename KeyType> class OperationLimiter { public: explicit OperationLimiter(int limit) : mLimitPerKey(limit) {} ~OperationLimiter() { DCHECK(mCounters.empty()) << "Destroying OperationLimiter with active operations"; } // Returns false if |key| has reached the maximum number of concurrent // operations, otherwise increments the counter and returns true. // // Note: each successful start(key) must be matched by exactly one call to // finish(key). bool start(KeyType key) EXCLUDES(mMutex) { std::lock_guard lock(mMutex); auto& cnt = mCounters[key]; // operator[] creates new entries as needed. if (cnt >= mLimitPerKey) { // Oh, no! return false; } ++cnt; return true; } // Decrements the number of operations in progress accounted to |key|. // See usage notes on start(). void finish(KeyType key) EXCLUDES(mMutex) { std::lock_guard lock(mMutex); auto it = mCounters.find(key); if (it == mCounters.end()) { LOG(FATAL_WITHOUT_ABORT) << "Decremented non-existent counter for key=" << key; return; } auto& cnt = it->second; --cnt; if (cnt <= 0) { // Cleanup counters once they drop down to zero. mCounters.erase(it); } } private: // Protects access to the map below. std::mutex mMutex; // Tracks the number of outstanding queries by key. std::unordered_map<KeyType, int> mCounters GUARDED_BY(mMutex); // Maximum number of outstanding queries from a single key. const int mLimitPerKey; }; } // namespace netdutils } // namespace android #endif // NETUTILS_OPERATIONLIMITER_H
[ "codewiz@google.com" ]
codewiz@google.com
1255a2d2d095467535d1c49e50039a4407cf3218
81e143f110aeebe93759cfdb66adea0d212e6db1
/ChatClient_skeleton/RequestUpdate.cpp
321093f975bd13fa3f6a9fc98db22f3cda145ff8
[]
no_license
huwdp/Chat-Client-and-Server
64c05d7e6d588c2eed1296c0b96483bae2482c09
ccb60500681fddc06a9de72fad5fd7ffd486ae88
refs/heads/master
2021-01-10T10:09:48.526762
2015-10-02T00:23:24
2015-10-02T00:23:24
43,526,384
0
0
null
null
null
null
UTF-8
C++
false
false
1,779
cpp
/* * RequestUpdate.cpp * * Created on: 02-Feb-2010 * Author: sc-gj */ #include "RequestUpdate.h" RequestUpdate::RequestUpdate(int lastMessageNo) { this->lastMessageNo = lastMessageNo; type = UPDATE; } RequestUpdate::RequestUpdate() { type = UPDATE; this->lastMessageNo = 0; } RequestUpdate::~RequestUpdate() { } int RequestUpdate::encode(char** buffer) { //get size works out the size of //the encoded message using //xdr functions int bytes = getXDRSize(); int error =0; (*buffer)=(char*)malloc(bytes); //allocate some memory. //Create the stream xdrmem_create(&encodeStream, (*buffer), bytes, XDR_ENCODE ); if(!xdr_int(&encodeStream,&type)) return -1; if(!xdr_int(&encodeStream,&lastMessageNo)) return -1; //distroy the stream once decoding is complete xdr_destroy(&encodeStream); return bytes; } size_t RequestUpdate::getXDRSize(void) { size_t strLenght; //this will be used as a place holder for the strings lenght ulong lenght; //length calculated xdrproc_t proc; //pointer to the filter proc = (xdrproc_t)xdr_int; //set filter to xdr_int //use size of to work out size of encoded data //note must pass void* pointer to data lenght = xdr_sizeof(proc,(void*)&type) + xdr_sizeof(proc,(void*)&lastMessageNo); return lenght; } void RequestUpdate::decode(char* buffer, int bufferSize) { //Create the stream xdrmem_create(&decodeStream, buffer, bufferSize, XDR_DECODE ); //Use filters to enter the data if(xdr_int(&decodeStream,&type)) { if(xdr_int(&decodeStream,&lastMessageNo)); else { printf("Error decoding lastMessageNo\n"); } } else { printf("Error decoding type\n"); } xdr_destroy(&decodeStream); } int RequestUpdate::getLastMessageNo() { return lastMessageNo; }
[ "huw008@gmail.com" ]
huw008@gmail.com
fe5c158724e99b17506236e5232865f3651f9941
b6450bcc107521c0f5056475e383bcd3147a0a5e
/Linux/apitest/bayer.cpp
2d8e9cb89aa19414ef5df52da62f470d27c3d15c
[]
no_license
nickluo/camaro-sdk
d75b012469fbdd8eb0b4473fd1572fce123fd9a1
7362a3dbf5a54d659a15343e405cfb6d4fef6a36
refs/heads/master
2020-05-21T13:35:47.840366
2017-01-10T09:13:17
2017-01-10T09:13:17
45,231,885
1
3
null
null
null
null
UTF-8
C++
false
false
20,029
cpp
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <memory.h> #ifdef _WIN32 #include <omp.h> #endif //////////////////////////////////////////////////////// int PIX_HEIGHT = 0; int PIX_WIDTH = 0; #define R(x,y) rgb[0+ 3 * ((x) + PIX_WIDTH *(y))] #define G(x,y) rgb[1+ 3 * ((x) + PIX_WIDTH *(y))] #define B(x,y) rgb[2+ 3 * ((x) + PIX_WIDTH *(y))] #define GREY(x,y) grey[(x)+PIX_WIDTH*(y)] #if 0 //OV 4682 /* B IR B IR G R G R B IR B IR G R G R */ #define Bay(x,y) ((unsigned short)(raw_16[(x) + PIX_WIDTH *(y)] >> 2)) void bayer_copy(unsigned short * raw_16, unsigned char *rgb, int x, int y) { //G(x+1,y) = Bay(x+1,y) ; //G(x,y+1) = Bay(x,y+1); //G(x,y) = G(x+1,y+1) = (Bay(x+1,y) + Bay(x,y+1)) / 2; G(x,y) = G(x,y+1) = G(x+1,y) = G(x+1,y+1) = Bay(x,y+1); B(x,y)=B(x+1,y)=B(x,y+1)=B(x+1,y+1) = Bay(x,y); R(x,y)=R(x+1,y)=R(x,y+1)=R(x+1,y+1) = Bay(x+1,y+1); } void bayer_bilinear(unsigned short * raw_16, unsigned char *rgb,int x, int y) { R(x,y) = (Bay(x-1,y-1) + Bay(x+1, y+1) + Bay(x+1,y-1) + Bay(x-1,y+1)) / 4; //G(x,y) = (Bay(x-1,y) + Bay(x+1,y) + Bay(x,y-1) + Bay(x,y+1)) / 4; G(x,y) = ( Bay(x,y-1) + Bay(x,y+1)) / 2; B(x,y) = Bay(x,y); R(x+1,y) = (Bay(x+1,y-1) + Bay(x+1, y+1)) / 2; //G(x+1,y) = Bay(x+1,y); G(x+1,y) = (Bay(x,y-1) + Bay(x+2, y+1) + Bay(x+2,y-1) + Bay(x,y+1)) / 4; B(x+1,y) = (Bay(x,y) + Bay(x+2,y)) / 2 ; R(x,y+1) = (Bay(x-1,y+1) + Bay(x+1, y+1)) /2; G(x,y+1) = Bay(x,y+1); B(x,y+1) = (Bay(x,y) + Bay(x, y+2)) / 2; R(x+1,y+1) = Bay(x+1,y+1); //G(x+1,y+1) = (Bay(x+1,y) + Bay(x,y+1) + Bay(x+2,y+1) + Bay(x+1,y+2)) / 4; G(x+1,y+1) = (Bay(x,y+1) + Bay(x+2,y+1)) / 2; B(x+1,y+1) = (Bay(x,y) + Bay(x+2, y+2) + Bay(x+2,y) + Bay(x,y+2)) / 4; } #else //AR 0134 #define Bay(x,y) ((unsigned short)(raw_16[(x) + PIX_WIDTH *(y)] & 0x0FFF)) /* G R G R B G B G G R G R B G B G */ // for grey void grey_copy(unsigned short * raw_16, unsigned char *grey, int x, int y) { GREY(x,y) = (unsigned char)(Bay(x,y)>>4); } void bayer_copy(unsigned short * raw_16, unsigned char *rgb, int x, int y) { G(x,y) = (unsigned char)(Bay(x,y)>>4); G(x+1,y+1) = (unsigned char)(Bay(x+1,y+1)>>4); G(x+1,y) = G(x,y+1) = (G(x,y) + G(x+1,y+1))>>1; B(x,y)=B(x+1,y)=B(x,y+1)=B(x+1,y+1) = (unsigned char)(Bay(x,y+1)>>4); R(x,y)=R(x+1,y)=R(x,y+1)=R(x+1,y+1) = (unsigned char)(Bay(x+1,y)>>4); } void bayer_bilinear(unsigned short * raw_16, unsigned char *rgb,int x, int y) { B(x,y) = (Bay(x,y-1) + Bay(x, y+1)) >>5; G(x,y) = Bay(x,y)>>4; R(x,y) = (Bay(x-1,y) + Bay(x+1, y)) >>5; B(x+1,y) = (Bay(x,y-1) + Bay(x+2, y+1) + Bay(x+2,y-1) + Bay(x,y+1)) >>6; G(x+1,y) = (Bay(x,y) + Bay(x+2, y) + Bay(x+1,y-1) + Bay(x+1,y+1)) >>6; R(x+1,y) = Bay(x+1,y)>>4; B(x,y+1) = Bay(x,y+1)>>4; G(x,y+1) = (Bay(x,y) + Bay(x+1, y+1) + Bay(x-1,y+1) + Bay(x,y+2)) >>6; R(x,y+1) = (Bay(x-1,y) + Bay(x+1,y) + Bay(x-1,y+2) + Bay(x+1,y+2)) >>6; B(x+1,y+1) = (Bay(x,y+1) + Bay(x+2,y+1))>>5; G(x+1,y+1) = Bay(x+1,y+1)>>4; R(x+1,y+1) = (Bay(x+1,y) + Bay(x+1, y+2))>>5; } // the following bayer_xxx functions are for "CFA Demosaicing with "directional weighted gradient based interpolation"" // void bayer_copy_G(unsigned short * raw_16, unsigned char *rgb, int x, int y) { G(x,y) = (unsigned char)(Bay(x,y)>>4); } void bayer_copy_B(unsigned short * raw_16, unsigned char *rgb, int x, int y) { B(x,y) = (unsigned char)(Bay(x,y)>>4); } void bayer_copy_R(unsigned short * raw_16, unsigned char *rgb, int x, int y) { R(x,y) = (unsigned char)(Bay(x,y)>>4); } void bayer_inter_G_at_BR(unsigned short * raw_16, unsigned char *rgb,int x, int y) { float Wn, We, Ws, Ww, temp; int Gn, Ge, Gs, Gw; Wn = 1.0f / (1 + abs(Bay(x,y+1) - Bay(x,y-1)) + abs(Bay(x,y) - Bay(x,y-2))); We = 1.0f / (1 + abs(Bay(x-1,y) - Bay(x+1,y)) + abs(Bay(x,y) - Bay(x+2,y))); Ws = 1.0f / (1 + abs(Bay(x,y-1) - Bay(x,y+1)) + abs(Bay(x,y) - Bay(x,y+2))); Ww = 1.0f / (1 + abs(Bay(x+1,y) - Bay(x-1,y)) + abs(Bay(x,y) - Bay(x-2,y))); Gn = Bay(x,y-1) + (Bay(x,y) - Bay(x,y-2)) /2; Ge = Bay(x+1,y) + (Bay(x,y) - Bay(x+2,y)) /2; Gs = Bay(x,y+1) + (Bay(x,y) - Bay(x,y+2)) /2; Gw = Bay(x-1,y) + (Bay(x,y) - Bay(x-2,y)) /2; temp = (Wn * Gn + We * Ge + Ws * Gs + Ww * Gw) / (Wn + We + Ws + Ww); if (temp > 254.5f) G(x,y) = 255; else if (temp < 0.5f) G(x,y) = 0; else G(x,y) = (unsigned char)(temp + 0.5f); } void bayer_inter_B_at_R(unsigned short * raw_16, unsigned char *rgb,int x, int y) { float Wne, Wse, Wsw, Wnw, Bne, Bse, Bsw, Bnw, temp; Wne = 1.0f / (1 + abs(Bay(x-1,y+1) - Bay(x+1,y-1)) + abs(G(x,y) - G(x+1,y-1))); Wse = 1.0f / (1 + abs(Bay(x-1,y-1) - Bay(x+1,y+1)) + abs(G(x,y) - G(x+1,y+1))); Wsw = 1.0f / (1 + abs(Bay(x+1,y-1) - Bay(x-1,y+1)) + abs(G(x,y) - G(x-1,y+1))); Wnw = 1.0f / (1 + abs(Bay(x+1,y+1) - Bay(x-1,y-1)) + abs(G(x,y) - G(x-1,y-1))); Bne = Bay(x+1,y-1) + (G(x,y) - G(x+1,y-1)) *0.5f; Bse = Bay(x+1,y+1) + (G(x,y) - G(x+1,y+1)) *0.5f; Bsw = Bay(x-1,y+1) + (G(x,y) - G(x-1,y+1)) *0.5f; Bnw = Bay(x-1,y-1) + (G(x,y) - G(x-1,y-1)) *0.5f; temp = (Wne * Bne + Wse * Bse + Wsw * Bsw + Wnw * Bnw) / (Wne + Wse + Wsw + Wnw); if (temp > 254.5f) B(x,y) = 255; else if (temp < 0.5f) B(x,y) = 0; else B(x,y) = (unsigned char)(temp + 0.5f); } void bayer_inter_R_at_B(unsigned short * raw_16, unsigned char *rgb,int x, int y) { float Wne, Wse, Wsw, Wnw, Rne, Rse, Rsw, Rnw, temp; Wne = 1.0f / (1 + abs(Bay(x-1,y+1) - Bay(x+1,y-1)) + abs(G(x,y) - G(x+1,y-1))); Wse = 1.0f / (1 + abs(Bay(x-1,y-1) - Bay(x+1,y+1)) + abs(G(x,y) - G(x+1,y+1))); Wsw = 1.0f / (1 + abs(Bay(x+1,y-1) - Bay(x-1,y+1)) + abs(G(x,y) - G(x-1,y+1))); Wnw = 1.0f / (1 + abs(Bay(x+1,y+1) - Bay(x-1,y-1)) + abs(G(x,y) - G(x-1,y-1))); Rne = Bay(x+1,y-1) + (G(x,y) - G(x+1,y-1)) *0.5f; Rse = Bay(x+1,y+1) + (G(x,y) - G(x+1,y+1)) *0.5f; Rsw = Bay(x-1,y+1) + (G(x,y) - G(x-1,y+1)) *0.5f; Rnw = Bay(x-1,y-1) + (G(x,y) - G(x-1,y-1)) *0.5f; temp = (Wne * Rne + Wse * Rse + Wsw * Rsw + Wnw * Rnw) / (Wne + Wse + Wsw + Wnw); if (temp > 254.5f) R(x,y) = 255; else if (temp < 0.5f) R(x,y) = 0; else R(x,y) = (unsigned char)(temp + 0.5f); } void bayer_inter_B_at_G(unsigned short * raw_16, unsigned char *rgb,int x, int y) { float Wn, We, Ws, Ww, Bn, Be, Bs, Bw, temp; Wn = 1.0f / (1 + abs(B(x,y+1) - B(x,y-1)) + abs(G(x,y) - G(x,y-2))); We = 1.0f / (1 + abs(B(x-1,y) - B(x+1,y)) + abs(G(x,y) - G(x+2,y))); Ws = 1.0f / (1 + abs(B(x,y-1) - B(x,y+1)) + abs(G(x,y) - G(x,y+2))); Ww = 1.0f / (1 + abs(B(x+1,y) - B(x-1,y)) + abs(G(x,y) - G(x-2,y))); Bn = B(x,y-1) + (G(x,y) - G(x,y-2)) *0.5f; Be = B(x+1,y) + (G(x,y) - G(x+2,y)) *0.5f; Bs = B(x,y+1) + (G(x,y) - G(x,y+2)) *0.5f; Bw = B(x-1,y) + (G(x,y) - G(x-2,y)) *0.5f; temp = (Wn * Bn + We * Be + Ws * Bs + Ww * Bw) / (Wn + We + Ws + Ww); if (temp > 254.5f) B(x,y) = 255; else if (temp < 0.5f) B(x,y) = 0; else B(x,y) = (unsigned char)(temp + 0.5f); } void bayer_inter_R_at_G(unsigned short * raw_16, unsigned char *rgb,int x, int y) { float Wn, We, Ws, Ww, Rn, Re, Rs, Rw, temp; Wn = 1.0f / (1 + abs(R(x,y+1) - R(x,y-1)) + abs(G(x,y) - G(x,y-2))); We = 1.0f / (1 + abs(R(x-1,y) - R(x+1,y)) + abs(G(x,y) - G(x+2,y))); Ws = 1.0f / (1 + abs(R(x,y-1) - R(x,y+1)) + abs(G(x,y) - G(x,y+2))); Ww = 1.0f / (1 + abs(R(x+1,y) - R(x-1,y)) + abs(G(x,y) - G(x-2,y))); Rn = R(x,y-1) + (G(x,y) - G(x,y-2)) *0.5f; Re = R(x+1,y) + (G(x,y) - G(x+2,y)) *0.5f; Rs = R(x,y+1) + (G(x,y) - G(x,y+2)) *0.5f; Rw = R(x-1,y) + (G(x,y) - G(x-2,y)) *0.5f; temp = (Wn * Rn + We * Re + Ws * Rs + Ww * Rw) / (Wn + We + Ws + Ww); if (temp > 254.5f) R(x,y) = 255; else if (temp < 0.5f) R(x,y) = 0; else R(x,y) = (unsigned char)(temp + 0.5f); } #endif int convert_raw_to_grey_buffer(unsigned char *raw, unsigned char *grey, int w,int h) { PIX_WIDTH = w; PIX_HEIGHT = h; int i, j; for (j = 0; j < PIX_HEIGHT; j++) { for (i = 0; i < PIX_WIDTH; i++) { grey_copy((unsigned short *)raw,grey,i,j); } } return 0; } int convert_raw_to_rgb_buffer_with_lumi_calc(unsigned char *raw, unsigned char *rgb, int *lumi, int lumi_x, int lumi_y, int lumi_width, int lumi_height) { int i,j; int u, v; //unsigned short *raw_16 = (unsigned short *)raw; *lumi = 0; //int sum_lumi = 0; //#pragma omp parallel for shared(raw,rgb) private(i,j) auto x = (lumi_x % 2) ? (lumi_x + 1) : lumi_x; auto y = (lumi_y % 2) ? (lumi_y + 1) : lumi_y; auto width = (lumi_width % 2) ? (lumi_width - 1) : lumi_width; auto height = (lumi_height % 2) ? (lumi_height - 1) : lumi_height; for (j=0;j < PIX_HEIGHT; j+=2) { for (i=0;i < PIX_WIDTH; i+=2) { if (i==0||j==0||i== PIX_WIDTH -2|| j== PIX_HEIGHT-2) { bayer_copy(reinterpret_cast<unsigned short *>(raw),rgb, i,j); } else { bayer_bilinear(reinterpret_cast<unsigned short *>(raw),rgb, i,j); // bayer_copy((unsigned short *)raw,rgb, i,j); } if (i >= x && i < x + width && j >= y && j < y + height) { for (u = i; u <= i+1; u++) for (v = j; v <= j+1; v++) { *lumi += (R(u,v) * 299 + G(u,v) * 587 + B(u,v) * 114 + 500) / 1000 - 128; } } } } *lumi /= (width * height); *lumi += 128; return 0; } int convert_raw_to_rgb_buffer_with_histogram_calc(unsigned char *raw, unsigned char *rgb, unsigned int *histogram, int histogram_buckets, int w,int h) { PIX_WIDTH = w; PIX_HEIGHT = h; int i,j; int u, v; unsigned char lumi; unsigned int index; //unsigned short *raw_16 = (unsigned short *)raw; memset((void*)histogram, 0, histogram_buckets * sizeof(unsigned int)); //#pragma omp parallel for shared(raw,rgb) private(i,j, u, v) for (j=0;j < PIX_HEIGHT; j+=2) { for (i=0;i < PIX_WIDTH; i+=2) { if (i==0||j==0||i== PIX_WIDTH -2|| j== PIX_HEIGHT-2) { bayer_copy((unsigned short *)raw,rgb, i,j); } else { bayer_bilinear((unsigned short *)raw,rgb, i,j); // bayer_copy((unsigned short *)raw,rgb, i,j); } #if 1 // calculate histogram for (u = i; u <= i+1; u++) for (v = j; v <= j+1; v++) { lumi = (R(u,v) * 299 + G(u,v) * 587 + B(u,v) * 114 + 500) / 1000; index = lumi * histogram_buckets / 256; histogram[index]++; } #endif } } return 0; } int convert_raw_to_rgb_buffer(unsigned char *raw, unsigned char *rgb, bool isGradientBasedInter, int w, int h) { int i,j; PIX_WIDTH = w; PIX_HEIGHT = h; #if 1 if (!isGradientBasedInter) { #pragma omp parallel for shared(raw,rgb) private(i,j) for (j=0;j < PIX_HEIGHT; j+=2) { for (i=0;i < PIX_WIDTH; i+=2) { if (i==0||j==0||i== PIX_WIDTH -2|| j== PIX_HEIGHT-2) { bayer_copy((unsigned short *)raw,rgb, i,j); } else { bayer_bilinear((unsigned short *)raw,rgb, i,j); // bayer_copy((unsigned short *)raw,rgb, i,j); } } } } else { //0. fill the 4 sides first #pragma omp parallel for shared(raw,rgb) private(i,j) for (j=0;j < PIX_HEIGHT; j+=2) { for (i=0;i < PIX_WIDTH; i+=2) { if (i==0||j==0||i== PIX_WIDTH -2|| j== PIX_HEIGHT-2) { bayer_copy((unsigned short *)raw,rgb, i,j); } } } //1. fill G at G && interpolate G at B&R #pragma omp parallel for shared(raw,rgb) private(i,j) for (j = 2; j < PIX_HEIGHT-2; j++) { for (i = 2; i < PIX_WIDTH-2; i++) { if (((i + j) & 1) == 0) bayer_copy_G((unsigned short *)raw, rgb, i, j); else bayer_inter_G_at_BR((unsigned short *)raw, rgb, i, j); } } //2. interpolate B/R at R/B #pragma omp parallel for shared(raw,rgb) private(i,j) for (j = 2; j < PIX_HEIGHT-2; j++) { for (i = 2; i < PIX_WIDTH-2; i++) { if (i % 2 == 1 && j % 2 == 0) // at R { bayer_copy_R((unsigned short *)raw, rgb, i, j); bayer_inter_B_at_R((unsigned short *)raw, rgb, i, j); } else if (i % 2 == 0 && j % 2 == 1) // at B { bayer_copy_B((unsigned short *)raw, rgb, i, j); bayer_inter_R_at_B((unsigned short *)raw, rgb, i, j); } } } //3. interpolate B R at G #pragma omp parallel for shared(raw,rgb) private(i,j) for (j = 2; j < PIX_HEIGHT-2; j++) { for (i = 2; i < PIX_WIDTH-2; i++) { if ((i + j) % 2 == 0) //at G { bayer_inter_B_at_G((unsigned short *)raw, rgb, i, j); bayer_inter_R_at_G((unsigned short *)raw, rgb, i, j); } } } } #else //to show IR only unsigned short * raw_16 = (unsigned short *)raw; for (i=0;i < PIX_WIDTH; i+=2) { for (j=0;j < PIX_HEIGHT; j+=2) { unsigned char ir = Bay(i,j+1); unsigned char r = Bay(i+1,j+1); //unsigned char g = Bay(i+1,j+1); unsigned char b = Bay(i,j); R(i,j) = r; G(i,j) = ir; B(i,j) = b; R(i,j+1) = r; G(i,j+1) = ir; B(i,j+1) = b; R(i+1,j) = r; G(i+1,j) = ir; B(i+1,j) = b; R(i+1,j+1) = r; G(i+1,j+1) = ir; B(i+1,j+1) = b; } } #endif return 0; } // addition for lens focusing calibration // X_START, Y_START, WIDTH, HEIGHT: // specify the area for gradient calculation // fThreshold: // the threshold for excluding the little values // magnitude: // magnitude gradient value of the area //int convert_raw_to_rgb_buffer_with_gradient_calc(unsigned char *raw, unsigned char *rgb, bool isGradientBasedInter, int M_START_X, int M_START_Y, int M_WIDTH, int M_HEIGHT, float M_Threshold, float &magnitude) //{ // int i,j; // // unsigned short *raw_16 = (unsigned short *)raw; // float M[PIX_WIDTH][PIX_HEIGHT]; // // if (!isGradientBasedInter) // { // #pragma omp parallel for shared(raw,rgb) private(i,j) // for (j=0;j < PIX_HEIGHT; j+=2) // { // for (i=0;i < PIX_WIDTH; i+=2) // { // // if (i==0||j==0||i== PIX_WIDTH -2|| j== PIX_HEIGHT-2) // { // bayer_copy((unsigned short *)raw,rgb, i,j); // // } // else // { // bayer_bilinear((unsigned short *)raw,rgb, i,j); // // bayer_copy((unsigned short *)raw,rgb, i,j); // } // // if (i >=M_START_X && i < M_START_X + M_WIDTH && j >= M_START_Y && j < M_START_Y + M_HEIGHT) // { // int m, n, u, v; // for(m = 0; m <= 1; m++) // for (n = 0; n <= 1; n++) // { // u = i + m; v = j + n; // M[u-M_START_X][v-M_START_Y] = sqrt( (Bay(u+2,v) - Bay(u,v)) * (Bay(u+2,v)-Bay(u,v)) + (Bay(u,v+2) - Bay(u,v)) * (Bay(u,v+2)-Bay(u,v)) ); // } // } // // } // } // // magnitude = 0; // for (i = 0; i < M_WIDTH;i++) // for (j = 0; j < M_HEIGHT; j++) // { // if (M[i][j] > M_Threshold) // magnitude += M[i][j] / 1000; // } // } // else // { // //0. fill the 4 sides first // #pragma omp parallel for shared(raw,rgb) private(i,j) // for (j=0;j < PIX_HEIGHT; j+=2) // { // for (i=0;i < PIX_WIDTH; i+=2) // { // // if (i==0||j==0||i== PIX_WIDTH -2|| j== PIX_HEIGHT-2) // { // bayer_copy((unsigned short *)raw,rgb, i,j); // } // // if (i >=M_START_X && i < M_START_X + M_WIDTH && j >= M_START_Y && j < M_START_Y + M_HEIGHT) // { // int m, n, u, v; // for(m = 0; m <= 1; m++) // for (n = 0; n <= 1; n++) // { // u = i + m; v = j + n; // M[u-M_START_X][v-M_START_Y] = sqrt( (Bay(u+2,v) - Bay(u,v)) * (Bay(u+2,v)-Bay(u,v)) + (Bay(u,v+2) - Bay(u,v)) * (Bay(u,v+2)-Bay(u,v)) ); // } // } // // } // } // // magnitude = 0; // for (i = 0; i < M_WIDTH;i++) // for (j = 0; j < M_HEIGHT; j++) // { // if (M[i][j] > M_Threshold) // magnitude += M[i][j] / 1000; // } // // //1. fill G at G && interpolate G at B&R // #pragma omp parallel for shared(raw,rgb) private(i,j) // for (j = 2; j < PIX_HEIGHT-2; j++) // { // for (i = 2; i < PIX_WIDTH-2; i++) // { // if ((i + j) % 2 == 0) // bayer_copy_G((unsigned short *)raw, rgb, i, j); // else // bayer_inter_G_at_BR((unsigned short *)raw, rgb, i, j); // // } // } // // //2. interpolate B/R at R/B // #pragma omp parallel for shared(raw,rgb) private(i,j) // for (j = 2; j < PIX_HEIGHT-2; j++) // { // for (i = 2; i < PIX_WIDTH-2; i++) // { // if (i % 2 == 1 && j % 2 == 0) // at R // { // bayer_copy_R((unsigned short *)raw, rgb, i, j); // bayer_inter_B_at_R((unsigned short *)raw, rgb, i, j); // // } // else if (i % 2 == 0 && j % 2 == 1) // at B // { // bayer_copy_B((unsigned short *)raw, rgb, i, j); // bayer_inter_R_at_B((unsigned short *)raw, rgb, i, j); // } // } // } // // //3. interpolate B R at G // #pragma omp parallel for shared(raw,rgb) private(i,j) // for (j = 2; j < PIX_HEIGHT-2; j++) // { // for (i = 2; i < PIX_WIDTH-2; i++) // { // if ((i + j) % 2 == 0) //at G // { // bayer_inter_B_at_G((unsigned short *)raw, rgb, i, j); // bayer_inter_R_at_G((unsigned short *)raw, rgb, i, j); // } // } // } // } // // return 0; //}
[ "nickluo@gmail.com" ]
nickluo@gmail.com
7e3245878e2fe2535c66fa249619ec0e884cc6fd
503b89dd2280cb11fd7b5660e05db21c9aaa7569
/C++/Day13/Solution2.cpp
b2c1b3c652b6b7969e64a6cf9562ca290d4662ff
[]
no_license
tamycova/30DaysHR
50139390d79f24547b3bf43bfba7c41a2ea38696
4a1a9498382857501160e3e659361a4f35a824bb
refs/heads/master
2021-01-10T03:14:23.808221
2020-11-10T19:55:00
2020-11-10T19:55:00
49,034,458
54
81
null
2020-11-10T19:55:01
2016-01-05T01:39:48
C++
UTF-8
C++
false
false
958
cpp
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <string> using namespace std; class Book{ protected: string title; string author; public: Book(string t,string a){ title=t; author=a; } virtual void display()=0; }; //Write MyBook class class MyBook : public Book { private: int price; public: MyBook (string _title, string _author, int _price) : Book(_title,_author), price(_price) {} void display() { cout << "Title: " << title; cout << "\nAuthor: " << author; cout << "\nPrice: " << price << endl; } }; // end writing of MyBook class int main() { string title,author; int price; getline(cin,title); getline(cin,author); cin>>price; MyBook novel(title,author,price); novel.display(); return 0; }
[ "c650@users.noreply.github.com" ]
c650@users.noreply.github.com
59690b844baf2907cfe678d2fb82a710a4e93b0f
f6da620d475d3d097e5275129948823a2df7896f
/5.8(3)/main.cpp
b48decd355504fd76f290677ec924c89c4c6c3b3
[]
no_license
zwfree/C-code
0aebe9223336a5512f66169ece76397b2ad1190d
20dbcdcecb124090088d2f44215594e956193ec4
refs/heads/master
2020-12-02T13:19:52.738734
2016-08-31T12:07:52
2016-08-31T12:07:52
67,033,753
0
0
null
null
null
null
UTF-8
C++
false
false
183
cpp
#include <iostream> using namespace std; int main() { int sum=0; for(int i=1;i<=20;++i) { sum+=i*i; } cout << sum << endl; return 0; }
[ "m15908173435@hotmail.com" ]
m15908173435@hotmail.com
59e6ad8d97d6c0409843d8e4a665b4bb8f655fa1
df5f8f45d9a65453ac52a1feacb9bba7add261b2
/indeed2016/matrix.cpp
cad226510094682d7bd8c0cb7c39a17508f4523b
[]
no_license
honeyaya/interview
8301a7a8624a2cdab32372703cd1129d27d62a77
76bc79214d86d4e7ad878cc4c4adfb88eb9a3e2b
refs/heads/master
2021-06-22T05:40:57.904728
2017-08-16T16:21:28
2017-08-16T16:21:28
84,830,703
0
0
null
null
null
null
UTF-8
C++
false
false
771
cpp
#include <iostream> using namespace std; #define maxn 100 int m1[maxn][maxn]; int m2[maxn][maxn]; int ans[maxn][maxn]; int main(){ int n,m,k; while(cin >> n >> m >> k){ for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ cin >> m1[i][j] ; } } for(int i = 0; i < m; i++){ for(int j = 0; j < k; j++){ cin >> m2[i][j] ; } } for(int index1 = 0; index1 < n; index1++){ for(int index2 = 0; index2 < k; index2++){ int sum = 0; for(int index3 = 0; index3 < m; index3++){ sum += m1[index1][index3] * m2[index3][index2]; } ans[index1][index2] = sum; } } for(int i = 0; i < n; i++){ for(int j = 0; j < k; j++){ cout << ans[i][j] << " "; } cout << endl; } } return 0; }
[ "1194866931@qq.com" ]
1194866931@qq.com
6e7aedf94aea09120326bd3446f1f25cb7e15b50
fd5178b83eb0cfc7ce205220c3d80b2d25bec656
/headers/FGAmbientSoundSpline.h
b67d1259b1288c2af62cdd6a6cab6ad977354194
[]
no_license
ficsit/community-resources
e2d916ed3709562318369c81f7e70645ce005326
974089a84046b524ed5e2d19de4c09e8230ac7bf
refs/heads/master
2021-01-04T15:50:29.879718
2020-03-11T17:02:14
2020-03-11T17:02:14
240,621,430
0
0
null
null
null
null
UTF-8
C++
false
false
1,318
h
// Copyright 2016-2018 Coffee Stain Studios. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "FGSignificanceInterface.h" #include "FGAmbientSoundSpline.generated.h" UCLASS() class FACTORYGAME_API AFGAmbientSoundSpline : public AActor, public IFGSignificanceInterface { GENERATED_BODY() public: AFGAmbientSoundSpline(); protected: virtual void BeginPlay() override; virtual void EndPlay( const EEndPlayReason::Type endPlayReason ) override; public: //IFGSignificanceInterface virtual void GainedSignificance_Implementation() override; virtual void LostSignificance_Implementation() override; virtual float GetSignificanceRange() override; //End public: /** Gets the spline component */ UFUNCTION() FORCEINLINE class USplineComponent* GetSplineComponent(){ return mSpline; } protected: /** Spline to put multiple positions along. */ UPROPERTY( EditAnywhere, Category = "Ambient Sound Spline" ) class USplineComponent* mSpline; /** AkComponent that plays the sound on the spline. */ UPROPERTY( EditAnywhere, Category = "Ambient Sound Spline" ) class UFGSoundSplineComponent* mSoundSpline; /** Range that this volume should be significant within */ UPROPERTY( EditInstanceOnly, Category = "Significance" ) float mSignificanceRange; };
[ "ian@nevir.net" ]
ian@nevir.net
b724eb3de4318c43479df7789770a5590dbb61ec
a48b9bda3c9af73257873192a98d2d3db12d096d
/TMC2_7.0_Plenoptic_Point_Cloud_Source/lib/PccLibCommon/include/PCCCodec.h
93612880508943e93ce232ce2ef0c81cd562cd88
[]
no_license
xiaoliqiu/Plenopic_point_cloud_compression
7899eaad7a6e2fd5872bf087a63d446fbd16c435
89f148787e0813ea7ad08f0648b716ac6deb3384
refs/heads/main
2023-01-22T16:50:16.799372
2020-11-27T13:33:26
2020-11-27T13:33:26
316,504,258
0
0
null
null
null
null
UTF-8
C++
false
false
19,048
h
/* The copyright in this software is being made available under the BSD * License, included below. This software may be subject to other third party * and contributor rights, including patent rights, and no such rights are * granted under this license. * * Copyright (c) 2010-2017, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the ISO/IEC nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef PCCCodec_h #define PCCCodec_h #include "../../../../dependencies/tbb/include/tbb/compat/condition_variable" #include "PCCCommon.h" #include "PCCImage.h" #include "PCCMath.h" #include "PCCVideo.h" #include "PCCContext.h" namespace pcc { class PCCPatch; } /* namespace pcc */ namespace pcc { class PCCContext; class PCCFrameContext; class PCCGroupOfFrames; class PCCPointSet3; template <typename T, size_t N> class PCCVideo; typedef pcc::PCCVideo<uint8_t, 3> PCCVideoTexture; typedef pcc::PCCVideo<uint16_t, 3> PCCVideoGeometry; template <typename T, size_t N> class PCCImage; typedef pcc::PCCImage<uint16_t, 3> PCCImageGeometry; typedef pcc::PCCImage<uint8_t, 3> PCCImageOccupancyMap; struct GeneratePointCloudParameters { size_t occupancyResolution_; size_t occupancyPrecision_; bool gridSmoothing_; size_t gridSize_; size_t neighborCountSmoothing_; double radius2Smoothing_; double radius2BoundaryDetection_; double thresholdSmoothing_; size_t pcmPointColorFormat_; size_t nbThread_; bool absoluteD1_; size_t surfaceThickness_; double thresholdColorSmoothing_; bool gridColorSmoothing_; size_t cgridSize_; double thresholdColorDifference_; double thresholdColorVariation_; double thresholdLocalEntropy_; double radius2ColorSmoothing_; size_t neighborCountColorSmoothing_; bool flagGeometrySmoothing_; bool flagColorSmoothing_; bool enhancedDeltaDepthCode_; size_t EOMFixBitCount_; bool EOMTexturePatch_; size_t thresholdLossyOM_; bool removeDuplicatePoints_; size_t layerCountMinus1_; bool pointLocalReconstruction_; bool singleLayerPixelInterleaving_; std::string path_; bool useAdditionalPointsPatch_; size_t plrlNumberOfModes_; size_t geometryBitDepth3D_; size_t geometry3dCoordinatesBitdepth_; }; #ifdef CODEC_TRACE #define TRACE_CODEC( fmt, ... ) trace( fmt, ##__VA_ARGS__ ); #else #define TRACE_CODEC( fmt, ... ) ; #endif class PCCCodec { public: PCCCodec(); ~PCCCodec(); void generatePointCloud( PCCGroupOfFrames& reconstructs, PCCContext& context, const GeneratePointCloudParameters params ); bool colorPointCloud( PCCGroupOfFrames& reconstructs, PCCContext& context, #if MULTIPLE_ATTRIBUTES int viewIndex, #endif const uint8_t attributeCount, const PCCColorTransform colorTransform, const GeneratePointCloudParameters params ); void generateMPsGeometryfromImage( PCCContext& context, PCCFrameContext& frame, PCCGroupOfFrames& reconstructs, size_t frameIndex ); void generateMPsTexturefromImage( PCCContext& context, PCCFrameContext& frame, PCCGroupOfFrames& reconstructs, size_t frameIndex ); void generateMissedPointsGeometryfromVideo( PCCContext& context, PCCGroupOfFrames& reconstructs ); void generateMissedPointsTexturefromVideo( PCCContext& context, PCCGroupOfFrames& reconstructs ); void generateOccupancyMap( PCCContext& context, const size_t occupancyPrecision, const size_t thresholdLossyOM, bool enhancedOccupancyMapForDepthFlag ); #ifdef CODEC_TRACE template <typename... Args> void trace( const char* pFormat, Args... eArgs ) { if ( trace_ ) { FILE* output = traceFile_ ? traceFile_ : stdout; fprintf( output, pFormat, eArgs... ); fflush( output ); } } template <typename T> void traceVector( std::vector<T> data, const size_t width, const size_t height, const std::string string, const bool hexa = false ) { if ( trace_ ) { if ( data.size() == 0 ) { data.resize( width * height, 0 ); } trace( "%s: %lu %lu \n", string.c_str(), width, height ); for ( size_t v0 = 0; v0 < height; ++v0 ) { for ( size_t u0 = 0; u0 < width; ++u0 ) { if ( hexa ) { trace( "%2x", (int)( data[v0 * width + u0] ) ); } else { trace( "%3d", (int)( data[v0 * width + u0] ) ); } } trace( "\n" ); } } } void setTrace( bool trace ) { trace_ = trace; } bool getTrace() { return trace_; } bool openTrace( std::string file ) { if ( traceFile_ ) { fclose( traceFile_ ); traceFile_ = NULL; } if ( ( traceFile_ = fopen( file.c_str(), "w" ) ) == NULL ) { return false; } return true; } void closeTrace() { if ( traceFile_ ) { fclose( traceFile_ ); traceFile_ = NULL; } } #endif protected: void generateOccupancyMap( PCCFrameContext& frame, const PCCImageOccupancyMap& videoFrame, const size_t occupancyPrecision, const size_t thresholdLossyOM, const bool enhancedOccupancyMapForDepthFlag ); void generateBlockToPatchFromOccupancyMap( PCCContext& context, const size_t occupancyResolution ); void generateBlockToPatchFromOccupancyMap( PCCContext& context, PCCFrameContext& frame, size_t frameIndex, const size_t occupancyResolution ); void generateBlockToPatchFromBoundaryBox( PCCContext& context, const size_t occupancyResolution ); void generateBlockToPatchFromBoundaryBox( PCCContext& context, PCCFrameContext& frame, size_t frameIndex, const size_t occupancyResolution ); void generateBlockToPatchFromOccupancyMapVideo( PCCContext & context, const bool losslessGeo, const bool lossyMissedPointsPatch, const size_t testLevelOfDetail, const size_t occupancyResolution, const size_t occupancyPrecision); void generateBlockToPatchFromOccupancyMapVideo( PCCContext & context, PCCFrameContext & frame, PCCImageOccupancyMap & occupancyMapImage, size_t frameIndex, const size_t occupancyResolution, const size_t occupancyPrecision); int getDeltaNeighbors( const PCCImageGeometry& frame, const PCCPatch& patch, const int xOrg, const int yOrg, const int neighboring, const int threshold, const bool projectionMode, const double lodScale ); std::vector<PCCPoint3D> generatePoints( const GeneratePointCloudParameters& params, PCCFrameContext& frame, const PCCVideoGeometry& video, const PCCVideoGeometry& videoD1, const size_t shift, const size_t patchIndex, const size_t u, const size_t v, const size_t x, const size_t y, const bool interpolate, const bool filling, const size_t minD1, const size_t neighbor, const double lodScale ); inline double entropy( std::vector<uint8_t>& Data, int N ) { std::vector<size_t> count; count.resize( 256, 0 ); for ( size_t i = 0; i < N; ++i ) { ++count[size_t( Data[i] )]; } double s = 0; for ( size_t i = 0; i < 256; ++i ) { if ( count[i] ) { double p = double( count[i] ) / double( N ); s += -p * std::log2( p ); } } return s; } inline double median( std::vector<uint8_t>& Data, int N ) { float med = 0; int a = 0; int b = 0; float newMed = 0; if ( N % 2 == 0 ) a = N / 2; b = ( N / 2 ) - 1; med = int( Data.at( a ) ) + Data.at( b ); newMed = ( med / 2 ); return double( newMed ); } inline double mean( std::vector<uint8_t>& Data, int N ) { double s = 0.0; for ( size_t i = 0; i < N; ++i ) { s += double( Data[i] ); } return s / double( N ); } private: void generatePointCloud( PCCPointSet3& reconstruct, PCCContext& context, PCCFrameContext& frame, const PCCVideoGeometry& video, const PCCVideoGeometry& videoD1, const PCCVideoOccupancyMap& videoOM, const GeneratePointCloudParameters params, std::vector<uint32_t>& partition ); void smoothPointCloud( PCCPointSet3& reconstruct, const std::vector<uint32_t>& partition, const GeneratePointCloudParameters params ); void createSubReconstruct( const PCCPointSet3& reconstruct, const std::vector<uint32_t>& partition, PCCFrameContext& frame, const GeneratePointCloudParameters& params, const size_t frameCount, PCCPointSet3& subReconstruct, std::vector<uint32_t>& subPartition, std::vector<size_t>& subReconstructIndex ); void createSpecificLayerReconstruct( const PCCPointSet3& reconstruct, const std::vector<uint32_t>& partition, PCCFrameContext& frame, const GeneratePointCloudParameters& params, const size_t frameCount, PCCPointSet3& subReconstruct, std::vector<uint32_t>& subPartition, std::vector<size_t>& subReconstructIndex ); void updateReconstruct( PCCPointSet3& reconstruct, const PCCPointSet3& subReconstruct, const std::vector<size_t>& subReconstructIndex ); bool colorPointCloud( PCCPointSet3& reconstruct, PCCFrameContext& frame, const PCCVideoTexture& video, #if MULTIPLE_ATTRIBUTES int viewIndex, #endif const uint8_t attributeCount, const GeneratePointCloudParameters& params ); void smoothPointCloudColor( PCCPointSet3& reconstruct, const GeneratePointCloudParameters params ); void smoothPointCloudGrid( PCCPointSet3& reconstruct, const std::vector<uint32_t>& partition, const GeneratePointCloudParameters params, int gridWidth ); void addGridCentroid( PCCPoint3D& point, int patchIdx, std::vector<int>& cnt, std::vector<PCCVector3D>& center_grid, std::vector<int>& gpartition, std::vector<bool>& doSmooth, int gridSize, int gridWidth ); void addGridColorCentroid( PCCPoint3D& point, PCCVector3D& color, int patchIdx, std::vector<int>& color_gcnt, std::vector<PCCVector3D>& color_center_grid, std::vector<int>& color_gpartition, std::vector<bool>& color_doSmooth, int cgrid, std::vector<std::vector<uint8_t>>& CS_glum, const GeneratePointCloudParameters params ); bool GridFilteringColor( PCCPoint3D& curPos, PCCVector3D& color_centroid, int& color_cnt, std::vector<int>& color_gcnt, std::vector<PCCVector3D>& color_center_grid, std::vector<bool>& color_doSmooth, int grid, PCCVector3D& curPosColor, const GeneratePointCloudParameters params ); void smoothPointCloudColorLC( PCCPointSet3& reconstruct, const GeneratePointCloudParameters params ); bool gridFiltering( const std::vector<uint32_t>& partition, PCCPointSet3& pointCloud, PCCPoint3D& curPos, PCCVector3D& centroid, int& cnt, std::vector<int>& gcnt, std::vector<PCCVector3D>& center_grid, std::vector<bool>& doSmooth, int gridSize, int gridWidth ); void identifyBoundaryPoints( const std::vector<uint32_t>& occupancyMap, const size_t x, const size_t y, const size_t imageWidth, const size_t imageHeight, const size_t pointindex_1, std::vector<uint32_t>& PBflag, PCCPointSet3& reconstruct ); std::vector<int> gcnt_; std::vector<PCCVector3D> center_grid_; std::vector<bool> doSmooth_; std::vector<int> gpartition_; std::vector<int> CS_color_gcnt_; std::vector<PCCVector3D> CS_color_center_grid_; std::vector<bool> CS_color_doSmooth_; std::vector<int> CS_color_gpartition_; std::vector<std::vector<uint8_t>> CS_gLum_; #ifdef CODEC_TRACE bool trace_; FILE* traceFile_; #else #ifdef BITSTREAM_TRACE bool trace_; FILE* traceFile_; #endif #endif }; }; // namespace pcc #endif /* PCCCodec_h */
[ "noreply@github.com" ]
noreply@github.com
d99195e70f425a6113bfb5a8c2c3696c0f521dc3
080a0047de59189518fdaa61249585e7ef4c5214
/eg140-149/cpp142_LinkedListCycleIIsolve1.cpp
71bf0f6fdb10d043cc821feb5c6063576ee8aba8
[]
no_license
jjeff-han/leetcode
ba9565e5e4c3e4468711ba6e7eb6bc3cbeca9dc5
30f3d0b31cccbe83a65a6527b5e2fee79ddd59ec
refs/heads/master
2021-06-25T13:22:49.425376
2021-01-18T04:25:08
2021-01-18T04:25:08
195,916,790
0
0
null
null
null
null
UTF-8
C++
false
false
1,455
cpp
#include <stdio.h> struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; #include <set> class Solution { public: ListNode *detectCycleSet(ListNode *head) { std::set<ListNode *> node_set; while(head){ if (node_set.find(head) != node_set.end()){ return head; } node_set.insert(head); head = head->next; } return NULL; } ListNode *detectCycle_re(ListNode *head) { ListNode *fast = head; ListNode *slow = head; ListNode *meet = NULL; while(fast && fast->next){ slow = slow->next; fast = fast->next->next; //if (!fast){ // return NULL; //} //fast = fast->next; if (fast == slow){ meet = fast; break; } } if (meet == NULL){ return NULL; } while(head && meet){ if (head == meet){ return head; } head = head->next; meet = meet->next; } return NULL; } }; int main(){ ListNode a(1); ListNode b(2); ListNode c(3); ListNode d(4); ListNode e(5); ListNode f(6); a.next = &b; b.next = &c; c.next = &d; d.next = &e; e.next = &f; //f.next = &c; Solution solve; ListNode *node = solve.detectCycleSet(&a); if (node){ printf("%d\n", node->val); } else{ printf("NULL\n"); } return 0; }
[ "hjf11aa@126.com" ]
hjf11aa@126.com
d46573e3bbb015777a596f690b2a06fe12b30482
2a79e87928f4b17575171e029b54f9fe7f00046e
/src/crazyflie_driver/src/crazyflie_teleop.cpp
0dec2ffbb974ffb84aa6ee239371817c07f8b042
[ "Apache-2.0" ]
permissive
LARS-robotics/lars-ros
4303c6e2c1b351484a428dcd9f1c55b8e93c00c2
83b0161e1339b39f638276dcbc29f5c71a9c3d06
refs/heads/master
2016-09-06T08:48:59.616170
2015-07-07T19:56:41
2015-07-07T19:56:41
37,946,032
1
0
null
null
null
null
UTF-8
C++
false
false
1,859
cpp
#include <ros/ros.h> #include "geometry_msgs/Point.h" #include <sensor_msgs/Joy.h> #include "crazyflie_driver/RPYT.h" class TeleopCrazyflie { public: TeleopCrazyflie(); private: void joyCallback(const sensor_msgs::Joy::ConstPtr& joy); ros::NodeHandle nh_; int roll_, pitch_, yaw_, thrust_; ros::Publisher pub; ros::Subscriber joy_sub_; }; TeleopCrazyflie::TeleopCrazyflie(): roll_(0), pitch_(1), yaw_(2), thrust_(3) { //nh_.param("axis_linear", linear_, linear_); //nh_.param("axis_angular", angular_, angular_); //nh_.param("scale_angular", a_scale_, a_scale_); //nh_.param("scale_linear", l_scale_, l_scale_); //nh_.param("axis_radius", radius_, radius_); //nh_.param("scale_radius", r_scale_, r_scale_); pub = nh_.advertise<crazyflie_driver::RPYT>("rotation_desired", 1); joy_sub_ = nh_.subscribe<sensor_msgs::Joy>("joy", 10, &TeleopCrazyflie::joyCallback, this); } void TeleopCrazyflie::joyCallback(const sensor_msgs::Joy::ConstPtr& joy) { double roll = (joy->axes[roll_])*-30.0; double pitch = (joy->axes[pitch_])*30.0; double yaw = (joy->axes[yaw_]); if ((yaw < -0.2) || (yaw > 0.2)) { if (yaw < 0.0) { yaw = (yaw + 0.2) * 200 * 1.25; } else { yaw = (yaw - 0.2) * 200 * 1.25; } } else { yaw = 0.0; } double percent_to_thrust = (1.0/100.0)*65365.0; double thrust = (joy->axes[thrust_]); if (thrust < 0.05) { thrust = 0.0; } else { thrust = 25.0 + thrust*(100.0 - 25.0) ; } //ROS_ERROR("%f, %f, %f, %f\n", roll, pitch, yaw, thrust ); crazyflie_driver::RPYT msg; msg.roll = (float) roll; msg.pitch = (float) pitch; msg.yaw = (float) yaw; msg.thrust = (float) thrust; pub.publish(msg); } int main(int argc, char** argv) { ros::init(argc, argv, "joystick_control"); TeleopCrazyflie teleop_crazy; ros::spin(); }
[ "omarhasan777@gmail.com" ]
omarhasan777@gmail.com
8ed6045b03f0aa305189f615e6cd74f1e62ba44f
4a0763389fe85b09aea09907f9d575ba3056be14
/CaveStory/Player.cpp
146b6aea1b5beb89a7d002ca0613d5ff69ac4338
[]
no_license
mjtorchia/cavestory_remake
7e8820318a6c9cbf9312fb773c762bcfc63c1a6c
01f805c5c92d11b66535f09148da594408597bf5
refs/heads/master
2021-01-20T16:17:01.063215
2016-12-03T22:13:37
2016-12-03T22:13:37
63,710,950
0
0
null
null
null
null
UTF-8
C++
false
false
5,009
cpp
#include "Player.h" #include "graphics.h" #include "slope.h" namespace player_constants { const float WALK_SPEED = 0.2f; const float GRAVITY = 0.002f; const float GRAVITY_CAP = 0.8f; const float JUMP_SPEED = 0.7f; } Player::Player() { } Player::Player(Graphics &_graphics, Vector2 spawnPoint) : AnimatedSprite(_graphics, "MyChar.png", 0, 0, 16, 16, spawnPoint.x, spawnPoint.y, 100), _dx(0), _dy(0), _facing(RIGHT), _grounded(false) { _graphics.loadImage("MyChar.png"); this->setupAnimation(); this->playAnimation("RunRight"); } void Player::setupAnimation() { this->addAnimation(1, 0, 0, "IdleLeft", 16, 16, Vector2(0, 0)); this->addAnimation(1, 0, 16, "IdleRight", 16, 16, Vector2(0, 0)); this->addAnimation(3, 0, 0, "RunLeft", 16, 16, Vector2(0, 0)); this->addAnimation(3, 0, 16, "RunRight", 16, 16, Vector2(0, 0)); } const float Player::getX()const { return this->_x; } const float Player::getY()const { return this->_y; } void Player::animationDone(std::string currentAnimation) { } //these move functions do not actually move the sprite. they just modify _dx. update is what moves the sprite void Player::moveLeft() { this->_dx = -player_constants::WALK_SPEED; this->playAnimation("RunLeft"); this->_facing = LEFT; } void Player::moveRight() { this->_dx = player_constants::WALK_SPEED; this->playAnimation("RunRight"); this->_facing = RIGHT; } void Player::stopMoving() { this->_dx = 0; this->playAnimation(this->_facing == RIGHT ? "IdleRight" : "IdleLeft"); } void Player::jump() { if (this->_grounded) { this->_dy = 0; this->_dy -= player_constants::JUMP_SPEED; this->_grounded = false; } } //void handleTileCollisions //handles collisions with all tiles the player is colliding with void Player::handleTileCollision(std::vector<Rectangle> &other) { //figure out what side the collision happened on and move the player accordingly for (int i = 0; i < other.size(); i++) { sides::Side collisionSide = Sprite::getCollisionSide(other.at(i)); if (collisionSide != sides::NONE) { switch (collisionSide) { case sides::TOP: this->_dy = 0; //this resets all gravity because we hit something. there is no change is y anymore this->_y = other.at(i).getBottom() + 1; /*if the top collides, get the value of the collision rectangle at the bottom\ and then set the players y value to that. this gives the illusion of collision because the player will go through the collision rectangle 1 px and this will set it exactly to where it collided keeping it from going through*/ if (this->_grounded) { this->_dx = 0; this->_x -= this->_facing == RIGHT ? 1.0f : -1.0f; } break; case sides::BOTTOM: this->_y = other.at(i).getTop() - this->_boundingBox.getHeight() - 1; /*same idea as above except we need to minus the players height because if we didnt the players head would end up getting set to the top of the collision rectangle which would be the player in the rectangle. so if we subtract the players height it will then place the player on top of the collision rectangle*/ this->_dy = 0; //reset all gravity because there is no change in y anymore break; case sides::LEFT: this ->_x = other.at(i).getRight() + 1; break; case sides::RIGHT: this->_x = other.at(i).getLeft() - this->_boundingBox.getWidth() - 1; } } } } //void handleSlopeCollision //handles collision with all slopes the player is colliding with void Player::handleSlopeCollision(std::vector<Slope> &others) { for (int i = 0; i < others.size(); i++) { //Calculate where on the slope the players bottom center is touching //and use y=mx+b to figure out the y position to place him at //first calculate "b" using one of the points (b=y-mx) int b = (others.at(i).getP1().y - (others.at(i).getSlope()*fabs(static_cast<float>(others.at(i).getP1().x)))); //Now get players center x int centerX = this->_boundingBox.getCenterX(); //Now pass that X intot he equation y=mx+b using our found b and x to get hte new y position int newY = (others.at(i).getSlope() * centerX) + b-8; //y=mx+b //8 is a temp fix to a prob //reposition the player to the correct y if (this->_grounded) { this->_y = newY - this->_boundingBox.getHeight(); this->_grounded = true; } } } void Player::update(float elapstedTime) { //apply gravity if (this->_dy <= player_constants::GRAVITY_CAP)//if change in y pos less than equal to grav cap, then increase gravity cuz we're not falling at the cap yet { this->_dy += player_constants::GRAVITY*elapstedTime; //as time goes on, "more gravity" will be applied to the player } //move by dx this->_x += this->_dx*elapstedTime; //move by dy this->_y += this->_dy*elapstedTime; AnimatedSprite::update(elapstedTime); } void Player::draw(Graphics &_graphics) { AnimatedSprite::draw(_graphics, this->_x, this->_y); }
[ "michael.torchia@wayne.edu" ]
michael.torchia@wayne.edu
04050a278a5d19e9bb052d3d59c53354c219467d
c3fb8a14e4dfeaeb6fa08ba23033caf663508bd9
/runtime/include/runtime/vector.hpp
ee80a8d5bc1ff6064cabe851816f36458936181b
[ "MIT" ]
permissive
xlauko/lart
db49fd778ec9bc6ccf502385289960cc4a2370de
6e650e3f0b9c28a5c0aa590ee7b9a5e03e54482f
refs/heads/master
2023-04-03T21:28:09.124674
2023-01-15T20:41:57
2023-01-15T20:42:45
180,236,345
11
2
MIT
2023-03-17T10:56:09
2019-04-08T21:33:23
C++
UTF-8
C++
false
false
3,609
hpp
#pragma once #include <cstddef> #include <iterator> #include <memory> #include <algorithm> #include <type_traits> namespace __lart::rt { template< typename T > struct vector { static_assert( std::is_nothrow_destructible_v< T > ); using size_type = size_t; using value_type = T; using iterator = T *; using const_iterator = const T *; using reverse_iterator = std::reverse_iterator< iterator >; using const_reverse_iterator = std::reverse_iterator< const_iterator >; using difference_type = std::ptrdiff_t; using reference = T&; using const_reference = T const&; ~vector() noexcept { clear(); } [[nodiscard]] inline bool empty() const noexcept { return !_size; } [[nodiscard]] inline size_type size() const noexcept { return _size; } inline iterator begin() noexcept { return _data; } inline const_iterator begin() const noexcept { return _data; } inline const_iterator cbegin() const noexcept { return _data; } inline iterator end() noexcept { return _data + size(); } inline const_iterator end() const noexcept { return _data + size(); } inline const_iterator cend() const noexcept { return _data + size(); } inline reverse_iterator rbegin() noexcept { return reverse_iterator( end() ); } inline const_reverse_iterator rbegin() const noexcept { return const_reverse_iterator( end() ); } inline const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator( end() ); } inline reverse_iterator rend() noexcept { return reverse_iterator( begin() ); } inline const_reverse_iterator rend() const noexcept { return const_reverse_iterator( begin() ); } inline const_reverse_iterator crend() const noexcept { return const_reverse_iterator( begin() ); } T& back() noexcept { return *std::prev( end() ); } const T& back() const noexcept { return *std::prev( end() ); } T& front() noexcept { return *begin(); } const T& front() const noexcept { return *begin(); } void push_back( const T& t ) noexcept { _resize( size() + 1 ); new ( &back() ) T( t ); } template< typename... args_t > T& emplace_back( args_t&&... args ) { _resize( size() + 1 ); new ( &back() ) T( std::forward< args_t >( args )... ); return back(); } void pop_back() noexcept { back().~T(); _resize( size() - 1 ); } T& operator[]( size_type idx ) noexcept { return _data[ idx ]; } const T& operator[]( size_type idx ) const noexcept { return _data[ idx ]; } inline void clear() noexcept { if ( empty() ) return; std::destroy( begin(), end() ); std::free( _data ); _data = nullptr; _size = 0; } inline void resize( size_type n ) noexcept { _resize( n ); } private: void _resize( size_type n ) noexcept { if ( n == 0 ) { std::free( _data ); _data = nullptr; } else if ( empty() ) { _data = static_cast< T* >( std::malloc( n * sizeof( T ) ) ); } else { _data = static_cast< T* >( std::realloc( _data, n * sizeof( T ) ) ); } _size = n; } size_type _size = 0; T *_data = nullptr; }; } // namespace __lart::rt
[ "xlauko@mail.muni.cz" ]
xlauko@mail.muni.cz
7312e4e743a5913ff3c0f5fa19ca75a1be079cbf
119a3f41ebbcb34a7915cef3b189f05c03939446
/test_abb_productos.cpp
e7841a63e070f006d267077b31def4bca0994340
[]
no_license
sg0nzalez/taller1
fcd85d6408b643d14dd98465202b45fecb43d583
819060fb39f362d7debdaaae42bbfab5f9648bef
refs/heads/master
2021-01-10T19:51:22.169167
2013-03-16T00:21:18
2013-03-16T00:21:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
888
cpp
/* abb_productos productos; crear_abb_productos(productos); producto prod; producto prod2; prod.codigo = 133; prod.nombre = "Pelota"; abb_insertar_producto(productos, prod); boolean esVacio = abb_producto_es_vacio(productos); if(esVacio) { printf("\nEL ABB DE PRODUCTOS ESTA VACIO\n"); } else { printf("\nEL ABB DE PRODUCTOS NO ESTA VACIO\n"); } boolean existeCodigo = abb_existe_codigo(productos, 133); if(existeCodigo) { printf("\nEL PRODUCTO BUSCADO EXISTE\n"); } else { printf("\nEL PRODUCTO BUSCADO NO EXISTE\n"); } prod2 = abb_buscar_producto(productos, 133); if(prod2.codigo==prod.codigo && comparar_2_strings(prod.nombre, prod2.nombre)==TRUE) { printf("\nEL PRODUCTO DEVUELTO ES EL CORRECTO\n"); } printf("\nEL PRODUCTO BUSCADO ES EL SIG: \n"); printf("\nCODIGO = %d\n", prod2.codigo); printf("\nNOMBRE = "); desplegar_string(prod2.nombre); */
[ "santiago.gonzalez33@gmail.com" ]
santiago.gonzalez33@gmail.com
42c96369a6e487b80ba115bafc7a096baeee253b
e5507f069b6fe9ce8a37893f367634c002674ab9
/ros/src/common/libs/diagnostics_lib/diag_lib/include/diag_lib/diag_subscriber.h
c138ce8dd396a7e751b18e9dc4ef2de0e2f91f1a
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
racestart/nAutoware
e692ea0e96d74a9445d913b1d077a8c8ef18688e
b59c1ada87685f53f19f1ba1c69e0f14039635f5
refs/heads/nagain
2023-05-28T19:14:24.364611
2019-09-19T09:12:29
2019-09-19T09:12:29
209,509,359
0
1
Apache-2.0
2023-05-22T21:38:08
2019-09-19T09:04:52
C++
UTF-8
C++
false
false
803
h
#ifndef DIAG_SUBSCRIBER_H_INCLUDED #define DIAG_SUBSCRIBER_H_INCLUDED //headers in STL #include <vector> #include <mutex> #include <algorithm> //headers in ROS #include <ros/ros.h> //headers in diag_msgs #include <diag_msgs/diag_node_errors.h> #include <diag_msgs/diag_error.h> class diag_subscriber { public: diag_subscriber(std::string target_node,int target_node_number); ~diag_subscriber(); diag_msgs::diag_node_errors get_diag_node_errors(); private: std::mutex mtx_; std::vector<diag_msgs::diag_error> buffer_; ros::Subscriber diag_sub_; ros::NodeHandle nh_; void callback_(diag_msgs::diag_error msg); const std::string target_node_; const int target_node_number_; }; #endif //DIAG_SUBSCRIBER_H_INCLUDED
[ "ms.kataoka@gmail.com" ]
ms.kataoka@gmail.com
29b4da1127a1d5c5d373985c42cdff6aa964f47d
a7764174fb0351ea666faa9f3b5dfe304390a011
/inc/ShapeSchema_PGeom2d_Transformation.hxx
a069737c59ae0ebdac33a5cbde16812730c039a8
[]
no_license
uel-dataexchange/Opencascade_uel
f7123943e9d8124f4fa67579e3cd3f85cfe52d91
06ec93d238d3e3ea2881ff44ba8c21cf870435cd
refs/heads/master
2022-11-16T07:40:30.837854
2020-07-08T01:56:37
2020-07-08T01:56:37
276,290,778
0
0
null
null
null
null
UTF-8
C++
false
false
1,888
hxx
// This file is generated by WOK (CSFDBSchema). // 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 _ShapeSchema_PGeom2d_Transformation_HeaderFile #define _ShapeSchema_PGeom2d_Transformation_HeaderFile #ifndef _Storage_Schema_HeaderFile #include <Storage_Schema.hxx> #endif #ifndef _Storage_CallBack_HeaderFile #include <Storage_CallBack.hxx> #endif #ifndef _Storage_BaseDriver_HeaderFile #include <Storage_BaseDriver.hxx> #endif #ifndef _Handle_PGeom2d_Transformation_HeaderFile #include <Handle_PGeom2d_Transformation.hxx> #endif #ifndef _ShapeSchema_Standard_Persistent_HeaderFile #include <ShapeSchema_Standard_Persistent.hxx> #endif DEFINE_STANDARD_HANDLE(ShapeSchema_PGeom2d_Transformation,Storage_CallBack) class ShapeSchema_PGeom2d_Transformation : public Storage_CallBack { public: ShapeSchema_PGeom2d_Transformation() {} Standard_EXPORT static void SAdd(const Handle(PGeom2d_Transformation)& ,const Handle(Storage_Schema)&); Standard_EXPORT static void SWrite(const Handle(Standard_Persistent)&,Storage_BaseDriver&,const Handle(Storage_Schema)&); Standard_EXPORT static void SRead(const Handle(Standard_Persistent)&,Storage_BaseDriver&,const Handle(Storage_Schema)&); Standard_EXPORT Handle_Standard_Persistent New() const; Standard_EXPORT void Add(const Handle(Standard_Persistent)&,const Handle(Storage_Schema)&) const; Standard_EXPORT void Write(const Handle(Standard_Persistent)&,Storage_BaseDriver&,const Handle(Storage_Schema)&) const; Standard_EXPORT void Read(const Handle(Standard_Persistent)&,Storage_BaseDriver&,const Handle(Storage_Schema)&) const; DEFINE_STANDARD_RTTI(ShapeSchema_PGeom2d_Transformation) }; #endif
[ "shoka.sho2@excel.co.jp" ]
shoka.sho2@excel.co.jp
92172be5e5ebfc2673ced95bbd13947a348f9be7
32805a5b5bd65aab3d432c002e86144a53096a14
/cs1400/projects/lionheart/Player/ChrisIrvine.hpp
543677062791385a09182afe335d3d76e6ba8e49
[ "MIT" ]
permissive
gavinfowler/CourseMaterials
a2ebcb5cd55f59b53103ad29f4701aea1ad7b713
da9eee3aa935de2984d6126076deeff9aa5988fa
refs/heads/master
2020-12-21T19:44:24.527250
2020-01-27T16:41:38
2020-01-27T16:41:38
236,538,594
0
0
MIT
2020-01-27T16:39:46
2020-01-27T16:39:45
null
UTF-8
C++
false
false
387
hpp
#ifndef LIONHEART_CHRIS_IRVINE #define LIONHEART_CHRIS_IRVINE #include "Player.hpp" // Summer 2015 CS 1400 Champion - Chris Irvine namespace lionheart { class ChrisIrvine : public Player { public: Placement placeUnit(UnitType, StartBox const& box, SituationReport report); Action recommendAction(Unit const&, SituationReport, Plan); Blazon getBlazon(); }; } #endif
[ "Kenneth.Sundberg@sdl.usu.edu" ]
Kenneth.Sundberg@sdl.usu.edu
0eee878d7c71733329200e5c17ee201e9ef9d8d4
40712dc426dfb114dfabe5913b0bfa08ab618961
/Demos/ReadBlend/BulletBlendReader.cpp
735f3759af2a5619857c919f6e4a3b3f1f110cf5
[]
no_license
erwincoumans/dynamica
7dc8e06966ca1ced3fc56bd3b655a40c38dae8fa
8b5eb35467de0495f43ed929d82617c21d2abecb
refs/heads/master
2021-01-17T05:53:34.958159
2015-02-10T18:34:11
2015-02-10T18:34:11
31,622,543
7
3
null
null
null
null
UTF-8
C++
false
false
8,589
cpp
/* GameKit Copyright (c) 2009 Erwin Coumans http://gamekit.googlecode.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ //#define DUMP_TYPEDEFS 1 //#define DUMP_BLOCK_NAMES 1 #include "BulletBlendReader.h" #include <stdlib.h> #include <stdio.h> #include <string.h> #include "abs-file.h" #include "readblend.h" #include "blendtype.h" #include "btBulletDynamicsCommon.h" #include "BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.h" #include "BulletCollision/Gimpact/btGImpactShape.h" BulletBlendReader::BulletBlendReader(btDynamicsWorld* destinationWorld) :m_bf(0), m_destinationWorld(destinationWorld) { } int BulletBlendReader::openFile(const char* fileName) { MY_FILETYPE *file; file = MY_OPEN_FOR_READ(fileName); if (!file) { fprintf(stderr,"couldn't open file %s\n",fileName); return 0; } m_bf = blend_read(file); if (!m_bf) { fprintf(stderr, "couldn't read blender file. :(\n"); MY_CLOSE(file); m_bf=0; return 0; } #ifdef DUMP_TYPEDEFS blend_dump_typedefs(m_bf); #endif //DUMP_TYPEDEFS MY_CLOSE(file); return 1; } BulletBlendReader::~BulletBlendReader() { ///@todo: delete/close file/data structures } void BulletBlendReader::convertAllObjects() { if (!m_bf) { printf("ERROR: no file loaded, use openFile first\n"); return; } int j; for (j=0; j<m_bf->blocks_count; ++j) { { int entry_count = blend_block_get_entry_count(m_bf, &m_bf->blocks[j]); for (int i=0; i<entry_count; ++i) { BlendObject obj = blend_block_get_object(m_bf, &m_bf->blocks[j], i); //crawl(blend_file, obj); BlendObject data_obj; BlendObject data_obj2; BlendBlock* tmpBlock=0; { const char* type_name = m_bf->types[obj.type].name; #if DUMP_BLOCK_NAMES printf("type_name=%s. ",type_name); printf("block blenderptr = %lx\n",m_bf->blocks[j].blender_pointer); #endif //DUMP_BLOCK_NAMES if (strcmp(type_name,"Object")==0) { bObj tmpObj; blend_acquire_obj_from_obj(m_bf,&obj,&tmpObj,0); convertSingleObject(&tmpObj); } if (strcmp(type_name,"Mesh")==0) { //printf("object type_name = %s\n",type_name); bMesh tmpMesh; blend_acquire_mesh_from_obj(m_bf, &obj, &tmpMesh); convertSingleMesh(&tmpMesh); } } } } } } ///for each Blender Object, this method will be called to convert/retrieve data from the bObj void BulletBlendReader::convertSingleObject(_bObj* object) { switch (object->type) { case BOBJ_TYPE_MESH: break; case BOBJ_TYPE_CAMERA: addCamera(object); return; case BOBJ_TYPE_LAMP: addLight(object); return; default: { } }; //let's try to create some static collision shapes from the triangle meshes if (object->data.mesh) { btTriangleMesh* meshInterface = new btTriangleMesh(); btVector3 minVert(1e30f,1e3f,1e30f); btVector3 maxVert(-1e30f,-1e30f,-1e30f); for (int t=0;t<object->data.mesh->face_count;t++) { float* vt0 = object->data.mesh->vert[object->data.mesh->face[t].v[0]].xyz; btVector3 vtx0(vt0[0],vt0[1],vt0[2]); minVert.setMin(vtx0); maxVert.setMax(vtx0); float* vt1 = object->data.mesh->vert[object->data.mesh->face[t].v[1]].xyz; btVector3 vtx1(vt1[0],vt1[1],vt1[2]); minVert.setMin(vtx1); maxVert.setMax(vtx1); float* vt2 = object->data.mesh->vert[object->data.mesh->face[t].v[2]].xyz; btVector3 vtx2(vt2[0],vt2[1],vt2[2]); minVert.setMin(vtx2); maxVert.setMax(vtx2); meshInterface ->addTriangle(vtx0,vtx1,vtx2); if (object->data.mesh->face[t].v[3]) { float* vt3 = object->data.mesh->vert[object->data.mesh->face[t].v[3]].xyz; btVector3 vtx3(vt3[0],vt3[1],vt3[2]); minVert.setMin(vtx3); maxVert.setMax(vtx3); meshInterface ->addTriangle(vtx0,vtx3,vtx2);//? } } if (!meshInterface->getNumTriangles()) return; /* boundtype */ #define OB_BOUND_BOX 0 #define OB_BOUND_SPHERE 1 #define OB_BOUND_CYLINDER 2 #define OB_BOUND_CONE 3 #define OB_BOUND_POLYH 4 #define OB_BOUND_POLYT 5 #define OB_BOUND_DYN_MESH 6 /* ob->gameflag */ #define OB_DYNAMIC 1 //#define OB_CHILD 2 //#define OB_ACTOR 4 //#define OB_INERTIA_LOCK_X 8 //#define OB_INERTIA_LOCK_Y 16 //#define OB_INERTIA_LOCK_Z 32 //#define OB_DO_FH 64 //#define OB_ROT_FH 128 //#define OB_ANISOTROPIC_FRICTION 256 //#define OB_GHOST 512 #define OB_RIGID_BODY 1024 //#define OB_BOUNDS 2048 //#define OB_COLLISION_RESPONSE 4096//?? //#define OB_COLLISION 65536 //#define OB_SOFT_BODY 0x20000 btVector3 localPos = (minVert+maxVert)*0.5f; btVector3 localSize= (maxVert-minVert)*0.5f; btTransform worldTrans; worldTrans.setIdentity(); worldTrans.setOrigin(btVector3(object->location[0],object->location[1],object->location[2])); // blenderobject->loc[0]+blenderobject->dloc[0]//?? //btVector3 eulerXYZ(object->rotphr[0],object->rotphr[1],object->rotphr[2]); worldTrans.getBasis().setEulerZYX(object->rotphr[0],object->rotphr[1],object->rotphr[2]); btVector3 scale(object->scaling[0],object->scaling[1],object->scaling[2]); if ( (object->gameflag & OB_RIGID_BODY) || (object->gameflag & OB_DYNAMIC)) { //m_destinationWorld->addRigidBody( btCollisionShape* colShape = 0; switch (object->boundtype) { case OB_BOUND_SPHERE: { btScalar radius = localSize[localSize.maxAxis()]; colShape = new btSphereShape(radius); break; }; case OB_BOUND_BOX: { colShape = new btBoxShape(localSize); break; } case OB_BOUND_CYLINDER: { colShape = new btCylinderShapeZ(localSize); break; } case OB_BOUND_CONE: { btScalar radius = btMax(localSize[0], localSize[1]); btScalar height = 2.f*localSize[2]; colShape = new btConeShapeZ(radius,height); break; } case OB_BOUND_POLYT: { //better to approximate it, using btShapeHull colShape = new btConvexTriangleMeshShape(meshInterface); break; } case OB_BOUND_POLYH: case OB_BOUND_DYN_MESH: { btGImpactMeshShape* gimpact = new btGImpactMeshShape(meshInterface); gimpact->postUpdate(); colShape = gimpact; break; } default: { } }; if (colShape) { colShape->setLocalScaling(scale); btVector3 inertia; colShape->calculateLocalInertia(object->mass,inertia); btRigidBody* body = new btRigidBody(object->mass,0,colShape,inertia); if (!(object->gameflag & OB_RIGID_BODY)) { body->setAngularFactor(0.f); } body->setWorldTransform(worldTrans); m_destinationWorld->addRigidBody(body); //body->setActivationState(DISABLE_DEACTIVATION); createGraphicsObject(object,body); } } else { btCollisionObject* colObj = new btCollisionObject(); colObj->setWorldTransform(worldTrans); btCollisionShape* colShape =0; if (meshInterface->getNumTriangles()>0) { btBvhTriangleMeshShape* childShape = new btBvhTriangleMeshShape(meshInterface,true); if (scale[0]!=1. || scale[1]!=1. || scale[2]!=1.) { colShape = new btScaledBvhTriangleMeshShape(childShape,scale); } else { colShape = childShape; } colObj->setCollisionShape(colShape); m_destinationWorld->addCollisionObject(colObj,short(btBroadphaseProxy::StaticFilter),short(btBroadphaseProxy::AllFilter ^ btBroadphaseProxy::StaticFilter)); colObj->setActivationState(ISLAND_SLEEPING); createGraphicsObject(object,colObj); } } } } void BulletBlendReader::convertSingleMesh(_bMesh* mesh) { }
[ "erwin.coumans@e05b9ecc-110c-11df-b47a-af0d17c1a499" ]
erwin.coumans@e05b9ecc-110c-11df-b47a-af0d17c1a499
5a74a9d38a8720a8fc3407e799f3deb73231a651
737dfc310e26a0e324f1bf2ed6cfcaf0127ab0bd
/chess/Iterador.h
6e915d6865714473a0a301d4d7682400cd1263aa
[]
no_license
SSSWWWW/Ajedrez---Progra-II
1aa926de26cdad9eba217e469f4561cb1481481e
d5e91b3b0d34867052f34b0ca175ca1cb88920bc
refs/heads/master
2021-04-06T02:28:58.753334
2018-03-11T20:36:20
2018-03-11T20:36:20
124,678,004
0
0
null
null
null
null
UTF-8
C++
false
false
150
h
#pragma once #include "Objeto.h" template<class T> class Iterador { public: virtual bool hashNext() const = 0; virtual T next() = 0; };
[ "noreply@github.com" ]
noreply@github.com
8beac4436416d5ef5e38a45003f816bb00162f02
282ec49f8ce8aa176c24e4f13a8852c9b0752e4a
/ap/codeforces/training1075a.cc
26740aa846366a5ebe67ecaea0813d80da74713d
[]
no_license
montreal91/workshop
b118b9358094f91defdae1d11ff8a1553d67cee6
8c05e15417e99d7236744fe9f960f4d6b09e4e31
refs/heads/master
2023-05-22T00:26:09.170584
2023-01-28T12:41:08
2023-01-28T12:41:08
40,283,198
3
1
null
2023-05-01T20:19:11
2015-08-06T03:53:44
C++
UTF-8
C++
false
false
1,041
cc
// // Problem: https://codeforces.com/contest/1075/problem/A // Author: montreal91 // Type: training // Date: 19.11.2018 // Time: 00:15 // Failed attempts: 0 // #include <algorithm> #include <chrono> #include <cstdint> #include <iostream> #include <fstream> #include <limits> #include <map> #include <string> #include <unordered_map> #include <utility> #include <vector> using namespace std; void function(istream& in, ostream& out) { ios::sync_with_stdio(false); in.tie(nullptr); long long n, i, j; in >> n >> i >> j; if (i + j <= n + 1) { out << "white\n"; } else { out << "black\n"; } } int main() { #ifndef ONLINE_JUDGE using namespace chrono; auto time1 = duration_cast<milliseconds>(system_clock::now().time_since_epoch()); #endif // ONLINE_JUDGE function(cin, cout); #ifndef ONLINE_JUDGE auto time2 = duration_cast<milliseconds>(system_clock::now().time_since_epoch()); cout << "Time consumed: " << milliseconds(time2 - time1).count(); cout << " ms.\n"; #endif // ONLINE_JUDGE return 0; }
[ "noreply@github.com" ]
noreply@github.com
3e5d76d879df46c2253c3cf529e11a8c32aadd5d
b98189666820422b0e5212bfa02c53e9c49ffdd7
/randomservice.cpp
73fd8e2471d9ade3010c213d5b37b74739f364da
[]
no_license
monox0456/password_test_env
86ca908fd8dbc8b9128b7329b9510f01c8bdb332
81eda07bf591bce65d494ee304989f6def321ed4
refs/heads/master
2023-08-15T03:11:10.996548
2021-09-24T21:39:15
2021-09-24T21:39:15
410,106,308
0
0
null
null
null
null
UTF-8
C++
false
false
825
cpp
// // Created by HN on 24.09.2021. // #include <random> #include <iostream> #include "randomservice.h" using namespace std; randomservice::randomservice(){ } randomservice::~randomservice(){ } int randomservice::generateAccountNumber(){ int min = 1; int max = 9999; int res = subservice(min, max); return res; } int randomservice::generateBalance(){ int min = 1; int max = 999999; int res = subservice(min, max); return res; } int randomservice::generateName(){ int min = 0; int max = 49; int res = subservice(min, max); return res; } int randomservice::subservice(int min, int max){ std::random_device dev; std::mt19937 rng(dev()); std::uniform_int_distribution<std::mt19937::result_type> dist6(min,max); int rand = dist6(rng); return rand; }
[ "the.monox3.0@gmail.com" ]
the.monox3.0@gmail.com
e1e1d64102562b9aa6fa476e9dc9e711a9e68fc0
ea2900c9506fe8aaaeb8df1b5c155ec027f45d61
/src/utils/FileUtils.h
f7d9777e46d3750f454b796634027531e4c89173
[ "Apache-2.0" ]
permissive
neuronalmotion/blueprint
1aef0ff670b016e54bde8e7661abcc548e1b82d3
712296b744df27b28d6142b794045ff8bce6ee96
refs/heads/develop
2020-07-03T11:46:09.658591
2015-11-05T11:41:12
2015-11-05T11:41:12
37,804,460
7
3
null
2015-11-01T20:35:14
2015-06-21T10:05:49
C++
UTF-8
C++
false
false
365
h
#ifndef FILEUTILS_H #define FILEUTILS_H #include <QIODevice> #include <QString> namespace blueprint { class Blueprint; class FileUtils { public: static bool saveBlueprintToFile(const Blueprint& blueprint, const QString& filepath); static Blueprint* loadBlueprintFromFile(const QString& filepath); private: FileUtils(); }; } #endif // FILEUTILS_H
[ "robin.penea@gmail.com" ]
robin.penea@gmail.com
90364467a7ef2d987328645d59cd057dab584576
e6b96681b393ae335f2f7aa8db84acc65a3e6c8d
/atcoder.jp/k4pc/k4pc_c/Main.cpp
6686206ccf15812313309c5d5146b8bcc58018b8
[]
no_license
okuraofvegetable/AtCoder
a2e92f5126d5593d01c2c4d471b1a2c08b5d3a0d
dd535c3c1139ce311503e69938611f1d7311046d
refs/heads/master
2022-02-21T15:19:26.172528
2021-03-27T04:04:55
2021-03-27T04:04:55
249,614,943
0
0
null
null
null
null
UTF-8
C++
false
false
2,729
cpp
#include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <complex> #include <string> #include <sstream> #include <algorithm> #include <numeric> #include <vector> #include <queue> #include <stack> #include <functional> #include <iostream> #include <map> #include <set> #include <cassert> using namespace std; typedef pair<int,int> P; typedef long long ll; typedef vector<int> vi; typedef vector<ll> vll; #define pu push #define pb push_back #define mp make_pair #define eps 1e-9 #define INF 1000000000ll #define sz(x) ((int)(x).size()) #define fi first #define sec second #define SORT(x) sort((x).begin(),(x).end()) #define all(x) (x).begin(),(x).end() #define rep(i,n) for(int (i)=0;(i)<(int)(n);(i)++) #define repn(i,a,n) for(int (i)=(a);(i)<(int)(n);(i)++) #define EQ(a,b) (abs((a)-(b))<eps) int N,Q; struct edge{ int to; ll cost; edge(int to,ll cost):to(to),cost(cost){} }; vector<edge> g[100100]; ll dist[100100]; bool isleaf[100100]; int begin[100100],end[100100]; int id = 0; vector<int> et; void dfs(int v,int p,ll c){ dist[v]=c; begin[v]=id++; et.pb(v); int cnt = 0; for(int i=0;i<g[v].size();i++){ edge e = g[v][i]; if(e.to==p)continue; cnt++; dfs(e.to,v,c+e.cost); } if(cnt==0)isleaf[v]=true; end[v]=id; } const int SIZE = 1<<17; struct segtree{ ll seg[SIZE*2],lazy[SIZE*2]; void lazy_evaluate(int k){ seg[k]=seg[k]+lazy[k]; if(k<SIZE-1){ lazy[k*2+1]+=lazy[k]; lazy[k*2+2]+=lazy[k]; } lazy[k]=0ll; } void update(int a,int b,int k,int l,int r,ll x){ lazy_evaluate(k); if(r<=a||b<=l)return; else if(a<=l&&r<=b){ lazy[k]+=x; lazy_evaluate(k); }else{ update(a,b,k*2+1,l,(l+r)/2,x); update(a,b,k*2+2,(l+r)/2,r,x); seg[k]=min(seg[k*2+1],seg[k*2+2]); } } ll query(int a,int b,int k,int l,int r){ lazy_evaluate(k); if(r<=a||b<=l)return INF; else if(a<=l&&r<=b){ return seg[k]; }else{ ll lch = query(a,b,k*2+1,l,(l+r)/2); ll rch = query(a,b,k*2+2,(l+r)/2,r); seg[k]=min(seg[k*2+1],seg[k*2+2]); return min(lch,rch); } } }seg; int p[100100]; int main(){ scanf("%d %d",&N,&Q); for(int i=1;i<N;i++){ int w; scanf("%d %d",&p[i],&w); p[i]--; g[i].pb(edge(p[i],w)); g[p[i]].pb(edge(i,w)); } dfs(0,-1,0ll); /*for(int i=0;i<N;i++){ printf("%d %lld %d\n",i,dist[i],isleaf[i]); } for(int i=0;i<N;i++){ printf("%d %d %d\n",i,begin[i],end[i]); }*/ for(int i=0;i<N;i++){ if(isleaf[et[i]])seg.update(i,i+1,0,0,SIZE,dist[et[i]]); else seg.update(i,i+1,0,0,SIZE,INF); } for(int i=0;i<Q;i++){ int x; scanf("%d",&x); x--; seg.update(begin[x],end[x],0,0,SIZE,INF); ll ans = seg.query(0,N,0,0,SIZE); if(ans<INF)printf("%lld\n",seg.query(0,N,0,0,SIZE)); else printf("-1\n"); } return 0; }
[ "okuraofvegetable@gmail.com" ]
okuraofvegetable@gmail.com
60e806593a0e9cdb0ebcfe8858c63b57de229306
f55f273abac8d7d402d0dc5bec7408961d74964d
/Promise.h
e61966ebb9c0441e41a401a3b2fc00e5a1e3cc5c
[]
no_license
lemourin/cpp-promise
7a05d46876eed1458b45091601c5dfb8e5479ff8
1355ccde78ee07f04e8328dbec0d6b9fcafc9f17
refs/heads/master
2020-03-20T22:23:17.969635
2019-03-25T20:35:02
2019-03-25T20:35:02
137,795,872
0
0
null
null
null
null
UTF-8
C++
false
false
10,974
h
#ifndef PROMISE_H #define PROMISE_H #include <functional> #include <memory> #include <mutex> #include <type_traits> namespace util { namespace v2 { namespace detail { template <class... Ts> class Promise; template <typename T> struct PromisedType { using type = void; }; template <typename... Ts> struct PromisedType<Promise<Ts...>> { using type = std::tuple<Ts...>; }; template <typename T> struct IsPromise { static constexpr bool value = false; }; template <typename... Ts> struct IsPromise<Promise<Ts...>> { static constexpr bool value = true; }; template <typename T> struct IsTuple { static constexpr bool value = false; }; template <typename... Ts> struct IsTuple<std::tuple<Ts...>> { static constexpr bool value = true; }; template <int... T> struct Sequence { template <class Callable, class Tuple> static void call(Callable&& callable, Tuple&& d) { callable(std::move(std::get<T>(d))...); } }; template <int G> struct SequenceGenerator { template <class Sequence> struct Extract; template <int... Ints> struct Extract<Sequence<Ints...>> { using type = Sequence<Ints..., G - 1>; }; using type = typename Extract<typename SequenceGenerator<G - 1>::type>::type; }; template <> struct SequenceGenerator<0> { using type = Sequence<>; }; template <class Element> struct AppendElement; template <class T1, class T2> struct Concatenate; template <class... Fst, class... Nd> struct Concatenate<std::tuple<Fst...>, std::tuple<Nd...>> { using type = std::tuple<Fst..., Nd...>; }; template <class T> struct Flatten; template <class First, class... Rest> struct Flatten<std::tuple<First, Rest...>> { using rest = typename Flatten<std::tuple<Rest...>>::type; using type = typename Concatenate<First, rest>::type; }; template <> struct Flatten<std::tuple<>> { using type = std::tuple<>; }; template <typename T> struct SlotsReserved { static constexpr int value = 1; }; template <typename... T> struct SlotsReserved<Promise<T...>> { static constexpr int value = std::tuple_size<std::tuple<T...>>::value; }; template <class... Ts> class Promise { public: Promise() : data_(std::make_shared<CommonData>()) {} template <typename Callable> using ReturnType = typename std::result_of<Callable(Ts...)>::type; template <class First, class Promise> struct Prepend; template <class First, class... Args> struct Prepend<First, Promise<Args...>> { using type = Promise<First, Args...>; }; template <class T> using ResolvedType = typename std::conditional<IsPromise<T>::value, typename PromisedType<T>::type, std::tuple<T>>::type; template <class T> struct PromiseType; template <class... T> struct PromiseType<std::tuple<T...>> { template <class R> struct Replace; template <class... R> struct Replace<std::tuple<R...>> { using type = Promise<R...>; }; using type = typename Replace<typename Flatten<std::tuple<ResolvedType<T>...>>::type>::type; }; template <class T> struct ReturnedTuple; template <class... T> struct ReturnedTuple<Promise<T...>> { using type = std::tuple<T...>; }; template <int Index, int ResultIndex, class T> struct EvaluateThen; template <int Index, int ResultIndex, class... T> struct EvaluateThen<Index, ResultIndex, std::tuple<T...>> { template <class PromiseType, class ResultTuple> static void call(std::tuple<T...>&& d, const PromiseType& p, const std::shared_ptr<ResultTuple>& result) { using CurrentType = typename std::tuple_element<Index, std::tuple<T...>>::type; auto element = std::move(std::get<Index>(d)); auto continuation = [d = std::move(d), p, result]() mutable { EvaluateThen<Index - 1, ResultIndex - SlotsReserved<CurrentType>::value, std::tuple<T...>>::call(std::move(d), p, result); }; AppendElement<CurrentType>::template call<ResultIndex>(std::move(element), p, result, continuation); } }; template <int ResultIndex, class... T> struct EvaluateThen<-1, ResultIndex, std::tuple<T...>> { template <class Q> struct Call; template <class... Q> struct Call<std::tuple<Q...>> { template <class Promise> static void call(std::tuple<T...>&& d, const Promise& p, const std::shared_ptr<std::tuple<Q...>>& result) { SequenceGenerator<std::tuple_size<std::tuple<Q...>>::value>::type::call( [p](Q&&... args) { p.fulfill(std::move(args)...); }, *result); } }; template <class Promise, class ResultTuple> static void call(std::tuple<T...>&& d, const Promise& p, const std::shared_ptr<ResultTuple>& result) { Call<ResultTuple>::call(std::move(d), p, result); } }; template <typename Callable, typename Tuple = ReturnType<Callable>, typename ReturnedPromise = typename PromiseType<ReturnType<Callable>>::type, typename = typename std::enable_if<IsTuple<Tuple>::value>::type> ReturnedPromise then(Callable&& cb) { std::unique_lock<std::mutex> lock(data_->mutex_); ReturnedPromise promise; data_->on_fulfill_ = [promise, cb](Ts&&... args) mutable { try { using StateTuple = typename ReturnedTuple<ReturnedPromise>::type; auto r = cb(std::move(args)...); auto common_state = std::make_shared<StateTuple>(); EvaluateThen<static_cast<int>(std::tuple_size<Tuple>::value) - 1, static_cast<int>(std::tuple_size<StateTuple>::value) - 1, Tuple>::call(std::move(r), promise, common_state); } catch (...) { promise.reject(std::current_exception()); } }; data_->on_reject_ = [promise](std::exception_ptr&& e) { promise.reject(std::move(e)); }; if (data_->error_ready_) { lock.unlock(); data_->on_reject_(std::move(data_->exception_)); } else if (data_->ready_) { lock.unlock(); SequenceGenerator<std::tuple_size<std::tuple<Ts...>>::value>::type::call(data_->on_fulfill_, data_->value_); } return promise; } template <typename Callable, typename = typename std::enable_if<std::is_void<ReturnType<Callable>>::value>::type> Promise<> then(Callable&& cb) { return then([cb](Ts&&... args) { cb(std::move(args)...); return std::make_tuple(); }); } template <typename Callable, typename = typename std::enable_if<!IsTuple<ReturnType<Callable>>::value && !std::is_void<ReturnType<Callable>>::value>::type, typename ReturnedPromise = typename PromiseType<std::tuple<ReturnType<Callable>>>::type> ReturnedPromise then(Callable&& cb) { return then([cb](Ts&&... args) mutable { return std::make_tuple(cb(std::move(args)...)); }); } template <typename Exception, typename Callable> Promise<Ts...> error(Callable&& e) { std::unique_lock<std::mutex> lock(data_->mutex_); Promise<Ts...> promise; data_->on_reject_ = [promise, cb = std::move(e)](std::exception_ptr&& e) { try { std::rethrow_exception(std::move(e)); } catch (Exception& exception) { cb(std::move(exception)); } catch (...) { promise.reject(std::current_exception()); } }; data_->on_fulfill_ = [promise](Ts&&... args) { promise.fulfill(std::move(args)...); }; if (data_->error_ready_) { lock.unlock(); data_->on_reject_(std::move(data_->exception_)); } return promise; } template <typename Callable> Promise<Ts...> error_ptr(Callable&& e) { std::unique_lock<std::mutex> lock(data_->mutex_); Promise<Ts...> promise; data_->on_reject_ = e; data_->on_fulfill_ = [promise](Ts&&... args) { promise.fulfill(std::move(args)...); }; if (data_->error_ready_) { lock.unlock(); data_->on_reject_(std::move(data_->exception_)); } return promise; } void fulfill(Ts&&... value) const { std::unique_lock<std::mutex> lock(data_->mutex_); data_->ready_ = true; if (data_->on_fulfill_) { lock.unlock(); data_->on_fulfill_(std::move(value)...); data_->on_fulfill_ = nullptr; } else { data_->value_ = std::make_tuple(std::move(value)...); } } template <class Exception, typename = typename std::enable_if<std::is_base_of< std::exception, typename std::remove_reference<Exception>::type>::value>::type> void reject(Exception&& e) const { reject(std::make_exception_ptr(std::move(e))); } void reject(std::exception_ptr&& e) const { std::unique_lock<std::mutex> lock(data_->mutex_); data_->error_ready_ = true; if (data_->on_reject_) { lock.unlock(); data_->on_reject_(std::move(e)); data_->on_reject_ = nullptr; } else { data_->exception_ = std::move(e); } } private: template <class... T> friend class Promise; struct CommonData { std::mutex mutex_; bool ready_ = false; bool error_ready_ = false; std::function<void(Ts&&...)> on_fulfill_; std::function<void(std::exception_ptr&&)> on_reject_; std::tuple<Ts...> value_; std::exception_ptr exception_; }; std::shared_ptr<CommonData> data_; }; template <class Element> struct AppendElement { template <int Index, class PromiseType, class ResultTuple, class Callable> static void call(Element&& result, const PromiseType& p, const std::shared_ptr<ResultTuple>& output, Callable&& callable) { std::get<Index>(*output) = std::move(result); callable(); } }; template <int Index, typename Tuple, class... Args> struct SetRange; template <int Index, typename Tuple> struct SetRange<Index, Tuple> { static void call(Tuple&) {} }; template <int Index, typename Tuple, class First, class... Rest> struct SetRange<Index, Tuple, First, Rest...> { static void call(Tuple& d, First&& f, Rest&&... rest) { std::get<Index>(d) = std::move(f); SetRange<Index + 1, Tuple, Rest...>::call(d, std::move(rest)...); } }; template <class... PromisedType> struct AppendElement<Promise<PromisedType...>> { template <int Index, class PromiseType, class ResultTuple, class Callable> static void call(Promise<PromisedType...>&& d, const PromiseType& p, const std::shared_ptr<ResultTuple>& output, Callable&& callable) { d.then([output, callable = std::move(callable)](PromisedType&&... args) mutable { SetRange<Index - static_cast<int>(std::tuple_size<std::tuple<PromisedType...>>::value) + 1, ResultTuple, PromisedType...>::call(*output, std::move(args)...); callable(); return std::make_tuple(); }) .error_ptr([p](std::exception_ptr&& e) { p.reject(std::move(e)); }); } }; } // namespace detail } // namespace v2 using v2::detail::Promise; } // namespace util #endif
[ "pawel.wegner95@gmail.com" ]
pawel.wegner95@gmail.com
20daa4ef6bbe0ddc87b6e24d6dd35cd093ffad91
445d6fce837cacdf98444f69003b259702d4dee9
/lab7/Source/Actor.cpp
76deca9671f1d48c13ace5f0fa4e17abfe137d2f
[]
no_license
jasonulloa/ITP485-2017
3a827f525c58917846f78a058092ad5539a796aa
a2b8509c1519c500d863a4eecd314fe6e9ce43c0
refs/heads/master
2020-03-12T03:32:54.382027
2018-04-21T02:05:21
2018-04-21T02:05:21
130,426,525
0
1
null
null
null
null
UTF-8
C++
false
false
4,048
cpp
#include "ITPEnginePCH.h" IMPL_ACTOR(Actor, Object); Actor::Actor(Game& game) :mGame(game) ,mParent(nullptr) ,mScale(1.0f) ,mIsAlive(true) ,mIsPaused(false) { } Actor::~Actor() { mGame.GetGameTimers().ClearAllTimers(this); RemoveAllChildren(); RemoveAllComponents(); } void Actor::BeginPlay() { PROFILE_SCOPE(Actor_BeginPlay); } void Actor::Tick(float deltaTime) { } void Actor::EndPlay() { } void Actor::BeginTouch(Actor& other) { } void Actor::AddComponent(ComponentPtr component, Component::UpdateType update) { component->Register(); if (update == Component::PostTick) { mPostTickComponents.emplace(component); } else { mPreTickComponents.emplace(component); } } void Actor::RemoveComponent(ComponentPtr component) { component->Unregister(); // This may be pre-tick or post-tick auto iter = mPreTickComponents.find(component); if (iter != mPreTickComponents.end()) { mPreTickComponents.erase(component); } iter = mPostTickComponents.find(component); if (iter != mPreTickComponents.end()) { mPostTickComponents.erase(component); } } void Actor::AddChild(ActorPtr child) { mChildren.emplace(child); child->mParent = this; // Force the child to compute their transform matrix child->ComputeWorldTransform(); } void Actor::RemoveChild(ActorPtr child) { auto iter = mChildren.find(child); if (iter != mChildren.end()) { (*iter)->EndPlay(); mChildren.erase(iter); } child->mParent = nullptr; } Vector3 Actor::GetForward() const { // Following Unreal coordinate system so X is forward return mWorldTransform.GetXAxis(); } ComponentPtr Actor::GetComponentFromType(const TypeInfo* type) { PROFILE_SCOPE(Actor_GetComponentFromType); // Check the pre-tick ones first for (auto& comp : mPreTickComponents) { if (type->IsExactly(comp->GetType())) { return comp; } } // Now post-tick for (auto& comp : mPostTickComponents) { if (type->IsExactly(comp->GetType())) { return comp; } } // Didn't find anything so give up return nullptr; } void Actor::SetProperties(const rapidjson::Value& properties) { Super::SetProperties(properties); PROFILE_SCOPE(Actor_SetProperties); // TODO Lab 3m Vector3 pos; if (GetVectorFromJSON(properties, "position", pos)) SetPosition(pos); float scale; if (GetFloatFromJSON(properties, "scale", scale)) SetScale(scale); Quaternion rot; if (GetQuaternionFromJSON(properties, "rotation", rot)) SetRotation(rot); } void Actor::ComputeWorldTransform() { PROFILE_SCOPE(Actor_ComputeWorldTransform); // NOTE: Computing this recursively is not the most efficient // but it's the simplest to write! mWorldTransform = Matrix4::CreateScale(mScale) * Matrix4::CreateFromQuaternion(mRotation) * Matrix4::CreateTranslation(mPosition); // No parent is the base case if (mParent) { // My transform * Parent's transform mWorldTransform *= mParent->GetWorldTransform(); } // Tell my children to recompute for (auto& child : mChildren) { child->ComputeWorldTransform(); } // Notify my components that my transform has updated for (auto& comp : mPreTickComponents) { comp->OnUpdatedTransform(); } for (auto& comp : mPostTickComponents) { comp->OnUpdatedTransform(); } } void Actor::TickInternal(float deltaTime) { if (!mIsPaused) { // Tick pre-tick components for (auto& comp : mPreTickComponents) { comp->Tick(deltaTime); } // Tick myself Tick(deltaTime); // Tick post-tick components for (auto& comp : mPostTickComponents) { comp->Tick(deltaTime); } // Tick any children for (auto& child : mChildren) { child->TickInternal(deltaTime); } } } void Actor::RemoveAllComponents() { // Unregister everything first for (auto& comp : mPreTickComponents) { comp->Unregister(); } for (auto& comp : mPostTickComponents) { comp->Unregister(); } mPreTickComponents.clear(); mPostTickComponents.clear(); } void Actor::RemoveAllChildren() { for (auto& child : mChildren) { child->EndPlay(); child->mParent = nullptr; } mChildren.clear(); }
[ "jasonulloa@hotmail.com" ]
jasonulloa@hotmail.com
f03a8c3b1d320a1bcae6df8d5fba4d9100d140d6
bf0a971195ac08a62f9d6fafb7f5ca187ead8ed5
/packager/media/chunking/text_chunker.cc
54513efe765d618c7cb6a67ddb106d63f5cdf606
[ "BSD-3-Clause" ]
permissive
weiyuefei/shaka-packager
a70b057841f6836efe4d21c028d41ec39f6af1b5
1600909c4b9f8d3893d7252e18f66d2beb349ae8
refs/heads/master
2020-03-22T03:03:17.196549
2018-06-21T19:58:34
2018-06-29T23:02:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,292
cc
// Copyright 2017 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd #include "packager/media/chunking/text_chunker.h" #include "packager/status_macros.h" namespace shaka { namespace media { namespace { const size_t kStreamIndex = 0; } // namespace TextChunker::TextChunker(double segment_duration_in_seconds) : segment_duration_in_seconds_(segment_duration_in_seconds){}; Status TextChunker::Process(std::unique_ptr<StreamData> data) { switch (data->stream_data_type) { case StreamDataType::kStreamInfo: return OnStreamInfo(std::move(data->stream_info)); case StreamDataType::kTextSample: return OnTextSample(data->text_sample); case StreamDataType::kCueEvent: return OnCueEvent(data->cue_event); default: return Status(error::INTERNAL_ERROR, "Invalid stream data type for this handler"); } } Status TextChunker::OnFlushRequest(size_t input_stream_index) { // Keep outputting segments until all the samples leave the system. Calling // |DispatchSegment| will remove samples over time. while (samples_in_current_segment_.size()) { RETURN_IF_ERROR(DispatchSegment(segment_duration_)); } return FlushAllDownstreams(); } Status TextChunker::OnStreamInfo(std::shared_ptr<const StreamInfo> info) { time_scale_ = info->time_scale(); segment_duration_ = ScaleTime(segment_duration_in_seconds_); return DispatchStreamInfo(kStreamIndex, std::move(info)); } Status TextChunker::OnCueEvent(std::shared_ptr<const CueEvent> event) { // We are going to end the current segment prematurely using the cue event's // time as the new segment end. // Because the cue should have been inserted into the stream such that no // later sample could start before it does, we know that there should // be no later samples starting before the cue event. // Convert the event's time to be scaled to the time of each sample. const int64_t event_time = ScaleTime(event->time_in_seconds); // Output all full segments before the segment that the cue event interupts. while (segment_start_ + segment_duration_ < event_time) { RETURN_IF_ERROR(DispatchSegment(segment_duration_)); } const int64_t shorten_duration = event_time - segment_start_; RETURN_IF_ERROR(DispatchSegment(shorten_duration)); return DispatchCueEvent(kStreamIndex, std::move(event)); } Status TextChunker::OnTextSample(std::shared_ptr<const TextSample> sample) { // Output all segments that come before our new sample. const int64_t sample_start = sample->start_time(); while (sample_start >= segment_start_ + segment_duration_) { RETURN_IF_ERROR(DispatchSegment(segment_duration_)); } samples_in_current_segment_.push_back(std::move(sample)); return Status::OK; } Status TextChunker::DispatchSegment(int64_t duration) { DCHECK_GT(duration, 0) << "Segment duration should always be positive"; // Output all the samples that are part of the segment. for (const auto& sample : samples_in_current_segment_) { RETURN_IF_ERROR(DispatchTextSample(kStreamIndex, sample)); } // Output the segment info. std::shared_ptr<SegmentInfo> info = std::make_shared<SegmentInfo>(); info->start_timestamp = segment_start_; info->duration = duration; RETURN_IF_ERROR(DispatchSegmentInfo(kStreamIndex, std::move(info))); // Move onto the next segment. const int64_t new_segment_start = segment_start_ + duration; segment_start_ = new_segment_start; // Remove all samples that end before the (new) current segment started. samples_in_current_segment_.remove_if( [new_segment_start](const std::shared_ptr<const TextSample>& sample) { // For the sample to even be in this list, it should have started // before the (new) current segment. DCHECK_LT(sample->start_time(), new_segment_start); return sample->EndTime() <= new_segment_start; }); return Status::OK; } int64_t TextChunker::ScaleTime(double seconds) const { DCHECK_GT(time_scale_, 0) << "Need positive time scale to scale time."; return static_cast<int64_t>(seconds * time_scale_); } } // namespace media } // namespace shaka
[ "vaage@google.com" ]
vaage@google.com
782aed217c5c984a5abf98c4c546ee52adffb3eb
e1edf93837076bb0ebba29e7c7264f9cbc539afb
/String/11656 ์ ‘๋ฏธ์‚ฌ ๋ฐฐ์—ด.cpp
874398a6ee820618b1d975d63fa92a753c0fdc71
[]
no_license
proqk/Algorithm
62882ed7b8401ee57238f07cef5571809020842f
d5300e8712dc92282aefee4d652cc1ec4c1cde78
refs/heads/master
2022-06-21T21:21:19.132839
2022-06-15T02:00:28
2022-06-15T02:00:28
67,300,887
3
0
null
null
null
null
UTF-8
C++
false
false
373
cpp
#include <iostream> #include <algorithm> #include <vector> #include <string> using namespace std; string s; vector<string> v; int main() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin >> s; for (int i = 0; i < s.size(); i++) { v.push_back(s.substr(i, s.length())); } sort(v.begin(), v.end()); for (auto x : v) cout << x << "\n"; return 0; }
[ "noreply@github.com" ]
noreply@github.com
fbb91fe481a4e1003b792a7e407f317ead604c91
89b7e4a17ae14a43433b512146364b3656827261
/testcases/CWE762_Mismatched_Memory_Management_Routines/s03/CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_malloc_51a.cpp
be6fee67a059b31889a3867269346354570ce2b5
[]
no_license
tuyen1998/Juliet_test_Suite
7f50a3a39ecf0afbb2edfd9f444ee017d94f99ee
4f968ac0376304f4b1b369a615f25977be5430ac
refs/heads/master
2020-08-31T23:40:45.070918
2019-11-01T07:43:59
2019-11-01T07:43:59
218,817,337
0
1
null
null
null
null
UTF-8
C++
false
false
2,731
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_malloc_51a.cpp Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete.label.xml Template File: sources-sinks-51a.tmpl.cpp */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: malloc Allocate data using malloc() * GoodSource: Allocate data using new * Sinks: * GoodSink: Deallocate data using free() * BadSink : Deallocate data using delete * Flow Variant: 51 Data flow: data passed as an argument from one function to another in different source files * * */ #include "std_testcase.h" namespace CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_malloc_51 { #ifndef OMITBAD /* bad function declaration */ void badSink(int64_t * data); void bad() { int64_t * data; /* Initialize data*/ data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */ data = (int64_t *)malloc(100*sizeof(int64_t)); if (data == NULL) {exit(-1);} badSink(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* good function declarations */ void goodG2BSink(int64_t * data); void goodB2GSink(int64_t * data); /* goodG2B uses the GoodSource with the BadSink */ static void goodG2B() { int64_t * data; /* Initialize data*/ data = NULL; /* FIX: Allocate memory from the heap using new */ data = new int64_t; goodG2BSink(data); } /* goodB2G uses the BadSource with the GoodSink */ static void goodB2G() { int64_t * data; /* Initialize data*/ data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */ data = (int64_t *)malloc(100*sizeof(int64_t)); if (data == NULL) {exit(-1);} goodB2GSink(data); } void good() { goodG2B(); goodB2G(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_malloc_51; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
[ "35531872+tuyen1998@users.noreply.github.com" ]
35531872+tuyen1998@users.noreply.github.com
686ef74778172eaa14cebad4309687da67cbf3b5
95018bfba922db67947dd3da5a80f7f64f632c4b
/messageframe.h
21f08da6ce0573472ffe4135b60b97752b6fe5ab
[]
no_license
anton0380/informer
b0b9eccf18d8dab59794b59d35467c0ecfa6e550
e19806759de531420598319e71ff308da582c757
refs/heads/master
2020-12-24T20:00:04.543866
2017-03-26T10:32:35
2017-03-26T10:32:35
86,223,967
0
0
null
null
null
null
UTF-8
C++
false
false
698
h
#ifndef MESSAGEFRAME_H #define MESSAGEFRAME_H #include <QFrame> #include <QtWidgets> //#include <QMultiMap> namespace Ui { class MessageFrame; } struct MessageInfo { MessageInfo(QDate date, QString message):date(date),message(message){} QString message; QDate date; }; class MessageFrame : public QFrame { Q_OBJECT public: explicit MessageFrame(QWidget *parent = 0); ~MessageFrame(); private: Ui::MessageFrame *ui; void addRow(MessageInfo mi); QMultiMap<QDate,MessageInfo> messageMap; void setTableText(int row, int col, QString str, bool editable); void onTextChanged(const QString & text); void showMessages(); }; #endif // MESSAGEFRAME_H
[ "aa@unelma.ru" ]
aa@unelma.ru
6bcd593ac92a7d1a9bf8fd4dae60b17ad5dc94b8
b77348b8e20ac7ed69180b889b96e2fe1a6aaebe
/MachineLearning/Shared/genann.cpp
3a0010584ec2130e8fb5dc99e967162fdf5c114c
[ "MIT" ]
permissive
f13rce/CyberArk-MaliciousLogAnalyzer
361d6db9395b79c26879b5995e41bbdd6072870c
9ab256b28db1db32172b8f6b1cfbe09c2d48e55a
refs/heads/master
2022-11-07T00:10:20.378459
2020-07-05T19:24:26
2020-07-05T19:24:26
277,369,107
1
0
null
null
null
null
UTF-8
C++
false
false
12,042
cpp
/* * GENANN - Minimal C Artificial Neural Network * * Copyright (c) 2015-2018 Lewis Van Winkle * * http://CodePlea.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgement in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. * */ #include "genann.h" #include <assert.h> #include <errno.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <chrono> #include <random> #include <iostream> #ifndef genann_act #define genann_act_hidden genann_act_hidden_indirect #define genann_act_output genann_act_output_indirect #else #define genann_act_hidden genann_act #define genann_act_output genann_act #endif #define LOOKUP_SIZE 4096 double genann_act_hidden_indirect(const struct genann* ann, double a) { return ann->activation_hidden(ann, a); } double genann_act_output_indirect(const struct genann* ann, double a) { return ann->activation_output(ann, a); } const double sigmoid_dom_min = -15.0; const double sigmoid_dom_max = 15.0; double interval; double lookup[LOOKUP_SIZE]; #ifdef __GNUC__ #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #define unused __attribute__((unused)) #else #define likely(x) x #define unlikely(x) x #define unused #pragma warning(disable : 4996) /* For fscanf */ #endif double genann_act_sigmoid(const genann* ann unused, double a) { if (a < -45.0) return 0; if (a > 45.0) return 1; return 1.0 / (1 + exp(-a)); } void genann_init_sigmoid_lookup(const genann* ann) { const double f = (sigmoid_dom_max - sigmoid_dom_min) / LOOKUP_SIZE; int i; interval = LOOKUP_SIZE / (sigmoid_dom_max - sigmoid_dom_min); for (i = 0; i < LOOKUP_SIZE; ++i) { lookup[i] = genann_act_sigmoid(ann, sigmoid_dom_min + f * i); } } double genann_act_sigmoid_cached(const genann* ann unused, double a) { assert(!isnan(a)); if (a < sigmoid_dom_min) return lookup[0]; if (a >= sigmoid_dom_max) return lookup[LOOKUP_SIZE - 1]; size_t j = (size_t)((a - sigmoid_dom_min) * interval + 0.5); /* Because floating point... */ if (unlikely(j >= LOOKUP_SIZE)) return lookup[LOOKUP_SIZE - 1]; return lookup[j]; } double genann_act_linear(const struct genann* ann unused, double a) { return a; } double genann_act_threshold(const struct genann* ann unused, double a) { return a > 0; } double f13rce_act_relu(const struct genann* ann unused, double a) { if (a < 0) return a * 0.01; return a; } genann* genann_init(int inputs, int hidden_layers, int hidden, int outputs) { if (hidden_layers < 0) return 0; if (inputs < 1) return 0; if (outputs < 1) return 0; if (hidden_layers > 0 && hidden < 1) return 0; const int hidden_weights = hidden_layers ? (inputs + 1) * hidden + (hidden_layers - 1) * (hidden + 1) * hidden : 0; const int output_weights = (hidden_layers ? (hidden + 1) : (inputs + 1)) * outputs; const int total_weights = (hidden_weights + output_weights); const int total_neurons = (inputs + hidden * hidden_layers + outputs); /* Allocate extra size for weights, outputs, and deltas. */ const int size = sizeof(genann) + sizeof(double) * (total_weights + total_neurons + (total_neurons - inputs)); genann* ret = static_cast<genann*>(malloc(size)); if (!ret) return 0; ret->inputs = inputs; ret->hidden_layers = hidden_layers; ret->hidden = hidden; ret->outputs = outputs; ret->total_weights = total_weights; ret->total_neurons = total_neurons; /* Set pointers. */ ret->weight = (double*)((char*)ret + sizeof(genann)); ret->output = ret->weight + ret->total_weights; ret->delta = ret->output + ret->total_neurons; auto seed = std::chrono::high_resolution_clock::now().time_since_epoch().count(); std::mt19937 mt_rand(seed); int i; for (i = 0; i < ret->total_weights; ++i) { double r = double(mt_rand()) / std::mt19937::max(); //double r = 1.5; //std::cout << r << std::endl; /* Sets weights from -0.5 to 0.5. */ ret->weight[i] = r - 0.5; //ret->weight[i] *= sqrt((double)2) / (double)ret->hidden; } //genann_randomize(ret); //ret->activation_hidden = snek_act_relu; ret->activation_hidden = f13rce_act_relu; ret->activation_output = genann_act_sigmoid; genann_init_sigmoid_lookup(ret); return ret; } genann* genann_read(FILE* in) { if (!in) { return nullptr; } int inputs, hidden_layers, hidden, outputs; int rc; errno = 0; rc = fscanf(in, "%d %d %d %d", &inputs, &hidden_layers, &hidden, &outputs); if (rc < 4 || errno != 0) { perror("fscanf"); return NULL; } genann* ann = genann_init(inputs, hidden_layers, hidden, outputs); int i; for (i = 0; i < ann->total_weights; ++i) { errno = 0; rc = fscanf(in, " %le", ann->weight + i); if (rc < 1 || errno != 0) { perror("fscanf"); genann_free(ann); return NULL; } } return ann; } genann* genann_copy(genann const* ann) { const int size = sizeof(genann) + sizeof(double) * (ann->total_weights + ann->total_neurons + (ann->total_neurons - ann->inputs)); genann* ret = static_cast<genann*>(malloc(size)); if (!ret) return 0; memcpy(ret, ann, size); /* Set pointers. */ ret->weight = (double*)((char*)ret + sizeof(genann)); ret->output = ret->weight + ret->total_weights; ret->delta = ret->output + ret->total_neurons; return ret; } void genann_randomize(genann* ann) { auto seed = std::chrono::high_resolution_clock::now().time_since_epoch().count(); std::mt19937 mt_rand(seed); int i; for (i = 0; i < ann->total_weights; ++i) { double r = double(mt_rand()) / std::mt19937::max() * 2.0; //double r = 1.5; //std::cout << r << std::endl; /* Sets weights from -0.5 to 0.5. */ ann->weight[i] = r - 1.0;// -0.5; ann->weight[i] *= sqrt((double)2) / (double)ann->hidden; } } void genann_free(genann* ann) { /* The weight, output, and delta pointers go to the same buffer. */ free(ann); } double const* genann_run(genann const* ann, double const* inputs) { double const* w = ann->weight; double* o = ann->output + ann->inputs; double const* i = ann->output; /* Copy the inputs to the scratch area, where we also store each neuron's * output, for consistency. This way the first layer isn't a special case. */ memcpy(ann->output, inputs, sizeof(double) * ann->inputs); int h, j, k; if (!ann->hidden_layers) { double* ret = o; for (j = 0; j < ann->outputs; ++j) { double sum = *w++ * -1.0; for (k = 0; k < ann->inputs; ++k) { sum += *w++ * i[k]; } *o++ = genann_act_output(ann, sum); } return ret; } /* Figure input layer */ for (j = 0; j < ann->hidden; ++j) { double sum = *w++ * -1.0; for (k = 0; k < ann->inputs; ++k) { sum += *w++ * i[k]; } *o++ = genann_act_hidden(ann, sum); } i += ann->inputs; /* Figure hidden layers, if any. */ for (h = 1; h < ann->hidden_layers; ++h) { for (j = 0; j < ann->hidden; ++j) { double sum = *w++ * -1.0; for (k = 0; k < ann->hidden; ++k) { sum += *w++ * i[k]; } *o++ = genann_act_hidden(ann, sum); } i += ann->hidden; } double const* ret = o; /* Figure output layer. */ for (j = 0; j < ann->outputs; ++j) { double sum = *w++ * -1.0; for (k = 0; k < ann->hidden; ++k) { sum += *w++ * i[k]; } *o++ = genann_act_output(ann, sum); } /* Sanity check that we used all weights and wrote all outputs. */ assert(w - ann->weight == ann->total_weights); assert(o - ann->output == ann->total_neurons); return ret; } void genann_train(genann const* ann, double const* inputs, double const* desired_outputs, double learning_rate) { /* To begin with, we must run the network forward. */ genann_run(ann, inputs); int h, j, k; /* First set the output layer deltas. */ { double const* o = ann->output + ann->inputs + ann->hidden * ann->hidden_layers; /* First output. */ double* d = ann->delta + ann->hidden * ann->hidden_layers; /* First delta. */ double const* t = desired_outputs; /* First desired output. */ /* Set output layer deltas. */ if (genann_act_output == genann_act_linear || ann->activation_output == genann_act_linear) { for (j = 0; j < ann->outputs; ++j) { *d++ = *t++ - *o++; } } else { for (j = 0; j < ann->outputs; ++j) { *d++ = (*t - *o) * *o * (1.0 - *o); ++o; ++t; } } } /* Set hidden layer deltas, start on last layer and work backwards. */ /* Note that loop is skipped in the case of hidden_layers == 0. */ for (h = ann->hidden_layers - 1; h >= 0; --h) { /* Find first output and delta in this layer. */ double const* o = ann->output + ann->inputs + (h * ann->hidden); double* d = ann->delta + (h * ann->hidden); /* Find first delta in following layer (which may be hidden or output). */ double const* const dd = ann->delta + ((h + 1) * ann->hidden); /* Find first weight in following layer (which may be hidden or output). */ double const* const ww = ann->weight + ((ann->inputs + 1) * ann->hidden) + ((ann->hidden + 1) * ann->hidden * (h)); for (j = 0; j < ann->hidden; ++j) { double delta = 0; for (k = 0; k < (h == ann->hidden_layers - 1 ? ann->outputs : ann->hidden); ++k) { const double forward_delta = dd[k]; const int windex = k * (ann->hidden + 1) + (j + 1); const double forward_weight = ww[windex]; delta += forward_delta * forward_weight; } *d = *o * (1.0 - *o) * delta; ++d; ++o; } } /* Train the outputs. */ { /* Find first output delta. */ double const* d = ann->delta + ann->hidden * ann->hidden_layers; /* First output delta. */ /* Find first weight to first output delta. */ double* w = ann->weight + (ann->hidden_layers ? ((ann->inputs + 1) * ann->hidden + (ann->hidden + 1) * ann->hidden * (ann->hidden_layers - 1)) : (0)); /* Find first output in previous layer. */ double const* const i = ann->output + (ann->hidden_layers ? (ann->inputs + (ann->hidden) * (ann->hidden_layers - 1)) : 0); /* Set output layer weights. */ for (j = 0; j < ann->outputs; ++j) { *w++ += *d * learning_rate * -1.0; for (k = 1; k < (ann->hidden_layers ? ann->hidden : ann->inputs) + 1; ++k) { *w++ += *d * learning_rate * i[k - 1]; } ++d; } assert(w - ann->weight == ann->total_weights); } /* Train the hidden layers. */ for (h = ann->hidden_layers - 1; h >= 0; --h) { /* Find first delta in this layer. */ double const* d = ann->delta + (h * ann->hidden); /* Find first input to this layer. */ double const* i = ann->output + (h ? (ann->inputs + ann->hidden * (h - 1)) : 0); /* Find first weight to this layer. */ double* w = ann->weight + (h ? ((ann->inputs + 1) * ann->hidden + (ann->hidden + 1) * (ann->hidden) * (h - 1)) : 0); for (j = 0; j < ann->hidden; ++j) { *w++ += *d * learning_rate * -1.0; for (k = 1; k < (h == 0 ? ann->inputs : ann->hidden) + 1; ++k) { *w++ += *d * learning_rate * i[k - 1]; } ++d; } } // Sanitize weights int i; for (i = 0; i < ann->total_weights; ++i) { if (ann->weight[i] <= -1.0) { ann->weight[i] = -0.9999999; } else if (ann->weight[i] >= 1.0) { ann->weight[i] = 0.9999999; } } } void genann_write(genann const* ann, FILE* out) { fprintf(out, "%d %d %d %d", ann->inputs, ann->hidden_layers, ann->hidden, ann->outputs); int i; for (i = 0; i < ann->total_weights; ++i) { fprintf(out, " %.20e", ann->weight[i]); } }
[ "f13rce@protonmail.com" ]
f13rce@protonmail.com
ee7dee042a360e6646c163b0095260facada9f31
4df63e9ceeb55632db38d09522d538a6b650c15c
/cwinvistax64diskscanconfig.cpp
8162eb71b77b438a97c3e26d094776f4ab3622e5
[]
no_license
frankkon/Repairer
60e1bfdb9e9290da0256f47640844039f4ba486d
63dce150a62e2d8c6246d4433828fe969fa9b04d
refs/heads/master
2020-12-02T21:07:24.643598
2017-07-25T14:52:37
2017-07-25T14:52:37
96,259,328
4
2
null
null
null
null
UTF-8
C++
false
false
1,236
cpp
#include "cwinvistax64diskscanconfig.h" CWinVistaX64DiskScanConfig::CWinVistaX64DiskScanConfig() { } //่ฟ”ๅ›ž้œ€่ฆๆ‰ซๆ็š„็›ฎๅฝ•ไฟกๆฏๅˆ—่กจ QList<TDiskScanInfo*>* CWinVistaX64DiskScanConfig::getDiskScanInfo() { //ๅทฒ็ปๅŠ ่ฝฝ่ฟ‡ไบ†๏ผŒๅˆ™็›ดๆŽฅ่ฟ”ๅ›ž if(!m_lstDiskScanInfo.isEmpty()) { return &m_lstDiskScanInfo; } QString sSql = "select platform_id,platform_name,platform_cpu," " desc_cn,desc_en,trash_path,ext_name,clean_all_flag " " from disk_scan_info where platform_id=60 and platform_cpu=1"; if(loadDiskScanConfigFromDb(sSql)) { return &m_lstDiskScanInfo; } else { return NULL; } } QList<TRegScanInfo*>* CWinVistaX64DiskScanConfig::getRegScanInfo() { //ๅทฒ็ปๅŠ ่ฝฝ่ฟ‡ไบ†๏ผŒๅˆ™็›ดๆŽฅ่ฟ”ๅ›ž if(!m_lstRegScanInfo.isEmpty()) { return &m_lstRegScanInfo; } QString sSql = "select platform_id,platform_name,platform_cpu," " err_type,desc_cn,desc_en,reg_path " " from reg_scan_info where platform_id=60 and platform_cpu=1"; if(loadRegScanConfigFromDb(sSql)) { return &m_lstRegScanInfo; } else { return NULL; } }
[ "frankkon@sina.com" ]
frankkon@sina.com
90ea224ae044f67c39e0a14433655cf383b13137
f62a039a853d5b8235b9c4547656bbb3b108c463
/termproject/2018Server/2018Server/CollisionMap.h
dcf22f1bf5ba90c4024bf628e71f151a0ef7ae37
[]
no_license
yeosu0107/GameServerPrograming
b53316896d06e12ff9ca6f89d754b5b3bf5c75b5
fd463e2ead1b43687dd63437bab58fa0a11b2d0e
refs/heads/master
2018-12-12T07:45:30.646844
2018-09-13T07:51:00
2018-09-13T07:51:00
124,079,905
0
0
null
null
null
null
UTF-8
C++
false
false
583
h
#pragma once #include <queue> #include <vector> struct spawnPoint { int type; int xPos; int yPos; spawnPoint(int t, int x, int y) { type = t; xPos = x; yPos = y; } }; class CsvMap { private: int map[300][300]; queue<spawnPoint> spawn; vector<int> expTable; public: CsvMap(); ~CsvMap(); void LoadmapFile(const char* fileName); void LoadSpawnPoint(const char* fileName); void LoadExpTable(const char* fileName); int (*getCollisionMap())[300] { return map; } queue<spawnPoint> getSpawnPoint() { return spawn; } vector<int> getExpTable() { return expTable; } };
[ "yeosu0107@naver.com" ]
yeosu0107@naver.com
e3d39b2be32abdb6177f3870b3c5b1bf9f39d0cf
b00a3a6e24f10ac56134bb21246e63ed9ff5c25b
/papersheet.cpp
a6660627b936ef88fc70ad8abb476d0d52edac8f
[]
no_license
nlw0/filterSqp
ef45e0d180d6f5704e3c3461a77a0c55e1ee5808
b4e06e21812a2d2664e49926da09231d63e5eb4b
refs/heads/master
2021-01-12T17:23:34.545493
2015-10-02T05:10:51
2015-10-02T05:10:51
43,089,985
4
0
null
null
null
null
UTF-8
C++
false
false
3,444
cpp
#include "papersheet.h" B<F<double>> sq(const B<F<double>> &x) { return x * x; } B<F<double>> coplanar(const B<F<double>> *a, const B<F<double>> *b, const B<F<double>> *c) { B<F<double>> x[3]; x[0] = (a[1] * c[2] - a[2] * c[1]); x[1] = (a[2] * c[0] - a[0] * c[2]); x[2] = (a[0] * c[1] - a[1] * c[0]); B<F<double>> n2x = sq(x[0]) + sq(x[1]) + sq(x[2]); B<F<double>> n2b = sq(b[0]) + sq(b[1]) + sq(b[2]); return sq(b[0] * x[0] + b[1] * x[1] + b[2] * x[2]) / (n2x * n2b); } B<F<double>> papersheet_function(int lines, int columns, B<F<double>> *x) { int dims = 3; int n_vars = lines * columns * dims; int i, j, pt; B<F<double>> sphere_error = 0.0; for (i = 0; i < lines; i++) for (j = 0; j < columns; j++) { pt = 3 * (i * columns + j); double scale = 1.0; if (i == lines / 2 || j == columns / 2) scale = 100.0; sphere_error += scale * sq(sqrt(sq(x[pt]) + sq(x[pt + 1]) + sq(x[pt + 2])) - 1.0); } B<F<double>> angular_error = 0.0; for (i = 0; i < lines; i++) for (j = 1; j < columns - 1; j++) { pt = 3 * (i * columns + j); angular_error += coplanar(x + pt - 3, x + pt, x + pt + 3); } for (i = 1; i < lines - 1; i++) for (j = 0; j < columns; j++) { pt = 3 * (i * columns + j); angular_error += coplanar(x + pt - 3 * columns, x + pt, x + pt + 3 * columns); } B<F<double>> fixation_error = 0.0; i = lines / 2; j = columns / 2; pt = 3 * (i * columns + j); fixation_error += sq(x[pt]); fixation_error += sq(x[pt + 1]); fixation_error += sq(x[pt + 2] + 1); i = lines / 2; for (j = 0; j < columns; j++) { int pt = 3 * (i * columns + j); fixation_error += sq(x[pt + 1]); } j = columns / 2; for (i = 0; i < lines; i++) { int pt = 3 * (i * columns + j); fixation_error += sq(x[pt]); } B<F<double>> scale_error = 0.0; B<F<double>> lenA = 0.0; B<F<double>> lenB = 0.0; double seglen = 0.3; i = lines / 2; for (j = 0; j < columns - 1; j++) { int pta = 3 * (i * columns + j); int ptb = 3 * (i * columns + (j + 1)); lenA += sq(sqrt(sq(x[pta] - x[ptb]) + sq(x[pta + 1] - x[ptb + 1]) + sq(x[pta + 2] - x[ptb + 2])) - seglen); } j = columns / 2; for (i = 0; i < lines - 1; i++) { int pta = 3 * (i * columns + j); int ptb = 3 * ((i + 1) * columns + j); lenB += sq(sqrt(sq(x[pta] - x[ptb]) + sq(x[pta + 1] - x[ptb + 1]) + sq(x[pta + 2] - x[ptb + 2])) - seglen); } scale_error += lenA + lenB; return sphere_error + 10.0 * scale_error + 1.0 * angular_error + 1000.0 * fixation_error; } void target_papersheet_hess(int lines, int columns, double *x_val, double *y_val, double *gradient, double *hessian) { int dimensions = 3; int n_vars = lines * columns * dimensions; B<F<double>> x[n_vars]; unsigned int j; unsigned int i; for (i = 0; i < n_vars; i++) { x[i] = x_val[i]; x[i].x().diff(i, (unsigned int) n_vars); } B<F<double>> y = papersheet_function(lines, columns, x); y.diff(0, 1); *y_val = y.x().x(); for (i = 0; i < n_vars; i++) gradient[i] = x[i].d(0).x(); for (i = 0; i < n_vars; i++) for (j = 0; j < lines * columns; j++) hessian[-i*j] = x[i].d(0).d(j); //WTF }
[ "nwerneck@gmail.com" ]
nwerneck@gmail.com
a8758996b6a84bcbf80622b8cfbda009cbcc0ca4
7ec1b3860184ec10777540ffad68cd3e717ee337
/include/XPG/OpenGL/ShortIndexVBO.hpp
287159f3ce02d4a0f9fce71f7995b729d4168ad3
[]
no_license
binary-cocoa/LegacyXPG
688abb880bddb332fca172a6aad447acaa3e21ef
51c35a2249a6ad9a0126e6839c45f98b16bf862b
refs/heads/master
2021-01-10T00:54:38.855573
2011-08-27T17:20:13
2011-08-27T17:20:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
497
hpp
#ifndef XPGH_SHORTINDEXVBO #define XPGH_SHORTINDEXVBO #include "VertexBufferObject.hpp" namespace XPG { class ShortIndexVBO : public VertexBufferObject { public: ShortIndexVBO(GLenum inUsage = GL_STATIC_DRAW); virtual ~ShortIndexVBO(); void draw(GLenum inMode = GL_TRIANGLES) const; void drawInstanced(GLsizei inPrimCount, GLenum inMode = GL_TRIANGLES) const; protected: private: }; } #endif
[ "thebuzzsaw@gmail.com" ]
thebuzzsaw@gmail.com
1ae855755c81105777aa73655eaadaa7ab2e12b5
8b3f9e359cadff65d8574da9b44a1408ebcade86
/third_party/IXWebSocket/ixwebsocket/IXSocketFactory.h
c10145d17dcec157810b1ba799f6a262ec736f4d
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
opcon/nakama-cpp
42f2e1b837620bee15792695d71d31c1a1950f4e
ba965046c27b52303bf4519f9dee046d6499bac5
refs/heads/master
2020-05-15T15:08:37.546370
2019-04-15T15:41:01
2019-04-15T15:41:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
423
h
/* * IXSocketFactory.h * Author: Benjamin Sergeant * Copyright (c) 2018 Machine Zone, Inc. All rights reserved. */ #pragma once #include <memory> namespace ix { class Socket; std::shared_ptr<Socket> createSocket(bool tls, std::string& errorMsg); std::shared_ptr<Socket> createSocket(int fd, std::string& errorMsg); }
[ "kdl.dima@gmail.com" ]
kdl.dima@gmail.com
2af52514babc53882b9500d0875dc410d23af452
ae04470c3c266513002c2c5c9ac9b034614930cb
/15XX/zoj.1520.src.1.cpp
ce9870bf454d68737dcf8f391eae982439cd667c
[]
no_license
fish-ball/acm.zju.edu.cn
281315b9aab0517801ca780972a327642867eb7d
984d48539607ed082749204a81d4aecac5bdac53
refs/heads/master
2021-03-12T19:15:13.640962
2018-11-16T10:34:34
2018-11-16T10:34:34
14,883,882
1
1
null
null
null
null
GB18030
C++
false
false
1,032
cpp
// 1692615 2008-11-07 23:30:33 Accepted 1520 C++ 0 196 ๅ‘†ๆปž็š„ๆ…ขๆฟ // ็ปๅ…ธ่ƒŒๅŒ…๏ผŒ่ฎฐๅฝ•่ทฏๅพ„๏ผŒๆ”พๅพ—ไธ‹ๅฐฑ่กŒใ€‚ #include <iostream> using namespace std; int pre[1001], id[1001], cnt[1001], M, N, S, K, X; void disp(int pos) { if(pos == 0) return; disp(pre[pos]); cout << ' ' << id[pos]; } int main() { while(cin >> M >> N && (M || N)) { memset(pre, -1, sizeof(pre)); pre[0] = S = cnt[0] = 0; cin >> K; for(int i = 1; i <= K; ++i) { cin >> X; S += X; for(int j = M - X; j >= 0; --j) { if(pre[j] != -1 && pre[j + X] == -1) { pre[j + X] = j; id[j + X] = i; cnt[j + X] = cnt[j] + 1; } } } int pos = M; while(pre[pos] == -1) pos--; if(S - pos > N) { puts("Impossible to distribute"); continue; } cout << cnt[pos]; disp(pos); puts(""); } }
[ "alfred.h@163.com" ]
alfred.h@163.com
0610cee3c7c9e81b5306ff7788f268951c24eca6
88f5e4bec58c7026035a085165c6cbdb9b2e1529
/d04/ex01/Character.cpp
e79db6eaa1fce196700a5828730f558df7f5bfa3
[]
no_license
sploadie/piscine_cpp
b6b9b62bbfd0eec03a6d081bb7b21595b7383dc3
0f8b004ada40128c3950acc548231b0b57c65207
refs/heads/master
2021-01-13T14:28:06.655285
2017-01-15T17:04:03
2017-01-15T17:04:03
79,046,336
0
1
null
null
null
null
UTF-8
C++
false
false
2,564
cpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Character.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tgauvrit <tgauvrit@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/04/08 16:10:58 by tgauvrit #+# #+# */ /* Updated: 2016/04/08 16:50:14 by tgauvrit ### ########.fr */ /* */ /* ************************************************************************** */ #include "Character.hpp" Character::Character( void ) : _name(std::string("Sole Survivor")), _ap(Character::_MaxAP) { this->_weapon = NULL; return; } Character::Character( std::string const & name ) : _name(name), _ap(Character::_MaxAP) { this->_weapon = NULL; return; } Character::Character( Character const & obj ) { *this = obj; return; } Character::~Character( void ) { return; } Character & Character::operator=( Character const & rhs ) { this->_name = rhs._name; this->_ap = rhs._ap; this->_weapon = rhs._weapon; return *this; } void Character::recoverAP( void ) { this->_ap += 10; if (this->_ap > Character::_MaxAP) { this->_ap = Character::_MaxAP; } } void Character::equip( AWeapon * weapon ) { this->_weapon = weapon; } void Character::attack( Enemy * enemy ) { if (this->_weapon == NULL) { return; }; AWeapon const & weapon = *(this->_weapon); if (this->_ap < weapon.getAPCost()) { return; }; this->_ap -= weapon.getAPCost(); std::cout << this->_name << " attacks " << enemy->getType() << " with a " << weapon.getName() << std::endl; weapon.attack(); enemy->takeDamage(weapon.getDamage()); if (enemy->getHP() == 0) { delete enemy; } } std::string const & Character::getName( void ) const { return this->_name; } int Character::getAP( void ) const { return this->_ap; } AWeapon * Character::getWeapon( void ) const { return this->_weapon; } std::ostream & operator<<(std::ostream & o, Character const & rhs) { o << rhs.getName() << " has " << rhs.getAP() << " AP and "; if (rhs.getWeapon() != NULL) { o << "wields a " << rhs.getWeapon()->getName(); } else { o << "is unarmed"; } o << std::endl; return o; }
[ "tanguygauvrit@gmail.com" ]
tanguygauvrit@gmail.com
6c8d625343cc450189209a622b10fd7f265f6957
ae04470c3c266513002c2c5c9ac9b034614930cb
/17XX/zoj.1704.src.1.cpp
0a73c69b085d173681a9b9713522ab1e80857ced
[]
no_license
fish-ball/acm.zju.edu.cn
281315b9aab0517801ca780972a327642867eb7d
984d48539607ed082749204a81d4aecac5bdac53
refs/heads/master
2021-03-12T19:15:13.640962
2018-11-16T10:34:34
2018-11-16T10:34:34
14,883,882
1
1
null
null
null
null
GB18030
C++
false
false
2,584
cpp
// ็ฎ€ๅ•็š„ๅ‡ ไฝ•้—ฎ้ข˜๏ผŒ็”ฑไบŽ่ง„ๆจกๆžๅฐ๏ผŒๆ‰€ไปฅ้šไพฟๆžๆžๆžšไธพๅฐฑ่กŒไบ† // ่ฟ™ไธชๅฎŒๅ…จๅฏไปฅไธ็”จๆตฎ็‚น็š„๏ผŒ้‚ฃๅฐฑไธ่ฆ็”จไบ†๏ผŒๅ…ๅพ—็ฒพๅบฆ้—ฎ้ข˜ // 2889960 2008-05-05 01:06:05 Accepted 1704 C++ 00:00.00 840K ๅ‘†ๆปž็š„ๆ…ขๆฟ #include <cmath> #include <iostream> #include <algorithm> using namespace std; struct Point { int x, y; char label; bool inside( const Point& A, const Point& B, const Point& C ) { int p1 = ( A.x - B.x ) * ( y - B.y ) - ( A.y - B.y ) * ( x - B.x ); int p2 = ( B.x - C.x ) * ( y - C.y ) - ( B.y - C.y ) * ( x - C.x ); int p3 = ( C.x - A.x ) * ( y - A.y ) - ( C.y - A.y ) * ( x - A.x ); return p1 >= 0 && p2 >= 0 && p3 >= 0 || p1 <= 0 && p2 <= 0 && p3 <= 0; } }; int area( const Point& p1, const Point& p2, const Point& p3 ) { return abs( ( p3.y - p1.y ) * ( p2.x - p1.x ) - ( p2.y - p1.y ) * ( p3.x - p1.x ) ); } int main() { int N, Area; Point P[15]; char T[4] = "???"; while( ( cin >> N ) && N ) { for( int i = 0; i < N; ++i ) cin >> P[i].label >> P[i].x >> P[i].y; Area = 0; for( int i = 2; i < N; ++i ) { for( int j = 1; j < i; ++j ) { for( int k = 0; k < j; ++k ) { int now = area( P[k], P[j], P[i] ); if( now <= Area ) continue; bool valid = true; for( int t = 0; t < N; ++t ) { if( t == i || t == j || t == k ) continue; if( P[t].inside( P[i], P[j], P[k] ) ) { valid = false; break; } } if( valid && now > Area ) { Area = now; T[0] = P[k].label; T[1] = P[j].label; T[2] = P[i].label; } } } } sort( T, T + 3 ); cout << T << endl; } }
[ "alfred.h@163.com" ]
alfred.h@163.com
53043c46bb2fbef80c4e74f56b77d330b06a8800
91721cafcc790673eb39c99be05bad570aedef74
/Leetcode practice/17. Letter Combinations of a Phone Number.cpp
bb1a913b2a6314719be8f4da107cce18fbc9973c
[]
no_license
olee12/Leetcode-practice
6631d559377d926c480b3115c75b1348be5c55fe
ea4649601af66193da036c4cce6032a22b1a673b
refs/heads/master
2022-07-09T09:04:26.542487
2022-07-02T05:16:10
2022-07-02T05:16:10
81,569,221
0
0
null
2020-10-13T10:30:13
2017-02-10T13:45:44
C++
UTF-8
C++
false
false
720
cpp
#include <stdio.h> #include <string.h> #include <string> #include <vector> using namespace std; string digits; int vis[10]; std::vector<string> res; string ret; string table[] = {" ","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; void rec(int pos) { if(pos == digits.size()) { res.push_back(ret); return ; } int now = digits[pos] - '0'; for(int i = 0;i < table[now].size();i++){ ret.push_back(table[now][i]); rec(pos+1); ret.pop_back(); } return ; } class Solution { public: vector<string> letterCombinations(string digits) { ::digits = digits; memset(vis,0,sizeof(vis)); res.clear(); if(digits.size()==0) return res; rec(0); return res; } }; int main() { return 0; }
[ "th160887@gmail.com" ]
th160887@gmail.com
dae111fe20fa1b65dce3d87bc5379b23feabd353
f478cd50b4a7f1ee1517fd51d5e2e11a3e8166b5
/4/main.cpp
e425ad3c525ae7823c405be052baa8e5f50d6dc7
[]
no_license
alexchekmenev/math-logic
94e7d80e940efb8b2abaee22db995fb7f3543fca
a0ce51a4cabf069a80eb416c79e16f46c0e87972
refs/heads/master
2021-01-19T22:01:17.157471
2017-04-19T11:45:27
2017-04-19T11:45:27
88,738,361
0
0
null
null
null
null
UTF-8
C++
false
false
31,544
cpp
#include <fstream> #include <iostream> #include <string> #include <vector> #include <map> #include <set> #include <vector> using namespace std; const int N = 5000; int count = 0; long long prime[N * N]; string getStringWithoutSpaces(const string & s) { string res = ""; for (unsigned int i = 0; i < s.length(); i++) { char c = s[i]; if (!isspace(c)) res += c; } return res; } struct Node { long long hash; int vertCnt; int ptrCnt; bool lastValue; vector<Node*> terms; string s; Node * l; Node * r; Node() : vertCnt(0), ptrCnt(0), l(NULL), r(NULL) {} Node(string s, Node * l, Node * r) : s(s), l(l), r(r) { //cout << s << "\n"; vertCnt = 1; ptrCnt = 0; int lCnt = 0, rCnt = 0; if (l) { lCnt = l->vertCnt; vertCnt += lCnt; l->ptrCnt++; } if (r) { rCnt = r->vertCnt; vertCnt += rCnt; } hash = 0; if (l) hash += l->hash; for (int i = 0; i < s.length(); i++) { hash *= prime[1]; hash += s[i]; } if (r) { hash *= prime[rCnt]; hash += r->hash; r->ptrCnt++; } } Node(string s, vector<Node*> &terms) : Node(s, NULL, NULL) { this->terms = terms; hash = terms[0]->hash; for (int i = 1; i < terms.size(); i++) { hash *= prime[terms[i]->vertCnt]; hash += terms[i]->hash; } for (int i = 0; i < s.length(); i++) { hash *= prime[1]; hash += s[i]; } } ~Node() { if (l && l->ptrCnt == 0) delete l; if (r && r->ptrCnt == 0) delete r; } string getAsString(bool isMain = true) { string result = ""; if (!isVariable() && !isMain) { result += "("; } if (s != "@" && s != "?") { if (l) { result += l->getAsString(false); } result += s; } else { result += s; if (l) { result += l->getAsString(false); } } if (r) { result += r->getAsString(false); } if (terms.size() != 0) { result += "("; for (int i = 0; i < terms.size() - 1; i++) { result += terms[i]->getAsString() + ","; } result += terms.back()->getAsString(); result += ")"; } if (!isVariable() && !isMain) { result += ")"; } return result; } bool isVariable() { if (s.length() > 0 && s[0] >= 'a' && s[0] <= 'z' && terms.size() == 0) { return true; } return false; } bool isFunction() { if (s.length() > 0 && ( (s[0] >= 'a' && s[0] <= 'z' && terms.size() != 0) || s[0] == '\'' || s[0] == '*' || s[0] == '+' || s[0] == '0' )) { return true; } return false; } bool isPredicate() { if (s.length() > 0 && s[0] >= 'A' && s[0] <= 'Z') { return true; } return false; } }; struct SubstituteError { Node *x, *y; string a; // y[a:=x] SubstituteError(Node *y, const string &a, Node *x) : x(x), y(y), a(a) {} }; struct VariableFreeError { Node *x; string a; VariableFreeError(Node *x, const string &a) : x(x), a(a) {} }; struct KvantorError { string type; string a; Node *x; KvantorError(const string &type, const string &a, Node *x) : type(type), a(a), x(x) {} }; struct UnknownError { }; Node *notX(Node *x) { return new Node("!", NULL, x); } Node *notNotX(Node *x) { return notX(notX(x)); } vector<Node*> axioms; bool checkEqual(Node * a, Node * b) { if (!a && !b) return true; if (!a || !b) return false; if (a == b) return true; if (a->hash != b->hash) return false; else return true; if (a->terms.size() != b->terms.size()) return false; if (a->s != b->s) return false; for (int i = 0; i < a->terms.size(); i++) { if (!checkEqual(a->terms[i], b->terms[i])) { return false; } } if (!checkEqual(a->l, b->l)) return false; if (!checkEqual(a->r, b->r)) return false; return true; } #include "NodeParser.h" // by predicate or by variable bool fillMap(Node * formula, Node * template_, map<string, vector<Node *> > &variableMap, bool byPred = true) { if (!formula && !template_) return true; if (!formula || !template_) return false; const string &tempStr = template_->s; if (byPred && template_->isPredicate() || !byPred && template_->isVariable()) { variableMap[tempStr].push_back(formula); return true; } else { if (tempStr != formula->s) { return false; } return fillMap(formula->l, template_->l, variableMap, byPred) && fillMap(formula->r, template_->r, variableMap, byPred); } } // by predicate or by variable bool checkFormulaIsSimilarToTemplate(Node *formula, Node *template_, bool byPred = true) { if (!formula && !template_) return true; if (!formula || !template_) return false; if (formula == template_) return true; map<string, vector<Node*> > variableMap; if (fillMap(formula, template_, variableMap, byPred)) { for (auto& it : variableMap) { vector<Node*> &nodes = it.second; for (Node* node : nodes) { if (!checkEqual(node, *nodes.begin())) { return false; } } } return true; } return false; } // for 11, 12, 21 axioms bool checkFormulaIsSimilarToTemplate2(Node *formula, Node *template_) { if (!formula && !template_) return true; if (!formula || !template_) return false; if (formula == template_) return true; if (template_->isVariable()) { return formula->isVariable(); } if (template_->isPredicate()) { return true; } if (formula->s != template_->s) { return false; } return checkFormulaIsSimilarToTemplate2(formula->l, template_->l) && checkFormulaIsSimilarToTemplate2(formula->r, template_->r); } Node *getFirstNotBound(Node *formula, Node *template_, const string &x) { if (!formula || !template_) return NULL; if (template_->s == x) { return formula; } if (template_->s != formula->s) { return NULL; } if (template_->terms.size() != formula->terms.size()) { return NULL; } bool isKvant = false; if (formula->s == "@" || formula->s == "?") { if (formula->l->s == x) { return NULL; } isKvant = true; } for (int i = 0; i < formula->terms.size(); i++) { Node *res = getFirstNotBound(formula->terms[i], template_->terms[i], x); if (res) return res; } if (!isKvant) { Node *res1 = getFirstNotBound(formula->l, template_->l, x); if (res1) return res1; } Node *res2 = getFirstNotBound(formula->r, template_->r, x); if (res2) return res2; } bool checkIsFreeForSub(Node *v, const map<string, int> &bounded) { if (!v) return true; for (Node *term : v->terms) { if (!checkIsFreeForSub(term, bounded)) { return false; } } if (v->isVariable()) { auto it = bounded.find(v->s); return it == bounded.end() || it->second == 0; } return checkIsFreeForSub(v->l, bounded) && checkIsFreeForSub(v->r, bounded); } bool checkIsNotFree(Node *v, const string &x, map<string, int> &bounded) { if (!v) return true; if (v->s == "@" || v->s == "?") { bounded[v->l->s]++; } if (v->isVariable()) { auto it = bounded.find(v->s); return it == bounded.end() || it->second != 0; } bool result = checkIsNotFree(v->l, x, bounded) && checkIsNotFree(v->r, x, bounded); if (v->s == "@" || v->s == "?") { bounded[v->l->s]--; } return result; } bool checkIsNotFree(Node *v, const string &x) { map<string, int> bounded; return checkIsNotFree(v, x, bounded); } Node *substitute(Node *alpha, const string &x, Node *tetta, map<string, int> &bounded, bool &isFree) { if (!alpha) return NULL; bool isKvant = false; if (alpha->s == "@" || alpha->s == "?") { if (alpha->l->s == x) { return alpha; } bounded[alpha->l->s]++; isKvant = true; return new Node(alpha->s, alpha->l, substitute(alpha->r, x, tetta, bounded, isFree)); } Node *result = NULL; if (alpha->s == x) { if (!checkIsFreeForSub(tetta, bounded)) { isFree = false; } result = tetta; } else { if (alpha->terms.size() == 0) { result = new Node(alpha->s, substitute(alpha->l, x, tetta, bounded, isFree), substitute(alpha->r, x, tetta, bounded, isFree)); } else { vector<Node*> terms; for (Node *term : alpha->terms) { terms.push_back(substitute(term, x, tetta, bounded, isFree)); } result = new Node(alpha->s, terms); } } if (isKvant) { bounded[alpha->l->s]--; } return result; } // alpha[x:=tetta] Node *substitute(Node *alpha, const string &x, Node *tetta, bool &isFree) { map<string, int> bounded; Node *result = substitute(alpha, x, tetta, bounded, isFree); return result; } Node *getFormulaFromTemplate(Node *v, Node *a = NULL, Node *b = NULL, Node *c = NULL) { if (!v) return NULL; if (v->s == "A") return a; if (v->s == "B") return b; if (v->s == "C") return c; return new Node(v->s, getFormulaFromTemplate(v->l, a, b, c), getFormulaFromTemplate(v->r, a, b, c)); } void init() { prime[0] = 1; prime[1] = 31; for (int i = 2; i < N * N; i++) { prime[i] = prime[i - 1] * prime[1]; } axioms = vector<Node*>(30); axioms[1] = parseStringToFormula("A->B->A"); axioms[2] = parseStringToFormula("(A->B)->(A->B->C)->(A->C)"); axioms[3] = parseStringToFormula("A->B->A&B"); axioms[4] = parseStringToFormula("A&B->A"); axioms[5] = parseStringToFormula("A&B->B"); axioms[6] = parseStringToFormula("A->A|B"); axioms[7] = parseStringToFormula("B->A|B"); axioms[8] = parseStringToFormula("(A->C)->(B->C)->(A|B->C)"); axioms[9] = parseStringToFormula("(A->B)->(A->!B)->!A"); axioms[10] = parseStringToFormula("!!A->A"); axioms[11] = parseStringToFormula("@xA->A(x)"); axioms[12] = parseStringToFormula("A(x)->?xA"); axioms[13] = parseStringToFormula("a=b->a'=b'"); axioms[14] = parseStringToFormula("a=b->a=c->b=c"); axioms[15] = parseStringToFormula("a'=b'->a=b"); axioms[16] = parseStringToFormula("!a'=0"); axioms[17] = parseStringToFormula("a+b'=(a+b)'"); axioms[18] = parseStringToFormula("a+0=a"); axioms[19] = parseStringToFormula("a*0=0"); axioms[20] = parseStringToFormula("a*b'=a*b+a"); axioms[21] = parseStringToFormula("A(x)&@x(A->A(x))->A"); } int checkIsAxiom(Node *formula) { for (int i = 1; i <= 10; i++) { if (checkFormulaIsSimilarToTemplate(formula, axioms[i])) { return i; } } if (checkFormulaIsSimilarToTemplate2(formula, axioms[11])) { Node *x = getFirstNotBound(formula->r, formula->l->r, formula->l->l->s); //cout << x << "\n"; if (x) { bool isFree = true; Node *sub = substitute(formula->l->r, formula->l->l->s, x, isFree); if (checkEqual(sub, formula->r)) { if (isFree) { return 11; } else { throw SubstituteError(formula->l->r, formula->l->l->s, x); } } } else { if (checkEqual(formula->l->r, formula->r)) return 11; } } if (checkFormulaIsSimilarToTemplate2(formula, axioms[12])) { Node *x = getFirstNotBound(formula->l, formula->r->r, formula->r->l->s); if (x) { bool isFree = true; Node *sub = substitute(formula->r->r, formula->r->l->s, x, isFree); if (checkEqual(sub, formula->l)) { if (isFree) { return 12; } else { throw SubstituteError(formula->r->r, formula->r->l->s, x); } } } else { if (checkEqual(formula->r->r, formula->l)) return 12; } } for (int i = 13; i <= 20; i++) { //if (checkFormulaIsSimilarToTemplate(formula, axioms[i], false)) { if (checkEqual(formula, axioms[i])) { return i; } } if (checkFormulaIsSimilarToTemplate2(formula, axioms[21])) { if (checkEqual(formula->r, formula->l->r->r->l)) { const string &x = formula->l->r->l->s; bool isFree = true; Node *sub0 = substitute(formula->r, x, new Node("0", NULL, NULL), isFree); if (checkEqual(sub0, formula->l->l)) { Node *subx = substitute(formula->r, x, new Node("\'", new Node(x, NULL, NULL), NULL), isFree); if (checkEqual(subx, formula->l->r->r->r)) { return 21; } } } } return -1; } bool checkForallRule(Node *v, const vector<Node*> &formulas) { if (v->s == "->" && v->r->s == "@") { Node *toFind = new Node("->", v->l, v->r->r); /* if (checkIsNotFree(v->l, v->r->l->s)) { for (Node *formula : formulas) { if (checkEqual(toFind, formula)) { return true; } } } else { throw VariableFreeError(v->l, v->r->l->s); }*/ for (Node *formula : formulas) { if (checkEqual(toFind, formula)) { if (checkIsNotFree(v->l, v->r->l->s)) { return true; } else { throw VariableFreeError(v->l, v->r->l->s); } } } } return false; } bool checkExistsRule(Node *v, const vector<Node*> &formulas) { if (v->s == "->" && v->l->s == "?") { Node *toFind = new Node("->", v->l->r, v->r); /*if (checkIsNotFree(v->r, v->l->l->s)) { for (Node *formula : formulas) { if (checkEqual(toFind, formula)) { return true; } } } else { throw VariableFreeError(v->r, v->l->l->s); }*/ for (int i = 0; i < formulas.size(); i++) { Node *formula = formulas[i]; if (checkEqual(toFind, formula)) { //if (count==228)cout << formula->getAsString() << "\n" << toFind->getAsString() << "\n" << i + 2 << "\n"; if (checkIsNotFree(v->r, v->l->l->s)) { return true; } else { throw VariableFreeError(v->r, v->l->l->s); } } } } return false; } bool parseTitle(const string &ss, vector<Node*> &supposes, Node *&alpha, Node *&betta) { const string s = getStringWithoutSpaces(ss); for (int i = 0; i < s.length() - 1; i++) { if (s[i] == '|' && s[i+1] == '-') { int ptr = i + 2; betta = parseExpression(s, ptr); if (i == 0) return true; const string t = s.substr(0, i); ptr = 0; while (ptr < t.length()) { Node *expr = parseExpression(t, ptr); if (ptr < t.length() && t[ptr] != ',') throw "bad supposes list"; if (ptr < t.length()) { supposes.push_back(expr); } else { alpha = expr; } ptr++; } return true; } } return false; } bool checkIsSuppose(Node *formula, const vector<Node*> &supposes) { for (Node *suppose : supposes) { if (checkEqual(suppose, formula)) { return true; } } return false; } Node *checkIsModusPonens(Node *formula, const vector<Node*> &formulas) { for (Node *vf : formulas) { if (vf->s == "->" && checkEqual(vf->r, formula)) { for (Node *v : formulas) { if (checkEqual(v, vf->l)) { return v; } } } } return NULL; } bool checkVarIsFreeInFormula(const string &a, Node *v, bool isFree = true) { if (!v) { return false; } if (v->isVariable()) { if (v->s == a) { return isFree; } else { return false; } } for (Node *term : v->terms) { if (checkVarIsFreeInFormula(a, term, isFree)) { return true; } } if (v->s == "@" || v->s == "?") { return checkVarIsFreeInFormula(a, v->r, (v->l->s == a ? false : true) & isFree); } if (checkVarIsFreeInFormula(a, v->l, isFree) || checkVarIsFreeInFormula(a, v->r, isFree)) { return true; } return false; } Node *getAxiom(int number, Node *a = NULL, Node *b = NULL, Node *c = NULL) { return getFormulaFromTemplate(axioms[number], a, b, c); } void getAA(Node *a, vector<Node*> &proof) { proof.push_back(getAxiom(1, a, a)); proof.push_back(getAxiom(1, a, new Node("->", a, a))); proof.push_back(getAxiom(2, a, new Node("->", a, a), a)); proof.push_back(proof.back()->r); proof.push_back(proof.back()->r); } void simpleDeduction( const vector<Node*> &formulas, const vector<Node*> &supposes, Node *alpha, Node *betta, vector<Node*> &proof, int supBegin_ = 0, int supEnd_ = -1, int forBegin_ = 0, int forEnd_ = -1) { if (supEnd_ == -1) { supEnd_ = supposes.size(); } if (forEnd_ == -1) { forEnd_ = formulas.size(); } if (!checkEqual(formulas[forEnd_ - 1], betta)) { throw "Deduction fail : last formula != betta"; } for (int i = forBegin_; i < forEnd_; i++) { Node * expr = formulas[i]; int axiomNumber = checkIsAxiom(expr); int proofStart = proof.size(); if (axiomNumber != -1 || checkIsSuppose(expr, supposes)) { // di proof.push_back(expr); // di -> (a -> di) proof.push_back(getAxiom(1, expr, alpha)); proof.push_back(proof.back()->r); } else if (checkEqual(expr, alpha)) { getAA(alpha, proof); } else { Node *dj = checkIsModusPonens(expr, formulas); if (dj != NULL) { //Node * dk = formulas[mp.second]; // (a -> dj) -> ((a -> (dj -> di))) -> (a -> di) proof.push_back(getAxiom(2, alpha, dj, expr)); // ((a -> (dj -> di))) -> (a -> di) proof.push_back(proof.back()->r); // a -> di proof.push_back(proof.back()->r); } else { cout << "OOPS: " << "\n" << expr->getAsString() << "\n"; throw "there is an error in proof"; } } } } int main() { int counter = 1; Node *formula = NULL; ifstream cin("input.txt"); //ofstream cout("output.txt"); try { init(); vector<Node*> supposes, formulas; vector<Node*> proof; Node *alpha = NULL; Node *betta = NULL; string title; getline(cin, title); bool f = false; for (int i = 0; i < title.size() - 1; i++) { if (title[i] == '|' && title[i+1] == '-') { f = true; } } bool deduction = false; if (f) { deduction = parseTitle(title, supposes, alpha, betta); } else { cin.seekg(0, ios::beg); cin.clear(); } string s; while (getline(cin, s)) { count++; //if (count == 224) { // cout << s << "\n"; //} //if (count == 225) { // cout << s << "\n"; // break; //} //continue; if (s.length() == 0) continue; formula = parseStringToFormula(s); // cout << s << ": "; formulas.push_back(formula); int axiomNumber = -1; axiomNumber = checkIsAxiom(formula); if (axiomNumber != -1) { // cout << "axiom " << axiomNumber << "\n"; if (axiomNumber == 21 && deduction && alpha != NULL) { if (checkVarIsFreeInFormula(formula->l->r->l->s, alpha)) { throw KvantorError("ะฐะบัะธะพะผะฐ", formula->l->r->l->s, alpha); } } if (axiomNumber == 11 && deduction && alpha != NULL) { if (checkVarIsFreeInFormula(formula->l->l->s, alpha)) { throw KvantorError("ะฐะบัะธะพะผะฐ", formula->l->l->s, alpha); } } if (axiomNumber == 12 && deduction && alpha != NULL) { if (checkVarIsFreeInFormula(formula->r->l->s, alpha)) { throw KvantorError("ะฐะบัะธะพะผะฐ", formula->r->l->s, alpha); } } if (deduction && alpha != NULL) { proof.push_back(formula); proof.push_back(getAxiom(1, formula, alpha)); proof.push_back(proof.back()->r); } } else if (deduction && checkIsSuppose(formula, supposes)) { // cout << "suppose" << "\n"; if (alpha != NULL) { proof.push_back(formula); proof.push_back(getAxiom(1, formula, alpha)); proof.push_back(proof.back()->r); } } else if (deduction && checkEqual(formula, alpha)) { // cout << "alpha " << "\n"; getAA(alpha, proof); } else if (checkForallRule(formula, formulas)) { // cout << "forall rule" << "\n"; if (deduction && alpha != NULL) { if (checkVarIsFreeInFormula(formula->r->l->s, alpha)) { throw KvantorError("ะฟั€ะฐะฒะธะปะพ", formula->r->l->s, alpha); } } if (checkVarIsFreeInFormula(formula->r->l->s, formula->l)) { throw VariableFreeError(formula->l, formula->r->l->s); } // if (deduction) { // for (Node *v : supposes) { // if (checkVarIsFreeInFormula(formula->r->l->s, v)) { // throw VariableFreeError(v, formula->r->l->s); // } // } // } if (deduction && alpha != NULL) { vector<Node*> tmpSupposes; vector<Node*> tmpFormulas; vector<Node*> tmpProof; Node *A = alpha; Node *B = formula->l; Node *C = formula->r->r; //////////////////////////////////////////////////// /// A->(B->C), A&B |- C ... tmpSupposes.push_back(new Node("->", A, new Node("->", B, C))); tmpFormulas.push_back(new Node("&", A, B)); tmpFormulas.push_back(getAxiom(4, A, B)); tmpFormulas.push_back(A); tmpFormulas.push_back(getAxiom(5, A, B)); tmpFormulas.push_back(B); tmpFormulas.push_back(tmpSupposes[0]); tmpFormulas.push_back(tmpFormulas.back()->r); tmpFormulas.push_back(tmpFormulas.back()->r); simpleDeduction(tmpFormulas, tmpSupposes, tmpFormulas[0], C, proof); /// ... A&B -> C //////////////////////////////////////////////////// /// A&B -> @xC proof.push_back(new Node("->", tmpFormulas[0], formula->r)); //////////////////////////////////////////////////// /// A&B->@xC,A,B |- @xC ... tmpSupposes.clear(); tmpFormulas.clear(); tmpSupposes.push_back(proof.back()); tmpSupposes.push_back(A); tmpFormulas.push_back(A); tmpFormulas.push_back(B); tmpFormulas.push_back(getAxiom(3, A, B)); tmpFormulas.push_back(tmpFormulas.back()->r); tmpFormulas.push_back(tmpFormulas.back()->r); tmpFormulas.push_back(tmpSupposes[0]); tmpFormulas.push_back(tmpFormulas.back()->r); simpleDeduction(tmpFormulas, tmpSupposes, B, formula->r, tmpProof); /// ... A&B->@xC,A |- B->@xC ... tmpSupposes.pop_back(); simpleDeduction(tmpProof, tmpSupposes, A, tmpProof.back(), proof); /// ... A->B->@xC //////////////////////////////////////////////////// } } else if (checkExistsRule(formula, formulas)) { // cout << "exists rule" << "\n"; if (deduction && alpha != NULL) { if (checkVarIsFreeInFormula(formula->l->l->s, alpha)) { throw KvantorError("ะฟั€ะฐะฒะธะปะพ", formula->l->l->s, alpha); } } if (checkVarIsFreeInFormula(formula->l->l->s, formula->r)) { throw VariableFreeError(formula->r, formula->l->l->s); } // if (deduction) { // for (Node *v : supposes) { // if (checkVarIsFreeInFormula(formula->l->l->s, v)) { // throw VariableFreeError(v, formula->l->l->s); // } // } // } if (deduction && alpha != NULL) { Node *A = alpha; Node *B = formula->l->r; Node *C = formula->r; vector<Node*> tmpSupposes; vector<Node*> tmpFormulas; vector<Node*> tmpProof; /// A->B->C |- B->A->C /// A->B->C, B, A |- C ... tmpSupposes.push_back(new Node("->", A, new Node("->", B, C))); tmpSupposes.push_back(B); tmpFormulas.push_back(A); tmpFormulas.push_back(B); tmpFormulas.push_back(tmpSupposes[0]); tmpFormulas.push_back(tmpFormulas.back()->r); tmpFormulas.push_back(tmpFormulas.back()->r); simpleDeduction(tmpFormulas, tmpSupposes, A, C, tmpProof); /// ... A->B->C, B |- A->C tmpSupposes.pop_back(); simpleDeduction(tmpProof, tmpSupposes, B, new Node("->", A, C), proof); /// ... A->B->C |- B->(A->C) /// ?xB->(A->C) proof.push_back(new Node("->", formula->l, new Node("->", A, C))); //////////////////////////////////////////////////// /// ?xB->(A->C) |- A->(?xB->C) /// ?xB->(A->C), A, ?xB |- C ... tmpSupposes.clear(); tmpFormulas.clear(); tmpSupposes.push_back(proof.back()); tmpSupposes.push_back(A); tmpFormulas.push_back(A); tmpFormulas.push_back(tmpSupposes[0]->l); tmpFormulas.push_back(tmpSupposes[0]); tmpFormulas.push_back(tmpFormulas.back()->r); tmpFormulas.push_back(tmpFormulas.back()->r); simpleDeduction(tmpFormulas, tmpSupposes, tmpSupposes[0]->l, C, tmpProof); /// ... ?xB->(A->C), A |- ?xB->C tmpSupposes.pop_back(); simpleDeduction(tmpProof, tmpSupposes, A, formula, proof); /// ... A->(?xB->C) //////////////////////////////////////////////////// } } else { Node *v = checkIsModusPonens(formula, formulas); if (v != NULL) { // cout << "modus ponens" << "\n"; if (deduction && alpha != NULL) { proof.push_back(getAxiom(2, alpha, v, formula)); proof.push_back(proof.back()->r); proof.push_back(proof.back()->r); } } else { // cout << "uknown stuff" << "\n"; throw UnknownError(); } } if (!deduction || !alpha) { // cerr << "?????\n"; proof.push_back(formula); } counter++; } for (Node *formula : proof) { cout << formula->getAsString() << "\n"; } } catch (const SubstituteError &e) { cout << "ะ’ั‹ะฒะพะด ะฝะตะบะพั€ั€ะตะบั‚ะตะฝ ะฝะฐั‡ะธะฝะฐั ั ั„ะพั€ะผัƒะปั‹ " << counter << ": "; cout << "ั‚ะตั€ะผ " << e.x->getAsString() << " ะฝะต ัะฒะพะฑะพะดะตะฝ ะดะปั ะฟะพะดัั‚ะฐะฝะพะฒะบะธ ะฒ ั„ะพั€ะผัƒะปัƒ " << e.y->getAsString() << " ะฒะผะตัั‚ะพ ะฟะตั€ะตะผะตะฝะฝะพะน " << e.a << ".\n"; } catch (const VariableFreeError &e) { cout << "ะ’ั‹ะฒะพะด ะฝะตะบะพั€ั€ะตะบั‚ะตะฝ ะฝะฐั‡ะธะฝะฐั ั ั„ะพั€ะผัƒะปั‹ " << counter << ": "; cout << "ะฟะตั€ะตะผะตะฝะฝะฐั " << e.a << " ะฒั…ะพะดะธั‚ ัะฒะพะฑะพะดะฝะพ ะฒ ั„ะพั€ะผัƒะปัƒ " << e.x->getAsString() << ".\n"; } catch (const KvantorError &e) { cout << "ะ’ั‹ะฒะพะด ะฝะตะบะพั€ั€ะตะบั‚ะตะฝ ะฝะฐั‡ะธะฝะฐั ั ั„ะพั€ะผัƒะปั‹ " << counter << ": "; cout << "ะธัะฟะพะปัŒะทัƒะตั‚ัั " << e.type << " ั ะบะฒะฐะฝั‚ะพั€ะพะผ ะฟะพ ะฟะตั€ะตะผะตะฝะฝะพะน " << e.a << ", ะฒั…ะพะดัั‰ะตะน ัะฒะพะฑะพะดะฝะพ ะฒ ะดะพะฟัƒั‰ะตะฝะธะต " << e.x->getAsString() << ".\n"; } catch (const UnknownError &e) { cout << "ะ’ั‹ะฒะพะด ะฝะตะบะพั€ั€ะตะบั‚ะตะฝ ะฝะฐั‡ะธะฝะฐั ั ั„ะพั€ะผัƒะปั‹ " << counter << ".\n"; } catch (const char *c) { cout << c << "\n"; } // cout << "Finish\n"; return 0; }
[ "alexchekmenev@mail.ru" ]
alexchekmenev@mail.ru
8e1d3ff557e5b75983781c9074ee616bc1e10c73
3e70eda6819fec5bf5ba2299573b333a3a610131
/gf/gongfu_online/tools/reload/reload.cpp
d4e0929bdf5d60a7ef1b7b10c413a4919c6a1a64
[]
no_license
dawnbreaks/taomee
cdd4f9cecaf659d134d207ae8c9dd2247bef97a1
f21b3633680456b09a40036d919bf9f58c9cd6d7
refs/heads/master
2021-01-17T10:45:31.240038
2013-03-14T08:10:27
2013-03-14T08:10:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,942
cpp
#include <cerrno> #include <cstdio> #include <cstring> #include <libtaomee++/inet/pdumanip.hpp> extern "C" { #include <libtaomee/inet/mcast.h> #include <stdlib.h> #include <unistd.h> #include <getopt.h> #include <arpa/inet.h> } #include "mcast_proto.hpp" #include "reload_conf.hpp" #include "reload.hpp" static char proc_param[] = "[-v] [-h] [[-0...] [mcast / server_id(1, 2, ...)]]"; static char mcast_ip[16]; static char out_mcast_ip[] = "239.0.0.241"; static char in_mcast_ip[] = "239.0.0.241"; static uint16_t mcast_port = 8888; static char cmd_str_buf[128]; static char sendbuf[1024]; static int is_inner; /* 0: inner, 1: outer */ struct mcast_info_t { int mcast_fd; struct sockaddr_in mcast_addr; } mcast_info; static struct option long_options[] = { {"item", 1, 0, '0'}, {"btl", 1, 0, '1'}, {"daily", 1, 0, '2'}, {"task", 1, 0, '3'}, {"stage", 1, 0, '4'}, {"swap_action", 1, 0, '5'}, {"active data", 1, 0, '6'}, {"restriction", 1, 0, '7'}, {"bench", 1, 0, '8'}, {"btl_svr", 1, 0, '9'}, {"mon_bonus", 1, 0, 'a'}, {"exchange", 1, 0, 'b'}, {"evolve", 1, 0, 'c'}, {"hero_tower", 1, 0, 'd'}, {"nono", 1, 0, 'e'}, {"team_pk", 1, 0, 'f'}, {"help", 0, 0, 'h'}, {"version", 0, 0, 'v'}, }; long get_target_id(char* id_str) { char* endptr = 0; long val; errno = 0; val = strtol(id_str, &endptr, 10); if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN)) || (errno != 0 && val == 0)) { perror("strtol"); exit(EXIT_FAILURE); } if (endptr == id_str) { fprintf(stderr, "No digits were found\n"); exit(EXIT_FAILURE); } /* something uncenssary in the id_str, which is not safe condition... */ if (*endptr != '\0') { fprintf(stderr, "Further characters after number: %s\n", endptr); exit(EXIT_FAILURE); } /* val == 0 is not allowed when single reloading */ if (!val) { fprintf(stderr, "target_id == 0 is not allowed when single reloading\n"); exit(EXIT_FAILURE); } return val; } inline char* cmd_string(uint32_t cmd) { memset(cmd_str_buf, 0, sizeof(cmd_str_buf)); sprintf(cmd_str_buf, "reload_%s_config_cmd", long_options[cmd - 1].name); return cmd_str_buf; } int make_sockaddr(char* ip, uint16_t port, sockaddr_in* addr) { addr->sin_family = AF_INET; if (inet_pton(AF_INET, ip, &(addr->sin_addr)) != 1) return -1; if (port > 65535) return -1; addr->sin_port = htons(port); return 0; } void init_reload_pkg(mcast_pkg_t* pkg, uint32_t minor_cmd) { pkg->main_cmd = mcast_reload_conf; pkg->minor_cmd = minor_cmd; pkg->server_id = 0; /* mcast pkg_head id */ } int init_mcast_ip(void) { FILE *fp = NULL; /* try test evn */ fp = fopen("../../bench.conf", "r"); if (fp) { is_inner = 0; fclose(fp); memset(mcast_ip, 0, sizeof(mcast_ip)); memcpy(mcast_ip, in_mcast_ip, sizeof(in_mcast_ip)); printf("mcast_ip:\"%s\"\n", mcast_ip); return 0; } fp = fopen("../OnlineA/bench.conf", "r"); if (fp) { is_inner = 1; fclose(fp); memset(mcast_ip, 0, sizeof(mcast_ip)); memcpy(mcast_ip, out_mcast_ip, sizeof(out_mcast_ip)); return 0; } fp = fopen("../homeA/bench.conf", "r"); if (fp) { is_inner = 1; fclose(fp); memset(mcast_ip, 0, sizeof(mcast_ip)); memcpy(mcast_ip, out_mcast_ip, sizeof(out_mcast_ip)); return 0; } return -1; } void reload_config(char* id_str, char* mip, uint16_t port, uint32_t cmd) { printf("reload_config\n"); memset(sendbuf, 0, sizeof(sendbuf)); mcast_pkg_t* pkg = reinterpret_cast<mcast_pkg_t *>(sendbuf); struct sockaddr_in* addr = &(mcast_info.mcast_addr); int mcast_fd = mcast_info.mcast_fd; init_reload_pkg(pkg, cmd); int idx = sizeof(mcast_pkg_t); uint32_t target_id = 0; if (strcmp(id_str, "mcast")) target_id = get_target_id(id_str); taomee::pack_h(sendbuf, target_id, idx); printf("mcast_ip:\"%s\", port=%u, cmd=%s, target_id=%u\n", mip, port, cmd_string(cmd), target_id); int err = sendto(mcast_fd, sendbuf, idx, 0, reinterpret_cast<sockaddr*>(addr), sizeof(*addr)); if (err == -1) { perror("send faild!"); } } int make_mcast_sock() { mcast_info.mcast_fd = socket(AF_INET, SOCK_DGRAM, 0); struct sockaddr_in* mcast_addr = &(mcast_info.mcast_addr); mcast_set_if(mcast_info.mcast_fd, AF_INET, "eth1"); memset(mcast_addr, 0, sizeof(*mcast_addr)); if (make_sockaddr(mcast_ip, mcast_port, mcast_addr) < 0) { printf("invalid mcast addr: ip=\"%s\", port=%u\n",mcast_ip, mcast_port); fprintf(stderr, "invalid mcast addr: ip=\"%s\", port=%u\n", mcast_ip, mcast_port); return -1; } printf("mcast addr: ip=\"%s\", port=%u\n",mcast_ip, mcast_port); return mcast_info.mcast_fd; } int main(int argc, char* argv[]) { int c; if (argc == 1) { print_desc(); print_usage(argv, proc_param); print_ver(); exit(EXIT_SUCCESS); } if (init_mcast_ip() < 0) { fprintf(stderr, "cannot determine is inner or outer\n"); exit(EXIT_FAILURE); } memset(&mcast_info, 0, sizeof(mcast_info)); if (make_mcast_sock() < 0) exit(EXIT_FAILURE); while (1) { int option_index = 0; c = getopt_long(argc, argv, "0:1:2:3:4:5:6:7:8:9:a:b:c:d:e:f:vh", long_options, &option_index); printf("c=[%c%d]\n",c,c); if (c == -1) break; switch (c) { case '1': reload_config(optarg, mcast_ip, mcast_port, reload_item_config_cmd); break; case '2': reload_config(optarg, mcast_ip, mcast_port, reload_battle_config_cmd); break; case '3': reload_config(optarg, mcast_ip, mcast_port, reload_daily_activity_cmd); break; case '4': reload_config(optarg, mcast_ip, mcast_port, reload_task_cmd); break; case '5': reload_config(optarg, mcast_ip, mcast_port, reload_active_stage_cmd); break; case '6': reload_config(optarg, mcast_ip, mcast_port, reload_swap_action_cmd); break; case '7': reload_config(optarg, mcast_ip, mcast_port, reload_active_data_cmd); break; /* case '7': reload_config(optarg, mcast_ip, mcast_port, reload_restriction_config_cmd); break; case '8': reload_config(optarg, mcast_ip, mcast_port, reload_bench_config_cmd); break; case '9': reload_config(optarg, mcast_ip, mcast_port, reload_btl_svr_config_cmd); break; case 'a': reload_config(optarg, mcast_ip, mcast_port, reload_mon_bonus_config_cmd); break; case 'b': reload_config(optarg, mcast_ip, mcast_port, reload_exchange_config_cmd); break; case 'c': reload_config(optarg, mcast_ip, mcast_port, reload_cond_evolves_config_cmd); break; case 'd': reload_config(optarg, mcast_ip, mcast_port, reload_hero_tower_config_cmd); break; case 'e': reload_config(optarg, mcast_ip, mcast_port, reload_nono_config_cmd); break; case 'f': reload_config(optarg, mcast_ip, mcast_port, reload_team_pk_config_cmd); break; case 'h': print_usage(argv, proc_param); break; case 'v': print_ver(); break; case '?': break;*/ default: /* unsupported options */ printf("?? getopt returned character code 0%o ??\n", c); } } close(mcast_info.mcast_fd); exit(EXIT_SUCCESS); }
[ "smyang.ustc@gmail.com" ]
smyang.ustc@gmail.com
80d0fa47180b2fbed0c452366974b4ba1c457912
59d14a561e7792498196c32e1c19517b7b8731f8
/sb_gen.cpp
4eb5c3db03958b1d410c1d3cdef663f1f315e559
[]
no_license
xuzijian629/gkmeans
549609f11198ccc9d1008acb183d8e1fee1b55fe
1278fd16e4af2e2a7e9f70fbb0a6ea0f94f15879
refs/heads/master
2020-04-19T09:28:08.846725
2019-01-31T23:55:36
2019-02-01T00:04:08
168,112,020
0
0
null
null
null
null
UTF-8
C++
false
false
3,114
cpp
#include "gkmeans/graph.hpp" struct UnionFind { int n, cnt; vector<int> par, rank, sz; UnionFind(int n) : n(n), cnt(n), par(n), rank(n), sz(n, 1) { iota(par.begin(), par.end(), 0); } int find(int x) { if (x == par[x]) return x; return par[x] = find(par[x]); } bool same(int x, int y) { return find(x) == find(y); } int size(int x) { return sz[find(x)]; } void unite(int x, int y) { x = find(x), y = find(y); if (x == y) return; if (rank[x] < rank[y]) { par[x] = y; sz[y] += sz[x]; } else { par[y] = x; sz[x] += sz[y]; if (rank[x] == rank[y]) { rank[x]++; } } cnt--; } }; // ๅค‰ๆ•ฐใฏใƒ–ใƒญใƒƒใ‚ฏใฎๅ€‹ๆ•ฐใ€ๅ„ใƒ–ใƒญใƒƒใ‚ฏใฎใ‚ตใ‚คใ‚บใ€ใƒ–ใƒญใƒƒใ‚ฐๅ†…ๅฏ†ๅบฆใ€ใƒ–ใƒญใƒƒใ‚ฏ้–“ๅฏ†ๅบฆใ€ใƒ–ใƒญใƒƒใ‚ฏๅ†…ใฎ่พบใฎ้‡ใฟใ€ใƒ–ใƒญใƒƒใ‚ฏ้–“ใฎ่พบใฎ้‡ใฟ Graph gen_block_model(int block_num, vector<int> block_sizes, double in_density, double out_density, double in_w, double out_w, bool use_adj_mat = false) { assert(block_num == block_sizes.size()); int n = accumulate(block_sizes.begin(), block_sizes.end(), 0); vector<int> label(n); { int i = 0; for (int j = 0; j < block_num; j++) { for (int k = 0; k < block_sizes[j]; k++) { label[i++] = j; } } } Graph g(n, use_adj_mat); UnionFind uf(n); random_device rnd; mt19937 eng(rnd()); uniform_real_distribution<> ur(0, 1); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (label[i] == label[j]) { if (ur(eng) < in_density) { g.add_edge(i, j, in_w); uf.unite(i, j); } } else { if (ur(eng) < out_density) { g.add_edge(i, j, out_w); uf.unite(i, j); } } } } // assert connected assert(uf.cnt == 1); return g; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cout.setf(ios::fixed); cout.precision(10); int K; cin >> K; vector<int> block_sizes(K); for (int i = 0; i < K; i++) { cin >> block_sizes[i]; } double in_density, out_density, in_w, out_w; cin >> in_density >> out_density >> in_w >> out_w; string id = ""; for (int s : block_sizes) { id += "_" + to_string(s); } assert(freopen(("data/sbm" + id).substr(0, min(8 + int(id.size()), 100)).c_str(), "w", stdout)); cout << block_sizes.size() << '\n'; for (int s : block_sizes) { cout << s << ' '; } cout << '\n'; cout << in_density << ' ' << out_density << ' ' << in_w << ' ' << out_w << '\n'; cerr << "start generating graph " + id + "..." << endl; Graph g = gen_block_model(block_sizes.size(), block_sizes, in_density, out_density, in_w, out_w); cerr << "printing graph..." << endl; g.print(); }
[ "xuzijian@g.ecc.u-tokyo.ac.jp" ]
xuzijian@g.ecc.u-tokyo.ac.jp
aa71abf392fa7e4cfe8349e97da49b2f6fd9a9f2
c7d7ec41c7601f7f810cd825465dae573c945f76
/horas_trabajadas2.cpp
9f462c24ebeb669620f881e78512ab1db3444cc9
[]
no_license
Gerardouz/programas-c-
d48da8861b5e9176abec599c5de94ad097684056
e6e7682d9aabba45c8493b98d462e6deccbf14cb
refs/heads/master
2021-07-25T21:40:35.487821
2017-11-09T01:32:02
2017-11-09T01:32:02
68,869,507
1
0
null
null
null
null
UTF-8
C++
false
false
1,105
cpp
#include<iostream> using namespace std; int main(){ float horas_trabajadas=0,costo_hora=0,dinero_ganado=0; int cantidad_empleados; cout<<"introduzca la cantidad de empleados a calcular el salario"<<endl; cin>>cantidad_empleados; for (int i=1;i<=cantidad_empleados;i++) { cout<<"introduzca las horas trabajadas"<<endl; cin>>horas_trabajadas; cout<<"introduzca el costo por hora"<<endl; cin>>costo_hora; if (horas_trabajadas>=0 && horas_trabajadas<=40) { dinero_ganado=(costo_hora*horas_trabajadas); cout<<"la cantidad de dinero que se recibira es "<<dinero_ganado<<endl; } else { if (horas_trabajadas>40 && horas_trabajadas<=48) { dinero_ganado=(costo_hora*40)+(horas_trabajadas-40)*(costo_hora*2); cout<<"la cantidad de dinero que se recibira es "<<dinero_ganado<<endl; } else { if (horas_trabajadas>48) { dinero_ganado=(costo_hora*40)+8*(costo_hora*2)+(horas_trabajadas-48)*(costo_hora*3); cout<<"la cantidad de dinero que se recibira es "<<dinero_ganado<<endl; } else { cout<<"Error"<<endl; } } } } }
[ "noreply@github.com" ]
noreply@github.com
8f392dfc465a924ed529498ad9a331125a474a41
24428e18296300212ca28250208dc7f946542e3b
/Linked List/reversedoublelist.cpp
3935eadfc3ea8cee8327927b65be169db105c397
[]
no_license
Kunal1701/My-Codes
134b21fde6a45816d37a55743ea37a674a5c2ca8
27a81ebdc5c6c79ee9f3f43865803c9195c9d0e7
refs/heads/main
2023-08-29T17:29:26.503621
2021-11-11T15:54:35
2021-11-11T15:54:35
388,391,672
0
0
null
null
null
null
UTF-8
C++
false
false
1,639
cpp
#include <iostream> using namespace std; struct node { node *prev; int data; node *next; }; node *head = NULL; node *addtoempty(node *head, int x) { node *temp = new node(); temp->data = x; temp->next = NULL; temp->prev = NULL; head = temp; return head; } node *addatend(node *head, int x) { node *temp = new node(); temp->data = x; temp->next = NULL; temp->prev = NULL; node *tp; tp = head; while (tp->next != NULL) { tp = tp->next; } tp->next = temp; temp->prev = tp; return head; } void print() { node *temp = head; cout << "List is -> "; while (temp != NULL) { cout << temp->data << " "; temp = temp->next; } } node *createlist(node *head) { int n, data; cout << "enter the number of nodes" << endl; cin >> n; if (n == 0) { return head; } cout << "Enter data for 1 node" << endl; cin >> data; head = addtoempty(head, data); for (int i = 1; i < n; i++) { cout << "Enter data for " << i + 1 << " node" << endl; cin >> data; head = addatend(head, data); } return head; } node *reverse(node *head) { node *ptr1 = head; node *ptr2 = head->next; ptr1->next = NULL; ptr1->prev = ptr2; while (ptr2 != NULL) { ptr2->prev = ptr2->next; ptr2->next = ptr1; ptr1 = ptr2; ptr2 = ptr2->prev; } head = ptr1; return head; } int main() { head = createlist(head); print(); cout << endl; head = reverse(head); print(); cout << endl; return 0; }
[ "noreply@github.com" ]
noreply@github.com
fb845df4d46ef4851b25e6931e70c066e596d7fa
9e3408b7924e45aa851ade278c46a77b3a85614e
/CHIBI-Engine/Externals/boost/mpl/minus.hpp
f272f948d1a672955fc0cad9c3208b2f0eae9469
[]
no_license
stynosen/CHIBI-Engine
542a8670bbcd932c0fd10a6a04be3af2eb3991f4
6a1b41e94df2e807e9ce999ce955bf19bb48c8ec
refs/heads/master
2021-01-25T06:37:16.554974
2014-01-08T21:49:00
2014-01-08T21:49:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
618
hpp
#ifndef BOOST_MPL_MINUS_HPP_INCLUDED #define BOOST_MPL_MINUS_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2000-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: minus.hpp 49239 2008-10-10 09:10:26Z agurtovoy $ // $Date: 2008-10-10 11:10:26 +0200 (vr, 10 okt 2008) $ // $Revision: 49239 $ #define AUX778076_OP_NAME minus #define AUX778076_OP_TOKEN - #include <boost/mpl/aux_/arithmetic_op.hpp> #endif // BOOST_MPL_MINUS_HPP_INCLUDED
[ "stijndoyen@hotmail.com" ]
stijndoyen@hotmail.com
aaff5c013dcfead2166f236f5d84f4f3667d3681
78918391a7809832dc486f68b90455c72e95cdda
/boost_lib/boost/range/algorithm/rotate_copy.hpp
6217195ef7718f8d133dcfb2ff32e085bb41c739
[ "MIT" ]
permissive
kyx0r/FA_Patcher
50681e3e8bb04745bba44a71b5fd04e1004c3845
3f539686955249004b4483001a9e49e63c4856ff
refs/heads/master
2022-03-28T10:03:28.419352
2020-01-02T09:16:30
2020-01-02T09:16:30
141,066,396
2
0
null
null
null
null
UTF-8
C++
false
false
1,354
hpp
// Copyright Neil Groves 2009. Use, modification and // distribution is subject to 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) // // // For more information, see http://www.boost.org/libs/range/ // #ifndef BOOST_RANGE_ALGORITHM_ROTATE_COPY_HPP_INCLUDED #define BOOST_RANGE_ALGORITHM_ROTATE_COPY_HPP_INCLUDED #include <boost/concept_check.hpp> #include <boost/range/begin.hpp> #include <boost/range/end.hpp> #include <boost/range/concepts.hpp> #include <boost/range/iterator.hpp> #include <algorithm> namespace boost { namespace range { /// \brief template function rotate /// /// range-based version of the rotate std algorithm /// /// \pre Rng meets the requirements for a Forward range template<typename ForwardRange, typename OutputIterator> inline OutputIterator rotate_copy( const ForwardRange& rng, BOOST_DEDUCED_TYPENAME range_iterator<const ForwardRange>::type middle, OutputIterator target ) { BOOST_RANGE_CONCEPT_ASSERT(( ForwardRangeConcept<const ForwardRange> )); return std::rotate_copy(boost::begin(rng), middle, boost::end(rng), target); } } // namespace range using range::rotate_copy; } // namespace boost #endif // include guard
[ "k.melekhin@gmail.com" ]
k.melekhin@gmail.com
8e56cd23ea44495fc7c5523e5c89faebe2661163
467777ca6ea60429606fb9bb01ec0c311b09bc65
/Lab 3/Lab3_2d/Lab3_2d.ino
8452d133627e15f4ddee58e0aca62c6f6273b22b
[]
no_license
LuisAfonso95/Energia-workshop-with-Educational-Boosterpack-Mk-II
755c9dc3d4a8fa6bb618cc3e1f8571603b6d5555
cace0ed8186a63ae81fd72caae0a6903f316216f
refs/heads/master
2021-01-10T16:56:38.449110
2016-02-12T12:39:51
2016-02-12T12:39:51
47,903,752
0
1
null
null
null
null
UTF-8
C++
false
false
1,304
ino
/* Resolution for Lab 3, 2.d) for the Energia workshop with Educational Boosterpack Mk II by Luรญs Afonso Made in 22/12/2015 by Luรญs Afonso */ #define LED 39 //Varible that controls the delay. Default value 1000. int Time1=1000; int Time2=1000; //addition from 2.c) void setup() { pinMode(LED, OUTPUT); Serial.begin(9600); } void loop() { /* If there are chars in the buffer the first integer will be store in "Time" Note that if there is no number in the string received, the value returned will be 0 This time you should always send the 2 numbers in the same string Ex: "1000 50" or "1000 abcd 50" If you don't send 2 numbers then time2 will be 0. */ while( Serial.available() > 0){ /* Store values of Time1 and Time2 in case they are set to 0. */ int Time1_temp = Time1; int Time2_temp = Time2; Time1 = Serial.parseInt(); Time2 = Serial.parseInt(); //If Time1 is 0 then return to previous value if(Time1 == 0) Time1=Time1_temp; //If Time2 is 0 then return to previous value if(Time2 == 0) Time2 = Time2_temp; } digitalWrite(LED, HIGH); delay(Time1); digitalWrite(LED, LOW); delay(Time2); //change from 2.c) }
[ "luis.r.afonso@gmail.com" ]
luis.r.afonso@gmail.com
3180a62b60c7136d83bf509b02dda46d79898615
9e7afe972cbd86c8960a882920d54a4c25e6e4fa
/src/mqtt_api.cc
fee78a7881cf52687f363f7ee477a91dfd3abe8b
[ "MIT" ]
permissive
eranws/wavplayeralsa
dab8d83c728c9d210f0d375374d915895fc2f2ea
b219cf5d3377ac78ea82674d57ace3306cc39660
refs/heads/master
2023-03-16T08:34:50.967614
2020-10-15T19:04:45
2020-10-15T19:04:45
528,945,973
1
0
null
2022-08-25T17:09:44
2022-08-25T17:09:44
null
UTF-8
C++
false
false
2,341
cc
#include "mqtt_api.h" #include <iostream> #include <functional> #include <boost/date_time/time_duration.hpp> namespace wavplayeralsa { MqttApi::MqttApi(boost::asio::io_service &io_service) : io_service_(io_service), reconnect_timer_(io_service) { } void MqttApi::Initialize(std::shared_ptr<spdlog::logger> logger, const std::string &mqtt_host, uint16_t mqtt_port) { // set class members logger_ = logger; const char *mqtt_client_id = "wavplayeralsa"; logger_->info("creating mqtt connection to host {} on port {} with client id {}", mqtt_host, mqtt_port, mqtt_client_id); logger_->info("will publish current song updates on topic {}", CURRENT_SONG_TOPIC); mqtt_client_ = mqtt::make_sync_client(io_service_, mqtt_host, mqtt_port); mqtt_client_->set_client_id(mqtt_client_id); mqtt_client_->set_clean_session(true); mqtt_client_->set_error_handler(std::bind(&MqttApi::OnError, this, std::placeholders::_1)); mqtt_client_->set_close_handler(std::bind(&MqttApi::OnClose, this)); mqtt_client_->set_connack_handler(std::bind(&MqttApi::OnConnAck, this, std::placeholders::_1, std::placeholders::_2)); mqtt_client_->connect(); } void MqttApi::ReportCurrentSong(const std::string &json_str) { last_status_msg_ = json_str; PublishCurrentSong(); } void MqttApi::OnError(boost::system::error_code ec) { logger_->error("client disconnected from mqtt server. will try reconnect in {} ms", RECONNECT_WAIT_MS); reconnect_timer_.expires_from_now(boost::posix_time::milliseconds(RECONNECT_WAIT_MS)); reconnect_timer_.async_wait( [this] (boost::system::error_code ec) { if (ec != boost::asio::error::operation_aborted) { mqtt_client_->connect(); } }); } void MqttApi::OnClose() { logger_->error("client connection to mqtt server is closed"); } bool MqttApi::OnConnAck(bool session_present, std::uint8_t connack_return_code) { logger_->info("connack handler called. clean session: {}. coonack rerturn code: {}", session_present, mqtt::connect_return_code_to_str(connack_return_code)); PublishCurrentSong(); return true; } void MqttApi::PublishCurrentSong() { if(!this->mqtt_client_) return; if(last_status_msg_.empty()) return; this->mqtt_client_->publish_exactly_once(CURRENT_SONG_TOPIC, last_status_msg_, true); } }
[ "amirgiraffe@gmail.com" ]
amirgiraffe@gmail.com
4cf413670007b2cc63e17f928417d6dc4c189780
0b7f95a5a66eaa35738cd4e6b553e49175301959
/Source/System/Core/Utility/CoreDef.hpp
278db44404c1113556b8093a1582d471d0a7d95f
[ "MIT", "LicenseRef-scancode-public-domain" ]
permissive
arian153/Engine5th
f993b45122de49e305e698f44ac9be4e2462a003
34f85433bc0a74a7ebe7da350d3f3698de77226e
refs/heads/master
2021-11-19T20:09:20.716035
2021-09-04T05:59:27
2021-09-04T05:59:27
219,928,073
1
0
null
null
null
null
UTF-8
C++
false
false
1,197
hpp
#pragma once #include <locale> namespace Engine5 { using U8 = uint8_t; using U16 = uint16_t; using U32 = uint32_t; using U64 = uint64_t; using I8 = int8_t; using I16 = int16_t; using I32 = int32_t; using I64 = int64_t; using R32 = float; using R64 = double; using String = std::string; using WString = std::wstring; namespace Core { constexpr R32 R32_MIN = 1.175494351e-38F; constexpr R32 R32_MAX = 3.402823466e+38F; constexpr R64 R64_MIN = 2.2250738585072014e-308; constexpr R64 R64_MAX = 1.7976931348623158e+308; constexpr U8 U8_MAX = 0xffui8; constexpr U16 U16_MAX = 0xffffui16; constexpr U32 U32_MAX = 0xffffffffui32; constexpr U64 U64_MAX = 0xffffffffffffffffui64; constexpr I8 I8_MIN = (-127i8 - 1); constexpr I8 I8_MAX = 127i8; constexpr I16 I16_MIN = -32767i16 - 1; constexpr I16 I16_MAX = 32767i16; constexpr I32 I32_MIN = (-2147483647i32 - 1); constexpr I32 I32_MAX = 2147483647i32; constexpr I64 I64_MIN = (-9223372036854775807i64 - 1); constexpr I64 I64_MAX = 9223372036854775807i64; } }
[ "p084111@gmail.com" ]
p084111@gmail.com
372f0be126eb7c1269769c54828b3a5aa398c974
7fc072fd4c80b83fb964f545879a15d0974a79a8
/esp32_fpga-downloader/main/spartan-edge-esp32-boot.cpp
a01bbbb8b6afb823b2aa4c6aa7ae7f90e1ac7d9c
[]
no_license
Lmorales45/BSpartan
f8cbf3931d42595f5c2de6e9c9ea1d7175cf767e
485b44827a36611b9645ac56b3b84cfb9b619323
refs/heads/main
2023-01-19T23:57:17.060915
2020-11-16T10:25:56
2020-11-16T10:25:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,982
cpp
#include <Arduino.h> #include <HardwareSerial.h> #include "spartan-edge-esp32-boot.h" void spartan_edge_esp32_boot::xfpgaGPIOInit(void) { // GPIO Initialize pinMode(XFPGA_INTB_PIN, INPUT); pinMode(XFPGA_DONE_PIN, INPUT); pinMode(XFPGA_PROGRAM_PIN, OUTPUT); // FPGA configuration start sign digitalWrite(XFPGA_PROGRAM_PIN, LOW); pinMode(XFPGA_CCLK_PIN, OUTPUT); digitalWrite(XFPGA_CCLK_PIN, LOW); digitalWrite(XFPGA_PROGRAM_PIN, HIGH); // wait until fpga reports reset complete while (digitalRead(XFPGA_INTB_PIN) == 0) {} this->first_run = true; this->success = 0; } int spartan_edge_esp32_boot::xlibsSstream(const unsigned char *byte_buff, int buf_len) { int buf_pos = 0; // init if (first_run) { // find the raw bits if (byte_buff[0] != 0xff) { // skip header buf_pos = ((byte_buff[0] << 8) | byte_buff[1]) + 4; // find the 'e' record while (byte_buff[buf_pos] != 0x65) { // skip the record buf_pos += (byte_buff[buf_pos+1] << 8 | byte_buff[buf_pos+2]) + 3; // exit if the next record isn't within the buffer if (buf_pos >= buf_len) return -1; } // skip the field name and bitstrem length buf_pos += 5; } // else it's already a raw bin file // put pins down for Configuration pinMode(XFPGA_DIN_PIN, OUTPUT); first_run = false; } for ( ; buf_pos < buf_len; buf_pos++) send_byte(byte_buff[buf_pos]); } void spartan_edge_esp32_boot::finish() { digitalWrite(XFPGA_CCLK_PIN, LOW); // check the result if (0 == digitalRead(XFPGA_DONE_PIN)) { Serial.println("FPGA Configuration Failed"); } else { Serial.println("FPGA Configuration success"); this->success = 1; } } void spartan_edge_esp32_boot::send_byte(unsigned char byte) { for (int j = 0;j < 8;j++) { digitalWrite(XFPGA_CCLK_PIN, LOW); digitalWrite(XFPGA_DIN_PIN, (byte&0x80)?HIGH:LOW); byte = byte << 1; digitalWrite(XFPGA_CCLK_PIN, HIGH); } } int spartan_edge_esp32_boot::was_successfull() { return this->success; }
[ "marcohartmann95@gmail.com" ]
marcohartmann95@gmail.com
49fb6a3997fea2e331b7cb48303317cc214d54b6
3b80d69b2efb23a2588327c19d9a26d743b6ac6f
/Test.cpp
483a89ae39dec0b1be9066b4e4086e65a8b9925a
[]
no_license
Sachyyy/cpp_training
c73f293bee43051d67f3804c352e097e58f66265
07b2dfbf9980f7d11408645ee9dda26fe54bc52c
refs/heads/master
2021-07-07T01:31:23.757993
2017-09-28T16:53:57
2017-09-28T16:53:57
105,049,011
0
0
null
null
null
null
UTF-8
C++
false
false
706
cpp
// Test.cpp : Defines the entry point for the console application. // // This is my test code // This repo will be used to write test codes. #include "stdafx.h" #include <iostream> #include <thread> #include <memory> using namespace std; void prints() { int i = 0; while (i < 4) { cout << "printing sachith" << endl; this_thread::sleep_for(2s); i++; } } void printm() { int i = 0; while (i < 3) { cout << "printing mandy" << endl; this_thread::sleep_for(2s); i++; } } int main() { cout << "printing main1" << endl; std::thread t1(prints); t1.join(); cout << "printing main2" << endl; std::thread t2(printm); t2.join(); cout << "printing main3" << endl; return 0; }
[ "jayawarna@gmail.com" ]
jayawarna@gmail.com
beb67582c57cb427da0878b9f7f1ed0b6aacf28a
a16e03ae342f4c60af559294b495b4239e99934e
/1_fundament/pointer_cast/static_cast.cpp
c9c9138591bcb84539a5417939f0155e1fb673f5
[]
no_license
lihailihai/C_plus_plus_Primer
2bdd92a61650a8ebebdf0316d939935f3ac26327
7c5c97a5bac62f102aa6a84b740a9c1a304885ce
refs/heads/master
2020-09-14T09:34:57.841458
2019-11-30T12:17:05
2019-11-30T12:17:05
223,091,786
0
0
null
null
null
null
UTF-8
C++
false
false
1,914
cpp
#if 0 #include <iostream> using namespace std; class A{ public: A(){ cout<<"Iside class A"<<endl; double a = 9.8831; int i = static_cast<int>(a); cout<<"i = "<<i<<endl; } void Test(){ cout<<"Inside class A Test()"<<endl; char c = 'C'; int j = static_cast<int>(c); cout<<"j = "<< j <<endl; } ~A(){} }; class B :public A{ public: B(){ cout<<"Inside class B"<<endl; } B(const A*){ } }; class C{ public: C(){ cout<<"Inside class C"<<endl; } ~C(){ } }; int main(){ //basic data type casting. float a = 2.3456; double b = 4.56789; char ch = 'a'; int c = static_cast<int>(a); int d = static_cast<int>(b); int e = static_cast<int>(ch); cout<<"float convert into int:"<<a<<"->"<<c<<endl; cout<<"double convert into int:"<<b<<"->"<<d<<endl; cout<<"char convert into int:"<<ch<<"->"<<e<<endl; char c1 = static_cast<char>(98); float c2 = static_cast<float>(4); double c3 = static_cast<double>(4); cout<<"int convert into char:"<<98<<"->"<<c1<<endl; cout<<"int convert into float:"<<4<<"->"<<c2<<endl; cout<<"int convert into double:"<<4<<"->"<<c3<<endl; const float w1 = 10.0; const int w2 = 3; int w3 = 9; // demostration that static_cast not satisfied with parameter of const-attribute. // w2 = static_cast<const int>(w1); // cout<<"w2 = "<<w2<<endl; // w2 = static_cast<const int>(w3); // cout<<"w3 = "<<w3<<endl; // //objection data type casting A* a_sample = new A, *a_sample2; B* b_sample, *b_sample2 = new B; C* c_sample; b_sample = static_cast<B*>(a_sample); //inheritance relationship from parent class to subclass which complied is ok in this case. HINT: it's not always right! b_sample->Test(); a_sample2 = static_cast<A*>(b_sample2); //inheritance relationship from subclass to parent clsaa is right. a_sample2->Test(); // c_sample = static_cast<C*>(a_sample); //non-inheritance relationship is error return 0; } #endif
[ "137984942@qq.com" ]
137984942@qq.com
bf340605791cb32471b5806b578937f92981abcd
598100bfde20dca7e2ef506328a25e64b15a3897
/a60b_q3_perimeter.cpp
fd568f00e19b78e76e4db4085a9fa7491a4c2df1
[]
no_license
dolwijit13/2110327_Algorithm_Design
80f212a8811ea12204701168621aacb733f6fbbe
61140ac8ba68ae573246b8024cca7c97699bf59f
refs/heads/master
2020-09-07T13:52:22.310551
2019-11-10T14:38:56
2019-11-10T14:38:56
220,799,381
0
0
null
null
null
null
UTF-8
C++
false
false
760
cpp
#include<bits/stdc++.h> using namespace std; #define mp make_pair #define ft first #define sd second vector<int>v[1005]; int d[1005]; int main() { int n,m,k; scanf("%d %d %d",&n,&m,&k); int i,j; int ans=0; int x,y; for(i=1;i<=m;i++) { scanf("%d %d",&x,&y); v[x].push_back(y); v[y].push_back(x); } priority_queue<pair<int,int> >pq; pq.push(mp(-0,0));/// -distance last_location while(!pq.empty()) { int w; w=-pq.top().ft; x=pq.top().sd; pq.pop(); if(d[x]!=0) continue; d[x]=w; if(w==k) ans++; for(i=0;i<v[x].size();i++) { if(v[x][i]!=0) pq.push(mp(-w-1,v[x][i])); } } printf("%d",ans); }
[ "dol51890@gmail.com" ]
dol51890@gmail.com
bdbdd86e885aa33faeb29191ffe1c60f74969229
efc129216f321f85720f6fdfd5663a5c344a67ab
/game/gamesys/Event.cpp
e063c46c34a308e5eaf67f0127b68f5a7771a411
[]
no_license
Stradex/q4-librecoop
70d27054d303d847a5016b14e3286d1c267618ea
cd0c47e5f1b499bf146b65ae7d3d1e84eb95eb1f
refs/heads/main
2023-03-14T01:17:59.154888
2021-02-25T06:36:48
2021-02-25T06:36:48
341,447,640
4
0
null
null
null
null
UTF-8
C++
false
false
20,516
cpp
/* sys_event.cpp Event are used for scheduling tasks and for linking script commands. */ #include "../../idlib/precompiled.h" #pragma hdrstop #include "../Game_local.h" #define MAX_EVENTSPERFRAME 8192 // Upped from 4096 //#define CREATE_EVENT_CODE /*********************************************************************** idEventDef ***********************************************************************/ idEventDef *idEventDef::eventDefList[MAX_EVENTS]; int idEventDef::numEventDefs = 0; static bool eventError = false; static char eventErrorMsg[ 128 ]; /* ================ idEventDef::idEventDef ================ */ idEventDef::idEventDef( const char *command, const char *formatspec, char returnType ) { idEventDef *ev; int i; unsigned int bits; assert( command ); assert( !idEvent::initialized ); // Allow NULL to indicate no args, but always store it as "" // so we don't have to check for it. if ( !formatspec ) { formatspec = ""; } this->name = command; this->formatspec = formatspec; this->returnType = returnType; numargs = strlen( formatspec ); assert( numargs <= D_EVENT_MAXARGS ); if ( numargs > D_EVENT_MAXARGS ) { eventError = true; sprintf( eventErrorMsg, "idEventDef::idEventDef : Too many args for '%s' event.", name ); return; } // make sure the format for the args is valid, calculate the formatspecindex, and the offsets for each arg bits = 0; argsize = 0; memset( argOffset, 0, sizeof( argOffset ) ); for( i = 0; i < numargs; i++ ) { argOffset[ i ] = argsize; switch( formatspec[ i ] ) { case D_EVENT_FLOAT : bits |= 1 << i; argsize += sizeof( float ); break; case D_EVENT_INTEGER : argsize += sizeof( int ); break; case D_EVENT_VECTOR : argsize += sizeof( idVec3 ); break; case D_EVENT_STRING : argsize += MAX_STRING_LEN; break; case D_EVENT_ENTITY : argsize += sizeof( idEntityPtr<idEntity> ); break; case D_EVENT_ENTITY_NULL : argsize += sizeof( idEntityPtr<idEntity> ); break; case D_EVENT_TRACE : argsize += sizeof( trace_t ) + MAX_STRING_LEN + sizeof( bool ); break; default : eventError = true; sprintf( eventErrorMsg, "idEventDef::idEventDef : Invalid arg format '%s' string for '%s' event.", formatspec, name ); return; break; } } // calculate the formatspecindex formatspecIndex = ( 1 << ( numargs + D_EVENT_MAXARGS ) ) | bits; // go through the list of defined events and check for duplicates // and mismatched format strings eventnum = numEventDefs; for( i = 0; i < eventnum; i++ ) { ev = eventDefList[ i ]; if ( idStr::Cmp( command, ev->name ) == 0 ) { if ( idStr::Cmp( formatspec, ev->formatspec ) != 0 ) { eventError = true; sprintf( eventErrorMsg, "idEvent '%s' defined twice with same name but differing format strings ('%s'!='%s').", command, formatspec, ev->formatspec ); return; } if ( ev->returnType != returnType ) { eventError = true; sprintf( eventErrorMsg, "idEvent '%s' defined twice with same name but differing return types ('%c'!='%c').", command, returnType, ev->returnType ); return; } // Don't bother putting the duplicate event in list. eventnum = ev->eventnum; return; } } ev = this; if ( numEventDefs >= MAX_EVENTS ) { eventError = true; sprintf( eventErrorMsg, "numEventDefs >= MAX_EVENTS" ); return; } eventDefList[numEventDefs] = ev; numEventDefs++; } /* ================ idEventDef::NumEventCommands ================ */ int idEventDef::NumEventCommands( void ) { return numEventDefs; } /* ================ idEventDef::GetEventCommand ================ */ const idEventDef *idEventDef::GetEventCommand( int eventnum ) { return eventDefList[ eventnum ]; } /* ================ idEventDef::FindEvent ================ */ const idEventDef *idEventDef::FindEvent( const char *name ) { idEventDef *ev; int num; int i; assert( name ); num = numEventDefs; for( i = 0; i < num; i++ ) { ev = eventDefList[ i ]; if ( idStr::Cmp( name, ev->name ) == 0 ) { return ev; } } return NULL; } /*********************************************************************** idEvent ***********************************************************************/ static idLinkList<idEvent> FreeEvents; static idLinkList<idEvent> EventQueue; static idEvent EventPool[ MAX_EVENTS ]; bool idEvent::initialized = false; idDynamicBlockAlloc<byte, 16 * 1024, 256, MA_EVENT> idEvent::eventDataAllocator; /* ================ idEvent::~idEvent() ================ */ idEvent::~idEvent() { Free(); } void idEvent::WriteDebugInfo( void ) { idEvent *event; int count = 0; idFile *FH = fileSystem->OpenFileAppend( "idEvents.txt" ); FH->Printf( "Num Events = %d\n", EventQueue.Num() ); event = EventQueue.Next(); while( event != NULL ) { count++; FH->Printf( "%d. %d - %s - %s - %s\n", count, event->time, event->eventdef->GetName(), event->typeinfo->classname, event->object->GetClassname() ); event = event->eventNode.Next(); } FH->Printf( "\n\n" ); fileSystem->CloseFile( FH ); } /* ================ idEvent::Alloc ================ */ idEvent *idEvent::Alloc( const idEventDef *evdef, int numargs, va_list args ) { idEvent *ev; size_t size; const char *format; idEventArg *arg; byte *dataPtr; int i; const char *materialName; if ( FreeEvents.IsListEmpty() ) { WriteDebugInfo( ); gameLocal.Error( "idEvent::Alloc : No more free events for '%s' event.", evdef->GetName() ); } ev = FreeEvents.Next(); ev->eventNode.Remove(); ev->eventdef = evdef; if ( numargs != evdef->GetNumArgs() ) { gameLocal.Error( "idEvent::Alloc : Wrong number of args for '%s' event.", evdef->GetName() ); } size = evdef->GetArgSize(); if ( size ) { ev->data = eventDataAllocator.Alloc( size ); memset( ev->data, 0, size ); } else { ev->data = NULL; } format = evdef->GetArgFormat(); for( i = 0; i < numargs; i++ ) { arg = va_arg( args, idEventArg * ); if ( format[ i ] != arg->type ) { // RAVEN BEGIN // abahr: type checking change as per Jim D. if ( ( format[ i ] == D_EVENT_ENTITY_NULL ) && ( arg->type == D_EVENT_ENTITY ) ) { // these types are identical, so allow them } else if ( ( arg->type == D_EVENT_INTEGER ) && ( arg->value == 0 ) ) { if ( ( format[ i ] == D_EVENT_ENTITY ) || ( format[ i ] == D_EVENT_ENTITY_NULL ) || ( format[ i ] == D_EVENT_TRACE ) ) { // when NULL is passed in for an entity or trace, it gets cast as an integer 0, so don't give an error when it happens } else { gameLocal.Error( "idEvent::Alloc : Wrong type passed in for arg # %d on '%s' event.", i, evdef->GetName() ); } } else { gameLocal.Error( "idEvent::Alloc : Wrong type passed in for arg # %d on '%s' event.", i, evdef->GetName() ); } // RAVEN END } dataPtr = &ev->data[ evdef->GetArgOffset( i ) ]; switch( format[ i ] ) { case D_EVENT_FLOAT : case D_EVENT_INTEGER : *reinterpret_cast<int *>( dataPtr ) = arg->value; break; case D_EVENT_VECTOR : if ( arg->value ) { *reinterpret_cast<idVec3 *>( dataPtr ) = *reinterpret_cast<const idVec3 *>( arg->value ); } break; case D_EVENT_STRING : if ( arg->value ) { idStr::Copynz( reinterpret_cast<char *>( dataPtr ), reinterpret_cast<const char *>( arg->value ), MAX_STRING_LEN ); } break; // RAVEN BEGIN // abahr: type checking change as per Jim D. // jshepard: TODO FIXME HACK this never ever produces desired, positive results. Events should be built to prepare for null entities, especially when dealing with // script events. This will throw a warning, and events should be prepared to deal with null entities. case D_EVENT_ENTITY : if ( reinterpret_cast<idEntity *>( arg->value ) == NULL ) { gameLocal.Warning( "idEvent::Alloc : NULL entity passed in to event function that expects a non-NULL pointer on arg # %d on '%s' event.", i, evdef->GetName() ); } *reinterpret_cast< idEntityPtr<idEntity> * >( dataPtr ) = reinterpret_cast<idEntity *>( arg->value ); break; case D_EVENT_ENTITY_NULL : *reinterpret_cast< idEntityPtr<idEntity> * >( dataPtr ) = reinterpret_cast<idEntity *>( arg->value ); break; //RAVEN END case D_EVENT_TRACE : if ( arg->value ) { *reinterpret_cast<bool *>( dataPtr ) = true; *reinterpret_cast<trace_t *>( dataPtr + sizeof( bool ) ) = *reinterpret_cast<const trace_t *>( arg->value ); // save off the material as a string since the pointer won't be valid in save games. // since we save off the entire trace_t structure, if the material is NULL here, // it will be NULL when we process it, so we don't need to save off anything in that case. if ( reinterpret_cast<const trace_t *>( arg->value )->c.material ) { materialName = reinterpret_cast<const trace_t *>( arg->value )->c.material->GetName(); idStr::Copynz( reinterpret_cast<char *>( dataPtr + sizeof( bool ) + sizeof( trace_t ) ), materialName, MAX_STRING_LEN ); } } else { *reinterpret_cast<bool *>( dataPtr ) = false; } break; default : gameLocal.Error( "idEvent::Alloc : Invalid arg format '%s' string for '%s' event.", format, evdef->GetName() ); break; } } return ev; } /* ================ idEvent::CopyArgs ================ */ void idEvent::CopyArgs( const idEventDef *evdef, int numargs, va_list args, int data[ D_EVENT_MAXARGS ] ) { int i; const char *format; idEventArg *arg; format = evdef->GetArgFormat(); if ( numargs != evdef->GetNumArgs() ) { gameLocal.Error( "idEvent::CopyArgs : Wrong number of args for '%s' event.", evdef->GetName() ); } for( i = 0; i < numargs; i++ ) { arg = va_arg( args, idEventArg * ); if ( format[ i ] != arg->type ) { // RAVEN BEGIN // abahr: type checking change as per Jim D. if ( ( format[ i ] == D_EVENT_ENTITY_NULL ) && ( arg->type == D_EVENT_ENTITY ) ) { // these types are identical, so allow them } else if ( ( arg->type == D_EVENT_INTEGER ) && ( arg->value == 0 ) ) { if ( ( format[ i ] == D_EVENT_ENTITY ) || ( format[ i ] == D_EVENT_ENTITY_NULL ) ) { // when NULL is passed in for an entity, it gets cast as an integer 0, so don't give an error when it happens } else { gameLocal.Error( "idEvent::Alloc : Wrong type passed in for arg # %d on '%s' event.", i, evdef->GetName() ); } } else { gameLocal.Error( "idEvent::Alloc : Wrong type passed in for arg # %d on '%s' event.", i, evdef->GetName() ); } // RAVEN END } data[ i ] = arg->value; } } /* ================ idEvent::Free ================ */ void idEvent::Free( void ) { if ( data ) { eventDataAllocator.Free( data ); data = NULL; } eventdef = NULL; time = 0; object = NULL; typeinfo = NULL; eventNode.SetOwner( this ); eventNode.AddToEnd( FreeEvents ); } /* ================ idEvent::Schedule ================ */ void idEvent::Schedule( idClass *obj, const idTypeInfo *type, int time ) { idEvent *event; assert( initialized ); if ( !initialized ) { return; } object = obj; typeinfo = type; // wraps after 24 days...like I care. ;) this->time = gameLocal.time + time; eventNode.Remove(); event = EventQueue.Next(); while( ( event != NULL ) && ( this->time >= event->time ) ) { event = event->eventNode.Next(); } if ( event ) { eventNode.InsertBefore( event->eventNode ); } else { eventNode.AddToEnd( EventQueue ); } } /* ================ idEvent::CancelEvents ================ */ void idEvent::CancelEvents( const idClass *obj, const idEventDef *evdef ) { idEvent *event; idEvent *next; if ( !initialized ) { return; } for( event = EventQueue.Next(); event != NULL; event = next ) { next = event->eventNode.Next(); if ( event->object == obj ) { if ( !evdef || ( evdef == event->eventdef ) ) { event->Free(); } } } } // RAVEN BEGIN // abahr: /* ================ idEvent::EventIsPosted ================ */ bool idEvent::EventIsPosted( const idClass *obj, const idEventDef *evdef ) { idEvent *event; idEvent *next; if ( !initialized ) { return false; } for( event = EventQueue.Next(); event != NULL; event = next ) { next = event->eventNode.Next(); if( event->object == obj && evdef == event->eventdef ) { return true; } } return false; } // RAVEN END /* ================ idEvent::ClearEventList ================ */ void idEvent::ClearEventList( void ) { int i; // // initialize lists // FreeEvents.Clear(); EventQueue.Clear(); // // add the events to the free list // for( i = 0; i < MAX_EVENTS; i++ ) { EventPool[ i ].Free(); } } /* ================ idEvent::ServiceEvents ================ */ void idEvent::ServiceEvents( void ) { idEvent *event; int num; int args[ D_EVENT_MAXARGS ]; int offset; int i; int numargs; const char *formatspec; trace_t **tracePtr; const idEventDef *ev; byte *data; const char *materialName; num = 0; while( !EventQueue.IsListEmpty() ) { #ifdef _XENON session->PacifierUpdate(); #endif event = EventQueue.Next(); assert( event ); if ( event->time > gameLocal.time ) { break; } // copy the data into the local args array and set up pointers ev = event->eventdef; formatspec = ev->GetArgFormat(); numargs = ev->GetNumArgs(); for( i = 0; i < numargs; i++ ) { offset = ev->GetArgOffset( i ); data = event->data; switch( formatspec[ i ] ) { case D_EVENT_FLOAT : case D_EVENT_INTEGER : args[ i ] = *reinterpret_cast<int *>( &data[ offset ] ); break; case D_EVENT_VECTOR : *reinterpret_cast<idVec3 **>( &args[ i ] ) = reinterpret_cast<idVec3 *>( &data[ offset ] ); break; case D_EVENT_STRING : *reinterpret_cast<const char **>( &args[ i ] ) = reinterpret_cast<const char *>( &data[ offset ] ); break; // RAVEN BEGIN // abahr: type checking change as per Jim D. case D_EVENT_ENTITY : *reinterpret_cast<idEntity **>( &args[ i ] ) = reinterpret_cast< idEntityPtr<idEntity> * >( &data[ offset ] )->GetEntity(); if ( *reinterpret_cast<idEntity **>( &args[ i ] ) == NULL ) { gameLocal.Warning( "idEvent::ServiceEvents : NULL entity passed in to event function that expects a non-NULL pointer on arg # %d on '%s' event.", i, ev->GetName() ); } break; case D_EVENT_ENTITY_NULL : *reinterpret_cast<idEntity **>( &args[ i ] ) = reinterpret_cast< idEntityPtr<idEntity> * >( &data[ offset ] )->GetEntity(); break; // RAVEN END case D_EVENT_TRACE : tracePtr = reinterpret_cast<trace_t **>( &args[ i ] ); if ( *reinterpret_cast<bool *>( &data[ offset ] ) ) { *tracePtr = reinterpret_cast<trace_t *>( &data[ offset + sizeof( bool ) ] ); if ( ( *tracePtr )->c.material != NULL ) { // look up the material name to get the material pointer materialName = reinterpret_cast<const char *>( &data[ offset + sizeof( bool ) + sizeof( trace_t ) ] ); ( *tracePtr )->c.material = declManager->FindMaterial( materialName, true ); } } else { *tracePtr = NULL; } break; default: gameLocal.Error( "idEvent::ServiceEvents : Invalid arg format '%s' string for '%s' event.", formatspec, ev->GetName() ); } } // the event is removed from its list so that if then object // is deleted, the event won't be freed twice event->eventNode.Remove(); assert( event->object ); // savegames can trash the object, so do this for safety if ( event->object ) { event->object->ProcessEventArgPtr( ev, args ); } #if 0 // event functions may never leave return values on the FPU stack // enable this code to check if any event call left values on the FPU stack if ( !sys->FPU_StackIsEmpty() ) { gameLocal.Error( "idEvent::ServiceEvents %d: %s left a value on the FPU stack\n", num, ev->GetName() ); } #endif // return the event to the free list event->Free(); // Don't allow ourselves to stay in here too long. An abnormally high number // of events being processed is evidence of an infinite loop of events. num++; if ( num > MAX_EVENTSPERFRAME ) { gameLocal.Error( "Event overflow. Possible infinite loop in script." ); } } } /* ================ idEvent::Init ================ */ void idEvent::Init( void ) { gameLocal.Printf( "Initializing event system\n" ); if ( eventError ) { gameLocal.Error( "%s", eventErrorMsg ); } #ifdef CREATE_EVENT_CODE void CreateEventCallbackHandler(); CreateEventCallbackHandler(); gameLocal.Error( "Wrote event callback handler" ); #endif if ( initialized ) { gameLocal.Printf( "...already initialized\n" ); ClearEventList(); return; } ClearEventList(); eventDataAllocator.Init(); gameLocal.Printf( "...%i event definitions\n", idEventDef::NumEventCommands() ); // the event system has started initialized = true; } /* ================ idEvent::Shutdown ================ */ void idEvent::Shutdown( void ) { gameLocal.Printf( "Shutdown event system\n" ); if ( !initialized ) { gameLocal.Printf( "...not started\n" ); return; } ClearEventList(); eventDataAllocator.Shutdown(); // say it is now shutdown initialized = false; } /* ================ idEvent::Save ================ */ void idEvent::Save( idSaveGame *savefile ) { idEvent *event; savefile->WriteInt( EventQueue.Num() ); event = EventQueue.Next(); while( event != NULL ) { savefile->WriteInt( event->time ); savefile->WriteString( event->eventdef->GetName() ); savefile->WriteString( event->typeinfo->classname ); savefile->WriteObject( event->object ); savefile->WriteInt( event->eventdef->GetArgSize() ); savefile->Write( event->data, event->eventdef->GetArgSize() ); event = event->eventNode.Next(); } } /* ================ idEvent::Restore ================ */ void idEvent::Restore( idRestoreGame *savefile ) { int i; int num; int argsize; idStr name; idEvent *event; savefile->ReadInt( num ); for ( i = 0; i < num; i++ ) { if ( FreeEvents.IsListEmpty() ) { gameLocal.Error( "idEvent::Restore : No more free events" ); } event = FreeEvents.Next(); event->eventNode.Remove(); event->eventNode.AddToEnd( EventQueue ); savefile->ReadInt( event->time ); // read the event name savefile->ReadString( name ); event->eventdef = idEventDef::FindEvent( name ); if ( !event->eventdef ) { savefile->Error( "idEvent::Restore: unknown event '%s'", name.c_str() ); } // read the classtype savefile->ReadString( name ); event->typeinfo = idClass::GetClass( name ); if ( !event->typeinfo ) { savefile->Error( "idEvent::Restore: unknown class '%s' on event '%s'", name.c_str(), event->eventdef->GetName() ); } savefile->ReadObject( event->object ); assert( event->object ); // read the args savefile->ReadInt( argsize ); if ( argsize != event->eventdef->GetArgSize() ) { savefile->Error( "idEvent::Restore: arg size (%d) doesn't match saved arg size(%d) on event '%s'", event->eventdef->GetArgSize(), argsize, event->eventdef->GetName() ); } if ( argsize ) { event->data = eventDataAllocator.Alloc( argsize ); savefile->Read( event->data, argsize ); } else { event->data = NULL; } } } #ifdef CREATE_EVENT_CODE /* ================ CreateEventCallbackHandler ================ */ void CreateEventCallbackHandler( void ) { int num; int count; int i, j, k; char argString[ D_EVENT_MAXARGS + 1 ]; idStr string1; idStr string2; idFile *file; file = fileSystem->OpenFileWrite( "Callbacks.cpp" ); file->Printf( "// generated file - see CREATE_EVENT_CODE\n\n" ); for( i = 1; i <= D_EVENT_MAXARGS; i++ ) { file->Printf( "\t/*******************************************************\n\n\t\t%d args\n\n\t*******************************************************/\n\n", i ); for ( j = 0; j < ( 1 << i ); j++ ) { for ( k = 0; k < i; k++ ) { argString[ k ] = j & ( 1 << k ) ? 'f' : 'i'; } argString[ i ] = '\0'; string1.Empty(); string2.Empty(); for( k = 0; k < i; k++ ) { if ( j & ( 1 << k ) ) { string1 += "const float"; string2 += va( "*( float * )&data[ %d ]", k ); } else { string1 += "const int"; string2 += va( "data[ %d ]", k ); } if ( k < i - 1 ) { string1 += ", "; string2 += ", "; } } file->Printf( "\tcase %d :\n\t\ttypedef void ( idClass::*eventCallback_%s_t )( %s );\n", ( 1 << ( i + D_EVENT_MAXARGS ) ) + j, argString, string1.c_str() ); file->Printf( "\t\t( this->*( eventCallback_%s_t )callback )( %s );\n\t\tbreak;\n\n", argString, string2.c_str() ); } } fileSystem->CloseFile( file ); } #endif
[ "stradexengine@gmail.com" ]
stradexengine@gmail.com
b433143fdf589a762046a7c70d0b4ce1eef4cb9c
9b963f56e0964a88f2a45b6fe9aa371e1c1c704e
/Math/2960-์—๋ผํ† ์Šคํ…Œ๋„ค์Šค์˜์ฒด(์ •์ˆ˜๋ก , ์†Œ์ˆ˜).cpp
67c091cfeb6acae30127b5296753db73af9ae6bf
[]
no_license
kewook55/PS-BOJ
0d1880ac849dca3cad516204796d07d15836073a
aced5d3e2b073d4a3ef92607c159efe9936ff940
refs/heads/master
2022-12-15T10:59:41.845978
2020-09-12T05:09:45
2020-09-12T05:09:45
267,512,154
1
0
null
null
null
null
UTF-8
C++
false
false
418
cpp
/* ์—๋ผํ† ์Šคํ…Œ๋„ค์Šค์˜ ์ฒด */ #include<iostream> using namespace std; int N, K; bool check[1001]; int main(void) { ios::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL); cin >> N >> K; for (int i = 2; i <= N; i++) { if (check[i])continue; for (int j = i; j <= N; j += i) { if (check[j])continue; check[j] = true; --K; if (K == 0) { cout << j; return 0; } } } return 0; }
[ "bono4023@gmail.com" ]
bono4023@gmail.com