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 |
---|---|---|---|---|---|---|---|---|---|---|---|
3857c5ee8a476143f17f4d23d6b7bfe726ea97a2
|
C++
|
d3v1c3nv11/eduArdu
|
/SOFTWARE/8_eduArdu_Temperature/LED_Matrix.h
|
UTF-8
| 1,588 | 2.953125 | 3 |
[
"Apache-2.0"
] |
permissive
|
/*
LED_Matrix is a Library to drive the Olimex 8x8 (non-rgb) matrix
Based on the original library LED_Matrix created by Lutz Reiter, Dec 2014.
*/
#ifndef _LED_MATRIX_H
#define _LED_MATRIX_H
#define ROWS 8
#define STRING_MAX_CHAR 64
#include <Arduino.h>
#include "font.h"
typedef unsigned char uchar;
class LED_Matrix
{
public:
LED_Matrix(int latchPin, int dataPin, int clockPin);
// clears matrix
void clear();
void SetBrightness (int Brightness);
void ChangeBrightness (int X);
void drawArray(int x, int y, const uchar *array, int rows);
// draws a pixel
void drawPixel(int x, int y);
void DrawColumn(int Column, unsigned char Byte);
void DisplayChar (char C);
void CharIntoBuffer (unsigned char C, int Index);
void StringIntoBuffer (unsigned char Str[], int Index);
void DisplayText(unsigned char Str[]);
void DisplayText(unsigned char Str[], int Offset);
void UpdateText();
void SlideLeft (int Positions);
void SlideRight (int Positions);
// erase a Pixel
void erasePixel(int x, int y);
void drawLine(int x, int y, int length, boolean horizontal = true);
// draws a rectangle
void drawRectangle(int x, int y, int w, int h, boolean filled = false);
// shifts the data to the led-matrix to display it
//the multiplexing has to be done by the arduino, so this function has to be called constantly
void UpdateMatrix();
private:
int LED_Offset, TextLen;
unsigned char TextBuffer[STRING_MAX_CHAR * CHAR_WIDTH];
uchar matrix[ROWS];
int brightness; // 255 highest brigthness, 0 lowest brightness
int latchPin,dataPin,clockPin;
};
#endif
| true |
ad8480c5201277c67dc305a778031a8354a3fb9d
|
C++
|
enkiprobo/CPtraining
|
/hackerrank/warmup/i_birthdayCakeCandles.cpp
|
UTF-8
| 401 | 3.234375 | 3 |
[] |
no_license
|
/**
* Created By: Enki Probo S.
* Description:
* Counting the biggest number
* from the input
**/
#include <iostream>
using namespace std;
int main() {
int n, max=0, counter=0, input;
cin >> n;
for ( int i = 0; i < n; i++ ) {
cin >> input;
if (input > max ) {
max = input;
counter = 1;
}else if (input == max){
counter++;
}
}
cout << counter;
return 0;
}
| true |
a9d7ce5aa745474bf61804ef596474b8b8a09c60
|
C++
|
andimoto/stm32f4xx-cmake-cpp
|
/src/hal_uc/rng.cpp
|
UTF-8
| 694 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
/**
* Name: rng.cpp
* Initial Author: andimoto
*/
#include "rng.hpp"
#include "stm32f4xx.h"
#include "stm32f4xx_rng.h"
hal_uc::rng::rng(void)
{
/*
* Enable RNG Module
* */
RCC_AHB2PeriphClockCmd(RCC_AHB2Periph_RNG, ENABLE);
}
bool hal_uc::rng::getNumber(std::uint32_t& randNo)
{
if(!isStopped && (RNG_GetFlagStatus(RNG_FLAG_DRDY) == SET))
{
randNo = static_cast<std::uint32_t>(RNG_GetRandomNumber());
}
return isStopped;
}
void hal_uc::rng::start(void)
{
/* start rng module by enable generating numbers */
RNG_Cmd(ENABLE);
isStopped = false;
}
void hal_uc::rng::stop(void)
{
/* stop rng module by disabling generating numbers */
RNG_Cmd(DISABLE);
isStopped = true;
}
| true |
b99afad5bb9ec5d642dd126bf70cfbe91f6c2c09
|
C++
|
Pessu/Adventure
|
/Utilities.cpp
|
UTF-8
| 1,751 | 2.90625 | 3 |
[] |
no_license
|
/*
* Utilities.cpp
*
* Created on: 21.12.2012
* Author: Pessu
*/
#include "Utilities.h"
#include <iostream>
#include <iostream>
#include <fstream>
#include <string.h>
#include <cstdlib>
#include "Exceptions.h"
#include "Game.h"
#include "Player.h"
using namespace std;
//class Player;
Utilities::Utilities()
{
}
Utilities::~Utilities()
{
}
int isNumeric(char* str)
{
int len = strlen(str);
int i = 0;
int ret = 1;
int deccnt = 0;
while(i < len && ret != 0)
{
if(str[i] == '.')
{
deccnt++;
if(deccnt > 1)
ret = 0;
}
else
ret = isdigit(str[i]);
i++;
}
return ret;
}
int Utilities::convertStringToInt(string par1)
{
int result = atoi(par1.c_str());
return result;
}
Utilities::statsStruct Utilities::LoadPlayer()
{
statsStruct result;
string str;
ifstream instream;
instream.open("PlayerInfo.bin", ios::in);
int i = 0;
if (instream.is_open())
{
while(!instream.eof())
{
getline (instream,result.statsArray[i],'\n');
i++;
}
instream.close();
}
else
{
throw (FileNotFoundException("File error, could not load"));
}
return result;
}
bool Utilities::SavePlayer(Player & player)
{
ofstream outstream("PlayerInfo.bin", ios::out | ios::trunc);
if (outstream)
{
outstream << player.GetName() << endl;
outstream << player.GetAge() << endl;
outstream << player.GetRace() << endl;
outstream << player.GetGender() << endl;
outstream << player.GetClass() << endl;
outstream << player.GetExperience() << endl;
outstream << player.GetHitpoints() << endl;
outstream.close();
return true;
}
else
{
throw (FileNotFoundException("File error, could not save"));
}
}
| true |
3162acf5feb1b9c27506d51de8e6459e4b525b0d
|
C++
|
VishalDutt1998/Data-Structure
|
/PepC/DP1_1/CoinChange.cpp
|
UTF-8
| 1,056 | 3.234375 | 3 |
[] |
no_license
|
#include<iostream>
#include<vector>
#include<string>
using namespace std;
void printCoinPer()
{
}
int coinPermutations(vector<int>& coins, int amt)
{
vector<int> strg(amt + 1, 0);
strg[0] = 1;
for(int s = 1; s < strg.size(); s++)
{
for(int c = 0; c < coins.size(); c++)
{
int i = s - coins[c];
if(i >= 0)
{
strg[s] += strg[i];
}
}
}
return strg[strg.size() - 1];
}
int coinCombinations(vector<int>& coins, int amt)
{
vector<int> strg(amt + 1, 0);
strg[0] = 1;
for(int c = 0; c < coins.size(); c++)
{
for(int s = 1; s < strg.size(); s++)
{
int i = s - coins[c];
if(i >= 0)
{
strg[s] += strg[i];
}
}
}
return strg[strg.size() - 1];
}
int main(int argc, char** argv)
{
vector<int> coins{2, 3, 5, 6};
int amt = 7;
cout << coinPermutations(coins, amt) << endl;
cout << coinCombinations(coins, amt) << endl;
}
| true |
1c7d3e9b4b3d9786d01c023c8c8f22cd1693c93e
|
C++
|
levonala/cpp
|
/Classes/Classes/Student.cpp
|
UTF-8
| 218 | 3.015625 | 3 |
[] |
no_license
|
#include "Student.hpp"
Student::Student(unsigned int id, std::string name)
{
id_ = id;
name_ = name;
}
unsigned int Student::getId()
{
return id_;
}
std::string Student::getName()
{
return name_;
}
| true |
355e7249e15cc0b4d20b72bf8c2599b43451911e
|
C++
|
RTCSD2016/notes
|
/grp_cpp/_Old_Common_Files/OPER_INT.HPP
|
UTF-8
| 13,908 | 2.765625 | 3 |
[] |
no_license
|
//*************************************************************************************
// OPER_INT.HPP
// This file contains definitions of structures (or classes) and functions used
// for the generic character-mode operator interface for DOS or Easy Windows.
//
// The current version has been modified from a regular-C application for Windows
// into a basically regular-C application with a C++-style user interface.
//
// Version
// Original: copyright 1993, DM Auslander
// Modified: 1-94 JR non-C++ version added
// 2-94 JR Screen Manager stuff added
// 2-7-94 JR Went with op_xxxxx names only
// 8-94 JR Ported to Visual C++ DOS/QuickWin
// 9-94 JR Version done for Visual C++ running under Windows
// 12-94 JR C++ interface added to Windows app. in C version
// 6-95 JR Changed from function keys to control keys
//*************************************************************************************
#define OPER_INT_HPP // Variable to prevent multiple inclusions
#if !defined (BASE_OBJ_HPP) // If the base-object header (which contains the
#include <BASE_OBJ.HPP> // definition of a list handling object) hasn't
#endif // yet been included, include it now
#define TOP_BORDER 3 // Number of rows in area where window title goes
#define MAX_ITEMS 20 // Maximum number of input items or output items
#define MAX_KEYS 8 // or keys this program can support
#define MAX_INS 20 // These are the maximum number of input,
#define MAX_OUTS 20 // output, and key items allowed
#define MAX_KEYS 8
#define COL_INTITLE 1 // Define columns in which screen items begin.
#define COL_TYPEIN 16 // Windows uses pixels, DOS characters; these are
#define COL_INDATA 33 // all character coordinates, so Windows version
#define COL_OUTTITLE 48 // will multiply them by pixels-per-character
#define COL_OUTDATA 63 // sizes in determining where to draw stuff.
#define SCREEN_WIDTH 78 // dma added
//=====================================================================================
// External Function: UserMain
// In a Windows application, there is no main() which can be edited by the user.
// We want DOS applications to be fully code-compatible with Windows applications
// here. So we tell the user to write a function called UserMain() which acts
// like main() as far as he is concerned; and we write the code which replaces
// WinMain() or Main() in the program here. It returns int just like a main().
extern int UserMain (void);
//-------------------------------------------------------------------------------------
// Structure: OW_Rect
// This structure holds 4 numbers describing the boundaries of a rectangle. It's
// a replacement for the RECT structure used in the Windows API - because we
// don't have a definition of that structure in DOS.
typedef struct tagRECT
{
int left, top, right, bottom;
} RECT;
//=====================================================================================
// Class: CDataItem
// This class represents one input or output item. Deriving it from CBaseObj
// makes it easy to keep DataItems in a list. A DataItem has member functions
// which allow it to display itself and return its contents and...............
//=====================================================================================
// These are the types of data which can be entered and displayed
enum DataType {DEC_INT, HEX_INT, DEC_LONG, HEX_LONG, FLOAT, DOUBLE, LONG_DBL, STRING};
// An item can be of either input or output type. This enum determines which.
enum IO_Type {DATA_INPUT, DATA_OUTPUT};
class CDataItem
{
private:
DataType Type; // Type - int, string, double, whatever
char* Label; // Label text displayed next to item's value
void* pData; // Pointer to the data which is being shown
RECT ScreenRect; // Rectangle holds borders of area for item
IO_Type InOrOut; // Is this an input or output item?
void Data2String (void*, // Converts data in numeric format to a string
char*, DataType); // for display
int NumberInList; // Number index of item in the list
public:
CDataItem (DataType, IO_Type, // Constructor makes an item of given type
const char*, void*, // and figures out where it should go
int); // etc.
~CDataItem (void);
void SetValue (const char*); // Set data to equal what user typed
const char* GetLabel (void); // Update display on the screen
const char* GetData (void); // Returns data as a character string
void Paint (void); // Data item displays itself on the screen
};
//=====================================================================================
// Class: CDataItemList
// This class is derived from CListObj, which faciliates keeping a list of some
// objects (in this case, CDataItem's) derived from CBaseObj. Two data item
// lists are kept by an operator window, one for input and one for output items.
//=====================================================================================
class CDataItemList : public CBasicList
{
private:
IO_Type InOrOut; // Is this input or output item?
int ListIndex; // Counts elements in the list
public:
CDataItemList (IO_Type);
~CDataItemList (void);
void Insert (DataType, const char*, void*); // Create an item and put in list
boolean PaintOne (void); // Paint one item in the list
void PaintAll (void); // or paint the whole list full
};
//=====================================================================================
// Class: CKeyItem
// This class represents a key which can be pressed by the user. It contains a
// label to be displayed at the bottom of the screen which shows what the key
// does and a pointer to the function which will run when the key is pressed.
//=====================================================================================
class CKeyItem
{
private:
int KeyChar; // Character which activates key's function
void (*KeyFunction)(); // Function which runs when key's pressed
int SerialNumber; // Unique number for each key item
public:
char line1[16]; // First line of text to be displayed
char line2[16]; // Second line of key label text
// Constructor takes key number, 2 label lines, and pointer to key function
CKeyItem (int, const char*, const char*, void (*)(), int);
~CKeyItem (void);
void RunKeyFunction (void); // Run the function in response to key press
int GetKeyChar (void) // Function to return the number of the key
{ return KeyChar; } // associated with this item
void Paint (void); // Function draws key definition on screen
};
//=====================================================================================
// Class: CKeyItemList
// This class keeps a list of the above defined key mapping items.
//=====================================================================================
class CKeyItemList : public CBasicList
{
public:
CKeyItemList (void);
~CKeyItemList (void);
void Insert (int, const char*, const char*, void (*)(void), int);
};
//=====================================================================================
// Class: COperatorWindow
// This class holds together all the stuff needed to run an operator window.
// etc.
//=====================================================================================
class COperatorWindow
{
private:
CDataItemList* InputItems; // List object holding input data items
CDataItemList* OutputItems; // List of output-only items
CKeyItemList* KeyItems; // List of key mappings
char* Title; // Title of window
int InputIndex; // Currently selected character in buffer
void SaveCurrentInput (void); // Save user input into highlighted data field
void ShowAll (void); // Tells items in window to show themselves
int KeyItemSerialNumber; // Gives unique numbers to key items
#if defined (_WINDOWS) // These functions are only needed in Windows:
void ReadChar (MSG*); // Read a character the user typed into buffer
void KeyPress (MSG*); // Check what kind of key the user pressed
#endif
public:
char* InputBuffer; // Buffer for storing user's input
COperatorWindow (const char*); // Constructor assigns a window title
~COperatorWindow (void); // Destructor, uh... destructs stuff
// A whole bunch of overloaded methods allow user to add input and output
// items whose data is of various types.
void AddInputItem (const char*, int*);
void AddInputItem (const char*, long*);
void AddInputItem (const char*, float*);
void AddInputItem (const char*, double*);
void AddInputItem (const char*, long double*);
void AddInputItem (const char*, char*);
void AddOutputItem (const char*, int*);
void AddOutputItem (const char*, long*);
void AddOutputItem (const char*, float*);
void AddOutputItem (const char*, double*);
void AddOutputItem (const char*, long double*);
void AddOutputItem (const char*, char*);
// Here's the function we call to add a user key to the list
void AddKey (int, const char*, const char*, void (*)(void));
void Paint (void); // Function to repaint window when uncovered
void Display (void); // Call this to repaint entire window
void CheckKeyboard (void); // The part of Update() which processes keys
void Update (void); // Incremental, low-latency repainting
void Close (void); // Stop displaying it, but keep it around
friend class CWindowState; // This state needs access to item lists
};
#if defined (_TRANRUN3_) // This part's only for TranRun3 use
//=====================================================================================
// Class: CWindowState
// This class encapsulates a transition logic state which displays an operator
// window. In a given state, a given operator window interface is displayed.
// The design strategy is to use one window state of this type for each operator
// window which needs to be displayed. This class only has meaning in a project
// which has both operator windows and the TranRun scheduler, so only include it
// if the flag _TRANRUN_ has been defined.
class CWindowState : public CState
{
private:
COperatorWindow* pOpWin;
public:
CWindowState (char*); // Give window title to the constructor
void Entry (void); // Get the window painted at first
void Action (void); // Update the window periodically
void Close (void); // Tell operator window to close itself
// A bunch of overloaded methods to add input and output items whose data is
// of various types; these methods follow those in COperatorWindow
void AddInputItem (const char*, int*);
void AddInputItem (const char*, long*);
void AddInputItem (const char*, float*);
void AddInputItem (const char*, double*);
void AddInputItem (const char*, long double*);
void AddInputItem (const char*, char*);
void AddOutputItem (const char*, int*);
void AddOutputItem (const char*, long*);
void AddOutputItem (const char*, float*);
void AddOutputItem (const char*, double*);
void AddOutputItem (const char*, long double*);
void AddOutputItem (const char*, char*);
// Here's the function we call to add a user key to the list
void AddKey (int, const char*, const char*, void (*)(void));
};
#endif // End of TranRun3 specific stuff
//-------------------------------------------------------------------------------------
// Global variables
// CurrentOpWin: At any given time, there is one currently running operator
// window. This pointer is to point to that window object. This
// allows the object to be given messages by Windows when some-
// thing happens like a key press, etc. If this variable is NULL
// no operator window has been set up, or it's turned off.
// SelectedInput: Just one item in the input item list may be selected at any
// given time. This pointer points to the selected one.
extern COperatorWindow* CurrentOpWin;
extern CDataItem* SelectedInput;
| true |
5cd7665089f1541650d2536a85737a75e1d994ff
|
C++
|
AlejandroMB1/OrangoTango
|
/OrangoTango/factura.cpp
|
UTF-8
| 1,771 | 2.734375 | 3 |
[] |
no_license
|
#include "factura.h"
Factura::Factura(){
empresa = "";
nitEmpresa = "";
telEmpresa = "";
cliente = "";
numeroFactura = "";
fechaFactura = "";
precioItems = "";
cantidadItems = "";
totalPagar = "";
}
QString Factura::getEmpresa(){
return empresa;
}
void Factura::setEmpresa(QString miEmpresa){
empresa = miEmpresa;
}
QString Factura::getNitEmpresa(){
return nitEmpresa;
}
void Factura::setNitEmpresa(QString miNit){
nitEmpresa = miNit;
}
QString Factura::getTelEmpresa(){
return telEmpresa;
}
void Factura::setTelEmpresa(QString miTel){
telEmpresa = miTel;
}
QString Factura::getCliente(){
return cliente;
}
void Factura::setCliente(QString miCliente){
cliente = miCliente;
}
QString Factura::getNumeroFactura(){
return numeroFactura;
}
void Factura::setNumeroFactura(QString miNumero){
numeroFactura = miNumero;
}
QString Factura::getFechaFactura(){
return fechaFactura;
}
void Factura::setFechaFactura(QString miFecha){
fechaFactura = miFecha;
}
Producto* Factura::getItems(){
int p = items.size();
int i = 0;
while(i<p){
return items[i];
i++;
}
return 0;
}
void Factura::setItems(Producto *miItem){
items.append(miItem);
}
QString Factura::getPrecioItems(){
return precioItems;
}
void Factura::setPrecioItems(QString miPrecio){
precioItems = miPrecio;
}
QString Factura::getCantidadItems(){
return cantidadItems;
}
void Factura::setCantidadItems(QString miCantidad){
cantidadItems = miCantidad;
}
QString Factura::getTotalPagar(){
return totalPagar;
}
void Factura::setTotalPagar(QString miTotal){
totalPagar = miTotal;
}
| true |
c528b6930715f8e0453e012b36ad9d2057fb1091
|
C++
|
RiceReallyGood/nowcoder
|
/jzOffer/28_MoreThanHalfNum.h
|
UTF-8
| 551 | 3.125 | 3 |
[] |
no_license
|
#include <vector>
using namespace std;
class Solution {
public:
int MoreThanHalfNum_Solution(vector<int> numbers) {
int candidate = 0, count = 0;
for(int num : numbers){
if(count == 0){
candidate = num;
count = 1;
}
else if(num == candidate) count++;
else count--;
}
count = 0;
for(int num : numbers)
if(num == candidate) count++;
if(count > numbers.size() / 2) return candidate;
return 0;
}
};
| true |
9af4845e80b82d77552f8ebccc745d99c04ed7b7
|
C++
|
ashkon-zariv/MaximumFlowProblem
|
/FHflowgraph.h
|
UTF-8
| 12,771 | 2.828125 | 3 |
[] |
no_license
|
// File FHflowGraph.h EXPERIMENT
// Template definitions for FHflowGraph.
#ifndef FHflowGraph_H
#define FHflowGraph_H
#include <limits.h>
#include <utility>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <iostream>
#include <functional>
using namespace std;
template <class Object, typename CostType>
class FHflowVertex
{
typedef FHflowVertex<Object, CostType>* VertPtr;
typedef map<VertPtr, CostType> EdgePairList;
public:
static int n_sort_key;
static stack<int> key_stack;
static enum { SORT_BY_DATA, SORT_BY_DIST } e_sort_type;
static bool SetNSortType( int which_type );
static void pushSortKey() { key_stack.push(n_sort_key); }
static void popSortKey() { n_sort_key = key_stack.top();
key_stack.pop(); };
static int const INFINITY = INT_MAX;
EdgePairList flow_adj_list, res_adj_list;
Object data;
CostType dist;
VertPtr next_in_path;
FHflowVertex( const Object & x = Object() );
void addToFlowAdjList(VertPtr neighbor, CostType cost);
void addToResAdjList(VertPtr neighbor, CostType cost);
bool operator<( const FHflowVertex<Object, CostType> & rhs) const;
const FHflowVertex<Object, CostType> & operator=
( const FHflowVertex<Object, CostType> & rhs);
void showFlowAdjList();
void showResAdjList();
};
template <class Object, typename CostType>
int FHflowVertex<Object, CostType>::n_sort_key
= FHflowVertex<Object, CostType>::SORT_BY_DATA;
template <class Object, typename CostType>
stack<int> FHflowVertex<Object, CostType>::key_stack;
// ------------------------------------------------------
template <class Object, typename CostType>
bool FHflowVertex<Object, CostType>::SetNSortType( int which_type )
{
switch (which_type)
{
case SORT_BY_DATA:
case SORT_BY_DIST:
n_sort_key = which_type;
return true;
default:
return false;
}
}
template <class Object, typename CostType>
FHflowVertex<Object, CostType>::FHflowVertex(const Object & x)
: data(x), dist((CostType)INFINITY),
next_in_path(NULL)
{
// nothing to do
}
template <class Object, typename CostType>
void FHflowVertex<Object, CostType>::addToResAdjList
(FHflowVertex<Object, CostType> *neighbor, CostType cost)
{
res_adj_list[neighbor] = cost;
}
template <class Object, typename CostType>
void FHflowVertex<Object, CostType>::addToFlowAdjList
(FHflowVertex<Object, CostType> *neighbor, CostType cost)
{
flow_adj_list[neighbor] = cost;
}
template <class Object, typename CostType>
bool FHflowVertex<Object, CostType>::operator<(
const FHflowVertex<Object, CostType> & rhs) const
{
switch (n_sort_key)
{
case SORT_BY_DIST:
return (dist < rhs.dist);
case SORT_BY_DATA:
return (data < rhs.data);
default:
return false;
}
}
template <class Object, typename CostType>
const FHflowVertex<Object, CostType> & FHflowVertex<Object, CostType>
::operator=(const FHflowVertex<Object, CostType> & rhs)
{
flow_adj_list = rhs.flow_adj_list;
res_adj_list = rhs.res_adj_list;
data = rhs.data;
dist = rhs.dist;
next_in_path = rhs.next_in_path;;
return *this;
}
template <class Object, typename CostType>
void FHflowVertex<Object, CostType>::showResAdjList()
{
EdgePairList::iterator iter;
cout << "Residual Adj List for " << data << ": ";
for (iter = res_adj_list.begin(); iter != res_adj_list.end(); ++iter)
cout << iter->first->data << "(" << iter->second << ") ";
cout << endl;
}
template <class Object, typename CostType>
void FHflowVertex<Object, CostType>::showFlowAdjList()
{
EdgePairList::iterator iter;
cout << "Flow Adj List for " << data << ": ";
for (iter = flow_adj_list.begin(); iter != flow_adj_list.end(); ++iter)
cout << iter->first->data << "(" << iter->second << ") ";
cout << endl;
}
//============================================================================
template <class Object, typename CostType>
class FHflowGraph
{
// internal typedefs to simplify syntax
typedef FHflowVertex<Object, CostType> Vertex;
typedef FHflowVertex<Object, CostType>* VertPtr;
typedef map<VertPtr, CostType> EdgePairList;
typedef set<VertPtr> VertPtrSet;
typedef set<Vertex> VertexSet;
private:
VertPtrSet vert_ptr_set;
VertPtr start_vert_ptr, end_vert_ptr;
VertexSet vertex_set;
public:
FHflowGraph () {}
void addEdge(const Object &source, const Object &dest, CostType cost);
VertPtr addToVertexSet(const Object & object);
void showFlowAdjTable();
void showResAdjTable();
bool setStartVert(const Object &x);
bool setEndVert(const Object &x);
void clear();
CostType findMaxflow();
private:
VertPtr getVertexWithThisData(const Object & x);
bool establishNextFlowPath();
CostType getLimitingFlowOnResPath();
bool adjustPathByCost(CostType cost);
CostType getCostOfResEdge(VertPtr src, VertPtr dst);
bool addCostToResEdge(VertPtr src, VertPtr dst, CostType cost);
bool addCostToFlowEdge(VertPtr src, VertPtr dst, CostType cost);
};
template <class Object, typename CostType>
FHflowVertex<Object, CostType>* FHflowGraph<Object, CostType>::addToVertexSet(
const Object & object)
{
pair<typename VertexSet::iterator, bool> ret_val;
VertPtr v_ptr;
// save sort key for client
Vertex::pushSortKey();
Vertex::SetNSortType(Vertex::SORT_BY_DATA);
// build and insert vertex into master list
ret_val = vertex_set.insert( Vertex(object) );
// get pointer to this vertex and put into vert pointer list
v_ptr = (VertPtr)&*ret_val.first;
vert_ptr_set.insert(v_ptr);
Vertex::popSortKey(); // restore client sort key
return v_ptr;
}
template <class Object, typename CostType>
void FHflowGraph<Object, CostType>::clear()
{
vertex_set.clear();
vert_ptr_set.clear();
}
template <class Object, typename CostType>
void FHflowGraph<Object, CostType>::addEdge(
const Object &source, const Object &dest, CostType cost )
{
VertPtr src, dst;
src = addToVertexSet(source);
dst = addToVertexSet(dest);
src->addToResAdjList(dst, cost);
dst->addToResAdjList(src, 0);
src->addToFlowAdjList(dst, 0);
}
template <class Object, typename CostType>
bool FHflowGraph<Object, CostType>::setStartVert(const Object &x)
{
if( x.length() == NULL)
return false;
start_vert_ptr = getVertexWithThisData(x);
return true;
}
template <class Object, typename CostType>
bool FHflowGraph<Object, CostType>::setEndVert(const Object &x)
{
if( x.length() == NULL)
return false;
end_vert_ptr = getVertexWithThisData(x);
return true;
}
template <class Object, typename CostType>
void FHflowGraph<Object, CostType>::showResAdjTable()
{
typename VertPtrSet::iterator iter;
cout << "------------------------ \n";
for (iter = vert_ptr_set.begin(); iter != vert_ptr_set.end(); ++iter)
(*iter)->showResAdjList();
cout << endl;
}
template <class Object, typename CostType>
void FHflowGraph<Object, CostType>::showFlowAdjTable()
{
typename VertPtrSet::iterator iter;
cout << "------------------------ \n";
for (iter = vert_ptr_set.begin(); iter != vert_ptr_set.end(); ++iter)
(*iter)->showFlowAdjList();
cout << endl;
}
template <class Object, typename CostType>
CostType FHflowGraph<Object, CostType>::findMaxflow()
{
typename VertPtrSet::iterator v_iter;
typename EdgePairList::iterator edge_pr_iter;
VertPtr vp;
CostType min_cost, total_flow = 0;
for(v_iter = vert_ptr_set.begin(); v_iter != vert_ptr_set.end(); ++v_iter)
{
establishNextFlowPath();
min_cost = getLimitingFlowOnResPath();
if(!adjustPathByCost(min_cost))
break;
}
for (edge_pr_iter = start_vert_ptr->flow_adj_list.begin();
edge_pr_iter != start_vert_ptr->flow_adj_list.end();
edge_pr_iter++)
total_flow += edge_pr_iter->second;
return total_flow;
}
template <class Object, typename CostType>
bool FHflowGraph<Object, CostType>::establishNextFlowPath()
{
typename VertPtrSet::iterator v_iter;
typename EdgePairList::iterator edge_pr_iter;
VertPtr w_ptr, v_ptr, s_ptr;
CostType cost_vw;
queue<VertPtr> partially_processed_verts;
s_ptr = getVertexWithThisData(start_vert_ptr->data);
if (s_ptr == NULL)
return false;
for (v_iter = vert_ptr_set.begin();
v_iter != vert_ptr_set.end(); ++v_iter)
{
(*v_iter)->dist = Vertex::INFINITY;
(*v_iter)->next_in_path = NULL;
}
s_ptr->dist = 0;
partially_processed_verts.push( s_ptr );
// outer loop
while( !partially_processed_verts.empty() )
{
v_ptr = partially_processed_verts.front();
partially_processed_verts.pop();
for (edge_pr_iter = v_ptr->res_adj_list.begin();
edge_pr_iter != v_ptr->res_adj_list.end();
edge_pr_iter++)
{
w_ptr = edge_pr_iter->first;
cost_vw = edge_pr_iter->second;
if((v_ptr->dist + cost_vw < w_ptr->dist) && cost_vw != 0)
{
w_ptr->dist = v_ptr->dist + cost_vw;
w_ptr->next_in_path = v_ptr;
partially_processed_verts.push(w_ptr);
if(w_ptr == end_vert_ptr)
return true;
}
}
}
return false;
}
template <class Object, typename CostType>
CostType FHflowGraph<Object, CostType>::getLimitingFlowOnResPath()
{
VertPtr vp, np;
CostType min = INT_MAX;
stack<VertPtr> path_stack;
if (start_vert_ptr == NULL || end_vert_ptr == NULL)
return CostType();
for (vp = end_vert_ptr; vp != start_vert_ptr; vp = vp->next_in_path)
{
if(vp->next_in_path == NULL)
return false;
path_stack.push(vp);
}
path_stack.push(vp);
while (true)
{
vp = path_stack.top();
path_stack.pop();
if ( path_stack.empty() )
break;
np = path_stack.top();
if(getCostOfResEdge(vp , np) < min)
min = getCostOfResEdge(vp , np);
}
return min;
}
template <class Object, typename CostType>
bool FHflowGraph<Object, CostType>::adjustPathByCost(CostType cost)
{
VertPtr vp, np;
stack<VertPtr> path_stack;
if (start_vert_ptr == NULL || end_vert_ptr == NULL)
return CostType();
for (vp = end_vert_ptr; vp != start_vert_ptr; vp = vp->next_in_path)
{
if(vp->next_in_path == NULL)
return false;
path_stack.push(vp);
}
path_stack.push(vp);
while (true)
{
vp = path_stack.top();
path_stack.pop();
if ( path_stack.empty() )
break;
np = path_stack.top();
if(!addCostToResEdge(vp, np, -cost))
return false;
if(!addCostToResEdge(np, vp, cost))
return false;
if(!addCostToFlowEdge(vp, np, cost))
if(!addCostToFlowEdge(np, vp, -cost))
return false;
}
return true;
}
template <class Object, typename CostType>
CostType FHflowGraph<Object, CostType>::getCostOfResEdge
(VertPtr src, VertPtr dst)
{
typename EdgePairList::iterator edge_pr_iter;
for (edge_pr_iter = src->res_adj_list.begin();
edge_pr_iter != src->res_adj_list.end();
edge_pr_iter++)
{
if ( edge_pr_iter->first == dst )
return edge_pr_iter->second;
}
return INT_MAX;
}
template <class Object, typename CostType>
bool FHflowGraph<Object, CostType>::addCostToResEdge(
VertPtr src, VertPtr dst, CostType cost)
{
typename EdgePairList::iterator edge_pr_iter;
for (edge_pr_iter = src->res_adj_list.begin();
edge_pr_iter != src->res_adj_list.end();
edge_pr_iter++)
{
if ( edge_pr_iter->first == dst )
{
edge_pr_iter->second = edge_pr_iter->second + cost;
return true;
}
}
return false;
}
template <class Object, typename CostType>
bool FHflowGraph<Object, CostType>::addCostToFlowEdge
(VertPtr src, VertPtr dst, CostType cost)
{
typename EdgePairList::iterator edge_pr_iter;
for (edge_pr_iter = src->flow_adj_list.begin();
edge_pr_iter != src->flow_adj_list.end();
edge_pr_iter++)
{
if ( edge_pr_iter->first == dst )
{
edge_pr_iter->second = edge_pr_iter->second + cost;
return true;
}
}
return false;
}
template <class Object, typename CostType>
FHflowVertex<Object, CostType>* FHflowGraph<Object, CostType>::
getVertexWithThisData(const Object & x)
{
typename VertexSet::iterator find_result;
Vertex vert(x);
Vertex::pushSortKey(); // save client sort key
Vertex::SetNSortType(Vertex::SORT_BY_DATA);
find_result = vertex_set.find(vert);
Vertex::popSortKey(); // restore client value
if ( find_result == vertex_set.end() )
return NULL;
return (VertPtr)&*find_result;
}
#endif
| true |
bb00f1ba78897372d675fa6bdafc66d4ce186ba9
|
C++
|
hichoe95/BOJ
|
/2261.cpp
|
UTF-8
| 1,372 | 3.109375 | 3 |
[] |
no_license
|
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int dist(int a, int b, int x, int y){
return (a-x)*(a-x) + (b-y)*(b-y);
}
bool cmp(const pair<int,int> &a, const pair<int,int> &b){
return a.second<b.second;
}
int find_dist(vector<pair<int,int> > &v,int start, int end){
int m = -1;
for(int i=start ;i<= end;i++)
for(int j=i+1 ;j<= end; j++){
int d = dist(v[i].first,v[i].second,v[j].first,v[j].second);
if(m==-1|| m>d) m = d;
}
return m;
}
int solve(vector<pair<int,int> > &v, int start, int end){
if(end-start+1 <=3) return find_dist(v,start,end);
int mid = (start+end)/2;
int ret = min(solve(v,start,mid),solve(v,mid+1,end));
vector<pair<int,int> > tmp;
for(int i=start ; i<=end ; i++){
int d = v[i].first - v[mid].first;
if(d*d < ret) tmp.push_back(v[i]);
}
sort(tmp.begin(), tmp.end(), cmp);
int s = tmp.size();
for(int i=0 ; i<s ; i++)
for(int j=i+1 ; j<s ; j++){
int y = tmp[i].second - tmp[j].second;
if(y*y < ret){
int d = dist(tmp[i].first,tmp[i].second,tmp[j].first,tmp[j].second);
ret = ret<d ? ret : d;
}
else break;
}
return ret;
}
int main(){
ios_base::sync_with_stdio(false);
int n;
cin >> n;
vector<pair<int,int> > v(n);
for(int i=0 ;i<n;i++) cin >> v[i].first >> v[i].second;
sort(v.begin(),v.end());
cout << solve(v,0,n-1);
return 0;
}
| true |
ce821ce89d05262e8af7b05b294318e6f76dabe4
|
C++
|
disha03/my_notes
|
/april_may/search min in sorted array.cpp
|
UTF-8
| 1,021 | 2.703125 | 3 |
[] |
no_license
|
int Solution::findMin(const vector<int> &A) {
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details
int start=0,end=A.size()-1,n=A.size(),index=0,mid,prev,next;
while(start<=end)
{
if(start==end)
{
return A[start];
}
mid=start+(end-start)/2;
if(mid!=0){
prev=mid-1;
}
else{
prev=A.size()-1;
}
if(mid!=n-1){
next =mid+1;
}
else{
next=0;
}
if(A[mid]<=A[prev] && A[mid]<=A[next])
{
return A[mid];
}
else if(A[mid]<=A[end]){
end=mid;
}
else if(A[mid]>=A[start])
{
start=mid;
}
}
return A[0];
}
| true |
a44c73e582c910312526e0f07c25c49bcb923479
|
C++
|
LeulShiferaw/ProjectEuler
|
/PE11/PE11/main.cpp
|
UTF-8
| 1,239 | 3.28125 | 3 |
[] |
no_license
|
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream file("numbers.txt");
if (!file.is_open())
{
cerr << "File error!" << endl;
return 0;
}
int grid[20][20];
for (int i = 0; i < 20; ++i)
{
for (int j = 0; j < 20; ++j)
{
file >> grid[i][j];
}
}
file.close();
long long greatest = 1;
for (int i = 0; i < 20 - 4; ++i)
{
long long temp = 1;
for (int j = 0; j < 4; ++j)
{
temp *= grid[i][j];
}
if (temp > greatest)
greatest = temp;
}
cout << greatest << endl;
for (int i = 0; i < 20 - 4; ++i)
{
long long temp = 1;
for (int j = 0; j < 4; ++j)
{
temp *= grid[j][i];
}
if (temp > greatest)
greatest = temp;
}
cout << greatest << endl;
for (int i = 0; i < 20 - 4; ++i)
{
for (int j = 0; j < 20 - 4; ++j)
{
long long temp = 1;
for (int k = 0; k < 4; ++k)
{
temp *= grid[i + k][j + k];
}
if (temp > greatest)
greatest = temp;
}
}
cout << greatest << endl;
for (int i = 0; i < 20-4; ++i)
{
for (int j = 19; j >= 3; --j)
{
long long temp = 1;
for (int k = 0; k < 4; ++k)
{
temp *= grid[i + k][j - k];
}
if (temp > greatest)
greatest = temp;
}
}
cout << greatest << endl;
return 0;
}
| true |
ee976b8c0a29e8925c580cc74a309cc4866115db
|
C++
|
artemreyt/ConfigHolder
|
/Logger/include/BaseLogger.hpp
|
UTF-8
| 2,078 | 3.21875 | 3 |
[] |
no_license
|
#ifndef BASELOGGER_HPP
#define BASELOGGER_HPP
#include <string>
#include <memory>
#include <iostream>
#include <stdexcept>
#include <fstream>
namespace Logger
{
enum class t_level : unsigned int
{
ERROR,
WARNING,
INFO,
DEBUG
};
class BaseLogger
{
public:
BaseLogger(std::ostream *stream, t_level level);
BaseLogger(BaseLogger &&other) noexcept ;
BaseLogger &operator=(const BaseLogger& other) noexcept = default;
BaseLogger &operator=(BaseLogger &&other) noexcept ;
void debug(const std::string &msg);
void info(const std::string &msg);
void warn(const std::string &msg);
void error(const std::string &msg);
void set_level(t_level level);
t_level get_level() const;
virtual void flush();
protected:
t_level level_;
std::ostream *stream_;
private:
virtual void log(const std::string &msg, t_level level);
};
class StdoutLogger : public BaseLogger
{
public:
explicit StdoutLogger(t_level level = t_level::INFO);
StdoutLogger(StdoutLogger &&other) noexcept ;
StdoutLogger &operator=(const StdoutLogger &other) noexcept = default;
StdoutLogger &operator=(StdoutLogger &&other) noexcept = default;
};
class StderrLogger : public BaseLogger
{
public:
explicit StderrLogger(t_level level = t_level::INFO);
StderrLogger(StderrLogger &&other) noexcept ;
StderrLogger &operator=(const StderrLogger &other) noexcept = default;
StderrLogger &operator=(StderrLogger &&other) noexcept = default;
};
class FileLogger : public BaseLogger
{
public:
explicit FileLogger(const std::string &path, t_level level = t_level::INFO);
FileLogger(FileLogger &&other) noexcept;
FileLogger &operator=(const FileLogger &other) = delete ;
FileLogger &operator=(FileLogger &&other) noexcept ;
private:
std::ofstream outfile_;
};
}
#endif // BASELOGGER_HPP
| true |
3fec833770575cdb96158d39de38ba54afb97b0f
|
C++
|
Oxid2178/PraxisWissenC-NewStd
|
/PraxisWissenC++NewStd/PraxisWissenC++NewStd/BarChartView.h
|
UTF-8
| 407 | 2.578125 | 3 |
[] |
no_license
|
#pragma once
#include "IObserver.h"
#include "SpreadsheetModel.h"
class BarChartView : public IObserver
{
private:
SpreadsheetModel& model;
public:
BarChartView(SpreadsheetModel& theModel) :
model{ theModel } {}
virtual int getId() override
{
return 2;
}
virtual void update() override
{
std::cout << "Update of BarChartView." << "\n";
}
};
| true |
7598908b03fcabb2d092a920f9d10559ff687ab9
|
C++
|
1816013/ActionProject
|
/Action/ActionProject/Game/Player/SwordEquip.h
|
SHIFT_JIS
| 1,090 | 2.59375 | 3 |
[] |
no_license
|
#pragma once
#include "Equipment.h"
class FanCollider;
class ShadowClone;
class SwordEquip :
public Equipment
{
private:
int frame_;
std::shared_ptr<Player>& player_;
FanCollider* fanCollider_ = nullptr;
using func_t = void(SwordEquip::*)();
ShadowClone* shadow_;
Vector2f offset_ = Vector2f::ZERO;
func_t updater_;
SlashShape slash_;
bool isRight_;
void NomalUpdate();
public:
/// <summary>
/// CX^X
/// </summary>
/// <param name="p">vC[</param>
/// <param name="cm">RWǗp</param>
/// <param name="c">J</param>
SwordEquip(std::shared_ptr<Player>& p,
std::shared_ptr<CollisionManager>cm,
std::shared_ptr<Camera> c,
ShadowClone* shadow = nullptr);
/// <summary>
/// U
/// </summary>
/// <param name="player">vC[</param>
/// <param name="input">͏</param>
void Attack(const Player& player, const Input& input, Vector2f offset = Vector2f::ZERO)override;
/// <summary>
/// XV
/// </summary>
void Update();
/// <summary>
/// `
/// </summary>
void Draw();
};
| true |
66dc16ec4598ec2d98a899f2c6c67f3c1339e7df
|
C++
|
Dpham181/CPSC-323-PROJECT-2-
|
/PROJECT 2 SUBMIT (DANH PHAM)/PROJECT 2 SUBMIT (DANH PHAM)/SOURCE CODE/prase.h
|
UTF-8
| 43,862 | 2.8125 | 3 |
[] |
no_license
|
/*
Name: Danh Pham
Course: CPSC 323 SECTION 1
PRoject Name: PROJECT_2 SYNTAX ANNALYSIS
FILES CONTAIN: phrase.h, prase.h, main.cpp
PURPOSE: This program use to parse the tokens from the text file by using top-down parse desent. It gets all the tokens and push back
vector then find the gammar rule that fit to the Rat17f rule. System output to the terminal and Lexem can be find in lex.txt when u run
the execuable file(RAT17F).
*/
#ifndef PARSE_H
#define PARSE_H
#include <vector>
#include <iostream>
#include <string>
#include <fstream>
#include <windows.h>
#include "phrase.h"
using namespace std;
class Alloperation
{
public:
void start();
void add(mylist n);
private:
void check_length();
void display_errors();
void start_point();
void Opt_Function_Definition();
void myfunction();
void Opt_Declaration_List();
void Statement_List();
void Statement_List1();
void Opt_Parameter_List();
void Body();
void Write_statement();
void Read_statement();
void Return_statement();
void Return_statement1();
void Assign_statement();
void if_statement();
void while_statement();
void expression_func();
void Term();
void IDs();
void Factor();
void primary1();
void condition();
void invalid_id();
//all variables
errorlist error_object;
vector<mylist> alltokens;
vector<errorlist>allerrors;
int token_lenth;
int update_index;
int inserted_index;
string * allcontent;
string *alltypes;
int * lineofcode;
bool stop;
};
void Alloperation::add(mylist n)
{
alltokens.push_back(n);
}
//if there is another tokens to parse
void Alloperation::check_length()
{
if (update_index<inserted_index - 1)
update_index++;
else
{
stop = true;
if (allerrors.size() == 0)
{
cout << "...................................." << endl;
cout << "No syntax error" << endl;
}
}
}
void Alloperation::invalid_id() {
if (alltypes[update_index] == "invalid identifier") {
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
error_object.error_name = "invalid identifier, missed ( or , ";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
}
}
void Alloperation::display_errors()
{
stop = true;
allcontent[update_index] = "finish";
alltypes[update_index] = "no type";
cout << "...................................." << endl;
for (vector<errorlist>::iterator it = allerrors.begin(); it != allerrors.end(); ++it)
{
cout << "Error is:" << (*it).error_name << "\t" << "line:" << (*it).error_line << endl;
}
}
void Alloperation::start()
{
stop = false;
token_lenth = alltokens.size();
update_index = 0;
inserted_index = 0;
allcontent = new string[alltokens.size()];
alltypes = new string[alltokens.size()];
lineofcode = new int[alltokens.size()];
for (vector<mylist>::iterator it = alltokens.begin(); it != alltokens.end(); ++it)
{
allcontent[inserted_index] = (*it).content;
alltypes[inserted_index] = (*it).type;
lineofcode[inserted_index] = (*it).line;
inserted_index++;
}
start_point();
}
//it Rat17F rule
void Alloperation::start_point()
{
Opt_Function_Definition();
if (allcontent[update_index] == "%%")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Function Definition'> <Epsilon>"<<endl;
cout << "\n\n";
check_length();
Opt_Declaration_List();
Statement_List();
}
else
{
if (!stop)
{
error_object.error_name = "missed %%";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
}
}
}
void Alloperation::Opt_Function_Definition()
{
first:
if (allcontent[update_index] == "@")
{
myfunction();
if (allcontent[update_index] == "@")
goto first;
}
//if opt_fnction_defination -> empty that mean
}
void Alloperation::myfunction()
{
//we here must remove left recursive by make <Function Definitions> ::= <Function>
cout << "Token:" << alltypes[update_index] << "\t\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << endl;
cout << "<RAT17F> <Opt Function Definitions>" << "%% <Opt Declaration List> <Statement List>\n";
cout << "<Function> @ <Identifier> (<Opt Parameter List>) <Opt Declaration List> <Body>" << endl;
check_length();
cout << "\n\n";
if (alltypes[update_index] == "identifier")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\n\n";
check_length();
afterfirstadentifier:
if (allcontent[update_index] == "(")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\n\n";
check_length();
beforeparameterlist:
Opt_Parameter_List();
if (allcontent[update_index] == ")")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Parameter List'> <Epsilon>" << endl;
cout << "\n\n";
check_length();
afterparameterlist:
Opt_Declaration_List();
Body();
}
else
{
if (!stop)
{
error_object.error_name = "missed ) of parameter list";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
// goto afterparameterlist;
}
}
}
else
{
if (!stop)
{
error_object.error_name = "missed ( of parameter list";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
// goto beforeparameterlist;
}
}
}
else
{
if (!stop)
{
error_object.error_name = "missed identifier";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
//goto afterfirstadentifier;
}
}
}
/*
in this method we do recursion desent for (opt paramater list) and all rules we will used
<Opt Parameter List> ::= <Parameter List> | <Empty>
here it is must to remove left recursion by
<Parameter List> ::= <Parameter> | <Parameter> , <Parameter List>
turned to parameter list ::=parameter parameter list'
parameter list'::=,paramater|empty
<Parameter> ::= <IDs > : <Qualifier>
<Qualifier> ::= integer | boolean | floating
here it is must to remove left recursion by:
<IDs> ::= <Identifier> | <Identifier>, <IDs>
IDs ::= identifier IDs'
IDs'::=,identifier|empty
*/
void Alloperation::Opt_Parameter_List()
{
first:
if (alltypes[update_index] == "identifier")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Opt Parameter List> <Parameter List>" << endl;
cout << "\t" << "<parameter list> <parameter>" << endl;
cout << "\t" << "<Parameter> <IDs >" << endl;
cout << "\t" << "<IDs> <identifier> <IDs'>" << endl;
cout << "\n\n";
check_length();
invalid_id();
second:
if (allcontent[update_index] == ",")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Parameter> <IDs >" << endl;
cout << "\t" << "<IDs> <identifier> <IDs'>" << endl;
cout << "\t" << "<IDs'> ,<identifier> <IDs'>" << endl;
cout << "\n\n";
check_length();
if (alltypes[update_index] == "identifier")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\n\n";
check_length();
goto second;
}
else
{
if (!stop)
{
error_object.error_name = "missed identifier after ,";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
// goto second;
}
}
}
else if (allcontent[update_index] == ";")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\n\n";
check_length();
}
else if (allcontent[update_index] == ":")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << endl;
cout << "\t" << "<Opt Parameter List> <Parameter List>" << endl;
cout << "\t" << "<parameter list> <:>" << endl;
cout << "\t" << "<Parameter> <IDs >" << endl;
cout << "\t" << "<IDs> <identifier> <IDs'>" << endl;
cout << "\t" << "<IDs'> < Epsilon >" << endl;
cout << "\n\n";
check_length();
third:
if (allcontent[update_index] == "integer" || allcontent[update_index] == "boolean" || allcontent[update_index] == "floating")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << endl;
cout << "\t" << "<Opt Parameter List> <Parameter List>" << endl;
cout << "\t" << "<parameter list> <qualifier>" << endl;
cout << "\t" << "<Qualifier>" << " <" << allcontent[update_index] << ">" << endl;
cout << "\n\n";
check_length();
if (allcontent[update_index] == ",")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << endl;
cout << "\t" << "<Opt Parameter List> <Parameter List>" << endl;
cout << "\t" << "<parameter list> ::=<parameter> <parameter list'>" << endl;
cout << "\t" << "<parameter list>'::=,<paramater>" << endl;
cout << "\n\n";
check_length();
if (alltypes[update_index] == "identifier")
{
goto first;
}
else
{
if (!stop)
{
error_object.error_name = "missed identifier after ,";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
//goto second;
}
}
}
}
else
{
if (!stop)
{
error_object.error_name = "must be one of three boolean,integer,floating after :";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
// goto first;
}
}
}
else
{
if (!stop)
{
error_object.error_name = "error on parameter list formating ";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
//goto third;
}
}
}
}
/*
in this method we do recursion desent for (opt Declaration list) and all rules we will used
<Opt Declaration List> ::= <Declaration List> | <Empty>
<Declaration List> := <Declaration> ; | <Declaration> ; <Declaration List>
to remove left recursion turn to <Declartion list> := <Declaration>; <Declaration list'>
<Declaration list'>:=<Declaration>;|empty
<Declaration> ::= <Qualifier > <IDs>
<Qualifier> ::= integer | boolean | floating
<IDs> ::= <Identifier> | <Identifier>, <IDs>
to remove left recursion IDs ::= identifier IDs'
IDs'::=,identifier|empty
*/
void Alloperation::Opt_Declaration_List()
{
if (allcontent[update_index] == "integer" || allcontent[update_index] == "boolean" || allcontent[update_index] == " floating")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << endl;
cout << "\t" << "<Opt Declaration List> <Declaration List> " << endl;
cout << "\t" << " <Declartion list> <Declaration>; <Declaration list'>" << endl;
cout << "\t" << " <Declaration> <Qualifier><ID>" << endl;
cout << "\t" << "<Qualifier>" << " <" << allcontent[update_index] << ">" << endl;
cout << "\n\n";
check_length();
invalid_id();
first:
if (alltypes[update_index] == "identifier")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << endl;
cout << "\t" << "<Opt Declaration List> <Declaration List> " << endl;
cout << "\t" << " <Declartion list> <Declaration>; <Declaration list'>" << endl;
cout << "\t" << " <Declaration> <Qualifier><ID>" << endl;
cout << "\t" << "<IDs> <identifier> <IDs'>" << endl;
cout << "\n\n";
check_length();
if (allcontent[update_index] == ",")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << endl;
cout << "\t" << "<Opt Declaration List> <Declaration List> " << endl;
cout << "\t" << " <Declartion list> <Declaration>; <Declaration list'>" << endl;
cout << "\t" << " <Declaration> <Qualifier><ID>" << endl;
cout << "\t" << "<IDs> <identifier> <IDs'>" << endl;
cout << "\t" << "<IDs'><,identifier>" << endl;
cout << "\n\n";
check_length();
if (alltypes[update_index] == "identifier")
{
goto first;
}
else
{
error_object.error_name = "missed identifier";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
}
}
else if (allcontent[update_index] == ";")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<IDs'> -> Epsilon" << endl;
cout << "\n\n";
check_length();
if (allcontent[update_index] == "integer" || allcontent[update_index] == "boolean" || allcontent[update_index] == " floating")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Opt Declaration List> <Declaration List> " << endl;
cout << "\t" << " <Declartion list> <Declaration>; <Declaration list'>" << endl;
cout << "\t" << " <Declaration list'> <Declaration>;" << endl;
cout << "\t" << " <Declaration> <Qualifier><ID>" << endl;
cout << "\t" << "<Qualifier>" << " <" << allcontent[update_index] << ">" << endl;
cout << "\n\n";
check_length();
goto first;
}
}
else
{
error_object.error_name = "must be new identifier with , or ;";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
}
}
else
{
error_object.error_name = "must be new identifier with , or ;";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
}
}
}
/*
in this method we do recursion desent for (Body) and all rules we will used
<Body> ::= { < Statement List> }
*/
void Alloperation::Body()
{
if (allcontent[update_index] == "{")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Opt Declaration List><Epsilon>" << endl;
cout << "\t" << "<Body> { <Statement List> }" << endl;
cout << "\n\n";
check_length();
first:
Statement_List();
if (allcontent[update_index] == "}")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Statement List'> <Epsilon>" << endl;
cout << "\n\n";
check_length();
}
else
{
if (!stop)
{
error_object.error_name = "missed } for body";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
}
}
}
else
{
if (!stop)
{
error_object.error_name = "missed { for body";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
// goto first;
}
}
}
/*
in this method we do recursion desent for (statement list s ) and all rules we will used
<Statement List> ::= <Statement> | <Statement> <Statement List>
to remove left recursion turn to
<Statement List> ::=<Statement> <Statement List'>
<Statement List'>::<Statement>|empty
<Statement> ::= <Compound> | <Assign> | <If> | <Return> | <Write> | <Read> | <While>
*/
void Alloperation::Statement_List()
{
if (allcontent[update_index] == "write")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Statement> <write>" << endl;
cout << "\t" << "<Write> write (<Expression>);" << endl;
cout << "\n\n";
check_length();
Write_statement();
Statement_List1();
}
else if (allcontent[update_index] == "read")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Statement> <read>" << endl;
check_length();
Read_statement();
Statement_List1();
}
else if (allcontent[update_index] == "if")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Statement> <if>" << endl;
cout << "\t" << "<If> if (<Condition>) <Statement> <If >" << endl;
cout << "\n\n";
check_length();
if_statement();
Statement_List1();
}
else if (allcontent[update_index] == "while")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Statement> <While>" << endl;
cout << "\n\n";
check_length();
while_statement();
Statement_List1();
}
else if (allcontent[update_index] == "return")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Statement List> <Statement> <Statement List'>" << endl;
cout << "\t" << "<Statement> <return>" << endl;
cout << "\t" << "<Return> return <Return'>" << endl;
cout << "\n\n";
check_length();
Return_statement1();
Return_statement();
Statement_List1();
}
//compound statement
else if (allcontent[update_index] == "{")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Statement> {<compound> }" << endl;
cout << "\t" << "<Compound> { <StatementList> }" << endl;
cout << "\n\n";
check_length();
Statement_List1();
if (allcontent[update_index] == "}")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Statement List'> <Epsilon>" << endl;
cout << "\n\n";
check_length();
Statement_List1();
}
else
{
if (!stop)
{
error_object.error_name = "missed } for compound";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
}
}
}
else if (alltypes[update_index] == "identifier")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Statement> <Assign>" << endl;
cout << "\t" << "<Asign> <identifier>" << endl;
cout << "\n\n";
check_length();
Assign_statement();
Statement_List1();
}
else if (allcontent[update_index] == "integer" || allcontent[update_index] == "boolean" || allcontent[update_index] == "floating")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << endl;
cout << "\t" << "<Opt Parameter List> <Parameter List>" << endl;
cout << "\t" << "<parameter list> <qualifier>" << endl;
cout << "\t" << "<Qualifier>" << " <" << allcontent[update_index] << ">" << endl;
cout << "\n\n";
check_length();
Opt_Parameter_List();
Statement_List();
}
else
{
if (!stop&&allcontent[update_index] != "}")
{
error_object.error_name = "missed prefix of statement";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
}
}
}
/*
in this method we do recursion desent for (statement list s ) and all rules we will used
<Statement List> ::= <Statement> | <Statement> <Statement List>
to remove left recursion turn to
<Statement List> ::=<Statement> <Statement List'>
<Statement List'>::<Statement>|empty
<Statement> ::= <Compound> | <Assign> | <If> | <Return> | <Write> | <Read> | <While>
*/
void Alloperation::Statement_List1()
{
if (allcontent[update_index] == "write")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" <<"<Statement List> <Statement> <Statement List'>" << endl;
cout << "\t" <<"<Statement List'> <Statement>" << endl;
cout << "\t" <<"<Statement> <write>" << endl;
cout << "\t" << "<Write> write(<Expression>);" << endl;
cout << "\n\n";
check_length();
Write_statement();
Statement_List();
}
else if (allcontent[update_index] == "read")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Statement List> <Statement> <Statement List'>" << endl;
cout << "\t" << "<Statement List'> <Statement>" << endl;
cout << "\t" << "<Statement> <read>" << endl;
cout << "\n\n";
check_length();
Read_statement();
Statement_List();
}
else if (allcontent[update_index] == "if")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Statement List> <Statement> <Statement List'>" << endl;
cout << "\t" << "<Statement List'> <Statement>" << endl;
cout << "\t" << "<Statement> <if>" << endl;
cout << "\t" << "<If> if (<Condition>) <Statement> <If'>" << endl;
cout << "\n\n";
check_length();
if_statement();
Statement_List();
}
else if (allcontent[update_index] == "while")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Statement List> <Statement> <Statement List'>" << endl;
cout << "\t" << "<Statement List'> <Statement>" << endl;
cout << "\t" << "<Statement> <while>" << endl;
cout << "\n\n";
check_length();
while_statement();
Statement_List();
}
else if (allcontent[update_index] == "return")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Statement List> <Statement> <Statement List'>" << endl;
cout << "\t" << "<Statement List'> <Statement>" << endl;
cout << "\t" << "<Statement> <return>" << endl;
cout << "\n\n";
check_length();
Return_statement1();
Return_statement();
Statement_List();
}
//compound statement
else if (allcontent[update_index] == "{")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Statement List> <Statement> <Statement List'>" << endl;
cout << "\t" << "<Statement List'> <Statement>" << endl;
cout << "\t" << "<Statement> {<compound> }" << endl;
cout << "\n\n";
check_length();
Statement_List();
if (allcontent[update_index] == "}")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Statement List'> <Epsilon>" << endl;
check_length();
Statement_List();
}
else
{
if (!stop)
{
error_object.error_name = "missed } for compound";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
}
}
}
else if (alltypes[update_index] == "identifier")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Statement List> <Statement> <Statement List'>" << endl;
cout << "\t" << "<Statement List'> <Statement>" << endl;
cout << "\t" << "<Statement> <Assign>" << endl;
cout << "\t" << "<Assign> <Identifier> := <Expression>; " << endl;
cout << "\n\n";
check_length();
Assign_statement();
Statement_List();
}
}
/*in this method we do recursion desent for (Read ) and all rules we will used
<Read> ::= read ( <IDs> );
<IDs> ::= <Identifier> | <Identifier>, <IDs>
to remove left recursion IDs ::= identifier IDs'
IDs'::=,identifier|empty
*/
void Alloperation::Read_statement()
{
if (allcontent[update_index] == "(")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
check_length();
invalid_id();
first:
if (alltypes[update_index] == "identifier")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Statement> <read> " << endl;
cout << "\t" << " <read> (<IDs>)" << endl;
cout << "\t" << "<IDs> <identifier> <IDs'>" << endl;
cout << "\n\n";
check_length();
second:
if (allcontent[update_index] == ",")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << " <read> (<IDs>)" << endl;
cout << "\t" << "<IDs> <identifier> <IDs'>" << endl;
cout << "\t" << "<IDs'> ,<identifier> " << endl;
cout << "\n\n";
check_length();
if (alltypes[update_index] == "identifier")
{
goto first;
}
else
{
if (!stop)
{
error_object.error_name = "missed identifier after ,";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
// goto second;
}
}
}
if (allcontent[update_index] == ")")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<ID'> <Epsilon>" << endl;
cout << "\n\n";
check_length();
third:
if (allcontent[update_index] == ";")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\n\n";
check_length();
}
else
{
if (!stop)
{
error_object.error_name = "missed ;";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
}
}
}
else
{
if (!stop)
{
error_object.error_name = "missed ) for read ";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
// goto third;
}
}
}
else
{
if (!stop)
{
error_object.error_name = "missed ( for read ";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
// goto second;
}
}
}
else
{
if (!stop)
{
error_object.error_name = "missed ( or , for read ";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
//goto first;
}
}
}
/*in this method we do recursion desent for (write) and all rules we will used
<Write> ::= write ( <Expression>);
*/
void Alloperation::Write_statement()
{
if (allcontent[update_index] == "(")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\n\n";
invalid_id();
check_length();
first:
expression_func();
Statement_List1();
if (allcontent[update_index] == ")")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Primary'> <Epsilon> " << endl;
cout << "\t" << "<Term'> <Epsilon> " << endl;
cout << "\t" << "<Expression'> <Epsilon> " << endl;
cout << "\n\n";
check_length();
second:
if (allcontent[update_index] == ";")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\n\n";
check_length();
}
else
{
if (!stop)
{
error_object.error_name = "missed ; ";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
}
}
}
else
{
if (!stop)
{
error_object.error_name = "missed ) for write ";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
//goto second;
}
}
}
else
{
if (!stop)
{
error_object.error_name = "missed ( for write ";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
//goto first;
}
}
}
void Alloperation::Return_statement1() {
if (alltypes[update_index] == "integer")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Return'> <Expression>;" << endl;
cout << "\t" << "<Expression> <Term> <Expression'>" << endl;
cout << "\t" << "<Term> <Factor> <Term'>" << endl;
cout << "\t" << "<Factor> <Primary>" << endl;
cout << "\t" << "<Primary> <integer>" << endl;
cout << "\n\n";
check_length();
}
else if (alltypes[update_index] == "floating")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Return'> <Expression>;" << endl;
cout << "\t" << "<Expression> <Term> <Expression'>" << endl;
cout << "\t" << "<Term> <Factor> <Term'>" << endl;
cout << "\t" << "<Factor> <Primary>" << endl;
cout << "\t" << "<Primary> <floating>" << endl;
cout << "\n\n";
check_length();
}
}
void Alloperation::Return_statement()
{
if (allcontent[update_index] == ";")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Statement> <Return>" << endl;
cout << "\t" << "<Return> <return> <;>" << endl;
cout << "\n\n";
check_length();
}
else
{
expression_func();
if (allcontent[update_index] == ";")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Primary'> <Epsilon>" << endl;
cout << "\t" << "<Term'> <Epsilon>" << endl;
cout << "\t" << "<Expression'> <Epsilon>" << endl;
cout << "\n\n";
check_length();
}
else
{
if (!stop)
{
error_object.error_name = "missed ; ";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
}
}
}
}
void Alloperation::while_statement()
{
if (allcontent[update_index] == "(")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\n\n";
invalid_id();
check_length();
first:
condition();
if (allcontent[update_index] == ")")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Primary'> <Epsilon>" << endl;
cout << "\t" << "<Term'> <Epsilon>" << endl;
cout << "\t" << "<Expression'> <Epsilon>" << endl;
cout << "\n\n";
check_length();
second:
Statement_List();
}
else
{
if (!stop)
{
error_object.error_name = "missed ( for write ";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
//goto second;
}
}
}
else
{
if (!stop)
{
error_object.error_name = "missed ( for while ";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
// goto first;
}
}
}
void Alloperation::if_statement()
{
if (allcontent[update_index] == "(")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\n\n";
invalid_id();
check_length();
first:
condition();
if (allcontent[update_index] == ")")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Term'> <Epsilon>" << endl;
cout << "\t" << "<Expression'> <Epsilon>" << endl;
cout << "\n\n";
check_length();
second:
Statement_List();
if (allcontent[update_index] == "fi")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<If'> < fi > " << endl;
cout << "\n\n";
check_length();
}
else if (allcontent[update_index] == "else")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Statement> <if>" << endl;
cout << "\t" << "<If'> -> else <Statement> fi" << endl;
cout << "\n\n";
check_length();
third:
Statement_List();
if (allcontent[update_index] == "fi")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\n\n";
check_length();
}
else
{
if (!stop)
{
error_object.error_name = "missed fi for else statement ";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
}
}
}
else
{
if (!stop)
{
error_object.error_name = "missed second part of if_statement ";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
// goto first;
}
}
}
else
{
if (!stop)
{
error_object.error_name = "missed ) for condition ";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
// goto second;
}
}
}
else
{
if (!stop)
{
error_object.error_name = "missed ( for condition ";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
// goto first;
}
}
}
void Alloperation::Assign_statement()
{
if (allcontent[update_index] == ":=")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\n\n";
invalid_id();
check_length();
first:
expression_func();
if (allcontent[update_index] == ";")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Primary'> <Epsilon>" << endl;
cout << "\t" << "<Term'> <Epsilon>" << endl;
cout << "\t" << "<Expression'> <Epsilon>" << endl;
cout << "\n\n";
check_length();
}
else
{
if (!stop)
{
error_object.error_name = "missed ; ";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
}
}
}
else
{
if (!stop)
{
error_object.error_name = "mised equal operator for assign";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
// goto first;
}
}
}
/*
this method for expression
<Expression> ::= <Expression> + <Term> | <Expression> - <Term> | <Term>
<Expression> ::=<Term><Expression'>
<Expression'>::=+<Term><Expression'>|-<Term><Expression'>|empty
*/
void Alloperation::expression_func()
{
Term();
first:
if (allcontent[update_index] == "+")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout <<"\t"<< "<Expression> <Term><Expression'>" << endl;
cout <<"\t"<< "<Expression'> +<Term><Expression'>" << endl;
cout << "\n\n";
check_length();
Term();
goto first;
}
else if (allcontent[update_index] == "-")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout <<"\t"<< "<Expression> <Term><Expression'>" << endl;
cout <<"\t"<< "<Expression'> -<Term><Expression'>" << endl;
cout << "\n\n";
check_length();
Term();
goto first;
}
}
/*
this method for Term
<Term> ::= <Term> * <Factor> | <Term> / <Factor> | <Factor>
<Term> ::=<Factor><Term'>
<Term'>::=/<Factor><Term'>|*<Factor><Term'>|empty
*/
void Alloperation::Term()
{
Factor();
first:
if (allcontent[update_index] == "*")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Term> <Factor> <Term'>" << endl;
cout << "\t" << "<Term'> *<Factor> <Term'>" << endl;
cout << "\n\n";
check_length();
Factor();
goto first;
}
else if (allcontent[update_index] == "/")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Term> <Factor> <Term'>" << endl;
cout << "\t" << "<Term'> /<Factor> <Term'>" << endl;
cout << "\n\n";
check_length();
Factor();
goto first;
}
}
/*
this method for factor
<Factor> ::= - <Primary> | <Primary>
*/
void Alloperation::Factor()
{
if (allcontent[update_index] == "-")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Factor> -<Primary>" << endl;
check_length();
primary1();
}
else
{
primary1();
}
}
/*
<Primary> ::= <Identifier> | <Integer> | <Identifier> [<IDs>] | ( <Expression> ) | <Floating> | true | false
*/
void Alloperation::primary1()
{
invalid_id();
if (alltypes[update_index] == "identifier")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Expression> <Term> <Expression'>" << endl;
cout << "\t" << "<Term> <Factor> <Term'>" << endl;
cout << "\t" << "<Factor> <Primary>" << endl;
cout << "\t"<< "<Primary> <identifier><Primary'>" << endl;
cout << "\n\n";
check_length();
if (allcontent[update_index] == "[")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Primary'> [<IDs>]" << endl;
cout << "\n\n";
check_length();
IDs();
if (allcontent[update_index] == "]")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<IDs'> <Epsilon>" << endl;
cout << "\n\n";
check_length();
}
else
{
if (!stop)
{
error_object.error_name = "missed ]";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
}
}
}
}
else if (alltypes[update_index] == "integer")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Factor> <Primary>" << endl;
cout << "\t"<<"<Primary> <integer>" << endl;
cout << "\n\n";
check_length();
}
else if (allcontent[update_index] == "(")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Factor> <Primary>" << endl;
cout << "\t" << "<Primary> (<Expression>)" << endl;
cout << "\n\n";
update_index++;
expression_func();
if (allcontent[update_index] == ")")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Term'> <Epsilon>" << endl;
cout << "\t" << "<Expression'> <Epsilon>" << endl;
cout << "\n\n";
check_length();
}
else
{
if (!stop)
{
error_object.error_name = "missed )";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
}
}
}
else if (allcontent[update_index] == ";")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
}
else if (allcontent[update_index] == "true")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout <<"\t" <<"<Expression> <Term> <Expression'>" << endl;
cout <<"\t" <<"<Term> <Factor> <Term'>" << endl;
cout <<"\t" <<"<Factor> <Primary>" << endl;
cout <<"\t" <<"<Primary> <true>" << endl;
cout << "\n\n";
check_length();
}
else if (allcontent[update_index] == "false")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Expression> <Term> <Expression'>" << endl;
cout << "\t" << "<Term> <Factor> <Term'>" << endl;
cout << "\t" << "<Factor> <Primary>" << endl;
cout << "\t" << "<Primary> <false>" << endl;
cout << "\n\n";
check_length();
}
else if (alltypes[update_index] == "floating")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Factor> <Primary>" << endl;
cout << "\t" <<"<Primary> <floating>" << endl;
cout << "\n\n";
check_length();
}
/*else
{
if (!stop)
{
error_object.error_name = "error in primary";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
}
}
*/
}
/*
*/
void Alloperation::IDs()
{
invalid_id();
if (alltypes[update_index] == "identifier")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<IDs> <identifier> <IDs'>" << endl;
cout << "\n\n";
check_length();
first:
if (allcontent[update_index] == ",")
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<IDs> <identifier> <IDs'>" << endl;
cout << "\t" << "<IDs'><,identifier>" << endl;
check_length();
if (alltypes[update_index] == "identifier")
{
goto first;
}
else
{
if (!stop)
{
error_object.error_name = "missed identifier after ,";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
}
}
}
}
else
{
if (!stop)
{
error_object.error_name = "missed identifier ";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
// goto first;
}
}
}
/*
*/
void Alloperation::condition()
{
expression_func();
if (allcontent[update_index] == ":=" )
{
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
check_length();
}
else if (allcontent[update_index] == "="||allcontent[update_index] == ">" || allcontent[update_index] == "<"|| allcontent[update_index] == "/=" || allcontent[update_index] == "=>" || allcontent[update_index] == "<=") {
cout << "Token:" << alltypes[update_index] << "\t" << "Lexeme:" << allcontent[update_index] << endl;
cout << "\t" << "<Primary '> <Epsilon>" << endl;
cout << "\t" << "<Term '> <Epsilon>" << endl;
cout << "\t" << "<Expression'> <Epsilon>" << endl;
cout << "\t" << "<Relop> < " << allcontent[update_index] << " >" << endl;
cout << "\n\n";
check_length();
}
else
{
if (!stop)
{
error_object.error_name = "missed Relop ";
error_object.error_line = lineofcode[update_index];
allerrors.push_back(error_object);
update_index = inserted_index - 1;
display_errors();
}
}
expression_func();
}
#endif
| true |
74d6c53b7c9528da77a52eca7edd9a7e6c3a65f3
|
C++
|
fbocharov/mydb
|
/src/main.cpp
|
UTF-8
| 2,573 | 2.859375 | 3 |
[
"WTFPL"
] |
permissive
|
#include <iostream>
#include <sql/SQLParser.h>
#include <sql/SQLParserException.h>
#include <io/InputReader.h>
#include <io/CSVPrinter.h>
#include <backend/IOException.h>
#include <core/MyDB.h>
#include <utils/Log.h>
void PrintUsage(std::string const & appName) {
std::cout << "Usage: " << appName << " <db_file>" << std::endl;
}
void ExecuteSelect(MyDB & db, std::unique_ptr<ISQLStatement> const & statement, CSVPrinter & printer) {
auto cursor = db.ExecuteQuery(statement);
auto tableDescription = db.GetTableDescription(statement->GetTableName());
printer.PrintHeading(tableDescription);
while (cursor->Next())
printer.PrintLine(cursor->Get().GetValues());
}
void ExecuteStatement(MyDB & db, std::unique_ptr<ISQLStatement> const & statement, CSVPrinter & printer) {
switch (statement->GetType()) {
case SQLStatementType::CREATE: {
if (db.ExecuteCreate(statement))
std::cout << "OK" << std::endl;
break;
}
case SQLStatementType::INSERT: {
size_t rows = db.ExecuteUpdate(statement);
std::cout << "OK " << rows << std::endl;
break;
}
case SQLStatementType::SELECT: {
ExecuteSelect(db, statement, printer);
break;
}
default:
std::cout << "Unknown sql statement." << std::endl;
}
}
int main(int argc, char * argv[]) {
if (2 != argc) {
PrintUsage(argv[0]);
return 1;
}
std::ofstream log("mydb.log");
Log::SetStream(LogType::Info, log);
Log::SetStream(LogType::Debug, log);
Log::SetStream(LogType::Error, log);
std::string userInput;
InputReader reader(std::cin);
CSVPrinter printer(std::cout);
Log(LogType::Info) << "Start listening to unput." << std::endl;
try {
MyDB db(argv[1]);
std::cout << "Hello from MyDB!" << std::endl;
while (true) {
std::cout << "> ";
userInput = reader.Read();
try {
auto statement = SQLParser::Instance().ParseStatement(userInput);
if (!statement) { // input == quit/exit
std::cout << "Goodbye!" << std::endl;
break;
}
ExecuteStatement(db, statement, printer);
} catch (SQLParserException const & e) {
std::cerr << "ERROR: " << e.what() << std::endl;
Log(LogType::Error) << "Exception while parsing " << userInput << ": " << e.what() << std::endl;
} catch(std::runtime_error const & e) {
std::cerr << "ERROR: " << e.what() << std::endl;
Log(LogType::Error) << "Exception in main: " << e.what() << std::endl;
}
}
} catch (std::exception const & e) {
std::cerr << "FATAL ERROR: " << e.what() << std::endl;
Log(LogType::Error) << "std::exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
| true |
1c00593cc937495a089e6ddd0e5348c952ddea87
|
C++
|
xiaohejun/ACM
|
/1554: junlao的字符.cpp
|
UTF-8
| 639 | 2.765625 | 3 |
[] |
no_license
|
#include <cstdio>
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
/*
1554: junlao的字符
*/
int main()
{
//freopen("in.txt", "r", stdin);
int t;
cin >> t;
string str;
string strs[55];
char ch;
int n;
for (int i = 0; i < t; ++i)
{
cin >> strs[i];
}
for (int i = 0; i < t; i++){
str = strs[i];
for (int i = 0; str[i] != '\0'; ++i) // 循环
{
if(str[i] >= '1' && str[i] <= '9'){
n = str[i] - '0';
for (int j = 0; j < n; ++j)
{
printf("%c", ch);
}
} else {
ch = str[i];
printf("%c", ch);
}
}
printf("\n");
}
//fclose(stdin);
return 0;
}
| true |
aa7021979c78ac1683a7244c32d6a280131ec320
|
C++
|
WOODNOTWOODY/LearnOpenGL
|
/blade/gles3_render/GLES3RenderEngine.cpp
|
UTF-8
| 4,721 | 2.5625 | 3 |
[] |
no_license
|
#include "GLES3RenderStd.h"
#include "GLES3RenderEngine.h"
BLADE_NAMESPACE_BEGIN
RenderEngine::RenderEngine()
: m_curRenderWindow(NULL)
, m_curGLProgram(0)
, m_curGLVAO(0)
, m_curGLFBO(0)
, m_glActiveTexUnit(0)
{
for (uint32 i = 0; i < MAX_TEXTURE_UNIT_NUM; ++i)
{
for (uint32 j = 0; j < TT_COUNT; ++j)
{
m_texUnits[i][j] = (GLuint)(-1);
}
}
}
RenderEngine::~RenderEngine()
{
}
bool RenderEngine::initialize(const WindowSetting& setting)
{
m_pDefaultDSS = BLADE_NEW(DepthStencilState);
m_pCurrentDSS = m_pDefaultDSS;
m_pDefaultBS = BLADE_NEW(BlendState);
m_pCurrentBS = m_pDefaultBS;
m_pDefaultRS = BLADE_NEW(RasterizerState);
m_pCurrentRS = m_pDefaultRS;
m_curRenderWindow = BLADE_NEW(RenderWindow);
if (!m_curRenderWindow->initialize(setting))
{
destroy();
return false;
}
bindGLBuffer(GL_ARRAY_BUFFER, 0);
bindGLBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
bindGLProgram(0);
bindGLVAO(0);
return true;
}
void RenderEngine::destroy()
{
m_curRenderWindow->destroy();
BLADE_SAFE_DELETE(m_curRenderWindow);
m_curGLProgram = 0;
m_curGLVAO = 0;
}
void RenderEngine::render(RenderLayout* layout)
{
layout->bind();
GPUBuffer* indexBuffer = layout->getIndexBuffer();
if (indexBuffer)
{
Byte* offset = 0;
offset += layout->getStartIndex() * layout->getIndexStride();
glDrawElements(layout->getGLPrimitiveMode(), layout->getIndexCount(), layout->getGLIndexType(), offset);
}
else
{
glDrawArrays(layout->getGLPrimitiveMode(), layout->getStartVertexIndex(), layout->getVertexCount());
}
layout->unbind();
}
void RenderEngine::bindGLVAO(GLuint hVAO)
{
if (m_curGLVAO != hVAO)
{
glBindVertexArray(hVAO);
m_curGLVAO = hVAO;
}
}
void RenderEngine::bindGLFBO(GLuint hFBO)
{
if (m_curGLFBO != hFBO)
{
glBindFramebuffer(GL_FRAMEBUFFER, hFBO);
m_curGLFBO = hFBO;
}
}
void RenderEngine::bindGLProgram(GLuint hProgram)
{
if (m_curGLProgram != hProgram)
{
glUseProgram(hProgram);
m_curGLProgram = hProgram;
}
}
void RenderEngine::bindGLBuffer(GLenum glTarget, GLuint hVBO)
{
BindBufferMap::iterator it = m_bindBufferMap.find(glTarget);
if (it == m_bindBufferMap.end() || it->second != hVBO)
{
glBindBuffer(glTarget, hVBO);
m_bindBufferMap[glTarget] = hVBO;
}
}
void RenderEngine::unbindGLBuffer(GLenum glTarget, GLuint hVBO)
{
BindBufferMap::iterator it = m_bindBufferMap.find(glTarget);
if (it != m_bindBufferMap.end() && it->second == hVBO)
{
glBindBuffer(glTarget, 0);
m_bindBufferMap.erase(it);
}
}
void RenderEngine::setViewport(int left, int top, uint32 width, uint32 height)
{
glViewport(left, top, width, height);
}
void RenderEngine::clearGLColor(const Color& color)
{
glClearColor(color.r, color.g, color.b, color.a);
}
void RenderEngine::clearGLDepth(float depth)
{
glClearDepthf(depth);
}
void RenderEngine::clearGLStencil(uint32 stencil)
{
glClearStencil((GLint)stencil);
}
void RenderEngine::clear(uint32 flags)
{
GLbitfield mask = 0;
if (flags & CM_COLOR)
{
mask |= GL_COLOR_BUFFER_BIT;
}
if (flags & CM_DEPTH)
{
mask |= GL_DEPTH_BUFFER_BIT;
}
if (flags & CM_STENCIL)
{
mask |= GL_STENCIL_BUFFER_BIT;
}
if (mask != 0)
{
glClear(mask);
}
}
void RenderEngine::activeGLTextureUnit(GLenum texUnit)
{
if (m_glActiveTexUnit != texUnit)
{
glActiveTexture(GL_TEXTURE0 + texUnit);
m_glActiveTexUnit = texUnit;
}
}
void RenderEngine::bindGLTexture(TextureType type, GLenum glTarget, GLuint hTexture)
{
uint32& handle = m_texUnits[m_glActiveTexUnit][type];
if (hTexture != handle)
{
glBindTexture(glTarget, hTexture);
handle = hTexture;
}
}
void RenderEngine::unbindGLTexture(TextureType type, GLenum glTarget, GLuint hTexture)
{
for (uint32 i = 0; i < MAX_TEXTURE_UNIT_NUM; ++i)
{
uint32& handle = m_texUnits[i][type];
if (handle == hTexture)
{
glBindTexture(glTarget, 0);
handle = 0;
}
}
}
void RenderEngine::notifyBlendStateReleased(BlendState* pState)
{
if (m_pCurrentBS == pState)
{
m_pCurrentBS = NULL;
}
RenderContext* pContext = m_curRenderWindow->getContext();
if (pState == pContext->getBlendState())
{
pContext->setBlendState(NULL);
}
}
void RenderEngine::notifyRasterizerStateReleased(RasterizerState* pState)
{
if (m_pCurrentRS == pState)
{
m_pCurrentRS = NULL;
}
RenderContext* pContext = m_curRenderWindow->getContext();
if (pState == pContext->getRasterizerState())
{
pContext->setRasterizerState(NULL);
}
}
void RenderEngine::notifyDepthStencilStateReleased(DepthStencilState* pState)
{
if (m_pCurrentDSS == pState)
{
m_pCurrentDSS = NULL;
}
RenderContext* pContext = m_curRenderWindow->getContext();
if (pState == pContext->getDepthStencilState())
{
pContext->setDepthStencilState(NULL);
}
}
BLADE_NAMESPACE_END
| true |
fbc76196eedd190a8a935f988029c5cbbe335708
|
C++
|
aajjbb/contest-files
|
/Codeforces/Pipeline.cpp
|
UTF-8
| 1,081 | 2.625 | 3 |
[
"Apache-2.0"
] |
permissive
|
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
typedef long long Int;
Int N, K;
Int sumF(Int p) {
return p * (K + (K - p + 1)) / 2LL;
}
int main(void) {
cin >> N >> K;
if (N == 1) {
cout << "0\n";
return 0;
}
Int l = 1, h = K, m;
Int ans = 10010101001010LL;
for ( ; l <= h; ) {
m = (l + h) / 2;
Int sum = sumF(m) - m + 1;
// cerr << sum << " - " << m << "\n";
if (sum == N) {
ans = min(ans, m);
break;
} else if (sum < N) {
if (N - sum <= K - m - 1) {
// cerr << "fit\n";
ans = min(ans, m + 1);
}
l = m + 1;
} else {
if (sum - N <= K - m - 1) {
// cerr << "fit\n";
ans = min(ans, m + 1);
}
h = m - 1;
}
}
if (ans >= 10010101001010LL) {
ans = -1;
}
cout << ans << "\n";
return 0;
}
| true |
751c061ee34c4e15b2a0c3162504f00a73a4d925
|
C++
|
StefanButacu/Data-Structures-and-Algorithms
|
/ADT Ordered singly linked list(2)/Lab4/LO.h
|
UTF-8
| 1,692 | 2.78125 | 3 |
[] |
no_license
|
#pragma once
class Iterator;
typedef int TComparabil;
typedef TComparabil TElement;
typedef bool (*Relatie)(TElement, TElement);
#define NULL_TELEMENT -1
class LO {
private:
friend class Iterator;
private:
/* aici reprezentarea */
int cp;
int head, primLiber;
int sizeL;
TElement* elems;
int* urm;
int aloca();
void initSpatiuLiber(int cp);
void dealoca(int i);
int creeazaNod(TElement e);
Relatie r;
void redim(int cp);
public:
// constructor
LO(Relatie r);
// returnare dimensiune
int dim() const;
// verifica daca LO e vida
bool vida() const;
// prima pozitie din LO
Iterator prim() const;
// returnare element de pe pozitia curenta
//arunca exceptie daca poz nu e valid
TElement element(Iterator poz) const;
// adaugare element in LO a.i. sa se pastreze ordinea intre elemente
void adauga(TElement e);
// sterge element de pe o pozitie poz si returneaza elementul sters
//dupa stergere poz e pozitionat pe elementul de dupa cel sters
//arunca exceptie daca poz nu e valid
TElement sterge(Iterator& poz);
// cauta element si returneaza prima pozitie pe care apare (sau iterator invalid)
Iterator cauta(TElement e) const;
//destructor
~LO();
void printLO();
/// returnează ultimul index al unui element dat
// daca elementul nu este în listă returnează un TPozitie nevalid
// TPozitie [nume_clasa]::ultimulIndex(TElem elem) const;
// Obs: depinzând dacă aveți listă indexată sau cu poziție iterator,
//înlocuiți TPozitie cu int sau IteratorListă și TPozitie nevalid cu indexul - 1 sau iterator nevalid.
Iterator ultimulIndex(TElement elem) const;
};
| true |
4e6c2706dbdd26d4a49e8b93d9fb891422d5502d
|
C++
|
sntchaitu/CppND-System-Monitor-Project-Updated
|
/src/processor.cpp
|
UTF-8
| 525 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
#include "processor.h"
#include "linux_parser.h"
#include <vector>
#include <string>
using std::vector;
using std::string;
float Processor::Utilization() {
float utilization;
long active = LinuxParser::ActiveJiffies();
long idle = LinuxParser::IdleJiffies();
long cpu_total = active+idle;
long total_diff = cpu_total-prev_total;
long idle_diff = idle-prev_idle;
if(total_diff>0) utilization = (float)(total_diff-idle_diff)/total_diff;
prev_total = cpu_total;
prev_idle = idle;
return utilization;
}
| true |
027ef1de395725fb22214bd57da9a1a5cb1b9632
|
C++
|
sandeep1parmar/BEL_VMS
|
/Bel1/Model/Live/carouselmodel.cpp
|
UTF-8
| 1,096 | 2.546875 | 3 |
[] |
no_license
|
#include "carouselmodel.h"
CarouselModel::CarouselModel(QObject *parent) : QAbstractListModel(parent)
{
m_pCarouselList = new QList<CarouselItem*>;
}
CarouselModel::~CarouselModel()
{
}
void CarouselModel::setCarouselList(QList<CarouselItem*> *aList)
{
beginResetModel();
m_pCarouselList = aList;
endResetModel();
// reset();
}
void CarouselModel::AddCarousel(CarouselItem *aCarouselItem)
{
int first = m_pCarouselList->count();
int last = first;
beginInsertRows(QModelIndex(), first, last);
m_pCarouselList->append(aCarouselItem);
endInsertRows();
}
QVariant CarouselModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (index.row() >= m_pCarouselList->size())
return QVariant();
if (role == Qt::DisplayRole)
return QVariant(QString("%1").arg((m_pCarouselList->at(index.row()))->getCarouselName()));
else
return QVariant();
}
int CarouselModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return m_pCarouselList->size();
}
| true |
32b67fd0cc8fcadc3461ab6f990d71d6297f1d32
|
C++
|
enterstudio/sport-programming
|
/SPOJ/Archive/PERIOD.cpp
|
UTF-8
| 914 | 2.59375 | 3 |
[] |
no_license
|
// In the name of Allah, Most Gracious, Most Merciful
// SPOJ/PERIOD
// Period
// strings
//
//
// AC (2012-07-15 16:52:16)
#include <cstdio>
#include <cstring>
#include <algorithm>
#define SET(c, v) memset(c, v, sizeof(c))
using namespace std;
char S[1000005];
int P[1000005], Z[1000005];
void solve() {
strcat(S, "$");
int n = strlen(S);
P[0] = -1;
P[1] = 0;
for(int i = 2, j = 0; i < n; ) {
if(S[i-1] == S[j])
P[i++] = ++j;
else if(j > 0)
j = P[j];
else
P[i++] = 0;
}
--n;
SET(Z, -1);
for(int i = 1; i <= n; ++i) if(Z[i] == -1) {
for(int j = 2; i*j <= n; ++j) if(P[i*j] == i*(j-1))
Z[i*j] = Z[i*(j-1)]+1;
}
}
int main() {
int T, no = 1;
scanf("%d", &T);
while(T--) {
int N;
scanf("%d", &N);
scanf("%s", S);
solve();
printf("Test case #%d\n", no++);
for(int i = 1; i <= N; ++i) if(Z[i] >= 0)
printf("%d %d\n", i, Z[i]+2);
printf("\n");
}
return 0;
}
| true |
6ea6f8a4962d4f42fb418393abce50369a47a406
|
C++
|
xujingli/Programming
|
/pat/算法笔记&pat题解/2算法初步/two pointers/合并两个升序数组.cpp
|
GB18030
| 424 | 3.25 | 3 |
[] |
no_license
|
//ڣ2018/ ʱ䣺
#include <stdio.h>
#include <stdlib.h>
//A,BҪǺϲΪһC
int merge(int A[],int B[],int C[],int n,int m){
int i=0,j=0,index=0;
while(i<n && j<m){
if(A[i] < =B[j]){
C[index++]=A[i++];
}else{
C[index++]=B[j++];
}
}
while(i < n) C[index++]=A[i++];
while(j < m) C[index++]=B[j++];
return index;
}
int main(){
return 0;
}
| true |
a3aea197cc80105f8c7cf82fddc3a3b4979a8cd0
|
C++
|
schod005/ClassWork
|
/CSCI5511/SnakeAI/Snake.h
|
UTF-8
| 8,771 | 3.21875 | 3 |
[] |
no_license
|
#ifndef SNAKE_HPP
#define SNAKE_HPP
//Project Headers
#include "Constants.h"
#include "Misc.h"
class Snake
{
public:
Snake();
Snake(Grid*, int x, int y, int number);
void update(int);
int randMove();
void aStarMove();
void depthFirstMove();
bool checkApple(int);
void drawText() {WINDOW_HANDLE->draw(text);}
inline int getLength(){ return length; }
private:
int length;
int number;
sf::Text text;
Grid* GRID;
struct Node
{
Node* next;
Node* prev;
sf::Vector2i location;
}*head;
Node *tail;
};
#endif
Snake::Snake()
{
//empty
}
Snake::Snake(Grid* Grid_, int x, int y, int number_)
{
number = number_;
text.setFont(font);
text.setString(std::to_string(number));
text.setColor(sf::Color::Magenta);
text.setCharacterSize(20);
length = 1;
head = new Node;
head->next = nullptr;
head->prev = nullptr;
head->location.x = x;
head->location.y = y;
tail = head;
GRID = Grid_;
GRID->getDrawGrid()[x][y].setFillColor(sf::Color::Black);
}
//randomly moves the snake
int Snake::randMove()
{
//0 move left
//1 move up
//2 move right
//3 move down
for (int i = 0; i < GRID_SIZE; i++)
for (int j = 0; j < GRID_SIZE; j++)
if (GRID->getDrawGrid()[i][j].getFillColor() == sf::Color::Yellow)
GRID->getDrawGrid()[i][j].setFillColor(sf::Color(140, 140, 140, 255));
int move;
//testing if we are sitting on boundary cases elminating those movements
if ((head->location.x == 0) && (head->location.y == 0)) //move right if at top left corner
move = RIGHT;
else if ((head->location.x == GRID->getCols() - 1) && (head->location.y == 0)) //move down if at top right corner
move = DOWN;
else if ((head->location.x == GRID->getCols() - 1) && (head->location.y == GRID->getRows() - 1)) //move left if at bottum right corner
move = LEFT;
else if ((head->location.x == 0) && (head->location.y == GRID->getRows() - 1)) //move up if bottum left corner
move = UP;
else if ((head->location.x == 0))
move = RIGHT;
else if ((head->location.x == GRID->getCols() - 1))
move = DOWN;
else if ((head->location.y == 0))
move = DOWN;
else if ((head->location.y == GRID->getRows() - 1))
move = UP;
else
move = rand() % 4;
int count = 0;
while (true)
{
count++;
if (count > 50)
{
return -1;
}
if (move == UP)
{
if (!boundary_check(move, head->location))
{
move = rand() % 4;
}
else if (GRID->getDrawGrid()[head->location.x][head->location.y - 1].getFillColor() != sf::Color(140, 140, 140, 255) &&
GRID->getDrawGrid()[head->location.x][head->location.y - 1].getFillColor() != sf::Color::Red)
{
move = rand() % 4;
}
else
break;
}
if (move == DOWN)
{
if (!boundary_check(move, head->location))
{
move = rand() % 4;
}
else if (GRID->getDrawGrid()[head->location.x][head->location.y + 1].getFillColor() != sf::Color(140, 140, 140, 255) &&
GRID->getDrawGrid()[head->location.x][head->location.y + 1].getFillColor() != sf::Color::Red)
{
move = rand() % 4;
}
else
break;
}
if (move == LEFT)
{
if (!boundary_check(move, head->location))
{
move = rand() % 4;
}
else if (GRID->getDrawGrid()[head->location.x - 1][head->location.y].getFillColor() != sf::Color(140, 140, 140, 255) &&
GRID->getDrawGrid()[head->location.x - 1][head->location.y].getFillColor() != sf::Color::Red)
{
move = rand() % 4;
}
else
break;
}
if (move == RIGHT)
{
if (!boundary_check(move, head->location))
{
move = rand() % 4;
}
else if (GRID->getDrawGrid()[head->location.x + 1][head->location.y].getFillColor() != sf::Color(140, 140, 140, 255) &&
GRID->getDrawGrid()[head->location.x + 1][head->location.y].getFillColor() != sf::Color::Red)
{
move = rand() % 4;
}
else
break;
}
}
update(move);
//GRID->aStarSearch(head->location, GRID->getAppleLoc());
return 0;
}
//moves the snake according to the A* algorithm
void Snake::aStarMove()
{
int move = GRID->aStarSearch(head->location, GRID->getAppleLoc());
if (move != -1 && move != -123)
{
update(move);
}
else
{
for (int i = 0; i < GRID_SIZE; i++)
for (int j = 0; j < GRID_SIZE; j++)
if (GRID->getDrawGrid()[i][j].getFillColor() == sf::Color::Yellow || GRID->getDrawGrid()[i][j].getFillColor() == sf::Color::Blue)
GRID->getDrawGrid()[i][j].setFillColor(sf::Color(140, 140, 140, 255));
if (randMove() == -1)
{
std::cout << "GAME OVER!! Snake Length: " << length << " Nodes Expanded: " << GRID->getNodesExpanded() << std::endl;
sf::sleep(sf::Time(sf::seconds(100)));
}
}
}
//moves the snake according to the depth-first search algorithm
void Snake::depthFirstMove()
{
int move = GRID->depthFirstSearch(head->location, GRID->getAppleLoc());
if (move != -1 && move != -123)
{
update(move);
}
else
{
for (int i = 0; i < GRID_SIZE; i++)
for (int j = 0; j < GRID_SIZE; j++)
if (GRID->getDrawGrid()[i][j].getFillColor() == sf::Color::Yellow || GRID->getDrawGrid()[i][j].getFillColor() == sf::Color::Blue)
GRID->getDrawGrid()[i][j].setFillColor(sf::Color(140, 140, 140, 255));
if (randMove() == -1)
{
std::cout << "GAME OVER!! Snake Length: " << length << " Nodes Expanded: " << GRID->getNodesExpanded() << std::endl;
sf::sleep(sf::Time(sf::seconds(100)));
}
}
}
//updates positioning of the snake
void Snake::update(int move)
{
if (checkApple(move))
{
//if apple is eaten, add a new head at its location
GRID->getDrawGrid()[head->location.x][head->location.y].setFillColor(sf::Color::Black);
Node* newHead = new Node;
newHead->next = head;
newHead->prev = nullptr;
head->prev = newHead;
switch (move)
{
case UP:
newHead->location.x = head->location.x;
newHead->location.y = head->location.y - 1;
break;
case DOWN:
newHead->location.x = head->location.x;
newHead->location.y = head->location.y + 1;
break;
case LEFT:
newHead->location.x = head->location.x - 1;
newHead->location.y = head->location.y;
break;
case RIGHT:
newHead->location.x = head->location.x + 1;
newHead->location.y = head->location.y;
break;
default:
break;
}
head = newHead;
length++;
GRID->getDrawGrid()[head->location.x][head->location.y].setFillColor(sf::Color::Green);
GRID->generateApple();
}
else
{
if (length == 1)
{
//if length is 1, head and tail are pointing at the same thing, so just move head
GRID->getDrawGrid()[head->location.x][head->location.y].setFillColor(sf::Color(140, 140, 140, 255));
switch (move)
{
case UP:
head->location.y--;
break;
case DOWN:
head->location.y++;
break;
case LEFT:
head->location.x--;
break;
case RIGHT:
head->location.x++;
break;
default:
break;
}
GRID->getDrawGrid()[head->location.x][head->location.y].setFillColor(sf::Color::Green);
}
else
{
//update colors and move tail to location of move
GRID->getDrawGrid()[tail->location.x][tail->location.y].setFillColor(sf::Color(140, 140, 140, 255));
GRID->getDrawGrid()[head->location.x][head->location.y].setFillColor(sf::Color::Black);
Node* tempTail = tail;
tail = tail->prev;
tempTail->prev->next = nullptr;
tempTail->prev = nullptr;
tempTail->next = head;
head->prev = tempTail;
head = tempTail;
switch (move)
{
case UP:
head->location.y = head->next->location.y - 1;
head->location.x = head->next->location.x;
break;
case DOWN:
head->location.y = head->next->location.y + 1;
head->location.x = head->next->location.x;
break;
case LEFT:
head->location.y = head->next->location.y;
head->location.x = head->next->location.x - 1;
break;
case RIGHT:
head->location.y = head->next->location.y;
head->location.x = head->next->location.x + 1;
break;
default:
break;
}
GRID->getDrawGrid()[head->location.x][head->location.y].setFillColor(sf::Color::Green);
}
}
text.setPosition(GRID->getDrawGrid()[head->location.x][head->location.y].getPosition());
text.setString(std::to_string(number) + "\n" + std::to_string(length));
}
//checks if the apple is located at the location the snake will move
bool Snake::checkApple(int move)
{
sf::Vector2i appleLoc = GRID->getAppleLoc();
switch (move)
{
case UP:
if (appleLoc.x == head->location.x && appleLoc.y == head->location.y - 1)
return true;
break;
case DOWN:
if (appleLoc.x == head->location.x && appleLoc.y == head->location.y + 1)
return true;
break;
case LEFT:
if (appleLoc.x == head->location.x - 1 && appleLoc.y == head->location.y)
return true;
break;
case RIGHT:
if (appleLoc.x == head->location.x + 1 && appleLoc.y == head->location.y)
return true;
break;
default:
return false;
}
return false;
}
| true |
005007b19a60cb031f7142929a475a7f15c19960
|
C++
|
jashuaw2396/TicTacToe-ShortGame
|
/Jash's TicTacToe/Jash's TicTacToe/GameBoard.h
|
UTF-8
| 795 | 3.46875 | 3 |
[] |
no_license
|
#pragma once
#include <iostream>
using namespace std;
#include <vector>
#include "Console.h"
class GameBoard
{
private:
// Gameboard being used
vector<char> m_gameboard;
// Player turn counter
int m_playerTurn;
// Counter for max plays (in case of a tie)
int m_playsLeft;
public:
GameBoard();
~GameBoard();
// Prints game intro
void GameInstructions();
// Prints board (used after every successful move)
void PrintBoard();
// Increments player turn counter
void NextTurn();
// Receive the player input, return true if move successful, return false if not
bool PerformMove(char _input, char _playerSign);
// Check to see if a winner is found
char CheckForWinner();
// Getter
int GetPlayerTurn() { return m_playerTurn; }
int GetPlaysLeft() { return m_playsLeft; }
};
| true |
e4c3eca441e1fbb9a7cf1e1495ab4fb59cd66a66
|
C++
|
sfy1020/AlgorithmTutorial
|
/Algorithm/Sources/NumberTheory/Solutions/Programmers/124 나라의 숫자.cpp
|
UTF-8
| 2,712 | 3.625 | 4 |
[] |
no_license
|
// 124 나라의 숫자
// https://programmers.co.kr/learn/courses/30/lessons/12899
// 시행착오
// 1. 0011 의 경우 Convert를 이용하면 11로 표현된다. 현재 이 문제에서는 0 또한 중요한 정보이므로 제거하면 안된다.
// 2. setfill을 이용할 때 endl을 주의
// 3. 라이브러리 ToNumber 코드 long long으로 변경
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <iomanip>
#include <cmath>
using namespace std;
// 10진수 -> N진수 변환
// N진수 -> 10진수 변환
// (36진수까지 허용)
class DecimalNumberSystem
{
public:
// input : 10-진수 n, 변환 대상 진수 num_system [2 - 36]
// output : num_system-진수 값
static std::string Convert(long long num, int num_system)
{
using namespace std;
string out = "";
if (num == 0)
return "0";
while (num)
{
out += ToASCII(num % num_system);
num /= num_system;
}
reverse(begin(out), end(out));
return out;
}
// input : number_system-진수 num, 변환 대상 진수 10
// output : 10-진수 값
static long long ToDecimal(const std::string& val, int num_system)
{
long long out = 0;
long long mul = 1;
for (int i = val.size() - 1; i >= 0; --i)
{
char n = val[i];
long long num = ToNumber(n);
out += num * mul;
mul *= (long long)num_system;
}
return out;
}
private:
static char ToASCII(int n)
{
if (n < 10) return '0' + n;
else return 'A' + n - 10;
}
static long long ToNumber(char n)
{
if ('0' <= n && n <= '9') return (long long)n - (long long)'0';
else return (long long)(n - 'A') + 10LL;
}
};
string solution(int N)
{
int k = 0;
long long n = N;
long long sum = 0;
while (n > sum)
{
k++;
sum += pow(3, k);
}
long long prev = sum - pow(3, k);
long long left = n - prev;
string tri = DecimalNumberSystem::Convert(left - 1, 3);
stringstream ss;
ss << setfill('0') << setw(k) << tri;
tri = ss.str();
for (int i = 0; i < tri.size(); ++i)
{
char c = tri[i];
if (c == '0')
{
tri[i] = '1';
}
else if (c == '1')
{
tri[i] = '2';
}
else
{
tri[i] = '4';
}
}
//cout << sum << " " << k << " " << prev << " " << left << " " << tri;
return tri;
}
int main()
{
int n = 4;
string answer = solution(n);
cout <<answer;
return 0;
}
| true |
39f34f21082e531f8709ca1aa8b14fdc4df51727
|
C++
|
amuchow/Moonrockers
|
/telecommunicationsPCDuino/multithreaded/TCP/server.cpp
|
UTF-8
| 2,303 | 3.25 | 3 |
[] |
no_license
|
// socket server example, handles multiple clients using threads
#include<stdio.h>
#include<string.h> //strlen
#include<stdlib.h> //strlen
#include<sys/socket.h>
#include<arpa/inet.h> //inet_addr
#include<unistd.h> //write
#include<pthread.h> //for threading , link with lpthread
//the thread function
void *connection_handler(void *);
int main(int argc , char *argv[])
{
int socket_desc , client_sock , c , *new_sock;
struct sockaddr_in server , client;
//Create socket
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (socket_desc == -1)
{
printf("Could not create socket");
}
puts("Socket created");
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 3000 );
//Bind
if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
{
//print the error message
perror("bind failed. Error");
return 1;
}
puts("bind done");
//Listen
listen(socket_desc , 3);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
c=sizeof(struct sockaddr_in);
while(client_sock=accept(socket_desc,(struct sockaddr*)&client,(socklen_t*)&c))
{
puts("Connection accepted");
pthread_t sniffer_thread;
new_sock = (int *)malloc(1);
*new_sock = client_sock;
if( pthread_create( &sniffer_thread , NULL , connection_handler , (void*) new_sock) < 0)
{
perror("could not create thread");
return 1;
}
puts("Handler assigned");
}
if (client_sock < 0)
{
perror("accept failed");
return 1;
}
return 0;
}
/*
This will handle connection for each client
*/
void *connection_handler(void *socket_desc)
{
//Get the socket descriptor
int sock = *(int*)socket_desc;
int n;
char sendBuff[100], client_message[2000];
while((n=recv(sock,client_message,2000,0))>0)
{
send(sock,client_message,n,0);
}
close(sock);
if(n==0)
{
puts("Client Disconnected");
}
else
{
perror("recv failed");
}
return 0;
}
| true |
5b869adc5b56899615602d65e23f9aba8ccba628
|
C++
|
Sarat-Chandra/Heuristics-For-Parallel-Djikstra
|
/overlay1.cpp
|
UTF-8
| 3,568 | 3.1875 | 3 |
[] |
no_license
|
#include<iostream>
#include<stdio.h>
#include <cstdlib>
#define INFINITY 999
using namespace std;
FILE *fp = fopen("input.txt","w");
FILE *fp1 = fopen("overlay1.txt","w");
//FILE *fp2 = fopen("overlay2.txt","w");
int ov,ov1;
class Graph
{
private:
int adjMatrix[15][15];
int predecessor[15],distance[15];
bool mark[15];
int source;
long numOfVertices;
public:
void read();
void initialize();
int getClosestUnmarkedNode();
void dijkstra();
void output();
void printPath(int);
};
void Graph::read()
{
//cout<<"Enter the number of vertices of the graph(should be > 0)\n";
int k;
//cin>>numOfVertices;
numOfVertices=rand() % 15;
//numOfVertices=16;
cout<<numOfVertices<<endl;
for (int i=1;i<=numOfVertices; i++){
for(int j=1;j<=numOfVertices; j++) {
k=rand() % numOfVertices;
if(i==j)
adjMatrix[i][j]=999;
else if(j==k)
adjMatrix[i][j]=999;
else{
adjMatrix[i][j]=rand() % 100;}
cout<<adjMatrix[i][j]<<"\t";
fprintf(fp,"%d",adjMatrix[i][j]);
fprintf(fp,"\t");
}
cout<<endl;
fprintf(fp,"\n");
}
cout<<"Enter the source vertex\n";
cin>>source;
while((source<0) && (source>numOfVertices-1)) {
cout<<"Source vertex should be between 0 and "<<numOfVertices-1<<endl;
cout<<"Enter the source vertex again\n";
cin>>source;
}
ov=numOfVertices/4;
}
void Graph::initialize()
{
for(int i=0;i<numOfVertices;i++) {
mark[i] = false;
predecessor[i] = -1;
distance[i] = INFINITY;
}
distance[source] = 0;
}
int Graph::getClosestUnmarkedNode()
{
int minDistance = INFINITY;
int closestUnmarkedNode;
for(int i=0;i<ov1;i++) {
if((!mark[i]) && ( minDistance >= distance[i])) {
minDistance = distance[i];
closestUnmarkedNode = i;
}
}
return closestUnmarkedNode;
}
void Graph::dijkstra()
{
initialize();
int minDistance = INFINITY;
int closestUnmarkedNode;
int count = 0;
while(count < ov1) {
closestUnmarkedNode = getClosestUnmarkedNode();
mark[closestUnmarkedNode] = true;
for(int i=0;i<ov1;i++) {
if((!mark[i]) && (adjMatrix[closestUnmarkedNode][i]>0) ) {
if(distance[i] > distance[closestUnmarkedNode]+adjMatrix[closestUnmarkedNode][i]) {
distance[i] = distance[closestUnmarkedNode]+adjMatrix[closestUnmarkedNode][i];
predecessor[i] = closestUnmarkedNode;
}
}
}
count++;
}
}
/*void Graph::printPath(int node)
{
if(node == source)
{ cout<<node<<"..";
fprintf(fp1,"%d\n",node); }
else if(predecessor[node] == -1)
cout<<"No path from "<<source<<"to "<<node<<endl;
else {
printPath(predecessor[node]);
cout<<node<<"..";
fprintf(fp1,"%d\t",node);
}
}*/
void Graph::output()
{
for(int i=0;i<ov1;i++) {
if(i == source)
cout<<source<<".."<<source;
else
printPath(i);
fprintf(fp1,"\n");
cout<<"->"<<distance[i]<<endl;
}
}
void Graph::printPath(int node)
{
if(node == source)
{ cout<<node<<"..";
fprintf(fp1,"%d\t",node);
}
else if(predecessor[node] == -1)
cout<<"No path from "<<source<<"to "<<node<<endl;
else {
printPath(predecessor[node]);
cout<<node<<"..";
fprintf(fp1,"%d\t",node);
}
}
int main()
{
int p=0;
//int ov,ov1;
Graph G;
G.read();
//ov=numOfVertices/4;
ov1=ov;
//char[15];
for(p=1;p<=4;p++)
{
cout<<"\n\nLeveL";
if(p==1)
fp1=fopen("overlay1.txt","w");
else if(p==2)
fp1=fopen("overlay2.txt","w");
else if(p==3)
fp1=fopen("overlay3.txt","w");
else
fp1=fopen("overlay4.txt","w");
fprintf(fp1,"\n\n");
G.dijkstra();
//ov1=ov1+ov;
G.output();
ov1=ov1+ov;
}
return 0;
}
| true |
c2b1d36ffb56d7d89202e85e49791be3331c1855
|
C++
|
RandyViG/Sistemas-Distribuidos
|
/EleccionesPresidenciales/6_Sincronizacion/time.cpp
|
UTF-8
| 405 | 2.671875 | 3 |
[] |
no_license
|
#include <time.h>
#include <sys/time.h>
#include <stdlib.h>
#include <stdio.h>
int main( void ) {
struct timeval start;
time_t rawtime;
struct tm * timeinfo;
char buffer [14];
while(1){
gettimeofday(&start, NULL);
time (&rawtime);
timeinfo = localtime (&rawtime);
strftime (buffer,22,"Hora: %H:%M:%S",timeinfo);
printf("%s.%ld\n",buffer,start.tv_usec );
}
return 0;
}
| true |
655195b81d75524cb60509e29c4760174cb32477
|
C++
|
Dragon-qing/vs
|
/visual studio的代码/练习/Project1/源.cpp
|
WINDOWS-1252
| 772 | 3.328125 | 3 |
[] |
no_license
|
#include <iostream>
#include <string>
using namespace std;
class CBug {
int legNum, color;
public:
CBug(int ln, int c1) : legNum(ln), color(c1)
{
cout << "CBug Constructor" << endl;
};
~CBug()
{
cout << "CBug Destructor" << endl;
}
void Printlnfo()
{
cout << legNum << "," << color << endl;
}
};
class CFlyingBug : public CBug
{
int wingNum;
public:
//CFlyingBug(){} ע͵
CFlyingBug(int ln, int c1, int wn) : CBug(ln, c1), wingNum(wn)
{
cout << "CFlyingBug Constructor" << endl;
}
~CFlyingBug()
{
cout << "CFlyingBug Destructor" << endl;
}
};
int main() {
CFlyingBug fb(2, 3, 4);
fb.Printlnfo();
return 0;
}
| true |
8e3f38846ac8a5494aa1f7855551d5a703812152
|
C++
|
kenji-hosokawa/rba
|
/unittest/internal_test/HA729_hierarchy.cpp
|
UTF-8
| 6,568 | 2.5625 | 3 |
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
// Copyright (c) 2019 DENSO CORPORATION. All rights reserved.
/**
* HA729_hierarchy.cpp
*/
#include <fstream>
#include <vector>
#include <string>
#include "RBAJsonParser.hpp"
#include "HA729_hierarchy.hpp"
#include "TestCommon.hpp"
namespace {
#ifdef RBA_USE_LOG
/*
* BaseLogCollector
*/
BaseLogCollector::BaseLogCollector() {}
BaseLogCollector::~BaseLogCollector() {}
bool BaseLogCollector::open(std::string file_path)
{
model_path = file_path;
ofs.open(model_path, std::ofstream::out | std::ofstream::trunc); // open to overwrite
if (ofs) {
return true;
}
else {
return false;
}
}
void BaseLogCollector::write(std::string outputLine)
{
if (ofs) {
ofs << outputLine << std::endl;
}
}
void BaseLogCollector::close()
{
if (ofs) {
ofs.close();
}
}
bool BaseLogCollector::startsWith(const std::string &target,
const std::string &keyword)
{
if(target.size() >= keyword.size() &&
std::equal(std::begin(keyword), std::end(keyword), std::begin(target))) {
return true;
}
return false;
}
std::list<std::string>
BaseLogCollector::split(const std::string& line, const char sep)
{
std::list<std::string> res;
std::stringstream ss(line);
std::string buf;
while (std::getline(ss, buf, sep)) {
res.push_back(buf);
}
return res;
}
/*
* ConstraintLogCollector
*/
static const char SEPARATOR = ',';
static const char EXP_SEP = '\t';
ConstraintLogCollector::ConstraintLogCollector() {}
ConstraintLogCollector::~ConstraintLogCollector() {}
void ConstraintLogCollector::log(const std::string& log)
{
if (startsWith(log, std::string("#HierarchyOfConstraint#DEF_START"))) {
write("#DEF_START");
defValid = true;
expValid = false;
}
else if (startsWith(log, std::string("#HierarchyOfConstraint#DEF_END"))) {
write("#DEF_END");
defValid = false;
expValid = false;
}
else if (defValid) {
if (startsWith(log, "#HierarchyOfConstraint#START")) {
std::list<std::string> strName = split(log, SEPARATOR); // "#Hiera...#START", "ModelName,ModelType" // ModelType: (Constraint, PostConstraint, Rule)
std::list<std::string>::iterator strTCLog_itr = strName.begin();
strTCLog_itr++; // "#Hiera...#START"
strHeadString = *(strTCLog_itr++);
strRuntime = *(strTCLog_itr++);
strType = *(strTCLog_itr++);
expValid = strRuntime.compare("t") == 0 ? true : false;
} else if (startsWith(log, "#HierarchyOfConstraint#EXPRESSION")) {
if (expValid) {
std::list<std::string> strContents = split(log, EXP_SEP); // #Hie...#EXPRESSION", "<hierarchy>", "<expressionText>", "<expressionType>"
std::list<std::string>::iterator itr = strContents.begin();
std::string garbage(*(itr++));
std::string hierarchy(*(itr++));
std::string expressionText(*(itr++));
if (strContents.size() == 3) {
write(strHeadString + EXP_SEP + hierarchy + EXP_SEP + expressionText + EXP_SEP + strType);
} else if (strContents.size() == 4) {
std::string expressionType(*itr);
write(strHeadString + EXP_SEP + hierarchy + EXP_SEP + expressionText + EXP_SEP + expressionType + EXP_SEP + strType);
} else if (strContents.size() > 4) {
int index = log.find(hierarchy) + hierarchy.length() + 1;
write(strHeadString + EXP_SEP + hierarchy + EXP_SEP + log.substr(index) + EXP_SEP + strType);
}
}
} else if (startsWith(log, "#HierarchyOfConstraint#END")) {
expValid = false;
}
}
if (startsWith(log, "#Constraint#START")) {
std::list<std::string> strName = split(log, SEPARATOR); // "#Constraint#START", "<name>", "<runtime>"
std::list<std::string>::iterator itr = strName.begin();
std::string garbage(*(itr++));
strHeadString = *(itr++);
strRuntime = *(itr++);
valid = strRuntime.compare("t") == 0 ? true : false;
} else if (startsWith(log, "#Constraint#EXPRESSION")) {
if (valid) {
std::list<std::string> strContents = split(log, EXP_SEP); // "#Constraint#EXPRESSION", "<hierarchy>", "<expressionText>", "<result>"
std::list<std::string>::iterator itr = strContents.begin();
std::string garbage(*(itr++));
std::string hierarchy(*(itr++));
std::string expressionText(*(itr++));
std::string strInput;
if (strContents.size() == 3) {
strInput = strHeadString + EXP_SEP + hierarchy + EXP_SEP + expressionText;
} else if (strContents.size() == 4) {
std::string result(*(itr++));
strInput = strHeadString + EXP_SEP + hierarchy + EXP_SEP + expressionText + EXP_SEP + result;
} else if (strContents.size() > 4) {
int index = log.find(hierarchy) + hierarchy.length() + 1;
strInput = strHeadString + EXP_SEP + hierarchy + EXP_SEP + log.substr(index) + EXP_SEP + strType;
}
if (std::find(outputtedLogs.begin(), outputtedLogs.end(), strInput) == outputtedLogs.end()) {
outputtedLogs.push_back(strInput);
write(strInput);
}
}
} else if (startsWith(log, "#Constraint#END")) {
valid = false;
}
}
#endif
HA729_hierarchy::HA729_hierarchy()
{
}
HA729_hierarchy::~HA729_hierarchy()
{
}
void HA729_hierarchy::SetUp()
{
rba::RBAJsonParser parser;
model_ = parser.parse(GET_JSON_PATH(JSONFILE));
ASSERT_NE(nullptr, model_);
arb_ = new rba::RBAArbitrator(model_);
}
void HA729_hierarchy::TearDown()
{
if(arb_) {
delete arb_;
arb_ = nullptr;
}
if(model_) {
delete model_;
model_ = nullptr;
}
#ifdef RBA_USE_LOG
rba::RBALogManager::setLogManager(nullptr);
#endif
}
#ifdef RBA_USE_LOG
TEST_F(HA729_hierarchy, exec)
{
collector_ = new ConstraintLogCollector();
ASSERT_TRUE(collector_->open(LOGFILE));
logm_ = new rba::RBALogManager();
logm_->addCoverageLogCollector(collector_);
rba::RBALogManager::setLogManager(logm_);
std::unique_ptr<rba::RBAResult> result;
result = arb_->execute(u8"C1/NORMAL", true);
EXPECT_EQ(rba::RBAResultStatusType::SUCCESS, result->getStatusType());
result = arb_->execute(u8"C2/NORMAL", true);
EXPECT_EQ(rba::RBAResultStatusType::SUCCESS, result->getStatusType());
result = arb_->execute(u8"C3/NORMAL", true);
EXPECT_EQ(rba::RBAResultStatusType::SUCCESS, result->getStatusType());
result = arb_->execute(u8"C4/NORMAL", true);
EXPECT_EQ(rba::RBAResultStatusType::SUCCESS, result->getStatusType());
result = arb_->execute(u8"C5/NORMAL", true);
EXPECT_EQ(rba::RBAResultStatusType::SUCCESS, result->getStatusType());
delete collector_;
delete logm_;
}
#endif
}
| true |
e5d14c11273e337c93c9cc5ac19e4b917f30418f
|
C++
|
maldewar/calaveras
|
/jni/src/Engine/Animation.cpp
|
UTF-8
| 3,344 | 2.84375 | 3 |
[] |
no_license
|
#include "Animation.h"
#include "../Util/Log.h"
Animation::Animation() {
m_type = ANIM_TYPE_LINEAR;
m_play = true;
m_texture = NULL;
m_sprite = NULL;
m_currentFrame = 0;
m_frameInc = 1;
m_backwards = false;
m_framerate = 500;
m_maxFrames = 1;
m_oldTime = SDL_GetTicks();
}
void Animation::Play() {
m_play = true;
}
void Animation::Pause() {
m_play = false;
}
void Animation::Reset() {
m_play = true;
if (m_backwards) {
m_frameInc = -1;
m_currentFrame = m_maxFrames - 1;
} else {
m_frameInc = 0;
m_currentFrame = 0;
}
m_oldTime = SDL_GetTicks();
}
bool Animation::IsOngoing() {
if (m_type != ANIM_TYPE_LINEAR)
return true;
return m_play;
}
void Animation::SetBackwards(bool backwards) {
m_backwards = backwards;
if (m_type == ANIM_TYPE_WAVE)
m_frameInc *= -1;
else
if (m_backwards)
m_frameInc = -1;
else
m_frameInc = 1;
}
bool Animation::IsBackwards() {
return m_backwards;
}
void Animation::SetType(int type) {
m_type = type;
Reset();
}
int Animation::GetType() {
return m_type;
}
bool Animation::OnAnimate() {
if (!m_play)
return false;
if (m_oldTime + m_framerate > SDL_GetTicks())
return false;
m_oldTime = SDL_GetTicks();
m_currentFrame += m_frameInc;
if (m_type == ANIM_TYPE_LINEAR) {
if (m_backwards) {
if (m_currentFrame == 0) {
m_play = false;
}
} else {
if (m_currentFrame == m_maxFrames - 1) {
m_play = false;
}
}
} else {
if (m_backwards)
if (m_currentFrame < 0)
if (m_type == ANIM_TYPE_LOOP) {
m_currentFrame = m_maxFrames -1;
} else if (m_maxFrames > 1) {
m_currentFrame = 1;
m_frameInc *= -1;
}
else
if (m_currentFrame >= m_maxFrames )
if (m_type == ANIM_TYPE_LOOP) {
m_currentFrame = 0;
} else if (m_maxFrames - 2 >= 0) {
m_currentFrame = m_maxFrames -2;
m_frameInc *= -1;
}
}
return true;
}
void Animation::SetMaxFrames(int maxFrames) {
m_maxFrames = maxFrames;
}
int Animation::GetMaxFrames() {
return m_maxFrames;
}
void Animation::SetFramerate(int framerate) {
m_framerate = framerate;
}
int Animation::GetFramerate() {
return m_framerate;
}
void Animation::SetCurrentFrame(int frame) {
if (frame >= 0 && frame < m_maxFrames)
m_currentFrame = frame;
}
int Animation::GetCurrentFrame() {
return m_currentFrame;
}
void Animation::SetTexture(SDL_Texture* texture) {
m_texture = texture;
}
SDL_Texture* Animation::GetTexture() {
return m_texture;
}
void Animation::SetSprite(Sprite* sprite) {
m_sprite = sprite;
}
Sprite* Animation::GetSprite() {
return m_sprite;
}
SDL_Rect* Animation::GetSrcRect() {
if (m_sprite)
return m_sprite->GetTile(m_currentFrame);
return NULL;
}
SDL_Rect* Animation::GetDstRect(int centerX, int centerY) {
if (m_sprite)
return m_sprite->GetDstTile(m_currentFrame, centerX, centerY);
return NULL;
}
| true |
9eca7d3b2e38b9bb6628171f329346e6b83a6624
|
C++
|
gusenov/examples-cpp
|
/dtor/F.h
|
UTF-8
| 299 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
#ifndef F_H
#define F_H
#include <iostream>
#include "E.h"
class F : E {
public:
~F() {
std::cout << "~F()" << std::endl;
// Здесь дальше пойдёт вызов ~E().
// Т.к. доступ к ~E() protected, то это возможно.
}
};
#endif
| true |
707788ead58d1512ec0ca16a9e999034ababf56c
|
C++
|
lixu1/windowsAPI
|
/7.5Timer/timer.cpp
|
UTF-8
| 1,296 | 2.609375 | 3 |
[] |
no_license
|
#define _WIN32_WINNT 0x0500
#include <Windows.h>
#include <stdio.h>
#define ONE_SECOND 10000000
typedef struct _APC_PROC_ARG{
TCHAR *szText;
DWORD dwValue;
}APC_PROC_ARG;
VOID CALLBACK TimerAPCProc(LPVOID lpArg, DWORD dwTimerLowValue, DWORD dwTimerHighValue)
{
APC_PROC_ARG *pApcData = (APC_PROC_ARG *)lpArg;
printf("Message:%s\nvalue:%d\n", pApcData->szText, pApcData->dwValue);
//MessageBeep(MB_OK);
}
void main(void)
{
HANDLE hTimer;
BOOL bSuccess;
INT64 qwDueTime;
LARGE_INTEGER liDueTime;
APC_PROC_ARG ApcData;
ApcData.szText = "Message to apc proc.";
ApcData.dwValue = 1;
hTimer = CreateWaitableTimer(NULL, FALSE, "MyTimer");
if (!hTimer)
{
printf("CreateWaitableTimer failed with Error %d.",GetLastError());
return;
}
else
{
//try
//{
//5s
qwDueTime = -5 * ONE_SECOND;
liDueTime.LowPart = (DWORD)(qwDueTime & 0xFFFFFFFF);
liDueTime.HighPart = (LONG)(qwDueTime >> 32);
bSuccess = SetWaitableTimer(hTimer, &liDueTime, 1000, TimerAPCProc, &ApcData, FALSE);
if (bSuccess)
{
for (; ApcData.dwValue < 10; ApcData.dwValue++)
{
SleepEx(INFINITE, TRUE);
}
}
else
{
printf("SetWaitableTimer failed with Error %d.", GetLastError());
}
//}
//catch ()
//{
//}
//_finally
//{
CloseHandle(hTimer);
//}
}
}
| true |
27de6f80f3663c408226da713119fa784fb9add6
|
C++
|
zuhalpolat/hackerrank-algorithms-solutions
|
/Implementation/ACM ICPC Team.cpp
|
UTF-8
| 942 | 3.015625 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <string>
#include <bitset>
using namespace std;
// Complete the acmTeam function below.
vector<int> acmTeam(vector<string> topic) {
vector<int> result(2, 0);
for (int i = 0; i < topic.size() - 1; i++) {
for (int j = i + 1; j < topic.size(); j++) {
bitset<500> bitset1(topic[i]);
bitset<500> bitset2(topic[j]);
int numberOfOnes = static_cast<int> ((bitset1 | bitset2).count());
if (numberOfOnes > result[0]) {
result[0] = numberOfOnes;
result[1] = 1;
}
else if (numberOfOnes == result[0])
result[1]++;
}
}
return result;
}
int main() {
vector<string> arr;
arr.push_back("10101");
arr.push_back("11100");
arr.push_back("11010");
arr.push_back("00101");
vector<int> res = acmTeam(arr);
system("pause");
}
| true |
b39f7dc6edeb1072fb5db88b8ae0ce2333fc7259
|
C++
|
amacias10/CSC-17A
|
/Hmwk/Assignmnet 6 VS/16.1 Date Exceptions/16.1 Date Exceptions.cpp
|
UTF-8
| 1,555 | 4 | 4 |
[] |
no_license
|
#include <iostream>
using namespace std;
class Date {
private:
int month,
day,
year;
string monthWord(int m) {
switch (m) {
case 1:
return "January";
case 2:
return "February";
case 3:
return "March";
case 4:
return "April";
case 5:
return "May";
case 6:
return "June";
case 7:
return "July";
case 8:
return "August";
case 9:
return "September";
case 10:
return "October";
case 11:
return "November";
case 12:
return "December";
}
}
public:
void getMonth() {
do {
cout << "Enter month:";
cin >> month;
if (month > 12 || month < 1)
throw InvalidMonth();
} while (month > 12 || month < 1);
}
void getDay() {
do {
cout << "Enter day:";
cin >> day;
if (day < 1 || day > 31)
throw InvalidDay();
} while (day < 1 || day > 31);
}
void getYear() {
cout << "Enter year:";
cin >> year;
}
void showDate1() {
cout << month << "/" << day << "/" << year << endl;
}
void showDate2() {
cout << monthWord(month) << " " << day << ", " << year << endl;
}
void showDate3() {
cout << day << " " << monthWord(month) << " " << year << endl;
}
//Exceptions
class InvalidDay
{};
class InvalidMonth
{};
};
int main(int argc, char** argv) {
Date day;
try {
day.getMonth();
day.getDay();
day.getYear();
day.showDate1();
day.showDate2();
day.showDate3();
}
catch (Date::InvalidDay) {
cout << "Error Invalid Day. Exiting...";
}
catch (Date::InvalidMonth) {
cout << "Error Invalid Month. Exiting...";
}
return 0;
}
| true |
a6e7f1e3df132247660a941d80cef609f13c8b91
|
C++
|
sdamico23/Car-Project
|
/hw8Damico/simpletest_raspicam.cpp
|
UTF-8
| 1,402 | 3.203125 | 3 |
[] |
no_license
|
/*
* simpletest_raspicam.cpp
*
* Created on: Feb 18, 2017
* Author: steveb
*/
#include <ctime>
#include <fstream>
#include <iostream>
#include <raspicam/raspicam.h>
int main( int argc, char **argv )
{
raspicam::RaspiCam Camera; // Camera object
int return_value; // the return value of this program
// Open camera
std::cout << "Opening Camera..." << std::endl;
if (Camera.open())
{
// wait a while until camera stabilizes
std::cout << "Sleeping for 3 secs" << std::endl;
std::sleep( 3 );
// capture
Camera.grab();
// allocate memory
unsigned char *data = new unsigned char[Camera.getImageTypeSize( raspicam::RASPICAM_FORMAT_RGB )];
// extract the image in rgb format
Camera.retrieve( data, raspicam::RASPICAM_FORMAT_RGB ); // get camera image
// save
std::ofstream outFile( "raspicam_image.ppm",std::ios::binary );
outFile << "P6\n" << Camera.getWidth() << " " << Camera.getHeight() << " 255\n";
outFile.write( (char *)data, Camera.getImageTypeSize( raspicam::RASPICAM_FORMAT_RGB ) );
std::cout << "Image saved at raspicam_image.ppm" << std::endl;
//free resources
delete data;
return_value = 0;
}
else
{
std::cerr << "Error opening camera" << std::endl;
return_value = -1;
}
return return_value;
}
| true |
70aa133a80ce9c1e8cccff60c2dfdbe18277d721
|
C++
|
mapillary/OpenSfM
|
/opensfm/src/dense/src/depthmap.cc
|
UTF-8
| 22,014 | 2.640625 | 3 |
[
"BSD-3-Clause",
"LGPL-3.0-only",
"HPND",
"BSD-2-Clause"
] |
permissive
|
#include "../depthmap.h"
#include <cstdint>
#include <opencv2/opencv.hpp>
#include <random>
namespace dense {
static const double z_epsilon = 1e-8;
bool IsInsideImage(const cv::Mat &image, int i, int j) {
return i >= 0 && i < image.rows && j >= 0 && j < image.cols;
}
template <typename T>
float LinearInterpolation(const cv::Mat &image, float y, float x) {
if (x < 0.0f || x >= image.cols - 1 || y < 0.0f || y >= image.rows - 1) {
return 0.0f;
}
int ix = static_cast<int>(x);
int iy = static_cast<int>(y);
float dx = x - ix;
float dy = y - iy;
float im00 = image.at<T>(iy, ix);
float im01 = image.at<T>(iy, ix + 1);
float im10 = image.at<T>(iy + 1, ix);
float im11 = image.at<T>(iy + 1, ix + 1);
float im0 = (1 - dx) * im00 + dx * im01;
float im1 = (1 - dx) * im10 + dx * im11;
return (1 - dy) * im0 + dy * im1;
}
float Variance(float *x, int n) {
float sum = 0;
for (int i = 0; i < n; ++i) {
sum += x[i];
}
float mean = sum / n;
float sum2 = 0;
for (int i = 0; i < n; ++i) {
sum2 += (x[i] - mean) * (x[i] - mean);
}
return sum2 / n;
}
NCCEstimator::NCCEstimator()
: sumx_(0), sumy_(0), sumxx_(0), sumyy_(0), sumxy_(0), sumw_(0) {}
void NCCEstimator::Push(float x, float y, float w) {
sumx_ += w * x;
sumy_ += w * y;
sumxx_ += w * x * x;
sumyy_ += w * y * y;
sumxy_ += w * x * y;
sumw_ += w;
}
float NCCEstimator::Get() {
if (sumw_ == 0.0) {
return -1;
}
float meanx = sumx_ / sumw_;
float meany = sumy_ / sumw_;
float meanxx = sumxx_ / sumw_;
float meanyy = sumyy_ / sumw_;
float meanxy = sumxy_ / sumw_;
float varx = meanxx - meanx * meanx;
float vary = meanyy - meany * meany;
if (varx < 0.1 || vary < 0.1) {
return -1;
} else {
return (meanxy - meanx * meany) / sqrt(varx * vary);
}
}
void ApplyHomography(const cv::Matx33f &H, float x1, float y1, float *x2,
float *y2) {
float w = H(2, 0) * x1 + H(2, 1) * y1 + H(2, 2);
if (w == 0.0) {
*x2 = 0.0f;
*y2 = 0.0f;
return;
}
*x2 = (H(0, 0) * x1 + H(0, 1) * y1 + H(0, 2)) / w;
*y2 = (H(1, 0) * x1 + H(1, 1) * y1 + H(1, 2)) / w;
}
cv::Matx33d PlaneInducedHomography(const cv::Matx33d &K1, const cv::Matx33d &R1,
const cv::Vec3d &t1, const cv::Matx33d &K2,
const cv::Matx33d &R2, const cv::Vec3d &t2,
const cv::Vec3d &v) {
cv::Matx33d R2R1 = R2 * R1.t();
return K2 * (R2R1 + (R2R1 * t1 - t2) * v.t()) * K1.inv();
}
cv::Matx33f PlaneInducedHomographyBaked(const cv::Matx33d &K1inv,
const cv::Matx33d &Q2,
const cv::Vec3d &a2,
const cv::Matx33d &K2,
const cv::Vec3d &v) {
return K2 * (Q2 + a2 * v.t()) * K1inv;
}
cv::Vec3d Project(const cv::Vec3d &x, const cv::Matx33d &K,
const cv::Matx33d &R, const cv::Vec3d &t) {
return K * (R * x + t);
}
cv::Vec3d Backproject(double x, double y, double depth, const cv::Matx33d &K,
const cv::Matx33d &R, const cv::Vec3d &t) {
return R.t() * (depth * K.inv() * cv::Vec3d(x, y, 1) - t);
}
float DepthOfPlaneBackprojection(double x, double y, const cv::Matx33d &K,
const cv::Vec3d &plane) {
float denom = -(plane.t() * K.inv() * cv::Vec3d(x, y, 1))(0);
return 1.0f / std::max(1e-6f, denom);
}
cv::Vec3f PlaneFromDepthAndNormal(float x, float y, const cv::Matx33d &K,
float depth, const cv::Vec3f &normal) {
cv::Vec3f point = depth * K.inv() * cv::Vec3d(x, y, 1);
float denom = -normal.dot(point);
return normal / std::max(1e-6f, denom);
}
float UniformRand(float a, float b) {
return a + (b - a) * float(rand()) / RAND_MAX;
}
DepthmapEstimator::DepthmapEstimator()
: patch_size_(7),
min_depth_(0),
max_depth_(0),
num_depth_planes_(50),
patchmatch_iterations_(3),
min_patch_variance_(5 * 5),
rng_{std::random_device{}()},
uni_(0, 0),
unit_normal_(0, 1),
patch_variance_buffer_(patch_size_ * patch_size_) {}
void DepthmapEstimator::AddView(const double *pK, const double *pR,
const double *pt, const unsigned char *pimage,
const unsigned char *pmask, int width,
int height) {
Ks_.emplace_back(pK);
Rs_.emplace_back(pR);
ts_.emplace_back(pt);
Kinvs_.emplace_back(Ks_.back().inv());
Qs_.emplace_back(Rs_.back() * Rs_.front().t());
as_.emplace_back(Qs_.back() * ts_.front() - ts_.back());
images_.emplace_back(cv::Mat(height, width, CV_8U, (void *)pimage).clone());
masks_.emplace_back(cv::Mat(height, width, CV_8U, (void *)pmask).clone());
std::size_t size = images_.size();
int a = (size > 1) ? 1 : 0;
int b = (size > 1) ? size - 1 : 0;
uni_.param(std::uniform_int_distribution<int>::param_type(a, b));
}
void DepthmapEstimator::SetDepthRange(double min_depth, double max_depth,
int num_depth_planes) {
min_depth_ = min_depth;
max_depth_ = max_depth;
num_depth_planes_ = num_depth_planes;
}
void DepthmapEstimator::SetPatchMatchIterations(int n) {
patchmatch_iterations_ = n;
}
void DepthmapEstimator::SetPatchSize(int size) {
patch_size_ = size;
patch_variance_buffer_.resize(patch_size_ * patch_size_);
}
void DepthmapEstimator::SetMinPatchSD(float sd) {
min_patch_variance_ = sd * sd;
}
void DepthmapEstimator::ComputeBruteForce(DepthmapEstimatorResult *result) {
AssignMatrices(result);
int hpz = (patch_size_ - 1) / 2;
for (int i = hpz; i < result->depth.rows - hpz; ++i) {
for (int j = hpz; j < result->depth.cols - hpz; ++j) {
for (int d = 0; d < num_depth_planes_; ++d) {
float depth =
1 / (1 / min_depth_ + d * (1 / max_depth_ - 1 / min_depth_) /
(num_depth_planes_ - 1));
cv::Vec3f normal(0, 0, -1);
cv::Vec3f plane = PlaneFromDepthAndNormal(j, i, Ks_[0], depth, normal);
CheckPlaneCandidate(result, i, j, plane);
}
}
}
}
void DepthmapEstimator::ComputePatchMatch(DepthmapEstimatorResult *result) {
AssignMatrices(result);
RandomInitialization(result, false);
ComputeIgnoreMask(result);
for (int i = 0; i < patchmatch_iterations_; ++i) {
PatchMatchForwardPass(result, false);
PatchMatchBackwardPass(result, false);
}
PostProcess(result);
}
void DepthmapEstimator::ComputePatchMatchSample(
DepthmapEstimatorResult *result) {
AssignMatrices(result);
RandomInitialization(result, true);
ComputeIgnoreMask(result);
for (int i = 0; i < patchmatch_iterations_; ++i) {
PatchMatchForwardPass(result, true);
PatchMatchBackwardPass(result, true);
}
PostProcess(result);
}
void DepthmapEstimator::AssignMatrices(DepthmapEstimatorResult *result) {
result->depth = cv::Mat(images_[0].rows, images_[0].cols, CV_32F, 0.0f);
result->plane = cv::Mat(images_[0].rows, images_[0].cols, CV_32FC3, 0.0f);
result->score = cv::Mat(images_[0].rows, images_[0].cols, CV_32F, 0.0f);
result->nghbr =
cv::Mat(images_[0].rows, images_[0].cols, CV_32S, cv::Scalar(0));
}
void DepthmapEstimator::RandomInitialization(DepthmapEstimatorResult *result,
bool sample) {
int hpz = (patch_size_ - 1) / 2;
for (int i = hpz; i < result->depth.rows - hpz; ++i) {
for (int j = hpz; j < result->depth.cols - hpz; ++j) {
float depth = exp(UniformRand(log(min_depth_), log(max_depth_)));
cv::Vec3f normal(UniformRand(-1, 1), UniformRand(-1, 1), -1);
cv::Vec3f plane = PlaneFromDepthAndNormal(j, i, Ks_[0], depth, normal);
int nghbr;
float score;
if (sample) {
nghbr = uni_(rng_);
score = ComputePlaneImageScore(i, j, plane, nghbr);
} else {
ComputePlaneScore(i, j, plane, &score, &nghbr);
}
AssignPixel(result, i, j, depth, plane, score, nghbr);
}
}
}
void DepthmapEstimator::ComputeIgnoreMask(DepthmapEstimatorResult *result) {
int hpz = (patch_size_ - 1) / 2;
for (int i = hpz; i < result->depth.rows - hpz; ++i) {
for (int j = hpz; j < result->depth.cols - hpz; ++j) {
bool masked = masks_[0].at<unsigned char>(i, j) == 0;
bool low_variance = PatchVariance(i, j) < min_patch_variance_;
if (masked || low_variance) {
AssignPixel(result, i, j, 0.0f, cv::Vec3f(0, 0, 0), 0.0f, 0);
}
}
}
}
float DepthmapEstimator::PatchVariance(int i, int j) {
float *patch = patch_variance_buffer_.data();
int hpz = (patch_size_ - 1) / 2;
int counter = 0;
for (int u = -hpz; u <= hpz; ++u) {
for (int v = -hpz; v <= hpz; ++v) {
patch[counter++] = images_[0].at<unsigned char>(i + u, j + v);
}
}
return Variance(patch, patch_size_ * patch_size_);
}
void DepthmapEstimator::PatchMatchForwardPass(DepthmapEstimatorResult *result,
bool sample) {
int adjacent[2][2] = {{-1, 0}, {0, -1}};
int hpz = (patch_size_ - 1) / 2;
for (int i = hpz; i < result->depth.rows - hpz; ++i) {
for (int j = hpz; j < result->depth.cols - hpz; ++j) {
PatchMatchUpdatePixel(result, i, j, adjacent, sample);
}
}
}
void DepthmapEstimator::PatchMatchBackwardPass(DepthmapEstimatorResult *result,
bool sample) {
int adjacent[2][2] = {{0, 1}, {1, 0}};
int hpz = (patch_size_ - 1) / 2;
for (int i = result->depth.rows - hpz - 1; i >= hpz; --i) {
for (int j = result->depth.cols - hpz - 1; j >= hpz; --j) {
PatchMatchUpdatePixel(result, i, j, adjacent, sample);
}
}
}
void DepthmapEstimator::PatchMatchUpdatePixel(DepthmapEstimatorResult *result,
int i, int j, int adjacent[2][2],
bool sample) {
// Ignore pixels with depth == 0.
if (result->depth.at<float>(i, j) == 0.0f) {
return;
}
// Check neighbors and their planes for adjacent pixels.
for (int k = 0; k < 2; ++k) {
int i_adjacent = i + adjacent[k][0];
int j_adjacent = j + adjacent[k][1];
// Do not propagate ignored adjacent pixels.
if (result->depth.at<float>(i_adjacent, j_adjacent) == 0.0f) {
continue;
}
cv::Vec3f plane = result->plane.at<cv::Vec3f>(i_adjacent, j_adjacent);
if (sample) {
int nghbr = result->nghbr.at<int>(i_adjacent, j_adjacent);
CheckPlaneImageCandidate(result, i, j, plane, nghbr);
} else {
CheckPlaneCandidate(result, i, j, plane);
}
}
// Check random planes for current neighbor.
float depth_range = 0.02;
float normal_range = 0.5;
int current_nghbr = result->nghbr.at<int>(i, j);
for (int k = 0; k < 6; ++k) {
float current_depth = result->depth.at<float>(i, j);
float depth = current_depth * exp(depth_range * unit_normal_(rng_));
cv::Vec3f current_plane = result->plane.at<cv::Vec3f>(i, j);
if (current_plane(2) == 0.0) {
continue;
}
cv::Vec3f normal(-current_plane(0) / current_plane(2) +
normal_range * unit_normal_(rng_),
-current_plane(1) / current_plane(2) +
normal_range * unit_normal_(rng_),
-1.0f);
cv::Vec3f plane = PlaneFromDepthAndNormal(j, i, Ks_[0], depth, normal);
if (sample) {
CheckPlaneImageCandidate(result, i, j, plane, current_nghbr);
} else {
CheckPlaneCandidate(result, i, j, plane);
}
depth_range *= 0.3;
normal_range *= 0.8;
}
if (!sample || images_.size() <= 2) {
return;
}
// Check random other neighbor for current plane.
int other_nghbr = uni_(rng_);
while (other_nghbr == current_nghbr) {
other_nghbr = uni_(rng_);
}
cv::Vec3f plane = result->plane.at<cv::Vec3f>(i, j);
CheckPlaneImageCandidate(result, i, j, plane, other_nghbr);
}
void DepthmapEstimator::CheckPlaneCandidate(DepthmapEstimatorResult *result,
int i, int j,
const cv::Vec3f &plane) {
float score;
int nghbr;
ComputePlaneScore(i, j, plane, &score, &nghbr);
if (score > result->score.at<float>(i, j)) {
float depth = DepthOfPlaneBackprojection(j, i, Ks_[0], plane);
AssignPixel(result, i, j, depth, plane, score, nghbr);
}
}
void DepthmapEstimator::CheckPlaneImageCandidate(
DepthmapEstimatorResult *result, int i, int j, const cv::Vec3f &plane,
int nghbr) {
float score = ComputePlaneImageScore(i, j, plane, nghbr);
if (score > result->score.at<float>(i, j)) {
float depth = DepthOfPlaneBackprojection(j, i, Ks_[0], plane);
AssignPixel(result, i, j, depth, plane, score, nghbr);
}
}
void DepthmapEstimator::AssignPixel(DepthmapEstimatorResult *result, int i,
int j, const float depth,
const cv::Vec3f &plane, const float score,
const int nghbr) {
result->depth.at<float>(i, j) = depth;
result->plane.at<cv::Vec3f>(i, j) = plane;
result->score.at<float>(i, j) = score;
result->nghbr.at<int>(i, j) = nghbr;
}
void DepthmapEstimator::ComputePlaneScore(int i, int j, const cv::Vec3f &plane,
float *score, int *nghbr) {
*score = -1.0f;
*nghbr = 0;
for (int other = 1; other < images_.size(); ++other) {
float image_score = ComputePlaneImageScore(i, j, plane, other);
if (image_score > *score) {
*score = image_score;
*nghbr = other;
}
}
}
float DepthmapEstimator::ComputePlaneImageScoreUnoptimized(
int i, int j, const cv::Vec3f &plane, int other) {
cv::Matx33f H = PlaneInducedHomographyBaked(Kinvs_[0], Qs_[other], as_[other],
Ks_[other], plane);
int hpz = (patch_size_ - 1) / 2;
float im1_center = images_[0].at<unsigned char>(i, j);
NCCEstimator ncc;
for (int dy = -hpz; dy <= hpz; ++dy) {
for (int dx = -hpz; dx <= hpz; ++dx) {
float im1 = images_[0].at<unsigned char>(i + dy, j + dx);
float x2, y2;
ApplyHomography(H, j + dx, i + dy, &x2, &y2);
float im2 = LinearInterpolation<unsigned char>(images_[other], y2, x2);
float weight = BilateralWeight(im1 - im1_center, dx, dy);
ncc.Push(im1, im2, weight);
}
}
return ncc.Get();
}
float DepthmapEstimator::ComputePlaneImageScore(int i, int j,
const cv::Vec3f &plane,
int other) {
cv::Matx33f H = PlaneInducedHomographyBaked(Kinvs_[0], Qs_[other], as_[other],
Ks_[other], plane);
int hpz = (patch_size_ - 1) / 2;
float u = H(0, 0) * j + H(0, 1) * i + H(0, 2);
float v = H(1, 0) * j + H(1, 1) * i + H(1, 2);
float w = H(2, 0) * j + H(2, 1) * i + H(2, 2);
if (w == 0.0) {
return -1.0f;
}
float dfdx_x = (H(0, 0) * w - H(2, 0) * u) / (w * w);
float dfdx_y = (H(1, 0) * w - H(2, 0) * v) / (w * w);
float dfdy_x = (H(0, 1) * w - H(2, 1) * u) / (w * w);
float dfdy_y = (H(1, 1) * w - H(2, 1) * v) / (w * w);
float Hx0 = u / w;
float Hy0 = v / w;
float im1_center = images_[0].at<unsigned char>(i, j);
NCCEstimator ncc;
for (int dy = -hpz; dy <= hpz; ++dy) {
for (int dx = -hpz; dx <= hpz; ++dx) {
float im1 = images_[0].at<unsigned char>(i + dy, j + dx);
float x2 = Hx0 + dfdx_x * dx + dfdy_x * dy;
float y2 = Hy0 + dfdx_y * dx + dfdy_y * dy;
float im2 = LinearInterpolation<unsigned char>(images_[other], y2, x2);
float weight = BilateralWeight(im1 - im1_center, dx, dy);
ncc.Push(im1, im2, weight);
}
}
return ncc.Get();
}
float DepthmapEstimator::BilateralWeight(float dcolor, float dx, float dy) {
const float dcolor_sigma = 50.0f;
const float dx_sigma = 5.0f;
const float dcolor_factor = 1.0f / (2 * dcolor_sigma * dcolor_sigma);
const float dx_factor = 1.0f / (2 * dx_sigma * dx_sigma);
return exp(-dcolor * dcolor * dcolor_factor -
(dx * dx + dy * dy) * dx_factor);
}
void DepthmapEstimator::PostProcess(DepthmapEstimatorResult *result) {
cv::Mat depth_filtered;
cv::medianBlur(result->depth, depth_filtered, 5);
for (int i = 0; i < result->depth.rows; ++i) {
for (int j = 0; j < result->depth.cols; ++j) {
float d = result->depth.at<float>(i, j);
float m = depth_filtered.at<float>(i, j);
if (d == 0.0 || fabs(d - m) / d > 0.05) {
result->depth.at<float>(i, j) = 0;
}
}
}
}
DepthmapCleaner::DepthmapCleaner()
: same_depth_threshold_(0.01), min_consistent_views_(2) {}
void DepthmapCleaner::SetSameDepthThreshold(float t) {
same_depth_threshold_ = t;
}
void DepthmapCleaner::SetMinConsistentViews(int n) {
min_consistent_views_ = n;
}
void DepthmapCleaner::AddView(const double *pK, const double *pR,
const double *pt, const float *pdepth, int width,
int height) {
Ks_.emplace_back(pK);
Rs_.emplace_back(pR);
ts_.emplace_back(pt);
depths_.emplace_back(cv::Mat(height, width, CV_32F, (void *)pdepth).clone());
}
void DepthmapCleaner::Clean(cv::Mat *clean_depth) {
*clean_depth = cv::Mat(depths_[0].rows, depths_[0].cols, CV_32F, 0.0f);
for (int i = 0; i < depths_[0].rows; ++i) {
for (int j = 0; j < depths_[0].cols; ++j) {
float depth = depths_[0].at<float>(i, j);
cv::Vec3f point = Backproject(j, i, depth, Ks_[0], Rs_[0], ts_[0]);
int consistent_views = 1;
for (int other = 1; other < depths_.size(); ++other) {
cv::Vec3f reprojection =
Project(point, Ks_[other], Rs_[other], ts_[other]);
if (reprojection(2) < z_epsilon || isnan(reprojection(2))) {
continue;
}
float u = reprojection(0) / reprojection(2);
float v = reprojection(1) / reprojection(2);
float depth_of_point = reprojection(2);
float depth_at_reprojection =
LinearInterpolation<float>(depths_[other], v, u);
if (fabs(depth_at_reprojection - depth_of_point) <
depth_of_point * same_depth_threshold_) {
consistent_views++;
}
}
if (consistent_views >= min_consistent_views_) {
clean_depth->at<float>(i, j) = depths_[0].at<float>(i, j);
} else {
clean_depth->at<float>(i, j) = 0;
}
}
}
}
DepthmapPruner::DepthmapPruner() : same_depth_threshold_(0.01) {}
void DepthmapPruner::SetSameDepthThreshold(float t) {
same_depth_threshold_ = t;
}
void DepthmapPruner::AddView(const double *pK, const double *pR,
const double *pt, const float *pdepth,
const float *pplane, const unsigned char *pcolor,
const unsigned char *plabel, int width,
int height) {
Ks_.emplace_back(pK);
Rs_.emplace_back(pR);
ts_.emplace_back(pt);
depths_.emplace_back(cv::Mat(height, width, CV_32F, (void *)pdepth).clone());
planes_.emplace_back(
cv::Mat(height, width, CV_32FC3, (void *)pplane).clone());
colors_.emplace_back(cv::Mat(height, width, CV_8UC3, (void *)pcolor).clone());
labels_.emplace_back(cv::Mat(height, width, CV_8U, (void *)plabel).clone());
}
void DepthmapPruner::Prune(std::vector<float> *merged_points,
std::vector<float> *merged_normals,
std::vector<unsigned char> *merged_colors,
std::vector<unsigned char> *merged_labels) {
cv::Matx33f Rinv = Rs_[0].t();
for (int i = 0; i < depths_[0].rows; ++i) {
for (int j = 0; j < depths_[0].cols; ++j) {
float depth = depths_[0].at<float>(i, j);
if (depth <= 0) {
continue;
}
cv::Vec3f normal = cv::normalize(planes_[0].at<cv::Vec3f>(i, j));
float area = -normal(2) / depth * Ks_[0](0, 0);
cv::Vec3f point = Backproject(j, i, depth, Ks_[0], Rs_[0], ts_[0]);
bool keep = true;
for (int other = 1; other < depths_.size(); ++other) {
cv::Vec3d reprojection =
Project(point, Ks_[other], Rs_[other], ts_[other]);
if (reprojection(2) < z_epsilon || isnan(reprojection(2))) {
continue;
}
std::int64_t iu =
static_cast<std::int64_t>(reprojection(0) / reprojection(2) + 0.5);
std::int64_t iv =
static_cast<std::int64_t>(reprojection(1) / reprojection(2) + 0.5);
double depth_of_point = reprojection(2);
if (!IsInsideImage(depths_[other], iv, iu)) {
continue;
}
float depth_at_reprojection = depths_[other].at<float>(iv, iu);
if (depth_at_reprojection >
(1 - same_depth_threshold_) * depth_of_point) {
cv::Vec3f normal_at_reprojection =
cv::normalize(planes_[other].at<cv::Vec3f>(iv, iu));
if ((depth_at_reprojection == 0.0) ||
(-normal_at_reprojection(2) / depth_at_reprojection *
Ks_[other](0, 0) >
area)) {
keep = false;
break;
}
}
}
if (keep) {
cv::Vec3f R1_normal = Rinv * normal;
cv::Vec3b color = colors_[0].at<cv::Vec3b>(i, j);
unsigned char label = labels_[0].at<unsigned char>(i, j);
merged_points->push_back(point[0]);
merged_points->push_back(point[1]);
merged_points->push_back(point[2]);
merged_normals->push_back(R1_normal[0]);
merged_normals->push_back(R1_normal[1]);
merged_normals->push_back(R1_normal[2]);
merged_colors->push_back(color[0]);
merged_colors->push_back(color[1]);
merged_colors->push_back(color[2]);
merged_labels->push_back(label);
}
}
}
}
} // namespace dense
| true |
b4323653296b83b09009e29089e65232e21ac462
|
C++
|
sudiptog81/ducscode
|
/YearI/SemesterII/DiscreteStructures/Practicals/representIODegree/main.cpp
|
UTF-8
| 2,109 | 4.21875 | 4 |
[
"MIT"
] |
permissive
|
/**
* WAP to accept a directed graph and calculate the in-degree
* and out-degree of each vertex
*
* Written by Sudipto Ghosh for the University of Delhi
*/
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
// Accept the number of vertices in the graph
int v;
cout << "Enter the number of vertices: ";
cin >> v;
// Initialize the Adjacency Matrix with zeroes
int matrix[v][v];
for (int i = 0; i < v; i++)
for (int j = 0; j < v; j++)
matrix[i][j] = 0;
// Iterate over the number of vertices
for (int i = 0, e; i < v; i++)
{
cout << "Enter the number of edges incoming to vertex " << i + 1 << ": ";
cin >> e;
// Iterate over the number of edges incoming to ith vertex
for (int j = 0, f; j < e; j++)
{
cout << "Enter vertex from which the incoming edge to vertex " << i + 1 << " is emerging from: ";
cin >> f;
// Set -1 in correct position
matrix[i][f - 1] = -1;
}
cout << "Enter the number of edges outgoing from vertex " << i + 1 << ": ";
cin >> e;
// Iterate over the number of edges outgoing from ith vertex
for (int j = 0, f; j < e; j++)
{
cout << "Enter vertex from which the outgoing edge from vertex " << i + 1 << " is ending at: ";
cin >> f;
// Set 1 in correct position
matrix[i][f - 1] = 1;
}
}
// Calculate degrees for each vertex
for (int i = 0; i < v; i++)
{
int inDegree = 0, outDegree = 0;
for (int j = 0; j < v; j++)
{
if (matrix[i][j] == -1)
inDegree += matrix[i][j];
if (matrix[i][j] == 1)
outDegree += matrix[i][j];
}
// Output the outdegrees and indegrees
cout << "\nOutdegree of vertex " << i + 1 << ": " << outDegree
<< "\tIndegree of vertex " << i + 1 << ": " << abs(inDegree)
<< endl;
}
return 0;
}
| true |
9f0a48152d2747a18145a217cfe04fb3aad7f7ec
|
C++
|
CatanaRaulAndrei/MINI_PROIECTE
|
/Euler_totient.cpp
|
UTF-8
| 727 | 3.421875 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
class Functia_PHI{
private:
int n;
public:
int PHI(int n);
void Afisare_PHI(int numar_functii);
};
int Functia_PHI::PHI(int n){
int rezultat = n;
for(int p = 2 ; p*p < n; p++){
if(n % p == 0){
while(n % p){
n = n/p;
}
rezultat = rezultat - rezultat/p;
}
}
if(n > 1){
rezultat = rezultat - rezultat/n;
}
return rezultat;
}
void Functia_PHI::Afisare_PHI(int numar_functii){
for (int i = 1; i <= numar_functii; i++){
cout<<"phi["<<i<<"]="<<PHI(i)<<endl;
}
}
int main(){
Functia_PHI obj;
obj.Afisare_PHI(10);// PHI(1)........numar_functii_de_phi
return 0;
}
| true |
e71b2898b641c84e64ef134666f6802da43b1edd
|
C++
|
x-insane/os_experiments
|
/exp3/socket_test.cpp
|
UTF-8
| 2,476 | 2.828125 | 3 |
[] |
no_license
|
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
int port = 16352;
void error(const char* err) {
std::cerr << err << std::endl;
}
void server() {
int server_sockfd;
int client_sockfd;
sockaddr_in local_addr;
sockaddr_in remote_addr;
local_addr.sin_family = AF_INET;
local_addr.sin_addr.s_addr = INADDR_ANY;
local_addr.sin_port = htons(port);
if ((server_sockfd = socket(PF_INET,SOCK_STREAM,0)) < 0) {
error("can not open socket.");
exit(-1);
}
if (bind(server_sockfd, (sockaddr*) &local_addr, sizeof(sockaddr)) < 0) {
error("can not bind IP address.");
exit(-1);
}
if (listen(server_sockfd, 5) < 0) {
error("can not listen on port.");
exit(-1);
}
std::cout << "listen on port " << port << "..." << std::endl;
unsigned int sin_size = sizeof(sockaddr_in);
if ((client_sockfd = accept(server_sockfd, (sockaddr*) &remote_addr, &sin_size)) < 0) {
error("can not accept the client socket.");
exit(-1);
}
std::cout << "accept a client " << inet_ntoa(remote_addr.sin_addr) << std::endl;
char buffer[100] = "hello world!";
int len = write(client_sockfd, buffer, strlen(buffer));
std::cout << "send " << len << " bytes to client: " << buffer << std::endl;
while ((len = read(client_sockfd, buffer, 100)) > 0) {
buffer[len] = 0;
std::cout << "receive " << len << " bytes from client: " << buffer << std::endl;
sleep(1);
len = write(client_sockfd, buffer, strlen(buffer));
std::cout << "send " << len << " bytes to client: " << buffer << std::endl;
}
close(client_sockfd);
close(server_sockfd);
}
void client() {
int client_sockfd;
sockaddr_in remote_addr;
remote_addr.sin_family = AF_INET;
remote_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
remote_addr.sin_port = htons(port);
if ((client_sockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
error("can not open a client socket.");
exit(-1);
}
if (connect(client_sockfd, (sockaddr*) &remote_addr, sizeof(sockaddr)) < 0) {
error("can not connect the server socket.");
exit(-1);
}
char buffer[100];
int len = 0;
while((len = read(client_sockfd, buffer, 100)) > 0) {
buffer[len] = 0;
write(client_sockfd, buffer, strlen(buffer));
}
close(client_sockfd);
}
int main() {
if (fork() == 0)
client();
else
server();
return 0;
}
| true |
c39dffb841a721ca0686022dfc1a3ac9328e5faf
|
C++
|
LukaC256/simple-spectrum
|
/src/playback.cpp
|
UTF-8
| 833 | 2.640625 | 3 |
[] |
no_license
|
#include <SDL.h>
#include <iostream>
#include "utils.hpp"
using namespace std;
EResult fPlayback(short* wave, WAVEFORMAT format, long bytecount, float speed)
{
SDL_AudioSpec audiospec;
audiospec.freq = format.dwSamplesPerSec * speed;
audiospec.format = AUDIO_S16LSB;
audiospec.channels = format.wChannels;
audiospec.samples = 4096;
audiospec.callback = NULL;
SDL_AudioDeviceID device = SDL_OpenAudioDevice(NULL, 0, &audiospec, NULL, 0);
if (device == 0) {
cout << "Failed to open Audio Device: " << SDL_GetError() << endl;
return ER_E_GENERAL;
}
SDL_QueueAudio(device, (void*) wave, bytecount);
SDL_PauseAudioDevice(device, 0);
cout << "Currently Playing, type q to quit." << endl;
char inchar = '\0';
do {
inchar = getchar();
} while(inchar != 'q');
SDL_CloseAudioDevice(device);
return ER_S_OK;
}
| true |
a7c18b2699b5f828f2d81825aeb255a71f1cd6aa
|
C++
|
0daryo/cpp-atcoder
|
/lib/modpow/modpow.cpp
|
UTF-8
| 246 | 3.1875 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
int modPow(long long a, long long n, long long p)
{
if (n == 1)
return a % p;
if (n % 2 == 1)
return (a * modPow(a, n - 1, p)) % p;
long long t = modPow(a, n / 2, p);
return (t * t) % p;
}
| true |
5e0dec006c41756849d0079658d3210aab7c565e
|
C++
|
SeanTheBuilder1/tictactoe
|
/src/game.cpp
|
UTF-8
| 3,472 | 3.0625 | 3 |
[] |
no_license
|
#include <iostream>
#include <string>
#include <thread>
#include <chrono>
#define AY
class Game{
private:
std::string state;
public:
std::string getState(){
return state;
}
void gameStart(){
for(int i = 0; i < 9; ++i){
state [i] = (i + 1 + '0');
}
}
Game():state(){
gameStart();
}
bool turnX(int x){
if(state[x - 1] != 'O' && state[x - 1] != 'X' && x <= (9) && x >= (1)){
state[x - 1] = 'X';
return true;
}
else{
std::cout << (x <= (0));
std::cout << "Invalid Move\n";
return false;
}
}
bool turnO(int o){
if(state[o - 1] != 'X' && state[o - 1] != 'O' && o <= 9 && o >= 1){
state[o - 1] = 'O';
return true;
}
else{
std::cout << "Invalid Move\n";
return false;
}
}
friend std::ostream& operator<<(std::ostream& out, Game& x){
for(int i = 0; i < 3; ++i){
out << x.state[(i * 3)] << '|' <<
x.state[((i*3) + 1)] << '|' <<
x.state[((i * 3) + 2)] << '\n';
}
return out;
}
int checkGame(){
for(int i = 0; i < 3; ++i){
if(state[(i * 3)] == state [(i * 3) + 1] && state[(i * 3 ) + 1] == state[(i * 3) + 2]){
std::cout << state[i * 3] << " has won the game\n";
if(state[i * 3] == 'X'){
return 2;
}
else if(state[i * 3] == 'O'){
return 3;
}
}
if(state[i] == state[i + 3] && state[i + 3] == state[i + 6]){
std::cout << state[i] << " has won the game\n";
if(state[i] == 'X'){
return 2;
}
else if(state[i] == 'O'){
return 3;
}
}
}
if(state[0] == state[4] && state[4] == state[8]){
std::cout << state[0] << " has won the game\n";
if(state[0] == 'X'){
return 2;
}
else if(state[0] == 'O'){
return 3;
}
}
else if(state[2] == state[4] && state[4] == state[6]){
std::cout << state[2] << " has won the game\n";
if(state[2] == 'X'){
return 2;
}
else if(state[2] == 'O'){
return 3;
}
}
return 1;
}
};
#ifdef AY
/*
int main(){
Game game;
while(true){
game.gameStart();
bool Winning = true;
std::cout << game;
while(Winning){
while(true){
int input;
std::cout << "What number X?\n";
std::cin >> input;
bool pass = game.turnX(input);
if(pass)
break;
}
int state = game.checkGame();
std::cout << game;
if(state != 1)
break;
while(true){
int input2;
std::cout << "What number O?\n";
std::cin >> input2;
bool pass = game.turnO(input2);
if(pass)
break;
}
state = game.checkGame();
std::cout << game;
if(state != 1){
break;
}
}
std::cout << "\n";
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
}
}*/
#endif
| true |
afafdd87e6e426ce47785cd16de7f1b98c629449
|
C++
|
Mingchenchen/raptorx-zy
|
/contrib/BALL/include/BALL/CONCEPT/composite.h
|
UTF-8
| 51,483 | 2.734375 | 3 |
[] |
no_license
|
// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: composite.h,v 1.62.14.1 2007-03-25 21:23:37 oliver Exp $
//
// Author:
// Nicolas Boghossian
// Oliver Kohlbacher
//
#ifndef BALL_CONCEPT_COMPOSITE_H
#define BALL_CONCEPT_COMPOSITE_H
#ifndef BALL_COMMON_H
# include <BALL/common.h>
#endif
#ifndef BALL_CONCEPT_PERSISTENTOBJECT_H
# include <BALL/CONCEPT/persistentObject.h>
#endif
#ifndef BALL_CONCEPT_COMPARATOR_H
# include <BALL/CONCEPT/comparator.h>
#endif
#ifndef BALL_CONCEPT_BIDIRECTIONALITERATOR_H
# include <BALL/CONCEPT/bidirectionalIterator.h>
#endif
#ifndef BALL_CONCEPT_OBJECT_H
# include <BALL/CONCEPT/object.h>
#endif
#ifndef BALL_CONCEPT_SELECTABLE_H
# include <BALL/CONCEPT/selectable.h>
#endif
#ifndef BALL_CONCEPT_VISITOR_H
# include <BALL/CONCEPT/visitor.h>
#endif
#ifndef BALL_CONCEPT_PROCESSOR_H
# include <BALL/CONCEPT/processor.h>
#endif
#ifndef BALL_CONCEPT_TIMESTAMP_H
# include <BALL/CONCEPT/timeStamp.h>
#endif
///
namespace BALL
{
/** Composite Class.
This class implements a variant of the composite design pattern. A
Composite may contain an arbitrary number of other composites, thus
forming a tree. All BALL kernel classes are derived from Composite.
This provides a unique interface for all kernel classes.
\par
The composite class provides a selection mechanism that allows
hierarchical selection and deselection of arbitrary subtrees. The
time of the last selection/deselection operation is stored as well as
the time of the last modification operation in time stamps that can
be accessed via \link getModificationTime getModificationTime \endlink
and \link getSelectionTime getSelectionTime \endlink .
Selecting or deselecting a Composite automatically selects or
deselects all its children (recursively!). Selecting or deselecting
all children of a node deselects their parent as well. Selection
information is propagated upwards in the tree.
\par
Composites are persistent objects.
\par
\ingroup ConceptsMiscellaneous
*/
class BALL_EXPORT Composite
: public PersistentObject,
public Selectable
{
public:
/** @name Type Definitions and Enums
*/
//@{
#ifndef BALL_KERNEL_PREDICATE_TYPE
#define BALL_KERNEL_PREDICATE_TYPE
/** Composite predicate type.
This type declares a predicate operating on composites.
As it is used as a predicate for all kernel classes,
it is named KernelPredicateType.
*/
typedef UnaryPredicate<Composite> KernelPredicateType;
#endif
/** Time stamp type.
*/
enum StampType
{
/**
*/
MODIFICATION = 1,
/**
*/
SELECTION = 2,
/**
*/
BOTH = 3
};
//@}
BALL_CREATE_DEEP(Composite)
static UnaryProcessor<Composite> DEFAULT_PROCESSOR;
static KernelPredicateType DEFAULT_UNARY_PREDICATE;
/** @name Construction and Destruction
*/
//@{
/** Default constructor.
This constructor creates an empty composite object.
*/
Composite()
throw();
/** Copy constructor.
Creates a copy of a composite. <b> Deep </b> copies include the whole
composite tree, <b> shallow </b> copies contain anly a single composite.
@param composite the composite to be cloned (the root of the tree in
the case of a deep copy)
@param deep make a deep copy (<b>true</b>) or shallow copy
(<b>false</b>)
*/
Composite(const Composite& composite, bool deep = true)
throw();
/** Destructor.
The destructor calls \link destroy destroy \endlink to remove the composite from
potential tree structures. It also recursively destructs all
children of the composite.
*/
virtual ~Composite()
throw();
/** Clear the composite properties.
This method removes the composite's children and destructs them if
they are auto-deletable.
\par
It does not remove the composite from any parental structure.
\par
This method updates the modification time stamp of <tt>this</tt>.
@see stamp
@see AutoDeletable
@see destroy
*/
virtual void clear()
throw();
/** Destroy the composite.
This method removes the composite from potential parental
structures and then calls \link clear clear \endlink to destruct all children.
\par
This method updates the modification time stamp of <tt>this</tt>.
@see stamp
@see ~Composite
@see clear
*/
virtual void destroy()
throw();
/** Non-virtual destroy method.
This method behaves exactly like destroy except for a small
difference: when called with <b>true</b>, it calls the <b> virtual </b>
clear function. If called with <b>false</b> it calls the original
clear function of Composite. This is useful when implementing the
behaviour of derived classes.
\par
This method updates the modification time stamp of <tt>this</tt>.
@see stamp
@param virtual_destroy call the virtual clear method (<b>true</b>) or
<tt>Composite::clear()</tt> (<b>false</b>)
*/
void destroy(bool virtual_destroy)
throw();
/** Clone with a predicate.
This method copies the attributes of <tt>this</tt> composite to root
(shallow copy) and then adds recursively each of its children.
@param root the cloning target root is <tt>destroy</tt>ed prior to
any copying
@return a pointer to the root composite (<tt>&root</tt>)
*/
void* clone(Composite& root) const
throw();
//@}
/** @name Persistence
*/
//@{
/** Write a persistent copy of the object.
@param pm the persistence manager
@param name the object name
*/
virtual void persistentWrite(PersistenceManager& pm,
const char* name = 0) const
throw(Exception::GeneralException);
/** Read a persistent object.
@param pm the persistence manager
*/
virtual void persistentRead(PersistenceManager& pm)
throw(Exception::GeneralException);
//@}
/** @name Modifying and Accessing the Tree
*/
//@{
/** Assignment.
@param composite the Composite tree to assign from
@param deep a <tt>bool</tt> deciding whether the assignment will be
deep or shallow.
*/
void set(const Composite& composite, bool deep = true) throw();
/** Assignment operator.
@param composite the Composite tree to assign from
@return a const reference to <b>this</b>
*/
Composite& operator = (const Composite& composite) throw();
/** Assignment of a tree to another.
Create a deep (<tt>deep</tt> = <b>true</b>) or shallow copy of a composite
and assign it to <tt>composite</tt>. <tt>composite</tt> is destroyed first.
@param composite the composite to assign the copy to
@param deep <b>true</b> for a deep copy
*/
void get(Composite& composite, bool deep = true) const throw();
/** Return the degree of the node.
This method returns the number of children of a composite object.
@return Size the number of children
*/
Size getDegree() const throw();
/** Count the number of nodes fulfilling a predicate in this subtree.
@param predicate the predicate
@return Size the number of nodes in the subtree satisfying the predicate
*/
Size count(const KernelPredicateType& predicate) const throw();
/** Count the number of descendants.
@return Size the number of descendants of this node
*/
Size countDescendants() const throw();
/** Get the length of the path between two composite objects.
If no path exists <tt>INVALID_SIZE</tt> is returned.
@param composite the second object
@return Size the size of the path
*/
Size getPathLength(const Composite& composite) const throw();
/** Get the depth of this item in its tree.
The depth of a root item is 0.
@return Size the depth
*/
Size getDepth() const throw();
/** Get the height of this item in its tree.
The hight of a leaf is 0.
@return Size the height
*/
Size getHeight() const
throw();
/** Get the root of this item.
@return Composite& the root
*/
Composite& getRoot() throw();
/** Get a const reference to the root of this item.
@return Composite& the root
*/
const Composite& getRoot() const throw();
/** Get the lowest common ancestor of this item with an other.
If no common ancestor exists 0 is returned.
@return Composite& the lowest common ancestor
*/
Composite* getLowestCommonAncestor(const Composite& composite)
throw();
/** Get a const reference to the lowest common ancestor of this item
with an other. If no common ancestor exists, 0 is returned.
@return Composite& the lowest common ancestor
*/
const Composite* getLowestCommonAncestor(const Composite& composite) const
throw();
/** Find the first ancestor of type T.
This method walks up the tree from parent to parent and
checks whether the composite object is a kind of <tt>T</tt>.
This method is useful to identify special container classes.
@return a pointer to the first composite found that is a kind of T
or 0 if no matching composite was found up to the root of
the tree
*/
template <typename T>
T* getAncestor(const T& /* dummy */)
throw();
/** Find the first ancestor of type T (const method).
This method operates also on constant trees.
@return a pointer to the first composite found that is a kind of T
or 0 if no matching composite was found to the root of the
tree
*/
template <typename T>
const T* getAncestor(const T& /* dummy */) const throw();
/** Find the nearest previous composite of type T.
This method walks backward in the tree from composite to composite and
checks whether the composite object is a kind of <tt>T</tt>.
@return a pointer to the first composite found that is a kind of T
or 0 if no matching composite was found up to the root of
the tree
*/
template <typename T>
T* getPrevious(const T& /* dummy */) throw();
/** Find the nearest previous composite of type T (const method).
This method walks backward in the tree from composite to composite and
checks whether the composite object is a kind of <tt>T</tt>.
@return a pointer to the first composite found that is a kind of T
or 0 if no matching composite was found up to the root of
the tree
*/
template <typename T>
const T* getPrevious(const T& dummy) const throw();
/** Find the next composite of type T.
This method walks backward in the tree from composite to composite and
checks whether the composite object is a kind of <tt>T</tt>.
@return a pointer to the first composite found that is a kind of T
or 0 if no matching composite was found up to the root of
the tree
*/
template <typename T>
T* getNext(const T& /* dummy */) throw();
/** Find the next composite of type T (const method).
This method walks backward in the tree from composite to composite and
checks whether the composite object is a kind of <tt>T</tt>.
@return a pointer to the first composite found that is a kind of T
or 0 if no matching composite was found up to the root of
the tree
*/
template <typename T>
const T* getNext(const T& dummy) const throw();
/** Return the composite's parent.
@return a pointer to the parent composite or 0 if no parent exists
*/
Composite* getParent() throw();
/** Return the composite's parent (const method).
@return a pointer to the parent composite or 0 if no parent exists
*/
const Composite* getParent() const throw();
/** Return the <b> index </b>th child of this composite.
If no such child exists, 0 is returned.
The index of the first child is <b>0</b>.
@param index the index of the child to return
@return a pointer to the child or 0 if there is no such child.
*/
Composite* getChild(Index index) throw();
/** Return a const pointer to the <b> index </b>th child of this composite.
If no such child exists, 0 is returned.
The index of the first child is <b>0</b>.
@param index the index of the child to return
@return a const pointer to the child or 0 if there is no such child.
*/
const Composite* getChild(Index index) const throw();
/** Return a pointer to the sibling index positions from this composite.
A pointer to the sibling <tt>index</tt> positions to the right (for
positive values of <tt>index</tt>) or <tt>-index</tt> positions to the left
(for negative values of <tt>index</tt>) is returned.
For Index = 0 the this-pointer is returned.
@param index the index of the sibling
@return a pointer to the child or 0 if there is no such sibling.
*/
Composite* getSibling(Index index) throw();
/** Return a const pointer to the sibling index positions from this composite.
A pointer to the sibling <tt>index</tt> positions to the right (for
positive values of <tt>index</tt>) or <tt>-index</tt> positions to the left
(for negative values of <tt>index</tt>) is returned.
For Index = 0 the this-pointer is returned.
@param index the index of the sibling
@return a const pointer to the child or 0 if there is no such sibling.
*/
const Composite* getSibling(Index index) const throw();
/** Return a pointer to the first child.
@return a pointer to the first child or 0 if there is no child.
*/
Composite* getFirstChild() throw();
/** Return a const pointer to the first child.
@return a const pointer to the first child or 0 if there is no child.
*/
const Composite* getFirstChild() const throw();
/** Return a pointer to the last child.
@return a pointer to the last child or 0 if there is no child.
*/
Composite* getLastChild() throw();
/** Return a const pointer to the last child.
@return a const pointer to the last child or 0 if there is no child.
*/
const Composite* getLastChild() const throw();
/** Return the time of last modification
@return the last modification time
*/
const PreciseTime& getModificationTime() const throw();
/** Return the time of last change of selection.
@return the last time of change of selection
*/
const PreciseTime& getSelectionTime() const throw();
/** Modify a time stamp.
Update one or both of the two time stamps with the
current time. The time stamp is then propagated up to the
root of the composite tree. Each composite contains two stamps.
the <em>modification stamp</em> is updated each time the tree structure
changes, while the <em>selection stamp</em> is updated each time the
selection status changes.
@param stamp the time stamp type
*/
void stamp(StampType stamp = BOTH) throw();
/** Insert a composite as the first child of this composite.
Updates the modification time stamp.
@see stamp
@param composite the composite to be inserted
*/
void prependChild(Composite& composite) throw();
/** Insert a composite as the last child of this composite.
Updates the modification time stamp. <b>Note</b> that this method
alters the composite tree from which <tt>composite</tt> is taken,
if there is such a tree.
@see stamp
@param composite the composite to be inserted
*/
void appendChild(Composite& composite) throw();
/** Insert a new parent node.
This method is used to combine a range of nodes into a single
parent. First, the <tt>parent</tt> composite is <tt>destroy</tt>ed.
Then, all nodes from <tt>first</tt> through <tt>last</tt> are inserted
into <tt>parent</tt> and <tt>parent</tt> is inserted in the former
position of <tt>first</tt>. The method returns <b>false</b>, if {\tt
first} or <tt>last</tt> have differing parents, if <tt>parent</tt> is
identical with either <tt>first</tt> or <tt>last</tt>, or if <tt>first</tt>
is already a descendant of <tt>parent</tt>.
\par
This method updates the modification time stamp.
@see stamp
@param parent the new parent of the nodes from <tt>first</tt> through
<tt>last</tt>
@param first the first of the nodes to be inserted into <tt>parent</tt>
@param last the last of the nodes to be inserted into <tt>parent</tt>
@param destroy_parent keeps the current contents of <tt>parent</tt>
if set to <tt>true</tt>
*/
static bool insertParent(Composite& parent, Composite& first,
Composite& last, bool destroy_parent = true)
throw();
/** Insert a node before this node.
This method inserts <tt>composite</tt> before <tt>this</tt> node, if
<tt>this</tt> node has a parent and is not a descendant of <tt>composite</tt>.
Self-insertion is recognized and ignored (nothing is done).
\par
This method updates the modification time stamp.
@see stamp
@param composite the node to be inserted in the tree before <tt>this</tt>
*/
void insertBefore(Composite& composite) throw();
/** Insert a node after this node.
This method inserts <tt>composite</tt> after <tt>this</tt> node, if
<tt>this</tt> node has a parent and is not a descendant of <tt>composite</tt>.
Self-insertion is recognized and ignored (nothing is done).
\par
This method updates the modification time stamp.
@see stamp
@param composite the node to be inserted in the tree after of <tt>this</tt>
*/
void insertAfter(Composite& composite) throw();
/** Prepend all children of <tt>composite</tt> to the children of this
composite. The method does nothing, if <tt>composite</tt> is
identical to <tt>this</tt> or is a descendent of <tt>this</tt>.
\par
This method updates the modification time stamp.
@see stamp
@param the composite to be spliced
*/
void spliceBefore(Composite& composite) throw();
/** Append all children of <tt>composite</tt> to the children of this
composite. The method does nothing, if <tt>composite</tt> is
identical to <tt>this</tt> or is a descendent of <tt>this</tt>.
\par
This method updates the modification time stamp.
@see stamp
@param composite the composite to be spliced
*/
void spliceAfter(Composite& composite) throw();
/** Insert the children of composite into this composite.
The children of <tt>composite</tt> are inserted at the position of
<tt>composite</tt> if <tt>composite</tt> is a child of <tt>this</tt>.
Otherwise the children are inserted using \link spliceBefore spliceBefore \endlink .
\par
This method updates the modification time stamp.
@see stamp
@param composite the composite to be spliced
*/
void splice(Composite& composite) throw();
/** Remove a child from its parent.
<tt>child</tt> is only removed, if it is a true child of <tt>this</tt>.
\par
This method updates the modification time stamp of <tt>this</tt>.
@see stamp
@param child the child to remove
@return false if child could not be removed
*/
bool removeChild(Composite& child) throw();
/** Remove selected subcomposites.
This method iterates over all children of the current composite
and removes all selected composites by <tt>delete</tt>ing them.
If the respective Composite are not \link AutoDeletable \endlink,
they are just \link remove\endlink d from the hierarchy, but not
deleted.
This method is useful in combination with the \link Selector \endlink
class in order to remove unwanted partitions of kernel data structures.
@return the number of composites deleted.
*/
Size removeSelected() throw();
/** This instance and its subtree is removed form its tree and
replaced by <tt>composite</tt> and its subtree.
\par
This method updates the modification time stamp of
<tt>this</tt> and <tt>composite</tt>.
@see stamp
@param composite the composite which will be inserted
*/
void replace(Composite& composite) throw();
/** Swap the contents of two composites.
\par
This method updates the modification time stamp of <tt>this</tt> and
<tt>composite</tt>.
@see stamp
@param composite the composite with which the contents will be
swapped
*/
void swap(Composite& composite) throw();
/** Select a composite.
This method selects the composite and all the composites therein.
\par
If the state of this composite is modified, its selection time
stamp is updated and that of its ancestors (up to and including the
root composite) as well. The time stamps of descendants that
changed their selection state are update, too.
*/
virtual void select() throw();
/** Deselect a composite.
This method deselects the composite and all the composites therein.
\par
If the state of this composite is modified, its selection time
stamp is updated and that of its ancestors (up to and including the
root composite) as well. The time stamps of descendants that
changed their selection state are update, too.
*/
virtual void deselect() throw();
//@}
/** @name Predicates */
//@{
/** Equality operator.
Compares the handles of two Composite objects, therefore two
Composite objects can never be equal.
@see Object::operator ==
@param composite the composite against which equality will be tested
*/
bool operator == (const Composite& composite) const throw();
/** Inequality operator.
@see operator ==
B */
bool operator != (const Composite& composite) const
throw();
/** Return true if the node does not contain children.
@return bool <b>true</b> if <tt>number_of_children_ == 0</tt>
*/
bool isEmpty() const throw();
/** Return true if the node has no parent.
@return bool <b>true</b> if <tt>parent_ == 0</tt>
*/
bool isRoot() const throw();
/** Return true if the node is root of composite.
*/
bool isRootOf(const Composite& composite) const throw();
/** Return true if the node is not the root or a leaf.
*/
bool isInterior() const throw();
/** Return true if the node has a child.
*/
bool hasChild() const throw();
/** Return true if the node has the parent <tt>composite</tt>.
*/
bool isChildOf(const Composite& composite) const throw();
/** Return true if the node is the first child of its parent.
*/
bool isFirstChild() const throw();
/** Return true if the node is the first child of <tt>composite</tt>.
*/
bool isFirstChildOf(const Composite& composite) const throw();
/** Return true if the node is the last child of its parent.
*/
bool isLastChild() const throw();
/** Return true if the node is the last child of <tt>composite</tt>.
*/
bool isLastChildOf(const Composite& composite) const throw();
/** Return true if the node has a parent.
*/
bool hasParent() const throw();
/** Return true if the node is the parent of <tt>composite</tt>.
*/
bool isParentOf(const Composite& composite) const throw();
/** Return true if the node has a sibling.
(Its parent has other childs.)
*/
bool hasSibling() const throw();
/** Return true if the node is a sibling of <tt>composite</tt>.
*/
bool isSiblingOf(const Composite& composite) const throw();
/** Return true if the node has a previous sibling.
(Its parent has a child before this.)
*/
bool hasPreviousSibling() const throw();
/** Return true if the node is a previous sibling of <tt>composite</tt>.
*/
bool isPreviousSiblingOf(const Composite& composite) const throw();
/** Return true if the node has a previous sibling.
(Its parent has a child after this.)
*/
bool hasNextSibling() const throw();
/** Return true if the node is a next sibling of <tt>composite</tt>.
*/
bool isNextSiblingOf(const Composite& composite) const throw();
/** Return true if the node is a descendent of <tt>composite</tt>.
*/
bool isDescendantOf(const Composite& composite) const throw();
/** Return true if the node has a ancestor of the same type as dummy.
*/
template <typename T>
bool hasAncestor(const T& dummy) const throw();
/** Return true if the node has composite as descendent.
*/
bool isAncestorOf(const Composite& composite) const throw();
/** Return true if the node has composite as ancestor or
composite is ancestor of this node.
*/
bool isRelatedWith(const Composite& composite) const throw();
/** Return true if composite is homomorph to this node.
(The subtrees of the two instances have to be of the same form.)
*/
bool isHomomorph(const Composite& composite) const throw();
/** Return true if any descendant is selected.
This method does not check all nodes recursively. Instead, on each
modification of the tree, internal flags are updated and the
information is propagated upwards in the tree.
\par
Complexity: O(1)
\par
@return bool <b>true</b> if any node in the subtree is selected
*/
bool containsSelection() const throw();
//@}
/** @name Debugging and Diagnostics */
//@{
/** Test if the subtree with this node as root is valid.
(The structure of the subtree has to be valid.)
*/
virtual bool isValid() const throw();
/** Dump the constent of this instance to an ostream.
@param s the stream to which we will dump
@param depth the indentation depth of the output
*/
virtual void dump(std::ostream& s = std::cout, Size depth = 0) const
throw();
//@}
/** @name Application and Hosting */
//@{
/** Visitor host method.
Composites may be visited.
For an example look into Composite_test.C
@param visitor the visitor
*/
void host(Visitor<Composite>& visitor)
throw(Exception::GeneralException);
/** Apply a processor to all ancestors of this node.
@return true if the processor could be applied.
*/
template <typename T>
bool applyAncestor(UnaryProcessor<T>& processor)
throw(Exception::GeneralException);
/** Apply a processor to all children of this node.
@return true if the processor could be applied.
*/
template <typename T>
bool applyChild(UnaryProcessor<T>& processor)
throw(Exception::GeneralException);
/** Apply a processor to all descendents of this node.
The node itself is not processed.
The root of a subtree is accessed before the nodes in its left
and right subtree.
@return true if the processor could be applied.
*/
template <typename T>
bool applyDescendantPreorder(UnaryProcessor<T>& processor)
throw(Exception::GeneralException);
/** Apply a processor to all descendents of this node.
The node itself is not processed.
The root of a subtree is accessed after the nodes in its left
and right subtree.
@return true if the processor could be applied.
*/
template <typename T>
bool applyDescendantPostorder(UnaryProcessor<T>& processor)
throw(Exception::GeneralException);
/** Apply a processor to all descendents of this node.
The node itself is not processed.
applyDescendantPreorder is used.
@see applyDescendantPreorder
@return true if the processor could be applied.
*/
template <typename T>
bool applyDescendant(UnaryProcessor<T>& processor)
throw(Exception::GeneralException);
/** Apply a processor to the node and its subtree.
The root of a subtree is accessed before the nodes in its left
and right subtree.
@return true if the processor could be applied.
*/
template <typename T>
bool applyPreorder(UnaryProcessor<T>& processor)
throw(Exception::GeneralException);
/** Apply a processor to the node and its subtree.
The root of a subtree is accessed after the nodes in its left
and right subtree.
@return true if the processor could be applied.
*/
template <typename T>
bool applyPostorder(UnaryProcessor<T>& processor)
throw(Exception::GeneralException);
/** Apply a processor to the node and its subtree.
applyPreorder is used.
@see applyPreorder
@return true if the processor could be applied.
*/
template <typename T>
bool apply(UnaryProcessor<T>& processor)
throw(Exception::GeneralException);
/** Apply a processor to the node and its siblings.
@return true if the processor could be applied.
*/
template <typename T>
bool applyLevel(UnaryProcessor<T>& processor, long level)
throw(Exception::GeneralException);
//@}
class BALL_EXPORT AncestorIteratorTraits
{
public:
BALL_INLINE
AncestorIteratorTraits()
throw()
: bound_(0),
ancestor_(0)
{
}
BALL_INLINE
AncestorIteratorTraits(const Composite& composite)
throw()
: bound_(const_cast<Composite*>(&composite)),
ancestor_(0)
{
}
BALL_INLINE
AncestorIteratorTraits(const AncestorIteratorTraits& traits)
throw()
: bound_(traits.bound_),
ancestor_(traits.ancestor_)
{
}
BALL_INLINE
const AncestorIteratorTraits& operator = (const AncestorIteratorTraits& traits)
throw()
{
bound_ = traits.bound_;
ancestor_ = traits.ancestor_;
return *this;
}
BALL_INLINE Composite* getContainer() throw() { return bound_; }
BALL_INLINE const Composite* getContainer() const throw() { return bound_; }
BALL_INLINE bool isSingular() const throw() { return (bound_ == 0); }
BALL_INLINE Composite* getPosition() throw() { return ancestor_; }
BALL_INLINE Composite* const& getPosition() const throw() { return ancestor_; }
BALL_INLINE bool operator == (const AncestorIteratorTraits& traits) const throw() { return (ancestor_ == traits.ancestor_); }
BALL_INLINE bool operator != (const AncestorIteratorTraits& traits) const throw() { return !(ancestor_ == traits.ancestor_); }
BALL_INLINE bool isValid() const throw() { return (bound_ != 0 && ancestor_ != 0); }
BALL_INLINE void invalidate() throw() { bound_ = ancestor_ = 0; }
BALL_INLINE void toBegin() throw() { ancestor_ = bound_->parent_; }
BALL_INLINE bool isBegin() const throw() { return (ancestor_ == bound_->parent_); }
BALL_INLINE void toEnd() throw() { ancestor_ = 0; }
BALL_INLINE bool isEnd() const throw() { return (ancestor_ == 0); }
BALL_INLINE Composite& getData() throw() { return *ancestor_; }
BALL_INLINE const Composite& getData() const throw() { return *ancestor_; }
BALL_INLINE void forward() throw() { ancestor_ = ancestor_->parent_; }
private:
Composite* bound_;
Composite* ancestor_;
};
friend class AncestorIteratorTraits;
typedef ForwardIterator <Composite, Composite, Composite*, AncestorIteratorTraits>
AncestorIterator;
AncestorIterator beginAncestor() throw()
{
return AncestorIterator::begin(*this);
}
AncestorIterator endAncestor() throw()
{
return AncestorIterator::end(*this);
}
typedef ConstForwardIterator<Composite, Composite, Composite*, AncestorIteratorTraits>
AncestorConstIterator;
AncestorConstIterator beginAncestor() const throw()
{
return AncestorConstIterator::begin(*this);
}
AncestorConstIterator endAncestor() const throw()
{
return AncestorConstIterator::end(*this);
}
class BALL_EXPORT ChildCompositeIteratorTraits
{
public:
ChildCompositeIteratorTraits()
throw()
: bound_(0),
child_(0)
{
}
ChildCompositeIteratorTraits(const Composite& composite)
throw()
: bound_((Composite *)&composite),
child_(0)
{
}
ChildCompositeIteratorTraits(const ChildCompositeIteratorTraits& traits)
throw()
: bound_(traits.bound_),
child_(traits.child_)
{
}
const ChildCompositeIteratorTraits& operator = (const ChildCompositeIteratorTraits& traits)
throw()
{
bound_ = traits.bound_;
child_ = traits.child_;
return *this;
}
BALL_INLINE Composite* getContainer() throw() { return bound_; }
BALL_INLINE const Composite* getContainer() const throw() { return bound_; }
BALL_INLINE bool isSingular() const throw() { return (bound_ == 0); }
BALL_INLINE Composite* getPosition() throw() { return child_; }
BALL_INLINE Composite* const& getPosition() const throw() { return child_; }
BALL_INLINE bool operator == (const ChildCompositeIteratorTraits& traits) const throw() { return (child_ == traits.child_); }
BALL_INLINE bool operator != (const ChildCompositeIteratorTraits& traits) const throw() { return !(child_ == traits.child_); }
BALL_INLINE bool isValid() const throw() { return (bound_ != 0 && child_ != 0); }
BALL_INLINE void invalidate() throw() { bound_ = child_ = 0; }
BALL_INLINE void toBegin() throw() { child_ = bound_->first_child_; }
BALL_INLINE bool isBegin() const throw() { return (child_ == bound_->first_child_); }
BALL_INLINE void toEnd() throw() { child_ = 0; }
BALL_INLINE bool isEnd() const throw() { return (child_ == 0); }
BALL_INLINE void toRBegin() throw() { child_ = bound_->last_child_; }
BALL_INLINE bool isRBegin() const throw() { return (child_ == bound_->last_child_); }
BALL_INLINE void toREnd() throw() { child_ = 0; }
BALL_INLINE bool isREnd() const throw() { return (child_ == 0); }
BALL_INLINE Composite& getData() throw() { return *child_; }
BALL_INLINE const Composite& getData() const throw() { return *child_; }
BALL_INLINE void forward() throw() { child_ = child_->next_; }
BALL_INLINE void backward() throw()
{
if (child_ == 0)
{
// Allow decrementation for past-the-end iterators
child_ = bound_->last_child_;
}
else
{
child_ = child_->previous_;
}
}
private:
Composite* bound_;
Composite* child_;
};
friend class ChildCompositeIteratorTraits;
typedef BidirectionalIterator<Composite, Composite, Composite *, ChildCompositeIteratorTraits>
ChildCompositeIterator;
ChildCompositeIterator beginChildComposite()
throw()
{
return ChildCompositeIterator::begin(*this);
}
ChildCompositeIterator endChildComposite()
throw()
{
return ChildCompositeIterator::end(*this);
}
typedef ConstBidirectionalIterator<Composite, Composite, Composite *, ChildCompositeIteratorTraits>
ChildCompositeConstIterator;
ChildCompositeConstIterator beginChildComposite() const
throw()
{
return ChildCompositeConstIterator::begin(*this);
}
ChildCompositeConstIterator endChildComposite() const
throw()
{
return ChildCompositeConstIterator::end(*this);
}
typedef std::reverse_iterator<ChildCompositeIterator> ChildCompositeReverseIterator;
ChildCompositeReverseIterator rbeginChildComposite() throw()
{
return ChildCompositeReverseIterator(endChildComposite());
}
ChildCompositeReverseIterator rendChildComposite() throw()
{
return ChildCompositeReverseIterator(beginChildComposite());
}
typedef std::reverse_iterator<ChildCompositeConstIterator> ChildCompositeConstReverseIterator;
ChildCompositeConstReverseIterator rbeginChildComposite() const throw()
{
return ChildCompositeConstReverseIterator(endChildComposite());
}
ChildCompositeConstReverseIterator rendChildComposite() const throw()
{
return ChildCompositeConstReverseIterator(beginChildComposite());
}
class BALL_EXPORT CompositeIteratorTraits
{
public:
BALL_INLINE CompositeIteratorTraits()
throw()
: bound_(0),
position_(0)
{
}
CompositeIteratorTraits(const Composite& composite)
throw()
: bound_(const_cast<Composite*>(&composite)),
position_(0)
{
}
CompositeIteratorTraits(const CompositeIteratorTraits& traits)
throw()
: bound_(traits.bound_),
position_(traits.position_)
{
}
BALL_INLINE ~CompositeIteratorTraits() throw() {}
BALL_INLINE bool isValid() const throw()
{
return ((bound_ != 0) && (position_ != 0));
}
BALL_INLINE CompositeIteratorTraits& operator = (const CompositeIteratorTraits& traits) throw()
{
bound_ = traits.bound_;
position_ = traits.position_;
return *this;
}
BALL_INLINE Composite* getContainer() throw() { return bound_; }
BALL_INLINE const Composite* getContainer() const throw() { return bound_; }
BALL_INLINE bool isSingular() const throw() { return (bound_ == 0); }
BALL_INLINE Composite* getPosition() throw() { return position_; }
BALL_INLINE const Composite* getPosition() const throw() { return position_; }
BALL_INLINE void setPosition(Composite* position) throw() { position_ = position; }
BALL_INLINE Composite& getData() throw() { return *position_; }
BALL_INLINE const Composite& getData() const throw() { return *position_; }
BALL_INLINE bool operator == (const CompositeIteratorTraits& traits) const throw()
{
return (position_ == traits.position_);
}
BALL_INLINE bool operator != (const CompositeIteratorTraits& traits) const throw()
{
return !(position_ == traits.position_);
}
BALL_INLINE void invalidate() throw()
{
bound_ = 0;
position_ = 0;
}
BALL_INLINE void toBegin() throw()
{
position_ = bound_;
}
BALL_INLINE bool isBegin() const throw()
{
return (position_ == bound_);
}
BALL_INLINE void toEnd() throw()
{
position_ = 0;
}
BALL_INLINE bool isEnd() const throw()
{
return (position_ == 0);
}
BALL_INLINE void toRBegin() throw()
{
if (bound_ != 0)
{
position_ = findPreviousPosition(0);
}
}
BALL_INLINE bool isRBegin() const throw()
{
return (position_ == findPreviousPosition(0));
}
BALL_INLINE void toREnd() throw()
{
position_ = bound_;
}
BALL_INLINE bool isREnd() const throw()
{
return (position_ == bound_);
}
BALL_INLINE void forward() throw()
{
position_ = findNextPosition(position_);
}
BALL_INLINE void backward() throw()
{
position_ = findPreviousPosition(position_);
}
protected:
/// A pointer to the "container" the iterator is bound to
Composite* bound_;
/// The current iterator position
Composite* position_;
Composite* findPreviousPosition(Composite* p) const
{
// If we are at the root of the iterator, the
// decrementing it results in an invalid iterator
// (past-the-end).
if (p == bound_)
{
return 0;
}
// If we decrement a past-the-end-iterator, we
// start at the root and "fall down" on the right
// hand side following the last_child_ pointers
// until we hit bottom.
else if (p == 0)
{
if (bound_->last_child_ == 0)
{
return bound_;
}
else
{
p = bound_->last_child_;
}
while (p->last_child_ != 0)
{
p = p->last_child_;
}
}
// Normally, we just grab the guy to the
// left in the doubly-linked child list.
else if (p->previous_ != 0)
{
p = p->previous_;
// If the guy to the left hast children,
// we do the drop on the rigth again.
while (p->last_child_ != 0)
{
p = p->last_child_;
}
}
// Finally, if we can't go down and we can't go
// left, we have to go upwards.
else if (p != bound_)
{
p = p->parent_;
}
return p;
}
Composite* findNextPosition(Composite* p) const
{
// If we are in a past-the-end position, we stay put.
if (p == 0)
{
return 0;
}
// Otherwise, we try the first child. If there's one,
// that's our next position.
else
{
if (p->first_child_ != 0)
{
p = p->first_child_;
}
else
{
// If we are already in the root node, we are done.
if (p == bound_)
{
return 0;
}
// Otherwise, we try to walk to the right at the current level.
if (p->next_ != 0)
{
p = p->next_;
}
// If that doesn't work out, we'll have to climb up again.
// Now, we either revisit a node we have already been to, or we
// are trying to climb up *beyond* our iteration root (bound_).
// In the latter case, we return a past-the-end-iterator (0).
else
{
// If we could not walk left or right and we are at the root
// again, then we are done with the iteration (this is the
// case if bound_ is a leaf node).
while (p->next_ == 0)
{
p = p->parent_;
if ((p == bound_) || (p == 0))
{
return 0;
}
}
p = p->next_;
}
}
}
return p;
}
};
friend class CompositeIteratorTraits;
typedef BidirectionalIterator<Composite, Composite, Composite*, CompositeIteratorTraits>
CompositeIterator;
CompositeIterator beginComposite() throw() { return CompositeIterator::begin(*this); }
CompositeIterator endComposite() throw() { return CompositeIterator::end(*this); }
typedef ConstBidirectionalIterator<Composite, Composite, Composite*, CompositeIteratorTraits>
CompositeConstIterator;
CompositeConstIterator beginComposite() const throw()
{
return CompositeConstIterator::begin(*this);
}
CompositeConstIterator endComposite() const throw()
{
return CompositeConstIterator::end(*this);
}
typedef std::reverse_iterator<CompositeIterator> CompositeReverseIterator;
CompositeReverseIterator rbeginComposite() throw()
{
return CompositeReverseIterator(endComposite());
}
CompositeReverseIterator rendComposite() throw()
{
return CompositeReverseIterator(beginComposite());
}
typedef std::reverse_iterator<CompositeConstIterator> CompositeConstReverseIterator;
CompositeConstReverseIterator rbeginComposite() const throw()
{
return CompositeConstReverseIterator(endComposite());
}
CompositeConstReverseIterator rendComposite() const throw()
{
return CompositeConstReverseIterator(beginComposite());
}
private:
///
Size getHeight_(Size size, Size& max_height) const throw();
///
Size countDescendants_() const throw();
///
void clone_(Composite& parent, Composite& stack) const throw();
template <typename T>
bool applyLevelNostart_(UnaryProcessor<T>& processor, long level)
throw(Exception::GeneralException);
template <typename T>
bool applyChildNostart_(UnaryProcessor<T>& processor)
throw(Exception::GeneralException);
template <typename T>
bool applyPreorderNostart_(UnaryProcessor<T>& processor)
throw(Exception::GeneralException);
template <typename T>
bool applyDescendantPreorderNostart_(UnaryProcessor<T>& processor)
throw(Exception::GeneralException);
template <typename T>
bool applyDescendantPostorderNostart_(UnaryProcessor<T>& processor)
throw(Exception::GeneralException);
void updateSelection_() throw();
void determineSelection_() throw();
void select_(bool update_parent = true) throw();
void deselect_(bool update_parent = true) throw();
// private attributes
Size number_of_children_;
Composite* parent_;
Composite* previous_;
Composite* next_;
Composite* first_child_;
Composite* last_child_;
unsigned char properties_;
bool contains_selection_;
Size number_of_selected_children_;
Size number_of_children_containing_selection_;
TimeStamp selection_stamp_;
TimeStamp modification_stamp_;
};
template <typename T>
bool Composite::applyAncestor(UnaryProcessor<T>& processor)
throw(Exception::GeneralException)
{
if (processor.start() == false)
{
return false;
}
Processor::Result result;
for (Composite* composite = parent_; composite != 0; composite = composite->parent_)
{
T* t_ptr;
if ((t_ptr = dynamic_cast<T*>(composite)) != 0)
{
result = processor(*t_ptr);
if (result <= Processor::BREAK)
{
return (result == Processor::BREAK);
}
}
}
return processor.finish();
}
template <typename T>
bool Composite::applyChild(UnaryProcessor<T>& processor)
throw(Exception::GeneralException)
{
return processor.start() && applyChildNostart_(processor) && processor.finish();
}
template <typename T>
bool Composite::applyChildNostart_(UnaryProcessor<T>& processor)
throw(Exception::GeneralException)
{
Processor::Result result = Processor::CONTINUE;
for (Composite* composite = first_child_;
composite != 0; composite = composite->next_)
{
T* t_ptr;
if ((t_ptr = dynamic_cast<T*>(composite)) != 0)
{
result = processor(*t_ptr);
if (result <= Processor::BREAK)
{
break;
}
}
}
return (result >= Processor::BREAK);
}
template <typename T>
bool Composite::applyDescendantPreorder(UnaryProcessor<T>& processor)
throw(Exception::GeneralException)
{
return processor.start() && applyDescendantPreorderNostart_(processor) && processor.finish();
}
template <typename T>
bool Composite::applyDescendantPreorderNostart_(UnaryProcessor<T>& processor)
throw(Exception::GeneralException)
{
Processor::Result result;
for (Composite* composite = first_child_;
composite != 0; composite = composite->next_)
{
T* t_ptr;
if ((t_ptr = dynamic_cast<T*>(composite)) != 0)
{
result = processor(*t_ptr);
if (result <= Processor::BREAK)
{
return (result == Processor::BREAK);
}
}
if (composite->first_child_ != 0 && composite->applyDescendantPreorderNostart_(processor) == false)
{
return false;
}
}
return true;
}
template <typename T>
bool Composite::applyDescendantPostorder(UnaryProcessor<T>& processor)
throw(Exception::GeneralException)
{
return processor.start() && applyDescendantPostorderNostart_(processor) && processor.finish();
}
template <typename T>
bool Composite::applyDescendantPostorderNostart_(UnaryProcessor<T>& processor)
throw(Exception::GeneralException)
{
Processor::Result result;
for (Composite* composite = first_child_;
composite != 0; composite = composite->next_)
{
if (composite->first_child_ != 0 &&
composite->applyDescendantPostorderNostart_(processor) == false)
{
return false;
}
T* t_ptr = dynamic_cast<T*>(composite);
if (t_ptr != 0)
{
result = processor(*t_ptr);
if (result <= Processor::BREAK)
{
return (result == Processor::BREAK);
}
}
}
return true;
}
template <typename T>
bool Composite::applyPostorder(UnaryProcessor<T>& processor)
throw(Exception::GeneralException)
{
if (!processor.start() || !applyDescendantPostorderNostart_(processor))
{
return false;
}
T* t_ptr = dynamic_cast<T*>(this);
return (t_ptr != 0 &&
processor(*t_ptr) >= Processor::BREAK &&
processor.finish() );
}
template <typename T>
bool Composite::applyLevel(UnaryProcessor<T>& processor, long level)
throw(Exception::GeneralException)
{
return processor.start() && applyLevelNostart_(processor, level) && processor.finish();
}
template <typename T>
bool Composite::applyLevelNostart_(UnaryProcessor<T>& processor, long level)
throw(Exception::GeneralException)
{
if (level == 0)
{
T* t_ptr = dynamic_cast<T*>(this);
if (t_ptr != 0)
{
Processor::Result result = processor(*t_ptr);
if (result <= Processor::BREAK)
{
return (result == Processor::BREAK);
}
}
}
else
{
if (--level == 0)
{
return applyChildNostart_(processor);
}
else
{
if (level > 0)
{
for (Composite* composite = first_child_;
composite != 0; composite = composite->next_)
{
if (composite->first_child_ != 0 && composite->applyLevelNostart_(processor, level) == false)
{
return false;
}
}
}
}
}
return true;
}
template <typename T>
bool Composite::applyPreorderNostart_(UnaryProcessor<T>& processor)
throw(Exception::GeneralException)
{
Processor::Result result;
bool return_value;
T* t_ptr = dynamic_cast<T*>(this);
if (t_ptr != 0)
{
result = processor(*t_ptr);
if (result <= Processor::BREAK)
{
return_value = (result == Processor::BREAK);
}
else
{
return_value = applyDescendantPreorderNostart_(processor);
}
}
else
{
return_value = applyDescendantPreorderNostart_(processor);
}
return return_value;
}
template <typename T>
bool Composite::applyDescendant(UnaryProcessor<T>& processor)
throw(Exception::GeneralException)
{
return applyDescendantPreorder(processor);
}
template <typename T>
bool Composite::applyPreorder(UnaryProcessor<T>& processor)
throw(Exception::GeneralException)
{
return processor.start() && applyPreorderNostart_(processor) && processor.finish();
}
template <typename T>
BALL_INLINE
bool Composite::apply(UnaryProcessor<T>& processor)
throw(Exception::GeneralException)
{
return applyPreorder(processor);
}
template <typename T>
BALL_INLINE
T* Composite::getAncestor(const T& /* dummy */)
throw()
{
T* T_ptr = 0;
for (Composite* composite_ptr = parent_;
composite_ptr != 0; composite_ptr = composite_ptr->parent_)
{
T_ptr = dynamic_cast<T*>(composite_ptr);
if (T_ptr != 0)
{
break;
}
}
return T_ptr;
}
template <typename T>
BALL_INLINE
const T* Composite::getAncestor(const T& /* dummy */) const
throw()
{
T* t_ptr = 0;
for (Composite* composite_ptr = parent_;
composite_ptr != 0; composite_ptr = composite_ptr->parent_)
{
if ((t_ptr = dynamic_cast<T*>(composite_ptr)) != 0)
{
break;
}
}
return const_cast<const T*>(t_ptr);
}
template <typename T>
BALL_INLINE
T* Composite::getPrevious(const T& /* dummy */)
throw()
{
// create an iterator bound to the root of the subtree
CompositeIterator it(getRoot().endComposite());
// set its position to the current composite
it.getTraits().setPosition(this);
// walk back until we find something
// or we cannot walk any further
if (+it)
{
do
{
--it;
}
while (+it && !RTTI::isKindOf<T>(*it));
}
// return a NULL pointer if nothing was found
Composite* ptr = 0;
if (+it)
{
ptr = &*it;
}
return dynamic_cast<T*>(ptr);
}
template <typename T>
BALL_INLINE
const T* Composite::getPrevious(const T& dummy) const
throw()
{
// cast away the constness of this and call the non-const method
Composite* nonconst_this = const_cast<Composite*>(this);
return const_cast<const T*>(nonconst_this->getPrevious(dummy));
}
template <typename T>
BALL_INLINE
T* Composite::getNext(const T& /* dummy */)
throw()
{
// create an iterator bound to the root of the subtree
CompositeIterator it(getRoot().beginComposite());
// set its position to the current composite
it.getTraits().setPosition(this);
// walk forward until we find something
// or we cannot walk any further
do
{
it++;
}
while (it.isValid() && !RTTI::isKindOf<T>(*it));
// return a NULL pointer if nothing was found
Composite* ptr = 0;
if (+it)
{
ptr = &*it;
}
return dynamic_cast<T*>(ptr);
}
template <typename T>
BALL_INLINE
const T* Composite::getNext(const T& dummy) const
throw()
{
// cast away the constness of this and call the non-const method
Composite* nonconst_this = const_cast<Composite*>(this);
return const_cast<const T*>(nonconst_this->getNext(dummy));
}
template <typename T>
BALL_INLINE
bool Composite::hasAncestor(const T& dummy ) const
throw()
{
return (getAncestor(dummy) != 0);
}
# ifndef BALL_NO_INLINE_FUNCTIONS
# include <BALL/CONCEPT/composite.iC>
# endif
} // namespace BALL
#endif // BALL_CONCEPT_COMPOSITE_H
| true |
f92fd322ce1b79c73606fc28d43debf1e5800a73
|
C++
|
lukastk/ant_system
|
/gridants/antsim.cpp
|
UTF-8
| 8,434 | 2.6875 | 3 |
[] |
no_license
|
#include "antsim.h"
#include "maps.cpp"
using namespace std;
Point moves[] = { Point(0, 0), Point(0, -1), Point(1, 0), Point(0, 1), Point(-1, 0) };
Simulation::Simulation(
double _backwardBias,
double _traceIncrease,
double _traceBaseLine,
double _traceDecay,
Point _nest, Point _food,
int _world_w, int _world_h) :
backwardBias(_backwardBias),
traceIncrease(_traceIncrease),
traceBaseLine(_traceBaseLine),
traceDecay(_traceDecay),
nest(_nest), food(_food),
world_w(_world_w), world_h(_world_h) {
// Set up the array for the map
this->world = new BlockData*[this->world_h];
for (int y = 0; y < this->world_h; y++) {
this->world[y] = new BlockData[this->world_w];
for (int x = 0; x < this->world_w; x++) {
this->world[y][x].open = true;
this->world[y][x].trace = 0.0;
}
}
random = boost::random::mt19937();
}
Simulation::~Simulation() {
for (int y = 0; y < this->world_h; y++) {
delete world[y];
}
delete world;
}
void Simulation::init() {
// Apply baseline
for (int y = 0; y < this->world_h; y++) {
for (int x = 0; x < this->world_w; x++) {
this->world[y][x].trace = this->traceBaseLine;
}
}
}
/* Decay the world's traces */
void Simulation::decayWorld() {
for (int y = 0; y < this->world_h; y++) {
for (int x = 0; x < this->world_w; x++) {
this->world[y][x].trace *= traceDecay;
}
}
}
void Simulation::addAntTraces() {
for (std::vector<Ant*>::const_iterator it = ants.begin(), end = ants.end(); it != end; ++it) {
world[(*it)->pos.y][(*it)->pos.x].trace += traceIncrease;
}
}
void Simulation::addAnt(Ant* ant) {
this->ants.push_back(ant);
}
Directions Simulation::getOppositeDirection(Directions d) {
switch(d) {
case LEFT:
return RIGHT;
case RIGHT:
return LEFT;
case UP:
return DOWN;
case DOWN:
return UP;
default:
return NODIR;
}
}
Point Simulation::getRandomMove(Ant* ant) {
// Check available moves
int numOfMoves = 0;
std::vector<Directions> directions;
std::list<double> traces;
double totalTraces = 0;
int backDirIndex = -1;
double backDirTrace;
Point randomMove(-100, -100);
BlockData* block;
block = &world[ant->pos.y][ant->pos.x - 1];
if (ant->pos.x > 0 && block->open) {
directions.push_back(LEFT);
traces.push_back(block->trace);
numOfMoves++;
totalTraces += block->trace;
if (LEFT == ant->prev_dir) {
backDirIndex = numOfMoves - 1; // numOfMoves is effectively the index
backDirTrace = block->trace;
}
}
block = &world[ant->pos.y][ant->pos.x + 1];
if (ant->pos.x < world_w-1 && block->open) {
directions.push_back(RIGHT);
traces.push_back(block->trace);
numOfMoves++;
if (RIGHT == ant->prev_dir) {
backDirIndex = numOfMoves - 1;
backDirTrace = block->trace;
}
}
block = &world[ant->pos.y - 1][ant->pos.x];
if (ant->pos.y > 0 && block->open) {
directions.push_back(UP);
traces.push_back(block->trace);
numOfMoves++;
totalTraces += block->trace;
if (UP == ant->prev_dir) {
backDirIndex = numOfMoves - 1;
backDirTrace = block->trace;
}
}
block = &world[ant->pos.y + 1][ant->pos.x];
if (ant->pos.y < world_h-1 && block->open) {
directions.push_back(DOWN);
traces.push_back(block->trace);
numOfMoves++;
totalTraces += block->trace;
if (DOWN == ant->prev_dir) {
backDirIndex = numOfMoves - 1;
backDirTrace = block->trace;
}
}
Directions dir = NODIR;
if (numOfMoves != 1) {
std::list<double> probabilities;
std::list<double>::const_iterator pher_it = traces.begin(), end = probabilities.end();
double p = 0;
double total_weights = 0;
if (ant->prev_dir == NODIR ||
(ant->pos == food && !ant->has_food) ||
(ant->pos == nest && ant->has_food)) {
if (ant->pos == this->nest) {
ant->has_food = false;
} else if (ant->pos == this->food) {
ant->has_food = true;
}
for (int i = 0; i < numOfMoves; i++) {
p = 1.0 / double(numOfMoves);
p = p*( 1 + *pher_it);
total_weights += p;
probabilities.push_back(p);
pher_it++;
}
} else {
// Set the probability weights, with the backwardbias
for (int i = 0; i < numOfMoves; i++) {
if (i != backDirIndex) {
p = 1.0 / double(numOfMoves) + (1 - backwardBias)/(double(numOfMoves)*(numOfMoves - 1));
} else {
p = backwardBias/double(numOfMoves);
}
p = p*( 1 + *pher_it);
total_weights += p;
probabilities.push_back(p);
pher_it++;
}
}
/*
cout << ant->has_food << ": ";
int j = 0;
for (std::list<double>::const_iterator it = probabilities.begin(), end = probabilities.end(); it != end; ++it) {
if (j == backDirIndex) {
cout << "(" << *it << ")" << "-";
} else {
cout << *it << "-";
}
j++;
}
cout << endl;*/
//double r = double(rand()) / double(RAND_MAX);
boost::random::uniform_real_distribution<double> rand_dist = boost::random::uniform_real_distribution<double>(0, total_weights);
double r = rand_dist(random);
int i = 0;
bool moved = false;
for (std::list<double>::const_iterator it = probabilities.begin(), end = probabilities.end(); it != end; ++it) {
if (r < *it) {
moved = true;
dir = directions[i];
randomMove = moves[ dir ];
break;
} else {
r -= *it;
}
i++;
}
if (!moved) {
std::cerr << "Something wrong: Ant didn't move." << std::endl;
std::cerr << r << std::endl;
}
} else {
dir = directions[0];
randomMove = moves[ dir ];
}
ant->prev_dir = getOppositeDirection(dir);
return randomMove;
}
void Simulation::updateAnt(Ant* ant) {
Point randomMove = this->getRandomMove(ant);
ant->pos = ant->pos + randomMove;
}
void Simulation::update() {
for (vector<Ant*>::const_iterator it = ants.begin(), end = ants.end(); it != end; ++it) {
this->updateAnt(*it);
}
this->addAntTraces();
this->decayWorld();
}
double Simulation::minTrace() {
double minTrace = -1;
for (int y = 0; y < world_h; y++) {
for (int x = 0; x < world_w; x++) {
if (!world[y][x].open) {
continue;
}
if (minTrace == -1 || world[y][x].trace < minTrace) {
minTrace = world[y][x].trace;
}
}
}
return minTrace;
}
double Simulation::maxTrace() {
double maxTrace = 0;
for (int y = 0; y < world_h; y++) {
for (int x = 0; x < world_w; x++) {
bool invisible_block = false;
for (std::vector<Point>::const_iterator it = invisible_blocks.begin(), end = invisible_blocks.end(); it != end; ++it) {
if ((*it).x == x && (*it).y == y) {
invisible_block = true;
break;
}
}
if (invisible_block) {
continue;
}
if (!world[y][x].open) {
continue;
}
if (world[y][x].trace > maxTrace) {
maxTrace = world[y][x].trace;
}
}
}
return maxTrace;
}
int Simulation::minAnts() {
double minAnts = -1;
for (int y = 0; y < world_h; y++) {
for (int x = 0; x < world_w; x++) {
if (!world[y][x].open) {
continue;
}
int ants = getNumOfAntsAt(y, x);
if (minAnts == -1 || ants < minAnts) {
minAnts = ants;
}
}
}
return minAnts;
}
int Simulation::maxAnts() {
double maxAnts = 0;
for (int y = 0; y < world_h; y++) {
for (int x = 0; x < world_w; x++) {
if (!world[y][x].open) {
continue;
}
int ants = getNumOfAntsAt(y, x);
if (ants > maxAnts) {
maxAnts = ants;
}
}
}
return maxAnts;
}
double Simulation::getTraceAt(int y, int x) {
return world[y][x].trace;
}
bool Simulation::getBlockOpenAt(int y, int x) {
return world[y][x].open;
}
void Simulation::setBlockOpenAt(int y, int x, bool val) {
world[y][x].open = val;
}
void Simulation::setBlockVerticalLine(int y0, int x0, int length, bool val) {
if (length > 0) {
for (int y = y0; y < y0 + length; y++) {
setBlockOpenAt(y, x0, val);
}
} else {
for (int y = y0; y > y0 + length; y--) {
setBlockOpenAt(y, x0, val);
}
}
}
void Simulation::setBlockHorizontalLine(int y0, int x0, int length, bool val) {
if (length > 0) {
for (int x = x0; x < x0 + length; x++) {
setBlockOpenAt(y0, x, val);
}
} else {
for (int x = x0; x > x0 + length; x--) {
setBlockOpenAt(y0, x, val);
}
}
}
int Simulation::getNumOfAntsAt(int y, int x) {
int numOfAnts = 0;
for (std::vector<Ant*>::const_iterator it = ants.begin(), end = ants.end(); it != end; ++it) {
if ((*it)->pos.x == x && (*it)->pos.y == y) {
numOfAnts++;
}
}
return numOfAnts;
}
std::vector<Ant*>* Simulation::getAnts() {
return &this->ants;
}
Simulation* initialize_simulation() {
Simulation* sim = map1();
return sim;
}
| true |
b1bfc9d0581517a89c10ca3ab4a27e75047cd843
|
C++
|
jerry950208/Programmers
|
/Programmers_C++/Level 1/연습문제/이상한_문자_만들기.cpp
|
UTF-8
| 490 | 3.453125 | 3 |
[] |
no_license
|
#include <string>
#include <vector>
using namespace std;
string solution(string s) {
string answer = "";
int idx = 0;
for(int i=0; i<s.size(); i++){
if(s[i] == ' '){
idx = 0;
continue;
}
if(idx % 2 == 1) s[i] = tolower(s[i]); //tolower : 대문자만 소문자로 변환
else s[i] = toupper(s[i]); // toupper : 소문자만 대문자로 변환
idx++;
}
return s;
}
| true |
b07651da75034e8e29ed129bae8bbe81a6b63377
|
C++
|
jatvarthur/cybersnake
|
/engine/include/GameObject.h
|
UTF-8
| 1,852 | 2.78125 | 3 |
[] |
no_license
|
#pragma once
#ifndef GAME_OBJECT_H__
#define GAME_OBJECT_H__
#include "system.h"
struct Vector2i {
int x;
int y;
};
enum TypeKind {
TK_UNDEF,
TK_INT,
TK_STRING,
TK_VEC2I
};
struct PropertyInfo {
std::string name;
enum TypeKind type;
bool isArray; // std::vector
unsigned offset;
};
struct TypeInfo {
std::string className;
std::vector<PropertyInfo> properties;
};
#define DECLARE_TYPE_INFO(className) \
virtual const TypeInfo* getTypeInfo() const \
{ \
static TypeInfo typeInfo = { \
#className,
#define END_TYPE_INFO() \
}; \
return &typeInfo; \
}
#define BEGIN_PROPS() std::vector<PropertyInfo>({
#define END_PROPS() })
#define DECLARE_PROP(className, propName, propType, isArray) \
{ #propName, propType, isArray, (unsigned)&((className*)(nullptr))->propName ## _ },
class GameObject {
public:
DECLARE_TYPE_INFO(GameObject)
BEGIN_PROPS()
DECLARE_PROP(GameObject, name, TK_STRING, false)
DECLARE_PROP(GameObject, loc, TK_VEC2I, false)
END_PROPS()
END_TYPE_INFO()
public:
GameObject();
virtual ~GameObject() noexcept;
std::string getName() const;
void setName(const std::string& value);
Vector2i getLoc() const;
void setLoc(const Vector2i& value);
private:
std::string name_;
Vector2i loc_;
};
class Stream {
public:
virtual ~Stream() {}
virtual void write(const void* buf, int size) = 0;
virtual void read(void* buf, int size) = 0;
};
class BinaryStream: public Stream {
public:
BinaryStream();
virtual void write(const void* buf, int size) override;
virtual void read(void* buf, int size) override;
void rewind();
const void* data() const;
int size() const;
private:
std::vector<BYTE> buffer_;
int pos_;
};
class Serializer {
public:
void serialize(const GameObject* object, Stream* stream);
void deserialize(GameObject* object, Stream* stream);
};
#endif
| true |
5c7c3a380c6c6df9e5f6629bfc8e61897b01a8c7
|
C++
|
jkennedyvz/ashirt
|
/src/dtos/github_release.h
|
UTF-8
| 5,227 | 2.78125 | 3 |
[
"LicenseRef-scancode-free-unknown",
"MIT"
] |
permissive
|
#ifndef GITHUB_RELEASE_H
#define GITHUB_RELEASE_H
#include <QVariant>
#include <QRegularExpression>
#include <iostream>
#include "helpers/jsonhelpers.h"
namespace dto {
// SemVer is a (mostly) parsed out semantic version (V2). The major, minor, and patch versions are
// converted to ints, while the remainder is left untouched, in "extra".
class SemVer {
public:
SemVer(){}
SemVer(int major, int minor, int patch, QString extra) {
this->major = major;
this->minor = minor;
this->patch = patch;
this->extra = extra;
}
static SemVer parse(QString strTag) {
QRegularExpression semverRegex("^[vV]?(\\d+)\\.(\\d+)\\.(\\d+)(.*)");
SemVer ver;
QRegularExpressionMatch match = semverRegex.match(strTag);
if (match.hasMatch())
{
ver.major = match.captured(1).toInt();
ver.minor = match.captured(2).toInt();
ver.patch = match.captured(3).toInt();
ver.extra = match.captured(4);
}
return ver;
}
QString toString() {
return "v" + QString::number(this->major)
+ "." + QString::number(this->minor)
+ "." + QString::number(this->patch)
+ extra;
}
static bool isUpgrade(SemVer cur, SemVer next) {
return isMajorUpgrade(cur, next) ||
isMinorUpgrade(cur, next) ||
isPatchUpgrade(cur, next);
}
static bool isMajorUpgrade(SemVer cur, SemVer next) {
return next.major > cur.major;
}
static bool isMinorUpgrade(SemVer cur, SemVer next) {
return next.major == cur.major &&
next.minor > cur.minor;
}
static bool isPatchUpgrade(SemVer cur, SemVer next) {
return next.major == cur.major &&
next.minor == cur.minor &&
next.patch > cur.patch;
}
int major = 0;
int minor = 0;
int patch = 0;
QString extra = "";
};
class GithubRelease {
public:
QString url;
QString htmlURL;
QString assetsURL;
QString uploadURL;
QString tarballURL;
QString zipballURL;
QString tagName;
QString releaseName;
QString body;
bool prerelease;
bool draft;
QString publishedAt;
qint64 id;
public:
GithubRelease() {
this->id = 0;
}
static GithubRelease parseData(QByteArray data) {
return parseJSONItem<GithubRelease>(data, GithubRelease::fromJson);
}
static std::vector<GithubRelease> parseDataAsList(QByteArray data) {
return parseJSONList<GithubRelease>(data, GithubRelease::fromJson);
}
bool isLegitimate() {
return this->id != 0;
}
private:
static GithubRelease fromJson(QJsonObject obj) {
GithubRelease release;
release.url = obj["url"].toString();
release.htmlURL = obj["html_url"].toString();
release.assetsURL = obj["assets_url"].toString();
release.uploadURL = obj["upload_url"].toString();
release.tarballURL = obj["tarball_url"].toString();
release.zipballURL = obj["zipball_url"].toString();
release.tagName = obj["tag_name"].toString();
release.body = obj["body"].toString();
release.releaseName = obj["name"].toString();
release.publishedAt = obj["published_at"].toString();
release.draft = obj["draft"].toBool();
release.prerelease = obj["prerelease"].toBool();
// missing a number of fields here that maybe aren't relevant
release.id = obj["id"].toVariant().toLongLong();
return release;
}
};
class ReleaseDigest {
public:
ReleaseDigest(){}
public:
static ReleaseDigest fromReleases(QString curVersion, const std::vector<GithubRelease> &borrowedReleases) {
if (curVersion == "v0.0.0-unversioned" || curVersion == "v0.0.0-development") {
std::cerr << "skipping unversioned/development release check" << std::endl;
return ReleaseDigest();
}
std::vector<GithubRelease> upgrades;
SemVer currentVersion = SemVer::parse(curVersion);
SemVer majorVer = SemVer(currentVersion);
SemVer minorVer = SemVer(currentVersion);
SemVer patchVer = SemVer(currentVersion);
for (auto release : borrowedReleases) {
if (SemVer::isUpgrade(currentVersion, SemVer::parse(release.tagName))) {
upgrades.push_back(release);
}
}
auto rtn = ReleaseDigest();
for (GithubRelease upgrade : upgrades) {
auto upgradeVersion = SemVer::parse(upgrade.tagName);
if (SemVer::isMajorUpgrade(currentVersion, upgradeVersion) && SemVer::isUpgrade(majorVer, upgradeVersion)) {
majorVer = upgradeVersion;
rtn.majorRelease = upgrade;
}
else if (SemVer::isMinorUpgrade(currentVersion, upgradeVersion) && SemVer::isUpgrade(minorVer, upgradeVersion)) {
minorVer = upgradeVersion;
rtn.minorRelease = upgrade;
}
else if (SemVer::isPatchUpgrade(currentVersion, upgradeVersion) && SemVer::isUpgrade(patchVer, upgradeVersion)) {
patchVer = upgradeVersion;
rtn.patchRelease = upgrade;
}
}
return rtn;
}
bool hasUpgrade() {
return majorRelease.isLegitimate()
|| minorRelease.isLegitimate()
|| patchRelease.isLegitimate();
}
public:
GithubRelease majorRelease = GithubRelease();
GithubRelease minorRelease = GithubRelease();
GithubRelease patchRelease = GithubRelease();
};
}
#endif // GITHUB_RELEASE_H
| true |
c4b0a22f292445398e7da49d4d41689ec05e03e9
|
C++
|
NhatPhuong02/HCMUS-Lectures
|
/1_NMLT/ThucHanh-T8/main.cpp
|
UTF-8
| 3,565 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
// MSSV: 1612180
// Ho ten: Nguyen Tran Hau
// Bai tap tuan 08
#include "xuly.h"
int main(void)
{
int arr[MAX][MAX], arr2[MAX][MAX], kqua[MAX][MAX];
int hang, cot, x, y, hang2, cot2, kqua_hang, kqua_cot;
float r_arr[MAX][MAX], r_kqua[MAX][MAX];
nhap_mang(arr, hang, cot);
xuat_mang(arr, hang, cot);
printf("Tong cac phan tu cua mang: %d\n",
tong(arr, hang, cot)); // Bai 1 TB
printf("Nhap x can tim tan suat: ");
scanf("%d", &x);
printf("Tan suat cua x: %d lan xuat hien.\n",
tan_suat(x, arr, hang, cot)); // Bai 2 TB
printf("So lan xuat hien cua cac so nguyen duong: %d\n",
tan_suat_duong(arr, hang, cot)); // Bai 3 TB
printf("Tong cac phan tu khong am: %d\n",
tong_khong_am(arr, hang, cot)); // Bai 4 TB
printf("Tong cac phan tu tren duong cheo chinh: %d\n",
tong_cheo_chinh(arr, hang, cot)); // Bai 5 TB
printf("Tong cac phan tu tren duong cheo phu: %d\n",
tong_cheo_phu(arr, hang, cot)); // Bai 6 TB
nhap_mang(arr2, hang2, cot2);
printf("Tong 2 mang da nhap:\n");
tong_matran(arr, hang, cot, arr2, hang2, cot2, kqua, kqua_hang,
kqua_cot); // Bai 8-tong TB
xuat_mang(kqua, kqua_hang, kqua_cot);
printf("Tich 2 ma tran da nhap:\n");
tich_matran(arr, hang, cot, arr2, hang2, cot2, kqua, kqua_hang,
kqua_cot); // Bai 8-tich TB
xuat_mang(kqua, kqua_hang, kqua_cot);
printf("Mang tang dan tren hang:\n");
tang_hang(arr, hang, cot); // Bai 7 TB
xuat_mang(arr, hang, cot);
printf("Mang tang dan tren cot va giam dan tren hang: \n");
tang_cot_giam_hang(arr, hang, cot); // Bai 1 K
xuat_mang(arr, hang, cot);
printf("Mang tang dan tren cot va tang dan tren hang: \n");
tang_hang_tang_cot(arr, hang, cot); // Bai 2 K
xuat_mang(arr, hang, cot);
printf("Xoay ma tran sang phai: \n"); // Bai 4 K
phai_90(arr, hang, cot);
xuat_mang(arr, hang, cot);
printf("Xoay ma tran sang trai: \n"); // Bai 4 K
trai_90(arr, hang, cot);
xuat_mang(arr, hang, cot);
printf("Nhap 1 neu xoay trai nhap 2 neu muon xoay phai: "); // Bai 5 K
scanf("%d", &x);
printf("Nhap so lan quay: ");
scanf("%d", &y);
xoay(arr, hang, cot, x, y);
xuat_mang(arr, hang, cot);
printf("Nhap cot can xoa: "); // Bai 6 K
scanf("%d", &x);
xoa_cot(x, arr, hang, cot);
xuat_mang(arr, hang, cot);
printf("Nhap hang can xoa: "); // Bai 6 K
scanf("%d", &x);
xoa_hang(x, arr, hang, cot);
xuat_mang(arr, hang, cot);
printf("Nhap hai mang de xoa trung lap:\n");
nhap_mang(arr, hang, cot);
nhap_mang(arr2, hang2, cot2);
xoa_trung(arr, hang, cot, arr2, hang2, cot2); // Bai 7 K
xuat_mang(arr, hang, cot);
printf("\n");
xuat_mang(arr2, hang2, cot2);
lon_nhat(arr, hang, cot); // Bai 11 K
nho_nhat(arr, hang, cot);
matran_tong(arr, hang, cot); // Bai 8 K
matran_tich(arr, hang, cot); // Bai 9 K
if (tong_n_mtran(kqua, kqua_hang, kqua_cot)) // Bai 3 K
{
printf("Tong n ma tran da nhap\n");
xuat_mang(kqua, kqua_hang, kqua_cot);
} else
printf("Khong cong duoc\n");
if (tich_n_mtran(kqua, kqua_hang, kqua_cot)) // Bai 3 K
{
printf("Tich n ma tran da nhap\n");
xuat_mang(kqua, kqua_hang, kqua_cot);
} else
printf("Khong nhan duoc\n");
printf("Nhap ma tran can tim nghich dao\n");
nhap_mang_r(r_arr, hang, cot);
if (hang != cot)
printf("Khong co nghich dao\n");
else {
if (nghich_dao(r_arr, hang, r_kqua)) // Bai 10 K
{
printf("Nghich dao:\n");
xuat_mang_r(r_kqua, hang, hang);
} else
printf("Khong co nghich dao\n");
}
return 0;
}
| true |
9c176dd35eeb3fd7008dc6a4842f90acf6d3a235
|
C++
|
Lucasian-z/PAT
|
/PTA_Advanced/PTA_Advanced1097 Deduplication on a Linked List.cpp
|
UTF-8
| 1,555 | 2.671875 | 3 |
[] |
no_license
|
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
using namespace std;
struct node {
int val;
int next;
};
vector<node> list(100000);
int main()
{
int baseAddress = 0, cnt = 0;
int addr, val, next;
scanf("%d%d", &baseAddress, &cnt);
if (cnt == 0) return 0;
set<int> nums;
vector<pair<int, int>> del;
int pre = baseAddress, base = pre, cnt1 = cnt;
while (cnt--) {
scanf("%d%d%d", &addr, &val, &next);
list[addr].val = val;
list[addr].next = next;
}
int validCnt = 0; //有效节点个数
while (baseAddress != -1) {
if (nums.find(abs(list[baseAddress].val)) != nums.end()) {
list[pre].next = list[baseAddress].next;
del.push_back(make_pair(baseAddress, list[baseAddress].val));
}else {
pre = baseAddress;
}
nums.insert(abs(list[baseAddress].val));
baseAddress = list[baseAddress].next;
++validCnt;
}
int n = validCnt - del.size();
for (int i = 0; i < n; ++i) {
if (i < n - 1) {
printf("%05d %d %05d\n", base, list[base].val, list[base].next);
}else {
printf("%05d %d -1\n", base, list[base].val);
}
base = list[base].next;
}
for (int i = 0; i < del.size(); ++i) {
if (i < del.size() - 1) {
printf("%05d %d %05d\n", del[i].first, del[i].second, del[i+1].first);
}else {
printf("%05d %d -1\n", del[i].first, del[i].second);
}
}
return 0;
}
| true |
f3d74b13a69ad2a52d0ef9cf7de45b0c69110f70
|
C++
|
MastaLomaster/MHook
|
/source/HookHandler.h
|
UTF-8
| 1,599 | 2.515625 | 3 |
[] |
no_license
|
// Обработчик хука, виртуальный класс
#ifndef __MH_HOOKHANDLER
#define __MH_HOOKHANDLER
#include "MHKeypad.h"
class MHookHandler
{
public:
MHookHandler():rbutton_pressed(false),initialized(false),position_mem(-1),mouse_path_squared(0){};
virtual int OnMouseMove(LONG _x, LONG _y)=0;
virtual void OnMouseScroll(LONG _x, LONG _y);
virtual bool OnRDown()=0; // возвращает, нужно ли подавлять правый клик
virtual bool OnRUp()=0;
virtual void OnLDown();
virtual void OnLUp();
virtual int GetPosition() { return MHKeypad::GetPosition(); } // по умолчанию возвращаем нажатую клавишу
virtual void OnTimer(){};
virtual void OnDraw(HDC hdc, LONG window_size){}; // Нужна в 4 режиме для рисования квадратиков
virtual void Halt(){};
void HaltGeneral(){ rbutton_pressed=false; initialized=false; position_mem=-1; mouse_path_squared=0; }
void Deinitialize(){initialized=false;} // Нужно, когда мы временно не обрабатываем перемещения мыши (пауза, скролл)
void TopLeftCornerTimer(); // Тут левая кнопка мыши преображается
void OnFastMove(LONG _dx, LONG _dy); // Определяет, был ли рывок мыши
protected:
bool rbutton_pressed, initialized;
LONG dx,dy,last_x,last_y;
int position_mem;
DWORD last_button5_time; // для нажатия на 5 кнопку при быстром движении мыши
LONG mouse_path_squared;
};
#endif
| true |
18f0b93f8cbde8941dc4c63d66a1178f5498ec29
|
C++
|
skuzi/Paradigms-HW
|
/hw9/src/ThreadPool.cpp
|
UTF-8
| 2,267 | 3.3125 | 3 |
[
"Unlicense"
] |
permissive
|
#include "ThreadPool.h"
#include <iostream>
void Task::wait() {
pthread_mutex_lock(&m_mutex);
while(!m_stop) {
pthread_cond_wait(&m_cond, &m_mutex);
}
pthread_mutex_unlock(&m_mutex);
}
void* thread_action(void* pool) {
ThreadPool* th_pool = (ThreadPool*) pool;
while (1) {
pthread_mutex_lock(&th_pool->m_mutex);
while (th_pool->m_tasks.empty() && !th_pool->m_stop) {
pthread_cond_wait(&th_pool->m_cond, &th_pool->m_mutex);
}
if (th_pool->m_tasks.empty()) {
pthread_mutex_unlock(&th_pool->m_mutex);
break;
}
else {
Task* task = th_pool->m_tasks.front();
th_pool->m_tasks.pop();
pthread_mutex_unlock(&th_pool->m_mutex);
task->m_func(task->m_arg);
pthread_mutex_lock(&task->m_mutex);
task->m_stop = 1;
pthread_cond_broadcast(&task->m_cond);
pthread_mutex_unlock(&task->m_mutex);
}
}
return NULL;
}
ThreadPool::ThreadPool(std::size_t threads_count) {
pthread_mutex_init(&m_mutex, NULL);
pthread_cond_init(&m_cond, NULL);
m_stop = 0;
m_threads.resize(threads_count);
for(std::size_t i = 0; i < threads_count; i++) {
pthread_create(&m_threads[i], NULL, thread_action, this);
}
}
ThreadPool::~ThreadPool() {
pthread_mutex_lock(&m_mutex);
m_stop = 1;
pthread_cond_broadcast(&m_cond);
pthread_mutex_unlock(&m_mutex);
for (std::size_t i = 0; i < m_threads.size(); i++) {
pthread_join(m_threads[i], NULL);
}
pthread_cond_destroy(&m_cond);
pthread_mutex_destroy(&m_mutex);
}
void ThreadPool::submit(Task* task) {
pthread_mutex_lock(&m_mutex);
m_tasks.push(task);
pthread_cond_signal(&m_cond);
pthread_mutex_unlock(&m_mutex);
}
Task::Task(void (*func) (void*), void* arg) {
pthread_mutex_init(&m_mutex, NULL);
m_stop = 0;
m_func = func;
m_arg = arg;
pthread_cond_init(&m_cond, NULL);
}
Task::Task() {
pthread_mutex_init(&m_mutex, NULL);
m_stop = 0;
m_func = NULL;
m_arg = NULL;
pthread_cond_init(&m_cond, NULL);
}
Task::~Task() {
pthread_mutex_destroy(&m_mutex);
pthread_cond_destroy(&m_cond);
}
| true |
661959b9c186a3735d73b52b4bbf7cc92c9e1621
|
C++
|
amd/libflame
|
/test/lapacke/LIN/RSEE/lapacke_gtest_gerfs.cc
|
UTF-8
| 41,153 | 2.578125 | 3 |
[
"BSD-3-Clause",
"LicenseRef-scancode-other-permissive"
] |
permissive
|
#include "gtest/gtest.h"
#include "../../lapacke_gtest_main.h"
#include "../../lapacke_gtest_helper.h"
#define gerfs_free() \
if (a != NULL) free (a ); \
if (aref != NULL) free (aref); \
if (b != NULL) free (b ); \
if (bref != NULL) free (bref); \
if (x != NULL) free (x ); \
if (xref != NULL) free (xref); \
if (af != NULL) free (af ); \
if (afref != NULL) free (afref); \
if (ferr != NULL) free (ferr ); \
if (ferrref != NULL) free (ferrref); \
if (berr != NULL) free (berr ); \
if (berrref != NULL) free (berrref); \
if (ipiv != NULL) free (ipiv ); \
if (ipivref != NULL) free (ipivref); \
if( hModule != NULL) dlclose(hModule); \
if(dModule != NULL) dlclose(dModule)
// index of the 'config parameter struct' array to enable multiple sub-tests.
static int idx = 0;
/* Begin gerfs_float_parameters class definition */
class gerfs_float_parameters{
public:
int b_bufsize;
int x_bufsize;
float diff; // capture difference between ref o/p & libflame lapacke o/p.
float diff_berr, diff_ferr, diff_xerr;
void *hModule, *dModule;
/* Input parameters */
int matrix_layout; // storage layout LAPACK_ROW_MAJOR or LAPACK_COL_MAJOR
char fact; // Must be 'F', 'N', or 'E'.
char trans; // Must be 'N' , 'T' or 'C'.
lapack_int n; // The order of A (Square matrix).
lapack_int nrhs; // The number of right-hand sides
lapack_int lda; // leading dimension of 'a'
lapack_int ldb; // leading dimension of 'b'
lapack_int ldaf; // leading dimension of 'af'
lapack_int ldx; // leading dimension of 'x'
/* Input/ Output parameters */
float *b, *bref; //right-hand sides for the systems of equations.
float *a, *aref; //The array ab contains the matrix A
float *af, *afref; //contains the factored form of the matrix A
lapack_int *ipiv, *ipivref; // pivot buffer
/* Output parameters */
float rpivot, rpivotref; // reciprocal pivot growth factor.
float rcond, rcondref; // estimate of the reciprocal condition number of the matrix A.
float* x, *xref;
float* ferr, *ferrref; // estimated forward error bound for each solution vector x.
float* berr, *berrref; // component-wise relative backward error for each solution vector xj.
/* Return Values */
lapack_int info, inforef;
public:
gerfs_float_parameters ( int matrix_layout_i, char trans_i,
lapack_int n_i, lapack_int nrhs_i);
~gerfs_float_parameters ();
}; /* end of gerfs_float_parameters class definition */
/* Constructor gerfs_float_parameters definition */
gerfs_float_parameters:: gerfs_float_parameters ( int matrix_layout_i,
char trans_i, lapack_int n_i, lapack_int nrhs_i) {
matrix_layout = matrix_layout_i;
trans = trans_i;
n = n_i;
nrhs = nrhs_i;
lda = n;
ldaf = n;
if(matrix_layout==LAPACK_COL_MAJOR){
ldb = n;
ldx = n;
b_bufsize = ldb*nrhs;
x_bufsize = ldx*nrhs;
}
else if(matrix_layout==LAPACK_ROW_MAJOR){
ldb = nrhs;
ldx = nrhs;
b_bufsize = ldb*n;
x_bufsize = ldx*n;
}
else
{
EXPECT_TRUE(false) << "matrix_layout invalid";
}
#if LAPACKE_TEST_VERBOSE
printf(" \n gerfs Double: n: %d, fact: %c trans: %c lda: %d \
ldb: %d nrhs: %d ldaf: %d ldx: %d \n", n, fact, trans, lda,
ldb, nrhs);
#endif
/* Memory allocation of the buffers */
lapacke_gtest_alloc_float_buffer_pair( &a, &aref, n*n);
lapacke_gtest_alloc_float_buffer_pair( &b, &bref, n*nrhs);
lapacke_gtest_alloc_float_buffer_pair( &x, &xref, n*nrhs);
lapacke_gtest_alloc_float_buffer_pair( &af, &afref, (n*n));
lapacke_gtest_alloc_float_buffer_pair( &ferr, &ferrref, nrhs);
lapacke_gtest_alloc_float_buffer_pair( &berr, &berrref, nrhs);
lapacke_gtest_alloc_int_buffer_pair ( &ipiv, &ipivref, n+2);
if( (a==NULL) || (aref==NULL) || \
(b==NULL) || (bref==NULL) || \
(x==NULL) || (xref==NULL) || \
(af==NULL) || (afref==NULL) || \
(ferr==NULL) || (ferrref==NULL) || \
(berr==NULL) || (berrref==NULL) || \
(ipiv==NULL) || (ipivref==NULL) ){
EXPECT_FALSE( true) << "pbtrs_float_parameters object: malloc error.";
gerfs_free();
exit(-1);
}
/* Initialization of input Buffers */
lapacke_gtest_init_float_buffer_pair_rand( a, aref, n*n);
lapacke_gtest_init_float_buffer_pair_rand( b, bref, n*nrhs);
lapacke_gtest_init_float_buffer_pair_with_constant(x, xref, n*nrhs, 0.0);
lapacke_gtest_init_float_buffer_pair_with_constant(ferr, ferrref, nrhs, 0.0);
lapacke_gtest_init_float_buffer_pair_with_constant(berr, berrref, nrhs, 0.0);
memcpy(af, a, (n*n*sizeof(float)));
memcpy(afref, a, (n*n*sizeof(float)));
} /* end of Constructor */
gerfs_float_parameters:: ~gerfs_float_parameters ()
{
#if LAPACKE_TEST_VERBOSE
printf(" gerfs_float_parameters object: destructor invoked. \n");
#endif
gerfs_free();
// if (a != NULL) free (a );
// if (aref != NULL) free (aref);
// if (b != NULL) free (b );
// if (bref != NULL) free (bref);
// if (x != NULL) free (x );
// if (xref != NULL) free (xref);
// if (af != NULL) free (af );
// if (afref != NULL) free (afref);
// if (ferr != NULL) free (ferr );
// if (ferrref != NULL) free (ferrref);
// if (berr != NULL) free (berr );
// if (berrref != NULL) free (berrref);
// if (ipiv != NULL) free (ipiv );
// if (ipivref != NULL) free (ipivref);
// if( hModule != NULL) dlclose(hModule);
// if(dModule != NULL) dlclose(dModule);
}
// Test fixture class definition
class sgerfs_test : public ::testing::Test {
public:
gerfs_float_parameters *sgerfs_obj;
void SetUp();
void TearDown () { delete sgerfs_obj; }
};
void sgerfs_test::SetUp(){
/* LAPACKE SGERFS prototype */
typedef int (*Fptr_NL_LAPACKE_sgerfs) (int matrix_layout,
char trans,
lapack_int n,
lapack_int nrhs,
const float* a,
lapack_int lda,
const float* af,
lapack_int ldaf,
const lapack_int* ipiv,
const float* b,
lapack_int ldb,
float* x,
lapack_int ldx,
float* ferr,
float* berr);
Fptr_NL_LAPACKE_sgerfs SGERFS;
/* LAPACKE SGETRF prototype */
typedef int (*Fptr_NL_LAPACKE_sgetrf) ( int matrix_layout,lapack_int m,lapack_int n,
float* a,lapack_int lda,lapack_int* ipiv );
Fptr_NL_LAPACKE_sgetrf SGETRF;
sgerfs_obj = new gerfs_float_parameters ( lin_solver_paramslist[idx].matrix_layout,
lin_solver_paramslist[idx].transr,
lin_solver_paramslist[idx].n,
lin_solver_paramslist[idx].nrhs);
idx = Circular_Increment_Index(idx);
sgerfs_obj->dModule = dlopen(NETLIB_BLAS_LIB, RTLD_NOW | RTLD_GLOBAL);
sgerfs_obj->hModule = dlopen(NETLIB_LAPACKE_LIB, RTLD_NOW);
ASSERT_TRUE(sgerfs_obj->dModule != NULL) << "Netlib Blas handle NULL";
ASSERT_TRUE(sgerfs_obj->hModule != NULL) << "Netlib lapacke handle NULL";
SGERFS = (Fptr_NL_LAPACKE_sgerfs)dlsym(sgerfs_obj->hModule, "LAPACKE_sgerfs");
ASSERT_TRUE(SGERFS != NULL) << "failed to get the Netlib LAPACKE_sgerfs symbol";
SGETRF = (Fptr_NL_LAPACKE_sgetrf)dlsym(sgerfs_obj->hModule,"LAPACKE_sgetrf");
ASSERT_TRUE(SGETRF != NULL) << "failed to get the Netlib LAPACKE_sgetrf symbol";
sgerfs_obj->inforef = SGETRF( sgerfs_obj->matrix_layout,
sgerfs_obj->n, sgerfs_obj->n,
sgerfs_obj->afref,
sgerfs_obj->lda,
sgerfs_obj->ipivref);
sgerfs_obj->info = LAPACKE_sgetrf( sgerfs_obj->matrix_layout,
sgerfs_obj->n, sgerfs_obj->n,
sgerfs_obj->af,
sgerfs_obj->lda,
sgerfs_obj->ipiv);
/* Compute the reference o/p by invoking Netlib-Lapack's API */
sgerfs_obj->inforef = SGERFS( sgerfs_obj->matrix_layout,
sgerfs_obj->trans,
sgerfs_obj->n,
sgerfs_obj->nrhs,
sgerfs_obj->aref,
sgerfs_obj->lda,
sgerfs_obj->afref,
sgerfs_obj->ldaf,
sgerfs_obj->ipivref,
sgerfs_obj->bref,
sgerfs_obj->ldb,
sgerfs_obj->xref,
sgerfs_obj->ldx,
sgerfs_obj->ferrref,
sgerfs_obj->berrref );
/* Compute libflame's Lapacke o/p */
sgerfs_obj->info = LAPACKE_sgerfs( sgerfs_obj->matrix_layout,
sgerfs_obj->trans,
sgerfs_obj->n,
sgerfs_obj->nrhs,
sgerfs_obj->a,
sgerfs_obj->lda,
sgerfs_obj->af,
sgerfs_obj->ldaf,
sgerfs_obj->ipiv,
sgerfs_obj->b,
sgerfs_obj->ldb,
sgerfs_obj->x,
sgerfs_obj->ldx,
sgerfs_obj->ferr,
sgerfs_obj->berr);
if( sgerfs_obj->info < 0 ) {
printf( "\n warning: The i:%d th argument with libflame \
LAPACKE_sgerfs is wrong\n", sgerfs_obj->info );
}
if( sgerfs_obj->inforef < 0 ) {
printf( "The i:%d th argument with Netlib LAPACKE_sgerfs is wrong\n",
sgerfs_obj->inforef );
}
/* Compute Difference between libflame and Netlib o/ps */
sgerfs_obj->diff_xerr = computeDiff_s( sgerfs_obj->x_bufsize,
sgerfs_obj->x, sgerfs_obj->xref );
sgerfs_obj->diff_berr = computeDiff_s( sgerfs_obj->nrhs,
sgerfs_obj->berr, sgerfs_obj->berrref );
sgerfs_obj->diff_ferr = computeDiff_s( sgerfs_obj->nrhs,
sgerfs_obj->ferr, sgerfs_obj->ferrref );
}
TEST_F(sgerfs_test, sgerfs1) {
EXPECT_NEAR(0.0, sgerfs_obj->diff_xerr, LAPACKE_GTEST_THRESHOLD);
EXPECT_NEAR(0.0, sgerfs_obj->diff_berr, LAPACKE_GTEST_THRESHOLD);
EXPECT_NEAR(0.0, sgerfs_obj->diff_ferr, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(sgerfs_test, sgerfs2) {
EXPECT_NEAR(0.0, sgerfs_obj->diff_xerr, LAPACKE_GTEST_THRESHOLD);
EXPECT_NEAR(0.0, sgerfs_obj->diff_berr, LAPACKE_GTEST_THRESHOLD);
EXPECT_NEAR(0.0, sgerfs_obj->diff_ferr, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(sgerfs_test, sgerfs3) {
EXPECT_NEAR(0.0, sgerfs_obj->diff_xerr, LAPACKE_GTEST_THRESHOLD);
EXPECT_NEAR(0.0, sgerfs_obj->diff_berr, LAPACKE_GTEST_THRESHOLD);
EXPECT_NEAR(0.0, sgerfs_obj->diff_ferr, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(sgerfs_test, sgerfs4) {
EXPECT_NEAR(0.0, sgerfs_obj->diff_xerr, LAPACKE_GTEST_THRESHOLD);
EXPECT_NEAR(0.0, sgerfs_obj->diff_berr, LAPACKE_GTEST_THRESHOLD);
EXPECT_NEAR(0.0, sgerfs_obj->diff_ferr, LAPACKE_GTEST_THRESHOLD);
}
/* Begin gerfs_double_parameters class definition */
class gerfs_double_parameters{
public:
int b_bufsize;
int x_bufsize;
double diff; // capture difference between ref o/p & libflame lapacke o/p.
double diff_berr, diff_ferr, diff_xerr;
void *hModule, *dModule;
/* Input parameters */
int matrix_layout; // storage layout LAPACK_ROW_MAJOR or LAPACK_COL_MAJOR
char fact; // Must be 'F', 'N', or 'E'.
char trans; // Must be 'N' , 'T' or 'C'.
lapack_int n; // The order of A (Square matrix).
lapack_int nrhs; // The number of right-hand sides
lapack_int lda; // leading dimension of 'a'
lapack_int ldb; // leading dimension of 'b'
lapack_int ldaf; // leading dimension of 'af'
lapack_int ldx; // leading dimension of 'x'
/* Input/ Output parameters */
double *b, *bref; //right-hand sides for the systems of equations.
double *a, *aref; //The array ab contains the matrix A
double *af, *afref; //contains the factored form of the matrix A
lapack_int *ipiv, *ipivref; // pivot buffer
/* Output parameters */
double rpivot, rpivotref; // reciprocal pivot growth factor.
double rcond, rcondref; // estimate of the reciprocal condition number of the matrix A.
double* x, *xref;
double* ferr, *ferrref; // estimated forward error bound for each solution vector x.
double* berr, *berrref; // component-wise relative backward error for each solution vector xj.
/* Return Values */
lapack_int info, inforef;
public:
gerfs_double_parameters ( int matrix_layout_i, char trans_i,
lapack_int n_i, lapack_int nrhs_i);
~gerfs_double_parameters ();
}; /* end of gerfs_double_parameters class definition */
/* Constructor gerfs_double_parameters definition */
gerfs_double_parameters:: gerfs_double_parameters ( int matrix_layout_i,
char trans_i, lapack_int n_i, lapack_int nrhs_i) {
matrix_layout = matrix_layout_i;
trans = trans_i;
n = n_i;
nrhs = nrhs_i;
lda = n;
ldaf = n;
if(matrix_layout==LAPACK_COL_MAJOR){
ldb = n;
ldx = n;
b_bufsize = ldb*nrhs;
x_bufsize = ldx*nrhs;
}
else if(matrix_layout==LAPACK_ROW_MAJOR){
ldb = nrhs;
ldx = nrhs;
b_bufsize = ldb*n;
x_bufsize = ldx*n;
}
else
{
EXPECT_TRUE(false) << "matrix_layout invalid";
}
#if LAPACKE_TEST_VERBOSE
printf(" \n gerfs Double: n: %d, fact: %c trans: %c lda: %d \
ldb: %d nrhs: %d ldaf: %d ldx: %d \n", n, fact, trans, lda,
ldb, nrhs);
#endif
/* Memory allocation of the buffers */
lapacke_gtest_alloc_double_buffer_pair( &a, &aref, n*n);
lapacke_gtest_alloc_double_buffer_pair( &b, &bref, n*nrhs);
lapacke_gtest_alloc_double_buffer_pair( &x, &xref, n*nrhs);
lapacke_gtest_alloc_double_buffer_pair( &af, &afref, (n*n));
lapacke_gtest_alloc_double_buffer_pair( &ferr, &ferrref, nrhs);
lapacke_gtest_alloc_double_buffer_pair( &berr, &berrref, nrhs);
lapacke_gtest_alloc_int_buffer_pair ( &ipiv, &ipivref, n+2);
if( (a==NULL) || (aref==NULL) || \
(b==NULL) || (bref==NULL) || \
(x==NULL) || (xref==NULL) || \
(af==NULL) || (afref==NULL) || \
(ferr==NULL) || (ferrref==NULL) || \
(berr==NULL) || (berrref==NULL) || \
(ipiv==NULL) || (ipivref==NULL) ){
EXPECT_FALSE( true) << "pbtrs_double_parameters object: malloc error.";
gerfs_free();
exit(-1);
}
/* Initialization of input Buffers */
lapacke_gtest_init_double_buffer_pair_rand( a, aref, n*n);
lapacke_gtest_init_double_buffer_pair_rand( b, bref, n*nrhs);
lapacke_gtest_init_double_buffer_pair_with_constant(x, xref, n*nrhs, 0.0);
lapacke_gtest_init_double_buffer_pair_with_constant(ferr, ferrref, nrhs, 0.0);
lapacke_gtest_init_double_buffer_pair_with_constant(berr, berrref, nrhs, 0.0);
memcpy(af, a, (n*n*sizeof(double)));
memcpy(afref, a, (n*n*sizeof(double)));
} /* end of Constructor */
gerfs_double_parameters:: ~gerfs_double_parameters ()
{
#if LAPACKE_TEST_VERBOSE
printf(" gerfs_double_parameters object: destructor invoked. \n");
#endif
gerfs_free();
}
// Test fixture class definition
class dgerfs_test : public ::testing::Test {
public:
gerfs_double_parameters *dgerfs_obj;
void SetUp();
void TearDown () { delete dgerfs_obj; }
};
void dgerfs_test::SetUp(){
/* LAPACKE DGERFS prototype */
typedef int (*Fptr_NL_LAPACKE_dgerfs) (int matrix_layout,
char trans,
lapack_int n,
lapack_int nrhs,
const double* a,
lapack_int lda,
const double* af,
lapack_int ldaf,
const lapack_int* ipiv,
const double* b,
lapack_int ldb,
double* x,
lapack_int ldx,
double* ferr,
double* berr);
Fptr_NL_LAPACKE_dgerfs DGERFS;
/* LAPACKE DGETRF prototype */
typedef int (*Fptr_NL_LAPACKE_dgetrf) ( int matrix_layout,lapack_int m,lapack_int n,
double* a,lapack_int lda,lapack_int* ipiv );
Fptr_NL_LAPACKE_dgetrf DGETRF;
dgerfs_obj = new gerfs_double_parameters ( lin_solver_paramslist[idx].matrix_layout,
lin_solver_paramslist[idx].transr,
lin_solver_paramslist[idx].n,
lin_solver_paramslist[idx].nrhs);
idx = Circular_Increment_Index(idx);
dgerfs_obj->dModule = dlopen(NETLIB_BLAS_LIB, RTLD_NOW | RTLD_GLOBAL);
dgerfs_obj->hModule = dlopen(NETLIB_LAPACKE_LIB, RTLD_NOW);
ASSERT_TRUE(dgerfs_obj->dModule != NULL) << "Netlib Blas handle NULL";
ASSERT_TRUE(dgerfs_obj->hModule != NULL) << "Netlib lapacke handle NULL";
DGERFS = (Fptr_NL_LAPACKE_dgerfs)dlsym(dgerfs_obj->hModule, "LAPACKE_dgerfs");
ASSERT_TRUE(DGERFS != NULL) << "failed to get the Netlib LAPACKE_dgerfs symbol";
DGETRF = (Fptr_NL_LAPACKE_dgetrf)dlsym(dgerfs_obj->hModule,"LAPACKE_dgetrf");
ASSERT_TRUE(DGETRF != NULL) << "failed to get the Netlib LAPACKE_dgetrf symbol";
dgerfs_obj->inforef = DGETRF( dgerfs_obj->matrix_layout,
dgerfs_obj->n, dgerfs_obj->n,
dgerfs_obj->afref,
dgerfs_obj->lda,
dgerfs_obj->ipivref);
dgerfs_obj->info = LAPACKE_dgetrf( dgerfs_obj->matrix_layout,
dgerfs_obj->n, dgerfs_obj->n,
dgerfs_obj->af,
dgerfs_obj->lda,
dgerfs_obj->ipiv);
/* Compute the reference o/p by invoking Netlib-Lapack's API */
dgerfs_obj->inforef = DGERFS( dgerfs_obj->matrix_layout,
dgerfs_obj->trans,
dgerfs_obj->n,
dgerfs_obj->nrhs,
dgerfs_obj->aref,
dgerfs_obj->lda,
dgerfs_obj->afref,
dgerfs_obj->ldaf,
dgerfs_obj->ipivref,
dgerfs_obj->bref,
dgerfs_obj->ldb,
dgerfs_obj->xref,
dgerfs_obj->ldx,
dgerfs_obj->ferrref,
dgerfs_obj->berrref );
/* Compute libflame's Lapacke o/p */
dgerfs_obj->info = LAPACKE_dgerfs( dgerfs_obj->matrix_layout,
dgerfs_obj->trans,
dgerfs_obj->n,
dgerfs_obj->nrhs,
dgerfs_obj->a,
dgerfs_obj->lda,
dgerfs_obj->af,
dgerfs_obj->ldaf,
dgerfs_obj->ipiv,
dgerfs_obj->b,
dgerfs_obj->ldb,
dgerfs_obj->x,
dgerfs_obj->ldx,
dgerfs_obj->ferr,
dgerfs_obj->berr);
if( dgerfs_obj->info < 0 ) {
printf( "\n warning: The i:%d th argument with libflame \
LAPACKE_dgerfs is wrong\n", dgerfs_obj->info );
}
if( dgerfs_obj->inforef < 0 ) {
printf( "The i:%d th argument with Netlib LAPACKE_dgerfs is wrong\n",
dgerfs_obj->inforef );
}
/* Compute Difference between libflame and Netlib o/ps */
dgerfs_obj->diff_xerr = computeDiff_d( dgerfs_obj->x_bufsize,
dgerfs_obj->x, dgerfs_obj->xref );
dgerfs_obj->diff_berr = computeDiff_d( dgerfs_obj->nrhs,
dgerfs_obj->berr, dgerfs_obj->berrref );
dgerfs_obj->diff_ferr = computeDiff_d( dgerfs_obj->nrhs,
dgerfs_obj->ferr, dgerfs_obj->ferrref );
}
TEST_F(dgerfs_test, dgerfs1) {
EXPECT_NEAR(0.0, dgerfs_obj->diff_xerr, LAPACKE_GTEST_THRESHOLD);
EXPECT_NEAR(0.0, dgerfs_obj->diff_berr, LAPACKE_GTEST_THRESHOLD);
EXPECT_NEAR(0.0, dgerfs_obj->diff_ferr, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(dgerfs_test, dgerfs2) {
EXPECT_NEAR(0.0, dgerfs_obj->diff_xerr, LAPACKE_GTEST_THRESHOLD);
EXPECT_NEAR(0.0, dgerfs_obj->diff_berr, LAPACKE_GTEST_THRESHOLD);
EXPECT_NEAR(0.0, dgerfs_obj->diff_ferr, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(dgerfs_test, dgerfs3) {
EXPECT_NEAR(0.0, dgerfs_obj->diff_xerr, LAPACKE_GTEST_THRESHOLD);
EXPECT_NEAR(0.0, dgerfs_obj->diff_berr, LAPACKE_GTEST_THRESHOLD);
EXPECT_NEAR(0.0, dgerfs_obj->diff_ferr, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(dgerfs_test, dgerfs4) {
EXPECT_NEAR(0.0, dgerfs_obj->diff_xerr, LAPACKE_GTEST_THRESHOLD);
EXPECT_NEAR(0.0, dgerfs_obj->diff_berr, LAPACKE_GTEST_THRESHOLD);
EXPECT_NEAR(0.0, dgerfs_obj->diff_ferr, LAPACKE_GTEST_THRESHOLD);
}
/* Begin gerfs_scomplex_parameters class definition */
class gerfs_scomplex_parameters{
public:
int b_bufsize;
int x_bufsize;
float diff; // capture difference between ref o/p & libflame lapacke o/p.
float diff_berr, diff_ferr, diff_xerr;
void *hModule, *dModule;
/* Input parameters */
int matrix_layout; // storage layout LAPACK_ROW_MAJOR or LAPACK_COL_MAJOR
char fact; // Must be 'F', 'N', or 'E'.
char trans; // Must be 'N' , 'T' or 'C'.
lapack_int n; // The order of A (Square matrix).
lapack_int nrhs; // The number of right-hand sides
lapack_int lda; // leading dimension of 'a'
lapack_int ldb; // leading dimension of 'b'
lapack_int ldaf; // leading dimension of 'af'
lapack_int ldx; // leading dimension of 'x'
/* Input/ Output parameters */
lapack_complex_float *b, *bref; //right-hand sides for the systems of equations.
lapack_complex_float *a, *aref; //The array ab contains the matrix A
lapack_complex_float *af, *afref; //contains the factored form of the matrix A
lapack_int *ipiv, *ipivref; // pivot buffer
/* Output parameters */
lapack_complex_float* x, *xref;
float* ferr, *ferrref; // estimated forward error bound for each solution vector x.
float* berr, *berrref; // component-wise relative backward error for each solution vector xj.
/* Return Values */
lapack_int info, inforef;
public:
gerfs_scomplex_parameters ( int matrix_layout_i, char trans_i,
lapack_int n_i, lapack_int nrhs_i);
~gerfs_scomplex_parameters ();
}; /* end of gerfs_scomplex_parameters class definition */
/* Constructor gerfs_scomplex_parameters definition */
gerfs_scomplex_parameters:: gerfs_scomplex_parameters ( int matrix_layout_i,
char trans_i, lapack_int n_i, lapack_int nrhs_i) {
matrix_layout = matrix_layout_i;
trans = trans_i;
n = n_i;
nrhs = nrhs_i;
lda = n;
ldaf = n;
if(matrix_layout==LAPACK_COL_MAJOR){
ldb = n;
ldx = n;
b_bufsize = ldb*nrhs;
x_bufsize = ldx*nrhs;
}
else if(matrix_layout==LAPACK_ROW_MAJOR){
ldb = nrhs;
ldx = nrhs;
b_bufsize = ldb*n;
x_bufsize = ldx*n;
}
else
{
EXPECT_TRUE(false) << "matrix_layout invalid";
}
#if LAPACKE_TEST_VERBOSE
printf(" \n gerfs Double: n: %d, fact: %c trans: %c lda: %d \
ldb: %d nrhs: %d ldaf: %d ldx: %d \n", n, fact, trans, lda,
ldb, nrhs);
#endif
/* Memory allocation of the buffers */
lapacke_gtest_alloc_lapack_scomplex_buffer_pair( &a, &aref, n*n);
lapacke_gtest_alloc_lapack_scomplex_buffer_pair( &b, &bref, n*nrhs);
lapacke_gtest_alloc_lapack_scomplex_buffer_pair( &x, &xref, n*nrhs);
lapacke_gtest_alloc_lapack_scomplex_buffer_pair( &af, &afref, (n*n));
lapacke_gtest_alloc_float_buffer_pair( &ferr, &ferrref, nrhs);
lapacke_gtest_alloc_float_buffer_pair( &berr, &berrref, nrhs);
lapacke_gtest_alloc_int_buffer_pair ( &ipiv, &ipivref, n+2);
if( (a==NULL) || (aref==NULL) || \
(b==NULL) || (bref==NULL) || \
(x==NULL) || (xref==NULL) || \
(af==NULL) || (afref==NULL) || \
(ferr==NULL) || (ferrref==NULL) || \
(berr==NULL) || (berrref==NULL) || \
(ipiv==NULL) || (ipivref==NULL) ){
EXPECT_FALSE( true) << "pbtrs_scomplex_parameters object: malloc error.";
gerfs_free();
exit(-1);
}
/* Initialization of input Buffers */
lapacke_gtest_init_scomplex_buffer_pair_rand( a, aref, n*n);
lapacke_gtest_init_scomplex_buffer_pair_rand( b, bref, n*nrhs);
lapacke_gtest_init_scomplex_buffer_pair_with_constant(x, xref, n*nrhs, 0.0);
lapacke_gtest_init_float_buffer_pair_with_constant(ferr, ferrref, nrhs, 0.0);
lapacke_gtest_init_float_buffer_pair_with_constant(berr, berrref, nrhs, 0.0);
memcpy(af, a, (n*n*sizeof(lapack_complex_float)));
memcpy(afref, a, (n*n*sizeof(lapack_complex_float)));
} /* end of Constructor */
gerfs_scomplex_parameters:: ~gerfs_scomplex_parameters ()
{
#if LAPACKE_TEST_VERBOSE
printf(" gerfs_scomplex_parameters object: destructor invoked. \n");
#endif
gerfs_free();
}
// Test fixture class definition
class cgerfs_test : public ::testing::Test {
public:
gerfs_scomplex_parameters *cgerfs_obj;
void SetUp();
void TearDown () { delete cgerfs_obj; }
};
void cgerfs_test::SetUp(){
/* LAPACKE CGERFS prototype */
typedef int (*Fptr_NL_LAPACKE_cgerfs) (int matrix_layout,
char trans,
lapack_int n,
lapack_int nrhs,
const lapack_complex_float* a,
lapack_int lda,
const lapack_complex_float* af,
lapack_int ldaf,
const lapack_int* ipiv,
const lapack_complex_float* b,
lapack_int ldb,
lapack_complex_float* x,
lapack_int ldx,
float* ferr,
float* berr);
Fptr_NL_LAPACKE_cgerfs CGERFS;
/* LAPACKE CGETRF prototype */
typedef int (*Fptr_NL_LAPACKE_cgetrf) ( int matrix_layout,lapack_int m,lapack_int n,
lapack_complex_float* a,lapack_int lda,lapack_int* ipiv );
Fptr_NL_LAPACKE_cgetrf CGETRF;
cgerfs_obj = new gerfs_scomplex_parameters ( lin_solver_paramslist[idx].matrix_layout,
lin_solver_paramslist[idx].transr,
lin_solver_paramslist[idx].n,
lin_solver_paramslist[idx].nrhs);
idx = Circular_Increment_Index(idx);
cgerfs_obj->dModule = dlopen(NETLIB_BLAS_LIB, RTLD_NOW | RTLD_GLOBAL);
cgerfs_obj->hModule = dlopen(NETLIB_LAPACKE_LIB, RTLD_NOW);
ASSERT_TRUE(cgerfs_obj->dModule != NULL) << "Netlib Blas handle NULL";
ASSERT_TRUE(cgerfs_obj->hModule != NULL) << "Netlib lapacke handle NULL";
CGERFS = (Fptr_NL_LAPACKE_cgerfs)dlsym(cgerfs_obj->hModule, "LAPACKE_cgerfs");
ASSERT_TRUE(CGERFS != NULL) << "failed to get the Netlib LAPACKE_cgerfs symbol";
CGETRF = (Fptr_NL_LAPACKE_cgetrf)dlsym(cgerfs_obj->hModule,"LAPACKE_cgetrf");
ASSERT_TRUE(CGETRF != NULL) << "failed to get the Netlib LAPACKE_cgetrf symbol";
cgerfs_obj->inforef = CGETRF( cgerfs_obj->matrix_layout,
cgerfs_obj->n, cgerfs_obj->n,
cgerfs_obj->afref,
cgerfs_obj->lda,
cgerfs_obj->ipivref);
cgerfs_obj->info = LAPACKE_cgetrf( cgerfs_obj->matrix_layout,
cgerfs_obj->n, cgerfs_obj->n,
cgerfs_obj->af,
cgerfs_obj->lda,
cgerfs_obj->ipiv);
/* Compute the reference o/p by invoking Netlib-Lapack's API */
cgerfs_obj->inforef = CGERFS( cgerfs_obj->matrix_layout,
cgerfs_obj->trans,
cgerfs_obj->n,
cgerfs_obj->nrhs,
cgerfs_obj->aref,
cgerfs_obj->lda,
cgerfs_obj->afref,
cgerfs_obj->ldaf,
cgerfs_obj->ipivref,
cgerfs_obj->bref,
cgerfs_obj->ldb,
cgerfs_obj->xref,
cgerfs_obj->ldx,
cgerfs_obj->ferrref,
cgerfs_obj->berrref );
/* Compute libflame's Lapacke o/p */
cgerfs_obj->info = LAPACKE_cgerfs( cgerfs_obj->matrix_layout,
cgerfs_obj->trans,
cgerfs_obj->n,
cgerfs_obj->nrhs,
cgerfs_obj->a,
cgerfs_obj->lda,
cgerfs_obj->af,
cgerfs_obj->ldaf,
cgerfs_obj->ipiv,
cgerfs_obj->b,
cgerfs_obj->ldb,
cgerfs_obj->x,
cgerfs_obj->ldx,
cgerfs_obj->ferr,
cgerfs_obj->berr);
if( cgerfs_obj->info < 0 ) {
printf( "\n warning: The i:%d th argument with libflame \
LAPACKE_cgerfs is wrong\n", cgerfs_obj->info );
}
if( cgerfs_obj->inforef < 0 ) {
printf( "The i:%d th argument with Netlib LAPACKE_cgerfs is wrong\n",
cgerfs_obj->inforef );
}
/* Compute Difference between libflame and Netlib o/ps */
cgerfs_obj->diff_xerr = computeDiff_c( cgerfs_obj->x_bufsize,
cgerfs_obj->x, cgerfs_obj->xref );
cgerfs_obj->diff_berr = computeDiff_s( cgerfs_obj->nrhs,
cgerfs_obj->berr, cgerfs_obj->berrref );
cgerfs_obj->diff_ferr = computeDiff_s( cgerfs_obj->nrhs,
cgerfs_obj->ferr, cgerfs_obj->ferrref );
}
TEST_F(cgerfs_test, cgerfs1) {
EXPECT_NEAR(0.0, cgerfs_obj->diff_xerr, LAPACKE_GTEST_THRESHOLD);
EXPECT_NEAR(0.0, cgerfs_obj->diff_berr, LAPACKE_GTEST_THRESHOLD);
EXPECT_NEAR(0.0, cgerfs_obj->diff_ferr, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(cgerfs_test, cgerfs2) {
EXPECT_NEAR(0.0, cgerfs_obj->diff_xerr, LAPACKE_GTEST_THRESHOLD);
EXPECT_NEAR(0.0, cgerfs_obj->diff_berr, LAPACKE_GTEST_THRESHOLD);
EXPECT_NEAR(0.0, cgerfs_obj->diff_ferr, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(cgerfs_test, cgerfs3) {
EXPECT_NEAR(0.0, cgerfs_obj->diff_xerr, LAPACKE_GTEST_THRESHOLD);
EXPECT_NEAR(0.0, cgerfs_obj->diff_berr, LAPACKE_GTEST_THRESHOLD);
EXPECT_NEAR(0.0, cgerfs_obj->diff_ferr, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(cgerfs_test, cgerfs4) {
EXPECT_NEAR(0.0, cgerfs_obj->diff_xerr, LAPACKE_GTEST_THRESHOLD);
EXPECT_NEAR(0.0, cgerfs_obj->diff_berr, LAPACKE_GTEST_THRESHOLD);
EXPECT_NEAR(0.0, cgerfs_obj->diff_ferr, LAPACKE_GTEST_THRESHOLD);
}
/* Begin gerfs_dcomplex_parameters class definition */
class gerfs_dcomplex_parameters{
public:
int b_bufsize;
int x_bufsize;
double diff; // capture difference between ref o/p & libflame lapacke o/p.
double diff_berr, diff_ferr, diff_xerr;
void *hModule, *dModule;
/* Input parameters */
int matrix_layout; // storage layout LAPACK_ROW_MAJOR or LAPACK_COL_MAJOR
char fact; // Must be 'F', 'N', or 'E'.
char trans; // Must be 'N' , 'T' or 'C'.
lapack_int n; // The order of A (Square matrix).
lapack_int nrhs; // The number of right-hand sides
lapack_int lda; // leading dimension of 'a'
lapack_int ldb; // leading dimension of 'b'
lapack_int ldaf; // leading dimension of 'af'
lapack_int ldx; // leading dimension of 'x'
/* Input/ Output parameters */
lapack_complex_double *b, *bref; //right-hand sides for the systems of equations.
lapack_complex_double *a, *aref; //The array ab contains the matrix A
lapack_complex_double *af, *afref; //contains the factored form of the matrix A
lapack_int *ipiv, *ipivref; // pivot buffer
/* Output parameters */
lapack_complex_double* x, *xref;
double* ferr, *ferrref; // estimated forward error bound for each solution vector x.
double* berr, *berrref; // component-wise relative backward error for each solution vector xj.
/* Return Values */
lapack_int info, inforef;
public:
gerfs_dcomplex_parameters ( int matrix_layout_i, char trans_i,
lapack_int n_i, lapack_int nrhs_i);
~gerfs_dcomplex_parameters ();
}; /* end of gerfs_dcomplex_parameters class definition */
/* Constructor gerfs_dcomplex_parameters definition */
gerfs_dcomplex_parameters:: gerfs_dcomplex_parameters ( int matrix_layout_i,
char trans_i, lapack_int n_i, lapack_int nrhs_i) {
matrix_layout = matrix_layout_i;
trans = trans_i;
n = n_i;
nrhs = nrhs_i;
lda = n;
ldaf = n;
if(matrix_layout==LAPACK_COL_MAJOR){
ldb = n;
ldx = n;
b_bufsize = ldb*nrhs;
x_bufsize = ldx*nrhs;
}
else if(matrix_layout==LAPACK_ROW_MAJOR){
ldb = nrhs;
ldx = nrhs;
b_bufsize = ldb*n;
x_bufsize = ldx*n;
}
else
{
EXPECT_TRUE(false) << "matrix_layout invalid";
}
#if LAPACKE_TEST_VERBOSE
printf(" \n gerfs Double: n: %d, fact: %c trans: %c lda: %d \
ldb: %d nrhs: %d ldaf: %d ldx: %d \n", n, fact, trans, lda,
ldb, nrhs);
#endif
/* Memory allocation of the buffers */
lapacke_gtest_alloc_lapack_dcomplex_buffer_pair( &a, &aref, n*n);
lapacke_gtest_alloc_lapack_dcomplex_buffer_pair( &b, &bref, n*nrhs);
lapacke_gtest_alloc_lapack_dcomplex_buffer_pair( &x, &xref, n*nrhs);
lapacke_gtest_alloc_lapack_dcomplex_buffer_pair( &af, &afref, (n*n));
lapacke_gtest_alloc_double_buffer_pair( &ferr, &ferrref, nrhs);
lapacke_gtest_alloc_double_buffer_pair( &berr, &berrref, nrhs);
lapacke_gtest_alloc_int_buffer_pair ( &ipiv, &ipivref, n+2);
if( (a==NULL) || (aref==NULL) || \
(b==NULL) || (bref==NULL) || \
(x==NULL) || (xref==NULL) || \
(af==NULL) || (afref==NULL) || \
(ferr==NULL) || (ferrref==NULL) || \
(berr==NULL) || (berrref==NULL) || \
(ipiv==NULL) || (ipivref==NULL) ){
EXPECT_FALSE( true) << "pbtrs_dcomplex_parameters object: malloc error.";
gerfs_free();
exit(-1);
}
/* Initialization of input Buffers */
lapacke_gtest_init_dcomplex_buffer_pair_rand( a, aref, n*n);
lapacke_gtest_init_dcomplex_buffer_pair_rand( b, bref, n*nrhs);
lapacke_gtest_init_dcomplex_buffer_pair_with_constant(x, xref, n*nrhs, 0.0);
lapacke_gtest_init_double_buffer_pair_with_constant(ferr, ferrref, nrhs, 0.0);
lapacke_gtest_init_double_buffer_pair_with_constant(berr, berrref, nrhs, 0.0);
memcpy(af, a, (n*n*sizeof(lapack_complex_double)));
memcpy(afref, a, (n*n*sizeof(lapack_complex_double)));
} /* end of Constructor */
gerfs_dcomplex_parameters:: ~gerfs_dcomplex_parameters ()
{
#if LAPACKE_TEST_VERBOSE
printf(" gerfs_dcomplex_parameters object: destructor invoked. \n");
#endif
gerfs_free();
}
// Test fixture class definition
class zgerfs_test : public ::testing::Test {
public:
gerfs_dcomplex_parameters *zgerfs_obj;
void SetUp();
void TearDown () { delete zgerfs_obj; }
};
void zgerfs_test::SetUp(){
/* LAPACKE ZGERFS prototype */
typedef int (*Fptr_NL_LAPACKE_zgerfs) (int matrix_layout,
char trans,
lapack_int n,
lapack_int nrhs,
const lapack_complex_double* a,
lapack_int lda,
const lapack_complex_double* af,
lapack_int ldaf,
const lapack_int* ipiv,
const lapack_complex_double* b,
lapack_int ldb,
lapack_complex_double* x,
lapack_int ldx,
double* ferr,
double* berr);
Fptr_NL_LAPACKE_zgerfs ZGERFS;
/* LAPACKE ZGETRF prototype */
typedef int (*Fptr_NL_LAPACKE_zgetrf) ( int matrix_layout,lapack_int m,lapack_int n,
lapack_complex_double* a,lapack_int lda,lapack_int* ipiv );
Fptr_NL_LAPACKE_zgetrf ZGETRF;
zgerfs_obj = new gerfs_dcomplex_parameters ( lin_solver_paramslist[idx].matrix_layout,
lin_solver_paramslist[idx].transr,
lin_solver_paramslist[idx].n,
lin_solver_paramslist[idx].nrhs);
idx = Circular_Increment_Index(idx);
zgerfs_obj->dModule = dlopen(NETLIB_BLAS_LIB, RTLD_NOW | RTLD_GLOBAL);
zgerfs_obj->hModule = dlopen(NETLIB_LAPACKE_LIB, RTLD_NOW);
ASSERT_TRUE(zgerfs_obj->dModule != NULL) << "Netlib Blas handle NULL";
ASSERT_TRUE(zgerfs_obj->hModule != NULL) << "Netlib lapacke handle NULL";
ZGERFS = (Fptr_NL_LAPACKE_zgerfs)dlsym(zgerfs_obj->hModule, "LAPACKE_zgerfs");
ASSERT_TRUE(ZGERFS != NULL) << "failed to get the Netlib LAPACKE_zgerfs symbol";
ZGETRF = (Fptr_NL_LAPACKE_zgetrf)dlsym(zgerfs_obj->hModule,"LAPACKE_zgetrf");
ASSERT_TRUE(ZGETRF != NULL) << "failed to get the Netlib LAPACKE_zgetrf symbol";
zgerfs_obj->inforef = ZGETRF( zgerfs_obj->matrix_layout,
zgerfs_obj->n, zgerfs_obj->n,
zgerfs_obj->afref,
zgerfs_obj->lda,
zgerfs_obj->ipivref);
zgerfs_obj->info = LAPACKE_zgetrf( zgerfs_obj->matrix_layout,
zgerfs_obj->n, zgerfs_obj->n,
zgerfs_obj->af,
zgerfs_obj->lda,
zgerfs_obj->ipiv);
/* Compute the reference o/p by invoking Netlib-Lapack's API */
zgerfs_obj->inforef = ZGERFS( zgerfs_obj->matrix_layout,
zgerfs_obj->trans,
zgerfs_obj->n,
zgerfs_obj->nrhs,
zgerfs_obj->aref,
zgerfs_obj->lda,
zgerfs_obj->afref,
zgerfs_obj->ldaf,
zgerfs_obj->ipivref,
zgerfs_obj->bref,
zgerfs_obj->ldb,
zgerfs_obj->xref,
zgerfs_obj->ldx,
zgerfs_obj->ferrref,
zgerfs_obj->berrref );
/* Compute libflame's Lapacke o/p */
zgerfs_obj->info = LAPACKE_zgerfs( zgerfs_obj->matrix_layout,
zgerfs_obj->trans,
zgerfs_obj->n,
zgerfs_obj->nrhs,
zgerfs_obj->a,
zgerfs_obj->lda,
zgerfs_obj->af,
zgerfs_obj->ldaf,
zgerfs_obj->ipiv,
zgerfs_obj->b,
zgerfs_obj->ldb,
zgerfs_obj->x,
zgerfs_obj->ldx,
zgerfs_obj->ferr,
zgerfs_obj->berr);
if( zgerfs_obj->info < 0 ) {
printf( "\n warning: The i:%d th argument with libflame \
LAPACKE_zgerfs is wrong\n", zgerfs_obj->info );
}
if( zgerfs_obj->inforef < 0 ) {
printf( "The i:%d th argument with Netlib LAPACKE_zgerfs is wrong\n",
zgerfs_obj->inforef );
}
/* Compute Difference between libflame and Netlib o/ps */
zgerfs_obj->diff_xerr = computeDiff_z( zgerfs_obj->x_bufsize,
zgerfs_obj->x, zgerfs_obj->xref );
zgerfs_obj->diff_berr = computeDiff_d( zgerfs_obj->nrhs,
zgerfs_obj->berr, zgerfs_obj->berrref );
zgerfs_obj->diff_ferr = computeDiff_d( zgerfs_obj->nrhs,
zgerfs_obj->ferr, zgerfs_obj->ferrref );
}
TEST_F(zgerfs_test, zgerfs1) {
EXPECT_NEAR(0.0, zgerfs_obj->diff_xerr, LAPACKE_GTEST_THRESHOLD);
EXPECT_NEAR(0.0, zgerfs_obj->diff_berr, LAPACKE_GTEST_THRESHOLD);
EXPECT_NEAR(0.0, zgerfs_obj->diff_ferr, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(zgerfs_test, zgerfs2) {
EXPECT_NEAR(0.0, zgerfs_obj->diff_xerr, LAPACKE_GTEST_THRESHOLD);
EXPECT_NEAR(0.0, zgerfs_obj->diff_berr, LAPACKE_GTEST_THRESHOLD);
EXPECT_NEAR(0.0, zgerfs_obj->diff_ferr, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(zgerfs_test, zgerfs3) {
EXPECT_NEAR(0.0, zgerfs_obj->diff_xerr, LAPACKE_GTEST_THRESHOLD);
EXPECT_NEAR(0.0, zgerfs_obj->diff_berr, LAPACKE_GTEST_THRESHOLD);
EXPECT_NEAR(0.0, zgerfs_obj->diff_ferr, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(zgerfs_test, zgerfs4) {
EXPECT_NEAR(0.0, zgerfs_obj->diff_xerr, LAPACKE_GTEST_THRESHOLD);
EXPECT_NEAR(0.0, zgerfs_obj->diff_berr, LAPACKE_GTEST_THRESHOLD);
EXPECT_NEAR(0.0, zgerfs_obj->diff_ferr, LAPACKE_GTEST_THRESHOLD);
}
| true |
906297e61217ec26968ca6ca557884b1efa5ae82
|
C++
|
kmehrunes/BoundedMap
|
/bounded_map.h
|
UTF-8
| 2,432 | 3.515625 | 4 |
[] |
no_license
|
#ifndef BOUNDED_MAP_H
#define BOUNDED_MAP_H
#include <deque>
template<typename map_t, typename key_t, typename value_t, unsigned cap>
class static_bounded_map
{
public:
/**
* @throws exception!
*/
void insert(std::pair<key_t, value_t> entry)
{
m_map.insert(entry);
m_keys.push_back(entry.first);
if (m_keys.size() > cap)
remove_oldest();
}
value_t & at(key_t key)
{
return m_map.at(key);
}
typename map_t::size_type size()
{
return m_map.size();
}
typename map_t::iterator begin()
{
return m_map.begin();
}
typename map_t::iterator cbegin()
{
return m_map.cbegin();
}
typename map_t::iterator end()
{
return m_map.end();
}
typename map_t::iterator cend()
{
return m_map.cend();
}
private:
/**
* @brief remove_last
* @throws An exception if any operation on internal
* structures threw one.
*/
void remove_oldest()
{
key_t & front = m_keys.front();
m_map.erase(front);
m_keys.pop_front();
}
private:
std::deque<key_t> m_keys;
map_t m_map;
};
template<typename map_t, typename key_t, typename value_t>
class bounded_map
{
public:
bounded_map(unsigned cap)
{
m_cap = cap;
}
/**
* @throws exception!
*/
void insert(std::pair<key_t, value_t> entry)
{
m_map.insert(entry);
m_keys.push_back(entry.first);
if (m_keys.size() > m_cap)
remove_oldest();
}
value_t & at(key_t key)
{
return m_map.at(key);
}
typename map_t::size_type size()
{
return m_map.size();
}
typename map_t::iterator begin()
{
return m_map.begin();
}
typename map_t::iterator cbegin()
{
return m_map.cbegin();
}
typename map_t::iterator end()
{
return m_map.end();
}
typename map_t::iterator cend()
{
return m_map.cend();
}
private:
/**
* @brief remove_last
* @throws An exception if any operation on internal
* structures threw one.
*/
void remove_oldest()
{
key_t & front = m_keys.front();
m_map.erase(front);
m_keys.pop_front();
}
private:
std::deque<key_t> m_keys;
map_t m_map;
unsigned m_cap;
};
#endif // BOUNDED_MAP_H
| true |
c252e0d56a2275c9bc614c4ee4864d8353d8477a
|
C++
|
zhjwpku/leetcode
|
/solutions/129_sum_root_to_leaf_numbers.cpp
|
UTF-8
| 384 | 3.21875 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
using namespace std;
int sumNumbers(TreeNode *root, int sum) {
if (root == NULL) return 0;
if (root->left == NULL && root->right == NULL)
return sum * 10 + root->val;
return sumNumbers(root->left, sum * 10 + root->val) +
sumNumbers(root->right, sum * 10 + root->val);
}
int sumNumbers(TreeNode *root) {
return sumNumbers(root, 0);
}
| true |
660f3b337343ad7d1a9061eabd21facd07f320c4
|
C++
|
JanWalsh91/Piscine_CPP
|
/j02/ex02/Fixed.hpp
|
UTF-8
| 1,192 | 2.765625 | 3 |
[] |
no_license
|
#ifndef FIXED_H
# define FIXED_H
#include <iostream>
class Fixed {
private:
int _i;
static const int _bit = 8;
public:
Fixed( void );
Fixed( Fixed const & fixed );
Fixed( int const i );
Fixed( float const i );
~Fixed( void );
Fixed & operator=( Fixed const & rhs );
Fixed operator+( Fixed const & rhs );
Fixed operator-( Fixed const & rhs );
Fixed operator*( Fixed const & rhs );
Fixed operator/( Fixed const & rhs );
Fixed operator++( int i );
Fixed operator--( int i );
Fixed & operator++( void );
Fixed & operator--( void );
bool operator<( Fixed const & rhs );
bool operator>( Fixed const & rhs );
bool operator<=( Fixed const & rhs );
bool operator>=( Fixed const & rhs );
bool operator==( Fixed const & rhs );
bool operator!=( Fixed const & rhs );
int getRawBits( void ) const;
void setRawBits( int const raw );
float toFloat( void ) const;
int toInt( void ) const;
static const Fixed & min(const Fixed & a, const Fixed & b);
static const Fixed & max(const Fixed & a, const Fixed & b);
};
std::ostream & operator<<( std::ostream & o, Fixed const & rhs );
#endif
| true |
84313dd09c721f3e24e5444bf3901491666682f3
|
C++
|
v8App/v8App
|
/libs/core/testLib/TestLogSink.cc
|
UTF-8
| 5,259 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
// Copyright 2020 The v8App Authors. All rights reserved.
// Use of this source code is governed by a MIT license that can be
// found in the LICENSE file.
#include <queue>
#include <iostream>
#include <algorithm>
#include "Logging/Log.h"
#include "TestLogSink.h"
namespace v8App
{
namespace TestUtils
{
const std::string TestLogSink::GlobalTestSinkName("GlobalTestLogSink");
TestLogSink *TestLogSink::GetGlobalSink()
{
ILogSink* sink = Log::Log::GetLogSink(GlobalTestSinkName);
TestLogSink* testSink;
//if we get backa sink then we need to make sure it's a TestLogSink
if(sink != nullptr)
{
testSink = dynamic_cast<TestLogSink*>(sink);
if(testSink != nullptr)
{
return testSink;
}
//It's not so remove it and we'll readd it.
Log::Log::RemoveLogSink(GlobalTestSinkName);
}
//By default we want everything but it can be changed
WantsLogLevelsVector wants = {
Log::LogLevel::Error,
Log::LogLevel::General,
Log::LogLevel::Warn,
Log::LogLevel::Debug,
Log::LogLevel::Trace,
};
testSink = new TestLogSink(GlobalTestSinkName, wants);
std::unique_ptr<ILogSink> uTestSink(testSink);
Log::Log::AddLogSink(uTestSink);
return testSink;
}
TestLogSink::TestLogSink(const std::string &inName, const WantsLogLevelsVector &inWantLevels)
: ILogSink(inName), m_WantsLevels(inWantLevels)
{
}
void TestLogSink::SinkMessage(Log::LogMessage &inMessage)
{
m_Message.push_back(inMessage);
}
bool TestLogSink::WantsLogMessage(Log::LogLevel inLevel)
{
return (std::find(m_WantsLevels.begin(), m_WantsLevels.end(), inLevel) != m_WantsLevels.end());
}
void TestLogSink::SetWantsLogLevels(const WantsLogLevelsVector &inLevels)
{
m_WantsLevels = inLevels;
}
bool TestLogSink::PopMessage(Log::LogMessage &inMessage)
{
if (m_Message.empty())
{
return false;
}
inMessage = m_Message.front();
m_Message.pop_front();
return true;
}
bool TestLogSink::NoMessages() const
{
return m_Message.empty();
}
void TestLogSink::FlushMessages()
{
m_Message.clear();
}
bool TestLogSink::validateMessage(const Log::LogMessage &inExpected, const IgnoreMsgKeys &inIgnoreKeys, int skipMessages)
{
Log::LogMessage message;
if (m_Message.size() <= skipMessages)
{
std::cout << "Not enough messages to validate." << std::endl;
return false;
}
for (int x = 0; x < skipMessages; x++)
{
m_Message.pop_front();
}
message = m_Message.front();
m_Message.pop_front();
bool retValue = true;
//as part of the test we want to find the difference between the 2 maps
for (auto const &it : inExpected)
{
if (message.find(it.first) == message.end())
{
retValue = false;
break;
}
if (it.second != message[it.first])
{
retValue = false;
break;
}
}
//check for extra keys only if we validated the expected message
if (retValue)
{
//now run the reverse to find extra keys
for (auto const &it : message)
{
//if it's in the ignore list then skip it
if (std::find(inIgnoreKeys.begin(), inIgnoreKeys.end(), it.first) != inIgnoreKeys.end())
{
continue;
}
if (inExpected.find(it.first) == inExpected.end())
{
retValue = false;
continue;
}
}
}
if (retValue == false)
{
//ok pritnt hem out so we can see what was different
std::cout << "Expected:" << std::endl
<< "{" << std::endl;
for (auto const &it : inExpected)
{
std::cout << " " << it.first << " : " << it.second << std::endl;
}
std::cout << "}" << std::endl;
std::cout << "Actual:" << std::endl
<< "{" << std::endl;
for (auto const &it : message)
{
std::cout << " " << it.first << " : " << it.second << std::endl;
}
std::cout << "}" << std::endl;
}
return retValue;
}
}
}
| true |
d5c2e6e4c0365750ac4757d8b452399d2869770a
|
C++
|
alexvking/Clondike
|
/Clondike/Card.cpp
|
UTF-8
| 278 | 2.5625 | 3 |
[] |
no_license
|
//
// Card.cpp
// Clondike
//
// Created by Alex King on 6/30/17.
// Copyright © 2017 Alex King. All rights reserved.
//
#include "Card.hpp"
Card::Card()
{
this->rank = RANK_2;
this->suit = HEART;
}
Card::Card(Rank r, Suit s)
{
this->rank = r;
this->suit = s;
}
| true |
49a1efe0a7fd59167cfef3dfc2513fae767a9175
|
C++
|
Team3835Vulcan/robot-2018
|
/robot2018/src/Commands/Collector/SwitchClaw.cpp
|
UTF-8
| 930 | 2.5625 | 3 |
[] |
no_license
|
#include "SwitchClaw.h"
#include <Subsystems/Collector/Collector.h>
SwitchClaw::SwitchClaw() {
// Use Requires() here to declare subsystem dependencies
// eg. Requires(Robot::chassis.get());
}
// Called just before this Command runs the first time
void SwitchClaw::Initialize() {
if(Collector::GetInstance().GetClawMode() == Collector::CLAWMODE::OPEN)
Collector::GetInstance().SwitchClaw(Collector::CLAWMODE::CLOSE);
else
Collector::GetInstance().SwitchClaw(Collector::CLAWMODE::OPEN);
}
// Called repeatedly when this Command is scheduled to run
void SwitchClaw::Execute() {
}
// Make this return true when this Command no longer needs to run execute()
bool SwitchClaw::IsFinished() {
return true;
}
// Called once after isFinished returns true
void SwitchClaw::End() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
void SwitchClaw::Interrupted() {
}
| true |
ad9019dfd777b9738e3e0b864322630a3325db79
|
C++
|
wangyongliang/nova
|
/poj/1923/POJ_1923_2800560_AC_0MS_1236K.cpp
|
UTF-8
| 1,128 | 2.625 | 3 |
[] |
no_license
|
#include <iostream.h>
#include <memory.h>
#include <stdio.h>
const int maxn = 101;
const int maxm = 10001;
int flag,N,M,dp[maxn][maxm];
void Dynamic(int T)
{
int i,j,k,e,t;
for (i=flag; i<=N; i++)
{
t = i * (i-1) / 2;
for (j=1; j<=t; j++)
{
if (dp[i][j]) continue;
for (k=0; k<=i; k++)
{
e = j-k*(i-k);
if (e <0) break;
if (e>=0 && dp[i-k][e])
{
dp[i][j]=1;break;
}
}
}
}
flag = N+1;
if (dp[N][M])
printf("Case %d: %d lines with exactly %d crossings can cut the plane into %d pieces at most.\n"
,T,N,M,N+M+1);
else printf("Case %d: %d lines cannot make exactly %d crossings.\n",T,N,M);
}
int main()
{
int i,T=0;
flag = 2;
for (i=0; i<=100; i++) dp[i][0]=1;
while (scanf("%d%d",&N,&M))
{
if (N==0 && M==0) return 0;
T++;
if (N < flag)
{
if (dp[N][M])
printf("Case %d: %d lines with exactly %d crossings can cut the plane into %d pieces at most.\n"
,T,N,M,N+M+1);
else printf("Case %d: %d lines cannot make exactly %d crossings.\n",T,N,M);
}
else
Dynamic(T);
}
return 0;
}
| true |
22d05990e7a01f181ebf2d82082ff8a0e6193f90
|
C++
|
LeandroRodriguez/fpietomrearoleanoagus
|
/NodoInterno.cpp
|
UTF-8
| 14,446 | 2.953125 | 3 |
[] |
no_license
|
#include "NodoInterno.h"
bool compare (SubClaveRef* s1, SubClaveRef* s2){
bool resultado = s1->esMenorEstrictoQue(s2);
return resultado;
};
bool NodoInterno::SeRepiteSubclave(SubClaveRef* item){
list< SubClaveRef* >::iterator it;
it = this->ListaSubClaveRef->begin();
bool SeRepite=false;
for(;it!=this->ListaSubClaveRef->end();it++){
SubClaveRef* cosa = *it;
if( cosa->esIgualQue(item)){
SeRepite=true;
break;
}
}
return SeRepite;
}
void NodoInterno::inicialize(){
this->tamanioMaximoNodo=LONGITUD_BLOQUE_NODO;
this->CantElem=0;
this->ListaSubClaveRef= new list<SubClaveRef* >;
}
NodoInterno::NodoInterno(Bytes* CodigoBinario){
this->inicialize();
char* cod = new char[CodigoBinario->toString().length()];
strcpy(cod,CodigoBinario->toString().c_str());
this->Hidratar(cod);
}
NodoInterno::NodoInterno(char* cadena){
this->inicialize();
this->Hidratar(cadena);
}
NodoInterno::NodoInterno(){
this->inicialize();
}
NodoInterno::NodoInterno(int ref1,string subclave ,int ref2){
this->inicialize();
this->Inicializar(ref1,subclave,ref2);
}
Resultado NodoInterno::InsertarNuevaSubClaveRef ( string subclave,int refAbloqueArbol ){
/*Busca en el nodo si hay algún registro con los mismos identificadores que IdentificadorDato.
Si lo encuentra, devuelve como resultado RES_DUPLICADO.
Si el nodo hoja desborda, Devuelve RES_DESBORDADO
sino, devuelve RES_OK*/
if(this->ListaSubClaveRef->empty()){
this->ListaSubClaveRef->push_front(new SubClaveRef(subclave,refAbloqueArbol));
this->CantElem=this->CantElem+1;
return RES_OK;
}
SubClaveRef* itemNuevo = new SubClaveRef(subclave,refAbloqueArbol);
if( this->SeRepiteSubclave(itemNuevo) )return RES_DUPLICADO;
// SubClaveRef* primeritem = this->ListaSubClaveRef->front();
// if( itemNuevo->esMenorEstrictoQue(primeritem) ) {
// int aux = itemNuevo->getRefNodo();
// itemNuevo->setRefNodo(this->Ref1erNodo);
// this->Ref1erNodo=aux;/*tiene un grado mas de complejidad, debido a 1er ref nodo*/
// this->ListaSubClaveRef->push_front(itemNuevo);
// this->CantElem=this->CantElem+1;
// }else{
this->ListaSubClaveRef->push_back(itemNuevo);
this->ListaSubClaveRef->sort(compare);
this->CantElem=this->CantElem+1;
// }
if ( this->getTamanioSerializado() > this->tamanioMaximoNodo ) return RES_DESBORDADO;
return RES_OK;
}
void NodoInterno::Inicializar( int ref1 ,string subclave ,int ref2 ){
this->Ref1erNodo=ref1;
this->InsertarNuevaSubClaveRef(subclave,ref2);
}
unsigned long int NodoInterno::getTamanioSerializado(){
size_t tamanioSerializado = 0;
tamanioSerializado += sizeof(this->CantElem);
tamanioSerializado += sizeof(this->Altura);
tamanioSerializado += sizeof(this->dimension);
tamanioSerializado += sizeof(this->Ref1erNodo);
/* consigo el tamanio de los elementos contenidos en ListaSubClaveRef*/
list< SubClaveRef* >::iterator it;
it = this->ListaSubClaveRef->begin();
for(;it!=this->ListaSubClaveRef->end();it++){
tamanioSerializado += (*it)->getTamanioSerializado();
}
return tamanioSerializado;
}
char* NodoInterno::Serializarse(){
unsigned long int tamanioTotal = this->getTamanioSerializado();
/*el string que voy a devolver*/
char* str =(char*) malloc(tamanioTotal * sizeof(char));
unsigned int cur = 0;/*cur = cursor*/
/*guardo la cantidad de elementos */
memcpy(str + cur, &this->CantElem , sizeof(this->CantElem));
cur += sizeof(this->CantElem);
memcpy(str + cur,&this->Altura, sizeof(this->Altura));
cur += sizeof(this->Altura);
memcpy(str + cur,&this->dimension , sizeof(this->dimension));
cur += sizeof(this->dimension);
memcpy(str + cur,&this->Ref1erNodo, sizeof(this->Ref1erNodo));
cur += sizeof(this->Ref1erNodo);
/*tengo que guardar todos los elementos de la lista */
list< SubClaveRef* >::iterator it;
it= this->ListaSubClaveRef->begin();
for(;it!=this->ListaSubClaveRef->end();it++){
SubClaveRef* cosa = *it;
char* serializacion = cosa->Serializarse();
memcpy(str+cur, serializacion, cosa->getTamanioSerializado() );
cur+=cosa->getTamanioSerializado();
}
//cout << "linea" << string(str) << endl;
return str;
}
void NodoInterno::Hidratar(char* bytes){
unsigned int cur = 0;/*cur = cursor ,ya se sabe el tipo*/
int AUXMAXCANT =0;//OJO, cant de elementos crece naturalmente al ingresar datos
memcpy(&AUXMAXCANT, bytes + cur, sizeof(this->CantElem));
cur += sizeof(this->CantElem);
memcpy(&this->Altura, bytes + cur, sizeof(this->Altura));
cur += sizeof(this->Altura);
//cout << "Altura: " << this->Altura << endl;
memcpy(&this->dimension, bytes + cur, sizeof(this->dimension));
cur += sizeof(this->dimension);
// cout << "Dimension: " << this->dimension << endl;
memcpy(&this->Ref1erNodo, bytes+ cur, sizeof(this->Ref1erNodo));
cur += sizeof(this->Ref1erNodo);
// cout << "Ref1erNodo: " << this->Ref1erNodo << endl;
//int hastaaca = cur;
int i=0;
while( i < AUXMAXCANT ){
SubClaveRef scr(bytes,cur);
this->InsertarNuevaSubClaveRef( scr.getSubClave(),scr.getRefNodo() );
//el cur se va incrementando solo, adentro del constructor de SubClaveRef
//cout << "cursor: " << (cur-hastaaca) << endl;
i=i+1;
}
}
int NodoInterno::DevolverNodoHijoSegunSubclave(string subcReq,int& OtroIdNodoEnCasoDeSubClaveIgual){
OtroIdNodoEnCasoDeSubClaveIgual= IDNODOINVALIDO;//DEFAULT
list< SubClaveRef* >::iterator it;
it= this->ListaSubClaveRef->begin();
SubClaveRef* cosa = *it;
//CasoParticularExtremoIzquierdo
/***********************************************************************/
bool FirstSubIgualaSubReq = (cosa->esIgualQue(subcReq));
if(FirstSubIgualaSubReq){
OtroIdNodoEnCasoDeSubClaveIgual = this->Ref1erNodo;
return cosa->getRefNodo();
}
bool FirstSubMayorEstrictoAsubReq = (cosa->esMayorEstrictoQue(subcReq));
if (FirstSubMayorEstrictoAsubReq){
return this->Ref1erNodo;
}
/***********************************************************************/
/*ya considere para el caso del extremo izquierdo */
for(;it!=this->ListaSubClaveRef->end();it++){
cosa = *it;
bool SubIgual = (cosa->esIgualQue(subcReq));
bool SubMayorEstricto = (cosa->esMayorEstrictoQue(subcReq));
/*si es igual, devuelvo ref a la derecha la subK de la lista,y el anterior */
if( SubIgual ) {
OtroIdNodoEnCasoDeSubClaveIgual = (*(it--))->getRefNodo();
return cosa->getRefNodo();
}
if (SubMayorEstricto){
/*si la subK en la que estoy en la lista, es mas grande que subcReq, devuelvo ref anterior */
it--;
cosa = *it;
return ( cosa->getRefNodo() );
}
/*si llegue aca, mi subcReq,es mayor que mi subK de la pos en la que estoy */
}
/*si llegue hasta aca, tengo que irme por el extremo derecho */
return cosa->getRefNodo();
}
list<int>* NodoInterno::DevolverTodosSusIdHijosEnOrden(){
list<int>* listIdHijos = new list<int>();
list< SubClaveRef* >::iterator it;
it= this->ListaSubClaveRef->begin();
listIdHijos->push_back(this->Ref1erNodo);
for( ; it != this->ListaSubClaveRef->end() ; it++ ){
SubClaveRef* item = *it;
// std::cout << "Id Hijo: " << (*item).getRefNodo() << endl;
listIdHijos->push_back(item->getRefNodo() );
}
return listIdHijos;
}
list<Nodo*>* NodoInterno::DevolverNodosDadasIds(list<int>* ListaIdsNodos){
list<Nodo*>* ListaNodosAdevolver = new list<Nodo*>();
list<int>::iterator it;
it= ListaIdsNodos->begin();
for(;it!=ListaIdsNodos->end();it++){
ListaNodosAdevolver->push_back(this->arbol->DevolverNodoSegunID(*it));
}
return ListaNodosAdevolver;
}
void NodoInterno::imprimir(){
std::cout <<"idBloque:"<<this->idBloque << ", cantElem:"<< this->CantElem << ", altura:" << this->Altura
<< ", dimension:" << this->dimension<< ", Referencias:"<<endl;
std::cout<< "idNodo: " << this->Ref1erNodo << endl;
list< SubClaveRef* >::iterator it;
it= this->ListaSubClaveRef->begin();
for(;it!=this->ListaSubClaveRef->end();it++){
SubClaveRef* cosa = *it;
cosa->imprimir();
}
std::cout <<"***************+++***************" << endl;
list< SubClaveRef* >::iterator it2;
it2= this->ListaSubClaveRef->begin();
Nodo* nodito = this->arbol->DevolverNodoSegunID(this->Ref1erNodo);
if(!nodito->tieneArbol())nodito->setArbol(this->arbol);
nodito->imprimir();
for(;it2!=this->ListaSubClaveRef->end();it2++){
SubClaveRef* sc = *it2;
Nodo* cosa = this->arbol->DevolverNodoSegunID(sc->getRefNodo());
if(!cosa->tieneArbol())cosa->setArbol(this->arbol);
cosa->imprimir();
}
}
bool NodoInterno::BuscarDato(Key* datoBuscado){
bool encontrado = false;
string subclave = datoBuscado->getSubClaveSegunDim(this->dimension);
int otroNodoPorSiDaIgualSub = IDNODOINVALIDO;
int id = this->DevolverNodoHijoSegunSubclave(subclave,otroNodoPorSiDaIgualSub);
Nodo* nodoHijo = arbol->DevolverNodoSegunID(id);
if( otroNodoPorSiDaIgualSub != IDNODOINVALIDO ){
Nodo* otroHijo = arbol->DevolverNodoSegunID(otroNodoPorSiDaIgualSub);
encontrado = ( nodoHijo->BuscarDato(datoBuscado) || otroHijo->BuscarDato(datoBuscado));
}else{
encontrado = nodoHijo->BuscarDato(datoBuscado);
}
return encontrado;
}
/*Se le pasa la subclave y la dimension a la que corresponde esta, mas el rango de fechas */
list<Key*>* NodoInterno::BuscarSegunFecha(string subclave, int dim, string fechaInicio, string fechaFin){
list<Key*>* datos1 = new list<Key*>();
list<Key*>* datos2 = new list<Key*>();
int otroNodoPorSiDaIgualSub = IDNODOINVALIDO;
if (this->getDim() == dim){
//caso feliz en q la dim coindice
int id = this->DevolverNodoHijoSegunSubclave(subclave,otroNodoPorSiDaIgualSub);
Nodo* nodoHijo = arbol->DevolverNodoSegunID(id);
if( otroNodoPorSiDaIgualSub != IDNODOINVALIDO ){
Nodo* otroHijo = arbol->DevolverNodoSegunID(otroNodoPorSiDaIgualSub);
datos1 = nodoHijo->BuscarSegunFecha(subclave, dim, fechaInicio, fechaFin);
datos2 = otroHijo->BuscarSegunFecha(subclave, dim, fechaInicio, fechaFin);
}else{
datos1 = nodoHijo->BuscarSegunFecha(subclave, dim, fechaInicio, fechaFin);
}
datos1->merge(*datos2);
}
else{
//caso no feliz en q la dim no coincide
list<int>* ids = this->DevolverTodosSusIdHijosEnOrden();
//devuelve lista de nodos hijos
list<Nodo*>* nodos= this->DevolverNodosDadasIds(ids);
list<Nodo*>::iterator itNodo = nodos->begin();
while (itNodo != nodos->end()){
datos2 = (*itNodo)->BuscarSegunFecha(subclave, dim, fechaInicio, fechaFin);
datos1->merge(*datos2);
itNodo++;
}
}
return datos1;
}
Resultado NodoInterno::insertarElemento(offset nroBloque, offset nroRegistro, Key* dato, double porcentaje){
string subclave = dato->getSubClaveSegunDim(this->dimension);
int dummy =0;
int IDNodoAbajo = this->DevolverNodoHijoSegunSubclave(subclave,dummy);
Resultado Res;
if (this->Altura > 1 ){/*He aqui la recursividad.Voy bajando por el arbol */
//levantar un nodo interno, de la persistencia, con IDNodoAbajo
Nodo* NodoLeido =this->arbol->DevolverNodoSegunID(IDNodoAbajo);
Res = NodoLeido->insertarElemento(nroBloque,nroRegistro,dato,porcentaje);
}else{/*estoy en un nodo interno de nivel 1*/
NodoHoja* NodoHleido = (NodoHoja*)(this->arbol->DevolverNodoSegunID(IDNodoAbajo));
Res = NodoHleido->insertarElemento(nroBloque,nroRegistro,dato, porcentaje);
if (Res == RES_DESBORDADO ){/*Aca tengo que solucionar overflow Hojas */
NodoHoja* NHder=NULL;
Key* k=NULL;
NHder = NodoHleido->PartirEn2(k, this->dimension);
Res = this->InsertarNuevaSubClaveRef((k->getSubClaveSegunDim(this->dimension)),NHder->getIdDelNodo());
if (Res==RES_OK || Res==RES_DESBORDADO){//actualizo todos los cambios
this->arbol->actualizarNodo(this);
this->arbol->actualizarNodo(NodoHleido);
this->arbol->actualizarNodo(NHder);
}
}else{
this->arbol->actualizarNodo(NodoHleido);
}
}
return Res;
}
void NodoInterno::setAltura(int h){
this->Altura=h;
}
void NodoInterno::setDim(int h){
this->dimension=h;
}
int NodoInterno::getDim(){
return this->dimension;
}
int NodoInterno::getAltura(){
return this->Altura;
}
bool NodoInterno::Baja(Key* datoBuscado){
bool encontrado = false;
string subclave = datoBuscado->getSubClaveSegunDim(this->dimension);
int otroNodoPorSiDaIgualSub = IDNODOINVALIDO;
int id = this->DevolverNodoHijoSegunSubclave(subclave,otroNodoPorSiDaIgualSub);
Nodo* nodoHijo = arbol->DevolverNodoSegunID(id);
if( otroNodoPorSiDaIgualSub != IDNODOINVALIDO ){
Nodo* otroHijo = arbol->DevolverNodoSegunID(otroNodoPorSiDaIgualSub);
bool encontroPrimero = nodoHijo->Baja(datoBuscado);
if(!encontroPrimero){
bool encontroSegundo = otroHijo->Baja(datoBuscado);
encontrado = encontroSegundo;
}
else
return true;
}else{
encontrado = nodoHijo->Baja(datoBuscado);
}
return encontrado;
}
| true |
ee616e7a7b497c1b667baa4aa0ee98695e404445
|
C++
|
marioblendea/CPPPlayground
|
/problems/largestNumberFrom2Arrays/largestNumberFrom2Arrays.test.cpp
|
UTF-8
| 384 | 3.078125 | 3 |
[] |
no_license
|
#include "gtest/gtest.h"
#include "largestNumberFrom2Arrays.h"
TEST(LargestNumberFrom2Arrays, test123) {
LargestNumberFrom2Arrays s;
std::vector<int> v1 = {3, 4, 6, 5};
std::vector<int> v2 = {9, 1, 2, 5, 8, 3};
auto res = s.maxNumber(v1, v2, 3);
EXPECT_EQ(res[0], 9);
EXPECT_EQ(res[1], 8);
EXPECT_EQ(res[2], 6);
// EXPECT_EQ(res[3], 5);
// EXPECT_EQ(res[4], 3);
}
| true |
c3abf22793f27611e299a5d380fe5f98d2ff39d2
|
C++
|
erniep/Potatoes
|
/Ernie/Communication/V1 Working Comm with Checksum in header/masterpi/fromPi/naviSyst2.h
|
UTF-8
| 39,526 | 2.640625 | 3 |
[] |
no_license
|
#include "virtualMap.h"
#include <time.h>
#include <queue>
#include <stack>
#include <deque>
#include <list>
#include <iostream>
#include <fstream>
#include <wiringPi.h>
#include <wiringSerial.h>
#include "loopingUltra.cpp"
#define LOG // Enables log file mode
#ifdef LOG
ofstream file("testLog.txt");
#endif
#define SERIAL // Enables serial comm between rpi and blue smurf for serial comm
/*January 24th, 2015:
-Fixed revisitCell function.
-Changed wallSensorsSim to Ernie's version.
-activeMap can now be changed with setActiveMap function
*/
/*February 27, 2015:
-This version of naviSyst will incorporate serial functions to instruct the tivaC to perform locomotion tasks
*/
/*March 2, 2015:
-Code includes ultrasonic sensors and serial
*/
/*
March 5, 2015
Log file functions added
*/
/*March 26, 2015
-Added resetCurrCell() and travCritPath()
-Added checkWall()
*/
/*March 29, 2015
-Added serialCalibrate()
*/
using namespace std;
class naviSyst{
private:
//[Internal variables]
virtualMap map2x2, map3x3, map4x4, map5x5, map6x6, map7x7;
virtualMap* activeMap; // Points at the map that the robot is using, since the map size changes for each round of the competition
int totalCells; // Total number of cells to visit for the current active map
int cellsVisited; // Number of unique cells currently visited
char currFace; // Current cardinal direction of front face
queue<int> critPath; // Cell# order of critical path
stack<int> travHist; // Travel history of robot. Used to retrace steps
stack<int> revisit; // Stack of cells that need to be revisited because there are still paths to explore there
queue<int> eggLocs; // Cell numbers of cells that contain Easter eggs
int Tiva_Handle;
//[Sensor variables]
bool wallReadings[4]; // Values returned by the wall sensors for the current cell. [0], [1], and [2] correspond to left, front, and right sensors. There is a fourth index in case a fourth sensor is added to the south of the robot. Since the wall sensors do not return values relative to the NESW convention used in this code, this function must use the robot's current face to translate these sensor readings into the NESW convention.
public:
//[Constructors]
naviSyst();
//[Debug variables]
int leftRotates;
int rightRotates;
int aboutFaceRotates;
//[Navigation get functions]
bool checkWall(char crdnlDir);
int getTotalCells();
int getCellsVisited();
char getCurrFace();
int getCurrNum();
unitCell* getCurrCell();
int peekCritPath();
int popCritPath();
int printCritPath(); // Also sets the critPath
int peekTravHist();
int popTravHist();
int printTravHist();
int peekRevisit();
int popRevisit();
bool isEmptyRevisit();
int printRevisit();
//[Navigation set functions]
void setCellsVisited(int n);
void incCellsVisited();
void setCurrFace(int crdnlDir);
void resetCurrCell();
void pushCritPath(int cellNum);
void pushTravHist(int cellNum);
void pushRevisit(int cellNum);
void pushEggLocs(int eggLoc);
void setActiveMap(string mapSize); // Set the active map of the robot
//[Movement functions]
int moveCell(int nextDir);
int moveCell(char nextDir); // Travel to an adjacent cell indicated by the cardinal direction passed as an argument. Checks against current face of robot, then updates the new face when the robot reaches the new cell. This movement is basic and does not use strafing.
void revisitCell(); // Travel to a cell that must be revisited. Intended to be called after the getNextPath function returns 'X'
int moveToFin(); // Travel to the end of the maze after all the cells have been visited.
void moveToCell(int returnCell);
void travCritPath();
int serialCalibrate(); // Code to initiate serial comm calibration with tiva
int forward(); // Move forward until the tivaC returns a flag saying that the robot is in a new cell.
int back();
int strafeLeft();
int strafeRight();
int faceLeft();
int faceRight();
int aboutFace();
void waitForAck();
//[Ultrasonic functions]
bool Tiva_init();
bool callUltras(); //Function to call the wall sensors. Updates the wallReadings array (Left, midddle, and right correspond to indexes 0, 1, and 2). This function assumes that the direction not covered by the wall sensors has no wall.
//[Serial comm functions]
int sendInstr(char instr);
//[Unit cell check functions]
void callRPiCam(); // Dummy function to call the raspberry pi camera.
int firstCellProtocol(); // Information retrieval function for the first cell, which has a few differences from other cells in the maze. This function must be called first to initialize the maze navigation algorithm. Assuming the robot is pointed north at the initial cell, this function ensures that the wall without a distance sensor is recorded as a wall in the virtual map. The wallScan() function assumes that the wall without a distance sensor is an open path, since it's assumed the robot entered the cell from there.
void scanWalls(); // Checks for walls in the current cell and update the virtual map to reflect the new information.
void checkFreePaths(); // Intended to be called after the scanWalls function has been used to detect and record walls in the current cell. This function will push onto the current cell's unexplPaths stack the free paths that the robot can travel to.
char getNextPath(); // Intended to be called after the checkFreePaths function. Determines the next direction to travel to, based on the unitCell's unexploredPaths stack. Returns a capital 'X' if there is no more unexplored paths to travel.
int getMapSize(); //Returns the size in number of cells of the current active map
//[Diagnostic functions]
void logMapInfo(ofstream & f);
void logTravHist(ofstream & f);
void logCritPath(ofstream & f);
};
naviSyst::naviSyst(){
leftRotates = 0;
rightRotates = 0;
aboutFaceRotates = 0;
map2x2.set2x2();
map3x3.set3x3();
map4x4.set4x4();
map6x6.set6x6();
map7x7.set7x7();
//activeMap = &map5x5;
//activeMap = &map6x6;
activeMap = &map7x7;
//activeMap = &map3x3;
totalCells = activeMap->getTotalCells();
cellsVisited = 0; // Number of unique cells visited
currFace = 'N'; // Default face of the robot is north
pushTravHist(getCurrNum()); // Add the beginning cell to the travel history. Necessary for critical path calculation and route decisions
}
bool naviSyst::checkWall(char crdnlDir){
unitCell* curr = getCurrCell();
return curr->getWall(crdnlDir);
}
int naviSyst::getTotalCells(){
return totalCells;
}
int naviSyst::getCellsVisited(){
return cellsVisited;
}
char naviSyst::getCurrFace(){
return currFace;
}
int naviSyst::getCurrNum(){
unitCell* c = activeMap->getCurr();
return c->getNum();
}
unitCell* naviSyst::getCurrCell(){
unitCell* c = activeMap->getCurr();
return c;
}
int naviSyst::printCritPath(){
queue<int> optPath;
list<int> routeToOpt; // Queue that must be optimized
stack<int> temp; // Stack used to restore the travelHist stack
temp.push(popTravHist()); // Top of the travHist stack is the current node, so we don't want to include it in the optPath queue
// cout << "(naviSyst::printCritPath) Travel history: " << endl;
// printTravHist();
int travHistTop = peekTravHist();
while(travHist.empty() == false){ // Push the cells that lead to the destination onto the routeToOpt list
routeToOpt.push_back(travHist.top());
temp.push(travHist.top());
travHist.pop();
if(!travHist.empty()){
travHistTop = travHist.top();
}
}
while(!temp.empty()){ //Restore the travel history stack
pushTravHist(temp.top());
temp.pop();
}
//Begin Looping Route Elimination Algorithm (LREA) on the routeToOpt list
queue<int> routeToOptRev; //aka RTOR, used to check for loops against the top value of the CFL. I want to iterate through the routeToOpt list in reverse because I want the longest loop. (e.g., if the CFL contains 9 (top), 16, 17, 18, 17, 16 (bottom), then the longest loop is 16, 17, 18, 17, 16, not 16, 17, 16).
stack<int> checkForLoop; // aka CFL. This stack contains values that must be checked for loops (e.g., if the CFL contains 9 (top), 16, 17, 18, 17, 16 (bottom), then 16 is a cell where a loop begins)
queue<int> restoreRTOR; // Used to restore the RTOR so we can iterate through it again through each value of the CFL stack that needs to be checked.
int cfl; // Current top value of the CFL that is being checked to see if it is the start of a redundant loop.
//LREA Step 1: Initialize RTOR and CFL
while(routeToOpt.empty() == false){ // The RTOR list must contain the contents of routeToOpt in reverse. I know I could have just accessed the last element of routeToOpt to accomplish the same thing, but it's easier for me to handle this algorithm this way
routeToOptRev.push(routeToOpt.back());
checkForLoop.push(routeToOpt.back());
routeToOpt.pop_back();
}
checkForLoop.push(getCurrNum()); // Need to have the current occupied cell in the CFL stack because we want to check loops that may return to the current cell
// Continue the LREA until the checkForLoop stack is empty, i.e., all possible values loops have been checked
while(checkForLoop.empty() == false){
cfl = checkForLoop.top();
//LREA Step 2: Check front value of CFL against all values of RTOR
while(routeToOptRev.empty() == false){
//LREA Step 3: If the current front value in the RTOR does not match cfl, then store the non-matching value in the restoreRTOR stack
if(cfl != routeToOptRev.front()){
restoreRTOR.push(routeToOptRev.front());
routeToOptRev.pop();
}
//LREA Step 4a: If the current front value in the RTOR matches cfl, then save the value onto the optPath
else if(cfl == routeToOptRev.front()){
optPath.push(cfl);
//LREA Step 4b: If the RTOR is empty after the matching cfl value, then no loop actually exists. Must verify that a loop actually exists to get rid of it.
routeToOptRev.pop();
if(routeToOptRev.empty() == false){
//LREA Step 4c: If the RTOR is not empty after the matching cfl value, then discard the rest of the contents, since the remaining values in the RTOR are the redundant loop.
while(routeToOptRev.empty() == false){
routeToOptRev.pop();
}
//LREA Step 4d: Since a loop is found, the CFL must be popped to omit iterating through the loop. Pop the CFL stack until the top value is repeated. Pop once more so the value right after the repeated one will be checked during the next iteration of the LREA.
checkForLoop.pop();
while(checkForLoop.top() != cfl){
checkForLoop.pop();
}
}
}
}
//LREA Step 4e: Restore the RTOR
while(restoreRTOR.empty() == false){
routeToOptRev.push(restoreRTOR.front());
restoreRTOR.pop();
}
//LREA Step 5: Pop the checkForLoop stack to ready the next value to be checked
checkForLoop.pop();
}
//Print out critical path
if(optPath.front() != activeMap->getFin()->getNum()){ // If the rear of the critical path is not the ending cell, add the ending cell
queue<int> tempOpt;
while(optPath.empty() == false){
tempOpt.push(optPath.front());
optPath.pop();
}
optPath.push(activeMap->getFin()->getNum());
while(tempOpt.empty() == false){
optPath.push(tempOpt.front());
tempOpt.pop();
}
}
critPath = optPath;
cout << "(printCritPath)" << endl;
while(optPath.empty() == false){
cout << optPath.front() << " ";
optPath.pop();
}
cout << endl;
return 0;
}
int naviSyst::peekTravHist(){
int p = travHist.top();
return p;
}
int naviSyst::popTravHist(){
int t = travHist.top();
travHist.pop();
return t;
}
int naviSyst::printTravHist(){
int moves = 0;
stack<int> temp = travHist;
cout << "(printTravHist) Stack top: " << endl;
while(!temp.empty()){
cout << temp.top() << " ";
temp.pop();
moves++;
}
cout << "Total moves: " << moves << endl;
cout << endl;
return 0;
}
int naviSyst::peekRevisit(){
int t = revisit.top();
return t;
}
int naviSyst::popRevisit(){
int t = revisit.top();
revisit.pop();
return t;
}
bool naviSyst::isEmptyRevisit(){
bool t = revisit.empty();
return t;
}
int naviSyst::printRevisit(){
stack<int> temp = revisit;
cout << "(printRevisit) Stack top: ";
while(!temp.empty()){
cout << temp.top() << " ";
temp.pop();
}
cout << endl;
return 0;
}
void naviSyst::setCellsVisited(int n){
cellsVisited = n;
}
void naviSyst::incCellsVisited(){
cellsVisited++;
}
void naviSyst::setCurrFace(int crdnlDir){
currFace = crdnlDir;
}
void naviSyst::resetCurrCell(){
activeMap->setCurr(activeMap->getStart());
}
void naviSyst::pushCritPath(int cellNum){
critPath.push(cellNum);
}
void naviSyst::pushTravHist(int cellNum){
travHist.push(cellNum);
}
void naviSyst::setActiveMap(string mapSize){
if(strcmp(&mapSize[0], "6x6") == 0){
activeMap = &map6x6;
}
else if(strcmp(&mapSize[0], "7x7") == 0){
activeMap = &map7x7;
}
else{
activeMap = &map5x5;
}
}
void naviSyst::pushRevisit(int cellNum){
revisit.push(cellNum);
}
int naviSyst::moveCell(int nextDir){
if (nextDir == 0){
moveCell('N');
}
else if(nextDir == 1){
moveCell('E');
}
else if(nextDir == 2){
moveCell('S');
}
else if(nextDir == 3){
moveCell('W');
}
else{
cout << "(naviSyst::moveCell) Invalid direction" << endl;
}
}
int naviSyst::moveCell(char nextDir){
unitCell* curr = activeMap->getCurr();
if(curr->getWall(nextDir) == true){
cout << "(naviSyst::moveCell) Cannot move in that direction, wall exists " << endl;
return 1;
}
else if (currFace == 'N'){
if(nextDir == 'N'){
forward();
curr = curr->getAdj('N');
currFace = 'N';
}
else if(nextDir == 'E'){
faceRight();
rightRotates++;
forward();
curr = curr->getAdj('E');
currFace = 'E';
}
else if(nextDir == 'S'){
aboutFace();
aboutFaceRotates++;
forward();
curr = curr->getAdj('S');
currFace = 'S';
}
else if(nextDir == 'W'){
faceLeft();
leftRotates++;
forward();
curr = curr->getAdj('W');
currFace = 'W';
}
}
else if (currFace == 'E'){
if(nextDir == 'N'){
faceLeft();
leftRotates++;
forward();
curr = curr->getAdj('N');
currFace = 'N';
}
else if(nextDir == 'E'){
forward();
curr = curr->getAdj('E');
currFace = 'E';
}
else if(nextDir == 'S'){
faceRight();
rightRotates++;
forward();
curr = curr->getAdj('S');
currFace = 'S';
}
else if(nextDir == 'W'){
aboutFace();
aboutFaceRotates++;
forward();
curr = curr->getAdj('W');
currFace = 'W';
}
}
else if (currFace == 'S'){
if(nextDir == 'N'){
aboutFace();
aboutFaceRotates++;
forward();
curr = curr->getAdj('N');
currFace = 'N';
}
else if(nextDir == 'E'){
faceLeft();
leftRotates++;
forward();
curr = curr->getAdj('E');
currFace = 'E';
}
else if(nextDir == 'S'){
forward();
curr = curr->getAdj('S');
currFace = 'S';
}
else if(nextDir == 'W'){
faceRight();
rightRotates++;
forward();
curr = curr->getAdj('W');
currFace = 'W';
}
}
else if (currFace == 'W'){
if(nextDir == 'N'){
faceRight();
rightRotates++;
forward();
curr = curr->getAdj('N');
currFace = 'N';
}
else if(nextDir == 'E'){
aboutFace();
aboutFaceRotates++;
forward();
curr = curr->getAdj('E');
currFace = 'E';
}
else if(nextDir == 'S'){
faceLeft();
leftRotates++;
forward();
curr = curr->getAdj('S');
currFace = 'S';
}
else if(nextDir == 'W'){
forward();
curr = curr->getAdj('W');
currFace = 'W';
}
}
else{
cout << "(moveCell) Invalid face" << endl;
return 1;
}
pushTravHist(curr->getNum()); // Record the new cell travelled to
activeMap->setCurr(curr); // Set the current position on the active map
#ifdef LOG
logMapInfo(file);
#endif
return 0;
}
void naviSyst::revisitCell(){
queue<int> revisitRoute; // Queue used to travel to the cell that must be revisited
list<int> routeToOpt; // Queue that must be optimized
stack<int> temp; // Stack used to restore the travelHist stack
unitCell* curr = activeMap->getCurr();
int dest = popRevisit(); // Indicate the cell that must be revisited
cout << "(revisitCell) Destination is cell " << dest << endl;
temp.push(popTravHist()); // Top of the travHist stack is the current node, so we don't want to include it in the revisitRoute queue
// cout << "(revisitCell) Travel history: " << endl;
// printTravHist();
int travHistTop = peekTravHist();
while((!travHist.empty())&&(travHistTop != dest)){ // Push the cells that lead to the destination onto the routeToOpt list
routeToOpt.push_back(travHist.top());
temp.push(travHist.top());
travHist.pop();
travHistTop = travHist.top();
}
routeToOpt.push_back(peekTravHist()); // Last value to enqueue onto the revisitRoute queue should be the destination
temp.push(popTravHist());
while(!temp.empty()){ //Restore the travel history stack
pushTravHist(temp.top());
temp.pop();
}
//Begin Looping Route Elimination Algorithm (LREA) on the routeToOpt list
queue<int> routeToOptRev; //aka RTOR, used to check for loops against the top value of the CFL. I want to iterate through the routeToOpt list in reverse because I want the longest loop. (e.g., if the CFL contains 9 (top), 16, 17, 18, 17, 16 (bottom), then the longest loop is 16, 17, 18, 17, 16, not 16, 17, 16).
stack<int> checkForLoop; // aka CFL. This stack contains values that must be checked for loops (e.g., if the CFL contains 9 (top), 16, 17, 18, 17, 16 (bottom), then 16 is a cell where a loop begins)
queue<int> restoreRTOR; // Used to restore the RTOR so we can iterate through it again through each value of the CFL stack that needs to be checked.
int cfl; // Current top value of the CFL that is being checked to see if it is the start of a redundant loop.
//LREA Step 1: Initialize RTOR and CFL
while(routeToOpt.empty() == false){ // The RTOR list must contain the contents of routeToOpt in reverse. I know I could have just accessed the last element of routeToOpt to accomplish the same thing, but it's easier for me to handle this algorithm this way
routeToOptRev.push(routeToOpt.back());
checkForLoop.push(routeToOpt.back());
routeToOpt.pop_back();
}
checkForLoop.push(getCurrNum()); // Need to have the current occupied cell in the CFL stack because we want to check loops that may return to the current cell
// Continue the LREA until the checkForLoop stack is empty, i.e., all possible values loops have been checked
while(checkForLoop.empty() == false){
cfl = checkForLoop.top();
//LREA Step 2: Check front value of CFL against all values of RTOR
while(routeToOptRev.empty() == false){
//LREA Step 3: If the current front value in the RTOR does not match cfl, then store the non-matching value in the restoreRTOR stack
if(cfl != routeToOptRev.front()){
restoreRTOR.push(routeToOptRev.front());
routeToOptRev.pop();
}
//LREA Step 4a: If the current front value in the RTOR matches cfl, then save the value onto the revisitRoute
else if(cfl == routeToOptRev.front()){
revisitRoute.push(cfl);
//LREA Step 4b: If the RTOR is empty after the matching cfl value, then no loop actually exists. Must verify that a loop actually exists to get rid of it.
routeToOptRev.pop();
if(routeToOptRev.empty() == false){
//LREA Step 4c: If the RTOR is not empty after the matching cfl value, then discard the rest of the contents, since the remaining values in the RTOR are the redundant loop.
while(routeToOptRev.empty() == false){
routeToOptRev.pop();
}
//LREA Step 4d: Since a loop is found, the CFL must be popped to omit iterating through the loop. Pop the CFL stack until the top value is repeated. Pop once more so the value right after the repeated one will be checked during the next iteration of the LREA.
checkForLoop.pop();
while(checkForLoop.top() != cfl){
checkForLoop.pop();
}
}
}
}
//LREA Step 4e: Restore the RTOR
while(restoreRTOR.empty() == false){
routeToOptRev.push(restoreRTOR.front());
restoreRTOR.pop();
}
//LREA Step 5: Pop the checkForLoop stack to ready the next value to be checked
checkForLoop.pop();
}
while(!revisitRoute.empty()){ // Begin algorithm to travel back to cell
cout << "(revisitCell) Travelling to cell " << revisitRoute.front() << " from cell " << getCurrNum() << endl;
if((curr->getNum() == revisitRoute.front())){ // If the next cell to travel to is already the current cell, get the next cell in the revisit route
revisitRoute.pop();
}
else{
for(int i = 0; i < 4; i++){
if(curr->getAdj(i) == NULL){ //If the adjacent cell is non-existent (i.e., the current cell being reviewed is on the outer part of the map)
continue;
}
else if((curr->getAdj(i))->getNum() == revisitRoute.front()){ // If the adjacent cell to the current cell matches the next cell on the revisitRoute queue, travel to it.
moveCell(i);
cout << "(revisitCell) Current cell: " <<getCurrNum() << endl;
revisitRoute.pop();
curr = curr->getAdj(i); // Update the new current cell
break;
}
}
}
}
}
int naviSyst::moveToFin(){
queue<int> revisitRoute; // Queue used to travel to the cell that must be revisited
list<int> routeToOpt; // Queue that must be optimized
stack<int> temp; // Stack used to restore the travelHist stack
unitCell* curr = activeMap->getCurr();
//If the current cell is already the ending cell, then exit this function.
if(curr->getNum() == activeMap->getFin()->getNum()){
return 1;
}
int dest = activeMap->getFin()->getNum(); // Indicate the cell that must be revisited
temp.push(popTravHist()); // Top of the travHist stack is the current node, so we don't want to include it in the revisitRoute queue
// cout << "(naviSyst::revisitCell) Travel history: " << endl;
// printTravHist();
int travHistTop = peekTravHist();
while((!travHist.empty())&&(travHistTop != dest)){ // Push the cells that lead to the destination onto the routeToOpt list
routeToOpt.push_back(travHist.top());
temp.push(travHist.top());
travHist.pop();
travHistTop = travHist.top();
}
routeToOpt.push_back(peekTravHist()); // Last value to enqueue onto the revisitRoute queue should be the destination
temp.push(popTravHist());
while(!temp.empty()){ //Restore the travel history stack
pushTravHist(temp.top());
temp.pop();
}
//Begin Looping Route Elimination Algorithm (LREA) on the routeToOpt list
queue<int> routeToOptRev; //aka RTOR, used to check for loops against the top value of the CFL. I want to iterate through the routeToOpt list in reverse because I want the longest loop. (e.g., if the CFL contains 9 (top), 16, 17, 18, 17, 16 (bottom), then the longest loop is 16, 17, 18, 17, 16, not 16, 17, 16).
stack<int> checkForLoop; // aka CFL. This stack contains values that must be checked for loops (e.g., if the CFL contains 9 (top), 16, 17, 18, 17, 16 (bottom), then 16 is a cell where a loop begins)
queue<int> restoreRTOR; // Used to restore the RTOR so we can iterate through it again through each value of the CFL stack that needs to be checked.
int cfl; // Current top value of the CFL that is being checked to see if it is the start of a redundant loop.
//LREA Step 1: Initialize RTOR and CFL
while(routeToOpt.empty() == false){ // The RTOR list must contain the contents of routeToOpt in reverse. I know I could have just accessed the last element of routeToOpt to accomplish the same thing, but it's easier for me to handle this algorithm this way
routeToOptRev.push(routeToOpt.back());
checkForLoop.push(routeToOpt.back());
routeToOpt.pop_back();
}
checkForLoop.push(getCurrNum()); // Need to have the current occupied cell in the CFL stack because we want to check loops that may return to the current cell
// Continue the LREA until the checkForLoop stack is empty, i.e., all possible values loops have been checked
while(checkForLoop.empty() == false){
cfl = checkForLoop.top();
//LREA Step 2: Check front value of CFL against all values of RTOR
while(routeToOptRev.empty() == false){
//LREA Step 3: If the current front value in the RTOR does not match cfl, then store the non-matching value in the restoreRTOR stack
if(cfl != routeToOptRev.front()){
restoreRTOR.push(routeToOptRev.front());
routeToOptRev.pop();
}
//LREA Step 4a: If the current front value in the RTOR matches cfl, then save the value onto the revisitRoute
else if(cfl == routeToOptRev.front()){
revisitRoute.push(cfl);
//LREA Step 4b: If the RTOR is empty after the matching cfl value, then no loop actually exists. Must verify that a loop actually exists to get rid of it.
routeToOptRev.pop();
if(routeToOptRev.empty() == false){
//LREA Step 4c: If the RTOR is not empty after the matching cfl value, then discard the rest of the contents, since the remaining values in the RTOR are the redundant loop.
while(routeToOptRev.empty() == false){
routeToOptRev.pop();
}
//LREA Step 4d: Since a loop is found, the CFL must be popped to omit iterating through the loop. Pop the CFL stack until the top value is repeated. Pop once more so the value right after the repeated one will be checked during the next iteration of the LREA.
checkForLoop.pop();
while(checkForLoop.top() != cfl){
checkForLoop.pop();
}
}
}
}
//LREA Step 4e: Restore the RTOR
while(restoreRTOR.empty() == false){
routeToOptRev.push(restoreRTOR.front());
restoreRTOR.pop();
}
//LREA Step 5: Pop the checkForLoop stack to ready the next value to be checked
checkForLoop.pop();
}
while(!revisitRoute.empty()){ // Begin algorithm to travel back to cell
// cout << "(naviSyst::revisitCell) Travelling to cell " << revisitRoute.front() << " from cell " << getCurrNum() << endl;
if((curr->getNum() == revisitRoute.front())){ // If the next cell to travel to is already the current cell, get the next cell in the revisit route
revisitRoute.pop();
}
else{
for(int i = 0; i < 4; i++){
if(curr->getAdj(i) == NULL){ //If the adjacent cell is non-existent (i.e., the current cell being reviewed is on the outer part of the map)
continue;
}
else if((curr->getAdj(i))->getNum() == revisitRoute.front()){ // If the adjacent cell to the current cell matches the next cell on the revisitRoute queue, travel to it.
moveCell(i);
cout << "(moveToFin) Current cell: " <<getCurrNum() << endl;
revisitRoute.pop();
curr = curr->getAdj(i); // Update the new current cell
break;
}
}
}
}
return 0;
}
void naviSyst::moveToCell(int returnCell){
int endCellNum = returnCell; //Get the cell number of the ending cell
stack<int> travHistCopy = travHist;
deque<int> routeToFin; // Will contain the route to the ending cell from whatever cell the robot is currently in
unitCell* currCopy = getCurrCell(); // unitCell pointer used to plan out the direct route to the ending cell
unitCell* curr = activeMap->getCurr();
travHistCopy.pop(); // Remove the cell that the robot is currently in
while((travHistCopy.top() != endCellNum)&&(!travHistCopy.empty())){
unitCell* t = activeMap->getCell(travHistCopy.top()); // Get the address of the cell that is next on the top of the travHistCopy stack
//cout << "(naviSyst::moveToFin) Checking if cell " << t->getNum() << " is a dead end" << endl;
if(t->getNumWalls() >= 3){ // If that cell has more than 3 walls, then it is a dead end and the robot should not travel there on the way back to the cell
travHistCopy.pop();
continue;
}
else if((!routeToFin.empty())&&(t->getNum() == routeToFin.back())){ // If the cell being considered is the most recent cell added to the routeToFin queue, do not add it again
travHistCopy.pop();
continue;
}
else{
routeToFin.push_back(t->getNum());
travHistCopy.pop();
}
}
//Determine quickest path to destination
int rtf[100]; // Route to fin array for checking the shortest path to the destination
deque<int> rtfCopy = routeToFin;
int routeSteps = 0;
for(int i = 0; rtfCopy.empty() == false; i++){
rtf[i] = rtfCopy.front();
rtfCopy.pop_front();
routeSteps++;
}
rtfCopy.clear();
if(routeSteps > 1){
for(int k = routeSteps; k > 0; k--){
for(int i = 0; i < routeSteps; i++){
if(rtf[k] == rtf[i]){
for(int j = 0; j < i; j++){
rtfCopy.push_back(rtf[j]);
}
break;
}
}
}
}
routeToFin = rtfCopy;
routeToFin.push_back(endCellNum); // Push the ending cell onto the routeToFin queue because the previous while loop does not do that
// cout << "(naviSyst::moveToFin) travHist: ";
// printTravHist();
// queue<int> rtf = routeToFin;
// cout << "(naviSyst::moveToFin) routeToFin front: ";
// while(!rtf.empty()){
// cout << rtf.front() << " ";
// rtf.pop();
// }
// cout << endl;
while(!routeToFin.empty()){ // Travel to the cell that must be revisited
// cout << "(naviSyst::moveToFin) Travelling to cell " << routeToFin.front() << " from cell " << getCurrNum() << endl;
for(int i = 0; i < 4; i++){
if((curr->getAdj(i))->getNum() == routeToFin.front()){ // If the adjacent cell to the current cell matches the next cell on the revisitRoute queue, travel to it.
moveCell(i);
routeToFin.pop_front();
curr = curr->getAdj(i); // Update the new current cell
break;
}
}
}
}
void naviSyst::travCritPath(){
queue<int> temp;
stack<int> path;
unitCell* curr = activeMap->getCurr();
while(!critPath.empty()){ //Create path stack and temp queue to preserve stack
temp.push(critPath.front());
path.push(critPath.front());
critPath.pop();
}
int nextCell;
while(!path.empty()){
if(curr->getNum() == path.top()){ // If the next cell to travel to is already the current cell, ignore it and get the next cell in the critical path
path.pop();
}
else{
for(int i = 0; i < 4; i++){
if(curr->getAdj(i) == NULL){ // If the adjacent cell is non-existent, ignore it
continue;
}
else if((curr->getAdj(i))->getNum() == path.top()){
moveCell(i);
cout << "(travCritPath) Current cell: " << getCurrNum() << endl;
path.pop();
curr = curr->getAdj(i);
break;
}
}
}
}
}
int naviSyst::serialCalibrate(){
#ifdef SERIAL
sendInstr('j');
#endif
}
int naviSyst::forward(){
#ifdef SERIAL
sendInstr('w');
#endif
#ifndef SERIAL
cout << "W - Move forward" << endl;
waitForAck();
#endif
return 0;
}
int naviSyst::back(){
#ifdef SERIAL
sendInstr('s');
#endif
#ifndef SERIAL
cout << "S - Move backward" << endl;
waitForAck();
#endif
return 0;
}
int naviSyst::strafeLeft(){
#ifdef SERIAL
sendInstr('a');
#endif
#ifndef SERIAL
cout << "A - Strafe left" << endl;
waitForAck();
#endif
return 0;
}
int naviSyst::strafeRight(){
#ifdef SERIAL
sendInstr('d');
#endif
#ifndef SERIAL
cout << "D - Strafe right" << endl;
waitForAck();
#endif
return 0;
}
int naviSyst::faceLeft(){
#ifdef SERIAL
sendInstr('q');
#endif
#ifndef SERIAL
cout << "Q - Face left" << endl;
waitForAck();
#endif
return 0;
}
int naviSyst::faceRight(){
#ifdef SERIAL
sendInstr('e');
#endif
#ifndef SERIAL
cout << "E - Face right" << endl;
waitForAck();
#endif
return 0;
}
int naviSyst::aboutFace(){
#ifdef SERIAL
sendInstr('r');
#endif
#ifndef SERIAL
cout << "R - About face" << endl;
waitForAck();
#endif
return 0;
}
void naviSyst::waitForAck(){
char response;
while(1){
scanf(" %c", &response); //Don't use getchar(), the 'a' gets left in cin and is counted again for some reason so it skips some waitForAck commands
if((response == 'a')||(response == 's')||(response == 'z')||(response == 'x')||(response == 'q')||(response == 'w')){
break;
}
}
}
bool naviSyst::callUltras(){ //Calls the ultrasonic distance sensors and modifies the wallReadings array to reflect the readings. Left, midddle, and right correspond to indexes 0, 1, and 2
wallReadings[0] = false;
wallReadings[1] = false;
wallReadings[2] = false;
cout << "(naviSyst.callUltras) 1: ";
if (getUltra(0)) wallReadings[0] = true;
cout << "(naviSyst.callUltras) 2: ";
if (getUltra(1)) wallReadings[1] = true;
cout << "(naviSyst.callUltras) 3: ";
if (getUltra(2)) wallReadings[2] = true;
cout << "Walls: " << wallReadings[0] << wallReadings[1] << wallReadings[2] << endl;
}
bool naviSyst::Tiva_init() {
Tiva_Handle = serialOpen("/dev/ttyAMA0", 9600);
return true;
}
int naviSyst::sendInstr(char instr){
char response;
serialFlush(Tiva_Handle);
serialPutchar(Tiva_Handle, ' ');
while(1) {
serialFlush(Tiva_Handle);
serialPutchar(Tiva_Handle, instr);
response = serialGetchar(Tiva_Handle);
cout << "(naviSyst2.sendInstr) Char from Tiva: " << (int) response << endl;
if (response == '~') break;
}
return 0;
}
int naviSyst::firstCellProtocol(){
unitCell* c = activeMap->getCurr();
scanWalls();
c->setWall('N', wallReadings[1]);
c->setWall('E', wallReadings[2]);
c->setWall('W', wallReadings[0]);
c->setWall('S', true);
cellsVisited++; // Count the initial cell as a unique cell
}
void naviSyst::scanWalls(){
callUltras();
unitCell* c = activeMap->getCurr();
//Update the current cell's wall array using the wall sensor readings relative to the current direction the robot is facing.
//This is function assumes that the robot has entered the cell from the direction of the robot that does not have any distance sensors, i.e., the robot's "south" side.
if(currFace == 'N'){ //If the robot is facing north:
c->setWall('N', wallReadings[1]); // Map front sensor reading to the north wall of the current cell.
c->setWall('E', wallReadings[2]); // Map right sensor reading to the east wall of the current cell.
c->setWall('W', wallReadings[0]); // Map left sensor reading to the west wall of the current cell.
c->setWall('S', false);
}
else if(currFace == 'E'){
c->setWall('E', wallReadings[1]);
c->setWall('S', wallReadings[2]);
c->setWall('N', wallReadings[0]);
c->setWall('W', false);
}
else if(currFace == 'S'){
c->setWall('S', wallReadings[1]);
c->setWall('W', wallReadings[2]);
c->setWall('E', wallReadings[0]);
c->setWall('N', false);
}
else if(currFace == 'W'){
c->setWall('W', wallReadings[1]);
c->setWall('N', wallReadings[2]);
c->setWall('S', wallReadings[0]);
c->setWall('E', false);
}
else{
cout << "(naviSyst) Current face of the robot is undefined" << endl;
}
//Make sure that adjacent cells have matching wall readings
unitCell* northAdj = activeMap->getCell('N');
unitCell* southAdj = activeMap->getCell('S');
unitCell* eastAdj = activeMap->getCell('E');
unitCell* westAdj = activeMap->getCell('W');
if(northAdj != NULL){
northAdj->setWall('S', c->getWall('N'));
}
if(southAdj != NULL){
southAdj->setWall('N', c->getWall('S'));
}
if(eastAdj != NULL){
eastAdj->setWall('W', c->getWall('E'));
}
if(westAdj != NULL){
westAdj->setWall('E', c->getWall('W'));
}
c->setWallScan(true);
}
void naviSyst::checkFreePaths(){
unitCell* c = activeMap->getCurr();
int totalFreePaths = 0;
// The order that the walls are checked matter: I want to keep the E>N>W>S priority of choosing the next cell to visit. Also want to ensure that an adjacent cell exists
if((c->getAdj('S') != NULL)&&(c->getWall('S') == false)) {
//cout << "(cFR) S" << endl;
if((c->getAdj('S'))->getWallScan() == false){ //I don't want the robot to revisit a cell it has already processed unless it's currently backtracking to an unvisited cell.
c->pushUnexplPaths('S');
totalFreePaths++;
}
}
if((c->getAdj('W') != NULL)&&(c->getWall('W') == false)) {
//cout << "(cFR) W" << endl;
if((c->getAdj('W'))->getWallScan() == false){
c->pushUnexplPaths('W');
totalFreePaths++;
}
}
if((c->getAdj('N') != NULL)&&(c->getWall('N') == false)) {
//cout << "(cFR) N" << endl;
if((c->getAdj('N'))->getWallScan() == false){
c->pushUnexplPaths('N');
totalFreePaths++;
}
}
if((c->getAdj('E') != NULL)&&(c->getWall('E') == false)) {
//cout << "(cFR) E" << endl;
if((c->getAdj('E'))->getWallScan() == false){
c->pushUnexplPaths('E');
totalFreePaths++;
}
}
if(totalFreePaths > 1){ // If there is more than one free path from the current cell, push the cell onto the revisit stack because the robot must revisit the cell later
pushRevisit(c->getNum());
}
// cout << "(naviSyst::checkFreePaths) Total free paths from cell " << getCurrNum() << ": " << totalFreePaths << endl;
c->setPathScan(true);
}
char naviSyst::getNextPath(){
unitCell* c = activeMap->getCurr();
char nextPath = 'X';
if(!(c->isUnexplPathsEmpty())){ // If there are unexplored paths, take the next unexplored path.
nextPath = c->popUnexplPaths();
}
return nextPath;
}
int naviSyst::getMapSize(){
int length;
length = activeMap->getLength();
if (length == 5){
return 26;
}
else if(length == 6){
return 37;
}
else{
return length*length;
}
}
void naviSyst::logMapInfo(ofstream & f){
#ifdef LOG
string NSwall = "--";
string EWwall = "|";
string NSfree = " ";
string EWfree = " ";
string NSunkn = "??";
string EWunkn = "?";
queue<string> topRow, leftRow, rightRow, botRow;
int l = 7; // max length of map
int aml = activeMap->getLength(); // length of active map
f << "Current cell: " << getCurrNum() << " / Current face:" << getCurrFace() << endl;
for(int i = 0; i <= l-1; i++){ // Row
while(!topRow.empty()){
topRow.pop();
}
while(!leftRow.empty()){
leftRow.pop();
}
while(!rightRow.empty()){
rightRow.pop();
}
while(!botRow.empty()){
botRow.pop();
}
for(int j = 1; j <= l; j++){ // Column
unitCell* c = activeMap->getCell((i*l)+ j);
if(c->getWallScan() == false){ //Cell has not been scanned for walls
topRow.push(NSunkn);
leftRow.push(EWunkn);
rightRow.push(EWunkn);
botRow.push(NSunkn);
}
else{
if(c->getWall('N') == false){
topRow.push(NSfree);
}
else {
topRow.push(NSwall);
}
if(c->getWall('E') == false){
rightRow.push(EWfree);
}
else {
rightRow.push(EWwall);
}
if(c->getWall('S') == false){
botRow.push(NSfree);
}
else {
botRow.push(NSwall);
}
if(c->getWall('W') == false){
leftRow.push(EWfree);
}
else {
leftRow.push(EWwall);
}
}
}
f << " ";
//Begin printing out column data for the row
for(int a = 1; a <= l; a++){
f << topRow.front() << " ";
topRow.pop();
}
f << endl;
for(int b = 1; b <= l; b++){
if((i*l)+ b < 10){
f << leftRow.front() << " " << (i*l)+ b << rightRow.front() << " ";
leftRow.pop();
rightRow.pop();
}
else{
f << leftRow.front() << (i*l)+ b << rightRow.front() << " ";
leftRow.pop();
rightRow.pop();
}
}
f << endl;
f << " ";
for(int c = 1; c <= l; c++){
f << botRow.front() << " ";
botRow.pop();
}
f << endl;
}
f << endl;
#endif
}
void naviSyst::logTravHist(ofstream & f){
#ifdef LOG
stack<int> temp = travHist;
stack<int> tempFlip;
while(!temp.empty()){ //Flip the travel stack so the first cell printed is the starting cell
tempFlip.push(temp.top());
temp.pop();
}
f << "Travel history: " << endl;
while(!tempFlip.empty()){
f << tempFlip.top() << " -> ";
tempFlip.pop();
}
#endif
}
void naviSyst::logCritPath(ofstream & f){ // Use after the critical path has been found
#ifdef LOG
queue<int> temp = critPath;
cout << endl;
f << "Critical path: " << endl;
while(!temp.empty()){
f << temp.front() << " -> ";
temp.pop();
}
#endif
}
| true |
46d935f945d610f63bc74305a971732783625552
|
C++
|
OverHold1997/hello-world
|
/第三题/Complex.cpp
|
UTF-8
| 336 | 3.03125 | 3 |
[] |
no_license
|
#include "Complex.h"
Complex Complex::operator +(Complex &c)
{
return Complex(real+c.real,imag+c.imag);
}
Complex Complex::operator+(int &i)
{
return Complex(real+i,imag);
}
void Complex::display()
{
cout<<"("<<real<<","<<imag<<"i)"<<endl;
}
Complex operator+(int&i,Complex &c)
{
return Complex(i+c.real,c.imag);
}
| true |
0329d71664ae2c5bdd3a6b2204e17f36af6e59cf
|
C++
|
LucaValenti/Programmazione2
|
/EsercizioPoligoni1/ellisse.hpp
|
UTF-8
| 1,262 | 3.203125 | 3 |
[] |
no_license
|
#include<iostream>
#include<cmath>
#include<sstream>
#include"forma.hpp"
using namespace std;
class Ellisse: public Forma{
protected:
double x,y;
double r1,r2;
public:
Ellisse(double _x, double _y, double _r1, double _r2):
x(_x), y(_y), r1(_r1), r2(_r2){}
double perimetro(){
return 2*M_PI*sqrt((pow(r1,2.0)+pow(r2, 2.0))/2);
}
double area(){
return M_PI*r1*r2;
}
void setCenter(double _x, double _y){
x=_x;
y= _y;
}
void setSemiasseMaggiore(double _r1){
r1=_r1;
}
void setSemiasseMinore(double _r2){
r2=_r2;
}
double getX(){
return x;
}
double getY(){
return y;
}
double getSemiasseMaggiore(){
return r1;
}
double getSemiasseMinore(){
return r2;
}
string ToString(){
stringstream stream;
stream<< "Ellisse di centro("<<x<<","<<y<<") con semiassi("<<r1<<","<<r2<<")";
return stream.str();
}
void print(){
}
};
| true |
7b4e14d6c968f34f370cdeca100b9aaa5dd37b81
|
C++
|
JunJun0411/Algorithm
|
/algorithm/2493번 탑.cpp
|
UTF-8
| 444 | 2.59375 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <utility>
using namespace std;
#define INF 100000001
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
vector<pair <int, int> >vec2;
vec2.push_back(make_pair(INF, 0));
int N, M; cin >> N;
for (int i = 1; i <= N; i++) {
cin >> M;
while (vec2.back().first < M) {
vec2.pop_back();
}
cout << vec2.back().second << " ";
vec2.push_back(make_pair(M, i));
}
}
| true |
2c202b31b34b6780beb2ffae56df953353292bdc
|
C++
|
Kleinsche/cocos2d-x-Teach
|
/教程/NoOneDie/Classes/GameController.cpp
|
UTF-8
| 1,861 | 2.5625 | 3 |
[] |
no_license
|
//
// GameController.cpp
// NoOneDie
//
// Created by Kleinsche on 2017/7/7.
//
//
#include "GameController.hpp"
bool GameController::init(Layer* layer,float poitionY){
_layer = layer;
_positionY = poitionY;
visibleSize = Director::getInstance()->getVisibleSize();
//添加边框
edge = Edge::create();
edge->setPosition(Vec2(visibleSize.width/2, visibleSize.height/2 +poitionY));
// edge->setContentSize(visibleSize);
layer->addChild(edge);
//添加地板
auto floor = Sprite::create();
floor->setColor(Color3B(0, 0, 0));
floor->setTextureRect(Rect(0, 0, visibleSize.width, 3));
floor->setPosition(visibleSize.width/2, 1.5 +poitionY);
layer->addChild(floor);
//添加角色
hero = Hero::create();
hero->setPosition(Vec2(25, hero->getContentSize().height +poitionY));
layer->addChild(hero);
resetFrames();
return true;
}
GameController* GameController::creat(Layer* layer,float poitionY){
auto _ins = new GameController();
_ins->init(layer, poitionY);
_ins->autorelease();
return _ins;
}
void GameController::onupdate(){
currentFrameIndex++;
// CCLOG("%d %d",currentFrameIndex,nextFrameCounts);
if (currentFrameIndex >= nextFrameCounts) {
resetFrames();
addBlock();
}
}
void GameController::resetFrames(){
currentFrameIndex = 0;
nextFrameCounts = rand()%120 +60;
}
void GameController::addBlock(){
auto b = Block::create();
b->setPositionY(b->getContentSize().height/2 +_positionY);
_layer->addChild(b);
}
bool GameController::hitTestPoint(Vec2 vec){
CCLOG("hitTestPoint");
return !edge->getBoundingBox().containsPoint(vec);
}
void GameController::onTouched(){
CCLOG("onTouched");
hero->getPhysicsBody()->setVelocity(Vec2(0, 400));
}
| true |
e569e902150df0376f8deb6c9aff5b4219f8701a
|
C++
|
mixify/algorithm
|
/cpp/stair_step.cpp
|
UTF-8
| 1,142 | 2.859375 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <climits>
#include <vector>
#include <utility>
#include <set>
#include <map>
using namespace std;
int cache[302][2];
int climb(vector<int> stair, int n, int adjacent_count);
int main(int argc, char *argv[])
{
int stair_num;
cin>>stair_num;
vector<int> stair;
for (int i = 0; i < stair_num; ++i) {
int input;
cin>>input;
stair.push_back(input);
}
memset(cache, -1, sizeof(cache));
// for (int i = stair_num-1; i >= 0; --i) {
// printf("%d = %d\n", i,climb(stair, i, 0));
// }
printf("%d\n", climb(stair, stair_num-1, 0));
return 0;
}
int climb(vector<int> stair, int n, int jump_type)
{
if(n < 0)
return -1;
// int ret;
int &ret = cache[n][jump_type];
if(ret!=-1)
return ret;
int val = stair[n];
if(n == 0)
return ret = val;
if(jump_type == 1)
{
if(n==1)
return ret = val;
return ret = val + climb(stair, n-2, 0);
}
return ret = val + max(climb(stair, n-1, 1), climb(stair, n-2, 0));
}
| true |
38e78d525c5da8c1065bc2d133d52ef62be91b89
|
C++
|
DelusionsOfGrandeur/labs
|
/ввп5(2).cpp
|
WINDOWS-1251
| 759 | 3 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <math.h>
#include <locale.h>
int main()
{
setlocale(LC_ALL, "Russian");
int a, b, c, ac, bc, s;
printf(" a \n");
scanf("%d", &a);
printf(" b \n");
scanf("%d", &b);
printf(" c \n");
scanf("%d", &c);
ac = abs(a - c);
bc = abs(b - c);
s = ac + bc;
printf(" ac " "%d\n", ac);
printf(" bc " "%d\n", bc);
printf(" ac bc " "%d\n", s);
return 0;
}
| true |
27694099529502a149f55448fc46fcd1c4e2e718
|
C++
|
WickedDevice/ESP8266_AT_Client
|
/examples/set_mac/set_mac.ino
|
UTF-8
| 1,664 | 2.671875 | 3 |
[] |
no_license
|
#include <ESP8266_AT_Client.h>
int esp8266_enable_pin = 23; // Arduino digital the pin that is used to reset/enable the ESP8266 module
Stream * at_command_interface = &Serial1; // Serial1 is the 'stream' the AT command interface is on
ESP8266_AT_Client esp(esp8266_enable_pin, at_command_interface); // instantiate the client object
#define ESP8266_INPUT_BUFFER_SIZE (1500)
uint8_t input_buffer[ESP8266_INPUT_BUFFER_SIZE] = {0}; // sketch must instantiate a buffer to hold incoming data
// 1500 bytes is way overkill for MQTT, but if you have it, may as well
// make space for a whole TCP packet
void setup(void){
Serial.begin(115200); // debug console
Serial1.begin(115200); // AT command interface
//ESP8266_AT_Client::debugStream = &Serial;
esp.setInputBuffer(input_buffer, ESP8266_INPUT_BUFFER_SIZE); // connect the input buffer up
esp.reset(); // reset the module
Serial.print("Set Mode to Station...");
esp.setNetworkMode(1);
Serial.println("OK");
uint8_t mac[6] = {0x18,0x3f,0x7a,0x11,0xF3,0x29};
if(!esp.setMacAddress(mac)){
Serial.println("Unable to set MAC address!");
}
else{
char mac_str[18] = {0};
if(!esp.getMacAddress(&(mac_str[0]))){
Serial.println("Unable to get MAC address!");
}
else{
Serial.print("MAC Address set to: ");
Serial.println(mac_str);
}
}
}
void loop(void){
if(Serial1.available()){
Serial.write(Serial1.read());
}
if(Serial.available()){
Serial1.write(Serial.read());
}
}
| true |
491ebc48f50e0945a5baeeda17d7d363b81977bf
|
C++
|
lynch829/Gate
|
/source/geometry/include/GateWedgeComponent.hh
|
UTF-8
| 2,754 | 2.65625 | 3 |
[] |
no_license
|
/*----------------------
Copyright (C): OpenGATE Collaboration
This software is distributed under the terms
of the GNU Lesser General Public Licence (LGPL)
See GATE/LICENSE.txt for further details
----------------------*/
#ifndef GateWedgeComponent_h
#define GateWedgeComponent_h 1
#include "GateSystemComponent.hh"
class GateWedge;
/*! \class GateWedgeComponent
\brief A GateWedgeComponent is a subtype of GateSystemComponent
\brief It is meant to be connected to Wedge creators, such as crystals or detectors
- GateWedgeComponent - by rannou@informatica.usach.cl (2007)
- A GateWedgeComponent is derived from GateSystemComponent, and thus inherits all
the properties of system-components. In addition, it includes some methods
that are specific to Wedge-creator creators: CastToWedgeCreator(), GetWedgeCreator(),
GetWedgeLength()
- There is also a method IsValidAttachmentRequest(), that overloads the method from
the GateSystemComponent base-class: this overloading allows to check that the
creator is indeed connected to a Wedge creator
\sa GateSystemComponent, GateWedge
*/
class GateWedgeComponent : public GateSystemComponent
{
public:
/*! \brief Constructor
\param itsName: the name chosen for this system-component
\param itsMotherComponent: the mother of the component (0 if top of a tree)
\param itsSystem: the system to which the component belongs
*/
GateWedgeComponent(const G4String& itsName,
GateSystemComponent* itsMotherComponent,
GateVSystem* itsSystem);
//! Destructor
virtual ~GateWedgeComponent();
//! Method overloading the method IsValidAttachmentRequest() of the base-class GateSystemComponent
//! It tells whether an creator may be attached to this component
//! In addition to the test performed by the base-class' method, it also
//! checks that the creator is indeed connected to a Wedge creator
virtual G4bool IsValidAttachmentRequest(GateVVolume* anCreator) const;
//! Return the Wedge creator attached to our own creator
inline GateWedge* GetWedgeCreator() const
{ return GetWedgeCreator(GetCreator()); }
//! Return the length along an axis of the Wedge-creator attached to our creator
G4double GetWedgeLength(size_t axis) const;
//! Tool method: return the creator attached to an creator
static inline GateWedge* GetWedgeCreator(GateVVolume* anCreator)
{ return anCreator ? CastToWedgeCreator( anCreator->GetCreator() ) : 0 ; }
//! Tool method: try to cast a creator into a Wedge creator
static GateWedge* CastToWedgeCreator(GateVVolume* creator);
};
#endif
| true |
7981ac45c52ea78988dba6d3f599dee50531e4b7
|
C++
|
ip75/simplex
|
/main.cpp
|
UTF-8
| 2,170 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
#include <iostream>
#include <ctime>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/asio.hpp>
#include <boost/format.hpp>
#include <boost/filesystem.hpp>
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options.hpp>
using namespace std;
using namespace boost;
using namespace boost::filesystem;
namespace po = boost::program_options;
#include "udp_server.h"
int main(int argc, const char** argv) {
int file_size;
int16_t port;
path directory;
// Declare a group of options that will be
// allowed only on command line
po::options_description generic("Generic options");
generic.add_options()
("version,v", "print version string")
("help", "produce help message")
;
// Declare a group of options that will be
// allowed both on command line and in
// config file
po::options_description config("Configuration");
config.add_options()
("port", po::value<int16_t>(&port)->default_value(5000),
"port which receive UDP data")
("file-size,s", po::value<int>(&file_size)->default_value(1000), // memory pages
"size of file to store data in memory pages (1 page 64Kb - windows)")
("result-path,D",
po::value<string>()->implicit_value(current_path().generic_string()),
"path where to store received data files")
;
po::options_description cmdline_options;
cmdline_options.add(generic).add(config);
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, cmdline_options), vm);
po::notify(vm);
// --help option
if ( vm.count("help") )
{
std::cout << "HELP:" << std::endl
<< cmdline_options << std::endl;
return 1;
}
if (vm.count("result-path"))
{
directory = vm["result-path"].as<std::string>();
}
try
{
boost::asio::io_service io_service;
udp_server server(io_service, port, file_size, directory);
io_service.run();
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
| true |
d558e8c2277a18aebffa3e3ffdcc230e5335f2f3
|
C++
|
ammarhakim/gkeyll1
|
/slvrs/LcMomentsAtEdgesUpdater.cpp
|
UTF-8
| 17,000 | 2.5625 | 3 |
[] |
no_license
|
/**
* @file LcMomentsAtEdgesUpdater.cpp
*
* @brief Computes several parallel velocity moments of the distribution function at both edges.
* Used for 1D/1V SOL Problem (Adiabatic Electrons)
*/
// config stuff
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
// lucee includes
#include <LcMomentsAtEdgesUpdater.h>
#include <LcGlobals.h>
// loki includes
#include <loki/Singleton.h>
// std includes
#include <limits>
#include <vector>
namespace Lucee
{
const char *MomentsAtEdgesUpdater::id = "MomentsAtEdgesUpdater";
MomentsAtEdgesUpdater::MomentsAtEdgesUpdater()
{
}
void
MomentsAtEdgesUpdater::readInput(Lucee::LuaTable& tbl)
{
UpdaterIfc::readInput(tbl);
if (tbl.hasObject<Lucee::NodalFiniteElementIfc<2> >("basis"))
nodalBasis = &tbl.getObjectAsBase<Lucee::NodalFiniteElementIfc<2> >("basis");
else
throw Lucee::Except("MomentsAtEdgesUpdater::readInput: Must specify element to use using 'basis'");
}
void
MomentsAtEdgesUpdater::initialize()
{
UpdaterIfc::initialize();
unsigned numNodes = nodalBasis->getNumNodes();
// Figure out what nodes are on the right edge
int numEdgeQuadNodes = nodalBasis->getNumSurfGaussNodes();
Lucee::Matrix<double> interpEdgeMatrixLucee(numEdgeQuadNodes, numNodes);
Lucee::Matrix<double> gaussEdgeOrdinatesLucee(numEdgeQuadNodes, 3);
// Allocate Eigen matrices
Eigen::MatrixXd interpEdgeMatrix(numEdgeQuadNodes, numNodes);
gaussEdgeOrdinates = Eigen::MatrixXd(numEdgeQuadNodes, 3);
gaussEdgeWeights = std::vector<double>(numEdgeQuadNodes);
// Get the interpolation matrix for the right edge quadrature points.
nodalBasis->getSurfUpperGaussQuadData(0, interpEdgeMatrixLucee, gaussEdgeOrdinatesLucee,
gaussEdgeWeights);
rightEdgeNodeNums = std::vector<int>(nodalBasis->getNumSurfUpperNodes(0));
leftEdgeNodeNums = std::vector<int>(nodalBasis->getNumSurfLowerNodes(0));
nodalBasis->getSurfUpperNodeNums(0, rightEdgeNodeNums);
nodalBasis->getSurfLowerNodeNums(0, leftEdgeNodeNums);
// Copy matrices to eigen objects
copyLuceeToEigen(interpEdgeMatrixLucee, interpEdgeMatrix);
copyLuceeToEigen(gaussEdgeOrdinatesLucee, gaussEdgeOrdinates);
edgeNodeInterpMatrix = Eigen::MatrixXd(numEdgeQuadNodes, rightEdgeNodeNums.size());
// Create a lower dimension (1-D) interpolation matrix
for (int nodeIndex = 0; nodeIndex < numEdgeQuadNodes; nodeIndex++)
{
// At each quadrature node, copy basis function evaluations for
// those basis functions associated with the nodes on the (right) edge
for (int basisIndex = 0; basisIndex < rightEdgeNodeNums.size(); basisIndex++)
{
edgeNodeInterpMatrix(nodeIndex, basisIndex) = interpEdgeMatrix(nodeIndex,
rightEdgeNodeNums[basisIndex]);
}
}
// Derivative stuff
Lucee::Matrix<double> massMatrixLucee(numNodes, numNodes);
Eigen::MatrixXd massMatrix(numNodes, numNodes);
nodalBasis->getMassMatrix(massMatrixLucee);
copyLuceeToEigen(massMatrixLucee, massMatrix);
Lucee::Matrix<double> gradStiffMatrixLucee(numNodes, numNodes);
Eigen::MatrixXd gradStiffMatrix(numNodes, numNodes);
nodalBasis->getGradStiffnessMatrix(1, gradStiffMatrixLucee);
copyLuceeToEigen(gradStiffMatrixLucee, gradStiffMatrix);
derivativeMatrix = massMatrix.inverse()*gradStiffMatrix.transpose();
}
Lucee::UpdaterStatus
MomentsAtEdgesUpdater::update(double t)
{
const Lucee::StructuredGridBase<2>& grid
= this->getGrid<Lucee::StructuredGridBase<2> >();
// Distribution function
const Lucee::Field<2, double>& distfIn = this->getInp<Lucee::Field<2, double> >(0);
// Hamiltonian
const Lucee::Field<2, double>& hamilIn = this->getInp<Lucee::Field<2, double> >(1);
// Output velocity moments (0, 1, 2, 3) vs time
Lucee::DynVector<double>& velocityMoments = this->getOut<Lucee::DynVector<double> >(0);
Lucee::Region<2, int> globalRgn = grid.getGlobalRegion();
Lucee::ConstFieldPtr<double> sknPtr = distfIn.createConstPtr(); // for skin-cell
Lucee::ConstFieldPtr<double> gstPtr = distfIn.createConstPtr(); // for ghost-cell
Lucee::ConstFieldPtr<double> sknHamilPtr = hamilIn.createConstPtr(); // for skin-cell
Lucee::ConstFieldPtr<double> gstHamilPtr = hamilIn.createConstPtr(); // for ghost-cell
unsigned numNodes = nodalBasis->getNumNodes();
double mom0AlongRightEdge = 0.0;
double mom0AlongLeftEdge = 0.0;
double mom1AlongRightEdge = 0.0;
double mom1AlongLeftEdge = 0.0;
double mom2AlongRightEdge = 0.0;
double mom2AlongLeftEdge = 0.0;
double mom3AlongRightEdge = 0.0;
double mom3AlongLeftEdge = 0.0;
double cellCentroid[3];
int idx[2];
int ix = globalRgn.getUpper(0)-1; // right skin cell x index
// Integrate along skin cell (right edge)
for (int js = globalRgn.getUpper(1)-1; js >= 0; js--)
{
idx[0] = ix;
idx[1] = js;
grid.setIndex(idx);
grid.getCentroid(cellCentroid);
// Don't want skin cell contributions for v < 0.0 (upwinding)
if (cellCentroid[1] < 0.0)
break;
distfIn.setPtr(sknPtr, ix, js);
hamilIn.setPtr(sknHamilPtr, ix, js);
Eigen::VectorXd hamilAtNodes(numNodes);
for (int i = 0; i < numNodes; i++)
hamilAtNodes(i) = sknHamilPtr[i];
Eigen::VectorXd hamilDerivAtNodes = derivativeMatrix*hamilAtNodes;
// Copy nodes on right edge into a vector
Eigen::VectorXd edgeHamilDerivData(rightEdgeNodeNums.size());
Eigen::VectorXd edgeHamilData(rightEdgeNodeNums.size());
Eigen::VectorXd edgeData(rightEdgeNodeNums.size());
// Copy nodal values of hamiltonian, hamiltonian derivative, and dist f into a vector
for (int edgeNodeIndex = 0; edgeNodeIndex < edgeHamilData.rows(); edgeNodeIndex++)
{
edgeHamilData(edgeNodeIndex) = hamilAtNodes(rightEdgeNodeNums[edgeNodeIndex]);
edgeHamilDerivData(edgeNodeIndex) = hamilDerivAtNodes(rightEdgeNodeNums[edgeNodeIndex]);
edgeData(edgeNodeIndex) = sknPtr[rightEdgeNodeNums[edgeNodeIndex]];
}
// Interpolate nodal data to quadrature points on the edge
Eigen::VectorXd edgeHamilQuadData = edgeNodeInterpMatrix*edgeHamilData;
Eigen::VectorXd edgeHamilDerivQuadData = edgeNodeInterpMatrix*edgeHamilDerivData;
Eigen::VectorXd edgeQuadData = edgeNodeInterpMatrix*edgeData;
// Integrate v*f over entire cell using gaussian quadrature
double mom0InEntireCell = 0.0;
double mom1InEntireCell = 0.0;
double mom2InEntireCell = 0.0;
double mom3InEntireCell = 0.0;
for (int quadNodeIndex = 0; quadNodeIndex < edgeQuadData.rows(); quadNodeIndex++)
{
double physicalV = cellCentroid[1] + gaussEdgeOrdinates(quadNodeIndex,1)*grid.getDx(1)/2.0;
mom0InEntireCell += gaussEdgeWeights[quadNodeIndex]*edgeQuadData(quadNodeIndex);
mom1InEntireCell += gaussEdgeWeights[quadNodeIndex]*physicalV*edgeQuadData(quadNodeIndex);
mom2InEntireCell += gaussEdgeWeights[quadNodeIndex]*2*edgeHamilQuadData[quadNodeIndex]*
edgeQuadData[quadNodeIndex];
mom3InEntireCell += gaussEdgeWeights[quadNodeIndex]*2*edgeHamilQuadData[quadNodeIndex]*
edgeHamilDerivQuadData[quadNodeIndex]*edgeQuadData[quadNodeIndex];
}
mom0AlongRightEdge += mom0InEntireCell;
mom1AlongRightEdge += mom1InEntireCell;
mom2AlongRightEdge += mom2InEntireCell;
mom3AlongRightEdge += mom3InEntireCell;
}
// Integrate along ghost cell (right edge)
for (int jg = globalRgn.getLower(1); jg < globalRgn.getUpper(1); jg++)
{
idx[0] = ix+1;
idx[1] = jg;
grid.setIndex(idx);
grid.getCentroid(cellCentroid);
// Don't want ghost cell contributions for v > 0.0 (upwinding)
if (cellCentroid[1] > 0.0)
break;
distfIn.setPtr(gstPtr, ix+1, jg);
hamilIn.setPtr(gstHamilPtr, ix, jg);
Eigen::VectorXd hamilAtNodes(numNodes);
for (int i = 0; i < numNodes; i++)
hamilAtNodes(i) = gstHamilPtr[i];
Eigen::VectorXd hamilDerivAtNodes = derivativeMatrix*hamilAtNodes;
// Copy nodes on left edge into a vector
Eigen::VectorXd edgeHamilDerivData(leftEdgeNodeNums.size());
Eigen::VectorXd edgeHamilData(leftEdgeNodeNums.size());
Eigen::VectorXd edgeData(leftEdgeNodeNums.size());
// Copy nodal values of hamiltonian, hamiltonian derivative, and dist f into a vector
for (int edgeNodeIndex = 0; edgeNodeIndex < edgeHamilData.rows(); edgeNodeIndex++)
{
edgeHamilData(edgeNodeIndex) = hamilAtNodes(rightEdgeNodeNums[edgeNodeIndex]);
edgeHamilDerivData(edgeNodeIndex) = hamilDerivAtNodes(rightEdgeNodeNums[edgeNodeIndex]);
edgeData(edgeNodeIndex) = gstPtr[leftEdgeNodeNums[edgeNodeIndex]];
}
// Interpolate nodal data to quadrature points on the edge
Eigen::VectorXd edgeHamilQuadData = edgeNodeInterpMatrix*edgeHamilData;
Eigen::VectorXd edgeHamilDerivQuadData = edgeNodeInterpMatrix*edgeHamilDerivData;
Eigen::VectorXd edgeQuadData = edgeNodeInterpMatrix*edgeData;
// Integrate v*f over entire cell using gaussian quadrature
double mom0InEntireCell = 0.0;
double mom1InEntireCell = 0.0;
double mom2InEntireCell = 0.0;
double mom3InEntireCell = 0.0;
for (int quadNodeIndex = 0; quadNodeIndex < edgeQuadData.rows(); quadNodeIndex++)
{
double physicalV = cellCentroid[1] + gaussEdgeOrdinates(quadNodeIndex,1)*grid.getDx(1)/2.0;
mom0InEntireCell += gaussEdgeWeights[quadNodeIndex]*edgeQuadData(quadNodeIndex);
mom1InEntireCell += gaussEdgeWeights[quadNodeIndex]*physicalV*edgeQuadData(quadNodeIndex);
mom2InEntireCell += gaussEdgeWeights[quadNodeIndex]*2*edgeHamilQuadData[quadNodeIndex]*
edgeQuadData[quadNodeIndex];
mom3InEntireCell += gaussEdgeWeights[quadNodeIndex]*2*edgeHamilQuadData[quadNodeIndex]*
edgeHamilDerivQuadData[quadNodeIndex]*edgeQuadData[quadNodeIndex];
}
mom0AlongRightEdge += mom0InEntireCell;
mom1AlongRightEdge += mom1InEntireCell;
mom2AlongRightEdge += mom2InEntireCell;
mom3AlongRightEdge += mom3InEntireCell;
}
ix = globalRgn.getLower(0); // left skin cell x index
// Integrate along skin cell (left edge)
for (int js = 0; js < globalRgn.getUpper(1); js++)
{
idx[0] = ix;
idx[1] = js;
grid.setIndex(idx);
grid.getCentroid(cellCentroid);
// Don't want skin cell contributions for v > 0.0 (upwinding)
if (cellCentroid[1] > 0.0)
break;
distfIn.setPtr(sknPtr, ix, js);
hamilIn.setPtr(sknHamilPtr, ix, js);
Eigen::VectorXd hamilAtNodes(numNodes);
for (int i = 0; i < numNodes; i++)
hamilAtNodes(i) = sknHamilPtr[i];
Eigen::VectorXd hamilDerivAtNodes = derivativeMatrix*hamilAtNodes;
// Copy nodes on left edge into a vector
Eigen::VectorXd edgeHamilDerivData(leftEdgeNodeNums.size());
Eigen::VectorXd edgeHamilData(leftEdgeNodeNums.size());
Eigen::VectorXd edgeData(leftEdgeNodeNums.size());
// Copy nodal values of hamiltonian, hamiltonian derivative, and dist f into a vector
for (int edgeNodeIndex = 0; edgeNodeIndex < edgeHamilData.rows(); edgeNodeIndex++)
{
edgeHamilData(edgeNodeIndex) = hamilAtNodes(leftEdgeNodeNums[edgeNodeIndex]);
edgeHamilDerivData(edgeNodeIndex) = hamilDerivAtNodes(leftEdgeNodeNums[edgeNodeIndex]);
edgeData(edgeNodeIndex) = sknPtr[leftEdgeNodeNums[edgeNodeIndex]];
}
// Interpolate nodal data to quadrature points on the edge
Eigen::VectorXd edgeHamilQuadData = edgeNodeInterpMatrix*edgeHamilData;
Eigen::VectorXd edgeHamilDerivQuadData = edgeNodeInterpMatrix*edgeHamilDerivData;
Eigen::VectorXd edgeQuadData = edgeNodeInterpMatrix*edgeData;
// Integrate v*f over entire cell using gaussian quadrature
double mom0InEntireCell = 0.0;
double mom1InEntireCell = 0.0;
double mom2InEntireCell = 0.0;
double mom3InEntireCell = 0.0;
for (int quadNodeIndex = 0; quadNodeIndex < edgeQuadData.rows(); quadNodeIndex++)
{
double physicalV = cellCentroid[1] + gaussEdgeOrdinates(quadNodeIndex,1)*grid.getDx(1)/2.0;
mom0InEntireCell += gaussEdgeWeights[quadNodeIndex]*edgeQuadData(quadNodeIndex);
mom1InEntireCell += gaussEdgeWeights[quadNodeIndex]*physicalV*edgeQuadData(quadNodeIndex);
mom2InEntireCell += gaussEdgeWeights[quadNodeIndex]*2*edgeHamilQuadData[quadNodeIndex]*
edgeQuadData[quadNodeIndex];
mom3InEntireCell += gaussEdgeWeights[quadNodeIndex]*2*edgeHamilQuadData[quadNodeIndex]*
edgeHamilDerivQuadData[quadNodeIndex]*edgeQuadData[quadNodeIndex];
}
mom0AlongLeftEdge += mom0InEntireCell;
mom1AlongLeftEdge += mom1InEntireCell;
mom2AlongLeftEdge += mom2InEntireCell;
mom3AlongLeftEdge += mom3InEntireCell;
}
// Integrate along ghost cell (left edge)
for (int jg = globalRgn.getUpper(1)-1; jg > 0; jg--)
{
idx[0] = ix-1;
idx[1] = jg;
grid.setIndex(idx);
grid.getCentroid(cellCentroid);
// Don't want ghost cell contributions for v < 0.0 (upwinding)
if (cellCentroid[1] < 0.0)
break;
distfIn.setPtr(gstPtr, ix-1, jg);
hamilIn.setPtr(gstHamilPtr, ix, jg);
Eigen::VectorXd hamilAtNodes(numNodes);
for (int i = 0; i < numNodes; i++)
hamilAtNodes(i) = gstHamilPtr[i];
Eigen::VectorXd hamilDerivAtNodes = derivativeMatrix*hamilAtNodes;
// Copy nodes on right edge into a vector
Eigen::VectorXd edgeHamilDerivData(rightEdgeNodeNums.size());
Eigen::VectorXd edgeHamilData(rightEdgeNodeNums.size());
Eigen::VectorXd edgeData(rightEdgeNodeNums.size());
// Copy nodal values of hamiltonian, hamiltonian derivative, and dist f into a vector
for (int edgeNodeIndex = 0; edgeNodeIndex < edgeHamilData.rows(); edgeNodeIndex++)
{
edgeHamilData(edgeNodeIndex) = hamilAtNodes(leftEdgeNodeNums[edgeNodeIndex]);
edgeHamilDerivData(edgeNodeIndex) = hamilDerivAtNodes(leftEdgeNodeNums[edgeNodeIndex]);
edgeData(edgeNodeIndex) = gstPtr[rightEdgeNodeNums[edgeNodeIndex]];
}
// Interpolate nodal data to quadrature points on the edge
Eigen::VectorXd edgeHamilQuadData = edgeNodeInterpMatrix*edgeHamilData;
Eigen::VectorXd edgeHamilDerivQuadData = edgeNodeInterpMatrix*edgeHamilDerivData;
Eigen::VectorXd edgeQuadData = edgeNodeInterpMatrix*edgeData;
// Integrate v*f over entire cell using gaussian quadrature
double mom0InEntireCell = 0.0;
double mom1InEntireCell = 0.0;
double mom2InEntireCell = 0.0;
double mom3InEntireCell = 0.0;
for (int quadNodeIndex = 0; quadNodeIndex < edgeQuadData.rows(); quadNodeIndex++)
{
double physicalV = cellCentroid[1] + gaussEdgeOrdinates(quadNodeIndex,1)*grid.getDx(1)/2.0;
mom0InEntireCell += gaussEdgeWeights[quadNodeIndex]*edgeQuadData(quadNodeIndex);
mom1InEntireCell += gaussEdgeWeights[quadNodeIndex]*physicalV*edgeQuadData(quadNodeIndex);
mom2InEntireCell += gaussEdgeWeights[quadNodeIndex]*2*edgeHamilQuadData[quadNodeIndex]*
edgeQuadData[quadNodeIndex];
mom3InEntireCell += gaussEdgeWeights[quadNodeIndex]*2*edgeHamilQuadData[quadNodeIndex]*
edgeHamilDerivQuadData[quadNodeIndex]*edgeQuadData[quadNodeIndex];
}
mom0AlongLeftEdge += mom0InEntireCell;
mom1AlongLeftEdge += mom1InEntireCell;
mom2AlongLeftEdge += mom2InEntireCell;
mom3AlongLeftEdge += mom3InEntireCell;
}
std::vector<double> data(8);
data[0] = mom0AlongLeftEdge;
data[1] = mom1AlongLeftEdge;
data[2] = mom2AlongLeftEdge;
data[3] = mom3AlongLeftEdge;
data[4] = mom0AlongRightEdge;
data[5] = mom1AlongRightEdge;
data[6] = mom2AlongRightEdge;
data[7] = mom3AlongRightEdge;
// Put data into the DynVector
velocityMoments.appendData(t, data);
return Lucee::UpdaterStatus();
}
void
MomentsAtEdgesUpdater::declareTypes()
{
// A distribution function
this->appendOutVarType(typeid(Lucee::Field<2, double>));
// A hamiltonian
this->appendOutVarType(typeid(Lucee::Field<2, double>));
// Moments 0-3 at left and right edges
this->appendOutVarType(typeid(Lucee::DynVector<double>));
}
void
MomentsAtEdgesUpdater::copyLuceeToEigen(const Lucee::Matrix<double>& sourceMatrix,
Eigen::MatrixXd& destinationMatrix)
{
for (int rowIndex = 0; rowIndex < destinationMatrix.rows(); rowIndex++)
{
for (int colIndex = 0; colIndex < destinationMatrix.cols(); colIndex++)
{
destinationMatrix(rowIndex, colIndex) = sourceMatrix(rowIndex, colIndex);
}
}
}
}
| true |
c60e6dfd2fc3030a240df77bef9a0be463249734
|
C++
|
SamuelEsd/Algorithmic_Toolbox
|
/week5_dynamic_programming1/3_edit_distance/edit_distance.cpp
|
UTF-8
| 1,212 | 3.171875 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
#include <iostream>
#include <string>
using std::string;
using std::vector;
using std::cout;
using std::min;
int edit_distance(const string &str1, const string &str2) {
vector<vector<int>> matrix(str1.size()+1, vector<int>(str2.size()+1));
int i = 0;
for(int row = 0; row < str1.size()+1; row++){
for(int col = 0; col < str2.size()+1; col++){
if(row == 0){
matrix[row][col] = col;
continue;
}
if(col == 0){
matrix[row][col] = row;
continue;
}
int up = matrix[row][col-1]+1;
int side;
if(str1[row-1] == str2[col-1]){
side = matrix[row-1][col-1];
}
else{
side = matrix[row-1][col-1]+1;
}
int down = matrix[row-1][col]+1;
matrix[row][col] = min(up,min(side,down));
}
}
// for(int x = 0; x < str1.size()+1; x++){
// for(int y = 0; y < str2.size()+1; y++){
// cout << matrix[x][y] << " ";
// }
// cout << "\n";
// }
// cout << str1.size()-1 << " " << str2.size()-1 << "\n";
return matrix[str1.size()][str2.size()];
}
int main() {
string str1;
string str2;
std::cin >> str1 >> str2;
std::cout << edit_distance(str1, str2) << std::endl;
return 0;
}
| true |
6edd668d5d424ba0d7837cff25dd15b30823a99e
|
C++
|
iamolivinius/frankfurt_university_material
|
/objektorientierte_programmierung_grundlagen/aufgabenblatt_2/aufgabe_5/TemperaturMeasurement.h
|
UTF-8
| 581 | 2.65625 | 3 |
[] |
no_license
|
#ifndef TEMPERATURMEASUREMENT_H_
#define TEMPERATURMEASUREMENT_H_
class TemperaturMeasurement {
private:
double value;
public:
static const double k_cons;
static const double f_cons_mult;
static const double f_cons_add;
TemperaturMeasurement();
TemperaturMeasurement(double val);
~TemperaturMeasurement();
double getTemperature();
static double toCelsius(TemperaturMeasurement& tm);
static double toFahrenheit(TemperaturMeasurement& tm);
static double toKelvin(TemperaturMeasurement& tm);
};
#endif /* TEMPERATURMEASUREMENT_H_ */
| true |
4f885173dc2757e5f4c780ee096519434d56c70d
|
C++
|
gauravk268/Competitive_Coding
|
/LeetCode/1631. Path With Minimum Effort.cpp
|
UTF-8
| 1,295 | 2.765625 | 3 |
[] |
no_license
|
class Solution
{
public:
int dx[4] = {0, 0, -1, 1};
int dy[4] = {-1, 1, 0, 0};
bool isValid(int x, int y, int n, int m)
{
return (x >= 0 && y >= 0 && x < n && y < m);
}
bool fun(vector<vector<int>> &h, int k)
{
int n = h.size(), m = h[0].size();
bool vis[n][m];
memset(vis, false, sizeof(vis));
queue<pair<int, int>> q;
q.push({0, 0});
vis[0][0] = true;
while (q.size())
{
pair<int, int> cur = q.front();
q.pop();
int x, y;
for (int i = 0; i < 4; i++)
{
x = cur.first + dx[i];
y = cur.second + dy[i];
if (isValid(x, y, n, m) && !vis[x][y] && abs(h[cur.first][cur.second] - h[x][y]) <= k)
{
if (x == n - 1 && y == m - 1)
return true;
vis[x][y] = true;
q.push({x, y});
}
}
}
return false;
}
int minimumEffortPath(vector<vector<int>> &h)
{
int n = h.size(), m = h[0].size();
if (n == 1 && m == 1)
return 0;
int low = 0, high = INT_MAX, result = 0, mid;
while (low <= high)
{
mid = low + (high - low) / 2;
if (fun(h, mid))
{
result = mid;
high = mid - 1;
}
else
{
low = mid + 1;
}
}
return result;
}
};
| true |
1cda4ae0e165bb2624a8a128ad6a14dc321b4db8
|
C++
|
pabletecor/UHU
|
/Grado Ingeniería Informática (Computación)/1º/2 Cuatri/EDII/Ejercicios/Ejercicio1-21.cpp
|
UTF-8
| 1,131 | 2.921875 | 3 |
[] |
no_license
|
//SOLUCION AL EJERCICIO 1 HACIENDO USO DE PUNTEROS AUXILIARES
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
char respuesta;
float suma=0;
int fila,col;
float **Datos=new float*[100];
if (Datos!=NULL)
{
float *Tabla;
for (int i=0;i<100;i++)
{
Datos[i]=new float[100-i];
Tabla=Datos[i];
for (int j=0;j<100-i;j++)
//Datos[i][j]=0.0;
Tabla[j]=0.0;
}
}
do
{
cout<<"Deme fila (1 a 100)\n";
cin>>fila;
Tabla=Datos[fila-1];
cout<<"Deme columna (1 a "<<100-fila+1<<")\n";
cin>>col;
cout<<"Deme valor\n";
cin>>Tabla[col-1];
cout<<"Desea continuar (S/N)\n";
respuesta=toupper(getch());
} while (respuesta!='N');
for (int i=0;i<100;i++) //para las filas
{
Tabla=Datos[i];
for (int j=0;j<100-i;j++) //recorrido de las columnas
//suma+=Datos[i][j]; //suma=suma + datos[i][j];
suma+=Tabla[j];
//delete [] Datos[i];
delete [] Tabla;
}
delete [] Datos;
Datos=NULL;
cout<<"La suma vale "<<suma<<endl;
system("pause");
return 0;
}
| true |
7b1bf2ae9f76d094452bb098b72180cf17a27a87
|
C++
|
ereichen/neural_nets
|
/net_signals.h
|
UTF-8
| 2,648 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
#ifndef NET_SIGNALS_H
#define NET_SIGNALS_H
#include <vector>
#include "neural_nets\detail\random_utils.h"
#include "neural_nets\detail\matrix_utils.h"
#include "neural_nets\detail\linear_feedback_shift_register.h"
namespace neural_nets
{
namespace net_signals
{
template <typename T>
boost::numeric::ublas::vector<T> linstep_space(T const &start_, T const &end_, T const &step_size_)
{
T tmp = start_;
boost::numeric::ublas::vector<T> result(static_cast<size_t>((end_ - start_) / step_size_ + 1), 1);
for (size_t i = 0; i < result.size(); ++i) {
result(i) = tmp;
tmp += step_size_;
}
return result;
}
template <typename T>
boost::numeric::ublas::vector<T> linspace(T const &start_, T const &end_, size_t const lenght_)
{
boost::numeric::ublas::vector<T> result(lenght_, 1);
T step_size = (end_ - start_) / (lenght_ - 1);
T current_value = start_;
for (size_t i = 0; i < lenght_; i++) {
result(i) = current_value;
current_value += step_size;
}
return result;
}
template <typename T>
boost::numeric::ublas::matrix<T> init_with_value(size_t const length_, T const &value_, size_t dim_ = 1)
{
boost::numeric::ublas::matrix<T> result(length_, dim_);
for (size_t i = 0; i < length_; ++i) {
for (size_t j = 0; j < dim_; ++j) {
result(i, j) = value_;
}
}
return result;
}
template <typename T>
boost::numeric::ublas::matrix<T> amp_pseudo_random_binary_sequence(boost::numeric::ublas::vector<T> const &t_, T max_hold_time_, T min_, T max_, size_t dim_ = 1)
{
boost::numeric::ublas::matrix<T> result(t_.size(), dim_);
std::vector<T> t;
t.reserve(t_.size());
for (size_t i = 0; i < t_.size(); ++i) {
t.push_back(t_(i));
}
std::vector<T> in = detail::amp_pseudo_random_binary_sequence(t, max_hold_time_, min_, max_);
for (size_t i = 0; i < dim_; ++i) {
for (size_t j = 0; j < in.size(); ++j) {
result(j, i) = in[j];
}
}
return result;
}
template <typename T>
boost::numeric::ublas::matrix<T> low_pass_filter(
boost::numeric::ublas::vector<T> const &time,
boost::numeric::ublas::matrix<T> const &input,
T const &gain,
T const &time_constant)
{
boost::numeric::ublas::matrix<T> result(input.size1(), input.size2());
for (size_t j = 0; j < input.size2(); ++j) {
result(0, j) = 0;
}
for (size_t i = 1; i < input.size1(); ++i) {
T dt = time(i) - time(i - 1);
for (size_t j = 0; j < input.size2(); ++j) {
result(i, j) = 1 / (time_constant / dt + 1)*(gain*input(i, j) + (time_constant / dt)*result(i - 1, j));
}
}
return result;
}
}
}
#endif
| true |
1849a6d801efecf6ce8142373296a65d0c122cf8
|
C++
|
WishAllVA/cpp-programs
|
/Codeforces/Codeforces 729 - A.cpp
|
UTF-8
| 608 | 3.125 | 3 |
[] |
no_license
|
// You are given a multiset (i. e. a set that can contain multiple equal integers) containing 2n integers.
// Determine if you can split it into exactly n pairs (i. e. each element should be in exactly one pair)
// so that the sum of the two elements in each pair is odd (i. e. when divided by 2, the remainder is 1)
#include<bits/stdc++.h>
using namespace std;
int main() {
int t;
cin>>t;
while(t--) {
int n;
cin>>n;
int m = n + n;
int a=0;
int k;
for(int i=0;i<m;i++) {
cin>>k;
if(k % 2==0) a++;
else a--;
}
if(a==0) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
return 0;
}
| true |
3b8dd1585ed4bf819380d808448936ee8e249b32
|
C++
|
AnByeongWoong/RTU_ObjectOrientedProgramming
|
/Demo solution - bicycle and guitar abstractions-20200501/ItemSpec.h
|
UTF-8
| 300 | 2.5625 | 3 |
[] |
no_license
|
#pragma once
#ifndef ITEM_SPEC
#include <ostream>
class ItemSpec
{
public:
virtual void send_to(std::ostream& os) const = 0;
virtual bool matches(const ItemSpec& itemSpec) const = 0;
};
std::ostream& operator<<(std::ostream& os, const ItemSpec& spec);
#endif // !ITEM_SPEC
| true |
f95761567763190dcc8bc2aa06adcc798b8b7783
|
C++
|
greenfox-zerda-sparta/kingamagyar
|
/Week_04/Day_02/07Car.cpp
|
UTF-8
| 236 | 2.640625 | 3 |
[] |
no_license
|
/*
* Car.cpp
*
* Created on: Nov 8, 2016
* Author: Kinga
*/
#include "Car.h"
#include <iostream>
Car::Car(string type, double km) {
this->type = type;
this->km = km;
}
void Car::run(double num) {
cout << km + num;
}
| true |
bb47d78de639f4724511fbcd03c4d6746d009298
|
C++
|
nipun0307/AlgorithmBasics
|
/Tree_Transversal.cpp
|
UTF-8
| 2,627 | 4 | 4 |
[] |
no_license
|
//Binary Tree and Transversals
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *right_child;
struct node *left_child;
};
struct node *new_node (int x){
struct node *ptr;
ptr=(struct node*)malloc(sizeof(struct node));
ptr->data=x;
ptr->left_child=NULL;
ptr->right_child=NULL;
return ptr;
}
struct node* insert(int x, struct node*root){
if (root==NULL){
return new_node (x);
}
if (x>root->data)
root->right_child=insert(x, root->right_child);
else if (x< root->data)
root->left_child=insert(x, root->left_child);
return root;
}
int find_min(struct node *root){
if (root==NULL){
return -1;
}
else if(root->left_child != NULL){
return find_min(root->left_child);
}
return root->data;
}
void inOrder (struct node *root){
if (root!=NULL){
inOrder(root->left_child);
printf("%d ",root->data);
inOrder(root->right_child);
}
}
struct node* deletep(int x, struct node* root){
if(root==NULL)
return NULL;
if (x<root->data)
root->left_child=deletep(x,root->left_child);
else if (x>root->data)
root->right_child=deletep (x, root->right_child);
else{
if (root->left_child==NULL && root->right_child==NULL)
{
free(root);
root=NULL;
}
else if(root->left_child==NULL || root->right_child==NULL)
{
//Node to be deleted has a left child or a right child,
//but not both
struct node *temp;
if (root->left_child==NULL)
//no left child; parent
//should point to right child
temp=root->right_child;
else
temp=root->left_child;
free (root);
return temp;
}
else
{
//Node to be deleted has both a left and a right child
int temp= find_min(root->right_child);
root->data= temp;
root->right_child=deletep (temp,root->right_child);
}
}
return root;
}
int main(void){
struct node* root;
root= new_node(50);
printf("The root is declared as 50\n");
int n;
printf("Enter the number of nodes to be inserted: ");
scanf("%d",&n);
while(n--){
int z;
printf("Enter the value: ");
scanf("%d", &z);
insert(z,root);
}
inOrder(root);
printf("\n");
inOrder (root);
printf("\nMin: %d\n\n",find_min(root));
return 0;
}
| true |
49f6bb1b9a9ea3ccf9926a7c68314e63bad46254
|
C++
|
warsztatywww/metaprogramming
|
/fib.cpp
|
UTF-8
| 347 | 3.140625 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
template <int n>
struct fib {
const static unsigned int value = fib<n-1>::value + fib<n-2>::value;
};
template <>
struct fib<0> {
const static unsigned int value = 1;
};
template <>
struct fib<1> {
const static unsigned int value = 1;
};
int main() {
cout << fib<900>::value << endl;
}
| true |
a69363dda5406b32c108a660cdba22196af3d51e
|
C++
|
vatva691/baitapc
|
/Untitled6.cpp
|
UTF-8
| 250 | 2.78125 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <math.h>
int main ()
{
float r, c, s;
printf("\nNhap vao ban kinh cua hinh tron : ");
scanf("%f",&r);
c=2*3,14*r;
s=pow(r,2)*3,14;
printf("\nChu vi hinh tron la: %f",c);
printf("\nDien tich hinh tron la: %f",s);
}
| true |
4d8ea09443e8eb10b2b29517451754bc80b52714
|
C++
|
zhouxiaoisme/caffe-easy
|
/src/caffe/layers/reverse_layer.cpp
|
GB18030
| 3,230 | 2.609375 | 3 |
[
"BSD-2-Clause",
"LicenseRef-scancode-generic-cla"
] |
permissive
|
#include "caffe/layers/lstm_common_layers.hpp"
namespace caffe {
/*
zx commment:
bottom[0] data shape = [30, 1, 384, 10] = [N, C, H, W]
reverseLayer ǽ[N, C, H, W] blob ָijά, data reorder, ԭ(1, 2, 3, ..., shapeOfThisDim) 洢˳ reversely reoderΪ(shapeOfThisDim, ...., 3, 2, 1)
:
ٶNάȽreverse, ôǽNάȿԭblob(:blobά忴һ1d vector.)
ֳN,
(Ϊ,N=10, ʵN=30)
ÿһdataΪλ, λݴ洢˳,NdataĴ洢˳revserse,
ͼiʶbottom[0]ĵidataĴ洢˳,
0 1 2 3 4 5 6 7 8 9
ıΪ:
9 8 7 6 5 4 3 2 1 0
*/
template <typename Dtype>
void reverse_cpu(const int count, const Dtype* from_data, Dtype* to_data,
const int* counts, const int axis_count, const int axis) {
// int prev_ind = -1;
for(int index=0; index<count; index++) {
int ind=(index/counts[axis])%axis_count;
int to_index=counts[axis]*(axis_count-2*ind-1)+index;
// if (ind != prev_ind)
// {
// printf("enter here...\n");
// prev_ind = ind;
// }
*(to_data+to_index)=*(from_data+index);
}
}
template <typename Dtype>
void ReverseLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
CHECK_NE(bottom[0], top[0])<<this->type()<<" does not support in-place computation.";
reverse_param_=this->layer_param_.reverse_param();
}
template <typename Dtype>
void ReverseLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
vector<int> shape=bottom[0]->shape();
axis_=reverse_param_.axis();
CHECK_GT(shape.size(), 0)<<this->type()<<" does not support 0 axes blob.";
CHECK_GE(axis_, 0)<<"axis must be greater than or equal to 0.";
CHECK_LT(axis_, shape.size())<<"axis must be less than bottom's dimension.";
top[0]->ReshapeLike(*bottom[0]);
const int dim=shape.size();
shape.clear();
shape.push_back(dim);
bottom_counts_.Reshape(shape);
int* p=bottom_counts_.mutable_cpu_data();
for (int i=1; i<dim; i++) {
*p=bottom[0]->count(i);
p++;
}
*p=1;
}
template <typename Dtype>
void ReverseLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
// printf("[ZXDBG] [ReverseLayer] bottom[0]->count() = %d\n", bottom[0]->count());
reverse_cpu<Dtype>(bottom[0]->count(), bottom[0]->cpu_data(),
top[0]->mutable_cpu_data(), bottom_counts_.cpu_data(),
bottom[0]->shape(axis_), axis_);
}
template <typename Dtype>
void ReverseLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {
if (!propagate_down[0]) {
return;
}
reverse_cpu<Dtype>(bottom[0]->count(), top[0]->cpu_diff(),
bottom[0]->mutable_cpu_diff(), bottom_counts_.cpu_data(),
bottom[0]->shape(axis_), axis_);
}
#ifdef CPU_ONLY
STUB_GPU(ReverseLayer);
#endif
INSTANTIATE_CLASS(ReverseLayer);
REGISTER_LAYER_CLASS(Reverse);
} // namespace caffe
| true |
b4c6be6e12a5d4d965a53caf7429efb22261452f
|
C++
|
Bk8/impulse-response-raytracer
|
/flattener/Source/SpeakerListBoxModel.cpp
|
UTF-8
| 1,595 | 2.765625 | 3 |
[] |
no_license
|
//
// SpeakerListBoxModel.cpp
// flattener
//
// Created by Reuben Thomas on 25/01/2014.
//
//
#include "SpeakerListBoxModel.h"
SpeakerListBoxModel::SpeakerListBoxModel (std::vector<Speaker> & speaker)
: speaker (speaker)
{
}
int SpeakerListBoxModel::getNumRows()
{
return speaker.size();
}
void SpeakerListBoxModel::paintListBoxItem
( int rowNumber
, Graphics & g
, int width
, int height
, bool isRowSelected
)
{
g.setColour (Colours::black);
if (isRowSelected)
{
g.fillAll (Colours::darkgrey);
g.setColour (Colours::white);
}
g.setFont (height * 0.7f);
g.drawText ("speaker " + String (rowNumber + 1),
5, 0, width, height,
Justification::centredLeft, true);
}
String SpeakerListBoxModel::getTooltipForRow (int row)
{
String ret;
ret += "x: ";
ret += String (speaker[row].direction.x);
ret += ", y: ";
ret += String (speaker[row].direction.y);
ret += ", z: ";
ret += String (speaker[row].direction.z);
ret += ", shape: ";
ret += String (speaker[row].directionality);
return ret;
}
void SpeakerListBoxModel::addListener (Listener * l)
{
listener.add (l);
}
void SpeakerListBoxModel::removeListener (Listener * l)
{
listener.remove (l);
}
void SpeakerListBoxModel::listBoxItemClicked (int row, const MouseEvent & e)
{
listener.call (&Listener::speakerSelected, row);
}
void SpeakerListBoxModel::deleteKeyPressed (const int lastRowSelected)
{
listener.call (&Listener::deleteKeyPressed, lastRowSelected);
}
| true |
d01be2391ea07a32c56a4de9f8f70838f37b170c
|
C++
|
RhobanProject/Common
|
/communication/Buffer.cpp
|
UTF-8
| 4,092 | 2.796875 | 3 |
[] |
no_license
|
/*************************************************
* Publicly released by Rhoban System, August 2012
* www.rhoban-system.fr
*
* Freely usable for non-commercial purposes
*
* Licence Creative Commons *CC BY-NC-SA
* http://creativecommons.org/licenses/by-nc-sa/3.0
*************************************************/
/*
* Buffer.cpp
*
* Created on: 21 mars 2011
* Author: hugo
*/
#include <cstdio>
#include <cstdlib>
#include <string>
#include <sstream>
#include "Buffer.h"
#include "encodings.h"
#include "Message.h"
#include "util.h"
namespace Rhoban
{
Buffer::Buffer(): buffer(0), size(0), buffer_size(0), owned(true)
{
//alloc(MSG_HEADER_SIZE + BUFFER_INI_SIZE);
}
/* copy constructor */
Buffer::Buffer(const Buffer& o) : buffer(NULL), size(o.size), buffer_size(o.buffer_size), owned(true)
{
buffer = (char *) malloc(buffer_size);
if (buffer == NULL)
throw string("Buffer:Constructor failed, Out of memory");
memcpy(buffer,o.buffer,buffer_size);
}
Buffer & Buffer::operator=(const Buffer& o)
{
if(this != &o)
{
size = o.size;
alloc(size);
memcpy(buffer, o.buffer, size);
}
return *this;
}
Buffer::Buffer(char * buf, size_t siz): buffer(buf), size(0), buffer_size(siz), owned(false)
{
}
Buffer::~Buffer()
{
if(owned && buffer)
{
free(buffer);
buffer = 0;
}
}
void Buffer::alloc(size_t new_size)
{
if(new_size <= buffer_size)
return ;
if(new_size>MSG_MAX_SIZE)
{
ostringstream os;
os << new_size;
throw string("Message too large "+os.str());
}
if(!buffer || !owned)
{
buffer = (char *)malloc(new_size * sizeof(char));
owned = true;
}
else
buffer = (char *)realloc(buffer, (new_size + MSG_HEADER_SIZE) * sizeof(char) + 32);
if(buffer)
{
buffer_size = new_size;
}
else
{
ostringstream os;
os << "Could not allocate buffer of size " << new_size;
throw os.str();
}
}
void Buffer::assign(char * data, size_t data_siz, size_t buffer_siz)
{
if(buffer && owned)
free(buffer);
owned = false;
buffer = data;
buffer_size=buffer_siz;
size=data_siz;
}
ui32 Buffer::read_uint(ui32 offset)
{
if(offset + sizeof(ui32) <= size)
return decode_uint((const char *) buffer+offset);
else
throw string("buffer too small to read uint at this offset");
}
int Buffer::read_int(ui32 offset)
{
if(offset + sizeof(int) <=size)
return decode_int((const char *) buffer+offset);
else
throw string("buffer too small to read int at this offset");
}
bool Buffer::read_bool(ui32 offset)
{
if( (offset + sizeof(char)) <=size)
return (buffer[offset] != 0);
else
throw string("buffer too small to read bool at this offset");
}
float Buffer::read_float(ui32 offset)
{
if(offset + sizeof(int) <=size)
return decode_float(buffer+offset);
else
throw string("buffer too small to read float at this offset");
}
void Buffer::write(const char * data, size_t siz)
{
alloc(siz);
memcpy(buffer,data,siz);
size=siz;
}
void Buffer::append_to_buffer(const vector<ui8> & data, size_t siz)
{
alloc(size + siz);
std::copy(data.begin(), data.end(), buffer + size);
size += siz;
}
void Buffer::append_to_buffer(const char * data, size_t siz)
{
alloc(size+siz);
memcpy(buffer+size,data,siz);
size+=siz;
}
void Buffer::write(string str)
{
write(str.c_str(), str.size());
}
void Buffer::clear()
{
size = 0;
}
string Buffer::read_string(ui32 siz, ui32 offset)
{
if(offset+siz<= size)
return string(buffer + offset,siz);
else
throw string("Buffer too small ") + my_itoa(size) + " " + string("to read such a string of size ") + my_itoa(siz) + string("offfset ") + my_itoa(offset);
}
void Buffer::read_array(ui32 siz, ui32 offset, vector<ui8> & data)
{
if(offset+siz<= size)
{
data.resize(siz);
for(uint i=0;i<siz;i++)
data[i] = buffer[offset+i];
}
else
throw string("Buffer too small to read such a string");
}
vector<ui8> Buffer::read_array(ui32 siz, ui32 offset)
{
vector<ui8> res;
read_array(siz,offset,res);
return res;
}
size_t Buffer::getSize()
{
return size;
}
void Buffer::setSize(size_t size)
{
this->size = size;
}
char *Buffer::getBuffer()
{
return buffer;
}
}
| true |
15e679723e3d4642bd33e42e5dd99b53eabda595
|
C++
|
zzlc/FileProcess
|
/FileProcess/Global/GlobalConfig.cpp
|
GB18030
| 3,858 | 2.78125 | 3 |
[] |
no_license
|
#include "GlobalConfig.h"
#include <io.h>
CSpdLog* CSpdLog::_spd_logger_ptr = nullptr;
CGlobalConfig* CGlobalConfig::_global_config_ptr = nullptr;
CGlobalConfig::CGlobalConfig()
{
LOGGER->info("{}", __FUNCTION__);
}
CGlobalConfig::~CGlobalConfig()
{
LOGGER->info("{}", __FUNCTION__);
LOGGER->flush();
}
CGlobalConfig* CGlobalConfig::Instance()
{
if (!_global_config_ptr) {
_global_config_ptr = new CGlobalConfig;
}
return _global_config_ptr;
}
const uint8_t* CGlobalConfig::GetAES128Key()
{
return (uint8_t *)_aes128_key;
}
const uint8_t* CGlobalConfig::GetAES128Iv()
{
return (uint8_t*)_aes128_iv;
}
void CGlobalConfig::SetCurrentFileName(const string& file_name_)
{
lock_guard<mutex> lock_(_mutex);
_current_file_name = file_name_;
}
const std::string& CGlobalConfig::GetCurrentFileName()
{
lock_guard<mutex> lock_(_mutex);
return _current_file_name;
}
std::string CGlobalConfig::CreateUUID()
{
//QUuid uid = QUuid::createUuid();
//return uid.toString().remove("{").remove("}").remove("-").toStdString();
return "";
}
std::wstring utf8_to_wstring(const std::string& utf8_str_)
{
int unicodeLen = ::MultiByteToWideChar(CP_UTF8, 0, utf8_str_.c_str(), utf8_str_.size(), NULL, 0);
wchar_t* pUnicode;
pUnicode = new wchar_t[unicodeLen + 1];
memset((void*)pUnicode, 0, (unicodeLen + 1) * sizeof(wchar_t));
::MultiByteToWideChar(CP_UTF8, 0, utf8_str_.c_str(), utf8_str_.size(), (LPWSTR)pUnicode, unicodeLen);
std::wstring wstrReturn(pUnicode);
delete[] pUnicode;
return wstrReturn;
}
std::string wstring_to_utf8(const std::wstring& wstr_)
{
char* pElementText;
int iTextLen = ::WideCharToMultiByte(CP_UTF8, 0, (LPWSTR)wstr_.c_str(), wstr_.size(), NULL, 0, NULL, NULL);
pElementText = new char[iTextLen + 1];
memset((void*)pElementText, 0, (iTextLen + 1) * sizeof(char));
::WideCharToMultiByte(CP_UTF8, 0, (LPWSTR)wstr_.c_str(), wstr_.size(), pElementText, iTextLen, NULL, NULL);
std::string strReturn(pElementText);
delete[] pElementText;
return strReturn;
}
std::string unicode_to_utf(std::wstring str)
{
std::string return_value;
//ȡĴСռ䣬Сǰֽڼ
int len = WideCharToMultiByte(CP_ACP, 0, str.c_str(), str.size(), NULL, 0, NULL, NULL);
char *buffer = new(std::nothrow) char[len + 1];
if (NULL == buffer) {
return NULL;
}
WideCharToMultiByte(CP_ACP, 0, str.c_str(), str.size(), buffer, len, NULL, NULL);
buffer[len] = '\0';
//ɾֵ
return_value.append(buffer);
delete[]buffer;
return return_value;
}
std::wstring utf_to_unicode(std::string str)
{
//ȡĴСռ䣬Сǰַ
int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), NULL, 0);
TCHAR *buffer = new(std::nothrow) TCHAR[len + 1];
if (NULL == buffer) {
return NULL;
}
//ֽڱתɿֽڱ
MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), buffer, len);
buffer[len] = '\0';//ַβ
//ɾֵ
std::wstring return_value;
return_value.append(buffer);
delete[]buffer;
return return_value;
}
extern bool FileExist(const string& file_name_)
{
if (_access(file_name_.c_str(), 0) != 0) {
return false;
} else {
return true;
}
}
extern int64_t GetFileSize(const string& file_name_)
{
if (file_name_.empty()) {
return -1;
}
if (!FileExist(file_name_)) {
return -1;
}
FILE* fp = fopen(file_name_.c_str(), "rb");
if (!fp) {
return -1;
}
_fseeki64(fp, 0, SEEK_END);
int64_t len = _ftelli64(fp);
fclose(fp);
return len;
}
| true |
a4a61a23f6404022c4d851b1f24d355c78592454
|
C++
|
ilya-prudnikov/lr7
|
/LabRab7.cpp
|
UTF-8
| 1,142 | 3.125 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
int main()
{
setlocale(LC_ALL, "rus");
int j, dlina, start, end;
char st[100], chislo[100];
cout << "Введите пожалуйста строку до 100 символов, содержащую 1 число с фиксированной точкой: " << endl;
cin >> st;
dlina = strlen(st);//Функция strlen видит начало Си-строки и начинает сначала считать количество символов (байтов, отводимых под каждый символ), этот процесс выполняется до тех пор, пока не будет достигнут завершающий нулевой символ.
for (j = 1; j <= dlina; j++)
if (st[j] == '.')
{
for (j = j - 1;j >= 0;j--)
{
/*if (st[j] == '-')
start = j;*/
if (isdigit(st[j]))
start = j;
}
for (j = j + 1;j < dlina;j++)
{
if (isdigit(st[j]))
end = j;
}
}
cout << "Результат = ";
for (j = start; j <= end; j++)
{
chislo[j] = st[j];
cout << chislo[j];
}
return 0;
system("pause");
}
| true |
67679abf10785faba4f9af8a9c9dca13dbef8a7b
|
C++
|
Debu922/ESO207
|
/PA_1/triangle_migration_recursive.cpp
|
UTF-8
| 796 | 2.921875 | 3 |
[] |
no_license
|
/*
#########################################
# Solution by Debaditya Bhattacharya #
# Roll No: 190254 #
# Email-id: debbh@iitk.ac.in #
# Hackkerrank-id: @debbh922 #
#########################################
*/
#include <iostream>
using namespace std;
long long int D_recursive(long long int n);
long long int U_recursive(long long int n);
long long int U_recursive(long long int n)
{
if (n == 0)
{
return 1;
}
return 3 * U_recursive(n - 1) + D_recursive(n - 1);
}
long long int D_recursive(long long int n)
{
if (n == 0)
{
return 0;
}
return 3 * D_recursive(n - 1) + U_recursive(n - 1);
}
int main()
{
long long int n;
cin >> n;
cout << U_recursive(n) % 1000000007;
return 0;
}
| true |
49d1fd5fb0b8f38e70ed1f2d25dfc67bdec83e8a
|
C++
|
lgsonic/mysqlIncSync
|
/src/log/log.h
|
UTF-8
| 1,314 | 2.71875 | 3 |
[] |
no_license
|
#ifndef _D_LOG_H_
#define _D_LOG_H_
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
#include <time.h>
#include <fcntl.h>
#include <string>
#include <iostream>
#include <sstream>
#define LOG(x) CLog(CLog::x).Log
inline std::string GetDateString(const time_t & t)
{
struct tm tmLocal;
gmtime_r(&t, &tmLocal);
char szDate[16] = {0};
snprintf(szDate, 16, "%04d%02d%02d", 1900+tmLocal.tm_year, tmLocal.tm_mon+1, tmLocal.tm_mday);
return szDate;
}
inline std::string GetTimeString(const time_t & t)
{
struct tm tmLocal;
gmtime_r(&t, &tmLocal);
char szTime[16] = {0};
snprintf(szTime, 16, "%02d:%02d:%02d", tmLocal.tm_hour, tmLocal.tm_min, tmLocal.tm_sec);
return szTime;
}
class CLog
{
public:
enum LogLevel_t {DEBUG,INFO,WARNING,ERROR,FATAL};
public:
CLog(LogLevel_t level): m_LogLevel(level) {}
void Log(const char * format, ...);
static void Init(LogLevel_t level);
static void SetLogLevel(LogLevel_t level) { m_GlobalLevel = level; }
private:
void __WriteLog(const char * szMsg);
static void __ResetLogFile();
private:
LogLevel_t m_LogLevel;
static LogLevel_t m_GlobalLevel;
static std::string m_LogFilePrefix;
static std::string m_LogFilePath;
static int m_LogFileFd;
};
#endif
| true |
127319b1cfe92ea830b69d08ee9cb4ca0d7c61a0
|
C++
|
TLabahn/Game_Collection
|
/SDL_functions.h
|
ISO-8859-1
| 3,091 | 2.65625 | 3 |
[] |
no_license
|
#include <SDL2/SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <stdbool.h>
#include <cmath>
/*Generelle Funktionen, Makros, Globale Variablen etc. die im Zusammenhang zu SDL2 stehen
*/
//Bildschirmauflsung
const int SCREEN_WIDTH = 1200;
const int SCREEN_HEIGHT = 800;
//Initialisiert SDL2 Funktionen
bool init();
//Ldt Medien hoch
bool loadmedia();
//Schliet SDL2 Funktionen und gibt Pointer frei
void close();
//Loads individual image as texture
SDL_Texture* loadTexture( std::string path );
SDL_Window* gWindow = NULL;
//The window renderer
SDL_Renderer* gRenderer = NULL;
bool init()
{
//Initialization flag
bool success = true;
//Initialize SDL
if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
{
printf( "SDL could not initialize! SDL Error: %s\n", SDL_GetError() );
success = false;
}
else
{
//Set texture filtering to linear
if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) )
{
printf( "Warning: Linear texture filtering not enabled!" );
}
//Create window
gWindow = SDL_CreateWindow( "Game_Collection.exe", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
if( gWindow == NULL )
{
printf( "Window could not be created! SDL Error: %s\n", SDL_GetError() );
success = false;
}
else
{
//Create renderer for window
gRenderer = SDL_CreateRenderer( gWindow, -1, SDL_RENDERER_ACCELERATED );
if( gRenderer == NULL )
{
printf( "Renderer could not be created! SDL Error: %s\n", SDL_GetError() );
success = false;
}
else
{
//Initialize renderer color
SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF );
//Initialize PNG loading
int imgFlags = IMG_INIT_PNG;
if( !( IMG_Init( imgFlags ) & imgFlags ) )
{
printf( "SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError() );
success = false;
}
}
}
}
return success;
}
bool loadMedia()
{
//Loading success flag
bool success = true;
//Nothing to load
return success;
}
void close()
{
//Destroy window
SDL_DestroyRenderer( gRenderer );
SDL_DestroyWindow( gWindow );
gWindow = NULL;
gRenderer = NULL;
//Quit SDL subsystems
IMG_Quit();
SDL_Quit();
}
SDL_Texture* loadTexture( std::string path )
{
//The final texture
SDL_Texture* newTexture = NULL;
//Load image at specified path
SDL_Surface* loadedSurface = IMG_Load( path.c_str() );
if( loadedSurface == NULL )
{
printf( "Unable to load image %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError() );
}
else
{
//Create texture from surface pixels
newTexture = SDL_CreateTextureFromSurface( gRenderer, loadedSurface );
if( newTexture == NULL )
{
printf( "Unable to create texture from %s! SDL Error: %s\n", path.c_str(), SDL_GetError() );
}
//Get rid of old loaded surface
SDL_FreeSurface( loadedSurface );
}
return newTexture;
}
| true |
c36b58a697e95c5c19bdc4ccae992a9233a6f49d
|
C++
|
pellarolojuani/pruebas
|
/src/Parser/Parser.h
|
UTF-8
| 929 | 2.59375 | 3 |
[] |
no_license
|
/*
* Parser.h
*
* Created on: Apr 2, 2013
* Author: lucia
*/
#ifndef DELIMITADORES
#define DELIMITADORES ",.;: ¡!¿?\"<>(){}-_”[]'\n\t\b"
#endif /*DELIMITADORES*/
#ifndef MAX_POSICIONES_LINEA
#define MAX_POSICIONES_LINEA 200
#endif /* MAX_POSICIONES */
#ifndef PARSER_H_
#define PARSER_H_
#include <iostream>
#include <stdio.h>
#include <string.h>
#include "Posiciones.h"
using namespace std;
namespace parser {
class Parser {
public:
Parser();
string* parsearLinea(string, Posiciones* posiciones, int maxPosicionesLinea);
int getUltimaPosicion();
void resetUltimaPosicion();
virtual ~Parser();
private:
string delimitadores;
bool esDelimitador(char c, string* delimitadores);
void agregarPalabra(string palabra, string* palabras, int cantPalabras);
string tolowercase(string s);
int pos;
int numeroPalabra;
string quitarFinDeLinea(string s);
};
} /* namespace parser */
#endif /* PARSER_H_ */
| true |
e300dd535ee8181e96ffd7104ec1bb3854925653
|
C++
|
TiwariSimona/Hacktoberfest-2021
|
/Aniket_Raj/kthsetbit.cpp
|
UTF-8
| 429 | 3.28125 | 3 |
[
"MIT"
] |
permissive
|
#include<iostream>
using namespace std;
int main()
{
int n,k;
cout<<"Enter the value of n and k: ";
cin>>n>>k;
int temp=n;
//using right shift operation
n=n>>(k-1);
if(n&1) cout<<"Yes kth bit is a set bit\n";
else cout<<"No kth bit is not a set bit\n";
n=temp;
//using left shift operation
int one=1;
one=one<<(k=1);
if(n&one!=0) cout<<"YES\n";
else cout<<"NO\n";
}
| true |
2f594c60b98197d6b902561007a6ecfdc9ff8346
|
C++
|
mhhuang95/LeetCode
|
/leetcodec++/leetcode211.cpp
|
UTF-8
| 1,919 | 3.578125 | 4 |
[] |
no_license
|
//
// Created by 黄敏辉 on 2019-09-02.
//
class TrieNode{
public:
TrieNode(bool end=false){
memset(branches, 0, sizeof(branches));
isEnd = end;
}
TrieNode* branches[26];
bool isEnd;
};
class WordDictionary {
public:
/** Initialize your data structure here. */
WordDictionary() {
root = new TrieNode();
}
/** Adds a word into the data structure. */
void addWord(string word) {
TrieNode* node = root;
int i;
for(i = 0; i < word.size(); i++){
if (node->branches[word[i] - 'a'] == NULL)
break;
else{
node = node->branches[word[i] - 'a'];
node->isEnd=((i==word.size()-1)?true:node->isEnd);
}
}
for (; i < word.size(); i++){
node->branches[word[i] - 'a'] = new TrieNode(i==word.size()-1);
node=node->branches[word[i]-'a'];
}
}
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
bool search(string word) {
return search(word.c_str(), root);
}
private:
TrieNode* root;
bool search(const char* word, TrieNode* node) {
for (int i = 0; word[i] && node; i++) {
if (word[i] != '.') {
node = node -> children[word[i] - 'a'];
} else {
TrieNode* tmp = node;
for (int j = 0; j < 26; j++) {
node = tmp -> children[j];
if (search(word + i + 1, node)) {
return true;
}
}
}
}
return node && node -> word;
}
};
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary* obj = new WordDictionary();
* obj->addWord(word);
* bool param_2 = obj->search(word);
*/
| true |
67838ab0e778ac9d4279d80c89d4cc5a529e9753
|
C++
|
lemon123456/ksc-archive
|
/cs320/SecuritySimulator/environment.h
|
UTF-8
| 708 | 2.515625 | 3 |
[] |
no_license
|
#ifndef ENVIRONMENT_H
#define ENVIRONMENT_H
#include <QObject>
#include "database.h"
#include "authenticator.h"
class User;
class Environment : public QObject
{
Q_OBJECT
public:
explicit Environment(QObject *parent = 0);
virtual ~Environment();
bool login(const QString &username, const QString &password);
User *user() const;
Database &database() const;
Authenticator &authenticator() const;
QString prompt();
void display(const QString &message, bool newline = true);
void insufficientPermissions();
void invalidCommandFormat();
void objectDoesNotExist(const QString &objectName);
private:
class Private;
Private *d;
};
#endif // ENVIRONMENT_H
| true |