blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 117 | path stringlengths 3 268 | src_encoding stringclasses 34
values | length_bytes int64 6 4.23M | score float64 2.52 5.19 | int_score int64 3 5 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | text stringlengths 13 4.23M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
71b92aa83be04beecf02d1921e20bc8d6db68256 | C++ | alexdoberman/kkm_server | /modules/kkm_control/src/proc_helper.cpp | UTF-8 | 1,225 | 2.609375 | 3 | [] | no_license | #include "proc_helper.h"
#include <Psapi.h>
#include <Shlwapi.h>
#include <tlhelp32.h>
#include <tchar.h>
#include <StrSafe.h>
namespace proc_helper
{
DWORD find(const wchar_t * szApp)
{
HANDLE hProcessSnap;
PROCESSENTRY32 pe32;
// Take a snapshot of all processes in the system.
hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
if( hProcessSnap == INVALID_HANDLE_VALUE )
{
//printError( TEXT("CreateToolhelp32Snapshot (of processes)") );
return( 0 );
}
// Set the size of the structure before using it.
pe32.dwSize = sizeof( PROCESSENTRY32 );
// Retrieve information about the first process,
// and exit if unsuccessful
if( !Process32First( hProcessSnap, &pe32 ) )
{
//printError( TEXT("Process32First") ); // show cause of failure
CloseHandle( hProcessSnap ); // clean the snapshot object
return( 0 );
}
DWORD pid = 0;
// Now walk the snapshot of processes, and
// display information about each process in turn
do
{
if ( StrStrI( pe32.szExeFile, szApp ) != NULL )
{
pid = pe32.th32ProcessID;
break;
}
} while( Process32Next( hProcessSnap, &pe32 ) );
CloseHandle( hProcessSnap );
return( pid );
}
}
| true |
6959db5cee92997d4b0ccd115e07de632a4d42d0 | C++ | SeanWuLearner/leetcode | /src/q0701.h | UTF-8 | 1,451 | 3.765625 | 4 | [
"MIT"
] | permissive | #include "tree_node.h"
/* Solution 1: recursive */
class Solution1 {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root==nullptr) return new TreeNode(val);
if(val > root->val)
root->right = insertIntoBST(root->right, val);
else
root->left = insertIntoBST(root->left, val);
return root;
}
};
/* Solution 2: iterative */
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root==nullptr) return new TreeNode(val);
TreeNode *cur = root;
while(true){
TreeNode **next = (val > cur->val)? &cur->right : &cur->left;
if(*next == nullptr){
*next = new TreeNode(val);
return root;
}
cur = *next;
}
}
};
#define null NULL_TNODE
TEST(Solution, test1){
Solution s;
int insert = 5;
TreeNode root{{4,2,7,1,3}};
TreeNode exp{{4,2,7,1,3,5}};
EXPECT_EQ(*s.insertIntoBST(&root, insert), exp);
}
TEST(Solution, test2){
Solution s;
int insert = 25;
TreeNode root{{40,20,60,10,30,50,70}};
TreeNode exp{{40,20,60,10,30,50,70,null,null,25}};
EXPECT_EQ(*s.insertIntoBST(&root, insert), exp);
}
TEST(Solution, test3){
Solution s;
int insert = 5;
TreeNode root{{4,2,7,1,3,null,null,null,null,null,null}};
TreeNode exp{{4,2,7,1,3,5}};
EXPECT_EQ(*s.insertIntoBST(&root, insert), exp);
} | true |
e3b9da3f6cc7748c355815c29fcaa5c50479bd83 | C++ | Bartleby2718/Introduction-To-Algorithms--CLRS- | /Tree/binarySearchTree.hpp | UTF-8 | 927 | 2.828125 | 3 | [
"MIT"
] | permissive | //
// Created by bartl on 06/15/2019.
//
#ifndef TREE_BINARYSEARCHTREE_HPP
#define TREE_BINARYSEARCHTREE_HPP
#include "BinarySearchTreeNode.hpp"
class BinarySearchTree
{
BinarySearchTreeNode *root;
public:
BinarySearchTree();
void insert(BinarySearchTreeNode *newNode);
void transplant(BinarySearchTreeNode *node1, BinarySearchTreeNode *node2);
void remove(int value);
void traverseInOrder() const;
void find(int target) const;
void printMinimum() const;
void printMaximum() const;
BinarySearchTreeNode *search(int target) const;
BinarySearchTreeNode *getMinimum() const;
BinarySearchTreeNode *getMaximum() const;
bool nullOrNotInTree(BinarySearchTreeNode *node) const;
BinarySearchTreeNode *getPredecessor(BinarySearchTreeNode *node) const;
BinarySearchTreeNode *getSuccessor(BinarySearchTreeNode *node) const;
};
#endif //TREE_BINARYSEARCHTREE_HPP
| true |
29f4082d4c75e63ddc06e7c591d0e34414669c0e | C++ | jing-ge/Jing-leetcode | /778.cpp | UTF-8 | 3,732 | 3.5 | 4 | [] | no_license | // 778. Swim in Rising Water
// On an N x N grid, each square grid[i][j] represents the elevation at that point (i,j).
// Now rain starts to fall. At time t, the depth of the water everywhere is t. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most t. You can swim infinite distance in zero time. Of course, you must stay within the boundaries of the grid during your swim.
// You start at the top left square (0, 0). What is the least time until you can reach the bottom right square (N-1, N-1)?
// Example 1:
// Input: [[0,2],[1,3]]
// Output: 3
// Explanation:
// At time 0, you are in grid location (0, 0).
// You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0.
// You cannot reach point (1, 1) until time 3.
// When the depth of water is 3, we can swim anywhere inside the grid.
// Example 2:
// Input: [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]]
// Output: 16
// Explanation:
// 0 1 2 3 4
// 24 23 22 21 5
// 12 13 14 15 16
// 11 17 18 19 20
// 10 9 8 7 6
// The final route is marked in bold.
// We need to wait until time 16 so that (0, 0) and (4, 4) are connected.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class UnionFind{
public:
vector<int> parent;
vector<int> size;
int n;
UnionFind(int _n){
n = _n;
for(int i=0;i<n;i++){
parent.push_back(i);
size.push_back(1);
}
}
int root(int i){
while(parent[i]!=i){
parent[i] = parent[parent[i]];
i = parent[i];
}
return i;
}
bool merge(int i, int j){
i = root(i);
j = root(j);
if(i==j)return false;
if(size[i]<size[j]){
parent[i] = j;
size[j]+=size[i];
}else{
parent[j] = i;
size[i] += size[j];
}
n--;
return true;
}
};
class Solution {
public:
//每次模拟时间超时
int swimInWater1(vector<vector<int>>& grid) {
int m = grid.size(),n = grid[0].size();
UnionFind uf(m*n);
int t = 0;
while(true){
for(int i=1;i<m;i++){
for(int j=0;j<n;j++){
if(grid[i][j]<=t&&grid[i-1][j]<=t){
uf.merge(i*n+j,(i-1)*n+j);
}
if(grid[j][i]<=t&&grid[j][i-1]<=t){
uf.merge(j*n+i,j*n+i-1);
}
}
}
if(uf.root(0)==uf.root(m*n-1))break;
t++;
}
return t;
}
//先排序后合并
int swimInWater(vector<vector<int>>& grid) {
int m = grid.size(),n = grid[0].size();
UnionFind uf(m*n);
vector<vector<int>> edges;
for(int i=1;i<m;i++){
for(int j=0;j<n;j++){
edges.push_back({i*n+j,(i-1)*n+j,max(grid[i][j],grid[i-1][j])});
edges.push_back({j*n+i,j*n+i-1,max(grid[j][i],grid[j][i-1])});
}
}
sort(edges.begin(),edges.end(),[](const vector<int>&a,const vector<int>&b)->bool{
return a[2]<b[2];
});
int res = 0;
for(auto &t:edges){
uf.merge(t[0],t[1]);
res = max(res,t[2]);
if(uf.root(0)==uf.root(m*n-1))break;
}
return res;
}
};
int main(){
Solution s;
vector<vector<int>> grid = {{0,1,2,3,4},{24,23,22,21,5},{12,13,14,15,16},{11,17,18,19,20},{10,9,8,7,6}};
int res = s.swimInWater(grid);
cout<<res<<endl;
return 0;
} | true |
b6d00cf5459eb40c0ddb7ba798030dc5f5950ef6 | C++ | maadborn/VisNode | /distrshapepositioncalc.cpp | UTF-8 | 13,483 | 2.828125 | 3 | [] | no_license | #include "distrshapepositioncalc.h"
#include "nodeitem.h"
#include <qmath.h>
#include <QDebug>
// Define some constants for ease of use when tweaking and debugging
static const int DISTR_SHAPE_MIN_RADIUS = 90;
static const int DISTR_SHAPE_RADIUS_INC_PER_ITEM = 10;
static const int DISTR_SHAPE_ARC_DEGREES = 120;
static const int DISTR_SHAPE_WIDTH_MOD = 100;
static const int DISTR_SHAPE_HEIGHT_MOD = 100;
/*
* Constructor
*/
DistrShapePositionCalc::DistrShapePositionCalc(QList<NodeItem*>& nodelist)
: AbstractNodeItemPositionCalc(nodelist)
{
}
/*
* Calculates the initial positions of all nodes, centered around the origin.
*
* At the current stage, it just positions them in a circle and spreads the nodes
* with many children in a roughly even manner.
*
* Call this:
* 1) In the beginning when all nodes have been added from parsing the file(s)
* 2) If a new node is added to an already created model. (Editable model not implemented yet!)
* Also make sure to call moveTo([new position]) afterwards.
*/
void DistrShapePositionCalc::calculate()
{
distributedShape();
}
/*
* Utility comparator function that helps sort the connections list in
* distributedShape() in falling order on the number of connection for
* each node name.
*/
static bool sortConnListLessThan(const QPair<QString, int>& one, const QPair<QString, int>& two) {
return one.second > two.second; // 'More than' achieves falling order sorting
}
/*
* This function creates the shape for the node map using the following algorithm:
*
* 1. Create a hashmap of all the items
* 2. Count all links to each item, both to and from
* 3. Create a list sorted by the number of links
* 4. For the item with most links:
* - place it in the center
* - if there are more than one with the same number of node, choose one of them
* - place other items around it, determined by:
* - all the items that connect to the center one
* 5. For all other items:
* - unless the child has already been placed, place it in:
* - a fan shape (~120 degr), facing away from the parent
*/
void DistrShapePositionCalc::distributedShape()
{
// Create a hashmap of all the items (uses hash at this stage to ease access to items)
QHash<QString, int> linkHash;
foreach(NodeItem* item, _nodelist) {
linkHash.insert(item->name(), 0);
}
// Count all links to each item, both to and from
foreach (NodeItem* item, _nodelist) {
int itemsChildrenCount = linkHash.value(item->name());
linkHash.insert(item->name(), itemsChildrenCount + item->childCount());
QList<NodeItem*> childlist = item->children();
foreach (NodeItem* child, childlist) {
int childsChildrenCount = linkHash.value(child->name());
linkHash.insert(child->name(), childsChildrenCount + 1);
}
}
// Create a list sorted by the number of links (use a list(pairs) at this stage to enable sorting)
QList<QPair<QString, int> > connCountList;
QHashIterator<QString, int> hashIter(linkHash);
while (hashIter.hasNext()) {
hashIter.next();
connCountList.append(qMakePair(hashIter.key(), hashIter.value()));
}
qSort(connCountList.begin(), connCountList.end(), sortConnListLessThan);
// For the item with most links:
// - place it in the center
NodeItem* centralNode = getNode(connCountList.at(0).first);
centralNode->setPosition(_centerPoint);
alreadyPlacedNodes.append(centralNode);
QList<NodeItem*> connectedNodes = getAllConnectedNodes(centralNode->name());
// TODO Perhaps add some code to this section to allow for more than one centrally
// placed node if more than one compete of that position
// - place other items around it, determined by:
// - all the items that connect to the center one
placeConnNodesCircle(centralNode, connectedNodes);
// For all other items:
// - unless the child has already been placed, place it in:
// - a fan shape (~120 degr), facing away from the parent
foreach (NodeItem* node, connectedNodes) {
placeConnNodesArc(node, centralNode);
}
// Calculate the current geometric size of the node map
calculateCurrentSize();
}
/*
* Returns the node with the name passed along.
* If not found, NULL is returned.
*/
NodeItem* DistrShapePositionCalc::getNode(const QString &nodeName)
{
for (int i = 0; i < _nodelist.size(); ++i) {
if (_nodelist[i]->name() == nodeName)
return _nodelist[i];
}
return NULL;
}
/*
* Returns a list with all the nodes that are connected to the node with the name [nodeName].
* This includes both its children and nodes who counts [nodeName] as its parent.
*/
QList<NodeItem*> DistrShapePositionCalc::getAllConnectedNodes(const QString& nodeName)
{
QList<NodeItem*> connectedNodes;
NodeItem* nodeToInvestigate = getNode(nodeName);
// Add the node's children as connected nodes
connectedNodes += nodeToInvestigate->children();
// For each of the nodes in the _nodelist ... (except itself)
foreach (NodeItem* node, _nodelist) {
if (node == nodeToInvestigate)
continue;
// ... see if its children count [nodeToInvestigate] as its child
foreach (NodeItem* child, node->children()) {
if (child == nodeToInvestigate) {
connectedNodes.append(node);
}
}
}
return connectedNodes;
}
/*
* Places the nodes connected to [centerNode] around it in a circle.
* Every node that gets its position is added to the exclusion list (alreadyPlacedNodes).
*/
void DistrShapePositionCalc::placeConnNodesCircle(const NodeItem* centerNode, QList<NodeItem*>& connectedNodes)
{
removePlacedNodes(connectedNodes);
int radius = radiusCircle(connectedNodes.size());
qreal betweenNodesRad = (M_PI / 180.0) * (360.0 / connectedNodes.size());
QPoint center = centerNode->position();
int xpos, ypos;
// Set the coords for all nodes, circle wise around (0,0)
// Note that the positions will need to be translated later during painting
for (int i = 0; i < connectedNodes.size(); ++i) {
xpos = radius * qCos(betweenNodesRad * i); // cos v = x / r <=> x = r * cos v
ypos = radius * qSin(betweenNodesRad * i); // sin v = y / r <=> y = r * sin v
connectedNodes[i]->setPosition(QPoint(center.x() + xpos, center.y() + ypos));
alreadyPlacedNodes.append(connectedNodes.at(i));
}
}
/*
* Recursive function that calculates and sets the positions of all the nodes connected to the [centerNode]
* except for those nodes who are already placed. Every node that gets its position is added to the exclusion
* list (alreadyPlacedNodes), and then this function is called for that node as [centerNode].
*/
void DistrShapePositionCalc::placeConnNodesArc(const NodeItem* centerNode, const NodeItem* centerNodesParent)
{
QList<NodeItem*> connectedNodes = getAllConnectedNodes(centerNode->name());
// Remove all the nodes that have already been placed from the passed along list
removePlacedNodes(connectedNodes);
// If the list is empty, stop here
if (connectedNodes.isEmpty()) {
return;
}
// Calculate the radius of the arc with this number of nodes
int radius = radiusArc(connectedNodes.size());
// Get the angle from this node's parent to the current node itself
qreal centerAngleRad = getRadAngle(centerNodesParent->position(), centerNode->position());
// Modify the start point of the angle using half the arc angle and the center angle just retrieved
qreal startAngelRad = centerAngleRad + (M_PI / 180.0) * (DISTR_SHAPE_ARC_DEGREES / 2);
// Calculate the angle width between nodes, in radians
// Divide the total arc angle with the number of nodes plus one (this centers the spread)
qreal betweenNodesRad = (M_PI / 180.0) * (static_cast<qreal>(DISTR_SHAPE_ARC_DEGREES) / (connectedNodes.size() + 1));
//qDebug() << centerAngleRad << "rad =" << centerAngleRad * (180.0 / M_PI) << "degr";
//qDebug() << startAngelRad << "rad =" << startAngelRad * (180.0 / M_PI) << "degr";
//qDebug() << radiansBetweenNodes << "rad =" << radiansBetweenNodes * (180.0 / M_PI) << "degr";
QPoint center = centerNode->position();
int xpos, ypos;
qreal angle;
// For each connected node, calculate it's position. Then run this function recursively on the that node.
for (int i = 0; i < connectedNodes.size(); ++i) { // BUG #100: SIZE MIGHT DECREASE AS OTHER NODES ARE PLACED ON RECURSIE CALLS
angle = startAngelRad - (betweenNodesRad * (i + 1));
xpos = radius * qCos(angle); // cos v = x / r <=> x = r * cos v
ypos = radius * qSin(angle); // sin v = y / r <=> y = r * sin v
connectedNodes[i]->setPosition(QPoint(center.x() + xpos, center.y() + ypos));
//qDebug() << angle << "rad =" << angle * (180.0 / M_PI) << "degr";
// Add the node to the list of the already placed ones, to avoid it from
alreadyPlacedNodes.append(connectedNodes.at(i));
// Continue recursively on all connected nodes
placeConnNodesArc(connectedNodes.at(i), centerNode);
}
// SOLUTION? TO BUG #100: Place all connected nodes in the for-loop above in a container
// instead of calling placeConnNodesArc() on them in the loop. After this loop, create
// another for-loop and in there call placeConnNodesArc() on the once stored in the container.
}
/*
* Removes all nodes from the list which have already been placed,
* to avoid duplicate nodes or "stolen" nodes
*/
void DistrShapePositionCalc::removePlacedNodes(QList<NodeItem*>& list)
{
foreach (NodeItem* node, list) {
if (alreadyPlacedNodes.contains(node)) {
list.removeOne(node);
}
}
}
/*
* Calculates the radius of the circle shaped placement of nodes around the center node
*/
int DistrShapePositionCalc::radiusCircle(int numOfConn) const
{
return (DISTR_SHAPE_MIN_RADIUS + numOfConn * DISTR_SHAPE_RADIUS_INC_PER_ITEM) * 0.75;
}
/*
* Calculates the radius of the fan, arc shaped placement of subsequent node placements
*/
int DistrShapePositionCalc::radiusArc(int numOfConn) const
{
return DISTR_SHAPE_MIN_RADIUS + numOfConn * DISTR_SHAPE_RADIUS_INC_PER_ITEM; // Let the radius be the same as for the circle for now, see how it works out
}
/*
* Calculates and returns the angle (in radians) of the [to] point, seen from the [from] point.
* Used to get the angle for placement of node arcs.
*/
qreal DistrShapePositionCalc::getRadAngle(const QPoint &from, const QPoint &to)
{
// Get the distances
qreal distX = (to.x() - from.x());
qreal distY = (to.y() - from.y());
qreal angleRad = atan2(distY, distX);
// // If the x distancs is 0, the angle is known, depending on the y distance
// // Also prevents division by zero in the arctangent calculation below
// if (distX == 0) {
// if (distY > 0)
// return (M_PI / 2);
// else
// return -(M_PI / 2);
// }
// // If the y distancs is 0, the angle is known, depending on the x distance
// if (distY == 0) {
// if (distX > 0)
// return 0;
// else
// return M_PI;
// }
// // Trigonometric arctangent calculation to get the angle
// qreal angleRad = qAtan(distY / distX);
// // If the angle is in the 2nd or 3rd quadrant, add PI radians (180 degrees)
// if (distX < 0)
// angleRad += M_PI;
// // Just for debugging.. degrees are a bit quicker to understand
// // qreal angleDeg = angleRad * (180.0 / M_PI);
// // Q_UNUSED(angleDeg);
return angleRad;
}
/*
* Calculates the width and height of the model by looking at
* the positions of all the nodes, finding the outermost ones.
* Adds a bit space around it determined by DISTR_SHAPE_WIDTH_MOD
* and DISTR_SHAPE_HEIGHT_MOD
*/
void DistrShapePositionCalc::calculateCurrentSize()
{
// Store some default, always to be over-written values
int maxX = INT_MIN, minX = INT_MAX,
maxY = INT_MIN, minY = INT_MAX;
// Look at each node's position and modify the max/min values if greater/lesser
foreach (NodeItem* node, _nodelist) {
QPoint nodepos = node->position();
if (nodepos.x() > maxX)
maxX = nodepos.x();
if (nodepos.x() < minX)
minX = nodepos.x();
if (nodepos.y() > maxY)
maxY = nodepos.y();
if (nodepos.y() < minY)
minY = nodepos.y();
}
// Add some extra space around the "node map"
minX -= DISTR_SHAPE_WIDTH_MOD;
maxX += DISTR_SHAPE_WIDTH_MOD;
minY -= DISTR_SHAPE_HEIGHT_MOD;
maxY += DISTR_SHAPE_HEIGHT_MOD;
int width = (maxX - minX);
int height = (maxY - minY);
QSize newSize(width, height);
// As the "node map" won't be perfectly centered at the origin, calculate a new center point
QPoint newCenter(minX + (width / 2), minY + (height / 2));
_currentSize = newSize;
_centerPoint = newCenter;
// Move the "node map" to center around the weighted center
moveInto(_centerPoint);
// _nodelist.append(new NodeItem(_nodelist.size(), "CENTER"));
// _nodelist.at(_nodelist.size()-1)->setPosition(_centerPoint);
}
| true |
68d123f52915e447c7b24e5740f1bc2d314501b8 | C++ | fanxingzju/PAT_advanced | /1037.cpp | UTF-8 | 786 | 2.796875 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
int NC, NP;
int coupons[100005];
int products[100005];
unsigned long long int max_sum = 0;
int main()
{
int index = 0;
int min_length = 0;
cin >> NC;
for (int i = 0; i != NC; ++i)
{
cin >> coupons[i];
}
cin >> NP;
for (int i = 0; i != NP; ++i)
{
cin >> products[i];
}
sort(coupons, coupons+NC);
sort(products, products+NP);
min_length = NC<NP? NC:NP;
while(coupons[index] < 0 && products[index] < 0 && index < min_length)
{
max_sum += coupons[index]*products[index];
++index;
}
index = 1;
while(coupons[NC-index] > 0 && products[NP-index] > 0 && index <= min_length)
{
max_sum += coupons[NC-index]*products[NP-index];
++index;
}
cout << max_sum << endl;
system("pause");
return 0;
} | true |
67a6432e0ded5d44e8179b6525ad28885a458a69 | C++ | mitempo/problems | /leetcode/0191_number_of_1_bits.cpp | UTF-8 | 214 | 2.859375 | 3 | [] | no_license | // https://leetcode.com/problems/number-of-1-bits/description/
class Solution {
public:
int hammingWeight(uint32_t n) {
int s = 0;
for (; n > 0; n >>= 1) s += n & 1;
return s;
}
};
| true |
9b65960a468b4343c2d0d5b637b41988adfdd13b | C++ | xiao7540916/Re-Vulkan | /Source/VulkanBackend/VulkanQueue/VulkanInstance.cpp | UTF-8 | 10,800 | 2.53125 | 3 | [] | no_license | #include "VulkanInstance.h"
#include <Horizon/Log/LogManager.h>
namespace Horizon
{
bool gInstanceInitialized = false;
VKAPI_ATTR VkBool32 VKAPI_CALL DebugUtilsMessengerCallback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
VkDebugUtilsMessageTypeFlagsEXT messageType, const VkDebugUtilsMessengerCallbackDataEXT* callbackData, void* userData)
{
if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT)
{
LOG_WARNING("{} - {}: {}", callbackData->messageIdNumber, callbackData->pMessageIdName, callbackData->pMessage);
}
else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT)
{
LOG_ERROR("{} - {}: {}", callbackData->messageIdNumber, callbackData->pMessageIdName, callbackData->pMessage);
}
return VK_FALSE;
}
static VKAPI_ATTR VkBool32 VKAPI_CALL DebugReportCallback(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType,
uint64_t object, size_t location, int32_t messageCode, const char* layerPrefix, const char* message, void* userData)
{
if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT)
{
LOG_ERROR("{}: {}", layerPrefix, message);
}
else if (flags & VK_DEBUG_REPORT_WARNING_BIT_EXT)
{
LOG_WARNING("{}: {}", layerPrefix, message);
}
else if (flags & VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT)
{
LOG_WARNING("{}: {}", layerPrefix, message);
}
else
{
LOG_INFO("{}: {}", layerPrefix, message);
}
return VK_FALSE;
}
static bool IsInstanceLayerSupported(const char* name, const std::vector<VkLayerProperties>& supportedLayers)
{
for (const auto& supportedLayer : supportedLayers)
{
if (strcmp(name, supportedLayer.layerName) == 0)
{
return true;
}
}
return false;
}
VulkanContext::VulkanContext()
: mHandle(VK_NULL_HANDLE)
, mDebugUtilsMessenger(VK_NULL_HANDLE)
, mDebugReportCallback(VK_NULL_HANDLE)
{
}
VulkanContext::~VulkanContext()
{
if (mHandle != VK_NULL_HANDLE)
{
Destroy();
}
}
bool VulkanContext::Init(const InstanceInitInfo& info)
{
LOG_TRACE("Init instance.");
assert(!gInstanceInitialized);
bool enableValidationLayers = info.enableValidationLayers;
if (enableValidationLayers)
{
uint32 validationLayerCount = 0;
VK_CHECK(vkEnumerateInstanceLayerProperties(&validationLayerCount, nullptr));
std::vector<VkLayerProperties> supportedValidationLayers(validationLayerCount);
VK_CHECK(vkEnumerateInstanceLayerProperties(&validationLayerCount, supportedValidationLayers.data()));
for (const auto& validationLayer : supportedValidationLayers)
{
LOG_TRACE("Supported instance layer: {} - vkspec version: {}.{}.{} {}: {}.",
validationLayer.layerName,
VK_VERSION_MAJOR(validationLayer.specVersion),
VK_VERSION_MINOR(validationLayer.specVersion),
VK_VERSION_PATCH(validationLayer.specVersion),
validationLayer.implementationVersion,
validationLayer.description);
}
const auto& requiredValidationLayers = info.instanceLayers.GetData();
for (const auto& requiredValidationLayer : requiredValidationLayers)
{
if (IsInstanceLayerSupported(requiredValidationLayer, supportedValidationLayers))
{
mEnabledInstanceLayers.emplace_back(requiredValidationLayer);
LOG_INFO("Enabled instance layer: {}.", requiredValidationLayer);
}
else
{
LOG_ERROR("Missing required instance layer: {}.", requiredValidationLayer);
return false;
}
}
}
uint32 supportedInstanceExtensionCount = 0;
VK_CHECK(vkEnumerateInstanceExtensionProperties(nullptr, &supportedInstanceExtensionCount, nullptr));
std::vector<VkExtensionProperties> supportedInstanceExtensions(supportedInstanceExtensionCount);
VK_CHECK(vkEnumerateInstanceExtensionProperties(nullptr, &supportedInstanceExtensionCount, supportedInstanceExtensions.data()));
for (const auto& instanceExtension : supportedInstanceExtensions)
{
LOG_TRACE("Supported instance extension: {} - vkspec version: {}.", instanceExtension.extensionName, instanceExtension.specVersion);
}
const auto& requiredInstanceExtensions = info.instanceExtensions.GetData();
for (const auto& requiredInstancwExtension : requiredInstanceExtensions)
{
if (IsExtensionSupported(requiredInstancwExtension, supportedInstanceExtensions))
{
mEnabledInstanceExtensions.emplace_back(requiredInstancwExtension);
LOG_INFO("Enabled instance extension: {}.", requiredInstancwExtension);
}
else
{
LOG_ERROR("Missing required instance extension: {}.", requiredInstancwExtension);
return false;
}
}
const auto& optionalInstanceExtensions = info.optionalInstanceExtensions.GetData();
for (const auto& optionalInstanceExtension : optionalInstanceExtensions)
{
if (IsExtensionSupported(optionalInstanceExtension, supportedInstanceExtensions))
{
mEnabledInstanceExtensions.emplace_back(optionalInstanceExtension);
LOG_INFO("Enabled instance extension: {}.", optionalInstanceExtension);
}
else
{
LOG_WARNING("Missing optional instance extension: {}.", optionalInstanceExtension);
}
}
bool enableDebugUtils = false;
bool enableDebugReport = false;
if (enableValidationLayers)
{
for (const auto& enabledInstanceExtension : mEnabledInstanceExtensions)
{
if (strcmp(enabledInstanceExtension, VK_EXT_DEBUG_UTILS_EXTENSION_NAME) == 0)
{
enableDebugUtils = true;
break;
}
if (strcmp(enabledInstanceExtension, VK_EXT_DEBUG_REPORT_EXTENSION_NAME) == 0)
{
enableDebugReport = true;
}
}
if ((!enableDebugUtils) && (!enableDebugReport))
{
LOG_WARNING("If validation layers are enabled. Extension: {} or {} must be enabled." VK_EXT_DEBUG_UTILS_EXTENSION_NAME, VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
if (IsExtensionSupported(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, supportedInstanceExtensions))
{
mEnabledInstanceExtensions.emplace_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
LOG_INFO("Enabled instance extension: {}.", VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
}
else if (IsExtensionSupported(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, supportedInstanceExtensions))
{
mEnabledInstanceExtensions.emplace_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
LOG_INFO("Enabled instance extension: {}.", VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
}
else
{
LOG_ERROR("Failed to enable instance layers.");
return false;
}
}
}
VkApplicationInfo appInfo = {};
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.apiVersion = VULKAN_API_VERSION;
appInfo.pApplicationName = info.applicationInfo.pApplicationName;
appInfo.applicationVersion = info.applicationInfo.applicationVersion;
appInfo.pEngineName = info.applicationInfo.pEngineName;
appInfo.engineVersion = info.applicationInfo.engineVersion;
VkInstanceCreateInfo instanceInfo = {};
instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
instanceInfo.pApplicationInfo = &appInfo;
instanceInfo.enabledExtensionCount = (uint32)(mEnabledInstanceExtensions.size());
instanceInfo.ppEnabledExtensionNames = mEnabledInstanceExtensions.data();
instanceInfo.enabledLayerCount = 0;
instanceInfo.ppEnabledLayerNames = nullptr;
if (enableValidationLayers)
{
instanceInfo.enabledLayerCount = (uint32)(mEnabledInstanceLayers.size());
instanceInfo.ppEnabledLayerNames = mEnabledInstanceLayers.data();
}
VkDebugUtilsMessengerCreateInfoEXT debugUtilsMessengerInfo = {};
VkDebugReportCallbackCreateInfoEXT debugReportCallbackInfo = {};
if (enableValidationLayers)
{
debugUtilsMessengerInfo = { VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT };
debugReportCallbackInfo = { VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT };
if (enableDebugUtils)
{
debugUtilsMessengerInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
debugUtilsMessengerInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT;
debugUtilsMessengerInfo.pfnUserCallback = DebugUtilsMessengerCallback;
instanceInfo.pNext = &debugUtilsMessengerInfo;
}
else
{
debugReportCallbackInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
debugReportCallbackInfo.pfnCallback = DebugReportCallback;
instanceInfo.pNext = &debugReportCallbackInfo;
}
}
VK_CHECK(vkCreateInstance(&instanceInfo, VULKAN_ALLOCATION_CALLBACKS, &mHandle));
uint32 physicalDeviceCount = 0;
VK_CHECK(vkEnumeratePhysicalDevices(mHandle, &physicalDeviceCount, nullptr));
assert(physicalDeviceCount > 0 && "No available physical device.");
mAvailablePhysicalDevices.resize(physicalDeviceCount);
VK_CHECK(vkEnumeratePhysicalDevices(mHandle, &physicalDeviceCount, mAvailablePhysicalDevices.data()));
if (enableValidationLayers)
{
if (enableDebugUtils)
{
PFN_vkCreateDebugUtilsMessengerEXT createDebugUtilsMessengerEXT = reinterpret_cast<PFN_vkCreateDebugUtilsMessengerEXT>(vkGetInstanceProcAddr(mHandle, "vkCreateDebugUtilsMessengerEXT"));
VK_CHECK(createDebugUtilsMessengerEXT(mHandle, &debugUtilsMessengerInfo, VULKAN_ALLOCATION_CALLBACKS, &mDebugUtilsMessenger));
}
else
{
PFN_vkCreateDebugReportCallbackEXT createDebugReportCallbackEXT = reinterpret_cast<PFN_vkCreateDebugReportCallbackEXT>(vkGetInstanceProcAddr(mHandle, "vkCreateDebugReportCallbackEXT"));
VK_CHECK(createDebugReportCallbackEXT(mHandle, &debugReportCallbackInfo, VULKAN_ALLOCATION_CALLBACKS, &mDebugReportCallback));
}
}
LOG_TRACE("Instance initialized.");
gInstanceInitialized = true;
return true;
}
void VulkanContext::Destroy()
{
LOG_TRACE("Destroy instance.");
if (mDebugUtilsMessenger != VK_NULL_HANDLE)
{
PFN_vkDestroyDebugUtilsMessengerEXT destroyDebugUtilsMessengerEXT = reinterpret_cast<PFN_vkDestroyDebugUtilsMessengerEXT>(vkGetInstanceProcAddr(mHandle, "vkDestroyDebugUtilsMessengerEXT"));
destroyDebugUtilsMessengerEXT(mHandle, mDebugUtilsMessenger, VULKAN_ALLOCATION_CALLBACKS);
mDebugUtilsMessenger = VK_NULL_HANDLE;
}
if (mDebugReportCallback != VK_NULL_HANDLE)
{
PFN_vkDestroyDebugReportCallbackEXT destroyDebugReportCallbackEXT = reinterpret_cast<PFN_vkDestroyDebugReportCallbackEXT>(vkGetInstanceProcAddr(mHandle, "vkDestroyDebugReportCallbackEXT"));
destroyDebugReportCallbackEXT(mHandle, mDebugReportCallback, VULKAN_ALLOCATION_CALLBACKS);
mDebugReportCallback = VK_NULL_HANDLE;
}
if (mHandle != VK_NULL_HANDLE)
{
vkDestroyInstance(mHandle, VULKAN_ALLOCATION_CALLBACKS);
mHandle = VK_NULL_HANDLE;
}
}
bool VulkanContext::IsInstanceExtensionEnabled(const char* extension)
{
for (const auto& enabledExtension : mEnabledInstanceExtensions)
{
if (strcmp(extension, enabledExtension) == 0)
{
return true;
}
}
return false;
}
} | true |
827398af78afc741c0ea53bb7995af287c53a32d | C++ | zhaoyaogit/lightRpc | /src/compress/test.cpp | UTF-8 | 190 | 3.140625 | 3 | [] | no_license |
#include <functional>
#include <iostream>
using namespace std;
int main()
{
auto f = [&](int a) {
if(a == 1) return a;
return f(a-1);
};
cout << f(5) << endl;
} | true |
9e0bae7cb0bb476ba80a33c38bb7c030bfc7c70a | C++ | comfort48/NAT-Application | /NAT_Application.cpp | UTF-8 | 1,233 | 2.8125 | 3 | [] | no_license | #include "NAT.cpp"
int main(int argc, char *argv[]) {
NetworkAddressTranslation nat; // nat object which does the work of reading the NAT and FLOW file and to output the result in OUTPUT file.
// Hard-coded the input file names -> NAT and FLOW
nat.populateNatMapper("NAT"); // Reads the NAT file and feeds the respective mapper (there are 3 mappers
// Examples: 1) maps 10.0.1.1:8080 -> 192.168.0.1:80. This kind uses "exact_ip_port_pairMapper" member variable
// 2) maps *:8081 -> 192.168.0.1:80 This kind uses "any_ip_specific_port_pairMapper" member variable
// 3) maps 10.0.1.2:* -> 192.168.0.1:80) This kind uses "specific_ip_any_port_pairMapper" member variable
nat.natFlowMapper("FLOW"); // Reads the incoming address and maps it to the exact flow as per the respective mappers.
cout<<"Nat mapping done...."<<endl<<"Output of Nat mappings is present in OUTPUT.txt file"<<endl;
return 0;
}
| true |
66626388cb41be6dfb7eed5f7f1ca5111b150987 | C++ | ayushsinghal2/ALGO | /sumproblem/varsum.cpp | UTF-8 | 1,329 | 3.46875 | 3 | [] | no_license | /* a[i]+a[j]=a[k]*/
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int partition(int a[], int low, int high )
{//partition
int pivot = a[low];
int left =low;
int right = high;
while(left<=right)
{
while(a[left]<=pivot)
{left++;}
while(a[right]>pivot)
{right--;}
if(left<right)
{
/////swapping
int temp = a[left];
a[left]=a[right];
a[right]=temp;
}
}
a[low]=a[right];
a[right]=pivot;
return right;
}
int randompar(int a[] , int low , int high)
{
int i = low + (rand()%(high-low));
int temp = a[low];
a[low] = a[i];
a[i] = temp;
return partition(a,low,high);
}
void quicksort(int a[],int low,int high)
{
if(low<high)
{
int k = randompar(a,low,high);
quicksort(a,low,k);
quicksort(a,k+1,high);
}
}
int sumprob(int a[],int size)
{
for (int k = 0; k < size; ++k)
{
int l=0;
int r=size-1;
while(l<=r)
{
if(a[l]+a[r]==a[k])
{
return 1;
}
else if (a[l]+a[r]<a[k])
l++;
else
r--;
}
}
return 0;
}
int main()
{
int start = clock();
int a[5] = {5555,400,80,55,1111};
quicksort(a,0,4);
if(sumprob(a,5))
cout<<"Yes there exist i,j and k pair"<<endl;
else
cout<<"Sorry there exist no i,j and k pair "<<endl;
int stop = clock();
cout << "time: " << (stop-start)/double(CLOCKS_PER_SEC)*1000 << endl;
} | true |
e3d0e23a42e0c9dc8b2b5ad366bdb081a20dd617 | C++ | liucsg/panoptic_mapping | /panoptic_mapping/include/panoptic_mapping/tools/log_data_writer.h | UTF-8 | 2,269 | 2.578125 | 3 | [
"BSD-3-Clause"
] | permissive | #ifndef PANOPTIC_MAPPING_TOOLS_LOG_DATA_WRITER_H_
#define PANOPTIC_MAPPING_TOOLS_LOG_DATA_WRITER_H_
#include <fstream>
#include <functional>
#include <string>
#include <vector>
#include "panoptic_mapping/3rd_party/config_utilities.hpp"
#include "panoptic_mapping/common/common.h"
#include "panoptic_mapping/map/submap_collection.h"
#include "panoptic_mapping/tools/data_writer_base.h"
namespace panoptic_mapping {
/**
* @brief Utility class that evaluates certain metrics during experiments and
* writes them to a log file.
*/
class LogDataWriter : public DataWriterBase {
public:
struct Config : public config_utilities::Config<Config> {
int verbosity = 4;
// Target directory to write the output to. This needs to exist already.
std::string output_directory = "";
// File name of the log file without suffix.
std::string file_name = "panoptic_mapping_data";
// Which fields to evaluate Fields.
bool evaluate_number_of_submaps = true;
bool evaluate_number_of_active_submaps = true;
bool evaluate_numer_of_objects = true;
Config() { setConfigName("LogDataWriter"); }
protected:
void setupParamsAndPrinting() override;
void checkParams() const override;
};
explicit LogDataWriter(const Config& config, bool print_config = true);
~LogDataWriter() override;
void writeData(double time_stamp, const SubmapCollection& submaps) override;
private:
static config_utilities::Factory::RegistrationRos<DataWriterBase,
LogDataWriter>
registration_;
const Config config_;
protected:
// Data.
std::string output_path_;
std::string outfile_name_;
std::ofstream outfile_;
std::vector<std::function<void(const SubmapCollection&)>> evaluations_;
// Methods.
virtual void setupLogFile();
virtual void setupEvaluations();
void writeEntry(const std::string& value);
// Evaluations. The data are always preceded by a separating comma.
void evaluateNumberOfSubmaps(const SubmapCollection& submaps);
void evaluateNumberOfActiveSubmaps(const SubmapCollection& submaps);
void evaluateNumberOfObjects(const SubmapCollection& submaps);
};
} // namespace panoptic_mapping
#endif // PANOPTIC_MAPPING_TOOLS_LOG_DATA_WRITER_H_
| true |
e38528beb8784ee0d7c3940aab3ca1719f53b74e | C++ | Taoaoxiang/PracticeLeetCode | /include_LeetCode.h | UTF-8 | 2,744 | 2.875 | 3 | [] | no_license | // All the needed headers for LeetCode
#include <iostream>
#include <string>
#include <vector>
#include <cmath>
#include <algorithm>
#include <map>
#include <unordered_map>
#include <functional>
#include <stack>
#include <queue>
#include <deque>
#include <set>
#include <unordered_set>
using namespace std;
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
///*
//// Definition for a Node.
//class Node {
//public:
// int val;
// Node* left;
// Node* right;
// Node* next;
//
// Node() {}
//
// Node(int _val, Node* _left, Node* _right, Node* _next) {
// val = _val;
// left = _left;
// right = _right;
// next = _next;
// }
//};
//*/
//class Node {
//public:
// int val;
// Node* left;
// Node* right;
// Node* next;
//
// Node() {}
//
// Node(int _val, Node* _left, Node* _right, Node* _next) {
// val = _val;
// left = _left;
// right = _right;
// next = _next;
// }
//};
///*
//// Definition for a Node.
//class Node {
//public:
// int val;
// vector<Node*> neighbors;
//
// Node() {}
//
// Node(int _val, vector<Node*> _neighbors) {
// val = _val;
// neighbors = _neighbors;
// }
//};
//*/
//class Node {
//public:
// int val;
// vector<Node*> neighbors;
//
// Node() {}
//
// Node(int _val, vector<Node*> _neighbors) {
// val = _val;
// neighbors = _neighbors;
// }
//};
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node() {}
Node(int _val, Node* _next, Node* _random) {
val = _val;
next = _next;
random = _random;
}
};
*/
class Node {
public:
int val;
Node* next;
Node* random;
Node() {}
Node(int _val, Node* _next, Node* _random) {
val = _val;
next = _next;
random = _random;
}
};
class TRIE {
bool end = false;
unordered_map<char, TRIE*> children;
public:
TRIE() {}
void insert(string &word) {
TRIE* root = this;
if (word.size() == 0) { return; }
for (int i = 0; i < word.size();++i) {
if (root->children[word[i]] == NULL) { root->children[word[i]] = new TRIE(); }
root = root->children[word[i]];
}
root->end = true;
}
bool find(string &word) {
TRIE* root = this;
for (int i = 0; i < word.size();++i) {
root = root->children[word[i]];
if (root == NULL) { return false; }
}
return root->end;
}
}; | true |
9549e8e388dc59da79bf9ba9b809f8d3bc0281fc | C++ | baetuc/IP-Lab-1 | /Responsabil.cpp | UTF-8 | 1,557 | 2.6875 | 3 | [] | no_license | #include "Responsabil.h"
#include"Utility.h"
#include<utility>
using namespace std;
extern map<string, map<int, pair<Serializabil*, bool>>> obiecteCreateDinClasa;
typedef Serializabil* (*CreareObiect)();
extern map<string, CreareObiect> creeazaObiectDeTipul;
list<Student*> Responsabil::getSubordonati() {
return subordonati;
}
void Responsabil::setSubordonati(list<Student*> subordonati) {
this->subordonati = subordonati;
}
void Responsabil::serializeaza(ostream& ostr) {
ostr << "\nResponsabil\n";
ostr << stud->getID() << '\n';
ostr << stud->getTip() << '\n';
ostr << "#";
}
void Responsabil::deserializeaza(istream& istr, int ID) {
creareStudent(istr, ID);
Utility::valideazaSfarsitObiect(istr);
}
void Responsabil::printInfo(ostream& ostr, int deplasament)
{
list<Student*>::iterator it;
Utility::printHeader(ostr, deplasament);
ostr << "Responsabil cu studentii:\n";
for (it = subordonati.begin(); it != subordonati.end(); ++it)
{
Utility::printHeader(ostr, deplasament+1);
ostr << (*it)->getID() << '\n';
}
}
extern map<string, map<int, pair<Serializabil*, bool>>> obiecteCreateDinClasa;
extern map<string, string> tipulTipului;
typedef Serializabil* (*CreareObiect)();
extern map<string, CreareObiect> creeazaObiectDeTipul;
namespace
{
Serializabil * creareResponsabil()
{
return new Responsabil;
}
CreareObiect x = (creeazaObiectDeTipul["Responsabil"] = creareResponsabil);
string y = (tipulTipului["Responsabil"] = "Responsabil");
map<int, pair<Serializabil*, bool>> z = obiecteCreateDinClasa["Responsabil"];
} | true |
750256b478e3fbf1801ce32808497a4f6f20fdb5 | C++ | Codetalker777/loncare_DataStructures | /loncare_DataStructures/StudentList.cpp | UTF-8 | 2,501 | 3.1875 | 3 | [] | no_license | #include "stdafx.h"
#include "StudentList.h"
#include <string>
#include <vector>
#include <list>
#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <iomanip>
#include <chrono>
using namespace std;
// constrcutor
StudentList::StudentList(string file_name)
{
// vairables
vector<string> names;
vector<int> ids;
// open file
fstream file(file_name, ios::in);
// check if not successful
if (!file.is_open()) {
cout << "File not found";
}
else {
// read input
string line;
while (getline(file, line, ',')) {
names.push_back(line);
}
// generate ids and store data into lists and vectors
GenerateRandomIDs(ids, names.size());
for (int i = 0; i < names.size(); i++) {
vectors.push_back(Student(ids.at(i), names.at(i)));
lists.push_back(Student(ids.at(i), names.at(i)));
}
file.close();
}
}
// sorts the vector and returns how long it took
double StudentList::sort_vector()
{
auto t1 = chrono::high_resolution_clock::now();
sort(vectors.begin(), vectors.end());
auto t2 = chrono::high_resolution_clock::now();
chrono::duration<double, milli> time = t2 - t1;
return time.count();
}
// sorts the list and returns how long it took
double StudentList::sort_list() {
auto t1 = chrono::high_resolution_clock::now();
lists.sort();
auto t2 = chrono::high_resolution_clock::now();
chrono::duration<double, milli> time = t2 - t1;
return time.count();
}
// searchs the vector and returns how long it took
double StudentList::search_vector_by_id(int search) {
auto t1 = chrono::high_resolution_clock::now();
find_if(vectors.begin(), vectors.end(), [&](Student& s) { return s.get_id() == search; });
auto t2 = chrono::high_resolution_clock::now();
chrono::duration<double, milli> time = t2 - t1;
return time.count();
}
// searches the list and returns how long it took
double StudentList::search_list_by_id(int search) {
auto t1 = chrono::high_resolution_clock::now();
find_if(lists.begin(), lists.end(), [search](Student& s) { return s.get_id() == search; });
auto t2 = chrono::high_resolution_clock::now();
chrono::duration<double, milli> time = t2 - t1;
return time.count();
}
//outputs the id and name in the vector when operator << is called
ostream& operator<<(ostream& out, const StudentList& value) {
for (int i = 0; i < value.vectors.size(); i++) {
out << left << fixed << setw(10) << value.vectors.at(i).get_id();
out << fixed << setw(10) << value.vectors.at(i).get_name() << endl;
}
return out;
}
| true |
98d85d1ef68838a26e0eeeaf4b92d7c832e89703 | C++ | xploora/kepler3d | /test-gl/unittests/src/test_BoundingBox.cpp | UTF-8 | 2,733 | 2.75 | 3 | [
"Apache-2.0"
] | permissive | #include "common_test.hpp"
#include <BoundingBox.hpp>
#include <Transform.hpp>
using namespace kepler;
using glm::quat;
using glm::radians;
static const vec3 origin;
static constexpr float float_err = 0.000001f;
TEST(boundingBox, empty) {
EXPECT_TRUE(BoundingBox().empty());
EXPECT_TRUE(BoundingBox(vec3(5), vec3(5)).empty());
BoundingBox a(vec3(-1), vec3(1));
EXPECT_FALSE(a.empty());
a.set(vec3(1), vec3(2));
EXPECT_FALSE(a.empty());
}
TEST(boundingBox, center) {
EXPECT_VE3_EQ(origin, BoundingBox().center());
BoundingBox a(vec3(-1, -1, -1), vec3(1, 1, 1));
EXPECT_VE3_EQ(origin, a.center());
BoundingBox b(vec3(5, 10, 15), vec3(15, 30, 65));
EXPECT_VE3_EQ(vec3(10, 20, 40), b.center());
}
TEST(boundingBox, merge) {
{
BoundingBox a(vec3(1, 2, 3), vec3(10, 20, 30));
BoundingBox b(vec3(-5, -10, 7), vec3(5, 100, 3));
a.merge(b);
EXPECT_VE3_EQ(vec3(-5, -10, 3), a.min);
EXPECT_VE3_EQ(vec3(10, 100, 30), a.max);
}
}
TEST(boundingBox, rotateY) {
using std::sqrt;
{
BoundingBox actual(vec3(-1, -1, -1), vec3(1, 1, 1));
Transform t;
t.setRotationFromEuler(0, PI_OVER_4, 0);
actual.transform(t.matrix());
const float sqrt2 = sqrt(2.0f);
EXPECT_VE3_EQ(vec3(-sqrt2, -1, -sqrt2), actual.min);
EXPECT_VE3_EQ(vec3(sqrt2, 1, sqrt2), actual.max);
}
{
BoundingBox actual(vec3(0), vec3(1, 1, 1));
Transform t;
t.setRotationFromEuler(0, -PI_OVER_4, 0);
actual.transform(t.matrix());
EXPECT_VE3_EQ(vec3(-sqrt(0.5f), 0.0f, 0), actual.min);
EXPECT_VE3_EQ(vec3(sqrt(0.5f), 1, sqrt(2.0f)), actual.max);
}
}
TEST(boundingBox, scaleTranslate) {
const vec3 t(1, 2, 3);
const vec3 s(10, 20, 30);
BoundingBox actual(vec3(-1, -1, -1), vec3(1, 1, 1));
BoundingBox expected;
for (int i = 0; i < 3; ++i) {
expected.min[i] = actual.min[i] * s[i] + t[i];
expected.max[i] = actual.max[i] * s[i] + t[i];
}
Transform transform;
transform.translate(t);
transform.scale(s);
actual.transform(transform.matrix());
EXPECT_VE3_EQ(expected.min, actual.min);
EXPECT_VE3_EQ(expected.max, actual.max);
}
TEST(boundingBox, rotateX) {
BoundingBox actual(vec3(0, 0, 0), vec3(1, 1, 1));
Transform t;
t.setRotationFromEuler(-PI_OVER_2, 0, 0);
actual.transform(t.matrix());
BoundingBox expected(vec3(0, 0, -1), vec3(1, 1, 0));
EXPECT_VE3_EQ(expected.min, actual.min);
EXPECT_FLOAT_CLOSE(expected.max.x, actual.max.x, float_err);
EXPECT_FLOAT_CLOSE(expected.max.y, actual.max.y, float_err);
EXPECT_FLOAT_CLOSE(expected.max.z, actual.max.z, float_err);
}
| true |
c9bfeced691eeee421b137119e731ed9754851f1 | C++ | lasaldan/wizards-court | /WizardsCourt/TextureCoordinate.cpp | UTF-8 | 566 | 2.671875 | 3 | [] | no_license | //
// TextureCoordinate.cpp
// wizards-court
//
// Created by Daniel Fuller on 9/15/15.
// Copyright (c) 2015 Daniel Fuller. All rights reserved.
//
#include <iostream>
#include <sstream>
#include <stdio.h>
#include "TextureCoordinate.h"
using namespace std;
TextureCoordinate::TextureCoordinate ( float X, float Y ) {
x = X;
y = Y;
};
float TextureCoordinate::getX() {
return x;
}
float TextureCoordinate::getY() {
return y;
}
string TextureCoordinate::print() {
ostringstream ss;
ss << "Tex: [" << x << "," << y << "]";
return ss.str();
}
| true |
b0c805b176e67a4b7763c92169cd3483b9ff22c7 | C++ | maxclappier/CitySim-Solver | /util.cpp | UTF-8 | 6,155 | 3.0625 | 3 | [
"BSD-3-Clause"
] | permissive | #include "util.h"
// *** Utils, CitySim *** //
// *** jerome.kaempf@epfl.ch *** //
// extern use of LAPACK in Fortran
extern "C" {
// LU decomposition and backsubstitution of a general matrix
void dgesv_(int *n, int *nrhs, double *a, int *lda, int *ipiv, double *b, int *ldb, int *info);
// LU decomposition of a general matrix
void dgetrf_(int* m, int *n, double* a, int* lda, int* ipiv, int* info);
// generates inverse of a matrix given its LU decomposition
void dgetri_(int* n, double* a, int* lda, int* ipiv, double* work, int* lwork, int* info);
// computes all eigenvalues and, optionally, eigenvectors of an n-by-n real symmetric matrix A
void dsyev_(char* jobz, char* uplo, int* n, double* a, int* lda, double* w, double* work, int* lwork, int* info);
}
// prints a matrix
void print_matrix(string desc, int m, int n, double* a, int lda) {
int i, j;
cout << "\n " << desc << endl;
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) cout << a[i+j*lda] << " ";
cout << endl;
}
return;
}
// prints a vector of int
void print_int_vector(string desc, int n, int* a) {
int j;
cout << "\n " << desc << endl;
for (j = 0; j < n; j++) cout << a[j] << " ";
cout << endl;
return;
}
// inverse a square matrix
void inverse_square_matrix(double* a, int n)
{
int ipiv[n];
int lwork = n*n;
double work[lwork];
int info;
//print_matrix("Matrix A", n, n, a, n);
dgetrf_(&n,&n,a,&n,ipiv,&info);
if (info<0) throw(string("LAPACK dgetrf: argument" + toString(-info) + " had an illegal value"));
else if (info>0) throw(string("LAPACK dgetrf: U(" + toString(info) + "," + toString(info) + ") is exactly zero. The factorization has been completed, but the factor U is exactly singular, and division by zero will occur if it is used to solve a system of equations.had an illegal value"));
dgetri_(&n,a,&n,ipiv,work,&lwork,&info);
if (info<0) throw(string("LAPACK dgetri: argument" + toString(-info) + " had an illegal value"));
else if (info>0) throw(string("LAPACK dgetri: U(" + toString(info) + "," + toString(info) + ") is exactly zero; the matrix is singular and its inverse could not be computed."));
//print_matrix("Matrix A^(-1)", n, n, a, n);
return;
}
// solve for the problem Ax=b using dgesv
void solve_Ax_equal_b(double* a, double *b, int n)
{
// run of DGESV - A * x = b (notation: row x column) NPxNP NPx1 = NPx1
int one = 1;
int ipiv[n]; // pivot indices
int info;
//print_matrix("Matrix A", n, n, a, n);
//print_matrix("Vector b", n, 1, b, 1);
dgesv_(&n, &one, a, &n, ipiv, b, &n, &info);
if (info<0) throw(string("LAPACK dgesv: argument" + toString(-info) + " had an illegal value"));
else if (info>0) throw(string("LAPACK dgesv: U(" + toString(info) + "," + toString(info) + ") is exactly zero. The factorization has been completed, but the factor U is exactly singular, so the solution could not be computed."));
// Print LU factorization
//print_matrix( "LU factorization", n, n, a, n );
// Print pivot indices
//print_int_vector( "Pivot indices", n, ipiv );
// Print solution
//print_matrix("Vector x", n, 1, b, 1);
return;
}
// solve for the eigenvalues of the real symmetric square matrix A
void eigenvalues_A(double *a, double *w, int n)
{
// run of DSYEV
char jobz = 'V', uplo = 'U';
int info;
int lwork = n*n;
double work[lwork];
//print_matrix("Matrix A", n, n, a, n);
// compute the eigenvalues
dsyev_(&jobz, &uplo, &n, a, &n, w, work, &lwork, &info);
// print the eigenvalues
//print_matrix("Vector w", 1, n, w, 1);
return;
}
// associate the logstreams
void associate(ostream* pLogStream, ostream& logStream) {
// the read buffers are associated
if(pLogStream!=NULL) logStream.rdbuf(pLogStream->rdbuf());
if (!logStream.good()) throw(string("Unable to define correctly the logStream."));
}
string tabs(unsigned int number) {
string myTabs = "";
for (unsigned int i=0; i<number; ++i) myTabs += "\t";
return myTabs;
}
void save(const string filename, ostringstream &oss, bool overwrite) {
fstream output;
if (overwrite)
output.open(filename.c_str(), ios::out | ios::binary);
else
output.open(filename.c_str(), ios::out | ios::binary | ios::app);
output << oss.str();
output.close();
return;
}
//calculates absolute value
uint32_t Abs(int32_t a) {
if(a < 0)
return -1*a;
else
return a;
}
float nfix(void)
{
const float r = 3.442620f; /* The start of the right tail */
static float x, y;
for(;;)
{ x=hz*wn[iz]; /* iz==0, handles the base strip */
if(iz==0)
{ do{ x=-log(UNI)*0.2904764; y=-log(UNI);} /* .2904764 is 1/r */
while(y+y<x*x);
return (hz>0)? r+x : -r-x;
}
/* iz>0, handle the wedges of other strips */
if( fn[iz]+UNI*(fn[iz-1]-fn[iz]) < exp(-.5*x*x) ) return x;
/* initiate, try to exit for(;;) for loop*/
hz=SHR3;
iz=hz&127;
if( Abs(hz) < kn[iz] ) return (hz*wn[iz]);
}
}
void zigset(uint32_t jsrseed)
{ const double m1 = 2147483648.0;
double dn=3.442619855899,tn=dn,vn=9.91256303526217e-3, q;
jsr^=jsrseed;
/* Set up tables for RNOR */
q=vn/exp(-.5*dn*dn);
kn[0]=(uint32_t) ((dn/q)*m1);
kn[1]=0;
wn[0]=q/m1;
wn[127]=dn/m1;
fn[0]=1.;
fn[127]=exp(-.5*dn*dn);
for(unsigned short int i=126;i>=1;i--) // put the index i in the loop declaration, JK - 22/02/09
{dn=sqrt(-2.*log(vn/dn+exp(-.5*dn*dn)));
kn[i+1]=(uint32_t) ((dn/tn)*m1);
tn=dn;
fn[i]=exp(-.5*dn*dn);
wn[i]=dn/m1;
}
}
double normallyDistributedSPRNG_Ziggurat() {
return RNOR;
}
double randomUniform(double minValue,double maxValue)
{
return minValue + UNI * (maxValue - minValue);
}
float cosAngleBetween(const GENPoint& a, const GENPoint& b) {
return GEN::dot_product(a,b)/(a.Radius()*b.Radius());
}
| true |
73e80a69f8afc93e244c8b68d36b8f61e0ee5cd1 | C++ | s947599549/CourseManageSystem | /CMD.cpp | UTF-8 | 2,553 | 3.46875 | 3 | [] | no_license | #include "CMD.h"
using namespace std;
vector<string> CMD::information = { "Print help information",
"List all courses",
"Print detailed course information by ID",
"Print detailed course information by name",
"Delete course by ID",
"Delete course by name",
"Add course",
"Exit" };
CMD::CMD(ifstream& infile) :cm(infile) {
}
void CMD::PrintHelpInfor() const {
int sz = information.size();
for (int i = 0; i < sz; ++i) {
cout << " " << i << " " << information[i] << endl;
}
}
void CMD::AddCourseKind() {
cout << " 0 " << "Basic course" << endl;
cout << " 1 " << "Project course" << endl;
cout << " 2 " << "Judge course" << endl;
cout << "Choose the kind of course:";
int num;
cin >> num;
string name;
cout << "Input course name:";
cin >> name;
cout << " ";
shared_ptr<Course> sp;
if (num == 0) {
sp = make_shared<Course>(Course(name));
}
else if (num == 1) {
cout << "Input course tag:";
int tag;
cin >> tag;
sp = make_shared<ProjectCourse>(ProjectCourse(name, tag));
}
else if (num == 2) {
cout << "Input course time:";
int time;
cin >> time;
sp = make_shared<JudgeCourse>(JudgeCourse(name, time));
}
cm.AddCourse(sp);
}
void CMD::ProcessCommand() {
cout << "--------------------------------" << endl;
PrintHelpInfor();
cout << "--------------------------------" << endl;
while (true) {
int number;
cout << "Command Number:";
cin >> number;
cout << endl;
if (number == 0)
PrintHelpInfor();
else if (number == 1)
cm.PrintCourseTable();
else if (number == 2) {
int id;
cout << "Input course ID:";
cin >> id;
if (cm.PrintCourseInfo(id) == 0)
cout << "Course ID not exist" << endl;
}
else if (number == 3) {
string name;
cout << "Input course name:";
cin >> name;
if (cm.PrintCourseInfo(name) == 0)
cout << "Course name not exist" << endl;
}
else if (number == 4) {
int id;
cout << "Input course ID:";
cin >> id;
if (cm.DeleteCourse(id) == 0)
cout << "Course ID not exist" << endl;
}
else if (number == 5) {
string name;
cout << "Input course name:";
cin >> name;
if (cm.DeleteCourse(name) == 0)
cout << "Course name exist" << endl;
}
else if (number == 6) {
AddCourseKind();
}
else if (number == 7)
return;
else
cout << "Input wrong" << endl;
cout << "---------------------------------" << endl;
}
} | true |
dfa2a7d95911ef8a813f30b6694898f990a29db2 | C++ | JanDeng25/Online-Judge | /PAT/Basic Level/1019. 数字黑洞 (20).cpp | UTF-8 | 685 | 2.875 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
#include <stdio.h>
#include <algorithm>
using namespace std;
int reverse(int n){
int m = 0;
for(int i = 0; i < 4; i++){
m = 10 * m + n % 10;
n /= 10;
}
return m;
}
int caculate(int n){
int a[4], m = 0, l = 0;
for(int i = 0; i < 4; i ++){
a[i] = n % 10;
n /= 10;
}
sort(a,a + 4);
for(int i = 0; i < 4; i ++){
l = 10 * l + a[i];
}
for(int i = 3; i >= 0; i --){
m = 10 * m + a[i];
}
printf("%04d - %04d = %04d\n",m,l,m-l);
return m - l;
}
int main(){
int n; cin >> n;
if(reverse(n) == n){
printf("%04d - %04d = %04d\n",n,n,n-n);
return 0;
}
n = caculate(n);
while(n != 6174){
n = caculate(n);
}
return 0;
} | true |
5bf2e13a6220e516ad933b09f7cf67f2acdd3f3e | C++ | Youngwb/leetcode_cplusplus | /22/Generate_Parentheses1.cpp | UTF-8 | 661 | 3.671875 | 4 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> ret;
string s;
dfs(s,ret,0,0,n);
return ret;
}
void dfs(string s,vector<string> & ret,int l,int r,int n){
if(r == n){
ret.push_back(s);
}
else if(l == n){
s+=')';
dfs(s,ret,l,r+1,n);
}else{
if(l>r)
dfs(s+')',ret,l,r+1,n);
dfs(s+'(',ret,l+1,r,n);
}
}
};
int main(int argc, char const *argv[])
{
Solution sln;
vector<string> ret;
ret=sln.generateParenthesis(3);
for(auto & itr:ret)
cout<<itr<<endl;
return 0;
} | true |
6fede70a723af558ea2c5ceadf68fbaf0151fffc | C++ | Dimbelio/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup- | /Visual Studio 2010/Projects/bjarneStroustrupC++PartIII/bjarneStroustrupC++PartIII/Chapter18Exercise11v4.cpp | UTF-8 | 1,692 | 3.328125 | 3 | [
"MIT"
] | permissive | /*
TITLE Skip List Chapter18Exercise11v2.cpp
"Bjarne Stroustrup "C++ Programming: Principles and Practice.""
COMMENT
Objcective: Research and implement the data structure:
Skip List.
References to the papers by W. Pugh:
http://epaperpress.com/sortsearch/download/skiplist.pdf
http://cglab.ca/~morin/teaching/5408/refs/p90b.pdf
Input: -
Output: -
Author: Chris B. Kirov
Date: 02.12.2017
*/
#include <iostream>
#include <time.h>
#include <string>
#include <sstream>
#include <vector>
#include "Chapter18Exercise11v4.h"
int main ()
{
try
{
// 1.Initialize an empty Skip_list object
Skip_list s;
int elements = 500;
// 2. insert()
for (int i = 0; i < elements ; ++i)
{
std::stringstream ss;
ss << i;
s.insert(i, ss.str());
}
// 2a. print()
std::cout <<"Count: "<< s.get_count() <<'\n';
std::cout <<"Max height: "<< s.get_height() <<'\n';
getchar();
//s.print();
//getchar();
// 3. find()
std::string* f = nullptr;
f = s.find(elements / 2);
if (f)
{
std::cout <<"Node found!\nvalue: "<< *f <<'\n';
}
else
{
std::cout <<"Node NOT found!\n";
}
getchar();
// 4. insert() - reassign
s.insert(499, "TEST");
// 4a. print()
s.print();
getchar();
std::cout <<"\nNodes: "<< s.get_count() <<'\n';
// 5. erase()
s.erase(499);
std::cout <<"\nNodes: "<< s.get_count() <<'\n';
getchar();
// 5a. print();
s.print();
getchar();
std::cout << "\nDone!\n";
}
catch (std::exception& e)
{
std::cerr << e.what();
}
catch (...)
{
std::cerr << "Unhandled exception!\n";
}
getchar();
}
| true |
11d5227ea758c633a20dfc7e64b45e305ceb8cba | C++ | CristhianR/Proyecto-Diagnostico | /ladrilloI.cpp | UTF-8 | 796 | 2.953125 | 3 | [] | no_license | // Clase Ladrillo
#include "ladrilloI.h"
#include <iostream>
#include "bola.h"
using std::cout;
// El constructor carga la imagen del ladrillo e inicializa el flag de la variable bool.
LadrilloI::LadrilloI(int x,int y) {
image.load(":image/bloqueI.png");
destroyed = false;
p = 0;
rect = image.rect();
rect.translate(x, y);
}
LadrilloI::~LadrilloI() {
//std::cout << ("Ladrillo eliminado") << std::endl;
}
QRect LadrilloI::getRect() {
return rect;
}
void LadrilloI::setRect(QRect rct) {
rect = rct;
}
QImage & LadrilloI::getImage() {
return image;
}
// Con la ayuda del flag se sabrá si el ladrillo se dibuja o no.
bool LadrilloI::isDestroyed() {
return destroyed;
}
void LadrilloI::setDestroyed(bool destr) {
if (p == 0)
destroyed = destr;
}
| true |
9a68e1f28de7e22f753b79f895450fc30119a70b | C++ | Voldakk/EVA-Engine | /EVA/Components/MeshRenderer.hpp | UTF-8 | 864 | 2.578125 | 3 | [] | no_license | #pragma once
#include <memory>
#include "../Mesh.hpp"
#include "../Material.hpp"
#include "../Component.hpp"
#include "../ComponentMap.hpp"
namespace EVA
{
class MeshRenderer : public Component
{
REGISTER_COMPONENT(MeshRenderer, "EVA::MeshRenderer")
std::shared_ptr<Mesh> m_Mesh;
std::shared_ptr<Material> m_Material;
FS::path m_ModelPath;
unsigned int m_MeshIndex = 0;
public:
// Public read only fields
const std::shared_ptr<Mesh>& mesh = m_Mesh;
const std::shared_ptr<Material>& material = m_Material;
~MeshRenderer() override;
void Start() override;
void Set(const std::shared_ptr<Mesh>& mesh, const std::shared_ptr<Material>& material);
void Render() const;
virtual void Serialize(DataObject& data) override;
private:
std::shared_ptr<Mesh> GetMesh(const FS::path& modelPath, unsigned int meshIndex);
};
}
| true |
0ef7caeb30b5385e1e61cbbe7942105fbc757914 | C++ | minhaz1217/My-C-Journey | /OJ_UVA/completed/11764 - Jumping Mario_completed_1.cpp | UTF-8 | 592 | 2.84375 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main(){
int tk,n,prev,cur,lj=0,sj=0,caseCounter = 1,i;
cin >> tk;
while(tk--){
cin >> n;
if(cin.eof()){
break;
}
lj=0;
sj = 0;
for(i=0;i<n;i++){
cin >> cur;
if(i!=0){
if(cur > prev){
lj++;
}else if(cur < prev){
sj++;
}
}
prev = cur;
}
cout << "Case " << caseCounter++ << ": " << lj << " " << sj << endl;
}
return 0;
}
| true |
4cc6f35e1321f680ae19119f549ebfcffa7ed409 | C++ | AnluTong/Algrithm | /filter/GaussianFilter.h | UTF-8 | 1,779 | 3.046875 | 3 | [] | no_license | #pragma once
#include "Util.h"
#include "Point.h"
class GaussianFilter
{
public:
GaussianFilter()
{
mSigma = 25;
}
GaussianFilter& setSigma(double sigma)
{
mSigma = sigma;
}
void filter(vector<Point<double>*>& src, vector<list<Point<double>*> >& mapping)
{
if(src.size() == 0 || src[0]->getPointType() != XYZI || src.size() != mapping.size())
{
return;
}
Util::getInstance()
.log("start gaussian filter at ")
.log(Util::getInstance().getCurrentTime())
.endl();
for(int j = 0; j < src.size(); ++j)
{
Point<double>* dest = src[j];
vector<double> pData (4);
Point<double> newPoint (pData);
double totalWeight (0);
for(list<Point<double>*>::iterator it = mapping[j].begin(); it != mapping[j].end(); ++it)
{
Point<double>* iPoint = *it;
double intencityDiv = dest->getValue(3) - iPoint->getValue(3);
double weight = gauss(mSigma, measureDistance(*dest, *iPoint));
totalWeight += weight;
for(int dim = 0; dim < newPoint.getDimensionAmount() - 1; ++dim)
{
//对某维度进行卷积,除去强度值维度
double setValue = newPoint.getValue(dim) + weight * iPoint->getValue(dim);
newPoint.setValue(dim, setValue);
}
}
//权重和不为0,则进行单位化,获取新值
if(totalWeight > 0.0001 || totalWeight < -0.0001)
{
for(int dim = 0; dim < dest->getDimensionAmount() - 1; ++dim)
{
dest->setValue(dim, newPoint.getValue(dim) / totalWeight);
}
}
}
Util::getInstance()
.log("end gaussian filter at ")
.log(Util::getInstance().getCurrentTime())
.endl();
}
private:
double mSigma;
double gauss (double sigma, double distance)
{
return exp(-((distance * distance) / (2 * sigma * sigma)));
}
}; | true |
02be7c460b715258ed8f7c43d05957129867730d | C++ | nanagami1369/UserDBAccesser | /include/User.h | UTF-8 | 780 | 3.171875 | 3 | [
"JSON",
"BSD-3-Clause",
"MIT"
] | permissive | /**
* @file User.h
* @brief ユーザーアカウントを保持するクラス
*/
#pragma once
#include "t_level.h"
#include <string>
/**
* @brief ユーザーアカウントを保持するクラス
* @attention このクラスではデータを保持するだけなので別途バリデーション等をすること
*/
class User {
public:
/** @brief 会員番号 */
uint ID;
/** @brief アカウント名 */
std::string Name;
/** @brief パスワード */
std::string Pass;
/** @brief アカウントの状態 (有効、無効) */
bool Avail;
/** @brief 権限 */
t_Level Level;
User(uint id,
std::string name,
std::string pass,
bool avail,
t_Level level);
std::string toString();
};
| true |
9a8c7237010eb177fdf749eeafd47ff921eb5b58 | C++ | Papagayos-Games/Papagayo-Engine | /Engine/dependencies/LuaBridge3-master/Tests/Source/OptionalTests.cpp | UTF-8 | 2,243 | 2.671875 | 3 | [
"MIT"
] | permissive | // https://github.com/kunitoki/LuaBridge3
// Copyright 2020, Lucio Asnaghi
// SPDX-License-Identifier: MIT
#include "TestBase.h"
#include "LuaBridge/Optional.h"
#include <optional>
struct OptionalTests : TestBase
{
};
TEST_F(OptionalTests, PassToFunction)
{
runLua("function foo (opt) "
" result = opt "
"end");
auto foo = luabridge::getGlobal(L, "foo");
{
resetResult();
std::optional<int> lvalue{ 10 };
foo(lvalue);
EXPECT_FALSE(result().isNil());
EXPECT_EQ(lvalue, result<std::optional<int>>());
resetResult();
const std::optional<int> constLvalue = lvalue;
foo(constLvalue);
EXPECT_FALSE(result().isNil());
EXPECT_EQ(lvalue, result<std::optional<int>>());
}
{
resetResult();
std::optional<std::string> lvalue;
foo(lvalue);
EXPECT_TRUE(result().isNil());
EXPECT_FALSE(result<std::optional<std::string>>());
resetResult();
const std::optional<std::string> constLvalue = lvalue;
foo(constLvalue);
EXPECT_TRUE(result().isNil());
EXPECT_FALSE(result<std::optional<std::string>>());
}
}
TEST_F(OptionalTests, FromCppApi)
{
struct OptionalClass
{
OptionalClass() = default;
void testOptionalAsArg(std::optional<int> v)
{
x = v;
}
std::optional<std::string> testOptionalAsReturn()
{
return "abcdef";
}
std::optional<int> x;
};
luabridge::getGlobalNamespace(L)
.beginClass<OptionalClass>("OptionalClass")
.addConstructor<void (*)()>()
.addFunction("testOptionalAsArg", &OptionalClass::testOptionalAsArg)
.addFunction("testOptionalAsReturn", &OptionalClass::testOptionalAsReturn)
.endClass();
resetResult();
runLua("result = OptionalClass () result:testOptionalAsArg (1337)");
EXPECT_TRUE(result().isUserdata());
EXPECT_EQ(1337, *result<OptionalClass>().x);
resetResult();
runLua("x = OptionalClass () result = x:testOptionalAsReturn ()");
EXPECT_FALSE(result().isNil());
EXPECT_EQ("abcdef", *result<std::optional<std::string>>());
}
| true |
b7a3c20aa33eb1e05fee20248fd9df438938685b | C++ | Jonaslinderoth/MasterThesis | /src/MineClusGPU/MineClusKernels.h | UTF-8 | 2,762 | 2.578125 | 3 | [] | no_license | #ifndef MINECLUSKERNELS_H
#define MINECLUSKERNELS_H
#include <vector>
#include <tuple>
#include <cuda.h>
#include <cuda_runtime.h>
#include <cuda_runtime_api.h>
void createInitialCandidatesWrapper(unsigned int dimGrid,
unsigned int dimBlock,
cudaStream_t stream,
unsigned int dim,
unsigned int* output
);
void extractMaxWrapper(unsigned int dimGrid, unsigned int dimBlock, cudaStream_t stream,
unsigned int* candidates, float* score, unsigned int centroid, unsigned int numberOfCandidates,
unsigned int* bestIndex,
unsigned int dim, unsigned int* bestCandidate, float* bestScore, unsigned int* bestCentroid);
void findPointInClusterWrapper(unsigned int dimGrid, unsigned int dimBlock, cudaStream_t stream,
unsigned int* candidate, float* data, float* centroid, unsigned int dim,
unsigned int numberOfPoints, float width, bool* pointsContained);
void orKernelWrapper(unsigned int dimGrid, unsigned int dimBlock, cudaStream_t stream,
unsigned int numberOfElements, bool* a, bool* b);
void disjointClustersWrapper(unsigned int dimGrid, unsigned int dimBlock, cudaStream_t stream,
unsigned int* centroids, float* scores, unsigned int* subspaces,
float* data, unsigned int numberOfClusters, unsigned int dim,
float width, unsigned int* output);
void unsignedIntToBoolArrayWrapper(unsigned int dimGrid, unsigned int dimBlock, cudaStream_t stream,
unsigned int* input, unsigned int numberOfElements, bool* output);
void copyCentroidWrapper(unsigned int dimGrid, unsigned int dimBlock, cudaStream_t stream,
unsigned int* centroids, float* data, unsigned int dim,
unsigned int numberOfCentroids, float* centroidsOut);
void indexToBoolVectorWrapper(unsigned int dimGrid, unsigned int dimBlock, cudaStream_t stream,
unsigned int* index, unsigned int numberOfElements, bool* output
);
// Testing functions
// ONLY FOR TESTING THE KERNELS
std::vector<unsigned int> createInitialCandidatesTester(unsigned int dim);
std::pair<std::vector<unsigned int>, float> extractMaxTester(std::vector<bool> oldCandidate,
unsigned int oldScore, unsigned int oldCentroid,
std::vector<std::vector<bool>> newCandidates,
std::vector<float> newScores, unsigned int newCentroid,
unsigned int index);
std::vector<bool> findPointsInClusterTester(std::vector<bool> candidate, std::vector<std::vector<float>*>* data, unsigned int centroid, float width);
std::vector<bool> disjointClustersTester(std::vector<std::vector<float>*>* data_v, std::vector<unsigned int> centroids_v, std::vector<unsigned int> subspaces_v, std::vector<float> scores_v);
#endif
| true |
d31fa7593ddab939f72ea2811216ef7be6422a90 | C++ | jondurrant/twinThingExample | /UartThreaded/src/ExampleObserver.h | UTF-8 | 967 | 3.015625 | 3 | [
"MIT"
] | permissive | /*
* ExampleObserver.h
*
* Example Observer takes a state from a StateExample object
* Looks for the state of On state variable and sets the onboard LED to
* be on or off
*
* Created on: 21 Sept 2021
* Author: jondurrant
*/
#ifndef EXAMPLEOBSERVER_H_
#define EXAMPLEOBSERVER_H_
#include "StateObserver.h"
#include "State.h"
#include "StateExample.h"
/***
* Example Observer which prints the delta on notification
*/
class ExampleObserver : public StateObserver {
public:
/***
* Constructor - Attaches to State and initialises the LED
* @param s - State object to attach to
*/
ExampleObserver(StateExample* s);
/***
* Destructor
*/
virtual ~ExampleObserver();
/***
* Notify called by State object to notify of a change.
* @param dirtyCode - used for pulling back delta of only notified change
*/
virtual void notifyState(unsigned char dirtyCode);
private:
StateExample* state = NULL;
};
#endif /* EXAMPLEOBSERVER_H_ */
| true |
f55dc41e3f1cc64102617c6672cf3c19f4aefb1f | C++ | jOnoNe/RTP_SFPC_FALL19 | /opencvExample/src/ofApp.cpp | UTF-8 | 6,423 | 3.328125 | 3 | [] | no_license | #include "ofApp.h"
// Goal: Draw an outline Contour of a human body / the largest object in the videostream.
//
// Steps:
// (1) grabber: Take video input from grabber.
// (2) ofImage `grayscale`: Take the current img from the video stream, and convert it to grayscale.
// (3) ofImage `background`: On keypress, capture the background image.
// (4) ofImage `diff`: Find the difference between the grayscale video img, and the background img.
// (5) ofxCv::ContourFinder `finder`: Use helpful robot from the ofxCv library that can find contours for us, and tell it to find contours in our difference img. We tell the robot to order its list of contours from biggest to smallest, and then tell it to give us the biggest one.
// (6) We draw the biggest contour from the difference image on the video input.
//
//--------------------------------------------------------------
void ofApp::setup(){
// Setup the video input of 640px x 480px
grabber.setup(640,480);
// Make a space in memory for an ofImage called `grayscale`. Make it an image of the same size as the grabber's video input.
// We use OF_IMAGE_GRAYSCALE because a grayscale img will take up different amt of memory than an rgb one.
grayscale.allocate(grabber.getWidth(),grabber.getHeight(), OF_IMAGE_GRAYSCALE);
// Make a space in memory for an ofImage called `background`.
background.allocate(grabber.getWidth(),grabber.getHeight(), OF_IMAGE_GRAYSCALE);
// We set bLearnBackground to true initially, so we have a background img already set on start, when we initially run the program.
bLearnBackground = true;
}
//--------------------------------------------------------------
void ofApp::update(){
// Get new video input. If you don't do this, you won't get new video data!
grabber.update();
// ofxCv::convertColor this is a function from the ofxCv library.
// This function converts the image `grabber` to grayscale, and puts it in the ofImage `grayscale`.
// `CV_RGB2GRAY` is a special keyword telling it to do the transformation: change from RGB to grayscale.
convertColor(grabber, grayscale, CV_RGB2GRAY);
// bLearnBackground = 'boolean learn background'. This `b` thing is a naming scheme for booleans. Another naming suggestion from the group was `shouldCaptureBackground`.
// This is a boolean flag that will be used to capture the background image on keypress.
//
if (bLearnBackground == true){
// Assign all the pixels in the ofImage `background` to all the pixels in the ofImage `grayscale`.
background.setFromPixels(grayscale.getPixels());
bLearnBackground = false;
}
// ofxCv::absdiff This is a function from the ofxCv library.
// This function subtracts the two images `grayscale` and `background`, and puts the result in `diff:
// `diff` = abs(`grayscale` - `background`)
// An important nuance here is why we use *abs*diff, which takes the *absolute value* of the difference. We do this (and not just a regular substraction), because we care about any difference- the direction of the difference does not matter.
// For example, if a light object is on a dark background, we want that to be picked up. If a dark object is on a light background, that should also be picked up.
absdiff(grayscale, background, diff);
// ofxCv::threshold This is a function from the ofxCv library.
// According to a threshold, make dark pixels in `diff` and make them all black, and make light pixels white.
// mouseX to adjust the threshold
threshold(diff, mouseX);
// "Save" the changes you've put in your ofImage containers.
diff.update();
background.update();
grayscale.update();
// ofxCv ContourFinder
// `finder` is a helpful robot from the ofxCv library that can find contours for us!
finder.setSortBySize(true); // Hey robot, while you're finding the contours, sort the contours by biggest first.
finder.findContours(diff); // Find the white blobs in `diff`.
}
//--------------------------------------------------------------
void ofApp::draw(){
ofScale(0.7, 0.7); // Don't draw too big, so we draw at 70%.
// Draw video input at top left.
grabber.draw(0,0);
// Draw grayscale image at top right.
grayscale.draw(grabber.getWidth(), 0);
// Draw background img in bottom left.
background.draw(0,grabber.getHeight());
// Draw diff img in bottom right.
diff.draw(grabber.getWidth(), grabber.getHeight());
// If the helpful robot `finder` has found any contours to give us,
if (finder.size() > 0){
// Get the first contour in the list-- the biggest contour. `finder` has a list of all the contours in the image, stored as polylines.
ofPolyline line = finder.getPolyline(0);
// Draw the biggest contour.
// Note: the contour is drawn on the top left img (the video input), even though the contour is taken from the bottom right img (the diff img).
line.draw();
}
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
// When a key is pressed, capture a new background img.
bLearnBackground = true;
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| true |
fa8bb84d710928b7196712d2ecf034e1b44240e8 | C++ | rovinbhandari/Programming_Scripting | /C_C++/preSem4/CS201/lab5/AKKImain.cpp | UTF-8 | 1,214 | 3.3125 | 3 | [] | no_license | //#include "../include/head.h"
#include <iostream>
using namespace std;
struct tree
{
int data;
tree *left;
tree *right;
};
void insert(tree *a, int x);
void inorder( tree *a);
void postorder( tree *a);
void preorder( tree *a);
int main(){
tree *root= new tree;
tree *pos= new tree;
cout<<"enter root";
int x;
cin>>x;
root->data=x;
root->left=NULL;
root->right=NULL;
cout<<"enter any value to insert except 0";
cin>>x;
while(x!=0){
pos=root;
insert(pos,x);
cout<<"enter value";
cin>>x;
}
pos=root;
inorder(pos);
cout<<"\n";
postorder(pos);
cout<<"\n";
preorder(pos);
cout<<"\n";
return 0;
}
void insert(tree *a, int x){
if(a->data<x)
{
if(a->right==NULL)
{a->right= new tree;
a=a->right;
a->data=x;
}
else{
insert(a->right,x);
}
}
else{
if(a->left==NULL)
{a->left= new tree;
a=a->left;
a->data=x;
}
else{
insert(a->left,x);
}
}
}
void inorder( tree *a){
if(a->left!=NULL){
inorder(a->left);}
cout<<a->data;
if(a->right!=NULL){
inorder(a->right);
}
}
void postorder( tree *a){
if(a->left!=NULL){
postorder(a->left);}
if(a->right!=NULL){
postorder(a->right);
}
cout<<a->data;
}
void preorder( tree *a){
cout<<a->data;
if(a->left!=NULL){
preorder(a->left);}
if(a->right!=NULL){
preorder(a->right);
}}
| true |
cbdf296a7ecd9ab0e8321fb89108f6535d14ff77 | C++ | BigETI/NoLifeNoCry | /engine/src/Utilities.cpp | UTF-8 | 383 | 2.6875 | 3 | [
"MIT"
] | permissive | #include <ctime>
#include <Utilities.hpp>
/// @brief Gets the date and time string from point
/// @param timePoint Time point
/// @return Date and time string
std::string DirtMachine::Utilities::GetDateTimeStringFromTimePoint(const std::chrono::system_clock::time_point& timePoint)
{
std::time_t time = std::chrono::system_clock::to_time_t(timePoint);
return std::ctime(&time);
}
| true |
e2fe78d637f3c05238523884978c8a345ba5ca51 | C++ | WiseCow/algorithm | /BOJ/모든 순열.cpp | UTF-8 | 658 | 2.78125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int N;
void dfs(int now, int jari,int map[10],bool visit[10])
{
if (jari == N + 1)
{
for (int i = 1; i <= N; i++)
{
printf("%d ", map[i]);
}
printf("\n");
}
else
{
for (int i = 1; i <= N; i++)
{
if (!visit[i])
{
map[jari] = i;
visit[i] = 1;
dfs(i, jari+1, map,visit);
map[jari] = 0;
visit[i] = 0;
}
}
}
}
int main()
{
scanf("%d", &N);
for (int i = 1; i <= N; i++)
{
int map[10] = { 0 };
bool visit[10] = { 0 };
map[1] = i;
visit[i] = 1;
dfs(i, 2, map,visit);
map[1] = 0;
visit[i] = 0;
}
return 0;
} | true |
43e907ff747fd4b5a0356002d9aa49f77859158d | C++ | shubham061996/Prebootcamp_course | /coursera/Algorithm_specialization/2.Graph Search, Shortest Paths, and Data Structures/week 4/2_sum.cpp | UTF-8 | 2,143 | 2.640625 | 3 | [] | no_license | #include<bits/stdc++.h>
#define NUM_ELEMENTS 1000000
#define MIN -10000
#define MAX 10000
using namespace std;
long long data[NUM_ELEMENTS];
int main()
{
ifstream fin;
fin.open("sum.txt");
for (int i = 0; i < NUM_ELEMENTS; i++)
{
fin >> data[i];
}
fin.close();
sort(data, data + NUM_ELEMENTS);
int start = 0;
int end = NUM_ELEMENTS - 1;
bool found[MAX - MIN + 1];
for (int i = MIN; i <= MAX; i++)
{
found[i - MIN] = false;
}
while (start < end)
{
long long probe_sum = data[start] + data[end];
if (probe_sum < MIN)
{
start++;
}
else if (probe_sum > MAX)
{
end--;
}
else
{
if (data[start] != data[end])
{
found[probe_sum - MIN] = true;
}
int current_start = start;
int current_end = end;
while (true)
{
start++;
long long probe_sum = data[start] + data[end];
if (probe_sum > MAX)
{
break;
}
else
{
if (data[start] != data[end])
{
found[probe_sum - MIN] = true;
}
}
}
start = current_start;
while (true)
{
end--;
long long probe_sum = data[start] + data[end];
if (probe_sum < MIN)
{
break;
}
else
{
if (data[start] != data[end])
{
found[probe_sum - MIN] = true;
}
}
}
end = current_end;
start++;
end--;
}
}
int count = 0;
for (int i = MIN; i <= MAX; i++)
{
if (found[i - MIN])
{
count++;
}
}
cout << count << endl;
return 0;
}
| true |
2ab98995d639e5f1588ec6ce4c7d27e21f69b54a | C++ | arbor-sim/arbor | /arbor/symmetric_recipe.cpp | UTF-8 | 1,668 | 2.609375 | 3 | [
"BSD-3-Clause"
] | permissive | #include <arbor/symmetric_recipe.hpp>
namespace arb {
cell_size_type symmetric_recipe::num_cells() const {
return tiled_recipe_->num_cells() * tiled_recipe_->num_tiles();
}
util::unique_any symmetric_recipe::get_cell_description(cell_gid_type i) const {
return tiled_recipe_->get_cell_description(i % tiled_recipe_->num_cells());
}
cell_kind symmetric_recipe::get_cell_kind(cell_gid_type i) const {
return tiled_recipe_->get_cell_kind(i % tiled_recipe_->num_cells());
}
// Only function that calls the underlying tile's function on the same gid.
// This is because applying transformations to event generators is not straightforward.
std::vector<event_generator> symmetric_recipe::event_generators(cell_gid_type i) const {
return tiled_recipe_->event_generators(i);
}
// Take connections_on from the original tile recipe for the cell we are duplicating.
// Transate the source and destination gids
std::vector<cell_connection> symmetric_recipe::connections_on(cell_gid_type i) const {
int n_local = tiled_recipe_->num_cells();
int n_global = num_cells();
int offset = (i / n_local) * n_local;
std::vector<cell_connection> conns = tiled_recipe_->connections_on(i % n_local);
for (unsigned j = 0; j < conns.size(); j++) {
conns[j].source.gid = (conns[j].source.gid + offset) % n_global;
}
return conns;
}
std::vector<probe_info> symmetric_recipe::get_probes(cell_gid_type i) const {
i %= tiled_recipe_->num_cells();
return tiled_recipe_->get_probes(i);
}
std::any symmetric_recipe::get_global_properties(cell_kind ck) const {
return tiled_recipe_->get_global_properties(ck);
};
} //namespace arb | true |
566a801c9447ef08c6f64a11635798fac1afa28f | C++ | withseungryu/Algorithms | /BackJoon/Greedy Algorithm/2217.cpp | UTF-8 | 473 | 2.8125 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
int N;
vector<int> rope;
int weight() {
int maximum = 0;
sort(rope.begin(), rope.end());
for (int i = 0; i < N; ++i) {
maximum = max(maximum, rope[i]*(N-i));
}
return maximum;
}
int main() {
scanf("%d", &N);
for (int i = 0; i < N; ++i) {
int tmp;
scanf("%d", &tmp);
rope.push_back(tmp);
}
printf("%d",weight());
} | true |
1bc35768668aa561a930ec11a39a619f34486bed | C++ | JohannEid/Dijkstra-Primm-and-other-algorithms... | /Graph.cpp | UTF-8 | 7,753 | 3.03125 | 3 | [] | no_license | //
// Created by johann on 15/03/17.
//
#include "Graph.h"
std::multiset<Edges> Graph::readFromFile() {
int compteur{0};
int value{0};
std::vector<int> temporary_values;
std::multiset<Edges> edges_collection;
std::ifstream myfile("source.txt");
if (myfile.is_open()) {
while (myfile >> value) {
++compteur;
if (compteur == 1) {
setOrder(value);
create_summit_collection();
} else if (compteur == 2) { setNumber_of_edges(value); }
else if (((compteur - 2) % 3 == 0) && (compteur > 2)) {
temporary_values.push_back(value);
edges_collection.insert(Edges(std::make_pair(&m_summits[temporary_values[compteur - 5]],
&m_summits[temporary_values[compteur - 4]]),
temporary_values[compteur - 3]));
} else {
temporary_values.push_back(value);
}
}
myfile.close();
} else { std::cout << "Couldn't open file" << std::endl; }
return edges_collection;
}
void Graph::solveKruskal() {
std::multiset<Edges> edges_collection = readFromFile();
for (auto &elem : edges_collection) {
if (elem.getSummits().first->getUnion() != elem.getSummits().second->getUnion())
m_smallest_weight_tree.push_back(elem);
solveUnions(elem, edges_collection);
}
}
void Graph::solveUnions(const Edges &to_unite, std::multiset<Edges> &edges_collection) {
int uni_lhs{to_unite.getSummits().first->getUnion()};
int uni_rhs{to_unite.getSummits().second->getUnion()};
for (auto &elem : edges_collection) {
if (elem.getSummits().first->getUnion() == uni_rhs) { elem.m_summits.first->setUnion(uni_lhs); }
else if (elem.getSummits().second->getUnion() == uni_rhs) {
elem.m_summits.second->setUnion(uni_lhs);
}
}
}
void Graph::solvePrimm() {
std::multiset<Edges> edges_collection = readFromFile();
edges_collection.begin()->getSummits().first->setVisited(true);
while (get_visited_summits() < getOrder() - 1) {
for (auto &elem : edges_collection) {
if ((elem.getSummits().first->isVisited()) &&
(!elem.getSummits().second->isVisited())) {
m_primm_algorithms.push_back(elem);
elem.getSummits().second->setVisited(true);
increment_visited_summits();
} else if ((elem.getSummits().second->isVisited()) &&
(!elem.getSummits().first->isVisited())) {
m_primm_algorithms.push_back(elem);
elem.getSummits().first->setVisited(true);
increment_visited_summits();
}
}
}
}
void Graph::display_graph(std::vector<Edges> &to_display) {
for (const auto &elem : to_display) {
std::cout << elem.getSummits().first->getId() << " ";
std::cout << elem.getSummits().second->getId() << " ";
std::cout << elem.getValue() << std::endl;
}
}
std::vector<std::vector<int >> Graph::readFromFileAdjacency() {
int value{0};
int compteur{0};
std::ifstream myfile("adjacency.txt");
std::vector<int> line;
std::vector<std::vector<int>> adjacency_matrix;
if (myfile.is_open()) {
while (myfile >> value) {
if (compteur == 0) { setOrder(value); }
else if (compteur % getOrder() != 0) { line.push_back(value); }
else if (compteur % getOrder() == 0) {
line.push_back(value);
adjacency_matrix.push_back(line);
line.clear();
}
++compteur;
}
} else { std::cout << "Couldn't open file" << std::endl; }
myfile.close();
return adjacency_matrix;
}
void Graph::solveDijkstra() {
std::vector<std::vector<int>> adjacency_matrix = readFromFileAdjacency();
std::priority_queue<Summit *, std::vector<Summit *>, std::greater<Summit *>> priority_queue;
int weight{0};
int source_id{0};
int distance{0};
create_summit_collection();
for (int i{0}; i < getOrder(); ++i) {
weight = (i == 0) ? 0 : -1;
m_summits[i].setWeight(weight);
priority_queue.push(&m_summits[i]);
}
while (!priority_queue.empty()) {
source_id = priority_queue.top()->getId();
for (int i{0}; i < getOrder(); ++i) {
distance = adjacency_matrix[source_id][i];
weight = distance + m_summits[source_id].getWeight();
if ((distance > 0) && (!m_summits[i].isVisited()) &&
((weight < m_summits[i].getWeight()) ||
(m_summits[i].getWeight() == -1))) {
m_summits[i].setWeight(weight);
m_summits[i].setM_previous(source_id);
}
}
m_summits[source_id].setVisited(true);
priority_queue.pop();
}
}
void Graph::display_dijkstra() {
for (const auto &elem: getM_summits()) {
std::cout << "Summit is : " << elem.getId() << "its shortest path is " << elem.getWeight() << std::endl;
}
}
void Graph::create_summit_collection() {
m_summits.clear();
for (int i{0}; i < getOrder(); ++i) {
m_summits.push_back(Summit(i));
}
}
void Graph::display_primm() {
std::cout << "PRIMM ALGORITHM" << std::endl;
display_graph(m_primm_algorithms);
}
void Graph::display_kruskal() {
std::cout << "KRUSKAL ALGORITHM" << std::endl;
display_graph(m_smallest_weight_tree);
}
void Graph::save_to_file(const std::string &file_name) {
std::ofstream my_file;
my_file.open(file_name);
try {
if (file_name == "primm.txt") {
save_graph(m_primm_algorithms, file_name);
} else if (file_name == "kruskal.txt") {
save_graph(m_smallest_weight_tree, file_name);
} else if (file_name == "dijkstra.txt") {
for (const auto &elem: getM_summits()) {
my_file << "Summit is : " << elem.getId()
<< "its shortest path is " << elem.getWeight() << std::endl;
}
} else {
throw std::domain_error("wrong input file_name ");
}
}
catch (std::exception const &e) {
std::cerr << "Erreur" << e.what() << std::endl;
}
}
void menu_choice(Graph &graph) {
std::string ichoice{" "};
int choice{0};
while (true) {
std::cout << "Please enter" << std::endl << "1.Kruskal" << std::endl << "2.Primm" << std::endl
<< "3.Dijkstra" << std::endl << "4.Quit" << std::endl;
try {
std::cin >> ichoice;
choice = std::stoi(ichoice);
if (choice == 1) {
graph.solveKruskal();
graph.display_kruskal();
} else if (choice == 2) {
graph.solvePrimm();
graph.display_primm();
} else if (choice == 3) {
graph.solveDijkstra();
graph.display_dijkstra();
} else if (choice == 4) {
break;
} else {
throw std::domain_error("Invalid choice ");
}
}
catch (std::exception const &e) {
std::cerr << "Erreur" << e.what() << std::endl;
}
}
}
void Graph::save_graph(std::vector<Edges> &to_display, const std::string &file_name) {
std::ofstream my_file;
my_file.open(file_name);
for (const auto &elem : to_display) {
my_file << elem.getSummits().first->getId() << " ";
my_file << elem.getSummits().second->getId() << " ";
my_file << elem.getValue() << std::endl;
}
}
| true |
bad7d11af4beef63fcf7c0c97bd1e19302062a04 | C++ | ericaddison/GWFisherMatrix | /gslWrappers.cpp | UTF-8 | 16,743 | 2.78125 | 3 | [] | no_license | /*--------------------------------
** USU FAST Group
** Eric Addison
** gslWrappers.cpp
** implementation of gslWrappers classes
*--------------------------------*/
#include "gslWrappers.h"
namespace gslWrappers
{
//************************************************************
// gslRootFinder
//************************************************************
/// Root finder class using Brent's method
gslRootFinder::gslRootFinder(double xmin, double xmax, double (*f)(double,void*), double Niter, double reltol, double abstol)
/// constructor
// inputs: xmin, xmax = interval endpoints
// *f = pointer to function to find root of
// Niter = max number of iteratons -- default = 1000;
// reltol = relative error tolerance
// abstol = absolute error tolerance
{
x_lo = xmin;
x_hi = xmax;
F.function = f;
F.params = NULL; // params needs to be explicitly set if needed
max_iter = Niter;
epsrel = reltol;
epsabs = abstol;
rootFinderInit();
}
gslRootFinder::~gslRootFinder()
/// destructor
{
gsl_root_fsolver_free (s);
}
void gslRootFinder::rootFinderInit()
/// initialize root finder stuff
{
T = gsl_root_fsolver_brent;
s = gsl_root_fsolver_alloc (T);
}
double gslRootFinder::findRoot()
{
gsl_root_fsolver_set (s, &F, x_lo, x_hi);
int status, iter=0;
double r=0;
do {
iter++;
status = gsl_root_fsolver_iterate (s);
r = gsl_root_fsolver_root (s);
x_lo = gsl_root_fsolver_x_lower (s);
x_hi = gsl_root_fsolver_x_upper (s);
status = gsl_root_test_interval (x_lo, x_hi,epsabs,epsrel);
} while (status == GSL_CONTINUE && iter < max_iter);
root = r;
return r;
}
//************************************************************
// gslIntegrator
//************************************************************
gslIntegrator::gslIntegrator()
/// default constructor
{
w = gsl_integration_cquad_workspace_alloc(10000); // set up workspace
initd = false; // integrand F has NOT been set
got_pars = false;
nevals = result = error = 0;
epsabs = 0;
epsrel = 1e-7; // initialized error tolerances
}
gslIntegrator::gslIntegrator(gsl_function G)
/// constructor with gsl_function argument
{
w = gsl_integration_cquad_workspace_alloc(10000); // set up workspace
F = G;
initd = true; // integrand F has been set
got_pars = true;
nevals = result = error = 0;
epsabs = 0;
epsrel = 1e-7; // initialized error tolerances
}
gslIntegrator::gslIntegrator(double (*f)(double x, void * params))
/// constructor with function pointer input
{
w = gsl_integration_cquad_workspace_alloc(10000); // set up workspace
F.function = f;
initd = true; // integrand F has been set
got_pars = false;
nevals = result = error = 0;
epsabs = 0;
epsrel = 1e-7; // initialized error tolerances
}
gslIntegrator::gslIntegrator(double (*f)(double x, void * params), void * params)
/// constructor with function pointer input and params
{
w = gsl_integration_cquad_workspace_alloc(10000); // set up workspace
F.function = f;
F.params = params;
initd = true; // integrand F has been set
got_pars = true;
result = nevals = error = 0;
epsabs = 0;
epsrel = 1e-7; // initialized error tolerances
}
gslIntegrator::~gslIntegrator()
/// destructor
{
gsl_integration_cquad_workspace_free (w);
}
void gslIntegrator::set_integrand(gsl_function G)
/// change integrand function
{ F = G; }
void gslIntegrator::set_integrand(double (*f)(double x, void * params))
/// another change integrand function
{ F.function = f; initd = true; got_pars = false; }
void gslIntegrator::set_params(void * p)
/// set params pointer
{
F.params = p;
got_pars = true;
}
bool gslIntegrator::init_checker(const char * fun)
/// check if initialization is complete
{
using std::cerr;
if( !initd )
{
cerr << "\nError: gslWrappers::gslIntegrator::" << fun << " -- integrand not initialized";
return false;
}
else if( !got_pars )
{
cerr << "\nError: gslWrappers::gslIntegrator::" << fun << " -- params pointer not initialized";
return false;
}
return true;
}
double gslIntegrator::get_result()
/// return result
{
if( !init_checker("get_result()") )
return 0;
return result;
}
double gslIntegrator::get_error()
/// return error
{
if( !init_checker("get_error()") )
return 0;
return error;
}
double gslIntegrator::get_nevals()
/// return error
{
if( !init_checker("get_nevals()") )
return 0;
return nevals;
}
void gslIntegrator::set_epsabs(double e)
/// set absolute error tolerance
{ epsabs = e; }
void gslIntegrator::set_epsrel(double e)
/// set relative error tolerance
{ epsrel = e; }
double gslIntegrator::get_epsabs()
/// set absolute error tolerance
{ return epsabs; }
double gslIntegrator::get_epsrel()
/// set relative error tolerance
{ return epsrel; }
double gslIntegrator::integrate(double xmin, double xmax)
/// do the integration
{
if ( !init_checker("integrate()") )
return 0;
gsl_integration_cquad(&F,xmin,xmax,epsabs,epsrel,w,&result,&error,&nevals);
return result;
}
double gslIntegrator::integrate(double xmin, double xmax, void * p)
/// do the integration and provide params
{
F.params = p;
got_pars = true;
if ( !init_checker("integrate()") )
return 0;
gsl_integration_cquad(&F,xmin,xmax,epsabs,epsrel,w,&result,&error,&nevals);
return result;
}
double gslIntegrator::operator()(double xmin, double xmax, void * p)
{ return integrate(xmin,xmax,p); }
double gslIntegrator::operator()(double xmin, double xmax)
{ return integrate(xmin,xmax); }
//************************************************************
// gslMatrix
//************************************************************
gslMatrix::gslMatrix()
/// default constructor
{
m = gsl_matrix_alloc (1, 1); // allocate space for a 1x1
gsl_matrix_set (m, 1, 1, 0.0); // set value to 0
rows = cols = 1;
loc[0] = loc[1] = 0;
temp = 0.0;
}
gslMatrix::gslMatrix(int M, int N)
/// construct empty MxN matrix
{
m = gsl_matrix_alloc(M,N); // allocate space for MxN
for(int i=0; i<M; i++) { // set all values to zero
for(int j=0; j<N; j++)
gsl_matrix_set(m,i,j,0.0);
}
rows = M;
cols = N;
loc[0] = loc[1] = 0;
temp = 0.0;
}
gslMatrix::gslMatrix(const gslMatrix & n)
/// copy constructor
{
rows = n.rows;
cols = n.cols; // copy rows and cols
m = gsl_matrix_alloc(rows,cols);// allocate new space
for(int i=0; i<rows; i++) { // deep copy
for(int j=0; j<cols; j++)
gsl_matrix_set(m,i,j,gsl_matrix_get(n.m,i,j));
}
loc[0] = loc[1] = 0;
temp = gsl_matrix_get(n.m,0,0);
}
gslMatrix::gslMatrix(const gsl_matrix * n, int i,int j)
{
rows = i;
cols = j; // copy rows and cols
m = gsl_matrix_alloc(rows,cols);// allocate new space
for(int i=0; i<rows; i++) { // deep copy
for(int j=0; j<cols; j++)
gsl_matrix_set(m,i,j,gsl_matrix_get(n,i,j));
}
loc[0] = loc[1] = 0;
temp = gsl_matrix_get(m,0,0);
}
gslMatrix::gslMatrix(double *X, int i, int j)
/// constructor for double ** (inside of MatInit)
{
rows = i;
cols = j; // copy rows and cols
fflush(stdout);
m = gsl_matrix_alloc(rows,cols);// allocate new space
for(int i=0; i<rows; i++) { // deep copy
for(int j=0; j<cols; j++)
gsl_matrix_set(m,i,j,X[i*cols+j]);
}
loc[0] = loc[1] = 0;
temp = gsl_matrix_get(m,0,0);
}
gslMatrix::~gslMatrix()
/// destructor
{ gsl_matrix_free (m); }
void gslMatrix::reassign()
/// reassign value to loc position
{
gsl_matrix_set(m,loc[0],loc[1],temp);
}
double & gslMatrix::operator()(const int i, const int j)
/// overload the () operator
{
if ( i<0 || i>=rows || j<0 || j>=cols )
{
std::cerr << "\nError: gslWrappers::gslMatrix::operator() -- Matrix indices out of bounds";
temp = GSL_WRAP_ERR;
return temp;
}
reassign();
temp = gsl_matrix_get(m,i,j);
loc[0] = i; loc[1] = j;
return temp;
}
void gslMatrix::show(std::ostream & os)
/// print out matrix with default ostream as cout
{
reassign();
using std::endl;
using std::setw;
os << endl;
for (int i=0; i<rows; i++)
{
os << "[";
for (int j=0; j<cols; j++)
os << setw(4) << gsl_matrix_get(m,i,j) << ", ";
os << "\b\b ]" << endl;
}
}
gslMatrix & gslMatrix::operator=(const gslMatrix & n)
/// assignment operator
{
reassign();
gsl_matrix_free (m); // free old memory
rows = n.rows;
cols = n.cols; // copy rows and cols
m = gsl_matrix_alloc(rows,cols);// allocate new space
for(int i=0; i<rows; i++) { // deep copy
for(int j=0; j<cols; j++)
gsl_matrix_set(m,i,j,gsl_matrix_get(n.m,i,j));
}
loc[0] = loc[1] = 0;
temp = gsl_matrix_get(n.m,0,0);
return *this;
}
gslMatrix gslMatrix::operator+(const gslMatrix & n)
/// addition operator
{
reassign();
gslMatrix sum(*this); // new sum matrix
gsl_matrix_add(sum.m,n.m); // gsl addition routine
return sum;
}
gslMatrix gslMatrix::operator-()
/// negation operator
{
reassign();
gslMatrix neg(*this); // new sum matrix
for(int i=0; i<rows; i++) { // deep copy
for(int j=0; j<cols; j++)
gsl_matrix_set(neg.m,i,j,-gsl_matrix_get(neg.m,i,j));
}
return neg;
}
gslMatrix gslMatrix::operator-(const gslMatrix & n)
/// subtraction operator
{
reassign();
gslMatrix diff(*this); // new sum matrix
gsl_matrix_sub(diff.m,n.m); // gsl addition routine
return diff;
}
gslMatrix gslMatrix::operator*(const double k)
/// scalar multiplication
{
reassign();
gslMatrix prod(*this);
gsl_matrix_scale(prod.m,k);
return prod;
}
gslMatrix gslMatrix::operator+(const double k)
/// add a constant value to the whole matrix
{
reassign();
gslMatrix sum(*this);
gsl_matrix_add_constant(sum.m,k);
return sum;
}
gslMatrix gslMatrix::operator&(const gslMatrix & n)
/// elementwise multiplication -- like matlab .*
{
reassign();
gslMatrix prod(*this);
gsl_matrix_mul_elements(prod.m,n.m);
return prod;
}
gslMatrix gslMatrix::operator|(const gslMatrix & n)
/// elementwise division -- like matlab ./
{
reassign();
gslMatrix quot(*this);
gsl_matrix_div_elements(quot.m,n.m);
return quot;
}
gslMatrix gslMatrix::operator*(const gslMatrix & n)
/// matrix-matrix multiplication
{
reassign();
if (cols != n.rows)
{
std::cerr << "\nError: gslWrappers::gslMatrix::operator* -- inner matrix dimensions must agree";
gslMatrix err(1,1);
err(1,1) = GSL_WRAP_ERR;
return err;
}
gslMatrix prod(rows,n.cols);
// call to the gsl interface to BLAS functions:
// http://www.gnu.org/software/gsl/manual/html_node/Level-3-GSL-BLAS-Interface.html
gsl_blas_dgemm(CblasNoTrans,CblasNoTrans,1.0,m,n.m,0.0,prod.m);
return prod;
}
gslMatrix gslMatrix::operator~()
/// inversion operator
{
reassign();
if(rows != cols)
{
std::cerr << "\nError: gslWrappers::gslMatrix::operator~ -- Matrix must be square";
gslMatrix inv(rows,cols);
return inv;
}
// the following code is weird, but it works.
// my original attempt didn't work, so this is what I will use
// similar to gsl example: http://www.gnu.org/software/gsl/manual/html_node/Linear-Algebra-Examples.html
gsl_matrix *M = gsl_matrix_alloc( rows, cols);
gsl_matrix_memcpy( M,m );
gsl_matrix *inv1 = gsl_matrix_alloc(rows,cols);
int s;
gsl_permutation * p = gsl_permutation_alloc (rows);
gsl_linalg_LU_decomp (M, p, &s);
gsl_linalg_LU_invert (M, p, inv1);
gslMatrix inv(inv1,rows,cols); // make new gslMatrix using inv1
gsl_matrix_free(M);
gsl_matrix_free(inv1);
gsl_permutation_free(p);
return inv; // return inv
}
gslMatrix gslMatrix::inv()
/// another inversion call
{ reassign(); return ~(*this); }
gslMatrix gslMatrix::operator*=( const gslMatrix & n)
{
reassign();
(*this) = (*this)*n;
return *this;
}
gslMatrix gslMatrix::operator+=( const gslMatrix & n)
{
reassign();
(*this) = (*this)+n;
return *this;
}
gslMatrix gslMatrix::operator^(int k)
/// raise a matrix to a power
{
reassign();
if(rows != cols)
{
std::cerr << "\nError: gslWrappers::gslMatrix::operator^ -- Matrix must be square";
gslMatrix inv(1,1);
return inv;
}
if (k == 0)
return eye();
else if(k > 0)
{
gslMatrix prod(rows,cols);
prod = (*this);
for(int i=0;i<k-1;i++)
prod *= (*this);
return prod;
}
else
{
gslMatrix prod(rows,cols);
gslMatrix inv(rows,cols);
inv = ~(*this);
prod = inv;
for(int i=0;i<abs(k)-1;i++)
prod *= inv;
return prod;
}
}
gslMatrix gslMatrix::eye(int n)
/// return an identity matrix of size n
{
reassign();
if (n==0)
n=rows;
else
n = ( n>0 ? n : 1);
gslMatrix I(n,n);
for(int i=0;i<n;i++)
I(i,i) = 1;
return I;
}
gslMatrix operator*(const double k, gslMatrix & M )
{ return M*k; }
gslMatrix operator+(const double k, gslMatrix & M )
{ return M+k; }
//************************************************************
// gslCSpline
//************************************************************
gslCSpline::gslCSpline(double * x, double * y, int N)
/// constructor
{
// define spline working variables
acc = gsl_interp_accel_alloc ();
spline = gsl_spline_alloc (gsl_interp_cspline,N); // allocate spline
// initialize spline
gsl_spline_init(spline,x,y,N);
initd = 1;
}
gslCSpline::~gslCSpline()
/// destructor
{
gsl_spline_free (spline);
gsl_interp_accel_free(acc);
}
double gslCSpline::operator()(double xi)
/// overload () for interpolation calls
{
if (initd)
return gsl_spline_eval(spline,xi,acc);
else
{
std::cerr << "\nError: gslWrappers::gslCSpline::operator() -- spline not initialized\n";
return GSL_WRAP_ERR;
}
}
void gslCSpline::init_spline(double * x, double * y, int N)
{
// define spline working variables
acc = gsl_interp_accel_alloc ();
spline = gsl_spline_alloc (gsl_interp_cspline,N); // allocate spline
// initialize spline
gsl_spline_init(spline,x,y,N);
initd = 1;
}
//************************************************************
// Test Functions
//************************************************************
void MatrixTest()
{
using std::cout;
using std::endl;
cout << "\nCreating empty matrix...";
gslMatrix M(3,3);
cout << "success\n";
cout << "Testing (i,j) opertor:\n";
cout << "\tM(2,2) = " << M(2,2) << endl;
cout << "\tM(1,1) = " << M(1,1) << endl;
cout << "\nTesting (i,j) on assignment on M(1,1)...";
fflush(stdout);
M(1,1) = 12.0;
cout << "Success\n\tM(1,1) = " << M(1,1) << endl;
cout << "\nTesting matrix show() routine:\n";
M.show();
cout << "\nCreating two new matrices for multiplication test...";
double f[2][3] = {{1.0, 2.0, 3.0},{3.0,4.0,3.0}};
double g[3][4] = {{1,2,3,4}, {2,3,4,5}, {4,5,6,7}};
gslMatrix M1(f[0],2,3), M2(g[0],3,4);
M1.show();
M2.show();
cout << "Product M1*M2 = ";
(M1*M2).show();
cout << "\nTesting identity .eye() function...";
M1.eye().show();
M2.eye(4).show();
cout << "\nTesting inversion...";
double h[3][3] = { {1,2,3},{4,5,6},{1,3,7} };
//double h[3][3] = { {1,0,0},{0,1,0},{0,0,1} };
gslMatrix M3(h[0],3,3);
M3.show();
cout << "inv(M3):\n";
M3.inv().show();
cout << "\nM3 * inv(M3):";
( M3 * ~M3).show();
cout << "\nTesting matrix power M^3:\n";
double ff[3][3] = {{ 2,0,0},{0,2,0},{0,0,2}};
gslMatrix M4(ff[0],3,3);
(M4^-3).show();
cout <<"\nTesting += and M+k:\n";
M4+=(2*M4);
M4.show();
}
double func(double x, void * params)
{
double a = *( (double *) params);
return a*x;
}
double gunc(double x, void * params)
{
(void)params; // params not used
return x*cos(x)+exp(-x*x);
}
void IntTest()
{
using std::cout;
using std::endl;
cout << "Creating a gslIntegrator object with function func...";
gslIntegrator inter(&func);
cout << "Success\n";
cout << "\nAttemtping integration of f(x)=x from x=[0..10]...";
double a = 1;
cout << "\n\tresult = " << inter.integrate(0,10,(void*)&a) << "\n";
cout << "\nAttemtping integration of g(x)=x*cos(x)+exp(-x^2) from x=[0..10]...";
inter.set_integrand(&gunc);
inter.integrate(0,1);
inter.set_params(NULL);
cout << "\n\tresult = " << inter(0,10) << "\n";
}
void rootTest()
{
using namespace std;
cout << "Creating a gslRootFinder object with function func2 = x^2-3...";
gslRootFinder finder(0,5,&func2);
cout << "Success!\n\n";
cout << "Finding root...";
finder.findRoot();
cout << "Success! root = " << finder.get_root() << endl;
}
double func2(double x, void * params)
{
(void)params;
return x*x - 3;
}
} // END NAMESPACE GSLWRAPPERS
| true |
5219d0e0644619ae5b87e9144eaf94bb59f26fdc | C++ | AdityaWadhwa/CANSAT_GAGAN_2020 | /PayloadCodes/SDcode.ino | UTF-8 | 1,608 | 2.6875 | 3 | [] | no_license |
void setupSD()
{
//pinMode(CSpin, OUTPUT);
// see if the card is present and can be initialized:
if (!SD.begin(10)) // CS pin is D10
{
Serial.println(F("Card failed, or not present")); // don't do anything more:
return;
}
//Serial.println(F("card initialized."));
/*
Serial.println("Creating Packets.csv...");
sensorData = SD.open("Packets.txt", FILE_WRITE);
sensorData.close();
*/
//Serial.println(F("Creating Hello.csv..."));
//File sensorData;
sensorData = SD.open("Hello.csv", FILE_WRITE);
if (!sensorData)
{
Serial.println(F("Error Creating"));
}
sensorData.close();
}
//
void writeToSD()
{
// build the data string
//String dataString = Tele; // convert to CSV
//File sensorData;
if(SD.exists("Hello.csv")) // check the card is still there
{
// now append new data file
sensorData = SD.open("Hello.csv", FILE_WRITE);
if (sensorData)
{
sensorData.println(Tele);
}
else
{
Serial.println(F("Error Writting"));
}
}
/*else
{
Serial.println("File doesn't exist");
}*/
sensorData.close(); // close the file
/*
String pktString = String(pkt);
//if(SD.exists("Packets.csv")) // check the card is still there
//{
// now append new data file
sensorData = SD.open("Packets.txt", FILE_WRITE);
if (sensorData)
{
sensorData.println(pktString);
sensorData.close(); // close the file
}
//}
else
{
Serial.println("Error writing to file !");
}
*/
}
| true |
54efea4673914f4c1ef49186ccc667fbf92b1c23 | C++ | madongyu/leetcode | /8_String_to_Integer_(atoi).cpp | UTF-8 | 685 | 3.21875 | 3 | [] | no_license | #include <string>
using std::string;
// how to know it is out of range ?
int myAtoi(string str) {
long long re = 0;
int base = 0;
int flag = false;
while (base < str.size() && str[base] == ' ')
{
base++;
}
if (base == str.size()) {
return 0;
}
if (str[base] == '-') {
flag = true;
base++;
}
else if (str[base] == '+') {
flag = false;
base++;
}
for (int i = base; i < str.size(); i++) {
if ('0' <= str[i] && str[i] <= '9') {
re = re * 10 + str[i] - '0';
if (!flag && re > INT_MAX) {
return INT_MAX;
}
if (flag && -re < INT_MIN){
return INT_MIN;
}
}
else {
break;
}
}
if (flag) {
return -re;
}
else {
return re;
}
} | true |
117528ca68043d268626526f03c2224ad4fdb1f9 | C++ | perryiv/cadkit | /Minerva/DataSources/PG/Info.cpp | UTF-8 | 9,850 | 2.59375 | 3 | [] | no_license |
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2006, Arizona State University
// All rights reserved.
// BSD License: http://www.opensource.org/licenses/bsd-license.html
// Created by: Adam Kubach
//
///////////////////////////////////////////////////////////////////////////////
#include "Minerva/DataSources/PG/Info.h"
using namespace Minerva::DataSources::PG;
///////////////////////////////////////////////////////////////////////////////
//
// Constructor.
//
///////////////////////////////////////////////////////////////////////////////
Info::Info( Connection* connection ) :
BaseClass(),
_connection ( connection )
{
}
///////////////////////////////////////////////////////////////////////////////
//
// Destructor.
//
///////////////////////////////////////////////////////////////////////////////
Info::~Info()
{
}
///////////////////////////////////////////////////////////////////////////////
//
// Get all public tables.
//
///////////////////////////////////////////////////////////////////////////////
Info::Strings Info::tables()
{
std::string query ( "SELECT table_schema || '.' || table_name FROM information_schema.tables" );
return this->_fillStringsFromQuery( query );
}
///////////////////////////////////////////////////////////////////////////////
//
// Get all polygon tables.
//
///////////////////////////////////////////////////////////////////////////////
Info::Strings Info::polygonTables()
{
Strings strings;
Strings geometryTables ( this->geometryTables() );
for( Strings::const_iterator iter = geometryTables.begin(); iter != geometryTables.end(); ++iter )
{
if( this->isPolygonTable( *iter ) )
strings.push_back( *iter );
}
return strings;
}
///////////////////////////////////////////////////////////////////////////////
//
// Get all line tables.
//
///////////////////////////////////////////////////////////////////////////////
Info::Strings Info::lineTables()
{
Strings strings;
Strings geometryTables ( this->geometryTables() );
for( Strings::const_iterator iter = geometryTables.begin(); iter != geometryTables.end(); ++iter )
{
if( this->isLineTable( *iter ) || this->isPolygonTable ( *iter ) )
strings.push_back( *iter );
}
return strings;
}
///////////////////////////////////////////////////////////////////////////////
//
// Get all point tables.
//
///////////////////////////////////////////////////////////////////////////////
Info::Strings Info::pointTables()
{
Strings strings;
Strings geometryTables ( this->geometryTables() );
for( Strings::const_iterator iter = geometryTables.begin(); iter != geometryTables.end(); ++iter )
{
if( this->isPointTable( *iter ) )
strings.push_back( *iter );
}
return strings;
}
///////////////////////////////////////////////////////////////////////////////
//
// Get all point time tables.
//
///////////////////////////////////////////////////////////////////////////////
Info::Strings Info::pointTimeTables()
{
Strings strings;
Strings pointTables ( this->pointTables() );
for( Strings::const_iterator iter = pointTables.begin(); iter != pointTables.end(); ++iter )
{
if( this->hasColumnType( *iter, "date" ) )
strings.push_back( *iter );
}
return strings;
}
///////////////////////////////////////////////////////////////////////////////
//
// Get all geometry tables.
//
///////////////////////////////////////////////////////////////////////////////
Info::Strings Info::geometryTables()
{
std::string query ( "SELECT table_schema || '.' || table_name FROM information_schema.columns WHERE column_name='geom'" );
return this->_fillStringsFromQuery( query );
}
///////////////////////////////////////////////////////////////////////////////
//
// Get the geometry type for a table.
//
///////////////////////////////////////////////////////////////////////////////
std::string Info::_getGeometryType ( const std::string& table ) const
{
std::string query ( "SELECT GeometryType(geom) FROM " + table + " WHERE IsEmpty(geom)=false LIMIT 1" );
Minerva::DataSources::Result::RefPtr result ( _connection->executeQuery ( query ) );
if( result->prepareNextRow() )
return result->asString ( 0 );
return "";
}
///////////////////////////////////////////////////////////////////////////////
//
// Copy results of a query into a vector.
//
///////////////////////////////////////////////////////////////////////////////
Info::Strings Info::_fillStringsFromQuery( const std::string& query ) const
{
Strings strings;
Minerva::DataSources::Result::RefPtr result ( _connection->executeQuery ( query ) );
while ( result->prepareNextRow() )
{
strings.push_back ( result->asString ( 0 ) );
}
return strings;
}
///////////////////////////////////////////////////////////////////////////////
//
// Is the given table a point table?
//
///////////////////////////////////////////////////////////////////////////////
bool Info::isPointTable ( const std::string& table ) const
{
const std::string type ( this->_getGeometryType ( table ) );
return ( ( type == "POINT" ) || ( type == "MULTIPOINT" ) );
}
///////////////////////////////////////////////////////////////////////////////
//
// Is the given table a point time table?
//
///////////////////////////////////////////////////////////////////////////////
bool Info::isPointTimeTable ( const std::string& table ) const
{
return ( this->isPointTable( table ) && this->hasColumnType( table, "date" ) );
}
///////////////////////////////////////////////////////////////////////////////
//
// Is the given table a line table?
//
///////////////////////////////////////////////////////////////////////////////
bool Info::isLineTable ( const std::string& table ) const
{
const std::string type ( this->_getGeometryType ( table ) );
return ( ( type == "LINESTRING" ) || ( type == "MULTILINESTRING" ) );
}
///////////////////////////////////////////////////////////////////////////////
//
// Is the given table a polygon table?
//
///////////////////////////////////////////////////////////////////////////////
bool Info::isPolygonTable ( const std::string& table ) const
{
const std::string type ( this->_getGeometryType ( table ) );
return ( ( type == "POLYGON" ) || ( type == "MULTIPOLYGON" ) );
}
///////////////////////////////////////////////////////////////////////////////
//
// Is the given table a point time table?
//
///////////////////////////////////////////////////////////////////////////////
bool Info::isPolygonTimeTable ( const std::string& table ) const
{
return ( this->isPolygonTable( table ) && this->hasColumnType( table, "date" ) );
}
///////////////////////////////////////////////////////////////////////////////
//
// Remove the schema name if present.
// Use this function when querying the information_schema table.
//
///////////////////////////////////////////////////////////////////////////////
namespace Detail
{
std::string tableName ( const std::string& table )
{
// Make a copy.
std::string name ( table );
// See if there is a schema specified.
std::string::size_type pos ( name.find_first_of ( '.' ) );
// Trim the table if we should.
if( std::string::npos != pos )
name = table.substr ( pos + 1, name.length() - pos );
return name;
}
}
///////////////////////////////////////////////////////////////////////////////
//
// Does the table have a column of the given type?
//
///////////////////////////////////////////////////////////////////////////////
bool Info::hasColumnType ( const std::string& table, const std::string& type ) const
{
// Remove the schema name, if any.
std::string name ( Detail::tableName( table ) );
// Run the query.
std::string query ( "SELECT column_name FROM information_schema.columns WHERE table_name='" + name + "' AND data_type='" + type + "'" );
Minerva::DataSources::Result::RefPtr result ( _connection->executeQuery ( query ) );
return !result->empty();
}
///////////////////////////////////////////////////////////////////////////////
//
// Get all column names.
//
///////////////////////////////////////////////////////////////////////////////
Info::Strings Info::getColumnNames ( const std::string& table ) const
{
// Remove the schema name, if any.
std::string name ( Detail::tableName( table ) );
// Run the query.
std::string query ( "SELECT column_name FROM information_schema.columns WHERE table_name='" + name + "'" );
return _fillStringsFromQuery( query );
}
///////////////////////////////////////////////////////////////////////////////
//
// Get all column names.
//
///////////////////////////////////////////////////////////////////////////////
Info::Strings Info::getColumnNames ( const std::string& table, const std::string& type ) const
{
// Remove the schema name, if any.
std::string name ( Detail::tableName( table ) );
// Run the query.
std::string query ( "SELECT column_name FROM information_schema.columns WHERE table_name='" + name + "' AND data_type='" + type + "'" );
return _fillStringsFromQuery( query );
}
///////////////////////////////////////////////////////////////////////////////
//
// Get min and max value for given query.
//
///////////////////////////////////////////////////////////////////////////////
void Info::getMinMaxValue( const std::string& query, const std::string& columnName, double& min, double& max ) const
{
std::string q ( "SELECT MAX(" + columnName + ") as max, MIN(" + columnName + ") FROM (" + query + ") temp" );
Minerva::DataSources::Result::RefPtr result ( _connection->executeQuery( q ) );
if( result->prepareNextRow() )
{
min = result->asDouble ( "min" );
max = result->asDouble ( "max" );
}
}
| true |
529e5f584cccc549b3f9cca9823c5b5536b63b21 | C++ | kaidee/kaidee | /cpp/str_length.cpp | UTF-8 | 921 | 3.4375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
using namespace std;
#pragma mark 获取UTF-8字符串长度
int strLength(const std::string &str)
{
if (typeid(str) == typeid(std::string) && str.length() > 0)
{
int len = str.length();
std::vector <std::string> dump;
int i = 0;
while(i < len)
{
if (~(str.at(i) >> 8) == 0) {
dump.push_back(str.substr(i, 3));
i += 3;
} else {
dump.push_back(str.substr(i, 1));
i += 1;
}
}
return dump.size();
} else {
printf("str is not string\n");
return 0;
}
}
int main(int argc, char const *argv[])
{
string s("中国人a1,");
cout<<"length: "<<strLength(s)<<endl;
cout<<"strlen: "<<strlen(s.c_str())<<endl;
cout<<"sizeof: "<<sizeof(s.c_str())<<endl;
return 0;
} | true |
ccbec53625b12741f782f2d2a909f1f6c8707f6a | C++ | TosakaUCW/Solution_Source_Code | /[Luogu P3374] 【模板】树状数组 1 .cpp | UTF-8 | 967 | 2.765625 | 3 | [] | no_license | #include <stdio.h>
#define Rep(i, x, y) for (register int i = x; i <= y; i++)
const int N = 5e5 + 5;
int n, m;
struct Binary_Indexed_Tree
{
int c[N];
int lowbit(int x) { return x & (-x); }
void add(int k, int x)
{
for (int i = k; i <= n; i += lowbit(i))
c[i] += x;
}
int find(int k)
{
int res = 0;
for (int i = k; i; i -= lowbit(i))
res += c[i];
return res;
}
int query_sum(int l, int r)
{
return find(r) - find(l - 1);
}
} BIT;
int main()
{
scanf("%d%d", &n, &m);
Rep(i, 1, n)
{
int a;
scanf("%d", &a);
BIT.add(i, a);
}
Rep(i, 1, m)
{
int opt, x, k;
scanf("%d%d%d", &opt, &x, &k);
switch (opt)
{
case 1:
BIT.add(x, k);
break;
case 2:
printf("%d\n", BIT.query_sum(x, k));
break;
}
}
return 0;
} | true |
5a82c8af1006923318e6acc3a9b702753519ff1e | C++ | maximzec/lab6 | /Alive/Animal.h | UTF-8 | 420 | 2.78125 | 3 | [] | no_license | //
// Created by User on 18.04.2019.
//
#ifndef LAB6_ANIMAL_H
#define LAB6_ANIMAL_H
#include "Alive.h"
class Animal : public Alive
{
private:
std::string type;
std::string animal_k;
std::string size;
public:
Animal();
Animal(int age, bool isAlive , std::string type , std::string animal_k ,std::string size);
void showAnimal();
void changeType(std::string type);
};
#endif //LAB6_ANIMAL_H
| true |
b8f399bfe532d8b49f55fc2c068e92cafaa94296 | C++ | Emma-Rabbit/bunny3d | /src/Scene.cpp | UTF-8 | 582 | 3.0625 | 3 | [] | no_license | #include "Scene.hpp"
#include <vector>
Scene::Scene(){
}
void Scene::AddObject(std::vector<float> ver, std::vector<unsigned int> ind){
for(float v : ver){
m_Verticies.push_back(v);
}
for(unsigned int i : ind){
m_Indecies.push_back(i);
}
}
void* Scene::GetVerticies(){
return m_Verticies.data();
}
void* Scene::GetIndecies(){
return m_Indecies.data();
}
unsigned int Scene::GetVerticiesSize(){
return m_Verticies.size() * sizeof(float);
}
unsigned int Scene::GetIndeciesSize(){
return m_Indecies.size() * sizeof(unsigned int);
} | true |
faa990666777a2d0ef0c825c0163fcd212f3850f | C++ | FBaldo98/hw3d | /hw3d/Window.h | UTF-8 | 2,196 | 2.6875 | 3 | [] | no_license | #pragma once
#include "BaldoWin.h"
#include "BaldoException.h"
#include "Keyboard.h"
#include "Mouse.h"
#include "Graphics.h"
#include <optional>
#include <memory>
class Window {
public:
class Exception : public BaldoException {
using BaldoException::BaldoException;
public:
static std::string TranslateErrorCode(HRESULT hr) noexcept;
};
class HrException : public Exception {
public:
HrException(int line, const char* file, HRESULT hr) noexcept;
const char* what() const noexcept override;
const char* GetType() const noexcept override;
HRESULT GetErrorCode() const noexcept;
std::string GetErrorDescription() const noexcept;
private:
HRESULT hr;
};
class NoGfxException : public Exception {
public:
using Exception::Exception;
const char* GetType() const noexcept override;
};
// singleton manages registration/cleanup of window class
class WindowClass {
public:
static const wchar_t* GetName() noexcept;
static HINSTANCE GetInstance() noexcept;
private:
WindowClass() noexcept;
~WindowClass();
WindowClass(const WindowClass&) = delete;
WindowClass& operator = (const WindowClass&) = delete;
static constexpr const wchar_t* wndClassName = L"Baldo Engine Window";
static WindowClass wndClass;
HINSTANCE hInst;
};
public:
Window(int width, int height, const wchar_t* name);
~Window();
Window(const Window&) = delete;
Window& operator = (const Window&) = delete;
void SetTitle(const std::string title);
static std::optional<int> ProcessMessages();
Graphics& Gfx();
private:
static LRESULT CALLBACK HandleMsgSetup(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) noexcept;
static LRESULT CALLBACK HandeMsgThunk(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) noexcept;
LRESULT HandleMsg(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) noexcept;
public:
Keyboard kbd;
Mouse mouse;
private:
int width;
int height;
HWND hWnd;
std::unique_ptr<Graphics> pGfx;
};
// error exception helper macro
#define BHWND_EXCEPT( hr ) Window::HrException( __LINE__, __FILE__, hr )
#define BHWND_LAST_EXCEPT() Window::HrException(__LINE__, __FILE__, GetLastError())
#define BHWND_NOGFX_EXCEPT() Window::NoGfxException(__LINE__, __FILE__) | true |
4ab248cb9c9b679e56dfcaa590ecd226a5944ff2 | C++ | DevinChang/LC_AC | /LeetCode/LC840.cpp | UTF-8 | 1,104 | 2.625 | 3 | [] | no_license | class Solution {
public:
int n, m;
vector<vector<int>> g;
bool check(int x, int y) {
bool st[10] = {0};
for (int i = x; i < x + 3; i ++ )
for (int j = y; j < y + 3; j ++ ) {
int t = g[i][j];
if (t < 1 || t > 9) return false;
if (st[t]) return false;
st[t] = true;
}
for (int i = 0; i < 3; i ++ ) {
if (g[x + i][y] + g[x + i][y + 1] + g[x + i][y + 2] != 15) return false;
if (g[x][y + i] + g[x + 1][y + i] + g[x + 2][y + i] != 15) return false;
}
if (g[x][y] + g[x + 1][y + 1] + g[x + 2][y + 2] != 15) return false;
if (g[x + 2][y] + g[x + 1][y + 1] + g[x][y + 2] != 15) return false;
return true;
}
int numMagicSquaresInside(vector<vector<int>>& grid) {
g = grid;
n = g.size(), m = g[0].size();
int res = 0;
for (int i = 0; i + 3 <= n; i ++ )
for (int j = 0; j + 3 <= m; j ++ )
if (check(i, j))
res ++ ;
return res;
}
}; | true |
ce58e6b647be182724bd4129619689d66f03539b | C++ | ernestk86/dungeon_game_cpp | /sMenu.cpp | UTF-8 | 953 | 3.1875 | 3 | [] | no_license | /******************************************************************
** Program Name: sMenu.cpp
** Author: Ernest Kim
** Date: 6/6/2019
** Description: Source code for implementation of questions
** for menu.
******************************************************************/
#include "sMenu.hpp"
/*****************************************************************
** Description: Function presents a menu for the user
*****************************************************************/
int sMenu(){
int choice = 0;
cout << "So:" << endl
<< "1. String cheese and potatos?" << endl
<< "2. Polymorphism" << endl
<< "3. Rick and Morty" << endl
<< "4. CS162" << endl
<< "5. Pencil Vester" << endl;
while((choice < 1) || (choice > 5)){
cin >> choice;
if((cin.fail()) || (choice < 1) || (choice > 5)){
cin.clear();
cin.ignore();
cout << "That doesn't work. Please choose an integer from 1-5:" << endl;
}
}
return choice;
}
| true |
bc09c87c24f48d145ab493e66f90bf39ffd1f91b | C++ | IngeDannyel/proytorta | /tortas.cpp | UTF-8 | 2,582 | 2.75 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<locale.h>
#define s scanf
#define p printf
struct menu{
int cantidad,costo;
};
main()
{
setlocale(LC_ALL,"esm");
char sel, cin[100];
int suma=0,i,aux;
FILE *arch;
system ("color f0");
struct menu c[4];
for(i=0;i<4;i++) //Declaración de cantidades del menu
c[i].cantidad=0;
do
{
p("\n Total es de: %d\n\n", suma);
//Esta parte del codigo se hace para la seleccion
do
{
arch=fopen("datos.txt","r"); //apertura de archivos
if (arch==NULL)
p("ERROR");
else
{
while(feof(arch)==NULL) //Verificar hasta que termine el archivo
{
fgets(cin,3,arch); //hace grupos de dos caracteres
aux=atoi(cin); //transformación de char a int
if(aux==40)
c[0].costo=aux;
if(aux==15)
c[1].costo=aux;
if(aux==55)
c[2].costo=aux;
if(aux==10)
c[3].costo=aux;
p("%s",cin);
}
fclose(arch);
}
p(" \n\nSeleccione que desea en su orden: " ); //Desicion de selección
fflush(stdin);
sel=getchar();
system("CLS");
} while(sel!='a'&& sel!='A' && sel!='b'&& sel!='B'&& sel!='c'&& sel!='C'&& sel!='d'&& sel!='D'&& sel!='e'&& sel!='E'); //la seleccion tiene que estar entre 0 y 7
if(sel=='e' || sel=='E')
{
system("CLS");
p("\n\n Tu pedido fue el siguiente:\n"); //Contador del pedido en cuanto al menu
p("-------------------------\n" );
p(" %d Cubana \n", c[0].cantidad);
p(" %d Jamon \n", c[1].cantidad);
p(" %d Especial \n", c[2].cantidad);
p(" %d Refresco \n", c[3].cantidad);
p("\n El monto a pagar es de: %d\n\n", suma);
break;
}
switch(sel) //Sel sirve de bandera para tomar desiciones
{
case 'a': case'A':
suma+=c[0].costo;
c[0].cantidad++;
break;
case 'b': case'B':
suma+=c[1].costo;
c[1].cantidad++;
break;
case 'c': case'C':
suma+=c[2].costo;
c[2].cantidad++;
break;
case 'd': case'D':
suma+=c[3].costo;
c[3].cantidad++;
break;
default:
break;
}
}while(sel);
}
| true |
9fd55e86b225e7f7489dbb2e484e9cf86fa5e4f8 | C++ | dkorytov/dtk | /dtk/math.hpp | UTF-8 | 3,352 | 2.890625 | 3 | [] | no_license | #ifndef DTK_MATH_HPP
#define DTK_MATH_HPP
#include <cmath>
#include <cstdlib>
#include <random>
#include "hdf5_util.hpp"
namespace dtk{
std::default_random_engine dtk_random_engine;
template<class T,class U>
T max(T* data, U size){
T max_val = data[0];
for(U i =1;i<size;++i){
if(data[i]>max_val)
max_val = data[i];
}
return max_val;
}
template<class T,class U>
T min(T* data, U size){
T min_val = data[0];
for(U i =1;i<size;++i){
if(data[i]<min_val)
min_val = data[i];
}
return min_val;
}
template<class T>
T min(std::vector<T> data){
return min(&data[0],data.size());
}
template<class T>
T max(std::vector<T> data){
return max(&data[0],data.size());
}
template<class T,class U>
T average(T* data, U size){
T result = 0;
for(U i =0;i<size;++i){
result += data[i];
}
return result/static_cast<T>(size);
}
template<class T>
T average(std::vector<T> data){
size_t size = data.size();
T result = 0;
for(size_t i =0;i<size;++i){
result += data[i];
}
return result/static_cast<T>(size);
}
template<class T>
std::vector<T> linspace(T start,T end, int num){
std::vector<T> result(num);
T del=0;
if(num != 0)
del = (end-start)/num;
for(int i =0;i<num-1;++i){
result[i]=start+del*i;
}
result[num-1]=end; //to avoid round off errors.
return result;
}
template<class T>
std::vector<T> logspace(T start,T end, int num){
std::vector<T> result = linspace(start,end,num);
for(int i =0;i<result.size();++i){
result[i] = std::pow(10,result[i]);
}
return result;
}
template<class T>
T root_mean_squared(std::vector<T> data){
T result =0;
for(size_t i =0;i<data.size();++i){
result+=data[i]*data[i];
}
return sqrt(result);
}
template<class T>
T rand(){
return (T) std::rand()/((T)RAND_MAX);
}
template<class T, class U>
void rand_fill(T* array, U size){
for(U i =0; i<size;++i)
array[i] = rand<T>();
}
template<class T>
T normal_random(T mean=0, T sigma=1){
std::normal_distribution<T> norm(mean, sigma);
return norm(dtk_random_engine);
}
template<class T>
void normal_random(T mean, T sigma, T* output, size_t num){
std::normal_distribution<T> norm(mean, sigma);
for(size_t i=0;i<num;++i){
output[i]=norm(dtk_random_engine);
// std::cout<<<<std::endl;
}
}
template<class T>
void random_vector3d(T& x, T& y, T& z, T radius){
std::normal_distribution<T> norm(0, 1);
x = norm(dtk_random_engine);
y = norm(dtk_random_engine);
z = norm(dtk_random_engine);
T r = std::sqrt(x*x + y*y + z*z);
x = x/r * radius;
y = y/r * radius;
z = z/r * radius;
}
template<class T>
struct Distribution{
std::vector<T> cdf;
std::vector<T> x;
// std::uniform_real_distribution<T> dist(0, 1);
std::default_random_engine dtk_random_engine;
Distribution(char* fname){
read_hdf5<T>(fname, "cdf", cdf);
read_hdf5<T>(fname, "x", x);
if (cdf.size() != x.size()){
std::cout<<"Size of cdf and x are not the same"<<std::endl;
throw;
}
}
T get_value(){
// size_t min, max;
// min = 0;
// max = cdf.size();
throw;
return 0;
}
};
}
#endif
| true |
c358aa07a59b6a23e516f30e8feeaf8c4423d9ec | C++ | kiner-shah/CompetitiveProgramming | /Codechef/LoC Competitive Programming Marathon/rectangles.cpp | UTF-8 | 671 | 2.765625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
int l1,w1,l2,w2;
cin>>t;
while(t-- > 0) {
cin>>l1>>w1>>l2>>w2;
if(l1 == l2 && w1 == w2) {
cout<<l1 * w1 + l2 * w2 - w1 * l2<<" ";
cout<<l1 * w1 + l2 * w2<<endl;
}
else {
if(l1 < l2) {
if(w1 < w2) {
cout<<l2 * w2<<" ";
cout<<l1 * w1 + l2 * w2<<endl;
}
else {
cout<<l2 * w2 + l1 * (w1 - w2)<<" ";
cout<<l1 * w1 + l2 * w2<<endl;
}
}
else {
if(w1 > w2) {
cout<<l1 * w1<<" ";
cout<<l1 * w1 + l2 * w2<<endl;
}
else {
cout<<l1 * w1 + l2 * (w2 - w1)<<" ";
cout<<l1 * w1 + l2 * w2<<endl;
}
}
}
}
return 0;
}
| true |
fa59e513642ea539efb2e71be8b0cc45c58c9630 | C++ | johanjm/Algoritmos-Estructura-Datos | /Quicksort/ordenamiento-quicksort.cpp | UTF-8 | 1,708 | 3.46875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
using namespace std;
double ingresoP(int n,int m, string c);
void ordenar(int arr[], int pinicial, int pfinal);
void imp(int a[],int n);
int mitad (int arr[], int pinicial, int pfinal);
ofstream archivo;
int main() {
int n=0;
archivo.open("interpolacion.txt", ios::app);
n= ingresoP(0, 10000, "¿Cuántos elementos va a ingresar?: ");
int a[n];
for (int i=0; i<n; i++) {
cout<<"Posición ["<<i+1<<"]"<<endl;
a[i]= ingresoP(-10000, 1000000, "Ingrese un número: ");
}
archivo<<"Arreglo de elementos originales:"<<endl;
imp(a, n);
archivo<<"Arreglo de elementos ordenados:"<<endl;
ordenar(a,0,n-1);
imp(a,n);
archivo.close();
}
double ingresoP(int n,int m, string c){
int op=0;
double a;
while(op==0){
cout<<c;
cin>>a;
if(a>n && a<=m){
op=1;
}else{
cout<<"El valor ingresado no es correcto"<<endl;
}
}
return a;
}
void ordenar(int arr[], int pinicial, int pfinal){
int i=pinicial;
int j=pfinal;
int temp;
int piv=mitad(arr,pinicial,pfinal);
do{
while(arr[i]<piv){
i++;
}while(arr[j]>piv){
j--;
}if(i<=j){
temp = arr[i];
arr[i]=arr[j];
arr[j]=temp;
i++;
j--;
}
}
while(i<=j);
if(pinicial<j)
ordenar(arr,pinicial,j);
if(i<pfinal)
ordenar(arr,i,pfinal);
}
void imp(int a[],int n){
for(int i=0; i<n; i++){
archivo<<a[i]<<" ";
}
archivo<<endl;
}
int mitad (int arr[], int pinicial, int pfinal){
return arr[(pinicial+pfinal)/2];
}
| true |
d24feae98656a3159da604ff6efa5b0f36f4d81c | C++ | marekrynarzewski/pto_gimpByMarek | /src/core/transformations/correction.cpp | UTF-8 | 1,592 | 2.734375 | 3 | [] | no_license | #include "correction.h"
#include <math.h>
#include <algorithm>
using namespace std;
Correction::Correction(PNM* img) :
Transformation(img)
{
}
Correction::Correction(PNM* img, ImageViewer* iv) :
Transformation(img, iv)
{
}
template <typename T>
T range(T min, T val, T max)
{
T result;
if (val < min)
{
result = min;
}
else if (min < val && val < max)
{
result = val;
}
else
{
result = max;
}
return result;
}
PNM* Correction::transform()
{
float shift = getParameter("shift").toFloat();
float factor = getParameter("factor").toFloat();
float gamma = getParameter("gamma").toFloat();
int width = image->width();
int height = image->height();
PNM* newImage = new PNM(width, height, image->format());
for (int i = PIXEL_VAL_MIN; i <= PIXEL_VAL_MAX; i++)
{
LUT[i] = range((float)0, i+shift, (float)255);
LUT[i] = range((float)0, LUT[i]*factor, (float)255);
LUT[i] = range((float)0, (float)pow(LUT[i], gamma), (float)255);
}
for (int x=0; x<width; x++)
{
for (int y=0; y<height; y++)
{
QRgb pixel = image->pixel(x,y); // Getting the pixel(x,y) value
int r = qRed(pixel); // Get the 0-255 value of the R channel
int g = qGreen(pixel); // Get the 0-255 value of the G channel
int b = qBlue(pixel);
r = LUT[r];
g = LUT[g];
b = LUT[b];
QColor newPixel = QColor(r,g,b);
newImage->setPixel(x,y, newPixel.rgb());
}
}
return newImage;
}
| true |
6bea956ed37d7ecde445462836650e385ec02c71 | C++ | tanker242/csci41-heap-rpg | /fight.h | UTF-8 | 1,493 | 3.328125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <vector>
#include <string>
#include <cmath>
#include <fstream>
using namespace std;
void fightMove (){
string line;
int random = 0;
random = rand() % 470;
int numberOfmoves = 0;
vector<string> moves;
ifstream File("randomMoves.txt");
while (getline(File, line)){
++numberOfmoves;
if (numberOfmoves == random) {
cout << line<< endl;
}
}
}
void fight(){
int health = 100;
int opponent = rand() % 100;
while (true) {
cout << "enter a number to continue" << endl << endl;
int y = 0;
cin >> y;
cout << "YOU used " ;
fightMove();
int attack = 0;
attack = rand() % 100;
cout << " and dealt " << attack << " damage to your opponent" << endl << endl << endl;
opponent = opponent - attack;
cout << "Your opponents health is " << opponent << endl << endl;
if (opponent <= 0){
cout << "your opponent has died" << endl;
break;
}
cout << "Your opponent used " ;
fightMove();
int blow = 0;
blow = rand() %100;
cout << " and dealt " << blow << " damage" << endl << endl << endl;
health = health - blow;
cout << "Your health is" << health << endl << endl;
if (health <= 0) {
cout << "Your health = 0 and therefore you have died, please try again" << endl;
exit(1);
}
}
}
| true |
3e098c8aced09699fdd4bd2fd0d7e74d799c883a | C++ | tanvib00/Strength-Balance-Device | /final_project.ino | UTF-8 | 7,779 | 2.671875 | 3 | [] | no_license |
#include <SPI.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include "Queue.h"
#include "HX711.h"
#define DOUT 3 // Load cell pin 1
#define CLK 2 // Load cell pin 2
#define BUTX 8
#define BUTR 9
#define BUTL 10
#define CALIBRATION_FACTOR -7050
#define WINDOW_SIZE 5
#define AVERAGES_SIZE 5
LiquidCrystal_I2C screen(0x27, 20, 4);
HX711 scale;
const char LEFT = 0;
const char RIGHT = 1;
float calibrationFactor = -7050;
//calibration factor used by HX711 library to do some sort of data filtering
unsigned long startMillis;
unsigned long timerMillis;
unsigned long currentMillis;
//const unsigned long period = 11000;
int exerciseTimer = 0;
int rightPressed = 1;
int leftPressed = 1;
int clearPressed = 1;
bool exerciseMode = false;
int leftMax = 0;
int rightMax = 0;
bool leftActivated = false;
bool rightActivated = false;
bool leftInUse = false;
bool rightInUse = false;
Queue<int> window = Queue<int>(WINDOW_SIZE);
int windowSum = 0;
Queue<float> averages = Queue<float>(AVERAGES_SIZE);
float averagesSum = 0;
String oldSlope = "flat";
int repLeftCount = 0;
int repLeftWeightSum = 0;
int repRightCount = 0;
int repRightWeightSum = 0;
//--- HELPERS ---
void initLoadCell()
{
scale.begin(DOUT, CLK);
scale.set_scale(CALIBRATION_FACTOR);
scale.tare(); //Reset the scale to 0
}
void homeScreen() {
screen.home();
screen.clear();
screen.print("Press L/R to begin");
screen.setCursor(0, 1);
screen.print("and end exercises.");
screen.setCursor(0, 2);
screen.print("Press X for results.");
screen.display();
}
void beginExDisp() {
for (int i = 5; i > 0; i--) {
screen.home();
screen.clear();
screen.print("Start in ");
screen.print(i);
screen.print(" seconds");
screen.display();
delay(1000);
}
screen.clear();
screen.print("Go!");
delay(500);
screen.display();
startMillis = millis();
exerciseTimer = 0;
}
void handleButtonSide(char side) {
beginExDisp();
if (side == LEFT)
{
leftActivated = true;
leftInUse = true;
rightInUse = false;
}
else
{
rightActivated = true;
leftInUse = false;
rightInUse = true;
}
}
void handleButtonClear() {
// if both the left and right buttons were pressed during
// the last exercise set
screen.clear();
if (leftActivated && rightActivated)
{
screen.print("Left Max: ");
screen.print(leftMax);
screen.setCursor(0, 1);
screen.print("Reps: ");
screen.print(repLeftCount);
screen.setCursor(0, 2);
screen.print("Avg Weight: ");
float leftAvg = (float)repLeftWeightSum / (float)repLeftCount;
screen.print(leftAvg);
delay(3000);
screen.clear();
screen.print("Right Max: ");
screen.print(rightMax);
screen.setCursor(0, 1);
screen.print("Reps: ");
screen.print(repRightCount);
screen.setCursor(0, 2);
screen.print("Avg Weight: ");
float rightAvg = (float)repRightWeightSum / (float)repRightCount;
screen.print(rightAvg);
delay(3000);
if (!(leftAvg == 0)) {
screen.clear();
//float ratio = rightAvg / leftAvg;
//above: not a very clear representation of data
screen.print("Right : Left = ");
screen.setCursor(0, 1);
screen.print(rightAvg);
screen.print(" : ");
screen.print(leftAvg);
//screen.print("%");
delay(3000);
}
}
else if (leftActivated)
{
screen.print("Left Max: ");
screen.print(leftMax);
screen.setCursor(0, 1);
screen.print("Reps: ");
screen.print(repLeftCount);
screen.setCursor(0, 2);
screen.print("Avg Weight: ");
float leftAvg = (float)repLeftWeightSum / (float)repLeftCount;
Serial.print(leftAvg);
screen.print(leftAvg);
delay(3000);
}
else if (rightActivated)
{
screen.print("Right Max: ");
screen.print(rightMax);
screen.setCursor(0, 1);
screen.print("Reps: ");
screen.print(repRightCount);
screen.setCursor(0, 2);
screen.print("Avg Weight: ");
float rightAvg = (float)repRightWeightSum / (float)repRightCount;
Serial.print(rightAvg);
screen.print(rightAvg);
delay(3000);
}
else
{
screen.print("No reps counted!");
delay(500);
}
// reset globals
leftMax = 0.0;
rightMax = 0.0;
leftActivated = false;
rightActivated = false;
leftInUse = false;
rightInUse = false;
homeScreen();
initLoadCell();
repLeftCount = 0;
repLeftWeightSum = 0;
repRightCount = 0;
repRightWeightSum = 0;
Serial.println("reset reps");
}
//--- MAIN CODE ---
void setup() {
Serial.begin(9600);
pinMode(BUTR, INPUT_PULLUP);
pinMode(BUTL, INPUT_PULLUP);
pinMode(BUTX, INPUT_PULLUP);
//initLoadCell();
screen.init();
screen.backlight();
screen.print("Welcome, Gary!");
delay(1000);
homeScreen();
scale.begin(DOUT, CLK);
scale.set_scale(CALIBRATION_FACTOR);
scale.tare();
startMillis = millis();
timerMillis = millis();
}
void loop() {
screen.home();
scale.set_scale(calibrationFactor);
currentMillis = millis();
rightPressed = !digitalRead(BUTR);
leftPressed = !digitalRead(BUTL);
clearPressed = !digitalRead(BUTX);
if (clearPressed)
{
exerciseMode = false;
handleButtonClear();
}
else if (leftPressed)
{
exerciseMode = true;
handleButtonSide(LEFT);
}
else if (rightPressed)
{
exerciseMode = true;
handleButtonSide(RIGHT);
}
// figure out average from window
int newReading = abs(scale.get_units()); // why is everything here on down not a helper function it runs always why
//Serial.print("start of loop: ");
//Serial.println(newReading);
window.push(newReading);
float newAverage;
if(window.count() >= WINDOW_SIZE)
{
int oldReading = window.pop();
windowSum += newReading;
windowSum -= oldReading;
newAverage = float(windowSum) / WINDOW_SIZE;
}
else
{
windowSum += newReading;
newAverage = float(windowSum) / window.count();
}
// figure out up/down from average
averages.push(newAverage);
float oldTotal = averagesSum;
float newTotal;
if(averages.count() >= AVERAGES_SIZE)
{
float oldAverage = averages.pop();
averagesSum += newAverage;
averagesSum -= oldAverage;
newTotal = averagesSum;
}
else
{
averagesSum += newAverage;
newTotal = averagesSum;
}
// decide if up/down, adjust vars
float difference = newTotal - oldTotal;
String newSlope = "";
if (difference <= 0.02 && difference >= -0.02)
{
newSlope = "flat";
}
else if(difference >= 0.02)
{
newSlope = "positive";
}
else if(difference <= -0.02)
{
newSlope = "negative";
}
// decide if a repitition was performed
if (newSlope == "negative" && oldSlope == "positive")
{
if (leftInUse)
{
repLeftCount++;
repLeftWeightSum += newReading;
Serial.println("left side reading: ");
Serial.print(newReading);
}
else if(rightInUse)
{
repRightCount++;
repRightWeightSum += newReading;
Serial.println("Right side reading: ");
Serial.print(newReading);
}
}
oldSlope = newSlope;
// update maximum reading
if (leftInUse && (leftMax < newReading))
{
leftMax = newReading;
}
else if(rightInUse && (rightMax < newReading))
{
rightMax = newReading;
}
if (exerciseMode) {
if (currentMillis - timerMillis >= 1000) { // keep track of time passed while exercising
exerciseTimer++;
screen.clear();
screen.print("Time: ");
screen.print(exerciseTimer);
screen.print(" seconds");
screen.setCursor(0,1);
screen.print("Working ");
if (leftInUse) { screen.print("left "); }
else { screen.print("right "); }
screen.print("side.");
screen.display();
timerMillis = millis();
}
}
}
| true |
57690741b235e70c053ae83f468e581aba0991b1 | C++ | starand/cpp_fw | /algorithm/algorithm.h | UTF-8 | 771 | 3.296875 | 3 | [] | no_license | #ifndef __H_ALGORITHM__
#define __H_ALGORITHM__
#ifndef min
# define min( a, b ) ((a) > (b) ? (b) : (a))
#endif
namespace Algorithm
{
template<class T> void swap( T& a, T& b )
{
T tmp = a; a = b; b = tmp;
}
template<typename T>
bool CheckIfValuesExists( const vector<T>& vtList, const T& tValue )
{
bool bResult = false;
size_t nListSize = vtList.size();
for( size_t idx = 0; idx < nListSize; ++idx )
{
if( vtList[idx] == tValue )
{
bResult = true;
break;
}
}
return bResult;
}
template<typename T>
size_t GetValuePos( const T* tArray, size_t nArraySize, const T& tValue )
{
for( size_t idx = 0; idx < nArraySize; ++idx )
if( tArray[idx] == tValue ) return idx;
return string::npos;
}
}
#endif // __H_ALGORITHM__
| true |
161b3acf0127f607a4a1132ccd8dca7d7635fe17 | C++ | floralunit/SPbCT_YaskunovaAY | /EducationalPractice/EduPractice/DLL.cpp | WINDOWS-1251 | 471 | 2.734375 | 3 | [] | no_license | #include "DLL.h"
void writeToFile2(const std::vector<char>& vector) //
{
std::ofstream file2("2.txt", std::ios::app); //
copy(vector.begin(), vector.end(), std::ostream_iterator<char>(file2)); //
file2 << std::endl; //
file2.close(); //
}
| true |
ea708e497b2226ed624ff7143e07949595468469 | C++ | ThetaQing/algorithms-and-data-structures | /MyTest/diagonalMatrix.h | GB18030 | 1,718 | 3.9375 | 4 | [] | no_license | #ifndef __DIAGONALMATRIX_
#define __DIAGONALMATRIX_
#include "arrayAndMatrix.h"
/****************ԽǾ******************
* diagonalMatrix<T>
* ˵һrow*rowsĶԽǾDֻrows0Ԫأ˿һһάelement[rows]ʾԽǾУ
element[i-1]ʾD(i,i)δһάгֵľԪؾΪ0.
* ʱ临Ӷȣڹ캯ʱ临Ӷ˵TڲʱΪO(1)TûʱΪO(rows)
getsetʱ临ӶȶO(1)
**/
template<class T>
class diagonalMatrix
{
public:
diagonalMatrix(int theN = 10);
~diagonalMatrix() { delete[] element; }
T get(int, int) const;
void set(int, int, const T&);
private:
int n; // ά
T* element; // 洢ԽǾһά
};
// 캯
template <class T>
diagonalMatrix<T>::diagonalMatrix(int theN)
{
// theNֵǷЧ
if (theN < 1)
throw "Matrix size must be > 0";
n = theN;
element = new T[n];
}
// get
template <class T>
T diagonalMatrix<T>::get(int i, int j)const
{
//ǷЧ
if (i < 1 || j < 1 || i > n || j > n)
throw "matrix index out of bounds";
else if (i == j)
return element[i - 1]; // ضԽϵԪ
else
return 0; // ǶԽϵԪ
}
// set
template<class T>
void diagonalMatrix<T>::set(int i, int j, const T& x)
{
//ǷЧ
if (i < 1 || j < 1 || i > n || j > n)
throw "matrix index out of bounds";
else if (i == j)
element[i - 1] = x;
else
if (x != 0)
throw "nondiagonal element must be zero";
}
#endif // !__DIAGONALMATRIX_
| true |
f33d22ef349980c8997e66a08bd66031abfb2dfb | C++ | huanggangfeng/Leetcode | /Cpp/栈_队列_堆_hash/220. 存在重复元素 III.cpp | UTF-8 | 2,758 | 3.28125 | 3 | [] | no_license |
// 在整数数组 nums 中,是否存在两个下标 i 和 j,使得 nums [i] 和 nums [j] 的差的绝对值小于等于 t ,且满足 i 和 j 的差的绝对值也小于等于 ķ 。
// 如果存在则返回 true,不存在返回 false。
//
// 示例 1:
// 输入: nums = [1,2,3,1], k = 3, t = 0
// 输出: true
// 示例 2:
// 输入: nums = [1,0,1,1], k = 1, t = 2
// 输出: true
// 示例 3:
// 输入: nums = [1,5,9,1,5,9], k = 2, t = 3
// 输出: false
// 来源:力扣(LeetCode)
// 链接:https://leetcode-cn.com/problems/contains-duplicate-iii
// 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
// 解题思路
// 在循环index走到i的时候, 滑动窗口中只保存窗口[i-k, i)的元素, 这个时候已经满足了index i和j的差的绝对值小于等于ķ的条件,
// 所以只需要查找set中是否存在一个target value,
// target value需要满足绝对值abs(nums[i], target) <= t, 分两种情况:
// 当nums[i] > target:
// nums[i] - target <= t ===> target >= nums[i] - t
// 2. 当nums[i] < value时,
// value - nums[i] <= t ===> target <= nums[i] + t *
// 所以只需要判断 nums[i] - t <= target <= nums[i] + t
// STL的 set::lower_bound(x)函数返回set当中,第一个大于等于target的指针it,
// target = \it; 这个时候it还只满足(nums[i] - t) <= target, 需再判断it 是否也满足小于上限nums[i] + t;
// 代码
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
if(nums.empty()){
return false;
}
// 用来保存滑动窗口[i-k, i] 中的元素,
// 这里不用考虑重复元素, 在for中先检查是否存在符合条件的元素, 最后插入新元素nums[i],
// 假设set中已经有相同值得元素, 会直接return true;
set<long> s;
for (int i = 0; i < nums.size() ; i++) {
// [i-k, i)的nums中查找是否有大于target的值,
auto it = s.lower_bound((long) nums[i] - t);
// lower_bound只满足>= nums[i] - t,
// 但是可能满足条件的是一个超大值, 仍需要判断是否小于upper_bound
if (it != s.end() && *it <= (long) nums[i] + t)
return true;
s.emplace(nums[i]);
if (s.size() == k + 1)
s.erase(nums[i - k]);
}
return false;
}
};
作者:huanggangfeng
链接:https://leetcode-cn.com/problems/contains-duplicate-iii/solution/hua-dong-chuang-kou-set-pei-you-xiang-xi-jie-shi-b/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 | true |
38df03ff94484fb5f2efd37b3c3ea13afd59f51f | C++ | oliviaSIT/leetcode | /648ReplaceWords.cpp | UTF-8 | 1,964 | 3.734375 | 4 | [] | no_license | /*
*time:
*solution: hash trie
*medium:
*/
#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <sstream>
using namespace std;
class Solution {
public:
class TrieNode{
public:
bool end;
string str;
TrieNode* children[26];
TrieNode(bool flag, string s): end(flag), str(s) {
memset(children, 0, sizeof(children));
}
};
class TrieTree{
public:
TrieNode* root;
TrieTree() {
root = new TrieNode(false,"");
}
void buildTree(vector<string>& dict){
for(int i = 0; i < (int)dict.size(); i++) {
TrieNode* cur = root;
for(int j = 0; j < (int)dict[i].size(); j++){
if(cur->children[dict[i][j] - 'a'] == NULL) {
cur->children[dict[i][j] - 'a'] = new TrieNode(false,"");
cur = cur->children[dict[i][j] - 'a'];
} else if(cur->children[dict[i][j] - 'a']->end == true){ //if a shorter root exists, we just stop build
cur = NULL;
break;
} else cur = cur->children[dict[i][j] - 'a'];
}
if(cur != NULL) { //mark the string and flag
cur->end = true;
cur->str = s;
}
}
return;
}
string replace(string s) {
TrieNode* cur =root;
string res="";
for(char c:s) {
cur = cur->children[c-'a'];
if(cur == NULL)
break;
if(cur->end == true){
res = cur->str;
break;
}
}
if(res != "")
return res;
return s;
}
};
string replaceWords(vector<string>& dict, string sentence) {
stringstream sen(sentence);
string res="";
string token;
TrieTree tree;
tree.buildTree(dict);
while(getline(sen,token,' ')) {
res += tree.replace(token);
res += " ";
}
return res.substr(0,res.size()-1); //ignore last space
}
};
int main() {
Solution sol;
vector<string> v{"cat", "bat", "rat"};
string s = "the cattle was rattled by the battery";
cout << sol.replaceWords(v, s) << endl;
return 0;
}
| true |
8f8ab835e2ec1be730b5991486d0c7598388dda7 | C++ | Cloverii/LeetCode | /11**.cpp | UTF-8 | 1,103 | 2.921875 | 3 | [] | no_license | class Solution {
public:
int maxArea(vector<int>& height) { // two pointers
/* int h[2];
h[0] = 0, h[1] = height.size() - 1;
int ans = min(h[0], h[1]) * (h[1] - h[0] + 1);
while(h[0] < h[1]) {
bool flag = height[h[0]] > height[h[1]]; //flag = lowID;
int step = 1 - 2 * flag, lowHeight = height[h[flag]];
int &low = h[flag]; int &high = h[flag ^ 1];
while(lowHeight >= low) h[flag] += step;
int tmp = min(low, high) * (abs(h[flag ^ 1] - h[flag]) + 1);
ans = max(tmp, ans);
cout << h[0] << ' ' << h[1] << endl;
}*/
int l = 0, r = height.size() - 1;
int ans = min(height[l], height[r]) * (r - l);
while(l < r) {
int minn = min(height[l], height[r]);
if(height[l] > height[r])
while(minn >= height[r]) r--;
else
while(minn >= height[l]) l++;
int tmp = min(height[l], height[r]) * (r - l);
ans = max(ans, tmp);
}
return ans;
}
};
| true |
1107014f49a0f1b8b0779c5ea74a24ad1d43fb60 | C++ | jaxonwang/my_leetcode | /problems/lt5.cc | UTF-8 | 831 | 3.296875 | 3 | [
"MIT"
] | permissive |
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
string longestPalindrome(string s) {
int s_size = s.size();
if (s_size == 0)
return "";
bool tb[s_size+1][s_size];
for (int i = 0; i < s_size; i++) {
tb[0][i] = true;
tb[1][i] = true;
}
int max_j = 1;
int max_i = 0;
for (int j = 2; j <= s_size; j++) {
for (int i = 0; i + j - 1 < s_size; i++) {
tb[j][i] = tb[j - 2][i + 1] && s[i] == s[i + j - 1] ? true : false;
if(j > max_j && tb[j][i]){
max_j = j;
max_i = i;
}
}
}
string ret{s, (size_t)max_i, (size_t)max_j};
return ret;
}
};
int main(int argc, const char *argv[]) {
string tmp = "a";
cout << Solution().longestPalindrome(tmp) << endl;
return 0;
}
| true |
4d9e7e6628fc4650d9035444f3f80f6755ed649c | C++ | shobhit3661/Amazon-GeeksforGeeks | /sub Super Array.cpp | UTF-8 | 1,108 | 3.171875 | 3 | [] | no_license | /*
Sub SuperArray HackerRank Problem
You are given an array of size containing distinct integers. You have to choose two non-overlapping subarrays and join them to make a super array such that all elements in the super array are strictly in increasing order. Find the maximum size of the super array.
For example, if the given array is and you choose subarrays and to form the super array, then the super array will be where ().
Notes
The swapping of elements is not allowed.
The subarray in the final optimal answer will always contain distinct numbers.
It is always possible to choose 2 subarrays that follow the given criteria.
Input:
1
10
7 1 2 4 6 5 3 8 9 10
output:
7
Explanation
For the given array if we choose a sub array from index [1,2,4,6] and index [8,9,10] to make the super array,
then we get the maximum size i.e 7.
*/
#include<bits/stdc++.h>
#define fast ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
typedef long long int ll;
using namespace std;
void solve()
{
}
int main()
{
fast;
ll t=1;
while(t--)
solve();
return 0;
}
| true |
7f4f3dc7a6e90fbff8c240d3421f04e60b325b25 | C++ | zmaker/arduino_cookbook | /264-graficoxy-oled/grafico_xy_oled/grafico_xy_oled.ino | UTF-8 | 1,238 | 2.53125 | 3 | [] | no_license | #include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define OLED_RESET 4 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
void setup() {
Serial.begin(9600);
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x32
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever
}
// Clear the buffer
display.clearDisplay();
axis();
display.display();
}
int bordo = 5;
int x = bordo;
int y, prev_y;
void loop() {
int var = analogRead(A0);
y = map(var, 0, 1023, SCREEN_HEIGHT - bordo, bordo);
display.drawLine(x, prev_y, x+1, y, WHITE);
prev_y = y;
x++;
if (x >= (SCREEN_WIDTH - bordo)) {
x = bordo;
display.clearDisplay();
axis();
}
delay(100);
display.display();
}
void axis(){
display.drawLine(bordo, SCREEN_HEIGHT - bordo, bordo, bordo, WHITE);
display.drawLine(bordo, SCREEN_HEIGHT - bordo, SCREEN_WIDTH - bordo, SCREEN_HEIGHT - bordo, WHITE);
}
| true |
56dcdd45fff0ba38a6544b1d50204aee2aceff57 | C++ | abduld/llambda | /runtime/binding/ProcedureCell.h | UTF-8 | 1,048 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | #ifndef _LLIBY_BINDING_PROCEDURECELL_H
#define _LLIBY_BINDING_PROCEDURECELL_H
#include "RecordLikeCell.h"
namespace lliby
{
class World;
/**
* Represents a Scheme procedure of an unknown type
*
* Untyped procedures can only have garbage collection performed on them. To be applied their exact type must be known.
* See TypedProcedureCell for a subclass that that supports application.
*/
class ProcedureCell : public RecordLikeCell
{
#include "generated/ProcedureCellMembers.h"
public:
ProcedureCell(RecordClassIdType recordClassId, bool dataIsInline, void *recordData, void *entryPoint) :
RecordLikeCell(CellTypeId::Procedure, recordClassId, dataIsInline, recordData),
m_entryPoint(entryPoint)
{
}
static ProcedureCell* createInstance(World &World, RecordClassIdType recordClassId, bool dataIsInline, void *recordData, void *entryPoint);
/**
* Indicates if this procedure captures variables from its enclosing scope
*/
bool capturesVariables() const
{
return recordClassId() != EmptyRecordLikeClassId;
}
};
}
#endif
| true |
d22f9c3256b0671beed43e0f5135e6b1e875d401 | C++ | tdk0371/learning_cpp | /newdel.cpp | UTF-8 | 2,466 | 3.71875 | 4 | [] | no_license | #include<iostream>
using std::string;
using std::cout;
using std::endl;
class POINT {
public:
int x;
int y;
POINT() {};
POINT(int nx, int ny): x(nx), y(ny) {cout<<"point initialized"<<endl;}
~POINT() {cout<<"destructor invoked"<<endl;}
};
class VECTOR {
public:
POINT start;
POINT end;
VECTOR () {start.x=0;start.y=0;end.x=0;end.y=0;cout<<"vector initialized"<<endl;}
VECTOR (VECTOR &o) {start = o.start; end = o.end; cout<<"vector copied"<<endl;}
void offset(int x, int y) {
start.x += x;
start.y += y;
end.x += x;
end.y += y;
cout<<"vector offseted"<<endl;}
void startoffset(int x, int y) {
start.x += x;
start.y += y;
cout<<"start point offseted"<<endl;}
void endoffset(int x, int y) {
end.x += x;
end.y += y;
cout<<"end point offseted"<<endl;}
void print() {
cout<<"vector start at ("<<start.x<<","<<start.y<<")"<<
" end at ("<<end.x<<","<<end.y<<")"<<endl;}
~VECTOR() {cout<<"destructor invoked"<<endl;}
};
//array wrapper object
class IARRAY {
public:
int * arr; //array pointer
int size; //array size
//constructor:
IARRAY (int size) {
arr = new int[size];
this->size = size;
cout<<"constructor invoked"<<endl;}
//copy constructor:
IARRAY (IARRAY &o) {
arr = new int[o.size];
size = o.size;
for (int i=0;i<size;i++) arr[i] = o.arr[i];
cout<<"copy constructor invoked"<<endl;}
//method:
int sum() {
int sum = 0;
for (int i=0;i<size;i++) sum += arr[i];
return sum;}
//destructor:
~IARRAY () {delete[] arr;cout<<"destructor invoker"<<endl;}
};
int main()
{
int i;
int arrsize = 5;
//use new to generate array
int * arr = new int[arrsize];
for (i=0;i<arrsize;i++) arr[i] = arrsize-i;
for (i=0;i<arrsize;i++) cout<<"arr["<<i<<"] = "<<arr[i]<<endl;
delete[] arr; //free memory
POINT * p1 = new POINT(20,30);
VECTOR *v1 = new VECTOR;
v1->offset(2,3);
v1->print();
v1->startoffset(3,-1);
v1->print();
v1->endoffset(-1,2);
v1->print();
IARRAY table(arrsize);
for (i=0;i<arrsize;i++) table.arr[i] = arrsize-i;
for (i=0;i<arrsize;i++) cout<<"table.arr["<<i<<"] = "<<table.arr[i]<<endl;
if (true)
{
IARRAY b = table; //b go out of scope after this line
for (i=0;i<arrsize;i++) cout<<"b.arr["<<i<<"] = "<<b.arr[i]<<endl;
}
for (i=0;i<arrsize;i++) cout<<"table.arr["<<i<<"] = "<<table.arr[i]<<endl;
//table became a dangling pointer after b is deleted
//solution: make a copy constructor in IARRAY class
cout<<"table.sum = "<<table.sum()<<endl;
return 0;
}
| true |
6767b917502dacf60e442a808298d882916c8f18 | C++ | khoiuit99/game | /03-Keyboard-States/Entity.cpp | UTF-8 | 2,660 | 2.734375 | 3 | [] | no_license | #include <d3dx9.h>
#include "Debug.h"
#include "GameManager.h"
#include "Entity.h"
#include "Sprite.h"
Entity::Entity()
{
this->velocity.x = 0;
this->velocity.y = 0;
}
Entity::~Entity()
{
}
void Entity::SetAliveState(Alive_State _alive)
{
this->aliveState = _alive;
}
void Entity::SetVelocity(float x, float y)
{
this->velocity.x = x;
this->velocity.y = y;
}
void Entity::SetPosition(float x, float y)
{
this->position.x = x;
this->position.y = y;
}
void Entity::SetPosition(D3DXVECTOR2 position)
{
this->position = position;
}
D3DXVECTOR2 Entity::GetPosition()
{
return this->position;
}
D3DXVECTOR2 Entity::GetVelocity()
{
return this->velocity;
}
float Entity::GetVelocityX()
{
return this->velocity.x;
}
float Entity::GetVelocityY()
{
return this->velocity.y;
}
void Entity::SetPositionX(float x)
{
this->position.x = x;
}
void Entity::SetPositionY(float y)
{
this->position.y = y;
}
void Entity::SetVelocity(D3DXVECTOR2 _velocity)
{
}
void Entity::SetVelocityX(float x)
{
this->velocity.x = x;
}
void Entity::SetVelocityY(float y)
{
this->velocity.y = y;
}
void Entity::AddVelocityX(float dx)
{
this->velocity.x += dx;
}
void Entity::AddVelocityY(float dy)
{
this->velocity.y += dy;
}
void Entity::SetSize(const SIZE& size)
{
this->size = size;
}
void Entity::SetSize(long width, long height)
{
this->size.cx = width;
this->size.cy = height;
}
SIZE Entity::GetSize()
{
return size;
}
void Entity::SetMoveHorizontalDirection(Entity_Horizontal_Direction _horizontalDirection)
{
this->horizontal_Direction = _horizontalDirection;
}
Entity::Entity_Horizontal_Direction Entity::GetMoveHorizontalDirection()
{
return this->horizontal_Direction;
}
void Entity::SetMoveVerticalDirection(Entity_Vertical_Direction _verticalDirection)
{
this->vertical_Direction = _verticalDirection;
}
Entity::Entity_Vertical_Direction Entity::GetMoveVerticalDirection()
{
return this->vertical_Direction;
}
void Entity::SetJumpDirection(Entity_Jump_Direction _jumpDirection)
{
this->jump_Direction = _jumpDirection;
}
Entity::Entity_Jump_Direction Entity::GetJumpDirection()
{
return this->jump_Direction;
}
void Entity::Update(float dt)
{
if (this->horizontal_Direction == Entity::Entity_Horizontal_Direction::LeftToRight) {
this->velocity.x = fabs(this->GetVelocityX());
}
else {
this->velocity.x = -fabs(this->GetVelocityX());
}
if (this->vertical_Direction == Entity::Entity_Vertical_Direction::BotToTop1) {
this->velocity.y = fabs(this->GetVelocityY());
}
else {
this->velocity.y = -fabs(this->GetVelocityY());
}
this->position.x += this->velocity.x * dt;
this->position.y += this->velocity.y * dt;
} | true |
584159015de7534b813ad473f6f617537288f8a3 | C++ | CIDCO-dev/SBET-decoder | /test/SbetPrinterTest.hpp | UTF-8 | 4,512 | 2.578125 | 3 | [
"MIT"
] | permissive | /*
* Copyright 2017 © Centre Interdisciplinaire de développement en Cartographie des Océans (CIDCO), Tous droits réservés
*/
/*
* File: SbetPrinterTest.hpp
* Author: jordan
*/
#ifndef SBETPRINTERTEST_HPP
#define SBETPRINTERTEST_HPP
#include "catch.hpp"
#include <string>
#include <sstream>
#include <cmath>
#include "Utils/CommandLineExecutor.hpp"
double absoluteDifference(double a, double b) {
return std::abs(a-b);
}
TEST_CASE("Accuracy Test") {
#ifdef _WIN32
std::string binexec("build\\bin\\accuracy-decoder.exe");
#else
std::string binexec("build/bin/accuracy-decoder");
#endif
std::string file(" test/data/20181023accuracy.out");
CommandLineExecutor exec;
std::stringstream ss;
ss = exec.execute(binexec + file);
//read header
std::string header;
for (int i = 0; i < 10; i++) {
ss >> header;
}
double Time;
double NorthingSD;
double EastingSD;
double AltitudeSD;
double SpeedNorthSD;
double SpeedEastSD;
double SpeedAltitudeSD;
double RollSd;
double PitchSd;
double HeadingSd;
ss >> Time >> NorthingSD >> EastingSD >> AltitudeSD >> SpeedNorthSD >> SpeedEastSD >> SpeedAltitudeSD >> RollSd >> PitchSd >> HeadingSd;
double eps = 1e-9;
//Time NorthingSD EastingSD AltitudeSD SpeedNorthSD SpeedEastSD SpeedAltitudeSD RollSd PitchSd HeadingSd
//225092.532698 0.023356 0.023366 0.018463 0.005244 0.005267 0.004156 0.002758 0.002759 0.044579
REQUIRE(absoluteDifference(Time, 225092.532698) < eps);
REQUIRE(absoluteDifference(NorthingSD, 0.023356) < eps);
REQUIRE(absoluteDifference(EastingSD, 0.023366) < eps);
REQUIRE(absoluteDifference(AltitudeSD, 0.018463) < eps);
REQUIRE(absoluteDifference(SpeedNorthSD, 0.005244) < eps);
REQUIRE(absoluteDifference(SpeedEastSD, 0.005267) < eps);
REQUIRE(absoluteDifference(SpeedAltitudeSD, 0.004156) < eps);
REQUIRE(absoluteDifference(RollSd, 0.002758) < eps);
REQUIRE(absoluteDifference(PitchSd, 0.002759) < eps);
REQUIRE(absoluteDifference(HeadingSd, 0.044579) < eps);
}
TEST_CASE("Sbet Test") {
#ifdef _WIN32
std::string binexec("build\\bin\\sbet-decoder.exe");
#else
std::string binexec("build/bin/sbet-decoder");
#endif
std::string file(" test/data/20181023.out");
CommandLineExecutor exec;
std::stringstream ss;
ss = exec.execute(binexec + file);
//read header
std::string header;
for (int i = 0; i < 17; i++) {
ss >> header;
}
// read data
double Time;
double Latitude;
double Longitude;
double Altitude;
double SpeedX;
double SpeedY;
double SpeedZ;
double Heading;
double Pitch;
double Roll;
double Wander;
double ForceX;
double ForceY;
double ForceZ;
double AngularRateX;
double AngularRateY;
double AngularRateZ;
ss >> Time >> Latitude >> Longitude >> Altitude >> SpeedX >> SpeedY >> SpeedZ >> Heading >> Pitch >> Roll >> Wander >> ForceX >> ForceY >> ForceZ >> AngularRateX >> AngularRateY >> AngularRateZ;
double eps = 1e-9;
//Time Latitude Longitude Altitude SpeedX SpeedY SpeedZ Heading Pitch Roll Wander ForceX ForceY ForceZ AngularRateX AngularRateY AngularRateZ
//225092.532698499999 46.783019673976 -71.272710666896 55.886139 0.003063 -0.002033 0.001337 4.601874186733 0.012073070456 0.079737922580 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
REQUIRE(absoluteDifference(Time, 225092.532698499999) < eps);
REQUIRE(absoluteDifference(Latitude, 46.783019673976) < eps);
REQUIRE(absoluteDifference(Longitude, -71.272710666896) < eps);
REQUIRE(absoluteDifference(Altitude, 55.886139) < eps);
REQUIRE(absoluteDifference(SpeedX, 0.003063) < eps);
REQUIRE(absoluteDifference(SpeedY, -0.002033) < eps);
REQUIRE(absoluteDifference(SpeedZ, 0.001337) < eps);
REQUIRE(absoluteDifference(Heading, 4.601874186733) < eps);
REQUIRE(absoluteDifference(Pitch, 0.012073070456) < eps);
REQUIRE(absoluteDifference(Roll, 0.079737922580) < eps);
REQUIRE(absoluteDifference(Wander, 0.0) < eps);
REQUIRE(absoluteDifference(ForceX, 0.0) < eps);
REQUIRE(absoluteDifference(ForceY, 0.0) < eps);
REQUIRE(absoluteDifference(ForceZ, 0.0) < eps);
REQUIRE(absoluteDifference(AngularRateX, 0.0) < eps);
REQUIRE(absoluteDifference(AngularRateY, 0.0) < eps);
REQUIRE(absoluteDifference(AngularRateZ, 0.0) < eps);
}
#endif /* SBETPRINTERTEST_HPP */
| true |
38c452ed6efcbdbb6f13937523636d1d186e59f2 | C++ | RexHac/ccompilerwithlex-yacc | /oldversion/Tree.cpp | UTF-8 | 2,474 | 3.171875 | 3 | [] | no_license | #include "Tree.h"
syntaxTree *createTree(string name, int num, ...)
{
va_list argList;
syntaxTree* head = new syntaxTree();
if (!head)
{
printf("create head failed!\n");
exit(0);
}
head->childrenAccount = NULL;
head->children = NULL;
head->value = "";
syntaxTree* temp = NULL;
head->name = name;
va_start(argList, num);
if (num > 0)
{
temp = va_arg(argList, syntaxTree*);
cout << "temp->name: "<<temp->name<<endl;
cout << "temp->value: "<<temp->value<<endl;
// 为什么要添加一个左节点,如果是num = 1 的话
// head->line = temp->line;
// num = 1 相当于把当前的temp完全赋值给head
if (num == 1)
{
head->childrenNumber = 1;
head->children = new syntaxTree*[1];
head->children[0] = temp;
if (temp->value.size() > 0)
{
//cout << "what value ???"<< temp->value<<endl;
//head->value = temp->value;
}
else
{
head->value = "";
}
}
else
{
head->children = new syntaxTree*[8];
head->childrenNumber = num;
for (int i = 0; i < num; i++)
{
head->children[i] = temp;
temp = va_arg(argList, syntaxTree*);
}
}
}
else
{
// int line = va_arg(argList, int);
// head->line = line;
head->childrenNumber = num;
head->value = yytext;
}
return head;
}
void printTree(syntaxTree *head, int level)
{
syntaxTree *tempRoot = head;
if (tempRoot != NULL)
{
if(tempRoot->children!=NULL)
{
int num = tempRoot->childrenNumber;
tempRoot->childrenAccount = new int[8];
//cout << "wo zhi xing "<<endl;
for(int i = 0; i < num; i++)
{
tempRoot->childrenAccount[i] = level + i;
//cout << "fuck" <<endl;
//cout <<"num: "<< num<<endl;
printTree(tempRoot->children[i],level++);
}
}
cout <<level<<": "<< tempRoot->name << " "<< tempRoot->value<<" children:";
for(int i = 0; i < tempRoot->childrenNumber ; i++)
{
cout<<tempRoot->childrenAccount[i]<<", ";
}
cout<< endl;
}
}
| true |
9f5f4a436135bd013039a231af8d0cddb39d8966 | C++ | 00mjk/Honeycomb-Game-Engine | /Honeycomb GE/include/object/GameObject.h | UTF-8 | 36,414 | 3.09375 | 3 | [
"MIT"
] | permissive | #pragma once
#ifndef GAME_OBJECT_H
#define GAME_OBJECT_H
#include <deque>
#include <functional>
#include <memory>
#include <string>
#include <vector>
#include "../component/GameComponent.h"
#include "../debug/Logger.h"
namespace Honeycomb { namespace Component { class GameComponent; } }
namespace Honeycomb { namespace Scene { class GameScene; } }
namespace Honeycomb { namespace Component { namespace Light {
class BaseLight; } } }
namespace Honeycomb { namespace Object {
/// <summary>
/// Exception which is to be thrown when a Game Object does not have a
/// component or child which the user is trying to access.
/// </summary>
class GameEntityNotAttachedException : public std::runtime_error {
public:
/// <summary>
/// Creates a new Game Entity Not Attached Exception for the object
/// of the specified name.
/// </summary>
/// <param name="g">
/// The game object which does not contain the Game Entity of the
/// given name.
/// </param>
/// <param name="name">
/// The name of the Game Entity which is not attached.
/// </param>
GameEntityNotAttachedException(const GameObject *g,
const std::string &name);
/// <summary>
/// Returns a constant character string containing the description of
/// the exception.
/// </summary>
/// <returns>
/// The constant character string exception info containing the name
/// of the Game Object and the name of the entity which could not be
/// fetched from the Game Object.
/// </returns>
virtual const char* what() const throw();
private:
const GameObject *gameObject; // Game Object for which exc. is thrown
std::string entityName; // Name of entity which D.N.E.
};
class GameObject {
friend class Honeycomb::Scene::GameScene;
public:
/// <summary>
/// Initializes a new Game Object with the name "Game Object" and no
/// parent or scene. The Game Object is not active by default and it
/// comes with a Transform component.
/// </summary>
GameObject();
/// <summary>
/// Initializes a new Game Object with the specified name, and no
/// parent or scene. The Game Object is not active by default and it
/// comes with a Transform component.
/// </summary>
/// <param name="name">
/// The name of the Game Object.
/// </param>
GameObject(const std::string &name);
/// <summary>
/// No copy constructor exists for the Game Object class.
/// </summary>
GameObject(const GameObject &object) = delete;
/// <summary>
/// Virtual Destructor for the Game Object class.
/// </summary>
virtual ~GameObject();
/// <summary>
/// Adds the specified Game Object as a child of this Game Object. If
/// the specified Game Object is already a child of this Game Object,
/// no further action is taken and the reference to the child is
/// returned. If the specified Game Object is already a child of some
/// other Game Object, the child is detached from its current parent
/// and reattached to this Game Object. Since the child is passed as a
/// unique pointer, this Game Object instance will take ownership of
/// the pointer.
/// </summary>
/// <param name="object">
/// The object to be parented to this Game Object. This should be moved
/// to the Game Object using the <see cref="std::move"/> function.
/// </param>
/// <returns>
/// The reference to the new child Game Object.
/// </returns>
virtual GameObject& addChild(std::unique_ptr<GameObject> object);
/// <summary>
/// Adds the specified Game Component to this Game Object. If the
/// specified Game Component is already attached to this Game Object,
/// no further action is taken and the reference to the component is
/// returned. If the specified Game Component is already attached to
/// some other Game Object, the component is detached from its current
/// parent and reattached to this Game Object. Since the component is
/// passed as a unique pointer, this Game Object instance will take
/// ownership of the pointer.
///
/// If the component has the DisallowMultiple property and there is
/// already a Game Component of the same type attached to this, a
/// GameComponentDisallowsMultipleException will be thrown.
/// </summary>
/// <param name="component">
/// The component to be parented to this Game Object. This should be
/// moved to the Game Component using the <see cref="std::move"/>
/// function.
/// </param>
/// <exception cref="GameComponentDisallowsMultipleException">
/// Thrown if a Game Component of the same type as the argument is
/// already attached to this Game Component.
/// </exception>
Honeycomb::Component::GameComponent& addComponent(std::unique_ptr<
Honeycomb::Component::GameComponent> component);
/// <summary>
/// Creates and adds a Game Component of the specified type to this
/// Game Object. The Game Component is constructed using the arguments
/// specified as parameters to this function.
///
/// If the component has the DisallowMultiple property and there is
/// already a Game Component of the same type attached to this, a
/// GameComponentDisallowsMultipleException will be thrown.
/// </summary>
/// <typeparam name="T">
/// The type of Game Component to be created and attached to this
/// Game Object.
/// </typeparam>
/// <typeparam name="...TArgs">
/// The arguments types to be passed to the constructor of the Game
/// Component.
/// </typeparam>
/// <param name="args">
/// The arguments to be passed to the constructor of the Game
/// Component.
/// </param>
template<typename T, typename ...TArgs>
Honeycomb::Component::GameComponent& addComponent(TArgs&&... args) {
Honeycomb::Component::GameComponent::assertIsBaseOf<T>();
std::unique_ptr<Honeycomb::Component::GameComponent> component =
std::make_unique<T>(std::forward<TArgs>(args)...);
return this->addComponent(std::move(component));
}
/// <summary>
/// Clones this Game Object into a new, independent Game Object. The
/// Game Object will have all of the same properties, components and
/// children of this Game Object, but they will all be cloned and
/// independent of this Game Object. The cloned Game Object will not be
/// parented to any Scene or Game Object, nor will it be active by
/// default.
/// </summary>
/// <returns>
/// The unique pointer to the Game Object clone instance.
/// </returns>
std::unique_ptr<GameObject> clone() const;
/// <summary>
/// Disables this Game Object. This has no effect if the Game Object is
/// already disabled. Note that this only disables the self-activeness
/// property of the Game Object.
/// </summary>
virtual void doDisable();
/// <summary>
/// Enables this Game Object. This has no effect if the Game Object is
/// already enabled. Note that this only enables the self-activeness
/// property of the Game Object.
/// </summary>
virtual void doEnable();
/// <summary>
/// Gets the child of this Game Object which has the specified name. If
/// the object has multiple children of the specified name, the first
/// child found in the children vector is returned.
/// </summary>
/// <param name="name">
/// The name of the Game Object child.
/// </param>
/// <returns>
/// The reference to the child Game Object.
/// </returns>
/// <exception cref="GameEntityNotAttachedException">
/// Thrown if the game object has no child of the specified name.
/// </exception>
GameObject& getChild(const std::string &name);
/// <summary>
/// Gets the child of this Game Object which has the specified name. If
/// the object has multiple children of the specified name, the first
/// child found in the children vector is returned.
/// </summary>
/// <param name="name">
/// The name of the Game Object child.
/// </param>
/// <returns>
/// The constant reference to the child Game Object.
/// </returns>
/// <exception cref="GameEntityNotAttachedException">
/// Thrown if the game object has no child of the specified name.
/// </exception>
const GameObject& getChild(const std::string &name) const;
/// <summary>
/// Returns a list of all of the children of this Game Object.
/// </summary>
/// <returns>
/// The vector containing the references to the children of this Game
/// Object.
/// </returns>
std::vector<std::reference_wrapper<GameObject>> getChildren();
/// <summary>
/// Returns a list of all of the children of this Game Object.
/// </summary>
/// <returns>
/// The vector containing the constant references to the children of
/// this Game Object.
/// </returns>
std::vector<std::reference_wrapper<const GameObject>> getChildren()
const;
/// <summary>
/// Returns a list of all of the children of this Game Object whose
/// name matches thes the specified string.
/// </summary>
/// <param name="name">
/// The name of the game objects.
/// </param>
/// <returns>
/// The vector containing the references to the children of this Game
/// Object with the specified name.
/// </returns>
std::vector<std::reference_wrapper<GameObject>> getChildren(
const std::string &name);
/// <summary>
/// Returns a list of all of the children of this Game Object whose
/// name matches thes the specified string.
/// </summary>
/// <param name="name">
/// The name of the game objects.
/// </param>
/// <returns>
/// The vector containing the constant references to the children of
/// this Game Object with the specified name.
/// </returns>
std::vector<std::reference_wrapper<const GameObject>> getChildren(
const std::string &name) const;
/// <summary>
/// Gets the component of this Game Object which has the specified Type
/// and downcasts it to that type. If the game object has multiple game
/// components of the specified type, the first component of that type
/// is returned.
/// </summary>
/// <typeparam name="T">
/// The type of the game component which is attached to this Game
/// Object.
/// </typeparam>
/// <returns>
/// The reference to the game component found.
/// </returns>
/// <exception cref="GameEntityNotAttachedException">
/// Thrown if the game object has no component of the specified name.
/// </exception>
template<class T>
T& getComponent() {
return const_cast<T&>(static_cast<const GameObject*>
(this)->getComponent<T>());
}
/// <summary>
/// Gets the component of this Game Object which has the specified Type
/// and downcasts it to that type. If the game object has multiple game
/// components of the specified type, the first component of that type
/// is returned.
/// </summary>
/// <typeparam name="T">
/// The type of the game component which is attached to this Game
/// Object.
/// </typeparam>
/// <returns>
/// The constant reference to the game component found.
/// </returns>
/// <exception cref="GameEntityNotAttachedException">
/// Thrown if the game object has no component of the specified name.
/// </exception>
template<class T>
const T& getComponent() const {
Honeycomb::Component::GameComponent::assertIsBaseOf<T>();
auto &componentsOfType = this->getComponentsInternal<T>();
for (auto &comp : componentsOfType)
return dynamic_cast<const T&>(*comp.get());
throw GameEntityNotAttachedException(this, typeid(T).name());
}
/// <summary>
/// Gets all of the components of this Game Object which have the
/// specified Type and returns a list of the references to them. If the
/// Game Object has no such component, the vector returned is empty.
/// </summary>
/// <typeparam name="T">
/// The type of the game component which is attached to this Game
/// Object.
/// </typeparam>
/// <returns>
/// The vector of references to the game components.
/// </returns>
template<class T>
std::vector<std::reference_wrapper<T>> getComponents() {
Honeycomb::Component::GameComponent::assertIsBaseOf<T>();
auto &rawComponents = this->getComponentsInternal<T>();
std::vector<std::reference_wrapper<T>> components;
for (auto &raw : rawComponents) {
auto &downcast = dynamic_cast<T&>(*raw.get());
auto refWrapped = std::ref(downcast);
components.push_back(refWrapped);
}
return components;
}
/// <summary>
/// Gets all of the components of this Game Object and all of the
/// components of all of the ancestors of this Game Object which have
/// the specified Type and returns a list of the references to them.
/// This function works recursively so it will contain the components
/// of the parent, and parent of parent, etc. Note that since the scene
/// is considered to be a parent, it may also contain components
/// attached to the scene. If the Game Object nor any parents have the
/// components of the specified type, the returned vector is empty.
/// </summary>
/// <typeparam name="T">
/// The type of the game component.
/// </typeparam>
/// <returns>
/// The vector of references to the game components.
/// </returns>
template<class T>
std::vector<std::reference_wrapper<T>> getComponentsInAncestors() {
Honeycomb::Component::GameComponent::assertIsBaseOf<T>();
std::vector<std::reference_wrapper<T>> ancestorComponents;
// Traverse up the parent hierarchy
GameObject *current = this;
do {
// Get the components of type T of the current object
const auto ¤tComponents =
current->getComponentsInternal<T>();
// For each component, downcast to type T, convert to reference
// and store into components vector.
for (const auto &raw : currentComponents) {
auto &downcast = dynamic_cast<T&>(*raw.get());
auto refWrapped = std::ref(downcast);
ancestorComponents.push_back(refWrapped);
}
// Go to next parent
current = current->parent;
} while (current != nullptr);
return ancestorComponents;
}
/// <summary>
/// Gets all of the components of this Game Object and all of the
/// components of all of the descendants of this Game Object which have
/// the specified Type and returns a list of the references to them.
/// This function uses the Depth First Search algorithm to find the
/// game components. If neither the Game Object nor any children have
/// components of the specified type, the returned vector is empty.
/// </summary>
/// <typeparam name="T">
/// The type of the game component.
/// </typeparam>
/// <returns>
/// The vector of references to the game components.
/// </returns>
template<class T>
std::vector<std::reference_wrapper<T>> getComponentsInDescendants() {
Honeycomb::Component::GameComponent::assertIsBaseOf<T>();
std::vector<std::reference_wrapper<T>> descendantComponents;
// For DFS, make a toVisit list and add root (this) node to it
std::deque<std::reference_wrapper<GameObject>> toVisit;
toVisit.push_back(std::ref(*this));
while (!toVisit.empty()) {
// Get the front node and remove it from the toVisit list
auto current = toVisit.front();
toVisit.pop_front();
// Add the children of this Game Object to the toVisit list
const auto ¤tChildren = current.get().getChildren();
for (auto &child : currentChildren) {
toVisit.push_back(child);
}
// Fetch components of type T from current object, downcast
// them, turn them to references, append to components list.
auto ¤tComponents =
current.get().getComponentsInternal<T>();
for (auto &comp : currentComponents) {
auto &downcast = dynamic_cast<T&>(*comp.get());
auto refWrapped = std::ref(downcast);
descendantComponents.push_back(refWrapped);
}
}
return descendantComponents;
}
/// <summary>
/// Gets all of the components of this Game Object which have the
/// specified Type or which are inherited from the specified Type and
/// returns a list of the references to them.
/// </summary>
/// <typeparam name="T">
/// The type of the game component. If the type specified is
/// GameComponent, this returns a list of references to all of the
/// components of the Game Object.
/// </typeparam>
/// <returns>
/// A list of references to the components of type T or which inherit
/// from type T.
/// </returns>
template<typename T>
std::vector<std::reference_wrapper<T>> getComponentsInherited() {
Honeycomb::Component::GameComponent::assertIsBaseOf<T>();
std::vector<std::reference_wrapper<T>> refComponents;
// Go through each component type
for (auto &componentsOfType : this->components) {
// If no components of this type exist, continue to next set
if (componentsOfType.empty()) continue;
// If any component in the set does not downcast to type T,
// continue to next set.
auto first = componentsOfType[0].get();
if (dynamic_cast<T*>(first) == nullptr) continue;
// Else, downcast each component to type T and store in
// the reference vector.
for (auto &component : componentsOfType) {
auto &downcast = dynamic_cast<T&>(*component.get());
auto refWrapped = std::ref(downcast);
refComponents.push_back(refWrapped);
}
}
return refComponents;
}
/// <summary>
/// Gets all of the components of this Game Object or any of its
/// ancestors which have the specified Type or which are inherited from
/// the specified Type and returns a list of the references to them.
/// This function works recursively so it will contain the components
/// of the parent, and parent of parent, etc. Note that since the scene
/// is considered to be a parent, it may also contain components
/// attached to the scene.
/// </summary>
/// <typeparam name="T">
/// The type of the game component. If the type specified is
/// GameComponent, this returns a list of references to all of the
/// components of this and the ancestor Game Objects.
/// </typeparam>
/// <returns>
/// A list of references to the components of type T or which inherit
/// from type T.
/// </returns>
template<typename T>
std::vector<std::reference_wrapper<T>>
getComponentsInheritedInAncestors() {
Honeycomb::Component::GameComponent::assertIsBaseOf<T>();
std::vector<std::reference_wrapper<T>> ancestorComponents;
// Traverse up the parent hierarchy
GameObject *current = this;
do {
// Get the components of type T of the current object
const auto ¤tComponents =
current->getComponentsInherited<T>();
// Add the fetched components to the ancestor components list
ancestorComponents.insert(ancestorComponents.end(),
currentComponents.begin(), currentComponents.end());
// Go to next parent
current = current->parent;
} while (current != nullptr);
return ancestorComponents;
}
/// <summary>
/// Gets all of the components of this Game Object or any of its
/// descendants which have the specified Type or which are inherited
/// from the specified Type and returns a list of the references to
/// them. This function uses the Depth First Search algorithm to find
/// the game components.
/// </summary>
/// <typeparam name="T">
/// The type of the game component. If the type specified is
/// GameComponent, this returns a list of references to all of the
/// components of this and the descendant Game Objects.
/// </typeparam>
/// <returns>
/// A list of references to the components of type T or which inherit
/// from type T.
/// </returns>
template<typename T>
std::vector<std::reference_wrapper<T>>
getComponentsInheritedInDescendants() {
Honeycomb::Component::GameComponent::assertIsBaseOf<T>();
std::vector<std::reference_wrapper<T>> descendantComponents;
// For DFS, make a toVisit list and add root (this) node to it
std::deque<std::reference_wrapper<GameObject>> toVisit;
toVisit.push_back(std::ref(*this));
while (!toVisit.empty()) {
// Get the front node and remove it from the toVisit list
auto current = toVisit.front();
toVisit.pop_front();
// Add the children of this Game Object to the toVisit list
const auto ¤tChildren = current.get().getChildren();
for (auto &child : currentChildren) {
toVisit.push_back(child);
}
// Get the components of type T of the current object and add
// the fetched components to the ancestor components list.
const auto ¤tComponents =
current.get().getComponentsInherited<T>();
descendantComponents.insert(descendantComponents.end(),
currentComponents.begin(), currentComponents.end());
}
return descendantComponents;
}
/// <summary>
/// Gets a boolean representing whether or not the Game Object is
/// enabled. This is true only if this is self active and its parent
/// is active.
/// </summary>
/// <returns>
/// True if the object is active, false otherwise.
/// </returns>
virtual bool getIsActive() const;
/// <summary>
/// Gets a boolean representing whether or not the Game Object is self
/// enabled. The self-activeness of the Game Object is independent of
/// its parent's activeness.
/// </summary>
/// <returns>
/// True if the object is self active, false otherwise.
/// </returns>
const bool& getIsSelfActive() const;
/// <summary>
/// Gets the name of this Game Object.
/// </summary>
/// <returns>
/// The name of this Game Object.
/// </returns>
const std::string& getName() const;
/// <summary>
/// Returns the total number of components attached to this Game
/// Object. Since the Game Object structure uses a hash table to store
/// its components, this should be used to find the number of
/// components, rather than checking the size of the vector returned by
/// the <see cref="getComponents"/> method.
/// </summary>
/// <returns>
/// The number of components attached to this Game Object.
/// </returns>
const unsigned int& getNumberOfComponents() const;
/// <summary>
/// Returns the total number of components of the specified type which
/// are attached to this Game Object.
/// </summary>
/// <typeparam name="T">
/// The type of the component.
/// </typeparam>
/// <returns>
/// The number of components of type T attached to this Game Object.
/// </returns>
template<typename T>
unsigned int getNumberOfComponents() const {
return this->getComponentsInternal<T>().size();
}
/// <summary>
/// Returns the number of components attached to this Game Object which
/// have the same Component ID as the specified parameter.
/// </summary>
/// <param name="id">
/// The Component ID of the Component Type.
/// </param>
/// <returns>
/// The number of components attached to this Game Object which share
/// the Component ID with the parameter.
/// </returns>
unsigned int getNumberOfComponents(const unsigned int &id) const;
/// <summary>
/// Returns the parent of this Game Object, or null if this object has
/// no parent.
/// </summary>
/// <returns>
/// The pointer to the parent.
/// </returns>
GameObject* getParent();
/// <summary>
/// Returns the parent of this Game Object, or null if this object has
/// no parent.
/// </summary>
/// <returns>
/// The constant pointer to the parent.
/// </returns>
const GameObject* getParent() const;
/// <summary>
/// Returns the scene of this Game Object, or null if this object is
/// not part of a scene.
/// </summary>
/// <returns>
/// The pointer to the scene.
/// </returns>
Honeycomb::Scene::GameScene* getScene();
/// <summary>
/// Returns the scene of this Game Object, or null if this object is
/// not part of a scene.
/// </summary>
/// <returns>
/// The constant pointer to the scene.
/// </returns>
const Honeycomb::Scene::GameScene* getScene() const;
/// <summary>
/// Checks if the specified child is attached to this Game Object.
/// </summary>
/// <param name="child">
/// The game object which is to be checked.
/// </param>
/// <returns>
/// True if that specified child instance is attached to this Game
/// Object.
/// </returns>
bool hasChild(const GameObject *child) const;
/// <summary>
/// Checks if the specified component is attached to this Game Object.
/// </summary>
/// <param name="component">
/// The component which is to be checked.
/// </param>
/// <returns>
/// True if that specific component instance is attached to this Game
/// Object.
/// </returns>
bool hasComponent(const Honeycomb::Component::GameComponent
*component) const;
/// <summary>
/// Checks if the Game Object has a Game Component of the specified ID
/// attached to it.
/// </summary>
/// <param name="id">
/// The Game Component ID.
/// </param>
/// <returns>
/// True if the Game Object has at least one component with the
/// specified ID attached to it, false otherwise.
/// </returns>
bool hasComponent(const unsigned int &id) const;
/// <summary>
/// Checks if this Game Object has at least one component of the
/// specified type.
/// </summary>
/// <typeparam name="T">
/// The type of the Game Component.
/// </typeparam>
/// <returns>
/// True if this Game Object has at least one component of the
/// specified type. False otherwise.
/// </returns>
template<typename T>
bool hasComponent() const {
Honeycomb::Component::GameComponent::assertIsBaseOf<T>();
return this->getNumberOfComponents<T>() > 0;
}
/// <summary>
/// Checks if this Game Object has a parent.
/// </summary>
/// <returns>
/// True if this Game Object has a parent, false otherwise.
/// </returns>
bool hasParent() const;
/// <summary>
/// Checks if this Game Object has a scene.
/// </summary>
/// <returns>
/// True if the Game Object is attached to a scene, false otherwise.
/// </returns>
bool hasScene() const;
/// <summary>
/// This function is called after the Game Object is disabled, and
/// should handle any (re)disabiling events for the object.
/// </summary>
virtual void onDisable();
/// <summary>
/// This function is called after the Game Object is enabled, and
/// should handle any (re)enabling events for the object.
/// </summary>
virtual void onEnable();
/// <summary>
/// This function is called once per frame if the Game Object is
/// active, and should handle any input events for the object.
/// This function is recursively called for each child.
/// </summary>
virtual void onInput();
/// <summary>
/// This function is called once per frame if the Game Object is
/// active, and should handle any rendering events for the object.
/// This function is recursively called for each child.
/// </summary>
/// <param name="shader">
/// The shader, using which, the Game Object is to be rendered.
/// </param>
virtual void onRender(Honeycomb::Shader::ShaderProgram &shader);
/// <summary>
/// Called when the Game Object first starts. This function should only
/// be called once and should initialize all of the properties of this
/// Object. This automatically enables the Game Object. This function
/// is recursively called for each child.
/// </summary>
virtual void onStart();
/// <summary>
/// Called when the Game Object ends. This function should only
/// be called once and should de-initialize all of the properties of
/// this Object. This automatically disables the Game Object. This
/// function is recursively called for each child.
/// </summary>
virtual void onStop();
/// <summary>
/// This function is called once per frame if the Game Object is
/// active, and should handle any updating events for the object.
/// This function is recursively called for each child.
/// </summary>
virtual void onUpdate();
/// <summary>
/// Removes the specified child from this Game Object and returns a
/// unique pointer to it. If the specified Game Object is not attached
/// to this Game Object, a GameEntityNotAttached exception will be
/// thrown
/// </summary>
/// <param name="object">
/// The pointer to the child which is to be removed.
/// </param>
/// <returns>
/// The unique pointer to the child after it has been removed from this
/// Game Object.
/// </returns>
/// <exception cref="GameEntityNotAttachedException">
/// Thrown if the Game Object specified is not attached to this.
/// </exception>
virtual std::unique_ptr<GameObject> removeChild(GameObject *object);
/// <summary>
/// Removes the specfied Game Component from this Game Object. If the
/// specified Game Component is not attached to this Game Object, a
/// GameEntityNotAttached exception will be thrown. Once the Game
/// Component is detached, it's onDetach method will be called and the
/// unique pointer containing it will be returned.
/// </summary>
/// <param name="component">
/// The component to be detached from this Game Object.
/// </param>
/// <returns>
/// The unique pointer to the newly independent game component.
/// </returns>
/// <exception cref="GameEntityNotAttachedException">
/// Thrown if the Game Component specified is not attached to this.
/// </exception>
/// <exception cref="GameComponentPermanentException">
/// Thrown if the Game Component specified is permanent and cannot be
/// removed.
/// </exception>
std::unique_ptr<Honeycomb::Component::GameComponent>
removeComponent(Honeycomb::Component::GameComponent
*component);
/// <summary>
/// Sets the name of this Game Object.
/// </summary>
/// <param name="name">
/// The new name of the Game Object.
/// </param>
void setName(const std::string &name);
/// <summary>
/// No assignment operator exists for the Game Object class.
/// </summary>
GameObject& operator=(const GameObject &object) = delete;
protected:
bool isSelfActive; // Is this object self active?
std::string name; // Name of this Game Object
GameObject *parent; // The parent of this Game Object
Honeycomb::Scene::GameScene *scene; // Scene to which this belongs to
// The children and components of this Game Object
std::vector<std::unique_ptr<GameObject>> children;
// The 2D array of all of the components of the Game Object. For each
// Game Component, there exists an array, at the index of the Game
// Component ID, which contains all of the Game Components of that
// type which are attached to this Game Object.
mutable std::vector<std::vector<std::unique_ptr<
Honeycomb::Component::GameComponent>>> components;
unsigned int numComponents;
/// <summary>
/// Initializes a new Game Object with the specified name, and no
/// parent or scene. The Game Object is not active by default. The
/// <paramref name="attachTransform"/> parameter specifies whether or
/// not a Transform component should be attached.
/// </summary>
/// <param name="name">
/// The name of the Game Object.
/// </param>
/// <param name="attachTransform">
/// Should a Transform component be attached?
/// </param>
GameObject(const std::string &name, const bool &attachTransform);
/// <summary>
/// Returns the list of components attached to this Game Object which
/// share the same Component ID as the specified parameter. This
/// function also automatically resizes the components vector if new
/// component types were added since it (or its overrides) was last
/// called.
/// </summary>
/// <param name="id">
/// The Component ID.
/// </param>
/// <returns>
/// The list of components attached to this Game Object which have the
/// same Component ID as the parameter, by means of a reference.
/// </returns>
std::vector<std::unique_ptr<Honeycomb::Component::GameComponent>>&
getComponentsInternal(const unsigned int &id);
/// <summary>
/// Returns the list of components attached to this Game Object which
/// share the same Component ID as the specified parameter. This
/// function also automatically resizes the components vector if new
/// component types were added since it (or its overrides) was last
/// called.
/// </summary>
/// <param name="id">
/// The Component ID.
/// </param>
/// <returns>
/// The list of components attached to this Game Object which have the
/// same Component ID as the parameter, by means of a reference.
/// </returns>
const std::vector<std::unique_ptr<
Honeycomb::Component::GameComponent>>&
getComponentsInternal(const unsigned int &id) const;
/// <summary>
/// Returns the list of components of the specified type which are
/// attached to this Game Object. This function also automatically
/// resizes the components vector if new component types were added
/// since it (or its overrides) was last called.
/// </summary>
/// <typeparam name="T">
/// The type of the component.
/// </typeparam>
/// <returns>
/// The list of components of type T attached to this Game Object, by
/// means of a reference.
/// </returns>
template<typename T>
std::vector<std::unique_ptr<Honeycomb::Component::GameComponent>>&
getComponentsInternal() {
Honeycomb::Component::GameComponent::assertIsBaseOf<T>();
this->resizeComponents();
// Get the list of components of the specified type and return it
unsigned int id = Honeycomb::Component::GameComponent::
getGameComponentTypeID<T>();
return this->components.at(id);
}
/// <summary>
/// Returns the list of components of the specified type which are
/// attached to this Game Object. This function also automatically
/// resizes the components vector if new component types were added
/// since it (or its overrides) was last called.
/// </summary>
/// <typeparam name="T">
/// The type of the component.
/// </typeparam>
/// <returns>
/// The list of components of type T attached to this Game Object, by
/// means of a reference.
/// </returns>
template<typename T>
const std::vector<std::unique_ptr<
Honeycomb::Component::GameComponent>>&
getComponentsInternal() const {
Honeycomb::Component::GameComponent::assertIsBaseOf<T>();
this->resizeComponents();
// Get the list of components of the specified type and return it
unsigned int id = Honeycomb::Component::GameComponent::
getGameComponentTypeID<T>();
return this->components.at(id);
}
/// <summary>
/// This function is called right after this Game Object is attached to
/// a new parent.
/// </summary>
/// <param name="object">
/// The object to which this Game Object was attached to. An assertion
/// checks that this is not null.
/// </param>
virtual void onAttach(GameObject *object);
/// <summary>
/// This function is called when this Game Object is attached to a new
/// scene. This function is called recursively for all children of this
/// Game Object.
/// </summary>
/// <param name="scene">
/// The scene to which this Game Object was attached to. An assertion
/// checks that this is not null.
/// </param>
virtual void onAttach(Honeycomb::Scene::GameScene *scene);
/// <summary>
/// This function is called right before this Game Object is detached
/// from its parent.
/// </summary>
/// <param name="object">
/// The object from which this Game Object was detached from. An
/// assertion checks that this is not null.
/// </param>
virtual void onDetach(GameObject *object);
/// <summary>
/// This function is called right before this Game Object is detached
/// from its scene. This function is called recursively for all
/// children of this Game Object.
/// </summary>
/// <param name="scene">
/// The scene from which this Game Object was detached from. An
/// assertion checks that this is not null.
/// </param>
virtual void onDetach(Honeycomb::Scene::GameScene *scene);
/// <summary>
/// Resizes the components vector of this Game Object to be roughly
/// twice the size of the number of component types if the number of
/// component types exceeds the components vector size.
/// </summary>
void resizeComponents() const;
};
} }
#endif
| true |
f8cbcf17afa78e7685a99390c0e128bb34ae6e3b | C++ | hkmangla/cppProgramms | /c.cpp | UTF-8 | 793 | 3.390625 | 3 | [] | no_license | #include <stdio.h>
#define SIZE 13
int boyerMoore(int arr[]) {
int current_candidate = arr[0], counter = 0, i;
for (i = 0; i < 11; ++i) {
if (current_candidate == arr[i]) {
++counter;
printf("candidate: %i, counter: %i\n",current_candidate,counter);
} else if (counter == 0) {
current_candidate = arr[i];
++counter;
printf("candidate: %i, counter: %i\n",current_candidate,counter);
} else {
--counter;
printf("candidate: %i, counter: %i\n",current_candidate,counter);
}
}
return current_candidate;
}
int main() {
int numbers[SIZE] = {5,5,5,3,3,1,1,5,3,1,2,2};
printf("majority: %i\n", boyerMoore(numbers));
return 0;
}
| true |
5bafc7024492fd90cba543385523a35d22769eb2 | C++ | Nikhil12321/codes | /rod_cutting.cpp | UTF-8 | 648 | 3.359375 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<climits>
using namespace std;
int rodCutting(vector<int> &prices){
int n = prices.size();
int i, j;
int ans[n+1];
ans[0] = 0;
for(j = 1; j<=n; j++){
int max = INT_MIN;
for(i = 0; i<j; i++){
if(prices[j-i-1] + ans[i] > max)
max = prices[j-i-1] + ans[i];
}
ans[j] = max;
}
return ans[n];
}
int main(){
std::vector<int> v;
int n;
cin>>n;
for(int i=0; i<n; i++)
{
int a;
cin>>a;
v.push_back(a);
}
int ans = rodCutting(v);
cout<<ans<<endl;
} | true |
20dc43a322e2ca2aa60c846283396a52a135b27b | C++ | ana-GT/Lucy | /RST_Summer_Code/Hope/dijkstra.cpp | UTF-8 | 7,647 | 2.734375 | 3 | [] | no_license | /**
* @file dijkstra.cpp
*/
#include "dijkstra.h"
const int Dijkstra3D::mNX[26] = { -1,-1,-1, -1,-1,-1, -1,-1,-1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
const int Dijkstra3D::mNY[26] = { -1, 0, 1, -1, 0, 1, -1, 0, 1, -1, 0, 1, -1, 1, -1, 0, 1, -1, 0, 1,-1, 0, 1,-1, 0, 1 };
const int Dijkstra3D::mNZ[26] = { -1,-1,-1, 0, 0, 0, 1, 1, 1, -1,-1,-1, 0, 0, 1, 1, 1, -1,-1,-1, 0, 0, 0, 1, 1, 1 };
const float Dijkstra3D::smSqr2 = sqrt(2);
const float Dijkstra3D::smSqr3 = sqrt(3);
/**
* @function State3D
*/
Node3D::Node3D()
{}
void Node3D::init( int _x, int _y, int _z )
{
this->x = _x;
this->y = _y;
this->z = _z;
this->dist = INF_VAL;
this->parent = -1;
this->color = 2; // WHITE: Nowhere
}
/**
* @function Destructor Node3D
*/
Node3D::~Node3D()
{
}
/**
* @function Constructor
*/
Dijkstra3D::Dijkstra3D()
{
this->mBaseCost = 1.0;
this->mMinObstDist = 0.05;
}
/**
* @function Destructor
*/
Dijkstra3D::~Dijkstra3D()
{
if( HT != NULL )
{ delete [] HT; }
if( V != NULL )
{ delete [] V; };
}
/**
* @function cleanup
*/
void Dijkstra3D::cleanup()
{
}
/**
* @function setGrid3D
*/
void Dijkstra3D::setGrid3D( VoxelGrid<int>* _grid )
{
grid = _grid;
mDimX = grid->getNumCells( VoxelGrid<int>::DIM_X );
mDimY = grid->getNumCells( VoxelGrid<int>::DIM_Y );
mDimZ = grid->getNumCells( VoxelGrid<int>::DIM_Z );
mTotalCells = mDimX*mDimY*mDimZ;
mStride1 = mDimY*mDimZ;
mStride2 = mDimZ;
//-- Initialize my Hash Table for my binary heap Q
HT = new int[mTotalCells];
std::fill( HT, HT + mTotalCells , -1 );
//-- Allocate space for V (total nodes)
V = new Node3D[mTotalCells];
}
/**
* @function setDF
*/
void Dijkstra3D::setDF( PFDistanceField* _df )
{
this->distField = _df;
}
/**
* @function setGoal
*/
void Dijkstra3D::setGoal( int _goalX, int _goalY, int _goalZ )
{
this->goalX = _goalX;
this->goalY = _goalY;
this->goalZ = _goalZ;
}
/**
* @function search
*/
void Dijkstra3D::search()
{
printf("Search build \n");
ts = clock();
//-- Initialize your states
for( int i = 0; i < mDimX; i++ )
{ for( int j = 0; j < mDimY; j++ )
{ for( int k = 0; k < mDimZ; k++ )
{
V[ ref(i,j,k) ].init( i, j, k ) ;
if( grid->getCell( i, j, k ) != 0 ) //-- If it is an obstacle
{ V[ ref(i,j,k) ].color = 3; }
}
}
}
tf = clock();
printf("Building structure in Dijkstra: %f \n", (double) (tf - ts)/CLOCKS_PER_SEC );
//-- Initialize the goal state
int s = ref( goalX, goalY, goalZ ) ;
V[ s ].color = 1; // gray: In Open List
V[ s ].dist = 0;
//-- Insert to Q (unvisited nodes)
insertOpenSet( s );
//-- Iterate
int u; int v;
float new_dist;
while( Q.size() != 0 )
{
u = popOpenSet( );
//-- All neighbors
std::vector< int > ng = neighbors( u );
for( int i = 0; i < ng.size(); i++ )
{
v = ng[i];
new_dist = ( edgeCost( u, v ) + V[ u ].dist );
if( new_dist < V[ v ].dist )
{
V[ v ].dist = new_dist ;
V[ v ].parent = u;
}
if( V[ v ].color == 2 ) //-- Nowhere
{
V[ v ].color = 1; //-- Add it to the OpenList (queue)
insertOpenSet( v );
}
else if( V[ v ].color == 1 )
{
lowerKeyOpenSet( v );
}
else
{ /** Pretty much nothing by now */ }
} //-- End for
V[u].color = 0; //-- Closed List
} //-- End while
}
/**
* @function insertOpenSet
*/
void Dijkstra3D::insertOpenSet( int ID )
{
int n;
int node; int parent;
int temp;
Q.push_back( ID );
n = Q.size() - 1;
// If this is the first element added
if( n == 0 )
{ HT[ID] = n; return; }
// If not, start on the bottom and go up
node = n;
int qp; int qn;
while( node != 0 )
{
//parent = floor( (node - 1)/2 );
parent = (node - 1)/2 ;
qp = Q[parent]; qn = Q[node];
if( V[ qp ].dist >= V[ qn ].dist )
{
temp = qp;
Q[parent] = qn; HT[qn] = parent;
Q[node] = temp; HT[temp] = node;
node = parent;
}
else
{ break; }
}
HT[ID] = node;
}
/**
* @function popOpenSet
*/
int Dijkstra3D::popOpenSet( )
{
int first; int bottom;
int node;
int child_1; int child_2;
int n;
int temp;
if( Q.size() == 0 )
{ printf("(!)-- ERROR ! No more elements left \n");return -1; }
// Save the pop-out element
first = Q[0];
// Reorder your binary heap
bottom = Q.size() - 1;
Q[0] = Q[bottom]; HT[Q[bottom]] = 0;
Q.pop_back();
n = Q.size();
int u = 0;
int qu;
while( true )
{
node = u;
child_1 = 2*node + 1;
child_2 = 2*node + 2;
if( child_2 < n )
{
if( V[ Q[node] ].dist >= V[ Q[child_1] ].dist )
{ u = child_1; }
if( V[ Q[u] ].dist >= V[ Q[child_2] ].dist )
{ u = child_2; }
}
else if( child_1 < n )
{
if( V[ Q[node] ].dist >= V[ Q[child_1] ].dist )
{ u = child_1; }
}
qu = Q[u];
if( node != u )
{ temp = Q[node];
Q[node] = qu; HT[qu] = node;
Q[u] = temp; HT[temp] = u;
}
else
{ break; }
}
return first;
}
/**
* @function lowerKeyOpenSet
*/
void Dijkstra3D::lowerKeyOpenSet( int ID )
{
int n;
int node; int parent;
int temp;
//-- Find your guy
n = HT[ID];
//-- If it happens to be the first element
if( n == 0 )
{ return; } //-- HT[ID] = 0, the same
//-- If not, start on the bottom and go up
node = n;
int qp; int qn;
while( node != 0 )
{
//parent = floor( (node - 1)/2 );
parent = floor( (node - 1)/2 );
qp = Q[parent]; qn = Q[node];
// Always try to put new nodes up
if( V[ qp ].dist > V[ qn ].dist )
{
temp = qp;
Q[parent] = qn; HT[qn] = parent;
Q[node] = temp; HT[temp] = node;
node = parent;
}
else
{ break; }
}
}
/**
* @function neighbors
*/
std::vector<int> Dijkstra3D::neighbors( int ID )
{
std::vector<int> Ng;
int idx = V[ID].x;
int idy = V[ID].y;
int idz = V[ID].z;
int nx; int ny; int nz;
for( int i = 0; i < 26; i++ )
{
nx = idx + mNX[i];
ny = idy + mNY[i];
nz = idz + mNZ[i];
if( nx < 0 || nx > mDimX -1 || ny < 0 || ny > mDimY -1 || nz < 0 || nz > mDimZ -1 )
{ continue; }
int nID = ref(nx,ny,nz);
if( V[ nID ].color == 0 || grid->getCell(nx,ny,nz) == 1 || V[ nID ].color == 3 )
{ continue; }
else
{ Ng.push_back( nID ); }
}
return Ng;
}
/**
* @function edgeCost
*/
float Dijkstra3D::edgeCost( int ID1, int ID2 )
{
float cost;
int diff = abs( V[ID1].x - V[ID2].x ) + abs( V[ID1].y - V[ID2].y ) + abs( V[ID1].z - V[ID2].z );
if( diff == 1 )
{ cost = 1*mBaseCost; }
else if( diff == 2 )
{ cost = smSqr2*mBaseCost; }
else if( diff == 3 )
{ cost = smSqr3*mBaseCost; }
else
{ printf("This case is not possible in this configuration, you moron! \n");}
return cost;
}
/**
* @function getPath
*/
std::vector<Eigen::Vector3i> Dijkstra3D::getPath( int x, int y, int z )
{
return getPath( ref(x,y,z) );
}
/**
* @function getPath
*/
std::vector<Eigen::Vector3i> Dijkstra3D::getPath( int ID )
{
std::vector<Eigen::Vector3i> path;
while( V[ID].parent > 0 )
{
path.push_back( Eigen::Vector3i(V[ID].x, V[ID].y, V[ID].z ) );
ID = V[ID].parent;
}
path.push_back( Eigen::Vector3i(V[ID].x, V[ID].y, V[ID].z ) );
return path;
}
| true |
cdc07697f432b12c4c1e32a91b7cb6ea5b0378ed | C++ | aag-github/mastermind | /src/controllers/client/MainMenuController.h | UTF-8 | 2,899 | 2.546875 | 3 | [] | no_license | #ifndef SRC_CONTROLLERS_MENUCONTROLLER_H_
#define SRC_CONTROLLERS_MENUCONTROLLER_H_
#include <assert.h>
#include "CombinationController.h"
#include "CommonMenuController.h"
#include "ReadCombinationController.h"
#include "QuitController.h"
#include "RestartController.h"
#include "LoadGameController.h"
#include "SaveGameController.h"
#include "UndoController.h"
#include "RedoController.h"
namespace Mastermind {
class MainMenuController: public ClientOperationController,
public CommonMenuController,
public UndoController,
public RedoController,
public RestartController,
public SaveGameController,
public ReadCombinationController
{
public:
MainMenuController(Game &game) :
ClientOperationController(game),
CommonMenuController(game),
readCombinationController(game),
restartController(game),
saveGameController(game),
undoController(game),
redoController(game)
{
}
virtual ~MainMenuController(){
}
virtual void accept(ClientOperationControllerVisitor *operationControllerVisitor) override final
{
assert(operationControllerVisitor != nullptr);
operationControllerVisitor->visit(this);
};
virtual void undo() override final {
undoController.undo();
}
virtual bool canUndo() override final {
return undoController.canUndo();
}
virtual void redo() override final {
redoController.redo();
}
virtual bool canRedo() override final {
return redoController.canRedo();
}
virtual void restart() override final {
restartController.restart();
}
virtual GamePersistenceResult save(std::string name) override final {
return saveGameController.save(name);
}
virtual std::vector<std::string> getAvailableGames() override final {
return saveGameController.getAvailableGames();
}
virtual void gameEnd(bool end) override final {
readCombinationController.gameEnd(end);
}
virtual ProposedCombinationState setProposedCombination (const Combination& proposedCombination) override final {
return readCombinationController.setProposedCombination(proposedCombination);
}
virtual const ProposedCombinationList& getProposedCombinations() const {
return readCombinationController.getProposedCombinations();
}
virtual const SecretCombination& getSecretCombination() const {
return readCombinationController.getSecretCombination();
}
private:
ReadCombinationControllerImpl readCombinationController;
RestartControllerImpl restartController;
SaveGameControllerImpl saveGameController;
UndoControllerImpl undoController;
RedoControllerImpl redoController;
};
}
#endif
| true |
b48b3e018eafdb08145a18793b5d3840fac951a0 | C++ | rishilss99/InterviewBit | /Problems/pascal_triangle.cpp | UTF-8 | 521 | 3.109375 | 3 | [] | no_license | void add_elements(vector<vector<int>> &result){
vector<int> arr;
for(int i = 0;i<result.back().size();i++){
if(i==0)
arr.push_back(1);
else
arr.push_back(result.back()[i-1] + result.back()[i]);
}
arr.push_back(1);
result.push_back(arr);
}
vector<vector<int> > Solution::solve(int A) {
vector<vector<int>> result;
if(A == 0)
return result;
result.push_back({1});
for(int i = 1;i<A;i++)
add_elements(result);
return result;
}
| true |
274f9c53d184ab954d11bdebb0e2c5a32f912912 | C++ | ketansahu07/Interview | /Graph/word ladder.cpp | UTF-8 | 2,755 | 3.6875 | 4 | [] | no_license | /*
Given a dictionary, and two words ‘start’ and ‘target’ (both of same length).
Find length of the smallest chain from ‘start’ to ‘target’ if it exists, such that
adjacent words in the chain only differ by one character and each word in the chain
is a valid word i.e., it exists in the dictionary.
It may be assumed that the ‘target’ word exists in dictionary and length of all dictionary words is same.
Time Complexity: O(N*M), where M is total number of entries in the dictionary
and N is the length of the word.
*/
int shortestChainLen(
string start, string target,
set<string>& D)
{
if(start == target)
return 0;
// If the target string is not
// present in the dictionary
if (D.find(target) == D.end())
return 0;
// To store the current chain length
// and the length of the words
int level = 0, wordlength = start.size();
// Push the starting word into the queue
queue<string> Q;
Q.push(start);
// While the queue is non-empty
while (!Q.empty()) {
// Increment the chain length
++level;
// Current size of the queue
int sizeofQ = Q.size();
// Since the queue is being updated while
// it is being traversed so only the
// elements which were already present
// in the queue before the start of this
// loop will be traversed for now
for (int i = 0; i < sizeofQ; ++i) {
// Remove the first word from the queue
string word = Q.front();
Q.pop();
// For every character of the word
for (int pos = 0; pos < wordlength; ++pos) {
// Retain the original character
// at the current position
char orig_char = word[pos];
// Replace the current character with
// every possible lowercase alphabet
for (char c = 'a'; c <= 'z'; ++c) {
word[pos] = c;
// If the new word is equal
// to the target word
if (word == target)
return level + 1;
// Remove the word from the set
// if it is found in it
if (D.find(word) == D.end())
continue;
D.erase(word);
// And push the newly generated word
// which will be a part of the chain
Q.push(word);
}
// Restore the original character
// at the current position
word[pos] = orig_char;
}
}
}
return 0;
} | true |
b1e57e82158a882df82666d905b3e9a656c8ea95 | C++ | Gouga34/TERM1_Poker | /Application/src/Profiling/CalculateProfilingData.cpp | UTF-8 | 6,906 | 2.8125 | 3 | [] | no_license | /*========================================================================
Nom: CalculDonneesProfilage.h Auteur: Morgane Vidal
Maj: 25/03/2015 Creation: 25/03/2015
Projet: Profilage par essais et erreurs au poker
--------------------------------------------------------------------------
Specification: Fichier contenant les définitions de
la classe CalculDonneesProfilage.
=========================================================================*/
#include "../../include/Profiling/CalculateProfilingData.h"
#include "../../include/Constants.h"
#include "../../include/MathematicalFormula/MathematicalFormula.h"
#include <cmath>
namespace profiling {
double CalculateProfilingData::calculateTheoreticalBet(const double maxGain, const double minGain, const double winningChances, const double minTheoreticalBet, const double maxTheoreticalBet) {
double dividend=(maxGain-minGain);
if (dividend != 0) {
double theoreticalBet = mathematicalformula::MathematicalFormula::calculateProportionalValue(minGain, winningChances, maxGain, minTheoreticalBet, maxTheoreticalBet);
return theoreticalBet;
}
else {
return -1;
}
}
double CalculateProfilingData::theoreticalBet(const double winningChances) {
//Variable qui contiendront les données des paliers :
double minGain, maxGain, minTheoreticalBet, maxTheoreticalBet;
//On regarde si le pourcentage de chances de gain est dans le premier palier :
if(winningChances >= RATIONALITY::PALIER1::DEBUT_GAIN
&& winningChances <= RATIONALITY::PALIER1::FIN_GAIN) {
minGain = RATIONALITY::PALIER1::DEBUT_GAIN;
maxGain = RATIONALITY::PALIER1::FIN_GAIN;
minTheoreticalBet = RATIONALITY::PALIER1::DEBUT_MISE_THEORIQUE;
maxTheoreticalBet = RATIONALITY::PALIER1::FIN_MISE_THEORIQUE;
}
//chancesGains palier 2
else if(winningChances > RATIONALITY::PALIER1::FIN_GAIN
&& winningChances <= RATIONALITY::PALIER2::FIN_GAIN) {
minGain = RATIONALITY::PALIER2::DEBUT_GAIN;
maxGain = RATIONALITY::PALIER2::FIN_GAIN;
minTheoreticalBet = RATIONALITY::PALIER2::DEBUT_MISE_THEORIQUE;
maxTheoreticalBet = RATIONALITY::PALIER2::FIN_MISE_THEORIQUE;
}
//chancesGains palier 3
else if(winningChances > RATIONALITY::PALIER2::FIN_GAIN
&& winningChances <= RATIONALITY::PALIER3::FIN_GAIN) {
minGain = RATIONALITY::PALIER3::DEBUT_GAIN;
maxGain = RATIONALITY::PALIER3::FIN_GAIN;
minTheoreticalBet = RATIONALITY::PALIER3::DEBUT_MISE_THEORIQUE;
maxTheoreticalBet = RATIONALITY::PALIER3::FIN_MISE_THEORIQUE;
}
//chancesGains palier 4
else if(winningChances > RATIONALITY::PALIER3::FIN_GAIN
&& winningChances <= RATIONALITY::PALIER4::FIN_GAIN) {
minGain = RATIONALITY::PALIER4::DEBUT_GAIN;
maxGain = RATIONALITY::PALIER4::FIN_GAIN;
minTheoreticalBet = RATIONALITY::PALIER4::DEBUT_MISE_THEORIQUE;
maxTheoreticalBet = RATIONALITY::PALIER4::FIN_MISE_THEORIQUE;
}
return CalculateProfilingData::calculateTheoreticalBet(maxGain, minGain, winningChances, minTheoreticalBet, maxTheoreticalBet);
}
double CalculateProfilingData::rationality(const double winningChances, const double totalBets) {
double thereoticalBet = theoreticalBet(winningChances);
if (thereoticalBet != 0) {
return 100 - abs(thereoticalBet - totalBets);
}
else {
return -1;
}
}
double CalculateProfilingData::calculateAggressiveness(const double betsRatio, const double rateBets, const double ratioHighestBet,
const double highestBet, const double maxAggressiveness, const double totalBets) {
double x = betsRatio * rateBets + ratioHighestBet * highestBet;
double y = x * ((maxAggressiveness - totalBets) / 100.0);
double agressiveness = totalBets + y;
return agressiveness;
}
double CalculateProfilingData::aggressiveness(const double highestBet, const double rateBets, const double totalBets) {
double maxAggressiveness;
double betsRatio, ratioHighestBet;
//miseLaPlusHaute dans PALIER1 ?
if (totalBets >= AGGRESSIVENESS::PALIER1::DEBUT_MISE_TOTALE
&& totalBets <= AGGRESSIVENESS::PALIER1::FIN_MISE_TOTALE) {
maxAggressiveness = AGGRESSIVENESS::PALIER1::FIN_AG_THEORIQUE;
betsRatio = static_cast<double>(AGGRESSIVENESS::PALIER1::RATIO_NB_MISES_DIVISE) / AGGRESSIVENESS::PALIER1::RATIO_NB_MISES_DIVISEUR;
ratioHighestBet = static_cast<double>(AGGRESSIVENESS::PALIER1::RATIO_MPH_DIVISE) / AGGRESSIVENESS::PALIER1::RATIO_MPH_DIVISEUR;
}
//miseLaPlusHaute dans PALIER2 ?
else if(totalBets > AGGRESSIVENESS::PALIER1::FIN_MISE_TOTALE
&& totalBets <= AGGRESSIVENESS::PALIER2::FIN_MISE_TOTALE) {
maxAggressiveness = AGGRESSIVENESS::PALIER2::FIN_AG_THEORIQUE;
betsRatio = static_cast<double>(AGGRESSIVENESS::PALIER2::RATIO_NB_MISES_DIVISE) / AGGRESSIVENESS::PALIER2::RATIO_NB_MISES_DIVISEUR;
ratioHighestBet = static_cast<double>(AGGRESSIVENESS::PALIER2::RATIO_MPH_DIVISE) / AGGRESSIVENESS::PALIER2::RATIO_MPH_DIVISEUR;
}
//miseLaPlusHaute dans PALIER3 ?
else if(totalBets > AGGRESSIVENESS::PALIER2::FIN_MISE_TOTALE
&& totalBets < AGGRESSIVENESS::PALIER3::FIN_MISE_TOTALE) {
maxAggressiveness = AGGRESSIVENESS::PALIER3::FIN_AG_THEORIQUE;
betsRatio = static_cast<double>(AGGRESSIVENESS::PALIER3::RATIO_NB_MISES_DIVISE) / AGGRESSIVENESS::PALIER3::RATIO_NB_MISES_DIVISEUR;
ratioHighestBet = static_cast<double>(AGGRESSIVENESS::PALIER3::RATIO_MPH_DIVISE) / AGGRESSIVENESS::PALIER3::RATIO_MPH_DIVISEUR;
}
//tapis
else {
return 100.0;
}
return CalculateProfilingData::calculateAggressiveness(betsRatio, rateBets, ratioHighestBet,
highestBet, maxAggressiveness, totalBets);
}
double CalculateProfilingData::bluff(const double rationality) {
return (100.0 - rationality);
}
double CalculateProfilingData::passivity(const double rateCall, const double rateChecks) {
return (rateChecks + rateCall);
}
double CalculateProfilingData::taux(const double valeur, const double valeurReference) {
if (valeurReference == 0) {
return -1;
}
else {
return ((valeur * 100.0) / valeurReference);
}
}
}
| true |
63add5e1d5926705fbf50716869902d818d98568 | C++ | kwmoore81/MathLibrary | /Math Library/vec3.cpp | UTF-8 | 4,329 | 3.109375 | 3 | [] | no_license | #include "vec3.h"
using namespace kml;
vec3 kml::reflect(const vec3 & incident, const vec3 & normal)
{
vec3 reflection;
reflection.x = incident.x - 2 * (incident.x * normal.x) * normal.x;
reflection.y = incident.y - 2 * (incident.y * normal.y) * normal.y;
reflection.z = incident.z - 2 * (incident.z * normal.z) * normal.z;
return reflection;
}
vec3 vec3::normal() const
{
return *this / magnitude();
}
vec3 kml::CrossProduct(float *a, float *b)
{
vec3 product;
product.x = (a[1] * b[2]) - (a[2] * b[1]);
product.y = (a[2] * b[0]) - (a[0] * b[2]);
product.z = (a[0] * b[1]) - (a[1] * b[0]);
product.normalize();
return product;
}
inline vec3 vec3::perp() const
{
vec3 perpVec3;
//check on this
perpVec3.x = -y;
perpVec3.y = x;
return perpVec3;
}
//vec3 kml::perp(vec3 & a)
//{
// return vec3({ -a.y, a.x, a.z});
//}
inline void vec3::normalize()
{
x = x / magnitude();
y = y / magnitude();
z = z / magnitude();
}
//inline vec3 vec3::operator-() const
//{
// vec3 negVec3;
//
// negVec3.x = -x;
// negVec3.y = -y;
// negVec3.z = -z;
//
// return negVec3;
//}
float kml::dot(const vec3 & lhs, const vec3 & rhs)
{
//return lhs.x * rhs.x + rhs.y * lhs.y + rhs.z * lhs.z;
float xval = lhs.x * rhs.x;
float yval = lhs.y * rhs.y;
float zval = lhs.z * rhs.z;
return xval + yval + zval;
}
vec3 kml::operator+(const vec3 & lhs, const vec3 & rhs)
{
vec3 plusVec3;
plusVec3.x = lhs.x + rhs.x;
plusVec3.y = lhs.y + rhs.y;
plusVec3.z = lhs.z + rhs.z;
return plusVec3;
}
vec3 kml::operator+=(const vec3 & lhs, const vec3 & rhs)
{
vec3 plEqVec3;
plEqVec3.x = lhs.x + rhs.x;
plEqVec3.y = lhs.y + rhs.y;
plEqVec3.z = lhs.z + rhs.z;
return plEqVec3;
}
vec3 kml::operator-(const vec3 & lhs, const vec3 & rhs)
{
/*vec3 minusVec3;
minusVec3.x = lhs.x - rhs.x;
minusVec3.y = lhs.y - rhs.y;
minusVec3.z = lhs.z - rhs.z;*/
return vec3(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z);
}
vec3 kml::operator-=(const vec3 & lhs, const vec3 & rhs)
{
vec3 minusVec3;
minusVec3.x = lhs.x - rhs.x;
minusVec3.y = lhs.y - rhs.y;
minusVec3.z = lhs.z - rhs.z;
return minusVec3;
}
vec3 kml::operator*(const vec3 & lhs, float rhs)
{
return{ lhs.x * rhs, lhs.y * rhs, lhs.z * rhs };
}
vec3 kml::operator*=(const vec3 & lhs, float rhs)
{
/*vec3 multVec3;
multVec3.x = lhs.x * rhs;
multVec3.y = lhs.y * rhs;
multVec3.z = lhs.z * rhs;
return multVec3;*/
return{ lhs.x * rhs, lhs.y * rhs, lhs.z * rhs };
}
vec3 kml::operator/(const vec3 & lhs, float rhs)
{
return vec3(lhs.x / rhs, lhs.y / rhs, lhs.z / rhs);
}
vec3 kml::operator/=(const vec3 & lhs, float rhs)
{
/*vec3 divVec3;
divVec3.x = lhs.x / rhs;
divVec3.y = lhs.y / rhs;
divVec3.z = lhs.z / rhs;
return divVec3;*/
return vec3(lhs.x / rhs, lhs.y / rhs, lhs.z / rhs);
}
inline bool kml::operator==(const vec3 & lhs, const vec3 & rhs)
{
/*if (fabs(lhs.x - rhs.x < FLT_EPSILON) && fabs(lhs.y - rhs.y < FLT_EPSILON) && fabs(lhs.z - rhs.z < FLT_EPSILON)) { return true; }
else { return false; }*/
return rhs.x - FLT_EPSILON < lhs.x && lhs.x < rhs.x + FLT_EPSILON &&
rhs.y - FLT_EPSILON < lhs.y && lhs.y < rhs.y + FLT_EPSILON &&
rhs.z - FLT_EPSILON < lhs.z && lhs.z < rhs.z + FLT_EPSILON;
}
bool kml::operator!=(const vec3 & lhs, const vec3 & rhs)
{
if (fabs(lhs.x - rhs.x < FLT_EPSILON) && fabs(lhs.y - rhs.y < FLT_EPSILON) && fabs(lhs.z - rhs.z < FLT_EPSILON)) { return false; }
else { return true; }
}
bool kml::operator<(const vec3 & lhs, const vec3 & rhs)
{
if (fabs(lhs.x < (rhs.x - FLT_EPSILON)) && fabs(lhs.y < (rhs.y - FLT_EPSILON)) && fabs(lhs.z < (rhs.z - FLT_EPSILON))) { return true; }
else { return false; }
}
bool kml::operator<=(const vec3 & lhs, const vec3 & rhs)
{
if (fabs(lhs.x <= (rhs.x - FLT_EPSILON)) && fabs(lhs.y <= (rhs.y - FLT_EPSILON)) && fabs(lhs.z <= (rhs.z - FLT_EPSILON))) { return true; }
else { return false; }
}
bool kml::operator>(const vec3 & lhs, const vec3 & rhs)
{
if (fabs(lhs.x > (rhs.x + FLT_EPSILON)) && fabs(lhs.y > (rhs.y + FLT_EPSILON)) && fabs(lhs.z > (rhs.z + FLT_EPSILON))) { return true; }
else { return false; }
}
bool kml::operator>=(const vec3 & lhs, const vec3 & rhs)
{
if (fabs(lhs.x >= (rhs.x + FLT_EPSILON)) && fabs(lhs.y >= (rhs.y + FLT_EPSILON)) && fabs(lhs.z >= (rhs.z + FLT_EPSILON))) { return true; }
else { return false; }
}
| true |
d56dc34fae0d9acfa1bfbdf9caae113dfbaf63b8 | C++ | hamburgerBear/simple-udp-protocol | /sender/main.cpp | UTF-8 | 387 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <unistd.h>
#include "CUdpCommunication.h"
int main()
{
CUdpCommunication udp_sender;
udp_sender.configSender();
while(1)
{
static float x = 1.0;
static float y = 1.2;
// udp_sender.send(100.0, 200.0);
udp_sender.send(x, y);
std::cout << "send udp message" << std::endl;
x = x + 0.1;
y = y + 0.1;
usleep(100 * 1000);
}
return 0;
} | true |
cf868293c57a6dd713afa32b2fe0acb2676e9da7 | C++ | robo8080/ESP32_IchigoLatte_Telnet | /ESP32_IchigoLatte_Telnet/ESP32_IchigoLatte_Telnet.ino | UTF-8 | 17,021 | 2.734375 | 3 | [
"MIT",
"CC-BY-4.0"
] | permissive | //#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <QueueArray.h>
HardwareSerial Serial1(2);
//rxPin = 16
//txPin = 17
// create a queue of characters.
QueueArray <char> queue;
const char* ssid = "******************";
const char* password = "******************";
WiFiServer server(10001);
WiFiClient serverClient;
//#define LED 23
#define LED 25
uint8_t cmd[6] = {255,251,3,255,253,3}; // suppress go-ahead
void serverSetup() {
pinMode(LED, OUTPUT);
digitalWrite(LED, LOW); // turn the LED off by making the voltage LOW
WiFi.begin(ssid, password);
Serial.print("\nConnecting to "); Serial.println(ssid);
uint8_t i = 0;
while (WiFi.status() != WL_CONNECTED && i++ < 20) {
Serial.print(".");
delay(500);
}
if (i == 21) {
Serial.print("Could not connect to"); Serial.println(ssid);
while (1) delay(500);
} else {
digitalWrite(LED, HIGH); // turn the LED on (HIGH is the voltage level)
}
server.begin();
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial1.begin(115200);
serverSetup();
delay(2000);
}
void serial2client(int select) {
// read from port 1, send to Client:
while(Serial1.available()){
size_t len = Serial1.available();
uint8_t sbuf[len];
Serial1.readBytes(sbuf, len);
// serverClient.write(sbuf, len);
for (int i = 0 ; i < len;i++) {
if(sbuf[i] == 0x0a) {
serverClient.print("\r\n");
} else {
serverClient.write(sbuf[i]);
}
}
if(select != 0) {
for (int i= 0 ; i< len ;i++) {
MJ_Command((char)sbuf[i]);
}
} else {
for (int i= 0 ; i< len ;i++) {
queue.enqueue ((char)sbuf[i]);
}
}
}
}
void loop() {
// put your main code here, to run repeatedly:
while (1) {
Serial.print("\nReady! Use 'telnet ");
Serial.print(WiFi.localIP());
Serial.println(" 10001' to connect");
digitalWrite(LED, LOW); // turn the LED off by making the voltage LOW
// wait for a new client:
while (1) {
serverClient = server.available();
if (serverClient) break;
digitalWrite(LED, HIGH); // turn the LED on (HIGH is the voltage level)
delay(500); // wait for a second
digitalWrite(LED, LOW); // turn the LED off by making the voltage LOW
delay(500); // wait for a second
}
Serial.println("Client Connected");
digitalWrite(LED, HIGH); // turn the LED on (HIGH is the voltage level)
delay(10);
serverClient.write(&cmd[0],6); // suppress go-ahead
delay(500);
// serverClient.print("\r\n");
while (serverClient.connected()) {
while(serverClient.available())
{
size_t len = serverClient.available();
uint8_t sbuf[len];
serverClient.read(sbuf, len);
// serverClient.write(sbuf, len); //Local echo
for (int i = 0 ; i < len;i++) {
if(sbuf[i] == 0x0d) {
serverClient.print("\r\n");
} else if(sbuf[i] == 0x08) {
serverClient.print("\b \b");
} else if(sbuf[i] != 0x0a)
serverClient.write(sbuf[i]);
}
for (int i = 0 ; i < len;i++) {
if(sbuf[i] == 0x0d)
Serial1.write(0x0a);
else if(sbuf[i] != 0x0a)
Serial1.write(sbuf[i]);
}
}
serial2client(1);
while (!queue.isEmpty ()) {
MJ_Command(queue.dequeue ());
}
} //ループの末尾
if (serverClient) serverClient.stop();
Serial.println("\nClient Disconnected");
} //無限ループの末尾
}
//------------------------------------------------------------------------------
/*
* MicJack by Michio Ono.
* IoT interface module for IchigoJam with ESP-WROOM-02
* CC BY
*/
// modified by robo8080
const String MicJackVer="MicJack-0.8.0";
const String MJVer="MixJuice-1.2.0";
String inStr = ""; // a string to hold incoming data
boolean stringComplete = false; // whether the string is complete
int httpPort = 80;
int posttype;
boolean postmode=false;
enum { HTML_GET, HTML_GETS,
HTML_POST, HTML_POSTS };
String postaddr="";
String postdata="";
String myPostContentType="";
#define kspw 20
#define kspn 30
int spw=kspw;
int spn=kspn;
/*** Use access Status LED ***/
//#define useMJLED
#ifdef useMJLED
const int connLED=12; //Green
const int postLED=4; //Yellow
const int getLED=5; //Red
#endif
String homepage="mj.micutil.com";
String lastGET=homepage;
/***************************************
* Reset POST parameters
* POST用パラメータをリセット
*
***************************************/
void ResetPostParam() {
postmode=false;
postaddr="";
postdata="";
}
void SetPCT(String s) {
int n=s.length();
if(n<=0) {
myPostContentType="";
} else {
//Content-Type: application/x-www-form-urlencoded;\r\n
myPostContentType="Content-Type: "+s+"\r\n";
}
}
void MJ_Command(char inChar) {
// while (Serial11.available()) {
// // get the new byte:
// char inChar = (char)Serial1.read();
Serial.write(inChar);
//Check end of line
if(inChar=='\n' || inChar=='\r') {
stringComplete = true;
inStr.replace("lash>","");
// if(!postmode) Serial1.flush(); //読み飛ばし "OK"など
// break;
} else {
inStr += inChar;
}
// }
if(stringComplete) { //データあり
stringComplete=false;
String cs=inStr;//文字をコピー
cs.toUpperCase();//大文字に
if(postmode) {
/**** POSTモード 処理 ****/
if(cs.startsWith("MJ POST END")) {
/* POST通信開始 */
MJ_HTML(posttype,postaddr);
ResetPostParam();
} else if(cs.startsWith("MJ POSTS END")) {
/* POST通信開始 */
MJ_HTMLS(posttype,postaddr);
ResetPostParam();
} else if(cs.startsWith("MJ POST CANCEL") || cs.startsWith("MJ POSTS CANCEL") ||
cs.startsWith("MJ POST STOP") || cs.startsWith("MJ POSTS STOP") ||
cs.startsWith("MJ POST ESC") || cs.startsWith("MJ POSTS ESC")) {
/*POST/POSTSデータリセット*/
ResetPostParam();
} else {
/* POSTコンテンツを記録 */
if(inStr.endsWith("\n")) inStr=inStr.substring(0,inStr.length()-1);//最後の"\n"を外す
postdata+=inStr;
postdata+="\n";
}
} else if(cs.startsWith("MJ GET ")) {
/*** GET通信 ****/
MJ_HTML(HTML_GET,inStr.substring(7));
} else if(cs.startsWith("MJ GETS ")) {
/**** HTMLS GET通信 ****/
MJ_HTMLS(HTML_GETS,inStr.substring(8));
// } else if(cs.startsWith("MJ FUJI")) {
// /*** FUJI ***/ MJ_HTMLS(HTML_GETS,"raw.githubusercontent.com/bokunimowakaru/petit15term/master/fuji.txt");
} else if(cs.startsWith("MJ POST START ")) {
/*** POST START通信 ***/
MJ_POST_START(HTML_POST,inStr.substring(14));
} else if(cs.startsWith("MJ POSTS START ")) {
/*** HTMLS POST通信 ***/
MJ_POST_START(HTML_POSTS,inStr.substring(15));
} else if(cs.startsWith("MJ PCT ")) {
/*** PCT ***/ SetPCT(inStr.substring(7));
} else if(cs.startsWith("MJ MJVER")) {
/*** バージョン ***/ Serial1.println("'"+MicJackVer);
serverClient.println(MicJackVer);
// IJCodeSendString(WS_num, "'"+MicJackVer);
// IJCodeSend(WS_num, 0x0a);
// Verで、エラー表示で、MixJuiceのバージョンを表示
// MJVerで、MicJackのバージョンを表示
} else if(cs.startsWith("MJ ")) {
/*** NG ***/ Serial1.println("'NG: "+MJVer);
serverClient.println("NG: "+MJVer);
// IJCodeSendString(WS_num, "'NG: "+MJVer);
// IJCodeSend(WS_num, 0x0a);
}
inStr="";
}
}
/***************************************
* MJ GET / POST
* HTTP GET/POST 通信
*
***************************************/
void MJ_HTML(int type, String addr) {
int sc=addr.length();
if(sc<=0) return;
String host="";
String url="/";
String prm="";
int ps;
ps=addr.indexOf("/");
if(ps<0) {
host=addr;
} else {
host=addr.substring(0,ps); // /より前
url=addr.substring(ps); // /を含んで後ろ
}
//Serial1.println("'"+host);
//Serial1.println("'"+url);
//------プロキシ-----
String httpServer=host;
// if(useProxy) httpServer=httpProxy;
//------ポート-----
int port=httpPort;
ps=host.indexOf(":");
if(ps>0) {
host=host.substring(0,ps); // :より前
port=host.substring(ps+1).toInt(); // :より後ろ
}
//------せつぞく-----
WiFiClient client;
if(!client.connect(httpServer.c_str(), port)) {
Serial1.write(0x04);
return;
}
//------リクエスト-----
switch(type) {
case HTML_GET:
case HTML_GETS:
#ifdef useMJLED
digitalWrite(getLED, HIGH);
#endif
client.print(String("GET ") + url + " HTTP/1.0\r\n" +
"Host: " + host + "\r\n" +
"User-Agent: " + MJVer + "\r\n" +
//"Connection: close\r\n" +
"\r\n");
//"Accept: */*\r\n" +
break;
case HTML_POST:
case HTML_POSTS:
#ifdef useMJLED
digitalWrite(postLED, HIGH);
#endif
prm=postdata;//postdata.replace("\n","\r\n");//改行を置き換え
client.print(String("POST ") + url + " HTTP/1.0\r\n" +
"Accept: */*\r\n" +
"Host: " + host + "\r\n" +
"User-Agent: " + MJVer + "\r\n" +
//"Connection: close\r\n" +
myPostContentType +
"Content-Length: " + String(prm.length()) + "\r\n" +
"\r\n" +
prm);
//"Content-Type: application/x-www-form-urlencoded;\r\n" +
break;
default:
return;
}
//------待ち-----
int64_t timeout = millis() + 5000;
while (client.available() == 0) {
if (timeout - millis() < 0) {
Serial1.println("'Client Timeout !");
serverClient.println("Client Timeout !");
client.stop();
Serial1.write(0x04);
return;
}
}
//------レスポンス-----
switch(type) {
case HTML_GET:
case HTML_GETS:
/* ヘッダー 読み飛ばし */
while(client.available()){
String line = client.readStringUntil('\n');
if(line.length()<2) break;
}
/*
* プログラム入力時は、改行後、50msくらい,
* 文字は、20msはあけないと、
* IchigoJamは処理できない
*/
if(spw<=1) {
while(client.available()){
String line = client.readStringUntil('\n');
Serial1.print(line);
Serial1.print('\n');
serverClient.print(line);
serverClient.print("\r\n");
delay(spn);
}
} else {
while(client.available()){
char c = client.read();
switch(c){
case 0:
break;
case '\r':
break;
case '\n':
Serial1.print('\n');
// IJCodeSend(WS_num, (uint8_t)'\n');
serverClient.print("\r\n");
delay(spn);
break;
default:
Serial1.print(c);
// IJCodeSend(WS_num, (uint8_t)c);
serverClient.print(c);
delay(spw);
break;
}
serial2client(0);
}
}
if(!addr.equals(homepage)) lastGET=addr;
#ifdef useMJLED
digitalWrite(getLED, LOW);
#endif
Serial1.write(0x04);
break;
case HTML_POST:
case HTML_POSTS:
Serial1.println("'POST OK!");
serverClient.println("POST OK!");
// IJCodeSendString(WS_num, "'POST OK!");
// IJCodeSend(WS_num, 0x0a);
#ifdef useMJLED
digitalWrite(postLED, LOW);
#endif
Serial1.write(0x04);
break;
default:
/* 読み飛ばし */
while(client.available()){
String line = client.readStringUntil('\r');
}
break;
}
}
/***************************************
* MJ GETS / POSTS
* HTTP GETS/POSTS 通信
*
***************************************/
void MJ_HTMLS(int type, String addr) {
int sc=addr.length();
if(sc<=0) return;
String host="";
String url="/";
String prm="";
int ps;
ps=addr.indexOf("/");
if(ps<0) {
host=addr;
} else {
host=addr.substring(0,ps); // /より前
url=addr.substring(ps); // /を含んで後ろ
}
//Serial1.println("'"+host);
//Serial1.println("'"+url);
//------プロキシ-----
String httpServer=host;
// if(useProxy) httpServer=httpProxy;
//------ポート-----
int port=httpPort;
ps=host.indexOf(":");
if(ps>0) {
host=host.substring(0,ps); // :より前
port=host.substring(ps+1).toInt(); // :より後ろ
}
switch(type) {
case HTML_GET:
case HTML_POST:
break;
case HTML_POSTS:
case HTML_GETS:
if(port==80) port=443;
break;
}
//------セキュアーなせつぞく-----
WiFiClientSecure client;
if(!client.connect(httpServer.c_str(), port)) {
Serial1.write(0x04);
return;
}
//------リクエスト-----
switch(type) {
case HTML_GET:
case HTML_GETS:
#ifdef useMJLED
digitalWrite(getLED, HIGH);
#endif
client.print(String("GET ") + url + " HTTP/1.0\r\n" +
"Host: " + host + "\r\n" +
"User-Agent: " + MJVer + "\r\n" +
// "Connection: close\r\n" +
"\r\n");
//"Accept: */*\r\n" +
break;
case HTML_POST:
case HTML_POSTS:
#ifdef useMJLED
digitalWrite(postLED, HIGH);
#endif
prm=postdata;//postdata.replace("\n","\r\n");//改行を置き換え
client.print(String("POST ") + url + " HTTP/1.0\r\n" +
"Accept: */*\r\n" +
"Host: " + host + "\r\n" +
"User-Agent: " + MJVer + "\r\n" +
//"Connection: close\r\n" +
myPostContentType +
"Content-Length: " + String(prm.length()) + "\r\n" +
"\r\n" +
prm);
//"Content-Type: application/x-www-form-urlencoded;\r\n" +
break;
default:
return;
}
//------待ち-----
int64_t timeout = millis() + 5000;
while (client.available() == 0) {
if (timeout - millis() < 0) {
Serial1.println("'Client Timeout !");
serverClient.println("Client Timeout !");
client.stop();
Serial1.write(0x04);
return;
}
}
//------レスポンス-----
switch(type) {
case HTML_GET:
case HTML_GETS:
/* ヘッダー 読み飛ばし */
while(client.available()){
String line = client.readStringUntil('\n');
if(line.length()<2) break;
}
/*
* プログラム入力時は、改行後、50msくらい,
* 文字は、20msはあけないと、
* IchigoJamは処理できない
*/
if(spw<=1) {
while(client.available()){
String line = client.readStringUntil('\n');
Serial1.print(line);
Serial1.print('\n');
serverClient.print(line);
serverClient.print("\r\n");
delay(spn);
}
} else {
while(client.available()){
char c = client.read();
switch(c){
case 0:
break;
case '\r':
break;
case '\n':
Serial1.print('\n');
serverClient.print("\r\n");
// IJCodeSend(WS_num, (uint8_t)'\n');
delay(spn);
break;
default:
Serial1.print(c);
serverClient.print(c);
// IJCodeSend(WS_num, (uint8_t)c);
delay(spw);
break;
}
serial2client(0);
}
}
if(!addr.equals(homepage)) lastGET=addr;
#ifdef useMJLED
digitalWrite(getLED, LOW);
#endif
Serial1.write(0x04);
break;
case HTML_POST:
case HTML_POSTS:
Serial1.println("'POST OK!");
serverClient.println("POST OK!");
// IJCodeSendString(WS_num,"'POST OK!");
// IJCodeSend(WS_num, 0x0a);
#ifdef useMJLED
digitalWrite(postLED, LOW);
#endif
Serial1.write(0x04);
break;
default:
/* 読み飛ばし */
while(client.available()){
String line = client.readStringUntil('\r');
}
break;
}
}
/***************************************
* MJ POST START addr
* POST/POSTS 開始
*
***************************************/
void MJ_POST_START(int type, String addr) {
int n=addr.length();
if(n>0) {
posttype=type;
postaddr=addr;
postdata="";
postmode=true;
}
}
| true |
e3ffc24afe7e664c73862c5b0758a5871215c912 | C++ | RobJenks/rj-engine | /RJ/ShipTileRequirement.h | UTF-8 | 1,230 | 2.921875 | 3 | [] | no_license | #pragma once
#ifndef __ShipTileRequirementH__
#define __ShipTileRequirementH__
class ComplexShipTileClass;
class ComplexShipTileDefinition;
class ShipTileRequirement
{
public:
// Requirement can be for a tile class and/or specific tile definition. We can also specify how many are required
ComplexShipTileClass * Class; // If not set, will be determined from definition anyway
ComplexShipTileDefinition * Definition; // Can be set to NULL to avoid this being a criteria (then we just look for tiles of the specified class)
int Level; // If not set, will default to zero (allowing any level of tile)
int Count; // Minimum number of this tile class/def required (or 0 will disable this requirement)
// Default constructor; will create a null requirement if no parameters are provided
ShipTileRequirement(void)
{
Class = NULL;
Definition = NULL;
Level = 0;
Count = 0;
}
// Main constructor; called with any supplied parameters, and derives any that should be defaulted when not specified
ShipTileRequirement(ComplexShipTileClass *_Class, ComplexShipTileDefinition *_Def, int _Level, int _Count);
// Default destructor
~ShipTileRequirement(void) { }
};
#endif
| true |
02390db793c6236361a60d54d8bcbaece9346086 | C++ | joel-perez/9515Algo2Juarez | /TP3/Arista.h | UTF-8 | 377 | 2.765625 | 3 | [] | no_license | #ifndef ARISTA_H
#define ARISTA_H_
#include <iostream>
class Vertice;
class Arista {
private:
Vertice* destino;
public:
//PRE: -
// POST: Arista con un destino fijado.
Arista(Vertice* destino);
//PRE: -
// POST: Devuelve el destino asociado a la arista.
Vertice* obtener_destino();
//PRE: -
// POST: Libera memoria.
~Arista();
};
#endif /* ARISTA_H_ */
| true |
ca55fea0c20ff282efe104562d29b48f48c4542f | C++ | MrMCG/MGL_old | /MGL/MGLMeshGenerator.cpp | UTF-8 | 2,176 | 2.796875 | 3 | [] | no_license | #include "stdafx.h"
#include "MGLMeshGenerator.h"
#include "MGLMesh.h"
MGLMesh* MGLMeshGenerator::Triangle() {
MGLMesh* mesh = new MGLMesh();
GLuint numVert = 3;
mesh->SetNumVertices(numVert);
MGLvecv3* m_vertices = new MGLvecv3(numVert);
MGLvecv2* m_texCoords = new MGLvecv2(numVert);
MGLvecv3* m_normals = new MGLvecv3(numVert);
MGLvecv4* m_colours = new MGLvecv4(numVert);
m_vertices->at(0) = glm::vec3(0.0f, 1.0f, 0.0f);
m_vertices->at(1) = glm::vec3(-1.0f, -1.0f, 0.0f);
m_vertices->at(2) = glm::vec3(1.0f, -1.0f, 0.0f);
m_texCoords->at(0) = glm::vec2(0.5f, 1.0f);
m_texCoords->at(1) = glm::vec2(0.0f, 0.0f);
m_texCoords->at(2) = glm::vec2(1.0f, 0.0f);
for (GLuint i = 0; i < numVert; ++i) {
m_normals->at(i) = glm::vec3(0.0f, 0.0f, 1.0f);
m_colours->at(i) = glm::vec4(1.0f, 1.0f, 1.0f, 1.0f);
}
mesh->SetVertices(m_vertices);
mesh->SetTexCoords(m_texCoords);
mesh->SetNormals(m_normals);
mesh->SetColours(m_colours);
mesh->BufferAllData();
return mesh;
}
MGLMesh* MGLMeshGenerator::Quad() {
MGLMesh* mesh = new MGLMesh();
GLuint numVert = 4;
GLuint numInd = 6;
mesh->SetNumVertices(numVert);
mesh->SetNumIndices(numInd);
MGLvecv3* m_vertices = new MGLvecv3(numVert);
MGLvecv2* m_texCoords = new MGLvecv2(numVert);
MGLvecv3* m_normals = new MGLvecv3(numVert);
MGLvecv4* m_colours = new MGLvecv4(numVert);
std::vector<GLuint>* m_indices = new std::vector < GLuint >{ 2, 1, 3, 1, 0, 3 };
m_vertices->at(0) = glm::vec3(-1.0f, -1.0f, 0.0f);
m_vertices->at(1) = glm::vec3(-1.0f, 1.0f, 0.0f);
m_vertices->at(2) = glm::vec3(1.0f, 1.0f, 0.0f);
m_vertices->at(3) = glm::vec3(1.0f, -1.0f, 0.0f);
m_texCoords->at(0) = glm::vec2(0.0f, 0.0f);
m_texCoords->at(1) = glm::vec2(0.0f, 1.0f);
m_texCoords->at(2) = glm::vec2(1.0f, 1.0f);
m_texCoords->at(3) = glm::vec2(1.0f, 0.0f);
for (GLuint i = 0; i < numVert; ++i) {
m_normals->at(i) = glm::vec3(0.0f, 0.0f, 1.0f);
m_colours->at(i) = glm::vec4(1.0f, 1.0f, 1.0f, 1.0f);
}
mesh->SetVertices(m_vertices);
mesh->SetTexCoords(m_texCoords);
mesh->SetNormals(m_normals);
mesh->SetColours(m_colours);
mesh->SetIndices(m_indices);
mesh->BufferAllData();
return mesh;
} | true |
93ee5fc511f7c5c3964069704c0a6e9f6ee75b07 | C++ | chinmaya00/lab6 | /lab6q5a.cpp | UTF-8 | 879 | 4.15625 | 4 | [] | no_license | #include<iostream>
using namespace std;
//write a program that includes sum, maximum and minimum
//finding sum
int func1(int a,int b){
int c=a+b;
return c;
}
//finding maximum
int func2(int a, int b){
if(a>b){
return a;
}
else
return b;
}
//finding minimum
int func3(int a, int b){
if(a<b){
return a;
}
else
return b;
}
//write a main function that asks the user to input 2 variables and what operation he wants to do and accordingly display the output
int main(){
int a,b,i;
cout<<"Enter 2 numbers: "<<endl;
cin>>a>>b;
cout<<"to find sum press 1"<<endl;
cout<<"to find maximum press 2"<<endl;
cout<<"to find minimum press 3"<<endl;
//output
cin>>i;
if(i==1)
{
cout<<"sum is:"<<func1(a,b)<<endl;
}
else if(i==2)
{
cout<<"maximum number is:"<<func2(a,b)<<endl;
}
else if(i==3)
{
cout<<"minimum number is:"<<func3(a,b)<<endl;
}
else
cout<<"invalid input";
return 0;
}
| true |
0b379c5c713b5cc9ad8b7f5869e85b6b7ca61e24 | C++ | gcjjyy/acmicpc | /2407.cpp | UTF-8 | 1,289 | 3.109375 | 3 | [
"MIT"
] | permissive | #include <stdio.h>
class BigInteger
{
public:
int length;
char buf[100];
BigInteger() {
length = 1;
for(int i = 0; i < 100; ++i) buf[i] = 0;
}
void put() {
for(int i = length - 1; i >= 0; --i) printf("%d", buf[i]);
printf("\n");
}
void set(unsigned long long value) {
length = 0;
while(value) {
buf[length++] = value % 10;
value /= 10;
}
}
void add(BigInteger &rhs) {
int upper = 0;
int i = 0;
int digit = 0;
while(i < this->length || i < rhs.length || upper) {
digit = this->buf[i] + rhs.buf[i] + upper;
if(digit >= 10) {
digit -= 10;
upper = 1;
}
else {
upper = 0;
}
this->buf[i] = digit;
i++;
if(i >= length) length = i;
}
}
};
int n, m;
BigInteger dp[101][101];
int main() {
scanf("%d%d", &n, &m);
for(int i = 0; i <= n; ++i) dp[i][0].set(1);
for(int i = 1; i <= n; ++i) {
for(int j = 1; j <= m; ++j) {
dp[i][j].add(dp[i-1][j-1]);
dp[i][j].add(dp[i-1][j]);
}
}
dp[n][m].put();
return 0;
}
| true |
01cfc414f3c468c1988e905f485c3eb06a88a2a3 | C++ | bratek20/Queue | /kolejka/main.cpp | UTF-8 | 1,305 | 3.46875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include "Queue.h"
using namespace std;
Queue factory() {
Queue q = Queue({ "elo", "r", "value", "rzadzi" },10);
return q;
}
int main() {
Queue* queue = new Queue(5);
string command;
while (true) {
try {
cin >> command;
if (command == "exit") {
break;
}
else if (command == "write") {
cout << "Queue contains: ";
for (auto& e : *queue) {
cout << e << " ";
}
cout << "\n";
}
else if (command == "size") {
cout << "Size: " << queue->size() << "\n";
}
else if (command == "push") {
Queue::Type x; cin >> x;
queue->push(x);
}
else if (command == "front") {
cout << "Front: " << queue->front() << "\n";
}
else if (command == "pop") {
cout << "Pop: " << queue->pop() << "\n";
}
else {
cout << "Command: " << command << " unknown :(\n";
}
}
catch (string error) {
cout << "Error: " << error << "\n";
}
}
return 0;
} | true |
e5c18f7e4950f88fccc7127164ecec8a7f596faa | C++ | mpearso3/Game-Engine-Tutorial | /Map.cc | UTF-8 | 515 | 3.046875 | 3 | [] | no_license | #include "Map.hpp"
#include "Game.hpp"
#include <fstream>
Map::Map()
{
}
Map::~Map()
{
}
void Map::load_map(std::string path, int size_x, int size_y)
{
char tile;
std::fstream map_file;
map_file.open(path);
{
for(int y = 0; y < size_y; y++)
{
for(int x = 0; x < size_x; x++)
{
map_file.get(tile);
std::cout << " tile " << atoi(&tile) << std::endl;
Game::add_tile(atoi(&tile), x * 32, y * 32);
map_file.ignore();
}
}
}
map_file.close();
}
| true |
710dcb8edfbcee5981fbb3e2ce1ccd87b982c896 | C++ | CStratton00/FantasyFightingGame | /NextMove.h | UTF-8 | 1,012 | 3.296875 | 3 | [] | no_license | //
// Created by Collin Stratton on 4/14/20.
//
#ifndef FANTASYFIGHTINGGAME_NEXTMOVE_H
#define FANTASYFIGHTINGGAME_NEXTMOVE_H
#include <string>
#include <vector>
#include "DirectionPair.h"
using namespace std;
class NextMove { // Class used store data about the description, location, and directions of a given player position
private:
string description;
vector <DirectionPair> newPos;
public:
NextMove(string e) {
description = e;
}
string GetDescription() {return description;}
vector<DirectionPair> GetDirectionPair() { // Returns the the vector DirectionPair
vector<DirectionPair> copy;
for (int i = 0; i < newPos.size(); i++) {copy.push_back(newPos[i]);}
return copy;
}
void ClearPair() {newPos.clear();}
void AddPair(char d, int p) { // Creates a new DirectionPair vector
DirectionPair dp(d, p);
newPos.push_back(dp);
}
void SetDescription(string d) {description = d;}
};
#endif //FANTASYFIGHTINGGAME_NEXTMOVE_H
| true |
c3f517a7a502c6f4d0c1d6c77236d8c868c97e17 | C++ | YadurajRao/Proof-Trapar-Pass | /libfaudes-2_29d/include/tp_attributes.h | UTF-8 | 7,501 | 2.625 | 3 | [] | no_license | /** @file tp_attributes.h Attributes for timed automata */
/* Timeplugin for FAU Discrete Event Systems Library (libfaudes)
Copyright (C) 2006 Berno Schlein
Copyright (C) 2007 Thomas Moor
Exclusive copyright is granted to Klaus Schmidt
*/
#ifndef FAUDES_TP_ATTRIBUTES_H
#define FAUDES_TP_ATTRIBUTES_H
#include "corefaudes.h"
#include "tp_timeconstraint.h"
namespace faudes {
/**
* Transition Attribute with guard and resets.
*
* @ingroup TimedPlugin
*/
class FAUDES_API AttributeTimedTrans : public AttributeFlags {
FAUDES_TYPE_DECLARATION(Void,AttributeTimedTrans,AttributeFlags)
public:
/** Constructor */
AttributeTimedTrans(void) : AttributeFlags() { mGuard.Name("Guard"); mResets.Name("Resets"); };
/**
* Test for default value (ie empty constraint and default flags)
*
* @return
* True for default value
*/
virtual bool IsDefault(void) const {return mGuard.Empty() && mResets.Empty() && AttributeFlags::IsDefault(); };
/** Guard */
TimeConstraint mGuard;
/** Resets */
ClockSet mResets;
protected:
/**
* Assignment method.
*
* @param rSrcAttr
* Source to assign from
*/
void DoAssign(const AttributeTimedTrans& rSrcAttr);
/**
* Test eaulity.
*
* @param rOther
* Other attribute to compare with.
*/
bool DoEqual(const AttributeTimedTrans& rOther) const;
/**
* Reads the attribute from TokenReader, see AttributeVoid for public wrappers.
*
* If the current token indicates a timing section, the method reads the guard and reset
* timing data from that section. Else it does nothing. Exceptions may only be thrown
* on invalid data within the timing section. The context argument is ignored, the
* label argument can be used to override the default section name Timing.
*
* @param rTr
* TokenReader to read from
* @param rLabel
* Section to read
* @param pContext
* Read context to provide contextual information
*
* @exception Exception
* - IO error (id 1)
*/
virtual void DoRead(TokenReader& rTr,const std::string& rLabel="", const Type* pContext=0);
/**
* Writes the attribute to TokenWriter, see AttributeVoid for public wrappers.
*
* Writes a Timing section to include data on the guard and resets. The label argument
* can be used to set a section label different the the default Timing.
* Th context argument is ignored.
*
* @param rTw
* TokenWriter to write to
* @param rLabel
* Section to write
* @param pContext
* Write context to provide contextual information
*
* @exception Exception
* - IO error (id 2)
*/
virtual void DoWrite(TokenWriter& rTw, const std::string& rLabel="", const Type* pContext=0) const;
}; // class AttributeTimedTrans
/**
*
* State attribute with invariant.
*
* @ingroup TimedPlugin
*
*/
class FAUDES_API AttributeTimedState : public AttributeFlags {
FAUDES_TYPE_DECLARATION(Void,AttributeTimedState,AttributeFlags)
public:
/** Constructor */
AttributeTimedState(void) : AttributeFlags() { mInvariant.Name("Invariant"); };
/**
* Test for default value (ie empty invariant and default flags)
*
* @return
* True for default value
*/
virtual bool IsDefault(void) const {return mInvariant.Empty() && AttributeFlags::IsDefault(); };
/** Invariant */
TimeConstraint mInvariant;
protected:
/**
* Assignment method.
*
* @param rSrcAttr
* Source to assign from
*/
void DoAssign(const AttributeTimedState& rSrcAttr);
/**
* Test eaulity.
*
* @param rOther
* Other attribute to compare with.
*/
bool DoEqual(const AttributeTimedState& rOther) const;
/**
* Reads the attribute from TokenReader, see AttributeVoid for public wrappers.
*
* If the current token indicates a invariant section, the method reads the invariant
* from that section. Else, it does nothing. Exceptions may only be thrown
* on invalid data within the timing section. The context argument is ignored, the
* label argument can be used to override the default section name Invariant.
*
* @param rTr
* TokenReader to read from
* @param rLabel
* Section to read
* @param pContext
* Read context to provide contextual information
*
* @exception Exception
* - IO error (id 1)
*/
virtual void DoRead(TokenReader& rTr, const std::string& rLabel="", const Type* pContext=0);
/**
* Writes the attribute to TokenWriter, see AttributeVoid for public wrappers.
*
* Writes am Invariant section to include data on the invariant. The label argument
* can be used to set a section label different the the default Invariant.
* Th context argument is ignored.
*
* @param rTw
* TokenWriter to write to
* @param rLabel
* Section to write
* @param pContext
* Write context to provide contextual information
*
* @exception Exception
* - IO error (id 2)
*/
virtual void DoWrite(TokenWriter& rTw, const std::string& rLabel="", const Type* pContext=0) const;
}; // class AttributeTimedState
/**
*
* Globat attribute with clockset.
*
* @ingroup TimedPlugin
*
*/
class FAUDES_API AttributeTimedGlobal : public AttributeVoid {
FAUDES_TYPE_DECLARATION(Void,AttributeTimedGlobal,AttributeVoid)
public:
/** Constructor */
AttributeTimedGlobal(void) {
mpClockSymbolTable=mClocks.SymbolTablep(); };
/**
* Test for default value (ie empty clockset)
*
* @return
* True for default value
*/
virtual bool IsDefault(void) const {return mClocks.Empty(); };
/** Clocks */
ClockSet mClocks;
/** Pointer to clock symboltable */
SymbolTable* mpClockSymbolTable;
protected:
/**
* Assignment method.
*
* @param rSrcAttr
* Source to assign from
*/
void DoAssign(const AttributeTimedGlobal& rSrcAttr);
/**
* Test eaulity.
*
* @param rOther
* Other attribute to compare with.
*/
bool DoEqual(const AttributeTimedGlobal& rOther) const;
/**
* Reads the attribute from TokenReader, see AttributeVoid for public wrappers.
*
* If the current token indicates a Clocks section, the method reads the global
* timing data from that section. Else, it does nothing. Exceptions may only be thrown
* on invalid data within the timing section. The context argument is ignored, the
* label argument can be used to override the default section name Clocks.
*
* @param rTr
* TokenReader to read from
* @param rLabel
* Section to read
* @param pContext
* Read context to provide contextual information
*
* @exception Exception
* - IO error (id 1)
*/
virtual void DoRead(TokenReader& rTr,const std::string& rLabel="", const Type* pContext=0);
/**
* Writes the attribute to TokenWriter, see AttributeVoid for public wrappers.
*
* Writes a Clocks section to include global timing data. The label argument
* can be used to set a section label different the the default Clocks.
* Th context argument is ignored.
*
* @param rTw
* TokenWriter to write to
* @param rLabel
* Section to write
* @param pContext
* Write context to provide contextual information
*
* @exception Exception
* - IO error (id 2)
*/
virtual void DoWrite(TokenWriter& rTw, const std::string& rLabel="", const Type* pContext=0) const;
}; // class AttributeTimedGlobal
} // namespace faudes
#endif
| true |
7f1fdcdd51583a7c887bfbfeca6e323d48d279ca | C++ | spacetelescope/spherical_geometry | /libqd/src/c_dd.cpp | UTF-8 | 6,630 | 2.921875 | 3 | [
"BSD-3-Clause"
] | permissive | /*
* src/c_dd.cc
*
* This work was supported by the Director, Office of Science, Division
* of Mathematical, Information, and Computational Sciences of the
* U.S. Department of Energy under contract number DE-AC03-76SF00098.
*
* Copyright (c) 2000-2001
*
* Contains the C wrapper functions for double-double precision arithmetic.
* This can be used from Fortran code.
*/
#include <cstring>
#include "config.h"
#include <qd/dd_real.h>
#include <qd/c_dd.h>
#define TO_DOUBLE_PTR(a, ptr) ptr[0] = a.x[0]; ptr[1] = a.x[1];
extern "C" {
/* add */
void c_dd_add(const double *a, const double *b, double *c) {
dd_real cc;
cc = dd_real(a) + dd_real(b);
TO_DOUBLE_PTR(cc, c);
}
void c_dd_add_dd_d(const double *a, double b, double *c) {
dd_real cc;
cc = dd_real(a) + b;
TO_DOUBLE_PTR(cc, c);
}
void c_dd_add_d_dd(double a, const double *b, double *c) {
dd_real cc;
cc = a + dd_real(b);
TO_DOUBLE_PTR(cc, c);
}
/* sub */
void c_dd_sub(const double *a, const double *b, double *c) {
dd_real cc;
cc = dd_real(a) - dd_real(b);
TO_DOUBLE_PTR(cc, c);
}
void c_dd_sub_dd_d(const double *a, double b, double *c) {
dd_real cc;
cc = dd_real(a) - b;
TO_DOUBLE_PTR(cc, c);
}
void c_dd_sub_d_dd(double a, const double *b, double *c) {
dd_real cc;
cc = a - dd_real(b);
TO_DOUBLE_PTR(cc, c);
}
/* mul */
void c_dd_mul(const double *a, const double *b, double *c) {
dd_real cc;
cc = dd_real(a) * dd_real(b);
TO_DOUBLE_PTR(cc, c);
}
void c_dd_mul_dd_d(const double *a, double b, double *c) {
dd_real cc;
cc = dd_real(a) * b;
TO_DOUBLE_PTR(cc, c);
}
void c_dd_mul_d_dd(double a, const double *b, double *c) {
dd_real cc;
cc = a * dd_real(b);
TO_DOUBLE_PTR(cc, c);
}
/* div */
void c_dd_div(const double *a, const double *b, double *c) {
dd_real cc;
cc = dd_real(a) / dd_real(b);
TO_DOUBLE_PTR(cc, c);
}
void c_dd_div_dd_d(const double *a, double b, double *c) {
dd_real cc;
cc = dd_real(a) / b;
TO_DOUBLE_PTR(cc, c);
}
void c_dd_div_d_dd(double a, const double *b, double *c) {
dd_real cc;
cc = a / dd_real(b);
TO_DOUBLE_PTR(cc, c);
}
/* copy */
void c_dd_copy(const double *a, double *b) {
b[0] = a[0];
b[1] = a[1];
}
void c_dd_copy_d(double a, double *b) {
b[0] = a;
b[1] = 0.0;
}
void c_dd_sqrt(const double *a, double *b) {
dd_real bb;
bb = sqrt(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_sqr(const double *a, double *b) {
dd_real bb;
bb = sqr(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_abs(const double *a, double *b) {
dd_real bb;
bb = abs(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_npwr(const double *a, int n, double *b) {
dd_real bb;
bb = npwr(dd_real(a), n);
TO_DOUBLE_PTR(bb, b);
}
void c_dd_nroot(const double *a, int n, double *b) {
dd_real bb;
bb = nroot(dd_real(a), n);
TO_DOUBLE_PTR(bb, b);
}
void c_dd_nint(const double *a, double *b) {
dd_real bb;
bb = nint(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_aint(const double *a, double *b) {
dd_real bb;
bb = aint(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_floor(const double *a, double *b) {
dd_real bb;
bb = floor(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_ceil(const double *a, double *b) {
dd_real bb;
bb = ceil(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_log(const double *a, double *b) {
dd_real bb;
bb = log(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_log10(const double *a, double *b) {
dd_real bb;
bb = log10(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_exp(const double *a, double *b) {
dd_real bb;
bb = exp(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_sin(const double *a, double *b) {
dd_real bb;
bb = sin(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_cos(const double *a, double *b) {
dd_real bb;
bb = cos(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_tan(const double *a, double *b) {
dd_real bb;
bb = tan(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_asin(const double *a, double *b) {
dd_real bb;
bb = asin(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_acos(const double *a, double *b) {
dd_real bb;
bb = acos(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_atan(const double *a, double *b) {
dd_real bb;
bb = atan(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_atan2(const double *a, const double *b, double *c) {
dd_real cc;
cc = atan2(dd_real(a), dd_real(b));
TO_DOUBLE_PTR(cc, c);
}
void c_dd_sinh(const double *a, double *b) {
dd_real bb;
bb = sinh(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_cosh(const double *a, double *b) {
dd_real bb;
bb = cosh(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_tanh(const double *a, double *b) {
dd_real bb;
bb = tanh(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_asinh(const double *a, double *b) {
dd_real bb;
bb = asinh(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_acosh(const double *a, double *b) {
dd_real bb;
bb = acosh(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_atanh(const double *a, double *b) {
dd_real bb;
bb = atanh(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_sincos(const double *a, double *s, double *c) {
dd_real ss, cc;
sincos(dd_real(a), ss, cc);
TO_DOUBLE_PTR(ss, s);
TO_DOUBLE_PTR(cc, c);
}
void c_dd_sincosh(const double *a, double *s, double *c) {
dd_real ss, cc;
sincosh(dd_real(a), ss, cc);
TO_DOUBLE_PTR(ss, s);
TO_DOUBLE_PTR(cc, c);
}
void c_dd_read(const char *s, double *a) {
dd_real aa(s);
TO_DOUBLE_PTR(aa, a);
}
void c_dd_swrite(const double *a, int precision, char *s, int len) {
dd_real(a).write(s, len, precision);
}
void c_dd_write(const double *a) {
std::cout << dd_real(a).to_string(dd_real::_ndigits) << std::endl;
}
void c_dd_neg(const double *a, double *b) {
b[0] = -a[0];
b[1] = -a[1];
}
void c_dd_rand(double *a) {
dd_real aa;
aa = ddrand();
TO_DOUBLE_PTR(aa, a);
}
void c_dd_comp(const double *a, const double *b, int *result) {
dd_real aa(a), bb(b);
if (aa < bb)
*result = -1;
else if (aa > bb)
*result = 1;
else
*result = 0;
}
void c_dd_comp_dd_d(const double *a, double b, int *result) {
dd_real aa(a), bb(b);
if (aa < bb)
*result = -1;
else if (aa > bb)
*result = 1;
else
*result = 0;
}
void c_dd_comp_d_dd(double a, const double *b, int *result) {
dd_real aa(a), bb(b);
if (aa < bb)
*result = -1;
else if (aa > bb)
*result = 1;
else
*result = 0;
}
void c_dd_pi(double *a) {
TO_DOUBLE_PTR(dd_real::_pi, a);
}
void c_dd_2pi(double *a) {
TO_DOUBLE_PTR(dd_real::_2pi, a);
}
double c_dd_epsilon(void) {
return (double) std::numeric_limits<dd_real>::epsilon();
}
}
| true |
fde166e12cff2d4e0c2f83a081256b60ab34c35f | C++ | Somefive/MercuryJson | /src/tape.cpp | UTF-8 | 33,589 | 2.578125 | 3 | [
"MIT"
] | permissive | #include "tape.h"
#include <assert.h>
#include <string.h>
#include <math.h>
#include <cassert>
#include <sstream>
#include <thread>
#include <future>
#include "constants.h"
#include "flags.h"
#include "mercuryparser.h"
#include "utils.h"
#include "parsestring.h"
namespace MercuryJson {
[[noreturn]] void _error(const char *expected, const char *input, char encountered, size_t index) {
std::stringstream stream;
char _encounter[3];
size_t len = 0;
__error_maybe_escape(_encounter, &len, encountered);
_encounter[len] = 0;
stream << "expected " << expected << " at index " << index << ", but encountered '" << _encounter << "'";
MercuryJson::__error(stream.str(), input, index);
}
size_t Tape::print_json(size_t tape_idx, size_t indent) {
uint64_t section = tape[tape_idx];
switch (section & TYPE_MASK) {
case TYPE_NULL:
printf("null");
return 1;
case TYPE_FALSE:
printf("false");
return 1;
case TYPE_TRUE:
printf("true");
return 1;
case TYPE_STR:
printf("\"%s\"", literals + (section & VALUE_MASK));
return 1;
case TYPE_INT:
printf("%lld", static_cast<long long int>(numeric[section & VALUE_MASK]));
return 1;
case TYPE_DEC:
printf("%.10lf", plain_convert(static_cast<long long int>(numeric[section & VALUE_MASK])));
return 1;
case TYPE_ARR: {
size_t elem_idx = tape_idx + 1;
bool first = true;
printf("[");
assert((section & VALUE_MASK) > tape_idx);
while (elem_idx < (section & VALUE_MASK)) {
if (first) first = false; else printf(",");
printf("\n");
print_indent(indent + 2);
elem_idx += print_json(elem_idx, indent + 2);
if ((tape[elem_idx] & TYPE_MASK) == TYPE_JUMP) {
// Skip jumps at the end of each value.
// Otherwise, this case will fail: [ value JUMP ]
elem_idx += tape[elem_idx] & VALUE_MASK;
}
}
assert(elem_idx == (section & VALUE_MASK) && tape_idx == (tape[elem_idx] & VALUE_MASK)
&& (tape[elem_idx] & TYPE_MASK) == TYPE_ARR);
printf("\n");
print_indent(indent);
printf("]");
return elem_idx + 1 - tape_idx;
}
case TYPE_OBJ: {
size_t elem_idx = tape_idx + 1;
bool first = true;
printf("{");
assert((section & VALUE_MASK) > tape_idx);
while (elem_idx < (section & VALUE_MASK)) {
if (first) first = false; else printf(",");
printf("\n");
print_indent(indent + 2);
elem_idx += print_json(elem_idx, indent + 2);
printf(": ");
elem_idx += print_json(elem_idx, indent + 2);
if ((tape[elem_idx] & TYPE_MASK) == TYPE_JUMP) {
// Skip jumps at the end of each value.
// Otherwise, this case will fail: { str : value JUMP }
elem_idx += tape[elem_idx] & VALUE_MASK;
}
}
assert(elem_idx == (section & VALUE_MASK) && tape_idx == (tape[elem_idx] & VALUE_MASK)
&& (tape[elem_idx] & TYPE_MASK) == TYPE_OBJ);
printf("\n");
print_indent(indent);
printf("}");
return elem_idx + 1 - tape_idx;
}
case TYPE_JUMP: {
size_t offset = (section & VALUE_MASK);
return print_json(tape_idx + offset, indent) + offset;
}
default:
throw std::runtime_error("unexpected element on tape");
}
}
void Tape::print_tape() {
for (size_t i = 0; i < tape_size; ++i) {
printf("[%3lu] ", i);
uint64_t section = tape[i];
switch (section & TYPE_MASK) {
case TYPE_NULL:
printf("null\n");
break;
case TYPE_FALSE:
printf("false\n");
break;
case TYPE_TRUE:
printf("true\n");
break;
case TYPE_STR:
printf("string: \"%s\"\n", literals + (section & VALUE_MASK));
break;
case TYPE_INT:
printf("integer: %lld\n", static_cast<long long int>(numeric[section & VALUE_MASK]));
break;
case TYPE_DEC:
printf("decimal: %lf\n", plain_convert(static_cast<long long int>(numeric[section & VALUE_MASK])));
break;
case TYPE_ARR:
printf("array: %llu\n", (section & VALUE_MASK));
break;
case TYPE_OBJ:
printf("object: %llu\n", (section & VALUE_MASK));
break;
case TYPE_JUMP:
printf("jump offset: %llu\n", (section & VALUE_MASK));
break;
default:
printf("unknown: type = %llu, value = %llu\n", (section & TYPE_MASK), (section & VALUE_MASK));
// throw std::runtime_error("unexpected element on tape");
break;
}
}
}
static const size_t kMaxDepth = 1024;
struct TapeStack {
size_t depth, extra_closing_count;
void *ret_address[kMaxDepth];
size_t scope_offset[kMaxDepth];
size_t extra_closing_offset[kMaxDepth]; // offsets of extra closing brackets
TapeStack() : depth(0), extra_closing_count(0) {}
inline void push(size_t offset, void *address) {
scope_offset[depth] = offset;
ret_address[depth] = address;
++depth;
}
};
#define peek_char() ({ \
idx = indices[idx_offset]; \
ch = input[idx]; \
})
#define expect(__char) ({ \
if (ch != (__char)) _error(#__char, input, ch, idx); \
})
void Tape::_thread_state_machine(char *input, const size_t *indices, size_t idx_begin, size_t idx_end,
TapeStack *stack, size_t *tape_end, bool start_unknown) {
#define next_char() ({ \
if (idx_offset == idx_end) goto succeed; \
idx = indices[idx_offset++]; \
ch = input[idx]; \
})
size_t idx; // index in input
char ch; // current character
size_t left_tape_idx, right_tape_idx;
size_t idx_offset = idx_begin;
// We keep a local counter for `tape_size` for the part of tape that the current thread writes to.
// Our implementation only guarantees that tape size is no greater than the number of structural characters,
// since commas (,) and colons (:) are not stored, and numerals and literals are stored off-tape.
size_t tape_pos = idx_begin;
if (start_unknown) {
goto unknown_start;
} else {
goto start_value;
}
#define PARSE_VALUE(continue_address) ({ \
switch (ch) { \
case '"': \
write_str(tape_pos++, _parse_str(input, idx)); \
break; \
case 't': \
parse_true(input, idx); \
write_true(tape_pos++); \
break; \
case 'f': \
parse_false(input, idx); \
write_false(tape_pos++); \
break; \
case 'n': \
parse_null(input, idx); \
write_null(tape_pos++); \
break; \
case '0': \
case '1': \
case '2': \
case '3': \
case '4': \
case '5': \
case '6': \
case '7': \
case '8': \
case '9': \
case '-': { \
_parse_and_write_number(input, idx, tape_pos++, idx_offset - 1); \
break; \
} \
case '[': { \
write_array(tape_pos); \
stack->push(tape_pos++, continue_address); \
goto array_begin; \
} \
case '{': { \
write_object(tape_pos); \
stack->push(tape_pos++, continue_address); \
goto object_begin; \
} \
default: \
goto fail; \
} \
})
#ifdef DEBUG
# define __PRINT_INFO(s) ({ printf("%lu[%c]: %s\n", idx, ch, s); })
#else
# define __PRINT_INFO(s) ({})
#endif
start_value:
__PRINT_INFO("parse value");
next_char();
PARSE_VALUE(&&start_continue);
goto succeed;
start_continue:
// next_char(); // strip off the extra closing bracket at end
goto succeed;
unknown_start:
__PRINT_INFO("parse unknown");
next_char();
switch (ch) {
case '"':
write_str(tape_pos++, _parse_str(input, idx));
peek_char();
if (ch == ':') goto object_key_state;
break;
case ']':
goto array_end;
case '}':
goto object_end;
case ':':
--idx_offset;
goto object_key_state;
case ',':
goto unknown_2nd_value;
default:
PARSE_VALUE(&&unknown_continue);
}
unknown_continue:
__PRINT_INFO("parse unknown continue");
next_char();
switch (ch) {
case ',':
goto unknown_2nd_value;
case ']':
goto array_end;
case '}':
goto object_end;
default:
goto fail;
}
unknown_2nd_value:
__PRINT_INFO("parse unknown 2nd value");
next_char();
if (ch == '"') {
write_str(tape_pos++, _parse_str(input, idx));
peek_char();
if (ch == ':') goto object_key_state;
else goto array_continue;
} else {
goto array_value;
}
object_begin:
__PRINT_INFO("parse object");
next_char();
switch (ch) {
case '"':
write_str(tape_pos++, _parse_str(input, idx));
goto object_key_state;
case '}':
goto object_end;
default:
goto fail;
}
object_key_state:
__PRINT_INFO("parse object key");
next_char();
expect(':');
next_char();
PARSE_VALUE(&&object_continue);
object_continue:
__PRINT_INFO("parse object continue");
next_char();
switch (ch) {
case ',':
next_char();
expect('"');
write_str(tape_pos++, _parse_str(input, idx));
goto object_key_state;
case '}':
goto object_end;
default:
goto fail;
}
object_end:
__PRINT_INFO("parse object end");
if (stack->depth == 0) {
// Extra closing curly bracket in current segment.
stack->extra_closing_offset[stack->extra_closing_count++] = tape_pos;
write_object(tape_pos);
append_content(tape_pos, idx_offset - 1);
++tape_pos;
goto unknown_continue;
} else {
--stack->depth;
left_tape_idx = stack->scope_offset[stack->depth];
right_tape_idx = tape_pos++;
write_object(left_tape_idx, right_tape_idx);
//@formatter:off
goto *stack->ret_address[stack->depth];
//@formatter:on
}
array_begin:
__PRINT_INFO("parse array");
next_char();
if (ch == ']') goto array_end;
array_value:
__PRINT_INFO("parse array value");
PARSE_VALUE(&&array_continue);
array_continue:
__PRINT_INFO("parse array continue");
next_char();
switch (ch) {
case ',':
next_char();
goto array_value;
case ']':
goto array_end;
default:
goto fail;
}
array_end:
__PRINT_INFO("parse array end");
if (stack->depth == 0) {
// Extra closing square bracket in current segment.
stack->extra_closing_offset[stack->extra_closing_count++] = tape_pos;
write_array(tape_pos);
append_content(tape_pos, idx_offset - 1);
++tape_pos;
goto unknown_continue;
} else {
--stack->depth;
left_tape_idx = stack->scope_offset[stack->depth];
right_tape_idx = tape_pos++;
write_array(left_tape_idx, right_tape_idx);
//@formatter:off
goto *stack->ret_address[stack->depth];
//@formatter:on
}
fail:
MercuryJson::__error("unexpected character when parsing value", input, idx);
succeed:
if (idx_offset != idx_end) MercuryJson::__error("excessive characters at end of input", input, idx);
__PRINT_INFO("parse succeed");
*tape_end = tape_pos;
#undef next_char
#undef PARSE_VALUE
}
inline bool __is_opening_bracket(char ch) {
return ch == '{' || ch == '[';
}
inline bool __is_closing_bracket(char ch) {
return ch == '}' || ch == ']';
}
inline bool __is_separator(char ch) {
return ch == ',' || ch == ':';
}
inline bool __is_non_structural(char ch) {
return !(__is_opening_bracket(ch) || __is_closing_bracket(ch) || __is_separator(ch));
}
void Tape::state_machine(char *input, size_t *idx_ptr, size_t structural_size) {
if (structural_size == 1)
__error("emtpy string is not valid JSON", input, 0);
#if PARSE_STR_NUM_THREADS
std::thread parse_str_threads[PARSE_STR_NUM_THREADS];
for (size_t i = 0; i < PARSE_STR_NUM_THREADS; ++i)
parse_str_threads[i] = std::thread(&Tape::_thread_parse_str, this, i, input, idx_ptr, structural_size);
#endif
literals = input;
#if TAPE_STATE_MACHINE_NUM_THREADS == 1
TapeStack stack;
_thread_state_machine(input, idx_ptr, 0, structural_size, &stack, &tape_size);
if (stack.depth != 0) throw std::runtime_error("unclosed brackets at end of input");
#else
TapeStack stack[TAPE_STATE_MACHINE_NUM_THREADS];
std::future<void> parse_threads[TAPE_STATE_MACHINE_NUM_THREADS - 1];
size_t tape_ends[TAPE_STATE_MACHINE_NUM_THREADS];
size_t idx_splits[TAPE_STATE_MACHINE_NUM_THREADS + 1];
// Choose a reasonable number of threads such that each split contains more than 1 character.
size_t num_threads = std::min(static_cast<size_t>(TAPE_STATE_MACHINE_NUM_THREADS),
std::max(1UL, (structural_size - 1) / 2));
for (int i = 0; i <= num_threads; ++i)
idx_splits[i] = (structural_size - 1) * i / num_threads;
for (int i = 1; i < num_threads; ++i) {
size_t idx_begin = idx_splits[i];
size_t idx_end = idx_splits[i + 1];
parse_threads[i - 1] = std::async(std::launch::async, &Tape::_thread_state_machine, this, input, idx_ptr,
idx_begin, idx_end, &stack[i], &tape_ends[i], /*start_unknown=*/true);
// parse_threads[i - 1].get();
}
_thread_state_machine(input, idx_ptr, idx_splits[0], idx_splits[1], &stack[0], &tape_ends[0]);
// for (int pid = 1; pid < TAPE_STATE_MACHINE_NUM_THREADS; ++pid)
// parse_threads[pid - 1].get();
// for (int i = 0; i < TAPE_STATE_MACHINE_NUM_THREADS; ++i) {
// size_t idx_begin = idx_splits[i];
// printf("Segment #%d: tape span = [%lu, %lu), stack size = %lu, extra brackets = %lu\n",
// i, idx_begin, tape_ends[i], stack[i].depth, stack[i].extra_closing_count);
// printf(" Extra: ");
// for (int j = 0; j < stack[i].extra_closing_count; ++j) {
// size_t offset = stack[i].extra_closing_offset[j];
// size_t type = tape[offset] & TYPE_MASK;
// printf(" %s(%lu)", type == TYPE_OBJ ? "obj" : "arr", offset);
// }
// printf("\n");
// printf(" Stack: ");
// for (int j = 0; j < stack[i].depth; ++j) {
// size_t offset = stack[i].scope_offset[j];
// size_t type = tape[offset] & TYPE_MASK;
// printf(" %s(%lu)", type == TYPE_OBJ ? "obj" : "arr", offset);
// }
// printf("\n");
// }
// Join threads and merge.
size_t merge_stack[kMaxDepth];
size_t top = 0;
for (int i = 0; i < stack[0].depth; ++i)
merge_stack[top++] = stack[0].scope_offset[i];
for (int pid = 1; pid < num_threads; ++pid) {
parse_threads[pid - 1].get();
// Verify grammar correctness checks for cross-boundary input.
// This is to make sure structural characters that are not stored on tape (, and :) are properly inserted
// between segments, i.e. the following cases should fail when running with 2 threads:
// No. Reason 1st Thread 2nd Thread
// 1. Missing colon (:) { "1": 2, "3" 4, "5": 6 }
// 2. Missing comma (,) [ 1, 2 3, 4]
// 3. Missing comma (,) [ [ 1, 2 ] [ 3, 4 ] ]
// 4. Extra colon (:) { "1": 2, "3": : 4, "5": 6 }
// 5. Extra comma (,) [ 1, 2, , 3, 4 ]
// 6. Extra kv-pair in object { "1": 2, "3": "4": 5, "5": 6 }
// 7. Array value in object { "1": 2, "3", "5": 6 }
size_t pos = idx_splits[pid];
size_t idx = idx_ptr[pos];
if (pos >= 1 && pos < structural_size) {
char left_char = input[idx_ptr[pos - 1]], right_char = input[idx];
if ((__is_non_structural(left_char) || __is_closing_bracket(left_char))
&& (__is_non_structural(right_char) || __is_opening_bracket(right_char))) // case 1, 2, 3
MercuryJson::__error("expected separator", input, idx);
if (__is_separator(left_char) && __is_separator(right_char)) // cases 4 & 5
MercuryJson::__error("extra separator", input, idx);
}
if (top > 0) {
bool in_object = (tape[merge_stack[top - 1]] & TYPE_MASK) == TYPE_OBJ;
for (size_t right_pos = pos; right_pos <= pos + 1; ++right_pos) {
if (right_pos >= 2 && right_pos < structural_size) {
char left_char = input[idx_ptr[right_pos - 2]], right_char = input[idx_ptr[right_pos]];
if (left_char == ':' && right_char == ':') // case 6
MercuryJson::__error("extra colon (:)", input, idx_ptr[right_pos]);
if (in_object && left_char == ',' && right_char == ',')
MercuryJson::__error("non key-value pair in object", input, idx_ptr[right_pos]);
}
}
}
TapeStack &cur_stack = stack[pid];
for (int i = 0; i < cur_stack.extra_closing_count; ++i) {
size_t right_tape_idx = cur_stack.extra_closing_offset[i];
size_t right_input_idx = idx_ptr[tape[right_tape_idx] & VALUE_MASK];
if (top == 0) MercuryJson::__error("unmatched closing bracket", input, right_input_idx);
size_t left_tape_idx = merge_stack[--top];
if ((tape[left_tape_idx] & TYPE_MASK) != (tape[right_tape_idx] & TYPE_MASK))
MercuryJson::__error("matching brackets have different types", input, right_input_idx);
write_content(right_tape_idx, left_tape_idx);
write_content(left_tape_idx, right_tape_idx);
}
for (int i = 0; i < cur_stack.depth; ++i)
merge_stack[top++] = cur_stack.scope_offset[i];
}
if (top > 0) throw std::runtime_error("unmatched opening brackets");
if (size_t pos = idx_ptr[idx_splits[num_threads] - 1]; input[pos] == ',')
MercuryJson::__error("extra separator", input, pos);
for (int i = 0; i < num_threads - 1; ++i) {
size_t idx_begin_next = idx_splits[i + 1];
if (tape_ends[i] < idx_begin_next) write_jump(tape_ends[i], idx_begin_next);
}
tape_size = tape_ends[num_threads - 1];
#endif
#if PARSE_NUM_NUM_THREADS && !NO_PARSE_NUMBER
std::thread parse_num_threads[PARSE_STR_NUM_THREADS];
for (size_t i = 0; i < PARSE_STR_NUM_THREADS; ++i)
parse_num_threads[i] = std::thread(&Tape::_thread_parse_num, this, i, input, idx_ptr, structural_size);
for (std::thread &thread : parse_num_threads)
thread.join();
#endif
#if PARSE_STR_NUM_THREADS
for (std::thread &thread : parse_str_threads)
thread.join();
#endif
// print_tape();
// print_json();
// printf("\n");
}
void Tape::__parse_and_write_number_backoff(const char *input, size_t offset, size_t tape_idx, size_t numeric_idx) {
bool is_decimal;
auto ret = parse_number(input, &is_decimal, offset);
if (is_decimal) {
tape[tape_idx] = TYPE_DEC | numeric_idx;
numeric[numeric_idx] = *reinterpret_cast<uint64_t *>(&ret);
} else {
tape[tape_idx] = TYPE_INT | numeric_idx;
numeric[numeric_idx] = *reinterpret_cast<uint64_t *>(&ret);
}
}
void Tape::__parse_and_write_number_fast(const char *input, size_t offset, size_t tape_idx, size_t numeric_idx) {
const char *s = input + offset;
uint64_t integer = 0ULL;
bool negative = false;
int64_t exponent = 0LL;
if (*s == '-') {
++s;
negative = true;
}
if (*s == '0') {
++s;
if (*s >= '0' && *s <= '9')
MercuryJson::__error("numbers cannot have leading zeros", input, offset);
} else {
if (*s < '0' || *s > '9')
MercuryJson::__error("numbers must have integer parts", input, offset);
do {
integer = integer * 10 + (*s++ - '0');
} while (*s >= '0' && *s <= '9');
}
if (*s == '.') {
const char *const base = ++s;
#if PARSE_NUMBER_AVX
if (_all_digits(s)) {
integer += integer * 100000000 + _parse_eight_digits(s);
s += 8;
}
#endif
while (*s >= '0' && *s <= '9')
integer = integer * 10 + (*s++ - '0');
exponent = base - s;
if (exponent == 0)
__error("excessive characters at end of number", input, s - input - 1);
}
if (s - input - offset >= 18) {
// use the slower back-off method
__parse_and_write_number_backoff(input, offset, tape_idx, numeric_idx);
return;
}
if (*s == 'e' || *s == 'E') {
++s;
bool negative_exp = false;
if (*s == '-') {
negative_exp = true;
++s;
} else if (*s == '+') ++s;
int64_t expo = 0LL;
if (*s < '0' || *s > '9')
MercuryJson::__error("numbers must not have null exponents", input, s - input);
do {
expo = expo * 10 + (*s++ - '0');
} while (*s >= '0' && *s <= '9');
exponent += negative_exp ? -expo : expo;
}
if (!kStructuralOrWhitespace[*s])
__error("excessive characters at end of number", input, s - input);
if (exponent == 0) {
tape[tape_idx] = TYPE_INT | numeric_idx;
numeric[numeric_idx] = negative ? -integer : integer;
} else {
if (exponent < -308 || exponent > 308)
MercuryJson::__error("decimal exponent out of range", input, offset);
double decimal = negative ? -integer : integer;
decimal *= kPowerOfTen[308 + exponent];
tape[tape_idx] = TYPE_DEC | numeric_idx;
numeric[numeric_idx] = plain_convert(decimal);
}
}
void Tape::_parse_and_write_number(const char *input, size_t offset, size_t tape_idx, size_t numeric_idx) {
#if NO_PARSE_NUMBER
tape[tape_idx] = 0;
#elif PARSE_NUM_NUM_THREADS
tape[tape_idx] = numeric_idx;
numeric[numeric_idx] = tape_idx;
#else
__parse_and_write_number_fast(input, offset, tape_idx, numeric_idx);
#endif
}
#define next_char() ({ \
idx = indices[idx_offset++]; \
ch = input[idx]; \
})
void TapeWriter::_parse_value() {
size_t idx;
char ch;
next_char();
switch (ch) {
case '"':
tape->write_str(_parse_str(idx));
break;
case 't':
parse_true(input, idx);
tape->write_true();
break;
case 'f':
parse_false(input, idx);
tape->write_false();
break;
case 'n':
parse_null(input, idx);
tape->write_null();
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-': {
bool is_decimal;
long long int ret = parse_number(input, &is_decimal, idx);
if (is_decimal) tape->write_decimal(plain_convert(ret));
else tape->write_integer(ret);
break;
}
case '[': {
size_t left_tape_idx = tape->write_array();
size_t right_tape_idx = _parse_array();
tape->write_content(right_tape_idx, left_tape_idx);
tape->write_content(left_tape_idx, right_tape_idx);
break;
}
case '{': {
size_t left_tape_idx = tape->write_object();
size_t right_tape_idx = _parse_object();
tape->write_content(right_tape_idx, left_tape_idx);
tape->write_content(left_tape_idx, right_tape_idx);
break;
}
default:
throw std::runtime_error("unexpected character when parsing value");
}
}
size_t TapeWriter::_parse_array() {
size_t idx;
char ch;
peek_char();
if (ch == ']') {
next_char();
return tape->write_array();
}
while (true) {
_parse_value();
next_char();
if (ch == ']') return tape->write_array();
expect(',');
}
}
size_t TapeWriter::_parse_object() {
size_t idx;
char ch;
next_char();
if (ch == '}') return tape->write_object();
while (true) {
expect('"');
tape->write_str(_parse_str(idx));
next_char();
expect(':');
_parse_value();
next_char();
if (ch == '}') return tape->write_object();
expect(',');
next_char();
}
}
#undef next_char
#undef peek_char
#undef expect
size_t TapeWriter::_parse_str(size_t idx) {
size_t index = tape->literals_size;
char *dest = tape->literals + index;
size_t len = 0;
parse_str(input, dest, &len, idx + 1);
tape->literals_size += len + 1;
return index;
}
size_t Tape::_parse_str(char *input, size_t idx) {
#if PARSE_STR_NUM_THREADS
return idx + 1;
#endif
// size_t index = literals_size;
// char *dest = literals + index;
size_t index = idx;
char *dest = input + idx + 1;
size_t len = 0;
parse_str(input, dest, &len, idx + 1);
literals_size += len + 1;
return index + 1;
}
void Tape::_thread_parse_str(size_t pid, char *input, const size_t *idx_ptr, size_t structural_size) {
#if PARSE_STR_NUM_THREADS
size_t idx;
size_t begin = pid * structural_size / PARSE_STR_NUM_THREADS;
size_t end = (pid + 1) * structural_size / PARSE_STR_NUM_THREADS;
if (end > structural_size) end = structural_size;
for (size_t i = begin; i < end; ++i) {
idx = idx_ptr[i];
char *dest = input + idx + 1;
if (input[idx] == '"') {
parse_str(input, dest, nullptr, idx + 1);
}
}
#endif
}
void Tape::_thread_parse_num(size_t pid, char *input, const size_t *idx_ptr, size_t structural_size) {
#if PARSE_NUM_NUM_THREADS
size_t begin = pid * structural_size / PARSE_NUM_NUM_THREADS;
size_t end = (pid + 1) * structural_size / PARSE_NUM_NUM_THREADS;
for (size_t numeric_idx = begin; numeric_idx < end; ++numeric_idx) {
size_t offset = idx_ptr[numeric_idx];
if (!(input[offset] == '-' || (input[offset] >= '0' && input[offset] <= '9'))) continue;
size_t tape_idx = numeric[numeric_idx];
__parse_and_write_number(input, offset, tape_idx, numeric_idx);
}
#endif
}
void Tape::components_analysis() {
uint64_t stats[16];
for (size_t i = 0; i < 16; ++i) stats[i] = 0;
for (size_t i = 0; i < tape_size; ++i) {
uint64_t section = tape[i];
stats[(section & TYPE_MASK) >> 60]++;
}
printf("integer: %10llu\n", stats[TYPE_INT >> 60]);
printf("decimal: %10llu\n", stats[TYPE_DEC >> 60]);
printf("string: %10llu\n", stats[TYPE_STR >> 60]);
printf("object: %10llu\n", stats[TYPE_OBJ >> 60] / 2);
printf("array: %10llu\n", stats[TYPE_ARR >> 60] / 2);
printf("null: %10llu\n", stats[TYPE_NULL >> 60]);
printf("true: %10llu\n", stats[TYPE_TRUE >> 60]);
printf("false: %10llu\n", stats[TYPE_FALSE >> 60]);
}
}
| true |
4cc60655f6cdad2a03b13a45fd855a182bf746d6 | C++ | serega111198/bubble-sorting | /bubble-sorting.cpp | UTF-8 | 611 | 3.3125 | 3 | [] | no_license | #include "stdafx.h"
int swap(int *xp, int *yp) {
int temp = *xp;
*xp = *yp;
*yp = temp;
}
int bubbleSortingUp(int a[], int size) {
int x, j;
for (int i = 0; i < size - 1; i++)
{
if (a[i] < -1500000000 || a[i]>1500000000)
return 1;
for (j = 0; j < size - 1 - i; j++)
if ((a[j] < a[j + 1]))
swap(&a[j], &a[j + 1]);
}
return 0;
}
int bubbleSortingDown(int a[], int size) {
int x, j;
for (int i = 0; i < size - 1; i++)
{
if (a[i] < -1500000000 || a[i]>1500000000)
return 1;
for (j = 0; j < size - 1 - i; j++)
if ((a[j] > a[j + 1]))
swap(&a[j], &a[j + 1]);
}
return 0;
} | true |
72de0b32fba4f12ccd2466101bb1ec7f6b6ed328 | C++ | gpudev0517/Fire-Simulator | /NVIS/Code/Geometry/Utility/NEVentCriteria.h | UTF-8 | 1,295 | 2.609375 | 3 | [] | no_license | #pragma once
class NECEXP_GEOMETRY NEVentCriteria
{
public:
enum CriteriaType
{
Temperature = 0,
Time = 1
};
struct VentValues
{
double m_Threshold;
double m_Percent;
VentValues()
{
m_Threshold = 0.0;
m_Percent = 0.0;
}
bool operator==(const VentValues& r) const
{
return m_Threshold == r.m_Threshold && m_Percent == r.m_Percent;
}
};
NEVentCriteria();
NEVentCriteria(const QString& name);
~NEVentCriteria(){}
const QString& name() const;
void setName(const QString& val);
int ID() const;
void setID(int val);
int index() const;
void setIndex(int index);
CriteriaType type() const;
void setType(CriteriaType type);
const QList<VentValues>& values() const;
void setValues(const QList<VentValues>& values);
operator QVariant() const;
operator QString() const;
bool operator==(const NEVentCriteria& r) const
{
return m_Name == r.m_Name && m_ID == r.m_ID && m_Type == r.m_Type && m_Values == r.m_Values;
}
private:
QString m_Name;
int m_ID;
int m_Index;
CriteriaType m_Type;
QList<VentValues> m_Values;
};
Q_DECLARE_METATYPE(NEVentCriteria)
| true |
002675d6da6689a0616178fe34bc94451b54d89c | C++ | andrewusc/Clone-of-STL | /alloc.h | UTF-8 | 1,669 | 2.890625 | 3 | [] | no_license |
#ifndef __TinySTL__alloc__
#define __TinySTL__alloc__
#include <stdio.h>
#include <cstdlib>
namespace TinySTL{
/*
** Space allocator
*/
class alloc{
private:
enum EAlign { ALIGN = 8 };
enum EMaxBytes { MAXBYTES = 128};
enum ENFreeLists{ NFREELISTS = (EMaxBytes::MAXBYTES)/(EAlign::ALIGN)};
enum ENObjs{ NOBJS = 20 };
private:
union obj{
union obj *next;
char client[1];
};
/* maintian a free-list[16], available chunks with size 8*(i+1) are linked at free_list[i] */
static obj *free_list[ENFreeLists::NFREELISTS];
private:
static char *start_free; //the start of pool
static char *end_free; //the end of pool
static size_t heap_size; // current size of heap_size
private:
static size_t ROUND_UP(size_t bytes){ // 将bytes以8为倍数向上取整
return (bytes + EAlign::ALIGN - 1) & ~(EAlign::ALIGN - 1);
}
static size_t FREELIST_INDEX(size_t bytes){ // find which free_list to use based on the size of bytes
return ((bytes + EAlign::ALIGN-1)/EAlign::ALIGN - 1);
}
static void *refill(size_t n); // take spaces from the pool
static char *chunk_alloc(size_t size, size_t & nobjs); // 分配一大块空间,可以容纳nobjs个大小为size的区块
public:
static void *allocate(size_t bytes);
static void deallocate(void *ptr,size_t bytes);
static void *reallocate(void *ptr, size_t old_sz, size_t new_sz);
};
}
#endif /* defined(__TinySTL__alloc__) */
| true |
1a157413ae63c7251ee92f9997851a5c49d02e67 | C++ | dvetutnev/learn_discrete_math | /find_sum/find_sum.h | UTF-8 | 2,184 | 3.296875 | 3 | [
"MIT"
] | permissive | #pragma once
#include <vector>
#include <set>
#include <utility>
#include <optional>
#include <cassert>
#include <unordered_set>
namespace bruteforce {
// Return pair numbers, not index
inline std::optional<std::pair<std::size_t, std::size_t>> findPair(const std::vector<std::size_t>& set, std::size_t sum) {
for (auto externIt = std::begin(set); externIt != std::end(set); ++externIt) {
for (auto internIt = std::begin(set); internIt != std::end(set); ++internIt) {
if (externIt == internIt) {
continue;
}
std::size_t first = *externIt;
std::size_t second = *internIt;
if (first + second == sum) {
return std::make_pair(first, second);
}
}
}
return std::nullopt;
}
}
namespace sort::bad {
inline std::optional<std::pair<std::size_t, std::size_t>> findPair(const std::vector<std::size_t>& input, std::size_t sum) {
// std::set is an associative container that contains a sorted set of unique objects of type Key
// https://en.cppreference.com/w/cpp/container/set
std::set<std::size_t> set = { std::begin(input), std::end(input) };
assert(set.size() <= input.size());
auto setIt = std::begin(set);
auto inputIt = std::begin(input);
auto end = std::end(set);
for (; setIt != end; ++setIt, ++inputIt) {
auto a = *setIt;
auto b = *inputIt;
if (a == b) {
continue;
}
if (a + b == sum) {
return std::make_pair(a, b);
}
}
return std::nullopt;
}
}
namespace sort {
inline std::optional<std::pair<std::size_t, std::size_t>> findPair(const std::vector<std::size_t>& input, std::size_t sum) {
std::unordered_set<std::size_t> set;
for (std::size_t i : input) {
auto diff = sum - i;
if (diff <= 0) {
continue;
}
// Unique numbers
if (diff == i) {
continue;
}
if (set.find(diff) == std::end(set)) {
set.insert(i);
continue;
}
return std::make_pair(i, diff);
}
return std::nullopt;
}
}
| true |
8eefdf39a83a0d7a30fe6680f3501abaa7eb8a09 | C++ | AlenaMitrakhovich/OOP244-Introduction-to-Object-Oriented-Programming | /Workshop8/w8_in_lab.cpp | UTF-8 | 818 | 3.015625 | 3 | [] | no_license | // OOP244 Workshop 8: Derived Classes
// File w8_in_lab.cpp
// Version 1.0
// Date 2016/11/06
// Author Franz Newland, Eden Burton
// Description
// This file demonstrates the client module of w8
/////////////////////////////////////////////////////
#include <iostream>
#include "Hero.h"
int main()
{
Hero m("Mom", 20);
m.display(std::cout);
Hero d("Dad", 10);
d.display(std::cout);
m += 70;
m.display(std::cout);
d += 20;
d.display(std::cout);
if (m < d)
std::cout << "Dad is stronger!" << std::endl;
else
std::cout << "Mom is stronger!" << std::endl;
d -= 25;
d.display(std::cout);
m -= 200;
m.display(std::cout);
if (m < d)
std::cout << "Dad is stronger!" << std::endl;
else
std::cout << "Mom is stronger!" << std::endl;
return 0;
} | true |
28325cb6111d7aa0ec339d2640b8edd3ec5c44c9 | C++ | p0kemo4ik/oop_exercise_08 | /octagon.cpp | UTF-8 | 1,083 | 3.265625 | 3 | [] | no_license | #include "octagon.hpp"
#include <cmath>
#include "vertex.hpp"
vertex octagon::center() const {
double x = 0;
double y = 0;
for(int i = 0; i < 8; i++){
x += Vertexs[i].x;
y += Vertexs[i].y;
}
x /= 8;
y /= 8;
vertex p(x,y);
return p;
}
void octagon::print(std::ostream& os) const {
for(int i = 0; i < 8; i++){
os << Vertexs[i] <<' ';
}
os << '\n'<< "Octagon" <<'\n' << "Center: " << center() << " Area: "<< area() << '\n' <<'\n';
}
void octagon::printFile(std::ofstream& of) const {
for(int i = 0; i < 8; i++){
of << Vertexs[i] <<' ';
}
of << '\n';
}
double octagon::area() const{
double Area = 0;
for (int i = 0; i < 8; i++) {
Area += (Vertexs[i].x) * (Vertexs[(i + 1) % 8].y) - (Vertexs[(i + 1) % 8].x)*(Vertexs[i].y);
}
Area *= 0.5;
return abs(Area);
}
octagon::octagon(std::istream& is) {
for(int i = 0; i < 8; i++){
is >> Vertexs[i];
}
}
octagon::octagon(std::ifstream& is) {
for(int i = 0; i < 8; i++){
is >> Vertexs[i];
}
} | true |
ad16fc59005f807aca401dd320b361826770f337 | C++ | cerebis/MetaCarvel | /OGDF/include/ogdf/fileformats/xml/Parser.h | UTF-8 | 3,434 | 2.53125 | 3 | [
"LGPL-2.1-or-later",
"GPL-3.0-only",
"GPL-1.0-or-later",
"EPL-1.0",
"MIT",
"GPL-2.0-only",
"LicenseRef-scancode-generic-exception",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /** \file
* \brief Declarations for simple XML parser.
*
* \author Łukasz Hanuszczak
*
* \par License:
* This file is part of the Open Graph Drawing Framework (OGDF).
*
* \par
* Copyright (C)<br>
* See README.txt in the root directory of the OGDF installation for details.
*
* \par
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* Version 2 or 3 as published by the Free Software Foundation;
* see the file LICENSE.txt included in the packaging of this file
* for details.
*
* \par
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* \par
* 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., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
* \see http://www.gnu.org/copyleft/gpl.html
***************************************************************/
#ifdef _MSC_VER
#pragma once
#endif
#ifndef OGDF_XML_PARSER_H
#define OGDF_XML_PARSER_H
#include <algorithm>
#include <exception>
#include <memory>
#include <vector>
#include <unordered_map>
using std::unique_ptr;
#include <ogdf/fileformats/xml/Lexer.h>
namespace ogdf {
namespace xml {
class ParseException : public std::exception {
public:
explicit ParseException(
const std::string &what,
std::size_t row, std::size_t column);
explicit ParseException(
const char *what,
std::size_t row, std::size_t column);
virtual const char *what() const throw() override {
return m_what.c_str();
}
private:
std::string m_what;
};
class Element {
public:
using Children = std::vector<unique_ptr<Element>>;
using Attributes = std::unordered_map<std::string, std::string>;
const std::string &name() const {
return m_name;
}
const std::string &text() const {
return m_text;
}
const Children &children() const {
return m_children;
}
const Attributes &attributes() const {
return m_attrs;
}
private:
std::string m_name;
std::string m_text;
Children m_children;
Attributes m_attrs;
friend class Parser;
};
class Parser {
public:
unique_ptr<Element> parse(std::istream &is);
private:
Lexer m_lexer;
class Piece {
public:
enum class type {
text,
tag_open,
tag_close,
tag_empty,
tag_header
};
type m_type;
std::string m_value;
std::unique_ptr<Element::Attributes> m_attrs;
};
Piece nextPiece();
std::unique_ptr<Element> parseElement(Piece &piece);
void fail(const char *message);
void fail(const std::string &message);
void expect(token expected, const char *message);
static bool isBlank(const std::string &str);
};
inline void Parser::fail(const char *message)
{
throw ParseException(message, m_lexer.row(), m_lexer.column());
}
inline void Parser::fail(const std::string &message)
{
fail(message.c_str());
}
inline void Parser::expect(token expected, const char *message)
{
if (m_lexer.currentToken() == expected) {
return;
}
fail(message);
}
inline bool Parser::isBlank(const std::string &str)
{
return std::all_of(str.begin(), str.end(), [](char c) {
// TODO: Replace it with std::isspace once VS will stop being retarded.
return isspace(c);
});
}
}
}
#endif
| true |
6ca139f49a9a71eff1f2efedace32716932e2794 | C++ | imrasp/CameraChecker | /main.cpp | UTF-8 | 2,609 | 2.734375 | 3 | [] | no_license | /*
* main.cpp
*
* Created on: May 15, 2017
* Author: rasp
*/
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
//#include <boost/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <iostream>
#include <fstream>
#include <string>
#include <thread>
using namespace cv;
using namespace std;
//using namespace boost;
using namespace boost::posix_time;
int findCamera();
void loopCamera();
VideoCapture stream1, stream2;
thread t1, t2;
class Video_Capture{
public:
Video_Capture();
~Video_Capture();
bool bFrontCamera, bDownCamera;
void start_thread();
};
Video_Capture::Video_Capture()
{
bFrontCamera = false;
bDownCamera = false;
}
Video_Capture::~Video_Capture()
{
t1.join();
}
int findCamera(int max)
{
VideoCapture stream; //0 is the id of video device.0 if you have only one camera.
int maxTested = max;
int i;
for (i = maxTested; i >= 0; i--){
VideoCapture stream(i);
bool res = (stream.isOpened());
cout << res <<endl;
if (res)
{
cout <<"Open camera " << i <<endl;
return i;
}
else
{
stream.release();
cout <<"Camera " << i << " is released" <<endl;
}
}
return -1;
}
void loopCamera()
{
int frameno = 0;
//uncondition loop
while (true)
{
ptime timestamp1 = microsec_clock::local_time();
Mat cameraFrame1, cameraFrame2;
stream1.read(cameraFrame1);
stream2.read(cameraFrame2);
imshow("cam", cameraFrame1);
imshow("cam2", cameraFrame2);
cout << "Frame" << ++frameno << " @ " << timestamp1 << endl;
if (waitKey(30) >= 0)
break;
}
}
void loopCamera2()
{
int frameno = 0;
//uncondition loop
while (true)
{
ptime timestamp1 = microsec_clock::local_time();
Mat cameraFrame;
stream2.read(cameraFrame);
imshow("cam2", cameraFrame);
cout << "Frame" << ++frameno << " @ " << timestamp1 << endl;
if (waitKey(30) >= 0)
break;
}
}
void Video_Capture::start_thread()
{
int cam = findCamera(5);
if(cam == -1)
{
cout << "cannot open camera";
//return 0;
}
stream1 = VideoCapture(cam);
int cam2 = findCamera(cam-1);
stream2 = VideoCapture(cam2);
t1 = thread(&loopCamera);
}
int main()
{
Video_Capture vc;
vc.start_thread();
for (int i = 0; i<=10;i++)
{
cout << "main : " << i <<endl;
sleep(1);
}
return 0;
}
| true |