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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
0f1af390dae0b750777319f1dc25558cad74a4e1 | C++ | devadomas/cpp-piscine | /d04/ex01/PlasmaRifle.hpp | UTF-8 | 303 | 2.53125 | 3 | [] | no_license | #ifndef PLASMA_RIFLE_HPP
# define PLASMA_RIFLE_HPP
# include "AWeapon.hpp"
class PlasmaRifle: public AWeapon
{
public:
PlasmaRifle(void);
PlasmaRifle(PlasmaRifle const & src);
virtual ~PlasmaRifle(void);
PlasmaRifle & operator=(PlasmaRifle const & src);
void attack(void) const;
};
#endif
| true |
3c8c78e26d80bd131706114dd90bed2984f1681c | C++ | robertsonasc/UFC-Estrutura-de-Dados | /2-trabalhos-entregues/tad/tad_ponto/Ponto2.h | UTF-8 | 812 | 3.59375 | 4 | [] | no_license | #ifndef PONTO_H
#define PONTO_H
#include <iostream>
#include <cmath>
class Ponto {
private:
double x;
double y;
public:
//Construtor padrão.
Ponto(){
x = 0;
y = 0;
};
// Construtor
Ponto(double X, double Y) {
x = X;
y = Y;
}
// Destrutor
~Ponto() {
//std::cout << "Ponto destruido" << std::endl;
}
// Getters
double getX() { return x; }
double getY() { return y; }
// Setters
void setX(double X) { x = X; }
void setY(double Y) { y = Y; }
double distancia(Ponto p) {
double dx = x - p.x;
double dy = y - p.y;
return sqrt(dx*dx + dy*dy);
}
};
#endif | true |
51a70e113a8b18965cd1fe2446f675011c3fb86f | C++ | sparkmxy/SJTU_Bookstore | /SJTU_Bookstore/index.cpp | UTF-8 | 1,637 | 2.734375 | 3 | [] | no_license | #include "index.h"
void multiIndex::add(keyT key, int recID) {
//std::cout << "add: " << key << ' ' << recID << '\n';
auto V = L.lookup(key);
if (!V.size()) {
//std::cout << "New key: " << key << '\n';
indexT NewIndex(key);
array A;
A.push(recID);
rec.push(A);
NewIndex.push(rec.size());
L.push(NewIndex);
}
else {
int cur = V[0].tail();
array A = rec.get(cur);
if (A.full()) {
array B;
B.push(recID);
rec.push(B);
V[0].push(rec.size());
L.modify(key, V[0]);
}
else {
A.push(recID);
rec.replace(A, cur);
}
}
//std::cout << "add finished!\n";
}
std::vector<int> multiIndex::find(keyT key) {
auto V = L.lookup(key);
if (!V.size()) return std::vector<int>();
// std::cout << "key found!\n";
std::vector<int> ret;
for (int i = 0; i < V[0].size(); i++) {
array A = rec.get(V[0](i));
for (int j = 0; j < A.size(); j++)
if (A(j) != -1)ret.push_back(A(j));
}
return ret;
}
void multiIndex::erase(keyT key, int recID) {
//std::cout << "erase: " << key << '\n';
if (key == "") return;
auto V = L.lookup(key);
for (int i = 0; i < V[0].size(); i++) {
array A = rec.get(V[0](i));
for (int j = 0; j < A.size(); j++)
if (A(j) == recID)A.del(j);
}
//std::cout << "erase finished!\n";
}
int singleIndex::find(keyT key) {
auto V = L.lookup(key);
if (!V.size()) return -1;
return V[0].val();
}
bool singleIndex::add(keyT key, int recID) {
auto V = L.lookup(key);
if (!V.size()) {
L.push(indexT2(key, recID));
return true;
}
error("Name reused.");
}
bool singleIndex::del(keyT key) {
try {
L.erase(key);
}
catch (...) {
return false;
}
return true;
}
| true |
df0e238f8a2ba23276e470020e6adb592376e90a | C++ | IamBikramPurkait/My-CP-Journey | /GFG/DSA ADVANCED/9 - Strings/naive_pattern_search.cpp | UTF-8 | 789 | 3.671875 | 4 | [
"MIT"
] | permissive | // { Driver Code Starts
// C++ program for Naive Pattern
// Searching algorithm
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
public:
//Function to check if the given pattern exists in the given string or not.
bool search(string pat, string txt)
{
// Your code here
size_t found = txt.find(pat);
if (found != string::npos)
return true;
return false;
}
};
// { Driver Code Starts.
// Driver Code
int main()
{
int t;
cin >> t;
while (t--)
{
string s, p;
cin >> s >> p;
Solution obj;
if (obj.search(p, s))
cout << "Yes";
else
cout << "No";
cout << endl;
}
return 0;
}
// } Driver Code Ends | true |
4ac0a01f8a3cee1b1366e825ab5d69a844783a75 | C++ | Kid03/Tarea02-Delgado-SanMartin-Salgado | /tarea2/src/TCPEchoServer.cc | UTF-8 | 4,145 | 2.515625 | 3 | [] | no_license | /*
* C++ sockets on Unix and Windows
* Copyright (C) 2002
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "YASL.h" // For Socket, ServerSocket, and SocketException
#include <iostream> // For cerr and cout
#include <cstdlib> // For atoi()
#include <fstream> // For File Stream
#include "json.hpp"
const uint32_t RCVBUFSIZE = 1024; // Size of receive buffer
// TCP client handling function
void HandleTCPClient(TCPSocket *sock) {
std::ifstream i("bin/config.json");
nlohmann::json j;
i >> j;
std::cout << "Handling client ";
try {
std::cout << sock->getForeignAddress() << ":";
} catch (SocketException e) {
std::cerr << "Unable to get foreign address" << std::endl;
}
try {
std::cout << sock->getForeignPort();
} catch (SocketException e) {
std::cerr << "Unable to get foreign port" << std::endl;
}
std::cout << std::endl;
// Send received string and receive again until the end of transmission
char echoBuffer[RCVBUFSIZE];
uint32_t recvMsgSize;
// Zero means end of transmission
while ((recvMsgSize = sock->recv(echoBuffer, RCVBUFSIZE)) != 0) {
// Echo message back to client
std::cout << echoBuffer;
break;
}
std::string pagina;
char *token = strtok(echoBuffer, " ");
for(int i = 0; i < 2; i++){
if(i == 0){
token = strtok(NULL," ");
}
else{
pagina = token;
}
}
//AQUI ESTA LA MALDITA PAGINA
pagina = pagina.substr(1, pagina.length());
if(pagina == "holamundo.html"){
pagina="";
pagina.append(j["root_dir"]);
pagina.append("holamundo.html");
}
else if(pagina == "chaomundo.html"){
pagina="";
pagina.append(j["root_dir"]);
pagina.append("chaomundo.html");
}
else if(pagina == "h1.html"){
pagina="";
pagina.append(j["root_dir"]);
pagina.append("h1.html");
}
else{
pagina = j["notFoundFile"];
//sock->send(lectura.c_str(),lectura.lenght());
}
std::ifstream archivo(pagina);
std::string lectura = "";
std::string a;
try{
sock->send("HTTP/1.1 200 ok\r\nContent-Type: text/html\r\n\r\n",44);
if(archivo.is_open()){
while(getline(archivo,a)){
lectura = lectura + a + "\n";
}
archivo.close();
}
else{
std::cerr << "Error en lectura." << std::endl;
exit(EXIT_FAILURE);
}
}
catch (std::ifstream::failure e) {
std::cerr << "Error al abrir el archivo." << std::endl;
exit(EXIT_FAILURE);
}
sock->send(lectura.c_str(),lectura.length());
delete sock;
}
int main(int argc, char *argv[]) {
if (argc >= 2) { // Test for correct number of arguments
std::cerr << "Usage: " << argv[0] << " [<Server Port>]" << std::endl;
exit(EXIT_FAILURE);
}
uint16_t echoServPort;
std::ifstream i("bin/config.json");
nlohmann::json j;
i >> j;
if (argc == 1){
echoServPort = j["puerto"];
}else {
echoServPort = atoi(argv[1]); // First arg: local port
}
try {
TCPServerSocket servSock(echoServPort); // Server Socket object
for (;;) { // Run forever
HandleTCPClient(servSock.accept()); // Wait for a client to connect
}
} catch (SocketException &e) {
std::cerr << e.what() << std::endl;
exit(EXIT_FAILURE);
}
// NOT REACHED
return EXIT_SUCCESS;
}
| true |
b02223dbcd29d5c650a751a4861bf88233d2d795 | C++ | goDawgs18/520-Assignments | /week_6/integrator.h | UTF-8 | 558 | 2.578125 | 3 | [] | no_license | #ifndef __INTEGRATOR_H
#define __INTEGRATOR_H
#include "elma/elma.h"
class Integrator : public elma::Process {
Integrator(std::string name) : Process(name) {}
void init() {}
void start() {}
void update() {
double newVal = 0.0;
if ( channel("link").nonempty() ) {
newVal = channel("link").latest();
}
double integrateVal = newVal * delta();
total += integrateVal;
}
void stop() {}
double value() {
return total;
}
private:
double total = 0;
};
#endif | true |
8d593a2567178cac06a81e6ca7ba0bcf3721534b | C++ | GDRH/mBot_Controller | /src/Serial.cpp | UTF-8 | 589 | 3.21875 | 3 | [] | no_license | #include "Serial.h"
Serial::Serial(){
filestream = NULL;
}
Serial::~Serial(){
fclose(filestream);
}
bool Serial::init( std::string filePath ){
filestream = fopen( filePath.c_str(), "w" );
if ( filestream ){
puts("Serial opened!\n");
return true;
}
//else...
puts("Error : failed to initialize serial!");
return false;
}
bool Serial::sendBytes ( char * buffer, unsigned int size ){
if ( !filestream )
return false;
for ( unsigned int i = 0; i < size; i++ ){
fputc( buffer[i], filestream );
}
fflush( filestream );
return true;
}
| true |
cc133bd15a92be6b8dab84fcb0d49013971d2875 | C++ | Hajiii88/RecordABC | /abc153_d.cpp | UTF-8 | 728 | 2.890625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define df(x) int x = in();
#define pb push_back
#define eb emplace_back
#define sz(x) int(x.size())
using ll = long long;
using p = pair<int, int>;
ll f(ll x){
if(x == 1) return 1;
ll a = f(x/2);
return a*2+1;
}
int main(){
ll h;
cin >> h;
cout << f(h) << endl;
return 0;
}
//2nd
ll rec(ll x){
if(x==1) return 1;
return rec(x/2)*2+1;
}
//よって計算量は O(logH) となる。
//その理由は「二分探索は毎回探索範囲が半減するから計算量が log になる」というのと一緒だ。
int main(){
ll h;
cin >> h;
cout << rec(h) << endl;
return 0;
} | true |
bb951995ed43cd72a2c9ab51b2350d45a2e55dd0 | C++ | Oleg-E-Bakharev/Sorting | /Sorting/rbt.hpp | UTF-8 | 9,684 | 3.140625 | 3 | [] | no_license | //
// rbt.hpp
// Sorting
//
// Created by Oleg Bakharev on 24/03/16.
// Copyright © 2016 Oleg Bakharev. All rights reserved.
//
#ifndef rbt_hpp
#define rbt_hpp
#include <iostream>
#include <string.h>
#include <assert.h>
// Красно-черное дерево. Удовлетворяет следующим условиям:
// 1. Все узлы либо красные, либо черные.
// 2. Корень дерева - черный.
// 3. Листья дерева - черные.
// 4. Если узел красный, то его родитель и оба ребенка - черные.
// 5. Количество черных узлов на любом кратчайшем пути из узла к его листу-потомку одинаково.
template <class Item>
class RBTree {
struct Node {
Item* i; // Ключ
Node* p; // Родитель
Node* l; // Левый потомок
Node* r; // Правый потомок
bool c; // Цвет: 0 - черный, 1 - красный.
Node( Node* null = nullptr, Item* i = nullptr ) : i(i), p(null), l(null), r(null), c(0) {}
// int key() { return int(*i); }
bool isLeft() { return p->l == this; }
bool isRight() { return p->r == this; }
Node* setLeft( Node* l ) {
Node* t = this->l;
this->l = l;
l->p = this;
return t;
}
Node* setRight( Node* r ) {
Node* t = this->r;
this->r = r;
r->p = this;
return t;
}
Node* cousine() {
if ( isLeft() ) return p->r;
return p->l;
}
Node* uncle() { return p->cousine(); }
bool isBlack() { return c == 0; }
bool isRed() { return c == 1; }
void setBlack() { c = 0; }
void setRed() { c = 1; }
// Св-во 4.
void test_rb() { if ( isRed() ) assert( p->isBlack() && l->isBlack() && r->isBlack() ); }
};
// Фиктивный узел являющийся одновременно и родителем root и всеми листьями.
Node null{};
using Link = Node*;
Link root = &null;
void setRoot( Link x ) {
root = x;
x->p = &null;
}
void destroy_( Link x ) {
if ( x == root ) root = &null;
if ( x != &null ) delete x;
}
int count_( Link x ) {
if ( x == &null ) return 0;
return count_(x->l) + count_( x->r ) + 1;
}
int height_( Link x ) {
if ( x == &null ) return -1;
int hl = height_(x->l), hr = height_( x->r );
return hl > hr ? hl + 1 : hr + 1;
}
Link search_( Link x, Item& key ) {
while (x != &null && *x->i != key)
if (key < *x->i) x = x->l;
else x = x->r;
return x;
}
Link min_( Link x ) {
while (x->l != &null) x = x->l;
return x;
}
Link insertionPoint( Item& key ) {
Link x = root;
Link y = &null;
while ( x != &null ) {
y = x;
if ( key < *x->i ) x = x->l;
else x = x->r;
}
return y;
}
// Заменить x на y. X выбрасываем.
Link transpant( Link x, Link y ) {
if ( x->p == &null ) setRoot( y );
else if ( x->isLeft() ) x->p->setLeft( y );
else x->p->setRight(y);
return y;
}
// Обход в ширину (поперечный) с указанием высоты.
void traverse_( Link x, int h, void(*traverseProc)(Item* x, int h, bool isRed) ) {
if ( x == &null ) {
// traverseProc( nullptr, h, x->isRed() );
return;
}
traverse_( x->r, h + 1, traverseProc );
traverseProc( x->i, h, x->isRed() );
traverse_( x->l, h + 1, traverseProc );
}
// Методы красно черных деревьев.
void rotate_left( Link x ) {
Link y = x->r;
Link p = x->p;
if ( x->isLeft() ) p->setLeft( y );
else p->setRight( y );
Link z = y->setLeft( x );
x->r = z;
if( z != &null ) z->p = x; // У нулевого узла родителя не меняем! Иначе в сл3. удаления получим сбой.
if ( root == x ) { root = y; }
}
void rotate_right( Link x ) {
Link y = x->l;
Link p = x->p;
if ( x->isLeft() ) p->setLeft( y );
else p->setRight( y );
Link z = y->setRight( x );
x->l = z;
if ( z != &null ) z->p = x; // У нулевого узла родтеля не меняем!
if ( root == x ) { root = y; }
}
typedef void ( RBTree::*rotate_f )( Link x );
// Случаи - из Кормена.
// возврат: true - остановиться, false - продолжить.
bool insert_fix_(Link x, rotate_f rotate_l, rotate_f rotate_r, bool moveX) {
Link y = x->uncle();
if ( y->isRed() ) { // дядя красный. Сл. 1.
y->setBlack();
x->p->setBlack();
y->p->setRed();
return false;
}
if ( moveX ) { // Мы должны продвинуть x. Сл. 2.
x = x->p;
(this->*rotate_l)( x );
}
x->p->setBlack(); // Сл. 3.
x->p->p->setRed();
(this->*rotate_r)( x->p->p );
return true;
}
void insert_fix( Link x ) {
while ( x->p->isRed() ) {
if ( x->p->isLeft() ) {
if ( insert_fix_( x, &RBTree::rotate_left, &RBTree::rotate_right, x->isRight() ) ) break;
}
else if ( insert_fix_( x, &RBTree::rotate_right, &RBTree::rotate_left, x->isLeft() ) ) break;
x = x->p->p;
}
root->setBlack();
}
typedef Link Node::*dir;
// Случаи из Кормена.
Link delete_fix_( Link x, rotate_f rotate_l, rotate_f rotate_r, dir left, dir right ) {
Link y = x->p->*right;
if ( y->isRed() ) { // брат красный. Сл.1.
y->setBlack();
x->p->setRed();
(this->*rotate_l)(x->p);
y = x->p->*right; // новый брат.
}
if ( y->l->isBlack() && y->r->isBlack() ) { // У нового брата оба ребенка черные. Сл.2
y->setRed();
return x->p; // продвигаемся на уровень вверх.
}
if ( (y->*right)->isBlack() ) { // у нового брата левый - красный, правый черный. Сл.3
(y->*left)->setBlack();
y->setRed();
(this->*rotate_r)(y);
y = x->p->*right;
}
y->c = x->p->c; // у нового брата правый красный. Сл.4.
x->p->setBlack();
(y->*right)->setBlack();
(this->*rotate_l)(x->p);
return root; // Выходим из цикла.
}
void delete_fix( Link x ) {
while ( x != root && x->isBlack() ) {
if ( x->isLeft() ) x = delete_fix_( x, &RBTree::rotate_left, &RBTree::rotate_right, &Node::l, &Node::r);
else x = delete_fix_( x, &RBTree::rotate_right, &RBTree::rotate_left, &Node::r, &Node::l);
}
x->setBlack();
}
// Тест св-в 4, 5. Возвращает черную высоту дерева.
int test_( Link x ) {
int h = height_(x);
if ( x == &null ) return 0;
x->test_rb(); // 4.
int bhl = test_(x->l), bhr = test_( x->r );
assert(bhl == bhr); // 5.
if ( x->isBlack() ) bhl++;
assert(h <= 2 * bhl); // Основное св-во КЧ-деревьев.
return bhl;
}
public:
RBTree() {}
~RBTree() { destroy_(root); }
int count() { return count_(root); }
int height() { return height_(root); }
Item* search( Item& key ) {
Link x = search_( root, int(key) );
if ( x != nullptr ) return &x->i;
return nullptr;
}
void insert( Item& i ) {
int c = count();
Link p = insertionPoint( i );
Link x = new Node( &null, &i );
if ( p == &null ) setRoot( x );
else {
x->p = p;
if ( int(i) < *p->i ) p->l = x;
else p->r = x;
}
x->setRed();
insert_fix( x );
assert( count() == c + 1 );
test();
}
void insert( Item* Items, int n ) { for( int i = 0; i < n; i++ ) insert( Items[i] ); }
bool remove(Item& i) {
int c = count();
Link x = search_( root, i );
Link z = nullptr;
if ( x == &null ) return false;
// Только в одном узле может произойти нарушение св-ва 5.
bool isRemovedBlack = x->isBlack();
if ( x->l == &null ) z = transpant( x, x->r );
else if ( x->r == &null ) z = transpant( x, x->l );
else {
Link y = min_( x->r );
z = y->r;
isRemovedBlack = y->isBlack();
if ( y->p == x ) {
z->p = y;
} else {
transpant( y, y->r );
y->setRight( x->r );
}
transpant( x, y );
y->setLeft( x->l) ;
y->c = x->c;
}
if ( isRemovedBlack ) {
delete_fix( z );
}
assert( count() == c - 1 );
test();
delete x;
return true;
}
void removeAll() { destroy_(root); }
// Обход в ширину (Поперечный обход).
typedef void(*TraverseProc)(Item* x, int h, bool isRed);
void traverse(TraverseProc proc) {
traverse_(root, 0, proc);
}
// Вывод дерева, повернутого на 90 градусов.
void show() {
using namespace std;
cout << endl;
traverse( []( Item* x, int h, bool isRed ) {
for (int i = 0; i < h; i++) cout << " ";
cout << (isRed ? 'r' : 'b');
if (x != nullptr) cout << *x;
else cout << "*";
cout << endl;
} );
cout << endl;
}
// Тест.
void test() {
assert( root->isBlack() );
test_(root);
}
};
namespace RBT {
void testRBT();
}
#endif /* rbt_hpp */
| true |
267514430b0dd31f4ac5e0cd9ec7966729bc2729 | C++ | Ze1598/Cpp_stuff | /learning/cpp_exceptions.cpp | UTF-8 | 1,199 | 4.5 | 4 | [] | no_license | // This file goes over exceptions
/*
In C++, exception handling is done using three keywords: `try`, `catch` and
`throw`.
A `try` block is a block of code that includes code which is usually
prone to raising exceptions. It's usually paired with a `catch` block.
A `catch` block when a particular exception is thrown or raised.
Lastly, `throw` is used to raise designated exceptions.
In the example:
try {
int a = 5;
int b = 0;
if (b == 0) {
throw 0;
}
}
catch (int x) {
cout << "You cannot divide by " << x << endl;
}
An exception is raised if the second variable is set to 0. When that happens,
we throw a 0, that is, an integer, which is caught by the `catch` block as
variable called `x`. Inside this block, we just output a message to detail
what hapenned.
*/
#include <iostream>
using namespace std;
int main() {
try {
int a = 5;
int b = 0;
// If the second number is 0, then throw an exception
if (b == 0) {
throw 0;
}
// Otherwise, output the result of dividing the two numbers
else {
cout << a / b << endl;
}
}
// Catch an exception raised with an integer
catch (int x) {
cout << "Error: You cannot divide by " << x << endl;
}
return 0;
}; | true |
adec1354a8a13b218f5df3c5cf6f95efa76482bb | C++ | oshernati22/College-projects | /ZOO System/allClasses.h | UTF-8 | 7,706 | 3.359375 | 3 | [] | no_license | #ifndef ALL_CLASSES
#define ALL_CLASSES
#include <iostream>
#include <cstring>
#include <typeinfo>
#include <fstream>
using namespace std;
class Animal
{
protected:
Animal();//set the default color to GRAY and other params to 0
Animal( const char* color, int childs, float avgLifetime );//init the Animal with a given attributes
Animal( ifstream& in_file );//init the Animal from a binary file
public:
virtual ~Animal();
public:
const char* GetColor() const;//return the color of the animal
int GetChildCount() const;//return the child count of the animal
float GetLifetime() const;//return the life time of the animal
void SetColor(const char* color);
void SetChildCount(int childs);
void SetLifetime(float lifetime);
void SetAnimal(const char* color, int childs, float avgLifetime);
protected:
char* m_color;
int m_childCount;
float m_avgLifetime;
};
class Mammals : virtual public Animal
{
public:
Mammals();//set the default color to GRAY and other params to 0
Mammals( const char* color, int childs, float avgLifetime, float preg, float milk );//init the Mammals with a given attributes
Mammals( ifstream& in_file );//init the Mammals from a binary file
virtual ~Mammals();
public:
float GetPregnanceTime() const;//return the pregnance time of the animal
float GetMilk() const;//return the milk liters of the animal
void SetPPregnanceTime(float pregnancytime);
void SetMilk(float milk);
protected:
float m_pregnancyTime;
float m_milkLiters;
};
class Birds : public Animal
{
public:
Birds();//set the default color to GRAY and other params to 0
Birds( const char* color, int childs, float avgLifetime, float incubation );//init the Birds with a given attributes
Birds( ifstream& in_file );//init the Birds from a binary file
virtual ~Birds();
public:
float GetIncubationTime() const;//return the incubation time of the animal
void SetIncubationTime(float incubationtime);
protected:
float m_incubationTime;
};
class Fish : virtual public Animal
{
public:
Fish();//set the default color to GRAY and other params to 0
Fish( const char* color, int childs, float avgLifetime, int fin, int gills );//init the Fish with a given attributes
Fish( ifstream& in_file );//init the Fish from a binary file
virtual ~Fish();
public:
int GetFinCount() const;//return the fin count of the animal
int GetGillsCount() const;//return the gills count of the animal
void SetFinCount(int fincount);
void SetGillsCount(int gillscount);
protected:
int m_finCount;
int m_gillsCount;
};
class Horse : public Mammals
{
public:
Horse();//set the default color to GRAY and other params to 0
Horse( const char* color, int childs, float avgLifetime, float preg, float milk, const char* type );//init the Horse with a given attributes
Horse( ifstream& in_file );//init the Horse from a binary file
virtual ~Horse();
public:
const char* GetType() const;//return the type of the horse
void SetType(const char * type);
protected:
char* m_type;
};
class Flamingo : public Birds
{
public:
Flamingo();//set the default color to GRAY and other params to 0
Flamingo( const char* color, int childs, float avgLifetime, float incubation, float avgHeight );//init the Flamingo with a given attributes
Flamingo( ifstream& in_file );//init the Flamingo from a binary file
virtual ~Flamingo();
public:
float GetHeight() const;//return the avg height of the flamingo
void SetHight(float height);
protected:
float m_avgHeight;
};
class MammalsFish : virtual public Mammals, virtual public Fish
{
public:
MammalsFish();//set the default color to GRAY and other params to 0
MammalsFish( const char* color, int childs, float avgLifetime, float preg, float milk, int fin, int gills );//init the MammalsFish with a given attributes
MammalsFish( ifstream& in_file );//init the MammalsFish from a binary file
virtual ~MammalsFish();
};
class GoldFish : public MammalsFish
{
public:
GoldFish();//set the default color to GRAY and other params to 0
GoldFish(const char* color, int childs, float avgLifetime, float preg, float milk, int fin, int gills, float avgW, float avgL);//init the GoldFish with a given attributes
GoldFish( ifstream& in_file );//init the GoldFish from a binary file
virtual ~GoldFish();
public:
float GetWeight() const;//return the avg weight of the gold fish
float GetLength() const;//return the avg length of the gold fish
void SetWeight(float weight);
void SetLength(float length);
protected:
float m_avgWeight;
float m_avgLength;
};
class Mermaid : public MammalsFish
{
public:
Mermaid();//set the default color to GRAY and other params to 0
Mermaid( const char* color, int childs, float avgLifetime, float preg, float milk, int fin, int gills, const char* firstName, const char* lastName );//init the Mermaid with a given attributes
Mermaid( ifstream& in_file );//init the Mermaid from a binary file
virtual ~Mermaid();
public:
const char* GetFirstName() const;//return the first name of the mermaid
const char* GetLastName() const;//return the last name of the mermaid
void SetFirstName(const char * firstname);
void SetLastName(const char * lastname);
protected:
char* m_firstName;
char* m_lastName;
};
class Zoo
{
public:
Zoo();//default c'tor - all to 0 or null
Zoo( const char* name, const char* address, float ticket, const char* open, const char* close );//c'tor with data - init class
Zoo( ifstream& in_file );//c'tor that gets a binary file and loads the data of the zoo from the file
virtual ~Zoo();//d'tor
public:
const char* GetName() const;//return the name of the zoo
const char* GetAddress() const;//return the address of the zoo
float GetTicketPrice() const;//return the ticket price of the zoo
const char* GetOpenHour() const;//return the open hour of the zoo
const char* GetCloseHour() const;//return the close hour of the zoo
int GetNumOfAnimals() const;//return the num of animals in the zoo
Animal** GetAnimals() const;//return the animals array of the zoo
public:
void AddAnimal( Animal* an );//creates a copy of "an" (deep copy) and adds an animal to the array
void LoadAnmialBin(ifstream& in_file);
Animal* CreateAnimalBin(ifstream& in_file);
public:
Zoo& operator+( Animal* an );//adds an animal (only pointer, no copy needed) to the class and returns this with the change
Zoo operator+( const Zoo& other ) const; //returns a new Zoo with the properties of this and animals of this and other (need to deep copy the data of other)
Zoo& operator+=(Animal* newanimal);
public:
friend ofstream& operator<<( ofstream& out, const Zoo& z );//operator to write the zoo to a text file
friend ifstream& operator>>( ifstream& in, Zoo& z );//operator to read the zoo from a text file
public:
void Save( ofstream& ofs ) const;//method to save the info to a text file
void Load( ifstream& ifs );//method to load the info from a text file
void SaveBin( ofstream& ofs ) const;//method to save the info to a binary file
void SetName1(const char* name);
void SetAdress1(const char* add);
void Setticket1(float ticket);
void Setopen1(const char* open);
void Setclose1(const char* close);
void Setnumofanimals1(int num);
char * CleanName(char * name);
private:
char* m_name;
char* m_address;
float m_ticketPrice;
char* m_openHours;
char* m_closeHours;
int m_numOfAnimals;
Animal** m_animals;
};
ofstream& operator<<( ofstream& out, const Zoo& z );
ifstream& operator>>( ifstream& in, Zoo& z );
#endif // ifndef | true |
244807f697ff3a09551493c0de7c9276e9a0ea12 | C++ | dicksonchum/DC-blackjack | /BlackJack/Hand.hpp | UTF-8 | 638 | 2.625 | 3 | [] | no_license | //
// Hand.hpp
// BlackJack
//
// Created by Dickson Chum on 2018-12-26.
// Copyright © 2018 Dickson Chum. All rights reserved.
//
#ifndef Hand_hpp
#define Hand_hpp
#include <stdio.h>
#include <vector>
#include "Card.hpp"
#include "Deck.hpp"
//using namespace std;
class Hand{
public:
Hand();
void startGame(Card card);
void startDealerGame(Card card);
void printHand();
void addCard(Card card);
int getHandValue();
void setHandValue(Card card);
int getNumOfCards();
private:
vector<Card> newHand;
// int indexOfAce;
int numOfAceInHand;
int handValue;
};
#endif /* Hand_hpp */
| true |
cf9872b8830fc5f91473dc84545421fb8e3b800e | C++ | msalamat/PageRank | /matrix.cpp | UTF-8 | 8,759 | 3.546875 | 4 | [] | no_license | //
// Created by Mohammad Salamat on 2019-01-28.
//
#include <iostream>
#include <iomanip>
#include <cmath>
#include <numeric>
#include "matrix.hpp"
/**
* A helper method.
*
* Determines whether a number is a square number
* @param n the number in question
* @return true, whether or not it is square
*/
bool isSquare(int n) {
int sq = (int) sqrt(n);
return sq*sq == n;
}
Matrix::Matrix() {
vector<double> babyVector;
babyVector.push_back(0.0);
daddyVector.push_back(babyVector);
}
Matrix::Matrix(int n) {
if (n <= 0) {
throw invalid_argument("n cannot be <= 0");
}
for (int i = 0; i < n; i++) {
vector<double> babyVector;
for (int j = 0; j < n; j++) {
babyVector.push_back(0.0);
}
daddyVector.push_back(babyVector);
}
}
Matrix::Matrix(int r, int c) {
if (r <= 0 || c <= 0) {
throw invalid_argument("one or both of the parameters was <= 0");
}
for (int i = 0; i < r; i++) {
vector<double> babyVector;
for (int j = 0; j < c; j++) {
babyVector.push_back(0.0);
}
daddyVector.push_back(babyVector);
}
}
Matrix::Matrix(double *p, int size) {
if (!isSquare(size)) {
throw invalid_argument("size of array is not an integer square root");
}
int counter = 0, sqrt_size = (int) sqrt(size);
for (int i = 0; i < sqrt_size; i++) {
vector<double> babyVector;
for (int j = 0; j < sqrt_size; j++) {
babyVector.push_back(* (p+counter));
counter++;
}
daddyVector.push_back(babyVector);
}
}
void Matrix::printMatrix() {
for (int i = 0; i < (int) daddyVector.size(); i++) {
for (int j = 0; j < (int) daddyVector[i].size(); j++) {
cout << daddyVector[i][j] << " ";
}
cout << endl;
}
}
void Matrix::set_value(const int row, const int column, const double newNum) {
if (row > (int) daddyVector.size() || column > (int) daddyVector[0].size() ||
row < 0 || column < 0) {
throw invalid_argument("row or column (or both) was out of bounds");
}
daddyVector[row][column] = newNum;
}
double Matrix::get_value(int row, int column) {
if (row > (int) daddyVector.size() || column > (int) daddyVector[0].size() ||
row < 0 || column < 0) {
throw invalid_argument("row or column (or both) was out of bounds");
}
return daddyVector[row][column];
}
void Matrix::clear() {
for (int i = 0; i < (int) daddyVector.size(); i++) {
for (int j = 0; j < (int) daddyVector[i].size(); j++) {
daddyVector[i][j] = 0.0;
}
}
}
Matrix::~Matrix() {
for (int i = 0; i < (int) daddyVector.size(); i++) {
daddyVector[i].clear();
daddyVector[i].shrink_to_fit();
}
daddyVector.clear();
daddyVector.shrink_to_fit();
}
ostream &operator<<(ostream & o, Matrix & m) {
for (int i = 0; i < (int) m.daddyVector.size(); i++) {
for (int j = 0; j < (int) m.daddyVector[i].size(); j++){
o << m.daddyVector[i][j] << "\t";
}
o << endl;
}
return o;
}
bool operator==(const Matrix &lhs, const Matrix &rhs) {
// size of daddy, i.e. number of rows
if (lhs.daddyVector.size() != rhs.daddyVector.size())
return false;
// row size
if (lhs.daddyVector[0].size() != rhs.daddyVector[0].size())
return false;
double smallerNum, biggerNum;
for (int i = 0; i < (int) lhs.daddyVector.size(); i++) {
for (int j = 0; j < (int) lhs.daddyVector[i].size(); j++) {
smallerNum = min(lhs.daddyVector[i][j], rhs.daddyVector[i][j]);
biggerNum = max(lhs.daddyVector[i][j], rhs.daddyVector[i][j]);
if (biggerNum > smallerNum + Matrix::tolerance)
return false;
}
}
return true;
}
bool operator!=(Matrix &lhs, Matrix &rhs) {
//return !operator==(lhs, rhs); both work
return !(lhs==rhs);
}
Matrix &Matrix::operator++() {
for (int i = 0; i < (int) daddyVector.size(); i++) {
for (int j = 0; j < (int) daddyVector[i].size(); j++) {
++daddyVector[i][j];
}
}
return *this;
}
Matrix Matrix::operator++(int) {
Matrix old(*this);
operator++();
return old;
}
Matrix &Matrix::operator--() {
for (unsigned long i = 0; i < daddyVector.size(); i++) {
for (unsigned long j = 0; j < daddyVector[i].size(); j++) {
--daddyVector[i][j];
}
}
return *this;
}
Matrix Matrix::operator--(int) {
Matrix old(*this);
operator--();
return old;
}
Matrix& Matrix::operator=(Matrix rhs) {
mySwap(*this, rhs);
return *this;
}
void Matrix::mySwap(Matrix &matrix, Matrix rhs) {
for (int i = 0; i < (int) rhs.daddyVector.size(); i++) {
for (int j = 0; j < (int) rhs.daddyVector[i].size(); j++) {
matrix.daddyVector[i][j] = rhs.daddyVector[i][j];
}
}
}
Matrix& Matrix::operator+=(const Matrix &rhs) {
*this = *this + rhs;
return *this;
}
Matrix operator+(Matrix lhs, const Matrix &rhs) {
if (lhs.daddyVector.size() != rhs.daddyVector.size())
throw invalid_argument("not same size error");
if (lhs.daddyVector[0].size() != rhs.daddyVector[0].size())
throw invalid_argument("not same size error");
for (int i = 0; i < (int) lhs.daddyVector.size(); i++) {
for (int j = 0; j < (int) lhs.daddyVector[i].size(); j++) {
lhs.daddyVector[i][j] += rhs.daddyVector[i][j];
}
}
return lhs;
}
Matrix &Matrix::operator-=(const Matrix &rhs) {
*this = *this - rhs;
return *this;
}
Matrix operator-(Matrix lhs, const Matrix &rhs) {
if (lhs.daddyVector.size() != rhs.daddyVector.size())
throw invalid_argument("not same size, error");
if (lhs.daddyVector[0].size() != rhs.daddyVector[0].size())
throw invalid_argument("not same size, error");
for (unsigned long i = 0; i < lhs.daddyVector.size(); i++) {
for (unsigned int j = 0; j < lhs.daddyVector[i].size(); j++) {
lhs.daddyVector[i][j] -= rhs.daddyVector[i][j];
}
}
return lhs;
}
Matrix &Matrix::operator*=(const Matrix &rhs) {
*this = *this - rhs;
return *this;
}
Matrix operator*(const Matrix &lhs, const Matrix &rhs) {
if (lhs.daddyVector[0].size() != rhs.daddyVector.size()) {
throw invalid_argument("col lhs must == row of rhs");
}
// an "n x m"
int n = (int) lhs.daddyVector.size();
int m = (int) rhs.daddyVector[0].size();
int l = (int) rhs.daddyVector.size();
Matrix resulting_matrix{n,m};
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
double result = 0;
for (int k = 0; k < l; k++) {
result += lhs.daddyVector[i][k] * rhs.daddyVector[k][j];
}
resulting_matrix.daddyVector[i][j] = result;
}
}
return resulting_matrix;
}
/**
* Check if a matrix has any full zeros in a column
* @param m a matrix
* @return The first occurance of a column with all zeroes
*/
int Matrix::getColoumnIfAllZeroes(const Matrix &m) {
int count = 0;
for (int i = 0; i < (int) m.daddyVector[0].size(); i++) { // loop column by column
for (int j = 0; j < (int) m.daddyVector.size(); j++) {
if (m.daddyVector[j][i] == 0)
break;
else
count++;
}
if (count == (int) m.daddyVector[0].size())
return i; // the col with all zeroes
count = 0;
}
return -1;
}
Matrix Matrix::getImportanceMatrix() {
Matrix m = *this;
int mSize = (int) m.daddyVector.size();
for (int i = 0; i < mSize; i++) {
double colWeight = 0;
for (int j = 0; j < mSize; j++) {
colWeight += m.daddyVector[j][i];
}
if (colWeight == 0) {
for (int j = 0; j < mSize; j++) {
m.daddyVector[j][i] = 1.0/mSize;
}
} else {
for (int j = 0; j < mSize; j++) {
m.daddyVector[j][i] /= colWeight;
}
}
}
return m;
}
int Matrix::get_size() {
return (int) (this->daddyVector.size());
}
Matrix::Matrix(int size, double p) : Matrix(size) {
double pp = p/size;
for (int i = 0; i < (int) daddyVector[0].size(); i++) {
for (int j = 0; j < (int) daddyVector.size(); j++) {
daddyVector[i][j] = pp;
}
}
}
Matrix::Matrix(int r, int c, double n) : Matrix(r, c) {
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
daddyVector[i][j] = n;
}
}
}
Matrix operator*(double scale, const Matrix &lhs) {
Matrix m = lhs;
for (int i = 0; i < (int) lhs.daddyVector.size(); i++) {
for (int j = 0; j < (int) lhs.daddyVector[i].size(); j++) {
m.daddyVector[i][j] *= scale;
}
}
return m;
}
double Matrix::getSumOfMatrixColumn(const Matrix &m) {
int rowLen = (int) m.daddyVector.size();
double sum = 0.0;
for (int i = 0; i < rowLen; i++) {
sum += m.daddyVector[i][0];
}
return sum;
}
void Matrix::scaleRank() {
double mSum = Matrix::getSumOfMatrixColumn(*this);
*this = (1/mSum) * (*this);
}
void Matrix::makeMToPercentage() {
*this = 100 * (*this);
}
void Matrix::formatPrint() {
int rowLen = (int) this->daddyVector.size();
this->scaleRank();
this->makeMToPercentage();
// next two lines are credited to https://stackoverflow.com/a/49210615
std::vector<char> alphabet(26);
std::iota(alphabet.begin(), alphabet.end(), 'A');
for (int i = 0 ; i < rowLen; i++) {
cout << "Page " << alphabet[i] << ": " <<
fixed << setprecision(2) <<
this->daddyVector[i][0] <<
"%" << endl;
}
} | true |
b1610087cfde94837fd1be3cb1dbcd7c17ffcc8a | C++ | karajensen/cloth-simulator | /ClothSimulator/mesh.h | UTF-8 | 6,416 | 2.59375 | 3 | [] | no_license | ////////////////////////////////////////////////////////////////////////////////////////
// Kara Jensen - mail@karajensen.com - mesh.h
////////////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "pickablemesh.h"
#include "callbacks.h"
class Picking;
class IOctree;
class CollisionMesh;
class Partition;
/**
* DirectX renderable, pickable and collidable mesh class
*/
class Mesh : public Transform, public PickableMesh
{
public:
/**
* Constructor
* @param engine Callbacks from the rendering engine
*/
explicit Mesh(EnginePtr engine);
/**
* Destructor
*/
~Mesh();
/**
* Load the mesh
* @param d3ddev The directX device
* @param filename The path to the mesh
* @param shader The shader attached to the mesh
* @param index A user defined index
*/
void LoadMesh(LPDIRECT3DDEVICE9 d3ddev,
const std::string& filename,
LPD3DXEFFECT shader,
int index = -1);
/**
* Load the mesh as an instance of another mesh
* @param d3ddev The directX device
* @param mesh The mesh of the object to instance off
* @param index A user defined index
*/
bool LoadAsInstance(LPDIRECT3DDEVICE9 d3ddev,
Mesh& mesh,
int index = -1);
/**
* Draw the visual model of the mesh
* @param cameraPos the position of the camera in world coordinates
* @param projection the projection matrix
* @param view the view matrix
*/
void DrawMesh(const D3DXVECTOR3& cameraPos,
const Matrix& projection,
const Matrix& view);
/**
* Draw the collision model of the mesh
* @param projection the projection matrix
* @param view the view matrix
*/
void DrawCollisionMesh(const Matrix& projection, const Matrix& view);
/**
* Renders diagnostics for the mesh
*/
void DrawDiagnostics();
/**
* Updates the mesh collision
*/
void UpdateCollision();
/**
* Tests whether mesh was clicked
* @param input the picking input structure
* @return whether this mesh was picked
*/
bool MousePickingTest(Picking& input);
/**
* Sets visibility of the mesh
* @param visible whether the mesh is visible or not
*/
void SetVisible(bool visible);
/**
* @return whether the mesh is visible
*/
bool IsVisible() const;
/**
* @return the mesh data
*/
std::shared_ptr<Geometry> Mesh::GetGeometry();
/**
* @return the collison mesh
*/
CollisionMesh& GetCollisionMesh();
/**
* Creates a collision model
* @param shape The shape of the collisin mesh
* @param minScale Minimum allowed scale of the collision mesh
* @param maxScale Maximum allowed scale of the collision mesh
* @param divisions The amount of divisions of the mesh if required
*/
void InitialiseCollision(Geometry::Shape shape,
const D3DXVECTOR3& minScale,
const D3DXVECTOR3& maxScale,
int divisions = 0);
/**
* @param draw whether the collision mesh is visible
*/
virtual void SetCollisionVisibility(bool draw);
/**
* @param pickable whether the mesh is pickable or not
*/
void SetPickable(bool pickable);
/**
* @return the user defined index for the mesh
*/
int GetIndex() const;
/**
* @param selected Whether the mesh is selected or not
*/
void SetSelected(bool selected);
/**
* Sets the mesh color
* @param r/g/b The rgb color components from 0->1
*/
void SetColor(float r, float g, float b);
/**
* Sets the mesh selected color
* @param r/g/b The rgb color components from 0->1
*/
void SetSelectedColor(float r, float g, float b);
/**
* Loads a texture for the mesh
* @param filename the filename for the texture
* @param dimensions the size of the texture
* @param miplevels the number of mipmap levels to generate
*/
void LoadTexture(const std::string& filename, int dimensions, int miplevels);
/**
* @return whether the mesh has collision geometry attached to it
*/
bool HasCollisionMesh() const;
/**
* Resets the animation
*/
void ResetAnimation();
/**
* Saves the mesh current position into the list of animation points
*/
void SavePosition();
/**
* @return the list of saved animation points
*/
const std::vector<D3DXVECTOR3>& GetAnimationPoints() const;
/**
* Animates the mesh through the list of animation points
* @param deltatime The time passed since last frame in seconds
*/
void Animate(float deltatime);
private:
/**
* Toggle whether this mesh is selected or not
*/
void ToggleSelected();
/**
* Initialises the collison geometry
*/
void InitializeCollision();
/**
* Prevent copying
*/
Mesh(const Mesh&);
Mesh& operator=(const Mesh&);
private:
EnginePtr m_engine; ///< Callbacks for the rendering engine
std::shared_ptr<CollisionMesh> m_collision; ///< The collision geometry attached to the mesh
std::shared_ptr<Geometry> m_geometry; ///< Data for rendering/instancing the mesh
D3DXVECTOR3 m_color; ///< Color for the mesh
D3DXVECTOR3 m_selectedcolor; ///< Color for the selected mesh
D3DXVECTOR3 m_initialcolor; ///< initial color for the mesh
std::vector<D3DXVECTOR3> m_animation; ///< Animation points for the mesh
int m_index = -1; ///< User defined index for the mesh
bool m_pickable = false; ///< Whether the mesh can be mouse picked or not
bool m_selected = false; ///< Whether the mesh is selected or not
bool m_draw = false; ///< Whether the mesh is visible or not
int m_target = -1; ///< Animation index target
bool m_animating = false; ///< Whether the mesh is animating or not
bool m_reversing = false; ///< Whether animating in reverse or not
float m_speed = 0.0f; ///< The speed the mesh will animate
};
| true |
ed41164390f2fe2fc034d5ad7669b6cb7f5eff06 | C++ | Makos63/CocktailPro | /src/main/VorhandeneZutaten.h | UTF-8 | 2,569 | 3.015625 | 3 | [] | no_license | //@(#) VorhandeneZutaten.h
#ifndef VorhandeneZutaten_H_H
#define VorhandeneZutaten_H_H
#include <string>
#include <unordered_map>
#include <vector>
#include <list>
#include <fstream>
#include <cstdlib> // fuer exit() unter Linux
#include <iostream>
#include <sstream>
/**
* @class VorhandeneZutaten
* @brief Class for managing the available ingredients.
*
* This class inputs zhe available ingredients from a text file and manages
them.
*/
class VorhandeneZutaten {
public:
/**
*@brief General Constructor of VorhandeneZutaten
*/
VorhandeneZutaten(void);
/**
* @brief copy Contructor of VorhandeneZutaten
*/
VorhandeneZutaten(const VorhandeneZutaten &vz);
/**
*@brief virtual Destructor of VorhandeneZutaten
*/
virtual ~VorhandeneZutaten();
/**
*@brief outputs the avaible ingredients to the console
*@return has no return type
*/
void browse(void);
/**
*@brief returns ingredients at the specified place in the vector
*@return a string-variable
*/
std::string getZutat(std::string);
/**
*@brief returns amount of ingredient
*@return an integer value
*/
int getMenge(std::string);
/*
*@brief returns the amount of available ingredients
*@return an interger
int getAnzahlVorhandeneZutaten();
*/
private:
/**
*a data strucuture(vector) containing all the available ingredients
as string variables
*/
std::vector<std::string> * zutaten;
/**
* a data structure (map) containing all availablie ingredients and amount
*/
std::unordered_multimap<std::string, float>* zutatenMap;
public:
/**
* Getter for ZutatenMap
* @return pointer to unordned_map
*/
std::unordered_multimap<std::string, float> *getZutatenMap() const;
private:
/**
* a static constant boolean variable for debugging
*/
static const bool DEBUG = false;
/**
*@brief reads the given text file for the ingredients
*@return void
*
*this function calls ZtatenDateiEinlesen() and adds special Ingredients
*/
void lesen();
/**
*@brief add a number of different zutaten into the list of zutaten
*/
//void DummyZutatenEinfuegen();
/**
*@brief reads the given ingredient file
*@param has a string-variable as parameter
*/
virtual void ZutatenDateiEinlesen(std::string);
/**
*@brief adds special ingredients Stampfen und Mischen to the Vector
*@return no returntype
*/
void addSpecial();
/**
* variable containing the number of Dosers in this CocktailPro
*/
int anzahlDosierer;
};
/**
* a static string variable holding the name of the file
*/
static std::string FileName;
#endif
| true |
11020354cff0cedebe737e4465b0227aa84c6611 | C++ | dgarciama/Primers-programes-Arduino | /05. Comunicació Sèrie Avançada/Prog.01/Prog.01.ino | UTF-8 | 1,125 | 2.53125 | 3 | [] | no_license | /**********************************************************************************
** **
** TÍTOL: 05. Comunicació Sèrie Avançada - Prog.01 **
** **
** NOM: Dennis Garcia DATA: 04/02/2019 **
**********************************************************************************/
//********** Includes *************************************************************
//********** Variables ************************************************************
int num = 64;
void setup() // run once, when the sketch starts
{
Serial.begin(9600); // set up Serial library at 9600 bps
Serial.println("Different formats for the same number:");
Serial.write(num);
Serial.println();
Serial.println(num);
Serial.println(num,DEC);
Serial.println(num,BIN);
Serial.println(num,HEX);
Serial.println(num,OCT);
}
void loop() // we need this to be here even though its empty
{
}
| true |
4134eac13a8ea45f67ccf5b9cf71836a939b98e3 | C++ | datracker/Evolutionary-Comp | /my_eval.cpp | UTF-8 | 433 | 3.296875 | 3 | [] | no_license | #include <iostream>
using namespace std;
string eval(int* x);
int main (){
string result = eval(x);
}
string eval(int* x){
int sum = 0;
for (int i = 0; i < 20; i++){
if (i%2 == 0 and x[i] == 1){
sum ++;
}
}
for (int i = 20; i < 50; i++){
if (i%2 == 1 and x[i] == 0){
sum ++;
}
}
if(x[23] and x [45] and x[78]){
sum += 100;
}
if(sum > 100){
return "Well done!";
}
else{
return "Try again";
}
} | true |
5515f6db38f1e1eeec9c533b3c41131d7ca3a058 | C++ | dg8fv2010/LeetCode | /238.cpp | UTF-8 | 1,255 | 3.8125 | 4 | [] | no_license | // 基本思路是用两个数组left和right,left保存从最左侧到当前数之前的所有数字的乘积,right保存从最右侧到当前之后的所有数字的乘积,
// 然后,结果数组就是把这两个数组对应位置相乘即可
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int len=nums.size();
vector<int> res;
if (len<2) return res;
vector<int> l;
l.resize(len);
vector<int> r;
r.resize(len);
l[0]=1;
r[len-1]=1;
for (int i=len-1;i>0;i--)
{
r[i-1]=r[i]*nums[i];
}
for (int i=0;i<len-1;i++)
{
l[i+1]=l[i]*nums[i];
}
for (int i=0;i<len;i++)
{
res.push_back(l[i]*r[i]);
}
return res;
}
};
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int len=nums.size();
vector<int> ans;
if (len<2)
{
return ans;
}
ans.resize(len);
ans[len-1]=1;
for (int i=len-1;i>0;i--)
{
ans[i-1]=ans[i]*nums[i];
}
int left=1;
for (int i=0;i<len;i++)
{
ans[i]*=left;
left*=nums[i];
}
return ans;
}
}; | true |
c442cafd2b43293642ebe19cc81d40c86c93c653 | C++ | dishankgoel/CodeChef-Solutions | /binadd.cpp | UTF-8 | 1,275 | 2.515625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main(){
int t;scanf("%d", &t);
while(t--){
string a,b;
cin>>a>>b;
int ans = 0;
if(b != "0"){
int n1 = a.length();
int n2 = b.length();
if(n1 > n2){
string to_append(n1-n2, '0');
b = to_append + b;
}else if(n2 > n1){
string to_append(n2-n1, '0');
a = to_append + a;
}
int n = max(n1,n2);
int ans = 0;
int curr = 0;int carry_on = 0;
for(int i=n-1;i>-1;i--){
if((a[i] == '1' && b[i] == '1' && carry_on == 1) || (a[i] == '0' && b[i] == '0' && carry_on == 1) ){
carry_on = 0;
ans = max(ans, curr);
curr = 0;
}else if( (a[i] == '1' && b[i] == '0' && carry_on == 1) || (a[i] == '0' && b[i] == '1' && carry_on == 1) ){
curr++;
}
if(a[i] == '1' && b[i] == '1' && carry_on == 0){
carry_on = 1;curr++;
}
}
ans = max(ans, curr);
cout<<ans+1<<"\n";
}else{
cout<<"0"<<"\n";
}
}
} | true |
5dfd3f3662e123d0035f0c726c6eb82b4823ea6a | C++ | vortydev/tp2-prog-a2020 | /TP2/assetManager.cpp | ISO-8859-1 | 821 | 2.921875 | 3 | [] | no_license | /*
* Author: tienne Mnard
* Date: 26/11/2020
* File: assetManager.cpp
* Description: Dfinition des mthodes de l'assetManager.
*/
#include "assetManager.h"
//load la texture et la met dans la map
void assetManager::loadTexture(string name, string fileName)
{
Texture tex;
if (tex.loadFromFile(fileName)) {
_textures[name] = tex;
}
}
//retourne la texture de la map correspondant au nom reu
Texture& assetManager::getTexture(string name)
{
return _textures.at(name);
}
//load la font et la met dans la map
void assetManager::loadFont(string name, string fileName)
{
Font font;
if (font.loadFromFile(fileName)) {
_fonts[name] = font;
}
}
//retourne la font de la map correspondant au nom recu
Font& assetManager::getFont(string name)
{
return _fonts.at(name);
} | true |
67b258b517f1236de5100b9d8d08faee69544634 | C++ | zhangyaqi1989/Python-Code-for-Competitive-Programming | /code/ch2/ch2_01_array_vector.cpp | UTF-8 | 761 | 3.703125 | 4 | [
"MIT"
] | permissive | #include <cstdio>
#include <vector>
using namespace std;
int main() {
int arr[5] = {7,7,7}; // initial size (5) and initial value {7,7,7,0,0}
vector<int> v(5, 5); // initial size (5) and initial value {5,5,5,5,5}
printf("arr[2] = %d and v[2] = %d\n", arr[2], v[2]); // 7 and 5
for (int i = 0; i < 5; i++) {
arr[i] = i;
v[i] = i;
}
printf("arr[2] = %d and v[2] = %d\n", arr[2], v[2]); // 2 and 2
// arr[5] = 5; // static array will generate index out of bound error
// uncomment the line above to see the error
v.push_back(5); // but vector will resize itself
printf("v[5] = %d\n", v[5]); // 5
return 0;
}
| true |
07f87809d094e9ef4b682828f51698011faeeb9b | C++ | anaguma2261/programming_study | /src/1_6_2.cpp | UTF-8 | 382 | 2.5625 | 3 | [] | no_license | #include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
int L = 10;
int n = 3;
int x[] = {2, 6, 7};
void solve() {
int minT = 0;
for(int i=0; i<n; i++){
minT = max(minT, min(x[i], L - x[i]));
}
int maxT = 0;
for(int i=0; i<n; i++){
maxT = max(maxT, max(x[i], L - x[i]));
}
printf("%d %d\n", minT, maxT);
}
int main() {
solve();
}
| true |
9b670e7ae8fc054a0ecd8eb2d3d839448c76e003 | C++ | Slidejiveman/Programming1 | /programming2Lab1/programming2Lab1/BubbleSort.cpp | UTF-8 | 1,232 | 3.578125 | 4 | [] | no_license | #include <iostream>
#include <fstream>
using namespace std;
//function prototypes
void sortArray(int[], int);
void showArray(const int[], int, ofstream&);
int main()
{
const int SIZE = 6;
ofstream outputFile;
outputFile.open("prgmAsn1.txt");
//array of unsorted values
int values[SIZE] = { 7, 2, 3, 8, 9, 1 };
//display the values
cout << "The unsorted values are: \n";
outputFile << "The unsorted values are: \n";
showArray(values, SIZE, outputFile);
//sort the values
sortArray(values, SIZE);
//display them again.
cout << "The sorted values are: \n";
outputFile << "The sorted values are: \n";
showArray(values, SIZE, outputFile);
return 0;
}
void sortArray(int values[], int SIZE)
{
bool swap;
int temp;
do
{
swap = false;
for (int count = 0; count < (SIZE - 1); count++)
{
if (values[count] > values[count + 1])
{
temp = values[count];
values[count] = values[count + 1];
values[count + 1] = temp;
swap = true;
}
}
} while (swap);
}
void showArray(const int values[], int SIZE, ofstream &outputFile)
{
for (int count = 0; count < SIZE; count++)
{
cout << values[count] << " ";
outputFile << values[count] << " ";
}
cout << endl;
outputFile << endl;
} | true |
abb568873098ccbeaf4fcfe2687121f9ae1a3b60 | C++ | DryRun/PFGAnalysis | /src/RBXMap.cc | UTF-8 | 9,116 | 2.640625 | 3 | [] | no_license | #include "HCALPFG/PFGAnalysis/interface/RBXMap.h"
#include <string>
#include <cstring>
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <iterator>
RBXMap::RBXMap():
m_hash_map_rbxstring ( 1600000, std::string("") ),
m_hash_map_rbxnumber ( 1600000, -1 ),
m_hash_map_fednumber ( 1600000, -1 ),
m_hash_map_rbxside ( 1600000, -1 ),
m_hash_map_hoIndex ( 1600000, -1 ),
m_hash_map_hbIndex ( 1600000, -1 ),
m_hash_map_heIndex ( 1600000, -1 ),
m_hash_map_hfIndex ( 1600000, -1 ),
m_hoIndex_to_hash ( 1600000, -1 ),
m_hbIndex_to_hash ( 1600000, -1 ),
m_heIndex_to_hash ( 1600000, -1 ),
m_hfIndex_to_hash ( 1600000, -1 )
{}
RBXMap::~RBXMap(){}
void RBXMap::PrintAllRBXs(){
PrintRBXs( 1 );
PrintRBXs( 2 );
PrintRBXs( 3 );
PrintRBXs( 4 );
// Ignore HOX
// PrintRBXs( 5 );
}
void RBXMap::PrintRBXs( int det_int ) {
std::string name;
std::vector<std::string> * rbxs = 0;
if ( det_int == 1 ) {
name = std::string("HB");
rbxs = & m_hb_rbx_names;
}
else if ( det_int == 2 ) {
name = std::string("HE");
rbxs = & m_he_rbx_names;
}
else if ( det_int == 3 ) {
name = std::string("HO");
rbxs = & m_ho_rbx_names;
}
else if ( det_int == 4 ) {
name = std::string("HF");
rbxs = & m_hf_rbx_names;
}
else if ( det_int == 5 ) {
name = std::string("HOX");
rbxs = & m_hox_rbx_names;
}
int n_rbx = rbxs -> size();
std::cout << "Loaded these "<< n_rbx << " " << name << " RBXs:" << std::endl;
for (int i = 0; i < n_rbx; ++i) {
std::cout << rbxs -> at(i) << "\t";
if ( (i+1) % 6 == 0 ) std::cout << std::endl;
}
std::cout << std::endl;
}
long RBXMap::getHash ( int det_int, int side, int ieta, int iphi, int depth ){
// side [1 digit], subdet [1 digit], eta [2 digits], phi [2 digits], depth [1 digit]
// Total of 7 digits: > 1 million addresses.
if (side == -1) side = 0;
long hash = 0;
hash += (side * 1000000);
hash += (det_int * 100000 );
hash += (ieta * 1000 );
hash += (iphi * 10 );
hash += (depth * 1 );
return hash;
}
int RBXMap::getDetInt ( const std::string & det ){
int det_int = -1;
if ( det.compare("HB" ) == 0 ) det_int = 1;
else if ( det.compare("HE" ) == 0 ) det_int = 2;
else if ( det.compare("HO" ) == 0 ) det_int = 3;
else if ( det.compare("HF" ) == 0 ) det_int = 4;
else if ( det.compare("HOX") == 0 ) det_int = 5;
else {
std::cout << "Don't understand this detector: " << det << std::endl;
return -1;
}
return det_int;
}
long RBXMap::getHash ( const std::string & det, int side, int ieta, int iphi, int depth ){
int det_int = getDetInt ( det ) ;
return getHash( det_int , side, ieta, iphi, depth );
}
std::string RBXMap::getRBXString( const std::string & det, int side, int ieta, int iphi, int depth ){
int hash = getHash ( det, side, ieta, iphi, depth );
return m_hash_map_rbxstring[hash];
}
int RBXMap::getIndex ( const std::string & det, int side, int ieta, int iphi, int depth ){
int hash = getHash ( det, side, ieta, iphi, depth );
if ( det.compare("HB") == 0 ) return m_hash_map_hbIndex[hash];
if ( det.compare("HE") == 0 ) return m_hash_map_heIndex[hash];
if ( det.compare("HO") == 0 ) return m_hash_map_hoIndex[hash];
if ( det.compare("HF") == 0 ) return m_hash_map_hfIndex[hash];
return -1;
}
int RBXMap::getIndex ( int det_int, int side, int ieta, int iphi, int depth ){
int hash = getHash ( det_int, side, ieta, iphi, depth );
if ( det_int == 1 ) return m_hash_map_hbIndex[hash];
if ( det_int == 2 ) return m_hash_map_heIndex[hash];
if ( det_int == 3 ) return m_hash_map_hoIndex[hash];
if ( det_int == 4 ) return m_hash_map_hfIndex[hash];
return -1;
}
void RBXMap::getCoordinates(int index, int det_int, int & side, int & ieta, int &iphi, int & depth ){
long hash = 0;
if ( det_int == 1 ) hash = m_hbIndex_to_hash[index];
if ( det_int == 2 ) hash = m_heIndex_to_hash[index];
if ( det_int == 3 ) hash = m_hoIndex_to_hash[index];
if ( det_int == 4 ) hash = m_hfIndex_to_hash[index];
depth = hash % 10;
iphi = (hash / 10) % 100;
ieta = (hash / 1000) % 100;
side = (hash / 1000000);
if ( side == 0 ) side = -1;
}
int RBXMap::getRBXNumber( const std::string & det, int side, int ieta, int iphi, int depth ){
int hash = getHash ( det, side, ieta, iphi, depth );
return m_hash_map_rbxnumber[hash];
}
int RBXMap::getRBXSide( const std::string & det, int side, int ieta, int iphi, int depth ){
int hash = getHash ( det, side, ieta, iphi, depth );
return m_hash_map_rbxside[hash];
}
std::string RBXMap::getRBXString( int det_int, int side, int ieta, int iphi, int depth ){
int hash = getHash ( det_int, side, ieta, iphi, depth );
return m_hash_map_rbxstring[hash];
}
int RBXMap::getRBXNumber( int det_int, int side, int ieta, int iphi, int depth ){
int hash = getHash ( det_int, side, ieta, iphi, depth );
return m_hash_map_rbxnumber[hash];
}
int RBXMap::getRBXSide( int det_int, int side, int ieta, int iphi, int depth ){
int hash = getHash ( det_int, side, ieta, iphi, depth );
return m_hash_map_rbxside[hash];
}
int RBXMap::getFEDNumber( const std::string & det, int side, int ieta, int iphi, int depth ){
int hash = getHash ( det, side, ieta, iphi, depth );
return m_hash_map_fednumber[hash];
}
int RBXMap::getFEDNumber( int det_int, int side, int ieta, int iphi, int depth ){
int hash = getHash ( det_int, side, ieta, iphi, depth );
return m_hash_map_fednumber[hash];
}
void RBXMap::LoadFile(const char* file_name){
std::fstream file(file_name, std::ios_base::in);
std::string line;
int iHB = 0;
int iHE = 0;
int iHO = 0;
int iHF = 0;
while ( std::getline(file, line)){
if (strncmp(&line[0],"#",1) == 0) continue;
std::istringstream iss(line);
std::vector<std::string> entries;
std::copy(std::istream_iterator<std::string>(iss),
std::istream_iterator<std::string>(),
std::back_inserter<std::vector<std::string> >(entries));
int side = std::stoi( entries[1] );
int ieta = std::stoi( entries[2] );
int iphi = std::stoi( entries[3] );
int depth = std::stoi( entries[5] );
std::string det = entries[6];
std::string rbx_name = entries[7];
int rbx_number = std::stoi( entries[7].substr(entries[7].size() - 2));
int fed_number = std::stoi( entries[entries.size() - 1] );
int rbx_side = 0;
std::string rbx_side_string;
rbx_side_string = rbx_name.substr(2, rbx_name.size());
rbx_side_string = rbx_side_string.substr(0, rbx_side_string.size() - 2);
if ( rbx_side_string.compare("2M") == 0 ) rbx_side = -2;
else if ( rbx_side_string.compare("1M") == 0 ) rbx_side = -1;
else if ( rbx_side_string.compare("0" ) == 0 ) rbx_side = 0;
else if ( rbx_side_string.compare("1P") == 0 ) rbx_side = 1;
else if ( rbx_side_string.compare("2P") == 0 ) rbx_side = 2;
else if ( rbx_side_string.compare("M") == 0 ) rbx_side = -1;
else if ( rbx_side_string.compare("P") == 0 ) rbx_side = 1;
int det_int = getDetInt ( det );
if ( det_int == 1 && std::find(m_hb_rbx_names .begin(), m_hb_rbx_names .end(), rbx_name )==m_hb_rbx_names .end() ) m_hb_rbx_names .push_back ( rbx_name );
else if ( det_int == 2 && std::find(m_he_rbx_names .begin(), m_he_rbx_names .end(), rbx_name )==m_he_rbx_names .end() ) m_he_rbx_names .push_back ( rbx_name );
else if ( det_int == 3 && std::find(m_ho_rbx_names .begin(), m_ho_rbx_names .end(), rbx_name )==m_ho_rbx_names .end() ) m_ho_rbx_names .push_back ( rbx_name );
else if ( det_int == 4 && std::find(m_hf_rbx_names .begin(), m_hf_rbx_names .end(), rbx_name )==m_hf_rbx_names .end() ) m_hf_rbx_names .push_back ( rbx_name );
else if ( det_int == 5 && std::find(m_hox_rbx_names.begin(), m_hox_rbx_names.end(), rbx_name )==m_hox_rbx_names.end() ) m_hox_rbx_names.push_back ( rbx_name );
int hash = getHash (det, side, ieta, iphi, depth);
m_hash_map_rbxstring[hash] = rbx_name;
m_hash_map_rbxnumber[hash] = rbx_number;
m_hash_map_fednumber[hash] = fed_number;
m_hash_map_rbxside [hash] = rbx_side;
if ( det.compare("HB") == 0 ){
m_hash_map_hbIndex[hash] = iHB;
m_hbIndex_to_hash[iHB] = hash;
iHB++;
}
else if ( det.compare("HE") == 0 ){
m_hash_map_heIndex[hash] = iHE;
m_heIndex_to_hash[iHE] = hash;
iHE++;
}
else if ( det.compare("HO") == 0 ){
m_hash_map_hoIndex[hash] = iHO;
m_hoIndex_to_hash[iHO] = hash;
iHO++;
}
else if ( det.compare("HF") == 0 ){
m_hash_map_hfIndex[hash] = iHF;
m_hfIndex_to_hash[iHF] = hash;
iHF++;
}
}
std::sort ( m_hb_rbx_names .begin(), m_hb_rbx_names .end());
std::sort ( m_he_rbx_names .begin(), m_he_rbx_names .end());
std::sort ( m_ho_rbx_names .begin(), m_ho_rbx_names .end());
std::sort ( m_hf_rbx_names .begin(), m_hf_rbx_names .end());
std::sort ( m_hox_rbx_names.begin(), m_hox_rbx_names.end());
}
| true |
b0169f083e7bf98916d022d11202657b48bf9b7a | C++ | samarcodes/Cpp-STL | /algorithms/sort.cpp | UTF-8 | 436 | 3.875 | 4 | [] | no_license | #include<iostream>
#include<algorithm>
using namespace std;
bool compare(int a, int b) {
return a > b;
}
int main() {
int a[] = {5, 2, 4, 3, 1};
int b[] = {5, 4, 3, 2, 1};
int n = 5;
sort(a, a + n); //ascending order
sort(b, b + n, compare); //descending order using a comparator
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << endl;
for (int i = 0; i < n; i++) {
cout << b[i] << " ";
}
cout << endl;
} | true |
2a930f8386ea0e4d2209b7d707a959c70af4e051 | C++ | HouCongCN/LeetCode_exercise | /771.宝石与石头.cpp | UTF-8 | 671 | 2.703125 | 3 | [
"MIT"
] | permissive | /*
* @Author: HouCong
* @Date: 2020-01-10 01:00:38
* @LastEditTime : 2020-01-10 01:07:51
* @Description: file content
* @FilePath: \LeetCode_exercise\771.宝石与石头.cpp
*/
/*
* @lc app=leetcode.cn id=771 lang=cpp
*
* [771] 宝石与石头
*/
// @lc code=start
#include <string>
#include <set>
using namespace std;
class Solution {
public:
int numJewelsInStones(string J, string S) {
set<char> gem;
int num = 0;
for (char c:J)
{
gem.insert(c);
}
for (char c:S)
{
if (gem.count(c) == 1)
num++;
}
return num;
}
};
// @lc code=end
| true |
d1b91f3972c6b41ccb5939b655796bbf4f0dfcd6 | C++ | fmidev/smartmet-library-spine | /spine/HTTPAuthentication.cpp | UTF-8 | 3,687 | 2.546875 | 3 | [
"MIT"
] | permissive | #include "HTTPAuthentication.h"
#include <boost/algorithm/string/case_conv.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/split.hpp>
#include <macgyver/Base64.h>
#include <macgyver/Exception.h>
#include <macgyver/TypeName.h>
namespace ba = boost::algorithm;
namespace SmartMet
{
namespace Spine
{
namespace HTTP
{
Authentication::Authentication(bool denyByDefault) : denyByDefault(denyByDefault) {}
Authentication::~Authentication() = default;
void Authentication::addUser(const std::string& name,
const std::string& password,
unsigned groupMask)
{
userMap[name] = std::make_pair(password, groupMask);
}
bool Authentication::removeUser(const std::string& name)
{
return userMap.erase(name) > 0;
}
void Authentication::clearUsers()
{
userMap.clear();
}
bool Authentication::authenticateRequest(const Request& request, Response& response)
{
try
{
auto credentials = request.getHeader("Authorization");
if (credentials)
{
std::vector<std::string> splitHeader;
ba::split(splitHeader, *credentials, ba::is_any_of(" "), ba::token_compress_on);
// printf("%s: Got credentials: %s\n", METHOD_NAME.c_str(), credentials->c_str());
if (splitHeader.size() < 2)
{
// Corrupt Authorization header - 400 Bad request
badRequestResponse(response);
return false;
}
if (ba::iequals(splitHeader.at(0), "basic"))
{
auto givenDigest = splitHeader.at(1);
unsigned groupMask = getAuthenticationGroup(request);
for (auto& item : userMap)
{
if ((item.second.second & groupMask) != 0)
{
auto trueDigest = Fmi::Base64::encode(item.first + ":" + item.second.first);
if (ba::iequals(trueDigest, givenDigest))
{
return true;
}
}
}
unauthorizedResponse(response);
return false;
}
// Not supported or invalid authentication type
badRequestResponse(response);
return false;
}
// Ask whether authentication is required for request if not provided there
if (!isAuthenticationRequired(request))
return true;
printf("%s: No credentials available\n", METHOD_NAME.c_str());
if (userMap.empty() and not denyByDefault)
return true;
unauthorizedResponse(response);
return false;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
bool Authentication::isAuthenticationRequired(const Request& request) const
{
(void)request;
return true;
}
unsigned Authentication::getAuthenticationGroup(const Request& request) const
{
(void)request;
return static_cast<unsigned>(-1);
}
std::string Authentication::getRealm() const
{
return "SmartMet server";
}
void Authentication::unauthorizedResponse(Response& response)
{
response.setStatus(Status::unauthorized);
response.setHeader("WWW-Authenticate", "Basic realm=\"" + getRealm() + "\"");
response.setHeader("Content-Type", "text/html; charset=UTF-8");
const std::string content = "<html><body><h1>401 Unauthorized </h1></body></html>\n";
response.setContent(content);
}
void Authentication::badRequestResponse(Response& response)
{
response.setStatus(Status::bad_request);
response.setHeader("WWW-Authenticate", "Basic realm=\"" + getRealm() + "\"");
response.setHeader("Content-Type", "text/html; charset=UTF-8");
const std::string content = "<html><body><h1>400 Bad request </h1></body></html>\n";
response.setContent(content);
}
} // namespace HTTP
} // namespace Spine
} // namespace SmartMet
| true |
c5e33a4c2edbb408b7c5bc3cd8ba76da5f0ad7e8 | C++ | zvova7890/lg-phone-develop | /gcc/Sources/LampFM/Core/TimerCounter.cpp | UTF-8 | 1,048 | 3.109375 | 3 | [] | no_license | #include "TimerCounter.h"
TimerCounter::TimerCounter(int initial_cout) :
m_value(initial_cout),
m_status(0)
{
m_comp = [](TimerCounter *tc) {
if(tc->value() > 65536)
return true;
return false;
};
m_vop = [](TimerCounter *tc) -> int {
return tc->value()+1;
};
}
void TimerCounter::start(int msec)
{
//if(m_status != 2) {
// m_value = 0;
//}
if(m_status) {
TimerCounter::stop();
}
Timer::start(msec);
m_status = 1;
}
void TimerCounter::pause()
{
if(m_status == 1) {
Timer::pause();
m_status = 2;
}
}
void TimerCounter::stop()
{
if(m_status) {
Timer::stop();
m_status = 0;
}
}
void TimerCounter::setFinalComp(std::function<bool (TimerCounter *)> f)
{
m_comp = f;
}
void TimerCounter::setValueOp(std::function<int (TimerCounter *)> f)
{
m_vop = f;
}
void TimerCounter::timerEvent()
{
if(m_comp(this)) {
stop();
return;
}
m_value = m_vop(this);
}
| true |
2434417be4c95a036c4072440385c1077f8037ca | C++ | hwangyukr/hwangyurithm | /DRAGON.cpp | UHC | 1,217 | 2.984375 | 3 | [] | no_license | // 4ð ̻,
#include <iostream>
#include <vector>
#include <string>
using namespace std;
typedef long long int INT;
const int MAXN = 50;
string FX = "FX";
INT nFunc(INT level) { // ̸ 迭 ð !
if (level == 0) return 1;
return nFunc(level-1) * 2 + 2;
}
char Func(string words, int n, INT &m) {
if (n == 0) {
// m < 5 ΰ ?
return words[m];
}
for (int i = 0; i < words.size(); i++) {
char iter = words[i];
string expandor = "";
if (iter == 'X') expandor = "X+YF";
if (iter == 'Y') expandor = "FX-Y";
if (iter == 'X' || iter == 'Y') {
INT len = nFunc(n);
if (m >= len) {
m -= len;
continue;
}
return Func(expandor, n - 1, m);
}
else {
if (m > 0) m--;
else return iter;
}
}
return ' ';
}
int main() {
int T; cin >> T;
for (int test_case = 1; test_case <= T; test_case++) {
INT n, p, l; cin >> n >> p >> l;
int left = p - 1;
int right = left + l - 1;
for (int i = left; i <= right; i++) {
INT dup = i;
char ret = Func("FX", n, dup);
cout << ret;
}
cout << endl;
}
return 0;
} | true |
7d0d6b34816a47c7f126adddd24bcc3029dfd31a | C++ | ekesel/450DSA | /C++/Linked_List/detect and remove loop.cpp | UTF-8 | 1,152 | 3.46875 | 3 | [
"Apache-2.0"
] | permissive | #include <bits/stdc++.h>
using namespace std;
struct Node{
int data;
Node* next;
Node(int x){
data=x;
next=NULL;
}
};
void detectRemoveLoop(Node* head)
{
Node *slow = head, *fast = head;
while (fast!=NULL && fast->next!=NULL) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
break;
}
}
if (slow == fast)
{
slow = head;
if(slow == fast) {
while(fast->next != slow) fast = fast->next;
}
else {
while (slow->next != fast->next) {
slow = slow->next;
fast = fast->next;
}
}
fast->next = NULL; /* remove loop */
}
}
void display(Node* head)
{
while(head)
{
cout<<head->data<<"--->";
head=head->next;
}
cout<<"NULL"<<"\n";
}
int main()
{
Node *head=new Node(15);
head->next=new Node(10);
head->next->next=new Node(12);
head->next->next->next=new Node(20);
head->next->next->next->next=head->next;
// display(head);
detectRemoveLoop(head);
// return 0;
display(head);
}
| true |
7f20ef3ddc99204d0589b5af941850262fe43b25 | C++ | lgkimjy/Control | /Impedance/Impedance.ino | UTF-8 | 2,398 | 2.65625 | 3 | [] | no_license | #include <TimerFive.h>
//Pin define
#define MA_DIR 12
#define MA_PWM 10
#define PT_ENC A0
#define PT_REF A1
#define LED 3
// Global variables
int loop_flag = 0;
int loop_chk = 0;
unsigned int t5_index = 0;
unsigned int first_t = 1;
int enc_val;
int ref_val;
// variables for Control
int err_k = 0;
int err_k_1 = 0;
int derr_k = 0;
int Kp = 60;
int Kd = 150;
//int Kp = 100;
//int Kd = 150;
int Up = 0;
int Ud = 0;
long sU = 0;
float fU = 0.0;
int uU = 0;
void setup() {
pinMode(MA_DIR, OUTPUT);
pinMode(MA_PWM, OUTPUT);
pinMode(PT_ENC, INPUT);
pinMode(PT_REF, INPUT);
pinMode(LED, OUTPUT);
Timer5.initialize(1000); //Timer interrupt - time setup (1000 usec)
Timer5.attachInterrupt(Timer5_ISR);
Serial.begin (230400);
}
void loop(){
//just 1 time excute
if(first_t){
first_t = 0;
t5_index = 0;
loop_flag = 0;
}
if(loop_flag){ //loop time 1msec
loop_flag = 0;
switch(t5_index){
case 0:
Serial.println("--------------------------------");
break;
case 1:
ref_val = analogRead(PT_REF);
ref_val = map(ref_val, 0, 1023, -500, 500);
Serial.print("ref potentio-meter : ");
Serial.println(ref_val);
break;
case 2:
// Read the potentio-meter of encoder
enc_val = analogRead(PT_ENC);
enc_val = map(enc_val, 0, 1023, -500, 500);
Serial.print("enc potentio-meter : ");
Serial.println(enc_val);
err_k = ref_val - enc_val;
//err_k = 0 - enc_val;
derr_k = err_k - err_k_1;
err_k_1 = err_k;
break;
case 3:
// Control
Up = Kp * err_k;
Ud = Kd * derr_k;
sU = (long)Up + (long)Ud;
fU = (float)sU / 50.0;
uU = (int)fU;
break;
case 4:
//
break;
case 5: //Control loop : 5mSec
t5_index = 0;
loop_chk ^= 1;
if(uU > 255) uU = 255;
else if(uU <-255) uU = -255;
if(uU >= 0){
digitalWrite(MA_DIR, HIGH);
}
else{
uU *= -1;
digitalWrite(MA_DIR, LOW);
}
analogWrite(MA_PWM, uU);
digitalWrite(LED, loop_chk);
break;
default:
t5_index = 0;
break;
}
}//end of time-loop
//Idle
}
void Timer5_ISR(){
loop_flag = 1;
t5_index++;
}
| true |
c11a02f69afda2f9af1c3a29662286de34cf5a15 | C++ | leftCoast/Arduino | /Double_blink_test/Double_blink_test.ino | UTF-8 | 6,419 | 2.921875 | 3 | [] | no_license | #include "blinker.h"
#include "idlers.h"
class delayWave : public blinker {
public:
enum waveState { startingUp, changingDelay, sitting, running };
delayWave(int pin1,int pin2,float pulseMs,float periodMs,float delayMs);
~delayWave(void);
void setDelay(float delayMs);
void startStop(bool onOff);
protected:
void startCycle(void);
virtual void pulseOn(void);
virtual void idle();
waveState mWaveState;
blinker* mSecondLED;
float mMinDelay;
float mMaxDelay;
timeObj mDelay;
float mDelayMs;
};
delayWave::delayWave(int pin1,int pin2,float pulseMs,float periodMs,float delayMs)
: blinker(pin1,pulseMs,periodMs) {
mSecondLED = new blinker(pin2,pulseMs,periodMs); // Second blinker.
mMinDelay = pulseMs; // Calculate our minimum delay.
mMaxDelay = periodMs - 2*pulseMs; // Calculate our maximum delay.
mDelayMs = 0; //
mWaveState = sitting; // Well, we're are.
setDelay(delayMs); // Calculate our initial delay setting.
}
// If we have the second blinker, recycle it.
delayWave::~delayWave(void) { if (mSecondLED) delete(mSecondLED); }
// User wants to delay the second wave differently.. We'll take note of it for later.
void delayWave::setDelay(float delayMs) {
if (delayMs<mMinDelay) { // Sanity first. If delayMs is less than the minimum linit..
delayMs = mMinDelay; // Set it to the minimum limit.
} else if (delayMs>mMaxDelay) { // If delayMs is greater than the max linit..
delayMs = mMaxDelay; // Set it to the max limit.
}
if (delayMs!=mDelayMs) { // Now, if its different than what we are running now..
mDelayMs = delayMs; // Set in the new number.
switch (mWaveState) { // Check the state we are in.
case startingUp : // We're already starting up..
case running : // Or we're running..
mWaveState = changingDelay; // Note change to be caught when our pulse is complete.
break; // And we are done.
case changingDelay : // Already noted I see..
case sitting : break; // Or we are just sitting? Don't need to do anything more.
}
}
}
// User switch for turning this thing on or off.
void delayWave::startStop(bool onOff) {
if (onOff) { // They want to turn us on. Eww!
hookup(); // When it comes on, we need to hook into the idle queue.
switch (mWaveState) { // Check the state we are in.
case startingUp : // We're already starting up, be patient.
case changingDelay : // Again, what with this? We're already running.
case running : break; // Duh! running. (all these cases we do nohing.)
case sitting : // Ok, in this case, call the startCycle() method.
startCycle(); // This fires up the start sequence,
break; // And we're done.
}
} else { // Else, they want us gone, Aww..
setOnOff(false); // Shut down ourselves.
mSecondLED->setOnOff(false); // Shut down the second blinker.
mWaveState = sitting; // Note we're off.
}
}
// Trapping when the pulse completes so we can change the delay. (if needed)
void delayWave::pulseOn(void) {
blinker::pulseOn(); // Our pulse is over, let our ancestor do their stuff.
if (mWaveState==changingDelay) { // if we need to change the delay of the second signal..
mDelay.setTime(mDelayMs+mNextPulse,true); // Fire up our delay timer. (Using mNextPulse is a hack, sorry.)
mWaveState = startingUp; // Note what we're up to for the guys downstairs.
}
}
// We don't really care what's going on, just start things up.
// We first shut things down if they are on. Then do the start up routine.
void delayWave::startCycle(void) {
Serial.println("Our State.");
printState();
Serial.println("Second state.");
mSecondLED->printState();
setOnOff(false); // Shut off the first blinker. (ourselves)
mSecondLED->setOnOff(false); // Shut down the second blinker.
setOnOff(true); // Fire up the first blinker. (ourselves)
mDelay.setTime(mDelayMs,true); // Fire up our delay timer. Just the length of the delay.
mWaveState = startingUp; // Note what we're up to for the guys downstairs.
Serial.println("-----");
Serial.println("Our State.");
printState();
Serial.println("Second state.");
mSecondLED->printState();
}
void delayWave::idle() {
blinker::idle(); // Ancester goes first, we did bypass the poor thing.
switch(mWaveState) { // Check our state..
case sitting : // Sitting? Do nothing.
case running : break; // Running? The acestor dealt with that.
case startingUp : // Starting up? We need to deal with this.
if (mDelay.ding()) { // If the dealy timer dinged..
mSecondLED->setOnOff(true); // Fire up the second blinker.
mWaveState = running; // Set our state to running.
}
break; // A good days work completed..
case changingDelay : break; // We ignore this too, coming off the pulse will take action in this case.
}
}
delayWave* ourWaveObj;
void setup() {
Serial.println("---\\\ In setup, calling delayWave();\\\---");Serial.flush(); ourWaveObj = new delayWave(13,16,2000,8000,3000);
Serial.println("---\\\ In setup, calling startStop();\\\---");Serial.flush(); ourWaveObj->startStop(true);
}
void loop() {
//idle();
// Do whatever else you want. Just NOT delay();
}
| true |
30c79fa2a5791fccacb883a893844a67b5db3877 | C++ | zcxsythenew/AVLTree | /AVLTree/Binary_node.h | UTF-8 | 113 | 2.546875 | 3 | [] | no_license | #pragma once
template <class Entry>
struct Binary_node
{
Entry data;
Binary_node *left;
Binary_node *right;
}; | true |
a6caaf316d570e58d72feff239bfcf615b219a0a | C++ | AnibalSiguenza/effectiveModernCppNotes | /item12-sideKnowledge.cpp | UTF-8 | 1,590 | 3.484375 | 3 | [] | no_license | // In item 12 is also discused the concept of reference qualifier, but since
// it's quite independent I decided to explain it in this file
#include <bits/stdc++.h>
#include "TestClass.hpp"
class Foo {
private:
TestClass tc;
public:
Foo(std::string name) : tc(name){};
TestClass &getData() { return tc; }
~Foo(){};
};
class Bar {
private:
TestClass tc;
public:
Bar(std::string name) : tc(name){};
// the reference qualifier & at the end indicates that this will apply for
// lvalues of (*this)
TestClass &getData() & { return tc; }
// the reference qualifier && at the end indicates that this will apply for
// rvalues of (*this)
TestClass &&getData() && { return std::move(tc); }
~Bar(){};
};
int main(int argc, char *argv[]) {
Foo f("fInstance");
Bar b("bInstance");
// The next 2 lines both call the copy constructor even though one is
// receiving the data from an lvalue and the other one from an rvalue
auto rec1 = f.getData(); // rec1 receives data from an lvalue, and calls copy
// constructure
auto rec2 = Foo("fRValue").getData(); // rec2 receies data from an rvalue, and
// calls COPY constructure
// Here they will behave different depending if (*this) is rvalue or lvalue.
auto rec3 = b.getData(); // rec1 receives data from an lvalue, and calls copy
// constructure
auto rec4 = Bar("bRValue").getData(); // rec2 receies data from an rvalue, and
// calls MOVE constructure
return 0;
} | true |
a88ad1877c649e1561cb551c9f9692213d61a861 | C++ | LiseR18/Knocki | /Code/eeprom_test.ino | UTF-8 | 976 | 3.171875 | 3 | [] | no_license | #include <EEPROM.h>
int eeprom_readout[] = {};
void setup() {
Serial.begin(9600);
//Commenter et décommenter les lignes pour écrire ou lire la mémoire
//writeInts();
readInts();
}
void loop() {
// put your main code here, to run repeatedly:
}
void writeInts() {
int addr = 0; //l'adresse de l'octet courant
while (addr < EEPROM.length()) { //tant qu'il reste des octets à
int rand_val = random(0, 256);
Serial.println(rand_val);
EEPROM.write(addr, rand_val); //on écrit à l'adresse de l'octet un nombre entre 0 et 255
addr += 1; //on passe à l'octet suivant
}
}
void readInts() {
int addr = 0; //l'adresse de l'octet courant
while (addr < EEPROM.length()) { //tant qu'il reste des octets à lire
int value = EEPROM.read(addr); //on lit l'octet à l'adresse actuelle
Serial.println(value);
eeprom_readout[addr] = value; //on ajoute cette valeur à notre tableau
addr += 1; //on passe à l'octet suivant
}
}
| true |
3649039c294083907f1a2405506677c25c08b8c6 | C++ | yisea123/Automa | /AutomaLib/include/DLine.h | BIG5 | 724 | 2.59375 | 3 | [] | no_license | #pragma once
#include "Coordinate.h"
#include <Math.h>
namespace AutoLib {
class DLine
{
public:
DLine(void);
~DLine(void);
DCoordinate PA,PB;
double GetAtan();
DLine Rotation(const double dblS);
double GetLength(){return sqrt((PA.x-PB.x)*(PA.x-PB.x)+(PA.y-PB.y)*(PA.y-PB.y));};
DCoordinate GetCenter(){return DCoordinate((PA.x+PB.x)/2,(PA.y+PB.y)/2,0,0);};
double GetLineSlope();
double GetMidLineSlope();
bool IsMidLineSlopeInfinite(){return (m_MiddleLineVertical);};
bool IsLineSlopeInfinite(){return (m_LineVertical);};
DCoordinate CalOffset(DLine dlTarget,DCoordinate dcRotationCenter);
private:
bool m_LineVertical; // uPA,PB.
bool m_MiddleLineVertical; // u.
};
}//namespace MacLib | true |
d5d15e3944a1de0c4a44bbf41e0f1164b096c00e | C++ | sikey647/algorithm008-class01 | /Week_03/practice/SingleNumberIII.cpp | UTF-8 | 571 | 3.109375 | 3 | [] | no_license | /*
* @lc app=leetcode.cn id=260 lang=cpp
*
* [260] 只出现一次的数字 III
*/
// @lc code=start
#include <vector>
using namespace std;
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
vector<int> res(2, 0);
int mask = 0, diff = 0;
for (auto num : nums)
mask ^= num;
diff = mask & (-mask);
for (auto num : nums) {
if (num & diff)
res[0] ^= num;
else
res[1] ^= num;
}
return res;
}
};
// @lc code=end
| true |
473f7087543e5d684c1c8a289a225dab3f02443f | C++ | Frapschen/Cdamo | /C progarm project/PracticeMain.cpp | GB18030 | 1,918 | 2.96875 | 3 | [] | no_license | //ϵͳͷļ
#include "stdio.h"
#include "conio.h"
#include "stdlib.h"
//Զͷļ
#include "HeadFile/practice1.h"
#include "HeadFile/practice2.h"
#include "HeadFile/practice3.h"
#include "HeadFile/practice4.h"
#include "HeadFile/practice5.h"
#include "HeadFile/practice6.h"
#include "HeadFile/practice7.h"
#include "HeadFile/practice8.h"
int MainDisplayMenu();//ʾ
int main()
{
int key;//ü
for (;;)
{
key = MainDisplayMenu();//Ŀ̲˵
switch (key)
{
case 1:
practice1();
break;
case 2:
practice2();
break;
case 3:
practice3();
break;
case 4:
practice4();
break;
case 5:
practice5();
break;
case 6:
practice6();
break;
case 7:
practice7();
break;
case 8:
practice8();
break;
case 9:
printf("ллʹã");
getch();
exit(0);
default:
printf("밴.....");
getch();
break;
}
}
return 0;
}
void MainDisplay()
{
}
int MainDisplayMenu()
{
int key;
system("cls");
printf("**********CۺʵսĿ˵**********\n");
printf("***** 1. ʵս1ģչʾ *****\n");
printf("***** 2. ʵս2ģչʾ *****\n");
printf("***** 3. ʵս3ģչʾ *****\n");
printf("***** 4. ʵս4ģչʾ *****\n");
printf("***** 5. ʵս5ģչʾ *****\n");
printf("***** 6. ʵս6ģչʾ *****\n");
printf("***** 7. ʵս7ģչʾ *****\n");
printf("***** 8. ʵս8ģչʾ *****\n");
printf("***** 9. ˳ *****\n");
printf("빦ܺţ");
scanf("%d", &key);
return key;
}
| true |
124725e1e03846406e73a54f33294e08b29facf8 | C++ | nickamor/fruitconda | /src/gameplay.cc | UTF-8 | 17,353 | 2.609375 | 3 | [
"MIT"
] | permissive | /*
* gameplay.c
*
* Created on: Aug 30, 2011
* Author: nick
*/
#include "gameplay.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "state.h"
#include "util.h"
#include "menu.h"
#include "input.h"
#define GAME_PI 3.141592
char *pausemenu_items[2] =
{"Retry", "Quit"};
struct menu_s pause_menu =
{2, 0, "Paused", pausemenu_items};
gameplay_state_t gameplay_state;
int
collide(struct snake_t *snake) {
int collide_wall = 0;
int collide_snake = 0;
collide_wall = level_tile(gameplay_state.level, snake->x, snake->y);
list_t *iter = snake->body;
while (iter) {
struct snake_piece_s *iter_p = (snake_piece_s *)iter->data;
if (snake->x == iter_p->x && snake->y == iter_p->y) {
collide_snake = 1;
break;
}
iter = iter->next;
}
return collide_wall || collide_snake;
}
void
gameplay_init() {
// initialise gameplay_state
gameplay_state.paused = 0;
gameplay_state.rotating = 0;
if (gameplay_state.level) {
gameplay_state.snake_1.x = gameplay_state.level->w / 2;
gameplay_state.snake_1.y = gameplay_state.level->h / 2;
}
gameplay_state.snake_1.dead = 0;
gameplay_state.snake_1.r = 0;
gameplay_state.snake_1.l = 0;
gameplay_state.snake_1.m = 5;
gameplay_state.snake_1.score = 0;
gameplay_state.tiles_info.tile_size = 16;
memset(&gameplay_state.bitmap_tiles, 0, sizeof(bitmap_t));
memset(&gameplay_state.bitmap_snake, 0, sizeof(bitmap_t));
bitmap_from_file(&gameplay_state.bitmap_tiles, "assets/graphics/tileset1.png",
"tileset1");
bitmap_from_file(&gameplay_state.bitmap_snake, "assets/graphics/snake.png",
"snake");
gameplay_state.board.r_time = 0.0;
gameplay_state.board.r_time_max = 0.25;
gameplay_state.board.r = 0;
}
void
gameplay_cleanup() {
snakebody_destroy(gameplay_state.snake_1.body);
gameplay_state.snake_1.body = NULL;
bitmap_cleanup(&gameplay_state.bitmap_tiles);
bitmap_cleanup(&gameplay_state.bitmap_snake);
}
void
gameplay_pause() {
gameplay_state.paused = 1;
}
void
gameplay_resume() {
gameplay_state.paused = 0;
}
void
pausemenu_input() {
if (input_state.up) {
menu_change_selection(&pause_menu, -1);
} else if (input_state.down) {
menu_change_selection(&pause_menu, 1);
} else if (input_state.button_action) {
switch (pause_menu.selection) {
case 1:
change_state(mainmenu);
break;
default:
change_state(gameplay);
break;
}
} else if (input_state.button_back) {
gameplay_state.paused = 0;
}
}
void
gameplay_input() {
if (input_state.button_pause) {
if (!gameplay_state.paused) {
game_state.state_pause();
} else {
game_state.state_resume();
}
return;
}
if (gameplay_state.paused) {
pausemenu_input();
} else {
if (gameplay_state.snake_1.dead)
return;
if (input_state.left && !gameplay_state.rotating) {
snake_turn(&gameplay_state.snake_1, 1);
} else if (input_state.right && !gameplay_state.rotating) {
snake_turn(&gameplay_state.snake_1, -1);
} else if (input_state.button_back) {
change_state(nullstate);
}
}
}
double snake_dead_anim = 0.0, snake_dead_anim_max = 2.0;
void
gameplay_update(double delta_time) {
if (!(gameplay_state.paused | gameplay_state.rotating)) {
if (!gameplay_state.snake_1.dead) {
snake_update(&gameplay_state.snake_1, delta_time);
} else {
if (snake_dead_anim < snake_dead_anim_max) {
snake_dead_anim += delta_time;
} else {
snake_dead_anim = 0.0;
change_state(gameplay);
}
}
}
}
void
pausemenu_draw() {
menu_draw(&pause_menu, 50, 50);
}
/**
* Decides what should be drawn
*/
void
gameplay_draw(double delta_time) {
if (gameplay_state.level) {
gameboard_draw(delta_time);
}
if (gameplay_state.paused) {
pausemenu_draw();
}
}
/** void draw_gameboard()
* draw the current level
*/
void
gameboard_draw(double delta_time) {
int ts = gameplay_state.tiles_info.tile_size;
struct board_state_t *b = &gameplay_state.board;
int level_width = gameplay_state.level->w;
int level_height = gameplay_state.level->h;
bitmap_t buffer_board;
bitmap_t buffer;
bitmap_create(&buffer_board, ts * level_width, ts * level_height);
bitmap_get_target(&buffer);
bitmap_set_target(&buffer_board);
level_draw(gameplay_state.level, 0, 0);
snake_draw(&gameplay_state.snake_1);
bitmap_set_target(&buffer);
/* rotate the board */
double r = (GAME_PI / 2) * b->r;
int snake_delta_r = gameplay_state.snake_1.r - b->r;
if (snake_delta_r > 1) {
snake_delta_r = -1;
} else if (snake_delta_r < -1) {
snake_delta_r = 1;
}
if (snake_delta_r != 0) {
gameplay_state.rotating = 1;
b->r_time += delta_time;
double r_max = (GAME_PI / 2) * snake_delta_r;
double r_degree = (-cos(b->r_time / b->r_time_max) + 1) * 2;
double delta_r = r_max * r_degree;
r += delta_r;
if (b->r_time > b->r_time_max) {
b->r_time = 0.0;
b->r = gameplay_state.snake_1.r;
}
} else {
gameplay_state.rotating = 0;
}
// draw rotated board - cx, cy: the center of the board bitmap
// bx, by: where to draw the board
int cx = buffer_board.w / 2;
int cy = buffer_board.h / 2;
int bx = gameplay_state.video_settings->width / 2;
int by = gameplay_state.video_settings->height / 2;
bitmap_draw_rotated(&buffer_board, cx, cy, bx, by, r, 0);
bitmap_cleanup(&buffer_board);
}
/** void snake_add()
* updates the snake body position
*/
void
snake_add() {
struct snake_piece_s* new_snake = (snake_piece_s *)safe_malloc(sizeof(struct snake_piece_s));
new_snake->x = gameplay_state.snake_1.x;
new_snake->y = gameplay_state.snake_1.y;
new_snake->r = gameplay_state.snake_1.r;
gameplay_state.snake_1.body = list_push(gameplay_state.snake_1.body,
(void *) new_snake);
++gameplay_state.snake_1.l;
// enforce maximum length
while (gameplay_state.snake_1.l >= gameplay_state.snake_1.m) {
list_t *tail = list_foot(gameplay_state.snake_1.body);
// ... by chopping off any extra bits
tail->prev->next = NULL;
free(tail->data);
free(tail);
--gameplay_state.snake_1.l;
}
}
/** void snake_destroy()
* free the snake-body-occupied memory
*/
void
snakebody_destroy(list_t *snakebody) {
list_t *iter = snakebody;
while (iter) {
list_t *next_iter = iter->next;
if (iter->data) {
free(iter->data);
}
free(iter);
iter->next = NULL;
iter = next_iter;
}
}
void
snake_draw(struct snake_t *snake) {
int ts = gameplay_state.tiles_info.tile_size;
bitmap_t *snake_gfx = &gameplay_state.bitmap_snake;
// dead blink animation
if (snake->dead) {
if (((int) (snake_dead_anim * 8) % 2) == 0) {
return;
}
}
if (gameplay_state.snake_1.body) {
int c_up = 0, c_down = 0, c_left = 0, c_right = 0;
int nx, ny;
nx = ((struct snake_piece_s *) gameplay_state.snake_1.body->data)->x;
ny = ((struct snake_piece_s *) gameplay_state.snake_1.body->data)->y;
// handle looped parts
if (nx == 0 && snake->x == gameplay_state.level->w - 1) {
nx = snake->x + 1;
}
if (ny == 0 && snake->y == gameplay_state.level->h - 1) {
ny = snake->y + 1;
}
if (nx == gameplay_state.level->w - 1 && snake->x == 0) {
nx = snake->x - 1;
}
if (ny == gameplay_state.level->h - 1 && snake->y == 0) {
ny = snake->y - 1;
}
// which way is the next piece
if (nx < snake->x) {
c_left = 1;
}
if (nx > snake->x) {
c_right = 1;
}
if (ny < snake->y) {
c_up = 1;
}
if (ny > snake->y) {
c_down = 1;
}
// draw snake head
if (snake->r == 0) {
if (c_down) {
bitmap_draw_region(snake_gfx, 0, 0, ts, ts, snake->x * ts,
snake->y * ts, 0);
}
if (c_left) {
bitmap_draw_region(snake_gfx, 0, 16, ts, ts, snake->x * ts,
snake->y * ts, 0);
}
if (c_right) {
bitmap_draw_region(snake_gfx, 0, 32, ts, ts, snake->x * ts,
snake->y * ts, 0);
}
}
if (snake->r == 1) {
if (c_right) {
bitmap_draw_region(snake_gfx, 16, 0, ts, ts, snake->x * ts,
snake->y * ts, 0);
}
if (c_down) {
bitmap_draw_region(snake_gfx, 16, 16, ts, ts, snake->x * ts,
snake->y * ts, 0);
}
if (c_up) {
bitmap_draw_region(snake_gfx, 16, 32, ts, ts, snake->x * ts,
snake->y * ts, 0);
}
}
if (snake->r == 2) {
if (c_up) {
bitmap_draw_region(snake_gfx, 32, 0, ts, ts, snake->x * ts,
snake->y * ts, 0);
}
if (c_left) {
bitmap_draw_region(snake_gfx, 32, 16, ts, ts, snake->x * ts,
snake->y * ts, 0);
}
if (c_right) {
bitmap_draw_region(snake_gfx, 32, 32, ts, ts, snake->x * ts,
snake->y * ts, 0);
}
}
if (snake->r == 3) {
if (c_left) {
bitmap_draw_region(snake_gfx, 48, 0, ts, ts, snake->x * ts,
snake->y * ts, 0);
}
if (c_up) {
bitmap_draw_region(snake_gfx, 48, 16, ts, ts, snake->x * ts,
snake->y * ts, 0);
}
if (c_down) {
bitmap_draw_region(snake_gfx, 48, 32, ts, ts, snake->x * ts,
snake->y * ts, 0);
}
}
} else {
switch (snake->r) {
case 0:
bitmap_draw_region(snake_gfx, 0, 48, ts, ts, snake->x * ts,
snake->y * ts, 0);
break;
case 1:
bitmap_draw_region(snake_gfx, 16, 48, ts, ts, snake->x * ts,
snake->y * ts, 0);
break;
case 2:
bitmap_draw_region(snake_gfx, 32, 48, ts, ts, snake->x * ts,
snake->y * ts, 0);
break;
case 3:
bitmap_draw_region(snake_gfx, 48, 48, ts, ts, snake->x * ts,
snake->y * ts, 0);
break;
}
}
// draw snake body
list_t *iter;
iter = snake->body;
while (iter) {
int sx = ((struct snake_piece_s *) iter->data)->x;
int sy = ((struct snake_piece_s *) iter->data)->y;
int c = snakebody_bitmask(iter);
switch (c) {
case 1: // Bottom End
bitmap_draw_region(snake_gfx, 0, 64, ts, ts, sx * ts, sy * ts, 0);
break;
case 2: // Right End
bitmap_draw_region(snake_gfx, 16, 64, ts, ts, sx * ts, sy * ts, 0);
break;
case 3: // Bottom-Right
bitmap_draw_region(snake_gfx, 32, 64, ts, ts, sx * ts, sy * ts, 0);
break;
case 4: // Left End
bitmap_draw_region(snake_gfx, 48, 64, ts, ts, sx * ts, sy * ts, 0);
break;
case 5: // Bottom-Left
bitmap_draw_region(snake_gfx, 0, 80, ts, ts, sx * ts, sy * ts, 0);
break;
case 6: // Left-Right
bitmap_draw_region(snake_gfx, 16, 80, ts, ts, sx * ts, sy * ts, 0);
break;
case 8: // Top End
bitmap_draw_region(snake_gfx, 32, 80, ts, ts, sx * ts, sy * ts, 0);
break;
case 9: // Top-Down
bitmap_draw_region(snake_gfx, 48, 80, ts, ts, sx * ts, sy * ts, 0);
break;
case 10: // Top-Right
bitmap_draw_region(snake_gfx, 0, 96, ts, ts, sx * ts, sy * ts, 0);
break;
case 12: // Top-Left
bitmap_draw_region(snake_gfx, 16, 96, ts, ts, sx * ts, sy * ts, 0);
break;
}
iter = iter->next;
}
}
/* for a given snake-body-part, how do we draw it? */
enum snakebody_bit {
bit_up = 8, bit_left = 4, bit_right = 2, bit_down = 1
};
int
snakebody_bitmask(list_t *bodypart) {
int up = 0, down = 0, left = 0, right = 0;
int bitmask = 0;
int this_x, this_y, prev_x, prev_y, next_x, next_y;
this_x = ((struct snake_piece_s *) bodypart->data)->x;
this_y = ((struct snake_piece_s *) bodypart->data)->y;
// if this bodypart is the first body part, the prev is actually the head
if (bodypart->prev != NULL) {
prev_x = ((struct snake_piece_s *) bodypart->prev->data)->x;
prev_y = ((struct snake_piece_s *) bodypart->prev->data)->y;
} else {
prev_x = gameplay_state.snake_1.x;
prev_y = gameplay_state.snake_1.y;
}
// handle bodyparts on the other side of the board due to looping
if (this_x == 0 && prev_x == gameplay_state.level->w - 1) {
prev_x = this_x - 1;
}
if (this_y == 0 && prev_y == gameplay_state.level->h - 1) {
prev_y = this_y - 1;
}
if (this_x == gameplay_state.level->w - 1 && prev_x == 0) {
prev_x = this_x + 1;
}
if (this_y == gameplay_state.level->h - 1 && prev_y == 0) {
prev_y = this_y + 1;
}
// add prev to bitmask
if (prev_y < this_y) {
up = 1;
}
if (prev_y > this_y) {
down = 1;
}
if (prev_x < this_x) {
left = 1;
}
if (prev_x > this_x) {
right = 1;
}
if (bodypart->next) {
next_x = ((struct snake_piece_s *) bodypart->next->data)->x;
next_y = ((struct snake_piece_s *) bodypart->next->data)->y;
// handle bodyparts on the other side of the board due to looping
if (this_x == 0 && next_x == gameplay_state.level->w - 1) {
next_x = this_x - 1;
}
if (this_y == 0 && next_y == gameplay_state.level->h - 1) {
next_y = this_y - 1;
}
if (this_x == gameplay_state.level->w - 1 && next_x == 0) {
next_x = this_x + 1;
}
if (this_y == gameplay_state.level->h - 1 && next_y == 0) {
next_y = this_y + 1;
}
// add next to bitmask
if (next_y < this_y) {
up = 1;
}
if (next_y > this_y) {
down = 1;
}
if (next_x < this_x) {
left = 1;
}
if (next_x > this_x) {
right = 1;
}
}
bitmask = (up * bit_up) + (left * bit_left) + (right * bit_right)
+ (down * bit_down);
return bitmask;
}
/*
* move the snake
*/
double snake_update_primer = 0.0, snake_update_max = 1.0;
int difficulty = 2;
void
snake_update(struct snake_t *snake, double delta_time) {
/* only move snake every some many updates */
snake_update_primer += delta_time;
if (snake_update_primer < snake_update_max / difficulty) {
return;
} else {
snake_update_primer = 0;
}
snake_add();
switch (snake->r) {
case 0:
snake->y -= 1;
break;
case 1:
snake->x -= 1;
break;
case 2:
snake->y += 1;
break;
case 3:
snake->x += 1;
break;
}
// snake wrap
if (snake->x >= gameplay_state.level->w) {
snake->x = 0;
}
if (snake->y >= gameplay_state.level->h) {
snake->y = 0;
}
if (snake->x < 0) {
snake->x = gameplay_state.level->w - 1;
}
if (snake->y < 0) {
snake->y = gameplay_state.level->h - 1;
}
if (collide(snake)) {
snake->dead = 1;
}
}
void
snake_turn(struct snake_t *snake, int r) {
int temp = snake->r;
temp += r;
// prevent from rotating backwards onto yourself
if (snake->body) {
int prev_r = ((struct snake_piece_s *) snake->body->data)->r;
if (temp != prev_r + 2 && temp != prev_r - 2) {
// wrap
if (temp > 3) {
temp = 0;
}
if (temp < 0) {
temp = 3;
}
snake->r = temp;
}
} else {
snake->r = temp;
}
gameplay_state.rotating = 1;
}
| true |
d9dfcc9b879d45407dc5decb751b4c4ced70d498 | C++ | MoonJam/MoonJamRelayServer | /src/Helpers.cpp | UTF-8 | 2,192 | 2.953125 | 3 | [] | no_license | #include "Helpers.h"
#include <random>
#include <fstream>
#include <sstream>
#include <cstdio>
#include <iostream>
#include <cstring>
#include <filesystem>
#include <algorithm>
namespace fs = std::filesystem;
std::string randomString(int length) {
static auto& characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
thread_local static std::mt19937 rg{std::random_device{}()};
thread_local static std::uniform_int_distribution<std::string::size_type> pick(0, sizeof(characters) - 2);
std::string s;
s.reserve(length);
for (int i = 0; i < length; i++) {
s += characters[pick(rg)];
}
return s;
}
bool fileExists(const std::string& path) {
return fs::exists(path);
}
void readFile(std::string& content, const std::string& path) {
std::ifstream stream(path);
std::stringstream buffer;
buffer << stream.rdbuf();
content = std::move(buffer.str());
stream.close();
content.erase(std::remove(content.begin(), content.end(), '\r'), content.end());
content.erase(std::remove(content.begin(), content.end(), '\n'), content.end());
}
void writeFile(const std::string& name, const std::string& content) {
std::ofstream outfile(name);
outfile << content;
outfile.close();
}
/*
will only remove a file, if a intermediate directory is passed it will fail, could use
remove_all and it will remove not only the intermediate directory but also it's sub files
return types:
remove = boolean
remove_all = uintmax_t
*/
bool deleteFile(const std::string& name) {
return fs::remove(name);
}
std::array<char, HASH_LENGTH> convertHash(const std::string& hash) {
if (hash.size() != HASH_LENGTH) {
std::cerr << "Invalid string when converting hash..." << std::endl;
return {};
}
std::array<char, HASH_LENGTH> value {};
for (int i = 0; i < HASH_LENGTH; i++) {
value[i] = hash[i];
}
return value;
}
std::string print(std::array<char, HASH_LENGTH>& hash) {
return std::string(std::begin(hash), std::end(hash));
}
FileLogger logger;
LogMessage::~LogMessage() {
m_ss << std::endl;
logger.log(m_ss.str());
}
| true |
c2cf434f1dc519941cc08bb6be101f5366ca5ac3 | C++ | keith-skinner/robotics | /demo/alpha.ino | UTF-8 | 894 | 3.078125 | 3 | [] | no_license | /*
** The alpha-bot has:
** - straight-ahead vision (can only detect prey directly in front of it)
*/
#include "common.h"
typedef enum { SCOUT, CHASE } mode_t;
/*
** The beta-bot sprints in the direction of the beta.
**
** Note: If it stays in chase mode for more than 5 seconds,
** it runs out of energy and loses the game.
*/
void chase()
{
// ...
}
/*
** The alpha roams, entering chase mode if it detects the beta.
*/
void scout()
{
// ...
}
/*
** Returns true if beta is detected.
**
** Note: The alpha-bot must be able to tell the difference between
** the beta-bot's IR output (by its frequency) versus its own reflection off
** of obstacles.
*/
bool detect_beta()
{
bool result = false;
return result;
}
/*
** this code runs once, at the very beginning
*/
void setup()
{
// 1. Set pinmode for each pin as either INPUT or OUTPUT.
}
void loop() {
// ...
}
| true |
eaf43aec8e236596b57eb51d10d2e4d9fcc8af06 | C++ | fieryheart/LearningRenderer | /Shaders/PhongShader.h | UTF-8 | 1,973 | 2.59375 | 3 | [] | no_license | #ifndef __PHONGSHADER_H_
#define __PHONGSHADER_H_
#include "shader.h"
namespace QGL {
class PhongShader : public Shader {
public:
StrangeModel *model;
Matrix uniform_mat_obj2view;
Matrix uniform_mat_transform;
Matrix uniform_mat_norm_transform;
Vec3f uniform_camera;
Vec3f uniform_light;
Vec3f varying_vertex[3];
Vec3f varying_normal[3];
Vec2f varying_uv[3];
virtual void vertex(const InVert &in, OutVert &out) {
Vec4f _normal = Vec4f(model->norm(in.nthface, in.nthvert), 0.0f);
_normal = (uniform_mat_norm_transform*_normal).normalize();
varying_normal[in.nthvert] = _normal.v3f();
varying_vertex[in.nthvert] = in.v;
Vec4f vertex = Vec4f(in.v, 1.0f);
float depth = (uniform_mat_obj2view*vertex).z;
vertex = uniform_mat_transform*vertex;
vertex = vertex / vertex.w;
vertex[2] = depth;
out.sCoord = vertex;
// tex
Vec2f uv = model->tex(in.nthface, in.nthvert);
varying_uv[in.nthvert] = uv;
}
virtual bool fragment(const InFrag &in, OutFrag &out) {
Vec3f bar = in.bar;
Vec3f dir = -uniform_light;
Vec3f N = varying_normal[0]*bar[0]+varying_normal[1]*bar[1]+varying_normal[2]*bar[2];
float diffuse = std::max(0.0f, dot(dir, N));
Vec3f v = varying_vertex[0]*bar[0]+varying_vertex[1]*bar[1]+varying_vertex[2]*bar[2];
Vec3f view = uniform_camera-v;
Vec3f h = (view + dir).normalize();
float a = std::max(0.0f, dot(h, N));
float specular = std::pow(a, 5.f);
Vec2f uv = varying_uv[0]*bar[0]+varying_uv[1]*bar[1]+varying_uv[2]*bar[2];
Vec4f color;
model->sampleDiffuse(uv, color);
float Kd = 0.8;
float Ks = 0.5;
float Ka = 0.2;
color = color*(Kd*diffuse+Ks*specular+Ka);
color[3] = 1.0f;
out.color = color;
return false;
}
};
}
#endif // __PHONGSHADER_H_ | true |
cc9afae6bfa301a8b2251b0727256a6e35664815 | C++ | catree/lbcpp | /include/ml/DoubleVector.h | UTF-8 | 14,638 | 2.59375 | 3 | [] | no_license | /*-----------------------------------------.---------------------------------.
| Filename: DoubleVector.h | Base class for Double Vectors |
| Author : Francis Maes | |
| Started : 03/02/2011 16:10 | |
`------------------------------------------/ |
| |
`--------------------------------------------*/
#ifndef ML_DATA_DOUBLE_VECTOR_H_
# define ML_DATA_DOUBLE_VECTOR_H_
# include <oil/Core/Vector.h>
# include <oil/Core/XmlSerialisation.h>
namespace lbcpp
{
class FeatureGeneratorCallback;
class DoubleVector;
typedef ReferenceCountedObjectPtr<DoubleVector> DoubleVectorPtr;
class SparseDoubleVector;
typedef ReferenceCountedObjectPtr<SparseDoubleVector> SparseDoubleVectorPtr;
class DenseDoubleVector;
typedef ReferenceCountedObjectPtr<DenseDoubleVector> DenseDoubleVectorPtr;
class CompositeDoubleVector;
typedef ReferenceCountedObjectPtr<CompositeDoubleVector> CompositeDoubleVectorPtr;
class DoubleVector : public Object
{
public:
DoubleVector(ClassPtr thisClass)
: Object(thisClass) {}
DoubleVector() {}
// tmp
virtual size_t getNumElements() const = 0;
virtual ObjectPtr getElement(size_t index) const = 0;
virtual void setElement(size_t index, const ObjectPtr& value) = 0;
virtual string getElementName(size_t index) const
{return getElementsEnumeration()->getElementName(index);}
virtual void append(const ObjectPtr& object) const {jassertfalse;}
virtual EnumerationPtr getElementsEnumeration() const
{return thisClass->getTemplateArgument(0);}
virtual ClassPtr getElementsType() const
{return thisClass->getTemplateArgument(1);}
static EnumerationPtr getElementsEnumeration(ClassPtr doubleVectorType);
static bool getTemplateParameters(ExecutionContext& context, ClassPtr type, EnumerationPtr& elementsEnumeration, ClassPtr& elementsType);
// compute - sum v[i] * log2(v[i])
virtual double entropy() const = 0;
virtual size_t l0norm() const = 0;
virtual double l1norm() const = 0;
virtual double sumOfSquares() const = 0;
virtual double getExtremumValue(bool lookForMaximum, size_t* index = NULL) const = 0;
virtual void multiplyByScalar(double scalar) = 0;
virtual void appendTo(const SparseDoubleVectorPtr& sparseVector, size_t offsetInSparseVector, double weight) const = 0;
virtual void addWeightedTo(const SparseDoubleVectorPtr& sparseVector, size_t offsetInSparseVector, double weight) const = 0;
virtual void addWeightedTo(const DenseDoubleVectorPtr& denseVector, size_t offsetInDenseVector, double weight) const = 0;
virtual double dotProduct(const DenseDoubleVectorPtr& denseVector, size_t offsetInDenseVector) const = 0;
virtual void computeFeatures(FeatureGeneratorCallback& callback) const = 0;
double getMaximumValue() const
{return getExtremumValue(true);}
int getIndexOfMaximumValue() const;
double getMinimumValue() const
{return getExtremumValue(false);}
int getIndexOfMinimumValue() const;
virtual double l2norm() const
{return sqrt(sumOfSquares());}
double dotProduct(const DenseDoubleVectorPtr& denseVector)
{return dotProduct(denseVector, 0);}
void addTo(const DenseDoubleVectorPtr& denseVector)
{addWeightedTo(denseVector, 0, 1.0);}
void subtractFrom(const DenseDoubleVectorPtr& denseVector)
{addWeightedTo(denseVector, 0, -1.0);}
virtual double l2norm(const DoubleVectorPtr& vector) const;
virtual SparseDoubleVectorPtr toSparseVector() const;
virtual DenseDoubleVectorPtr toDenseDoubleVector() const;
/*
** Lua
*/
static int dot(LuaState& state);
static int add(LuaState& state);
static int mul(LuaState& state);
static int l0norm(LuaState& state);
static int l1norm(LuaState& state);
static int l2norm(LuaState& state);
static int argmin(LuaState& state);
static int argmax(LuaState& state);
virtual int __add(LuaState& state);
virtual int __sub(LuaState& state);
virtual int __mul(LuaState& state);
virtual int __div(LuaState& state);
lbcpp_UseDebuggingNewOperator
};
extern ClassPtr doubleVectorClass(ClassPtr elementsEnumeration = enumValueClass, ClassPtr elementsType = doubleClass);
extern ClassPtr sparseDoubleVectorClass(ClassPtr elementsEnumeration = enumValueClass, ClassPtr elementsType = doubleClass);
extern ClassPtr denseDoubleVectorClass(ClassPtr elementsEnumeration = enumValueClass, ClassPtr elementsType = doubleClass);
extern ClassPtr lazyDoubleVectorClass(ClassPtr elementsEnumeration = enumValueClass, ClassPtr elementsType = doubleClass);
extern ClassPtr compositeDoubleVectorClass(ClassPtr elementsEnumeration = enumValueClass, ClassPtr elementsType = doubleClass);
class SparseDoubleVector : public DoubleVector
{
public:
SparseDoubleVector(EnumerationPtr elementsEnumeration, ClassPtr elementsType);
SparseDoubleVector(ClassPtr thisClass);
SparseDoubleVector(size_t initialReservedSize);
SparseDoubleVector();
void appendValue(size_t index, double value)
{jassert((int)index > lastIndex); values.push_back(std::make_pair(index, value)); lastIndex = (int)index;}
size_t incrementValue(size_t index, double delta);
size_t getNumValues() const
{return values.size();}
void reserveValues(size_t size)
{values.reserve(size);}
const std::pair<size_t, double>& getValue(size_t index) const
{jassert(index < values.size()); return values[index];}
const std::pair<size_t, double>* getValues() const
{return &values[0];}
std::pair<size_t, double>* getValues()
{return &values[0];}
std::vector< std::pair<size_t, double> >& getValuesVector()
{return values;}
int getLastIndex() const
{return lastIndex;}
void updateLastIndex()
{lastIndex = values.size() ? (int)values.back().first : -1;}
void pruneValues(double epsilon = 0.0);
// DoubleVector
virtual double entropy() const;
virtual size_t l0norm() const;
virtual double l1norm() const;
virtual double sumOfSquares() const;
virtual double getExtremumValue(bool lookForMaximum, size_t* index = NULL) const;
virtual void multiplyByScalar(double scalar);
virtual void appendTo(const SparseDoubleVectorPtr& sparseVector, size_t offsetInSparseVector, double weight) const;
virtual void addWeightedTo(const SparseDoubleVectorPtr& sparseVector, size_t offsetInSparseVector, double weight) const;
virtual void addWeightedTo(const DenseDoubleVectorPtr& denseVector, size_t offsetInDenseVector, double weight) const;
virtual double dotProduct(const DenseDoubleVectorPtr& denseVector, size_t offsetInDenseVector) const;
virtual void computeFeatures(FeatureGeneratorCallback& callback) const;
virtual double l2norm(const DoubleVectorPtr& vector) const;
virtual double l2norm() const {return DoubleVector::l2norm();}
virtual SparseDoubleVectorPtr toSparseVector() const
{return refCountedPointerFromThis(this);}
// Vector
virtual void clear();
virtual void reserve(size_t size);
virtual void resize(size_t size);
virtual void prependElement(const ObjectPtr& value);
virtual void appendElement(const ObjectPtr& value);
virtual void remove(size_t index);
// Container
virtual size_t getNumElements() const;
virtual ObjectPtr getElement(size_t index) const;
virtual void setElement(size_t index, const ObjectPtr& value);
// Object
virtual string toShortString() const;
virtual void saveToXml(XmlExporter& exporter) const;
virtual bool loadFromXml(XmlImporter& importer);
virtual size_t getSizeInBytes(bool recursively) const;
virtual void clone(ExecutionContext& context, const ObjectPtr& target) const;
// Lua
static int append(LuaState& state);
static int increment(LuaState& state);
virtual int __index(LuaState& state) const;
virtual int __newIndex(LuaState& state);
lbcpp_UseDebuggingNewOperator
private:
friend class DenseDoubleVector;
std::vector< std::pair<size_t, double> > values;
int lastIndex;
};
class DenseDoubleVector : public DoubleVector
{
public:
DenseDoubleVector(ClassPtr thisClass, std::vector<double>& values);
DenseDoubleVector(ClassPtr thisClass, size_t initialSize = (size_t)-1, double initialValue = 0.0);
DenseDoubleVector(EnumerationPtr enumeration, ClassPtr elementsType, size_t initialSize = (size_t)-1, double initialValue = 0.0);
DenseDoubleVector(size_t initialSize, double initialValue);
DenseDoubleVector();
virtual ~DenseDoubleVector();
const std::vector<double>& getValues() const
{jassert(values); return *values;}
std::vector<double>& getValues()
{jassert(values); return *values;}
double* getValuePointer(size_t index)
{jassert(values && index <= values->size()); return &(*values)[0] + index;}
const double* getValuePointer(size_t index) const
{jassert(values && index <= values->size()); return &(*values)[0] + index;}
double& getValueReference(size_t index)
{ensureSize(index + 1); return *getValuePointer(index);}
double getValue(size_t index) const
{jassert(values); return index < values->size() ? (*values)[index] : 0.0;}
void setValue(size_t index, double value)
{getValueReference(index) = value;}
size_t getNumValues() const
{return values ? values->size() : 0;}
void incrementValue(size_t index, double value)
{jassert(values && index < values->size()); (*values)[index] += value;}
void decrementValue(size_t index, double value)
{jassert(values && index < values->size()); (*values)[index] -= value;}
void appendValue(double value)
{jassert(values); values->push_back(value);}
void removeLastValue()
{jassert(values && values->size()); values->pop_back();}
void ensureSize(size_t minimumSize);
// compute log(sum_i(exp(value[i]))) by avoiding numerical errors
double computeLogSumOfExponentials() const;
// compute -sum_i(p_i * log2(p_i)) with p_i = value[i] / l1norm. By default, l1norm is computed automatically
double computeEntropy(double l1norm = -1.0) const;
// compute euclidean distance to another DenseDoubleVector
double distanceTo(const DenseDoubleVectorPtr& other) const;
// DoubleVector
virtual double entropy() const;
virtual size_t l0norm() const;
virtual double l1norm() const;
virtual double sumOfSquares() const;
virtual double getExtremumValue(bool lookForMaximum, size_t* index = NULL) const;
virtual void multiplyByScalar(double value);
virtual void appendTo(const SparseDoubleVectorPtr& sparseVector, size_t offsetInSparseVector, double weight) const;
virtual void addWeightedTo(const SparseDoubleVectorPtr& sparseVector, size_t offsetInSparseVector, double weight) const;
virtual void addWeightedTo(const DenseDoubleVectorPtr& denseVector, size_t offsetInDenseVector, double weight) const;
virtual double dotProduct(const DenseDoubleVectorPtr& denseVector, size_t offsetInDenseVector) const;
virtual void computeFeatures(FeatureGeneratorCallback& callback) const;
virtual double l2norm(const DoubleVectorPtr& vector) const;
virtual double l2norm() const {return DoubleVector::l2norm();}
virtual DenseDoubleVectorPtr toDenseDoubleVector() const
{return refCountedPointerFromThis(this);}
// Vector
virtual void clear();
virtual void reserve(size_t size);
virtual void resize(size_t size);
virtual void prependElement(const ObjectPtr& value);
virtual void appendElement(const ObjectPtr& value);
virtual void remove(size_t index);
// Container
virtual size_t getNumElements() const;
virtual ObjectPtr getElement(size_t index) const;
virtual void setElement(size_t index, const ObjectPtr& value);
// Object
virtual string toShortString() const;
virtual void clone(ExecutionContext& context, const ObjectPtr& target) const;
void saveToXml(XmlExporter& exporter) const;
bool loadFromXml(XmlImporter& importer);
virtual size_t getSizeInBytes(bool recursively) const;
// Lua
virtual int __len(LuaState& state) const;
virtual int __index(LuaState& state) const;
virtual int __newIndex(LuaState& state);
lbcpp_UseDebuggingNewOperator
private:
std::vector<double>* values;
bool ownValues;
};
class CompositeDoubleVector : public DoubleVector
{
public:
CompositeDoubleVector(ClassPtr thisClass)
: DoubleVector(thisClass) {}
CompositeDoubleVector() {}
// sub vectors
size_t getNumSubVectors() const
{return vectors.size();}
const DoubleVectorPtr& getSubVector(size_t index) const
{jassert(index < vectors.size()); return vectors[index].second;}
size_t getSubVectorOffset(size_t index) const
{jassert(index < vectors.size()); return vectors[index].first;}
void reserveSubVectors(size_t count)
{vectors.reserve(count);}
void appendSubVector(size_t shift, const DoubleVectorPtr& subVector);
void appendSubVector(const DoubleVectorPtr& subVector);
// DoubleVector
virtual double entropy() const;
virtual size_t l0norm() const;
virtual double l1norm() const;
virtual double sumOfSquares() const;
virtual double getExtremumValue(bool lookForMaximum, size_t* index = NULL) const;
virtual void multiplyByScalar(double value);
virtual void appendTo(const SparseDoubleVectorPtr& sparseVector, size_t offsetInSparseVector, double weight) const;
virtual void addWeightedTo(const SparseDoubleVectorPtr& sparseVector, size_t offsetInSparseVector, double weight) const;
virtual void addWeightedTo(const DenseDoubleVectorPtr& denseVector, size_t offsetInDenseVector, double weight) const;
virtual double dotProduct(const DenseDoubleVectorPtr& denseVector, size_t offsetInDenseVector) const;
virtual void computeFeatures(FeatureGeneratorCallback& callback) const;
virtual double l2norm() const {return DoubleVector::l2norm();}
// Vector
virtual void clear();
virtual void reserve(size_t size);
virtual void resize(size_t size);
virtual void prependElement(const ObjectPtr& value);
virtual void appendElement(const ObjectPtr& value);
virtual void remove(size_t index);
// Container
virtual size_t getNumElements() const;
virtual ObjectPtr getElement(size_t index) const;
virtual void setElement(size_t index, const ObjectPtr& value);
// Object
virtual void clone(ExecutionContext& context, const ObjectPtr& target) const;
virtual bool loadFromXml(XmlImporter& importer);
virtual void saveToXml(XmlExporter& exporter) const;
lbcpp_UseDebuggingNewOperator
private:
std::vector< std::pair<size_t, DoubleVectorPtr> > vectors;
};
}; /* namespace lbcpp */
#endif // !ML_DATA_DOUBLE_VECTOR_H_
| true |
c50cd1d9a9bdb988b903a114f2f19778db07af01 | C++ | dtbinh/com-vision | /DetectMouvement/control.cpp | UTF-8 | 6,354 | 2.71875 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
#include "control.h"
#include <string>
#include <stdlib.h>
#include <dirent.h>
#include "kalman.h"
using namespace cv;
using namespace std;
#define GRAY_LEVEL 256
#define CMD_FOND "fond"
#define CMD_DETECT "detect"
Control::Control(){}
/*
Permet de séparer le nom des fichiers appliqué et leur file
*/
int Split(vector<string>& vecteur, string chaine, char separateur)
{
vecteur.clear();
string::size_type stTemp = chaine.find(separateur);
while(stTemp != string::npos)
{
vecteur.push_back(chaine.substr(0, stTemp));
chaine = chaine.substr(stTemp + 1);
stTemp = chaine.find(separateur);
}
vecteur.push_back(chaine);
return vecteur.size();
}
/*
Pour attendre l'utilisateur tapper des commandes
Cette methode va traitter des commandes entrées pour
réaliser des besoin en rappant des autres méthodes correspondantes
*/
void Control::processCommand(int argc, char* argv[])
{
int time_per_image = 10;
string video_path, fond_name;
string video_src, video_des;
if(argc < 2)
return;
if(strcmp(argv[1], CMD_FOND) == 0)
{
if(argc < 4)
return;
video_path = std::string(argv[2]);
fond_name = std::string(argv[3]);
this->getImageDeFond(video_path, fond_name);
}
if(strcmp(argv[1], CMD_DETECT) == 0)
{
if(argc < 5)
return;
video_src = std::string(argv[2]);
fond_name = std::string(argv[3]);
time_per_image = atoi(argv[4]);
this->detectVideo(video_src, fond_name, time_per_image);
}
return;
}
void Control::detectVideo(string video_src, string fond_path, int time_per_image)
{
AMat mouvement, frame, frame_gray, fond;
//vector<AMat> fonds;
int time = 0;
ostringstream num_str;
string video_show = video_src + " - detect";
Mat image_tracking;
Mat kernel(3, 3, CV_8UC1, Scalar(255));
//Parametter for kalman filtter
vector<Point2f> center;
string video_tracking = video_src + " - tracking";
Kalman kalman;
fond = cv::imread(fond_path);
// open the video file for reading
cv::VideoCapture cap(video_src);
fond.copyTo(image_tracking);
cv::cvtColor(fond, fond, CV_RGB2GRAY);
cv::blur(fond, fond, Size(3, 3));
if ( !cap.isOpened() ) // if not success, exit program
{
cout << "Cannot open the video file" << endl;
return;
}
//get the frames per seconds of the video
double fps = cap.get(CV_CAP_PROP_FPS);
cout << "Frame per seconds : " << fps << endl;
namedWindow(video_src, CV_WINDOW_AUTOSIZE);
namedWindow(video_show, CV_WINDOW_AUTOSIZE);
while(1)
{
bool bSuccess = cap.read(frame); // read a new frame from video
if (!bSuccess) //if not success, break loop
{
cout << "Cannot read the frame from video file" << endl;
break;
}
time++;
if(time % time_per_image == 0)
{
num_str.str("");
num_str<<time;
cv::cvtColor(frame, frame_gray, CV_RGB2GRAY);
blur(frame_gray, frame_gray, Size(3, 3));
mouvement = frame_gray - fond;
cv::erode(mouvement, mouvement, kernel);
cv::dilate(mouvement, mouvement, kernel);
imshow(video_show, mouvement);
cv::imwrite("image/test3/2/" + num_str.str() + ".png", mouvement);
AMat::thresh_callback(mouvement, frame, center, image_tracking);
kalman.filters(center, image_tracking);
imshow(video_tracking, image_tracking);
cv::imwrite("image/test3/3/" + num_str.str() + ".png", image_tracking);
}
//blur(frame, frame, Size(3, 3));
imshow(video_src, frame); //show the frame in "video_name" window
cv::imwrite("image/test3/1/" + num_str.str() + ".png", frame);
//wait for 'esc' key press for 30 ms. If 'esc' key is pressed, break loop
if(waitKey(30) == 27)
{
cout << "esc key is pressed by user" << endl;
destroyWindow(video_src);
destroyWindow(video_show);
break;
}
}
return;
}
vector<AMat> Control::capImageFromVideo(string video_name, int time_per_image)
{
int time = 0;
// open the video file for reading
cv::VideoCapture cap(video_name);
std::vector<AMat> images;
cv::Mat frame_gray;
if ( !cap.isOpened() ) // if not success, exit program
{
cout << "Cannot open the video file" << endl;
return images;
}
//get the frames per seconds of the video
double fps = cap.get(CV_CAP_PROP_FPS);
cout << "Frame per seconds : " << fps << endl;
namedWindow(video_name,CV_WINDOW_AUTOSIZE);
while(1)
{
Mat frame;
bool bSuccess = cap.read(frame); // read a new frame from video
if (!bSuccess) //if not success, break loop
{
cout << "Cannot read the frame from video file" << endl;
break;
}
imshow(video_name, frame); //show the frame in "video_name" window
time++;
if(time % time_per_image == 0)
{
cv::cvtColor(frame, frame_gray, CV_RGB2GRAY);
images.push_back(frame_gray);
}
//wait for 'esc' key press for 30 ms. If 'esc' key is pressed, break loop
if(waitKey(30) == 27)
{
cout << "esc key is pressed by user" << endl;
destroyWindow(video_name);
break;
}
}
return images;
}
bool isEqualeSize(vector<AMat> &images)
{
int N = images.size();
for (int i = 0; i < N-1; ++i)
{
if(images[i].cols != images[i+1].cols ||
images[i].rows != images[i+1].rows)
{
return false;
}
}
return true;
}
template <typename T>
T getMedian(vector<T> L)
{
std::nth_element(L.begin(), L.begin() + L.size()/2, L.end());
return L[L.size()/2];
}
AMat Control::getImageDeFond(vector<AMat> images) const
{
AMat fond;
int M, N, SIZE = images.size();
vector<uchar> grays;
uchar value;
if(!isEqualeSize(images))
return fond;
if(SIZE > 0)
{
M = images[0].rows;
N = images[0].cols;
}
fond = AMat(M, N, CV_8UC1);
for (int i = 0; i < M; ++i)
{
for (int j = 0; j < N; ++j)
{
grays.clear();
for (int k = 0; k < SIZE; k++)
{
grays.push_back(images[k].at<uchar>(i, j));
}
value = getMedian(grays);
fond.at<uchar>(i, j) = value;
}
}
return fond;
}
void Control::getImageDeFond(string video_path, string image_fond)
{
vector<AMat> image_models = this->capImageFromVideo(video_path, 20);
AMat fond = this->getImageDeFond(image_models);
imwrite(image_fond, fond);
}
| true |
a2bf6fb68248a383426419415c5ebf5a605a8dbb | C++ | Pattywu20031224/cpp | /YTP/停課.cpp | UTF-8 | 1,016 | 2.921875 | 3 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
struct Class{
int count;
int positive;
};
struct School{
int count;
int positive;
vector<Class> classes;
};
int main(){
int ns, susp_students=0;
cin>>ns;
vector<School> school(ns);
for(int i=0; i<ns; i++){
int nc;
int total_susp=0, susp_schools=0, total_students;
cin>>nc;
school[i].classes.resize(nc);
for(int j=0; j<nc; j++){
cin>>school[i].classes[j].count;
school[i].count += school[i].classes[j].count;
for(int k=0; k<school[i].classes[j].count; k++){
int r;
cin>>r;
if (r==11){
school[i].classes[j].positive ++;
school[i].positive++;
}
}
if(school[i].classes[j].positive>0){
susp_students += school[i].classses[j].count;
}
}
if(school[i].positive>=2){
susp_students=school[i].count;
susp_schools++;
}
total_susp += susp_students;
total_students += school[i].count;
}
if(susp_schools*3 >= ns){
total_susp = total_students;
}
cout<< total_susp<<endl;
return 0;
}
| true |
b8f3bd99cbe8ba0e2cd9bf287e7a94f6fb44a0f5 | C++ | ysdeal/LeetCode | /permuteUnique.h | UTF-8 | 955 | 3.5 | 4 | [] | no_license | /**
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
[1,1,2] have the following unique permutations:
[1,1,2], [1,2,1], and [2,1,1].
*/
class Solution {
public:
vector<vector<int> > permuteUnique(vector<int> &num) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<vector<int>> res;
sort(num.begin(),num.end());
doPermute(num, 0, res);
return res;
}
void doPermute(vector<int> &num, int s, vector<vector<int>> &res){
if(s == num.size()){res.push_back(num); return;}
unordered_set<int> used;
for(int i = s; i < num.size(); i++){
if(used.find(num[i]) == used.end()){
swap(num[s],num[i]);
doPermute(num, s+1, res);
swap(num[s],num[i]);
used.insert(num[i]);
}
}
}
};
| true |
ab8dbf6c95117a7cc030ae21fc8438f9b3bede16 | C++ | Xuchaoxiong/PAT | /B1011/B1011/B1011.cpp | GB18030 | 598 | 2.984375 | 3 | [
"Apache-2.0"
] | permissive | // B1011.cpp : ̨Ӧóڵ㡣
//
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
struct NumStruct
{
long A;
long B;
long C;
};
int main()
{
int n;
cin >> n;
NumStruct *NumMass = new NumStruct [n];
for (int i = 0; i < n; i++)
{
cin >> NumMass[i].A;
cin >> NumMass[i].B;
cin >> NumMass[i].C;
}
for (int i = 0; i < n; i++)
{
if ((NumMass[i].A + NumMass[i].B)>NumMass[i].C)
cout << "Case #" << (i + 1) << ": " << "true" << endl;
else
cout << "Case #" << (i + 1) << ": " << "false" << endl;
}
system("pause");
}
| true |
902009fc0b69dca7ee7831267fc2c4d317e3c322 | C++ | UG-SEP/Data-Structure-and-Algorithms | /Leetcode/Unique Paths/Unique Paths withput DP.cpp | UTF-8 | 1,868 | 3.5625 | 4 | [
"MIT"
] | permissive | #include <bits/stdc++.h>
using namespace std;
/*
The code utilises the similarity of the problem to pascal's triangle and hence
uses nCr [N Combinations from R] formula to get the solution without the use of DP.
Here is the Pascals Triangle:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
The DP grid constructed containing ways to reach any point: // Any entry gives unique ways to reach that position
1 1 1 1 1 // All the way to right is 1 way as moving right is the only option, same goes for dowwn
1 2 3 4 5 // The rest of the ways are calculted from sum of the cell's top and left negighbours
1 3 6 10 15 // as those are the only cells that can reach to it.
1 4 10 20 35 // [ X ]
1 5 15 35 70 // ↓
-> // [ Y ] → [X+Y]
DP Grid Pascal's Triangel
1 1
^ 1 1 1
1
^ ^ 1
^ 2 1 2 1
1
*/
class Solution {
public:
// Efficient code to Calculate nCr Combinations
int NcR(int n, int r) {
// p holds the value of n*(n-1)*(n-2)...,
// k holds the value of r*(r-1)...
long long p = 1, k = 1;
// C(n, r) == C(n, n-r),
// choosing the smaller value
if (n - r < r)
r = n - r;
if (r != 0) {
while (r) {
p *= n;
k *= r;
// gcd of p, k
long long m = __gcd(p, k);
// dividing by gcd, to simplify
// product division by their gcd
// saves from the overflow
p /= m;
k /= m;
n--;
r--;
}
// k should be simplified to 1
// as C(n, r) is a natural number
// (denominator should be 1 ) .
} else
p = 1;
// if our approach is correct p = ans and k =1
return p;
}
int uniquePaths(int m, int n) {
// The solution works using (m+n)C(m) [Combinations from pascal's Triangle]
return NcR(m + n - 2, m - 1);
}
}; | true |
4aba654e0b9ba80fd9c14cb4c89a7d7540a7c3fe | C++ | toasti1973/TurboMath | /TurboMath/Matrix.h | WINDOWS-1250 | 15,520 | 2.640625 | 3 | [
"MIT"
] | permissive |
// -------------------------------------------------------------------
// File : Matrix
//
// Project : TurboMath
//
// Description : Class for Matrix
//
// Author : Thorsten Polte
// -------------------------------------------------------------------
// (c) 2011-2020 by Innovation3D-Studios
// --------------------------------------------------------------------
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//---------------------------------------------------------------------
// https://github.com/toasti1973/TurboMath
//
// Contact : thorsten.polte@innovation3d.de
//---------------------------------------------------------------------
#ifdef _MSC_VER
#pragma once
#endif
#ifndef _TURBOMATH_MATRIX_H_
#define _TURBOMATH_MATRIX_H_
namespace TurboMath
{
CACHE_ALIGN(16) class Matrix
{
public:
/// default constructor, NOTE: setup components to Identity!
Matrix();
/// construct from components
explicit Matrix(Vector4 const &row0, Vector4 const &row1, Vector4 const &row2, Vector4 const &row3);
/// construct from XMMATRIX
Matrix(const XMMATRIX& rhs);
/// C++11 Move Constructor
Matrix(_In_ Matrix&& other) noexcept;
/// constructs from Matrix
Matrix::Matrix(const Matrix& rhs) noexcept;
/// assignment operator
void XM_CALLCONV operator=(const Matrix& rhs) noexcept;
/// assign XMMATRIX
void XM_CALLCONV operator=(const XMMATRIX& rhs) noexcept;
/// equality operator
bool XM_CALLCONV operator==(const Matrix& rhs) const noexcept;
/// inequality operator
bool XM_CALLCONV operator!=(const Matrix& rhs) const noexcept;
// matrix-Vector product
const Vector4 XM_CALLCONV operator * (const Vector4& v) const noexcept;
/// C++11 Move
Matrix& XM_CALLCONV operator=( Matrix&& other) noexcept;
// member access
float XM_CALLCONV operator() ( const int iRow, const int iCol ) const;
float& XM_CALLCONV operator() ( const int iRow, const int iCol );
float XM_CALLCONV operator[] ( const int iPos ) const;
float& XM_CALLCONV operator[] ( const int iPos );
operator float* () {return (float*)&mx;}
operator const float* () const {return (float*)&mx;}
// arithmetic operations
Matrix XM_CALLCONV operator+ ( const Matrix& Matrix ) const noexcept;
Matrix XM_CALLCONV operator- (const Matrix& Matrix) const noexcept;
Matrix XM_CALLCONV operator* ( const Matrix& Matrix ) const noexcept;
Matrix XM_CALLCONV operator* ( float fScalar ) const noexcept;
Matrix XM_CALLCONV operator/ ( float fScalar ) const noexcept;
Matrix XM_CALLCONV operator- () const noexcept;
// arithmetic updates
Matrix& XM_CALLCONV operator+= ( const Matrix& Matrix ) noexcept;
Matrix& XM_CALLCONV operator-= ( const Matrix& Matrix ) noexcept;
Matrix& XM_CALLCONV operator*= ( const Matrix& Matrix ) noexcept;
Matrix& XM_CALLCONV operator*= ( float fScalar ) noexcept;
Matrix& XM_CALLCONV operator/= ( float fScalar ) noexcept;
/// load content from 16-byte-aligned memory
void XM_CALLCONV Load(const float* ptr) noexcept;
/// load content from unaligned memory
void XM_CALLCONV LoadU(const float* ptr) noexcept;
/// write content to 16-byte-aligned memory through the write cache
void XM_CALLCONV Store(float* ptr) const noexcept;
/// write content to unaligned memory through the write cache
void XM_CALLCONV StoreU(float* ptr) const noexcept;
/// stream content to 16-byte-aligned memory circumventing the write-cache
void XM_CALLCONV Stream(float* ptr) const noexcept;
/// set content
void XM_CALLCONV Set(Vector4 const &row0, Vector4 const &row1, Vector4 const &row2, Vector4 const &row3) noexcept;
/// write access to x component
void XM_CALLCONV SetRow0(Vector4 const &row0) noexcept;
/// write access to y component
void XM_CALLCONV SetRow1(Vector4 const &row1) noexcept;
/// write access to z component
void XM_CALLCONV SetRow2(Vector4 const &row2) noexcept;
/// write access to w component
void XM_CALLCONV SetRow3(Vector4 const &row3) noexcept;
/// read-only access to x component
const Vector4& XM_CALLCONV GetRow0() const noexcept;
/// read-only access to y component
const Vector4& XM_CALLCONV GetRow1() const noexcept;
/// read-only access to z component
const Vector4& XM_CALLCONV GetRow2() const noexcept;
/// read-only access to w component
const Vector4& XM_CALLCONV GetRow3() const noexcept;
/// Get access to M11 element
const float XM_CALLCONV GetM11() const noexcept;
/// Get access to M12 element
const float XM_CALLCONV GetM12() const noexcept;
/// Get access to M13 element
const float XM_CALLCONV GetM13() const noexcept;
/// Get access to M14 element
const float XM_CALLCONV GetM14() const noexcept;
/// Get access to M21 element
const float XM_CALLCONV GetM21() const noexcept;
/// Get access to M22 element
const float XM_CALLCONV GetM22() const noexcept;
/// Get access to M13 element
const float XM_CALLCONV GetM23() const noexcept;
/// Get access to M14 element
const float XM_CALLCONV GetM24() const noexcept;
/// Get access to M31 element
const float XM_CALLCONV GetM31() const noexcept;
/// Get access to M32 element
const float XM_CALLCONV GetM32() const noexcept;
/// Get access to M33 element
const float XM_CALLCONV GetM33() const noexcept;
/// Get access to M34 element
const float XM_CALLCONV GetM34() const noexcept;
/// Get access to M41 element
const float XM_CALLCONV GetM41() const noexcept;
/// Get access to M42 element
const float XM_CALLCONV GetM42() const noexcept;
/// Get access to M43 element
const float XM_CALLCONV GetM43() const noexcept;
/// Get access to M44 element
const float XM_CALLCONV GetM44() const noexcept;
/// Get Basis X
const Vector4& XM_CALLCONV GetBasisX() const noexcept;
/// Get Basis Y
const Vector4& XM_CALLCONV GetBasisY() const noexcept;
/// Get Basis Z
const Vector4& XM_CALLCONV GetBasisZ() const noexcept;
/// Get Translation
const Vector4& XM_CALLCONV GetTranslation() const noexcept;
/// Rotation
const Matrix XM_CALLCONV GetRotation() const noexcept;
/// Set Rotation
void XM_CALLCONV SetRotation( const Matrix& Rot ) noexcept;
/// Set Translation
void XM_CALLCONV SetTranslation( const Vector4& Trans ) noexcept;
/// Set access to M11 element
void XM_CALLCONV SetM11(const float m11) noexcept;
/// Set access to M12 element
void XM_CALLCONV SetM12(const float m12) noexcept;
/// Set access to M13 element
void XM_CALLCONV SetM13(const float m13) noexcept;
/// Set access to M14 element
void XM_CALLCONV SetM14(const float m14) noexcept;
/// Set access to M21 element
void XM_CALLCONV SetM21(const float m21) noexcept;
/// Set access to M22 element
void XM_CALLCONV SetM22(const float m22) noexcept;
/// Set access to M13 element
void XM_CALLCONV SetM23(const float m23) noexcept;
/// Set access to M14 element
void XM_CALLCONV SetM24(const float m24) noexcept;
/// Set access to M31 element
void XM_CALLCONV SetM31(const float m31) noexcept;
/// Set access to M32 element
void XM_CALLCONV SetM32(const float m32) noexcept;
/// Set access to M33 element
void XM_CALLCONV SetM33(const float m33) noexcept;
/// Set access to M34 element
void XM_CALLCONV SetM34(const float m34) noexcept;
/// Set access to M41 element
void XM_CALLCONV SetM41(const float m41) noexcept;
/// Set access to M42 element
void XM_CALLCONV SetM42(const float m42) noexcept;
/// Set access to M43 element
void XM_CALLCONV SetM43(const float m43) noexcept;
/// Set access to M44 element
void XM_CALLCONV SetM44(const float m44) noexcept;
/// write access to x component
void XM_CALLCONV Set_X_Axis(Vector4 const &x) noexcept;
/// write access to y component
void XM_CALLCONV Set_Y_Axis(Vector4 const &y) noexcept;
/// write access to z component
void XM_CALLCONV Set_Z_Axis(Vector4 const &z) noexcept;
/// write access to w component / pos component
void XM_CALLCONV Set_Position(Vector4 const &pos) noexcept;
/// read access to x component
const Vector4& XM_CALLCONV Get_X_Axis() const noexcept;
/// read access to y component
const Vector4& XM_CALLCONV Get_Y_Axis() const noexcept;
/// read access to z component
const Vector4& XM_CALLCONV Get_Z_Axis() const noexcept;
/// read access to w component / pos component
const Vector4& XM_CALLCONV Get_Position() const noexcept;
/// add a translation to pos_component
void XM_CALLCONV Translate(Vector4 const &t);
/// scale matrix
void XM_CALLCONV Scale(Vector4 const &v) noexcept;
/// Computer Matrix from Axis, rotation Angle, a Scale and a Translation
Matrix XM_CALLCONV MakeWorldMatrix(const Vector3& rotAxis, const float rotAngle, const Vector3& scale, const Vector3& translation) noexcept ;
/// return true if matrix is identity
bool XM_CALLCONV IsIdentity() const noexcept;
/// return determinant of matrix
float XM_CALLCONV Determinant() const noexcept;
/// decompose into scale, rotation and translation
void XM_CALLCONV Decompose(Vector4& outScale, Quat& outRotation, Vector4& outTranslation) const;
/// build identity matrix
static Matrix XM_CALLCONV Identity() noexcept;
/// Make all elements Zero
static Matrix XM_CALLCONV MakeZero() noexcept;
/// build matrix from affine transformation
static Matrix XM_CALLCONV AffineTransformation(float scaling, Vector4 const &rotationCenter, const Quat& rotation, Vector4 const &translation) noexcept;
/// compute the inverse of a matrix
static Matrix XM_CALLCONV Inverse(const Matrix& m) noexcept;
/// build left handed lookat matrix
static Matrix XM_CALLCONV LookAtLH(Vector4 const &eye, Vector4 const &at, Vector4 const &up) noexcept;
/// build right handed lookat matrix
static Matrix XM_CALLCONV LookAtRH(Vector4 const &eye, Vector4 const &at, Vector4 const &up) noexcept;
/// build left handed lookto matrix
static Matrix XM_CALLCONV LookToLH(Vector4 const &eye, Vector4 const &at, Vector4 const &up) noexcept;
/// build right handed lookto matrix
static Matrix XM_CALLCONV LookToRH(Vector4 const &eye, Vector4 const &at, Vector4 const &up) noexcept;
/// multiply 2 matrices
static Matrix XM_CALLCONV Multiply(const Matrix& m0, const Matrix& m1) noexcept;
/// build left handed orthogonal projection matrix
static Matrix XM_CALLCONV OrthoLH(float w, float h, float zn, float zf) noexcept;
/// build right handed orthogonal projection matrix
static Matrix XM_CALLCONV OrthoRH(float w, float h, float zn, float zf) noexcept;
/// build left-handed off-center orthogonal projection matrix
static Matrix XM_CALLCONV OrthoOffCenterLH(float l, float r, float b, float t, float zn, float zf) noexcept;
/// build right-handed off-center orthogonal projection matrix
static Matrix XM_CALLCONV OrthoOffCenterRH(float l, float r, float b, float t, float zn, float zf) noexcept;
/// build left-handed perspective projection matrix based on field-of-view
static Matrix XM_CALLCONV PerspectiveProjectionFovLH(float fovy, float aspect, float zn, float zf) noexcept;
/// build right-handed perspective projection matrix based on field-of-view
static Matrix XM_CALLCONV PerspectiveProjectionFovRH(float fovy, float aspect, float zn, float zf) noexcept;
/// build left-handed perspective projection matrix
static Matrix XM_CALLCONV PerspectiveProjectionLH(float w, float h, float zn, float zf) noexcept;
/// build right-handed perspective projection matrix
static Matrix XM_CALLCONV PerspectiveProjectionRH(float w, float h, float zn, float zf) noexcept;
/// build left-handed off-center perspective projection matrix
static Matrix XM_CALLCONV PerspOffCenterLH(float l, float r, float b, float t, float zn, float zf) noexcept;
/// build right-handed off-center perspective projection matrix
static Matrix XM_CALLCONV PerspOffCenterRH(float l, float r, float b, float t, float zn, float zf) noexcept;
/// build matrix that reflects coordinates about a plance
static Matrix XM_CALLCONV Reflect(const Plane& p) noexcept;
/// build rotation matrix around arbitrary axis
static Matrix XM_CALLCONV RotationAxis(Vector4 const &axis, float angle) noexcept;
/// build rotation matrix from quaternion
static Matrix XM_CALLCONV RotationQuaternion(const Quat& q) noexcept;
/// build x-axis-rotation matrix
static Matrix XM_CALLCONV RotationX(float angle) noexcept;
/// build y-axis-rotation matrix
static Matrix XM_CALLCONV RotationY(float angle) noexcept;
/// build z-axis-rotation matrix
static Matrix XM_CALLCONV RotationZ(float angle) noexcept;
/// build Rotation Matrix
void XM_CALLCONV Rotation(const Vector3& rot) noexcept;
/// build rotation matrix from yaw, pitch and roll
static Matrix XM_CALLCONV RotationYawPitchRoll(float yaw, float pitch, float roll) noexcept;
/// build a scaling matrix from components
static Matrix XM_CALLCONV Scaling(float sx, float sy, float sz) noexcept;
/// build a scaling matrix from components
static Matrix XM_CALLCONV Scaling(float s) noexcept;
/// build a scaling matrix from Vector4
static Matrix XM_CALLCONV Scaling(Vector4 const &s) noexcept;
/// build a transformation matrix
static Matrix XM_CALLCONV Transformation(Vector4 const &scalingCenter, const Quat& scalingRotation, Vector4 const &scaling, Vector4 const &rotationCenter, const Quat& rotation, Vector4 const &translation) noexcept;
/// build a translation matrix
static Matrix XM_CALLCONV Translation(float x, float y, float z) noexcept;
/// build a translation matrix from point
static Matrix XM_CALLCONV Translation(Vector4 const &t) noexcept;
/// return the transpose of a matrix
static Matrix XM_CALLCONV Transpose(const Matrix& m) noexcept;
/// transform 4d vector by Matrix, faster inline version than Vector4::transform
static Vector4 XM_CALLCONV Transform(const Vector4 &v, const Matrix &m) noexcept;
/// return a quaternion from rotational part of the 4x4 matrix
static Quat XM_CALLCONV RotationMatrix(const Matrix& m) noexcept;
// transform a plane with a matrix
static Plane XM_CALLCONV Transform(const Plane& p, const Matrix& m) noexcept;
/// Easy acces Matrix Members
/// So it is possible to do something like this:
/// Matrix matrix;
/// float value = matrix[Matrix::M11];
static constexpr int M11 = 0;
static constexpr int M12 = 1;
static constexpr int M13 = 2;
static constexpr int M14 = 3;
static constexpr int M21 = 4;
static constexpr int M22 = 5;
static constexpr int M23 = 6;
static constexpr int M24 = 7;
static constexpr int M31 = 8;
static constexpr int M32 = 9;
static constexpr int M33 = 10;
static constexpr int M34 = 11;
static constexpr int M41 = 12;
static constexpr int M42 = 13;
static constexpr int M43 = 14;
static constexpr int M44 = 15;
/// friend-classes
friend class Vector2;
friend class Vector3;
friend class Vector4;
friend class Plane;
friend class Quat;
friend class Frustum;
protected:
XMMATRIX mx;
};// End of Class : Matrix
}; // Namespace TurboMath
#endif | true |
0e83ee1d1ae9f3918046d776524acec25b3e6a56 | C++ | Filip-Novak/finding-perfect-matchings | /rekurzia/ba-graph/include/algorithms/object_collection/generation.hpp | UTF-8 | 4,942 | 2.59375 | 3 | [] | no_license | #ifndef BA_GRAPH_ALGORITHMS_OBJECT_COLLECTION_GENERATION_HPP
#define BA_GRAPH_ALGORITHMS_OBJECT_COLLECTION_GENERATION_HPP
#include <string>
#include <algorithms/isomorphism/isomorphism.hpp>
#include <algorithms/isomorphism/isomorphism_nauty.hpp>
#include <io/graph6.hpp>
#include <operations/copies.hpp>
using namespace ba_graph;
// satisfies requirements for CollectibleObject
class CanonicalGraph
{
protected:
bool minimised;
int cachedHash;
Factory f;
Graph G = createG(f);
public:
std::string serialisedG;
CanonicalGraph(const Graph &g, bool do_inflate)
{
serialisedG = canonical_sparse6(g);
cachedHash = std::hash<std::string>()(serialisedG);
minimised = true;
if (do_inflate)
inflate();
}
CanonicalGraph(const std::string &s, bool do_inflate)
{
deserialise(s, do_inflate);
}
inline const Graph& graph() const {
if (minimised)
throw std::logic_error("minimised, graph is inaccessible");
else
return G;
}
inline int size() const {
if (minimised)
throw std::logic_error("minimised, graph is inaccessible");
else
return G.order();
}
inline int hash() const { return cachedHash; }
inline void compute_property() const {}
inline bool property_computed() const { return true; }
inline int property_value() const { return 0; }
inline bool operator==(const CanonicalGraph &other) const {
return hash() == other.hash() && serialisedG == other.serialisedG;
}
inline bool is_minimised() const { return minimised; }
// keep as small memory footprint as possible
// useful for keeping failed candidates in ObjectCollection
void minimise()
{
if (!minimised) {
Graph H = createG(f);
std::swap(G, H); // throw away contents of G
minimised = true;
}
}
// restores after minimization
void inflate()
{
if (minimised) {
Graph H = std::move(read_graph6_line(serialisedG, f));
std::swap(G, H);
minimised = false;
}
}
std::string serialise() const
{
return serialisedG;
}
void deserialise(const std::string &s, bool do_inflate)
{
minimised = true;
serialisedG = s;
if (serialisedG.back() == '\n')
serialisedG.pop_back();
cachedHash = std::hash<std::string>()(serialisedG);
if (do_inflate)
inflate();
}
};
// satisfies requirements for CollectibleObject
// prefer CanonicalGraph, which unfortunately does not work for graphs with parallel edges (and loops probably)
class GraphWithHash
{
protected:
bool minimised;
int cachedHash;
Factory f;
Graph G = createG(f);
public:
std::string serialisedG;
GraphWithHash(const Graph &g)
{
G = copy_other_factory(g, f);
cachedHash = internal::isomorphism_graph_hash(G);
serialisedG = write_sparse6(G, false);
minimised = false;
}
GraphWithHash(const std::string &s, bool inflate)
{
deserialise(s, inflate);
}
inline const Graph& graph() const {
if (minimised)
throw std::logic_error("minimised, graph is inaccessible");
else
return G;
}
inline int size() const {
if (minimised)
throw std::logic_error("minimised, graph is inaccessible");
else
return G.order();
}
inline int hash() const { return cachedHash; }
inline void compute_property() const {}
inline bool property_computed() const { return true; }
inline int property_value() const { return 0; }
inline bool operator==(const GraphWithHash &other) const {
if (hash() != other.hash())
return false;
Factory localF;
const Graph *g1;
Graph g1storage = createG(localF);
if (!minimised) {
g1 = &G;
} else {
Graph H = read_graph6_line(serialisedG, localF);
std::swap(g1storage, H);
g1 = &g1storage;
}
const Graph *g2;
Graph g2storage = createG(localF);
if (!other.minimised) {
g2 = &other.G;
} else {
Graph H = read_graph6_line(other.serialisedG, localF);
std::swap(g2storage, H);
g2 = &g2storage;
}
return are_isomorphic(*g1, *g2);
}
inline bool is_minimised() const { return minimised; }
// keep as small memory footprint as possible
// useful for keeping failed candidates in ObjectCollection
void minimise()
{
if (!minimised) {
Graph H = createG(f);
std::swap(G, H); // throw away contents of G
minimised = true;
}
}
// restores after minimization
void inflate()
{
if (minimised) {
Graph H = std::move(read_graph6_line(serialisedG, f));
std::swap(G, H);
minimised = false;
}
}
std::string serialise() const
{
std::stringstream ss;
ss << cachedHash << " " << serialisedG;
return ss.str();
}
void deserialise(const std::string &s, bool do_inflate)
{
minimised = true;
std::stringstream ss(s);
ss >> cachedHash;
if (!ss.good())
throw std::invalid_argument("cannot deserialise GraphWithHash from '" + s + "'");
ss >> serialisedG;
if (serialisedG.back() == '\n')
serialisedG.pop_back();
if (serialisedG.size() < 1)
throw std::invalid_argument("cannot deserialise GraphWithHash from '" + s + "'");
if (do_inflate)
inflate();
}
};
#endif
| true |
1550f9a5df0e2a7c04d7fa0e6132288edeefcac8 | C++ | Luzio5/Programacion-2 | /tarea3/src/cadena.cpp | UTF-8 | 16,939 | 3.203125 | 3 | [] | no_license | /*4307385*/
#include "../include/cadena.h"
#include "../include/info.h"
#include <stddef.h>
#include <stdio.h>
#include <assert.h>
struct nodo {
info_t dato;
nodo *anterior;
nodo *siguiente;
};
struct rep_cadena {
nodo *inicio;
nodo *final;
};
/* Devuelve la cadena_t vacía (sin elementos). */
cadena_t crear_cadena(){
cadena_t res = new rep_cadena;
res->inicio = res->final = NULL;
return res;
}
/*
Se inserta `i' como último elemento de `cad'.
Devuelve `cad'.
Si es_vacia_cadena (cad) `i' se inserta como único elemento de `cad'.
*/
cadena_t insertar_al_final(info_t i, cadena_t cad) {
nodo *nuevo = new nodo;
nuevo->dato = i;
nuevo->siguiente = NULL;
nuevo->anterior = cad->final;
if (cad->final == NULL) {
assert (cad->inicio == NULL);
cad->inicio = nuevo;
} else {
assert (cad->inicio != NULL);
cad->final->siguiente = nuevo;
}
cad->final = nuevo;
return cad;
}
/*
Se inserta `i' como un nuevo elemento inmediatamente antes de `loc'.
Devuelve `cad'.
Precondición: localizador_en_cadena(loc, cad).
*/
cadena_t insertar_antes(info_t i, localizador_t loc, cadena_t cad){
assert (localizador_en_cadena(loc, cad));
if (localizador_en_cadena(loc , cad)) {
nodo *nuevo = new nodo;
nuevo->dato = i;
if (loc == cad->inicio) {
nuevo->anterior = NULL;
nuevo->siguiente = loc;
loc->anterior = nuevo;
cad->inicio = nuevo;
} else {
nuevo->anterior = loc->anterior;
nuevo->siguiente = loc;
loc->anterior->siguiente = nuevo;
loc->anterior = nuevo;
}
}
return cad;
}
/*
Se inserta la cadena_t `sgm' inmediatamente después de `loc' en `cad',
manteniendo los elementos originales y el orden relativo entre ellos.
Devuelve `cad'.
No se debe obtener memoria (los nodos de `sgm' pasan a ser parte de `cad').
Al terminar, `sgm' queda vacía.
Si es_vacia_cadena(cad) `loc' es ignorado y el segmento queda insertado.
Precondición: es_vacia_cadena(cad) o localizador_en_cadena(loc, cad).
*/
cadena_t insertar_segmento_despues (cadena_t &sgm, localizador_t loc,
cadena_t cad) {
assert(es_vacia_cadena(cad) || localizador_en_cadena(loc, cad));
if (es_vacia_cadena(cad)) {
cad->inicio = sgm->inicio;
cad->final = sgm->final;
} else {
if (!es_vacia_cadena(sgm)) {
sgm->inicio->anterior = loc;
sgm->final->siguiente = loc->siguiente;
if (es_final_cadena(loc, cad))
cad->final = sgm->final;
else
loc->siguiente->anterior = sgm->final;
loc->siguiente = sgm->inicio;
}
}
sgm->inicio = sgm->final = NULL;
return cad;
}
/*
Devuelve una cadena_t con los elementos de `cad' que se encuentran entre
`desde' y `hasta', incluidos.
La cadena_t resultado no comparte memoria con `cad'.
Si es_vacia_cadena(cad) devuelve la cadena_t vacia.
Precondición: es_vacia_cadena(cad) o precede_en_cadena(desde, hasta, cad).
*/
cadena_t copiar_segmento(localizador_t desde, localizador_t hasta,
cadena_t cad){
assert (es_vacia_cadena(cad) || precede_en_cadena(desde, hasta, cad));
cadena_t res = crear_cadena();
if(!es_vacia_cadena(cad)){
localizador_t loc = desde;
while (loc != siguiente(hasta, cad)){
//ERROR compartiria memoria
//info_t info = loc->dato;
info_t info = copia_info((loc->dato));
insertar_al_final(info, res);
loc = siguiente (loc,cad);
}
}
return res;
}
/*
Remueve de `cad' los elementos que se encuentran entre `desde' y `hasta',
incluidos y libera la memoria que tenían asignada y la de sus nodos.
Devuelve `cad'.
Si es_vacia_cadena(cad) devuelve la cadena_t vacía.
Precondición: es_vacia_cadena(cad) o precede_en_cadena(desde, hasta, cad).
*/
cadena_t cortar_segmento(localizador_t desde, localizador_t hasta, cadena_t cad){
assert (es_vacia_cadena(cad) || precede_en_cadena(desde, hasta, cad));
if (!es_vacia_cadena(cad)) {
cadena_t cad_a_borrar = crear_cadena();
localizador_t loc_aux = desde;
cad_a_borrar->inicio = loc_aux;
while (loc_aux != hasta) {
loc_aux = loc_aux->siguiente;
}
cad_a_borrar->final = loc_aux;
if (es_inicio_cadena(desde, cad) && es_final_cadena(hasta, cad)) {
cad->inicio = cad->final = NULL;
} else if (!es_inicio_cadena(desde, cad) && !es_final_cadena(hasta, cad)) {
desde->anterior->siguiente = hasta->siguiente;
desde->anterior->siguiente->anterior = desde->anterior;
desde->anterior = NULL;
hasta->siguiente = NULL;
} else if (!es_inicio_cadena(desde, cad) && es_final_cadena(hasta, cad)) {
desde->anterior->siguiente = NULL;
cad->final = desde->anterior;
desde->anterior = NULL;
} else if (es_inicio_cadena(desde, cad) && !es_final_cadena(hasta, cad)) {
hasta->siguiente->anterior = NULL;
cad->inicio = hasta->siguiente;
desde->anterior = NULL;
hasta->siguiente = NULL;
}
liberar_cadena(cad_a_borrar);
}
return cad;
}
/*
Se quita el elemento al que se accede desde `loc' y se libera la memoria
asignada al mismo y al nodo apuntado por el localizador.
Devuelve `cad'.
El valor de `loc' queda indeterminado.
Precondición: localizador_en_cadena(loc, cad).
*/
cadena_t remover_de_cadena(localizador_t &loc, cadena_t cad){
assert (localizador_en_cadena(loc, cad));
nodo *a_borrar;
a_borrar = loc;
if ((!es_inicio_cadena(loc, cad)) && (!es_final_cadena(loc, cad))){
localizador_t aux = loc->anterior;
aux->siguiente = loc->siguiente;
aux = aux->siguiente;
aux->anterior = loc->anterior;
} else if ((es_inicio_cadena(loc, cad)) && (!es_final_cadena(loc, cad))) {
localizador_t aux = loc;
aux = aux->siguiente;
aux->anterior = NULL;
cad->inicio = aux;
} else if ((es_final_cadena(loc, cad)) && (!es_inicio_cadena(loc, cad))) {
localizador_t aux = loc;
aux = aux->anterior;
aux->siguiente = NULL;
cad->final = aux;
} else if ((es_inicio_cadena(loc,cad)) && (es_final_cadena(loc, cad))) {
cad->inicio = cad->final = NULL;
}
liberar_info(a_borrar->dato);
delete a_borrar;
loc = NULL;
return cad;
}
/*
Libera la memoria asignada a `cad' y la de todos sus elementos.
Devuelve `cad'.
*/
cadena_t liberar_cadena(cadena_t cad){
nodo *a_borrar;
while (cad->inicio != NULL){
a_borrar = cad->inicio;
cad->inicio = cad->inicio->siguiente;
liberar_info(a_borrar->dato);
delete a_borrar;
}
delete cad;
return cad;
}
/*
Devuelve `true' si y sólo si `loc' es un localizador_t válido.
En cadenas enlazadas un localizador_t no es válido si es `NULL'.
*/
bool es_localizador(localizador_t loc){return loc != NULL;}
/* Devuelve `true' si y sólo si `cad' es vacía (no tiene elementos). */
bool es_vacia_cadena(cadena_t cad){
return (cad->inicio==NULL) && (cad->final==NULL);
}
/*
Devuelve `true' si y sólo si con `loc' se accede al último elemento de `cad'.
Si es_vacia_cadena (cad) devuelve `false'.
*/
bool es_final_cadena(localizador_t loc, cadena_t cad){
return ((loc == cad->final) && (!es_vacia_cadena(cad)));
}
/*
Devuelve `true' si y sólo si con `loc' se accede al primer elemento de `cad'.
Si es_vacia_cadena (cad) devuelve `false'.
*/
bool es_inicio_cadena(localizador_t loc, cadena_t cad){
return ((loc == cad->inicio) && (!es_vacia_cadena(cad)));
}
/*
Devuelve `true' si y sólo si con `loc' se accede a un elemento de `cad',
(o sea, si apunta a un nodo de `cad').
Si es_vacia_cadena (cad) devuelve `false'.
*/
bool localizador_en_cadena(localizador_t loc, cadena_t cad){
localizador_t cursor = inicio_cadena (cad);
while (es_localizador(cursor) && (cursor != loc)){
cursor = siguiente(cursor, cad);
}
return es_localizador(cursor);
}
/*
Devuelve `true' si y sólo si `loc1' es igual o precede a `loc2` en `cad`.
Si es_vacia_cadena (cad) devuelve `false'.
*/
bool precede_en_cadena(localizador_t loc1, localizador_t loc2, cadena_t cad){
bool todo_ok = false;
localizador_t aux2;
localizador_t aux1;
if (!es_vacia_cadena(cad)){
aux1 = cad->inicio;
aux2 = cad->inicio;
int i=1;
int j=1;
while ((aux1!=loc1) && (aux1!=NULL)) {
i++;
aux1 = aux1->siguiente;
}
while ((aux2!=loc2) && (aux2!=NULL)) {
j++;
aux2 = aux2->siguiente;
}
if (i<=j){
todo_ok=true;
}
}
return todo_ok;
}
/*
Devuelve el localizador_t con el que se accede al inicio de `cad`.
Si es_vacia_cadena(cad) devuelve un localizador_t no válido.
*/
localizador_t inicio_cadena(cadena_t cad){
localizador_t res;
if (es_vacia_cadena(cad)){
res=NULL;
} else {
res = cad->inicio;
}
return res;
}
/*
Devuelve el localizador_t con el que se accede al final de `cad'.
Si es_vacia_cadena(cad) devuelve un localizador_t no válido.
*/
localizador_t final_cadena(cadena_t cad){
localizador_t res;
if (es_vacia_cadena(cad)){
res = NULL;
} else {
res = cad->final;
}
return res;
}
/*
Devuelve el localizador_t con el que se accede al k-esimo elemento de `cad'.
Si `k' es 0 o mayor a la cantidad de elementos de `cad' devuelve un localizdor
no válido.
*/
localizador_t kesimo(nat k, cadena_t cad){
localizador_t res;
if (k==0) {
res = NULL;
} else {
nat i = 1;
localizador_t aux = cad->inicio;
while ((i<k) && (aux->siguiente != NULL)){
aux = aux->siguiente;
i++;
}
if (i==k){
res = aux;
} else {
res = NULL;
}
}
return res;
}
/*
Devuelve el localizador_t con el que se accede al elemento de `cad'
inmediatamente siguiente a `loc'.
Si es_final_cadena(loc, cad) devuelve un localizador_t no válido.
Precondición: localizador_en_cadena(loc, cad).
*/
localizador_t siguiente(localizador_t loc, cadena_t cad){
assert (localizador_en_cadena(loc , cad));
localizador_t res;
if (es_final_cadena(loc, cad)){
res = NULL;
} else {
res = loc->siguiente;
}
return res;
}
/*
Devuelve el localizador_t con el que se accede al elemento de `cad'
inmediatamente anterior a `loc'.
Si es_inicio_cadena(loc, cad) devuelve un localizador_t no válido.
Precondición: localizador_en_cadena(loc, cad).
*/
localizador_t anterior(localizador_t loc, cadena_t cad){
assert (localizador_en_cadena(loc , cad));
localizador_t res;
if (es_inicio_cadena(loc, cad)) {
res = NULL;
} else {
res = loc->anterior;
}
return res;
}
/*
Devuelve el localizador_t con el que se accede al elemento cuyo dato numérico
es el menor en el segmento que va desde `loc' hasta el final_cadena(cad).
Si hay más de un elemento cuyo valor es el menor el resultado accede al que
precede a los otros.
Precondición: localizador_en_cadena(loc, cad).
*/
localizador_t menor_en_cadena(localizador_t loc, cadena_t cad){
assert (localizador_en_cadena(loc , cad));
localizador_t res = loc;
while (es_localizador(siguiente(loc, cad))) {
loc = siguiente (loc, cad);
if (numero_info(info_cadena(loc, cad)) < numero_info (info_cadena(res, cad)))
res = loc;
}
return res;
}
/*
Devuelve el primer localizador_t con el que se accede a un elemento cuyo dato
numérico es igual a `clave', buscando desde `loc' (inclusive) hacia el final
de `cad'.
Si no se encuentra o `cad' es vacía devuelve un localizador_t no válido.
Precondición: es_vacia_cadena(cad) o localizador_en_cadena(loc, cad).
*/
localizador_t siguiente_clave(int clave, localizador_t loc, cadena_t cad){
assert (es_vacia_cadena(cad) || localizador_en_cadena (loc, cad));
localizador_t res = loc;
if (es_vacia_cadena (cad))
res = NULL;
else {
while (es_localizador(res) && numero_info(info_cadena(res, cad)) != clave)
res = siguiente (res , cad);
}
return res;
}
/*
Devuelve el elemento de `cad' al que se accede con `loc'.
Precondición: localizador_en_cadena(loc, cad).
*/
info_t info_cadena(localizador_t loc, cadena_t cad){
assert (localizador_en_cadena(loc, cad));
return (loc->dato);
}
/*
Sustituye con `i' el elemento de `cad' al que se accede con `loc'.
Devuelve `cad'.
No destruye el elemento al que antes se accedía con `loc'.
Precondición: localizador_en_cadena(loc, cad).
*/
cadena_t cambiar_en_cadena(info_t i, localizador_t loc, cadena_t cad){
assert (localizador_en_cadena(loc, cad));
loc->dato = i;
return cad;
}
/*
Intercambia los elementos a los que se accede con `loc1' y `loc2'.
`loc1' y `loc2' mantienen su relación de precedencia.
Devuelve `cad'.
Precondición:
localizador_en_cadena (loc1, cad)
y localizador_en_cadena (loc2, cad).
*/
cadena_t intercambiar(localizador_t loc1, localizador_t loc2, cadena_t cad){
assert (localizador_en_cadena (loc1, cad) && localizador_en_cadena(loc2, cad));
if (loc1 != loc2) {
localizador_t loc_aux2;
localizador_t loc_aux1;
if (precede_en_cadena (loc1, loc2, cad)) {
loc_aux1 = loc1;
loc_aux2 = loc2;
} else { // los doy vuelta
loc_aux2 = loc1;
loc_aux1 = loc2;
}
localizador_t cad_aux;
if ((!es_inicio_cadena(loc_aux1, cad)) && (!es_final_cadena(loc_aux2, cad))) {
localizador_t aux = loc_aux2->siguiente;
cad_aux=loc_aux1->anterior;
cad_aux->siguiente = loc_aux2;
cad_aux->siguiente->anterior = cad_aux;
cad_aux = cad_aux->siguiente;
if (loc_aux1->siguiente == cad_aux) {
loc_aux1->siguiente = loc_aux2->siguiente;
loc_aux1->siguiente->anterior = loc_aux1;
cad_aux->siguiente = loc_aux1;
cad_aux->siguiente->anterior = cad_aux;
} else {
cad_aux->siguiente = loc_aux1->siguiente;
cad_aux->siguiente->anterior = cad_aux;
while (cad_aux->siguiente != loc_aux2) {
cad_aux=cad_aux->siguiente;
}
loc_aux1->siguiente = aux;
loc_aux1->siguiente->anterior = loc_aux1;
cad_aux->siguiente = loc_aux1;
cad_aux->siguiente->anterior = cad_aux;
}
} else if ((es_inicio_cadena(loc_aux1, cad)) && (!es_final_cadena(loc_aux2, cad))) {
localizador_t aux = loc_aux2->siguiente;
cad_aux = loc_aux2;
cad->inicio = cad_aux;
cad_aux->anterior = NULL;
if (loc_aux1->siguiente == cad_aux) {
loc_aux1->siguiente=loc_aux2->siguiente;
loc_aux1->siguiente->anterior = loc_aux1;
cad_aux->siguiente = loc_aux1;
cad_aux->siguiente->anterior = cad_aux;
cad->inicio = loc_aux2;
} else {
cad_aux->siguiente = loc_aux1->siguiente;
cad_aux->siguiente->anterior = cad_aux;
while (cad_aux->siguiente != loc_aux2) {
cad_aux=cad_aux->siguiente;
}
loc_aux1->siguiente = aux;
loc_aux1->siguiente->anterior = loc_aux1;
cad_aux->siguiente = loc_aux1;
cad_aux->siguiente->anterior = cad_aux;
cad->inicio = loc_aux2;
}
} else if ((!es_inicio_cadena(loc_aux1, cad)) && (es_final_cadena(loc_aux2, cad))) {
cad_aux=loc_aux1->anterior;
cad_aux->siguiente = loc_aux2;
cad_aux->siguiente->anterior = cad_aux;
cad_aux = cad_aux->siguiente;
if (loc_aux1->siguiente == cad_aux) {
cad_aux->siguiente = loc_aux1;
cad_aux->siguiente->anterior = cad_aux;
cad_aux->siguiente->siguiente = NULL;
cad->final = loc_aux1;
} else {
cad_aux->siguiente = loc_aux1->siguiente;
cad_aux->siguiente->anterior = cad_aux;
while (cad_aux->siguiente != loc_aux2){
cad_aux=cad_aux->siguiente;
}
loc_aux1->siguiente = NULL;
cad_aux->siguiente = loc_aux1;
cad_aux->siguiente->anterior = cad_aux;
cad->final = loc_aux1;
}
} else if ((es_inicio_cadena(loc_aux1, cad)) && (es_final_cadena(loc_aux2, cad))) {
cad_aux = loc_aux2;
cad->inicio = cad_aux;
cad_aux->anterior = NULL;
cad_aux->siguiente = loc_aux1->siguiente;
cad_aux->siguiente->anterior = cad_aux;
while (cad_aux->siguiente != loc_aux2) {
cad_aux = cad_aux->siguiente;
}
cad_aux->siguiente = loc_aux1;
cad_aux->siguiente->anterior = cad_aux;
cad_aux->siguiente->siguiente = NULL;
cad->final = loc_aux1;
cad->inicio = loc_aux2;
}
}
localizador_t ayuda = loc2;
loc2=loc1;
loc1=ayuda;
return cad;
}
/*
Imprime los elementos de `cad` de la siguiente forma:
(dn de pos1,fr de pos1)(dn de pos2,fr de pos2) ...
donde `dn` es el dato numérico y `fr` es la frase.
Antes de terminar, se debe imprimir un fin de linea.
Si es_vacia_cadena(cad) sólo se imprime el fin de línea.
*/
void imprimir_cadena(cadena_t cad){
localizador_t aux = cad->inicio;
while (aux!=NULL) {
printf("(%d,%s)", numero_info(aux->dato), frase_info(aux->dato));
aux = aux->siguiente;
}
printf("\n");
}
| true |
5728070d948c92cf2abd594f52d3378baf981569 | C++ | MDOUBRE/Embedded-Projects | /Streamdeck/streamdeck_arduino/test_streamdeck.ino | UTF-8 | 1,734 | 2.515625 | 3 | [] | no_license | #include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Keypad.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels
#define OLED_RESET 4 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
//int sortie = 2;
int entree = 5;
int appuie=LOW;
int enCours=0;
void setup() {
//Serial.begin(9600);
//randomSeed(analogRead(0));
// SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
if(!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever
}
display.display();
delay(2000);
display.clearDisplay();
//pinMode(sortie,OUTPUT);
pinMode(entree,INPUT);
//digitalWrite(sortie,HIGH);
}
void loop() {
appuie=digitalRead(entree);
if(appuie==HIGH && enCours==0){
enCours=enCours+1;
TP1();
//Serial.print("coucou");
delay(500);
}
else if(appuie==HIGH && enCours==1){
enCours=enCours-1;
logoTP1();
//Serial.print(appuie/4);
//Serial.print("ah");
delay(500);
}
//Serial.print("ah");
//delay(1000);
}
void TP1()
{
display.clearDisplay();
display.setCursor(28,9);
display.setTextSize(1.7,2);
display.setTextColor(SSD1306_WHITE);
display.println(F("TantePanique"));
display.display();
}
void logoTP1()
{
display.clearDisplay();
display.drawChar(55,9,'T',SSD1306_WHITE,1,2);
display.drawChar(66,9,'P',SSD1306_WHITE,1,2);
display.display();
}
| true |
b176b2315dfb3ba46302e089e7ea67502ae37aaa | C++ | rickarkin/PyMesh-win | /tools/MeshUtils/FinFaceRemoval.h | UTF-8 | 1,505 | 2.734375 | 3 | [] | no_license | /* This file is part of PyMesh. Copyright (c) 2015 by Qingnan Zhou */
#pragma once
#include <Core/EigenTypedef.h>
namespace PyMesh {
/**
* This class removes duplicated triangle faces.
* Two faces are duplicates of each other if they consist of the same 3
* vertices.
*/
class FinFaceRemoval {
public:
FinFaceRemoval(const MatrixFr& vertices, const MatrixIr& faces);
public:
/**
* Only remove fins. A fin is defined as a pair of faces with identical
* vertices but opposite orientaiton.
*/
void set_fins_only() {
m_fins_only = true;
}
/**
* When set_fins_only() is called:
* Only fins are removed.
*
* Otherwise:
*
* For each set of duplicated faces, if there is a majority orientation,
* all but a single face is removed. The face kept has the same
* orientation as the majority orientation. This is necessary to remove
* "folds".
*
* If there is no majority orientation, all faces in the set are
* removed. This is necessary in removing "fins".
*/
size_t run();
MatrixFr get_vertices() const { return m_vertices; }
MatrixIr get_faces() const { return m_faces; }
VectorI get_face_indices() const { return m_face_indices; }
private:
bool m_fins_only;
MatrixFr m_vertices;
MatrixIr m_faces;
VectorI m_face_indices;
};
}
| true |
ed9e64f2694603f8a371b2b068ed1f476acb54bc | C++ | hicdre/skiaui | /skia/experimental/Intersection/QuadraticBezierClip.cpp | UTF-8 | 2,690 | 2.578125 | 3 | [
"BSD-3-Clause"
] | permissive | /*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "CurveIntersection.h"
#include "CurveUtilities.h"
#include "LineParameters.h"
#include <algorithm> // used for std::swap
#define DEBUG_BEZIER_CLIP 1
// return false if unable to clip (e.g., unable to create implicit line)
// caller should subdivide, or create degenerate if the values are too small
bool bezier_clip(const Quadratic& q1, const Quadratic& q2, double& minT, double& maxT) {
minT = 1;
maxT = 0;
// determine normalized implicit line equation for pt[0] to pt[3]
// of the form ax + by + c = 0, where a*a + b*b == 1
// find the implicit line equation parameters
LineParameters endLine;
endLine.quadEndPoints(q1);
if (!endLine.normalize()) {
printf("line cannot be normalized: need more code here\n");
assert(0);
return false;
}
double distance = endLine.controlPtDistance(q1);
// find fat line
double top = 0;
double bottom = distance / 2; // http://students.cs.byu.edu/~tom/557/text/cic.pdf (7.6)
if (top > bottom) {
std::swap(top, bottom);
}
// compute intersecting candidate distance
Quadratic distance2y; // points with X of (0, 1/2, 1)
endLine.quadDistanceY(q2, distance2y);
int flags = 0;
if (approximately_lesser(distance2y[0].y, top)) {
flags |= kFindTopMin;
} else if (approximately_greater(distance2y[0].y, bottom)) {
flags |= kFindBottomMin;
} else {
minT = 0;
}
if (approximately_lesser(distance2y[2].y, top)) {
flags |= kFindTopMax;
} else if (approximately_greater(distance2y[2].y, bottom)) {
flags |= kFindBottomMax;
} else {
maxT = 1;
}
// Find the intersection of distance convex hull and fat line.
int idx = 0;
do {
int next = idx + 1;
if (next == 3) {
next = 0;
}
x_at(distance2y[idx], distance2y[next], top, bottom, flags, minT, maxT);
idx = next;
} while (idx);
#if DEBUG_BEZIER_CLIP
_Rect r1, r2;
r1.setBounds(q1);
r2.setBounds(q2);
_Point testPt = {0.487, 0.337};
if (r1.contains(testPt) && r2.contains(testPt)) {
printf("%s q1=(%1.9g,%1.9g %1.9g,%1.9g %1.9g,%1.9g)"
" q2=(%1.9g,%1.9g %1.9g,%1.9g %1.9g,%1.9g) minT=%1.9g maxT=%1.9g\n",
__FUNCTION__, q1[0].x, q1[0].y, q1[1].x, q1[1].y, q1[2].x, q1[2].y,
q2[0].x, q2[0].y, q2[1].x, q2[1].y, q2[2].x, q2[2].y, minT, maxT);
}
#endif
return minT < maxT; // returns false if distance shows no intersection
}
| true |
0d85d5b440915492a9c52886854220a22b114d73 | C++ | eelfgnc/Object-Oriented-Programming1-Lab. | /Lab 05/Quiz5/Automobile.cpp | UTF-8 | 814 | 2.96875 | 3 | [] | no_license | #include "Automobile.h"
#include"Vehicle.h"
/**
*\brief Yapici Fonksiyon
*\param passengerCount: Aracin yolcu sayisina esit olur.
*\param productionYear: Aracin uretim yilina esit olur.
*\param tireCount: Aracin tekerlek sayisina esit olur.
*\param maxSpeed: Aracin maksimum hizina esit olur.
*/
Automobile::Automobile(int passengerCount, const string& productionYear, int tireCount, int maxSpeed):RoadVehicle(passengerCount, productionYear, tireCount),m_maxSpeed(maxSpeed)
{
cout << "Maximum speed: " << m_maxSpeed << endl;
}
/**
*\brief Aracin hareket ettigini bildiren fonksiyon
*/
void Automobile::DriveOnRoad()
{
cout << "Driving On Road..." << endl;
}
/**
*\brief Yikici Fonksiyon.Arac program icerisindeki kapsama alanindan cikarsa cagrilan fonksiyon.
*/
Automobile::~Automobile(){} | true |
702b4755f2189e9fae26206358a35c63f400c0e6 | C++ | amillerbrowne/BUCommunityApp | /DataBase/Colleges/don't touch/getColleges.cpp | UTF-8 | 984 | 3.09375 | 3 | [] | no_license | //created by Nicholas Maresco 3/5/15
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string line;
int name_start, name_end, size, line_number = 1;
ifstream raw_college_file("raw_BUColleges.txt");
ofstream official_college_file ("BUColleges.txt");
//check successful file open
if(raw_college_file.is_open())
{
//go line by line
while(getline(raw_college_file,line))
{
//finds locations of all colleges in text
name_start = line.find("<h3>") + 4;
name_end = line.find("</h3>");
//eliminates false readings
if(name_start > 2 && name_end > 2){
//console prints college names && writes them to txt file
for(int ii = name_start; ii < name_end; ii++){
cout << line[ii];
official_college_file << line[ii];
}
//adds newline to output file
official_college_file << endl;
cout << endl;
}
}
raw_college_file.close();
official_college_file.close();
}
else cout << "Unable to open file." << endl;
return 0;
}
| true |
a78e13424e567212ed9dde66ee15b33859e0e312 | C++ | dheerwani/competetive_coding | /2_d_array/suffix_sum_matrix.cpp | UTF-8 | 696 | 2.578125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{
int r,c;
cin>>r>>c;
int a[r][c];
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
cin>>a[i][j];
}
}
int suffsum[r][c];
suffsum[r-1][c-1] = a[r-1][c-1];
for(int i=r-2;i>=0;i--)
{
suffsum[i][c-1] = suffsum[i+1][c-1] + a[i][c-1];
}
for(int i=c-2;i>=0;i--)
{
suffsum[r-1][i] = suffsum[r-1][i+1] + a[r-1][i];
}
for(int i=r-2;i>=0;i--)
{
for(int j=c-2;j>=0;j--)
{
suffsum[i][j] = suffsum[i][j+1] + suffsum[i+1][j] - suffsum[i+1][j+1] + a[i][j];
}
}
int result = INT_MIN;
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
result = max(result,suffsum[i][j]);
}
}
cout<<endl<<result;
return 0;
} | true |
9d84bb240502770fb3fc528f17e9d9c6dcb325e7 | C++ | ptokponnon/Utils | /StackT.hpp | UTF-8 | 714 | 2.75 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: StackT.hpp
* Author: parfait
*
* Created on 26 septembre 2018, 16:10
*/
#ifndef STACKT_HPP
#define STACKT_HPP
#include <cstdlib>
#include <iostream>
#include "Stack.hpp"
using namespace std;
namespace StackT {
int main(int argc, char** argv) {
Stack<int> s;
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
s.push(6);
s.pop();
cout << "new stack\n";
s.print();
return 0;
}
}
#endif /* STACKT_HPP */
| true |
d3e712ea991c47e1dceb3c10bff0d153266a5334 | C++ | tyhenry/ofxPointCloudLibrary | /src/ofxPointCloudLibrary/Types.hpp | UTF-8 | 1,746 | 2.703125 | 3 | [
"MIT"
] | permissive | #pragma once
#include "ofMain.h"
#include "ofxPointCloudLibrary/Common.hpp"
namespace ofxPointCloudLibrary {
// Point
using Point = pcl::PointXYZ;
// Point Cloud
using PointCloud = pcl::PointCloud<pcl::PointXYZ>;
struct PointCloudData
{
PointCloudData() {}
PointCloudData( const PointCloud& pc )
: nPoints( pc.size() ), width( pc.width ), height( pc.height ), isDense( pc.is_dense ) {}
size_t nPoints = 0;
size_t width = 0; // if height is 1, width == nPoints, otherwise number of columns in image-structured point cloud (rows + cols)
size_t height = 1; // 1 means unstructured data, >1 means number of rows of structured data
bool isDense = false;
// TODO - add support for:
// pcl::PCLHeader header; // The point cloud header. It contains information about the acquisition time.
// Eigen::Vector4f sensor_origin_; // Sensor acquisition pose (origin/translation).
// Eigen::Quaternionf sensor_orientation_; // Sensor acquisition pose (rotation).
};
// ------------------------
// oF <--> PCL conversions
// ------------------------
// Point
inline glm::vec3 toOf( const Point& point )
{
return { point.x, point.y, point.z };
}
inline Point toPcl( const glm::vec3& point )
{
return { point.x, point.y, point.z };
}
// PointCloud
inline std::vector<glm::vec3> toOf( const PointCloud& pointCloud )
{
std::vector<glm::vec3> points;
points.reserve( pointCloud.size() );
for ( const auto& p : pointCloud ) {
points.emplace_back( p.x, p.y, p.z );
}
}
inline PointCloud toPcl( const std::vector<glm::vec3>& points )
{
auto pc = PointCloud( points.size(), 1 );
for ( int i = 0; i < points.size(); ++i ) pc[i] = toPcl( points[i] );
return pc;
}
} // namespace ofxPointCloudLibrary | true |
b511b27f897b6a27800542391d6f7937b85bd141 | C++ | veedee2000/Competitive-Programming | /GeeksForGeeks/Interview/Math/LCM.cpp | UTF-8 | 741 | 3.125 | 3 | [] | no_license | long long f(int base,int exp){
if(exp == 0) return 1;
else if(exp&1) return base * f(base,exp / 2) * f(base,exp / 2);
else return f(base, exp / 2) * f(base, exp / 2);
}
long long getSmallestDivNum(long long n){
long long ans = 1;
vector<int> primes = {2,3,5,7,11,13,17,19,23};
vector<int>v(primes.size(),0);
int x, val;
for(int i = 2;i <= n;i++){
x = i;
for(int j = 0;j < primes.size();j++){
val = 0;
while(x >= primes[j] and (x % primes[j] == 0)){
x /= primes[j];
val++;
}
v[j] = max(v[j],val);
}
}
for(int i = 0;i < primes.size();i++){
ans *= f(primes[i],v[i]);
}
return ans;
}
| true |
cd410fde47db1967cf7d39caef42e1e31ae2c996 | C++ | stonesha/UNR-CS | /CS 202/PA4_Sha_Stone/Agency.h | UTF-8 | 696 | 2.921875 | 3 | [] | no_license | #ifndef AGENCY_H
#define AGENCY_H
#include "func.h"
#include "Car.h"
class Agency
{
public:
Agency();
//GET AND SET FUNCTIONS ==============================
char *getName();
int getZipcode();
void setName(char temp[MAX_CHAR]);
void setZipcode(int temp);
//==============================================
Car operator[](const int index);
friend std::istream& operator>>(std::istream& inFile, Agency &agencyPtr);
void printAll();
void printAvailable();
Car *returnPtr();
private:
char m_name[MAX_CHAR];
int m_zipcode;
Car m_inventory[MAX_CAR];
};
#endif // AGENCY_H
| true |
950d7aae30d43414258c38360815e3ec54da7cc2 | C++ | AlbertPuwadol/2D-Data-Communication | /Assign/Test/ServoV2.5/ServoV2.5.ino | UTF-8 | 1,480 | 2.8125 | 3 | [] | no_license | #include <Servo.h>
Servo myServo;
char order;
void rotateR45() {
int detect = myServo.read();
for (int i = detect; i > detect - 45; i--) {
myServo.write(i);
delay(50);
}
Serial.print("c");
}
void rotateAll45(int dest) {
int detect = myServo.read();
if (detect <= dest) {
for (int i = detect; i <= dest; i++) {
myServo.write(i);
delay(50);
}
}
else {
for (int i = detect; i > dest; i--) {
myServo.write(i);
delay(50);
}
}
Serial.print("c");
}
void goStart() {
if (myServo.read() <= 135) {
for (int i = myServo.read(); i <= 135; i++) {
myServo.write(i);
delay(50);
}
}
else {
for (int i = myServo.read(); i > 135; i--) {
myServo.write(i);
delay(50);
}
}
order = '\0';
}
void setup() {
Serial.begin(9600);
pinMode(2, OUTPUT);
pinMode(9, OUTPUT);
pinMode(10, INPUT);
myServo.attach(13);
goStart();
//Serial.print("Start");
digitalWrite(2, LOW);
}
void loop() {
if (Serial.available() > 0) {
digitalWrite(2, HIGH);
order = Serial.read();
}
else
digitalWrite(2, LOW);
if (order == 's') {//start
//
if (myServo.read() <= 50) {
goStart();
//Serial.print("f");
}
else {
rotateR45();
}
}
else if (order == 'l'){
rotateAll45(135);
}
else if (order == 'm'){
rotateAll45(90);
}
else if (order == 'r'){
rotateAll45(45);
}
else if (order == 'e'){
goStart();
}
}
| true |
34f823f369b3c319e552b5f1f8d9420a67314f17 | C++ | leandrovianna/programming_contests | /lib/fenwick.cpp | UTF-8 | 380 | 2.515625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
const int N = 2*1e5+10;
int bit[N];
// execute the query [1, x]
int query(int x) {
int s = 0;
while (x) {
s += bit[x];
x -= (x & -x);
}
return s;
}
// execute the update [1,x]
void update(int x, int v) {
while (x <= N) {
bit[x] += v;
x += (x & -x);
}
}
int main() {
ios::sync_with_stdio(false);
return 0;
}
| true |
ec59bafcbdd56088b4caa0f354d742912234b9b3 | C++ | bzxing/container_benchmark | /src/main.cpp | UTF-8 | 2,666 | 3.0625 | 3 | [] | no_license |
#include <algorithm>
#include <iterator>
#include <memory>
#include <set>
#include <string>
#include <unordered_set>
#include <boost/container/flat_set.hpp>
#include "profiler.hpp"
#include "rand_gen.hpp"
using INT_TYPE = uint64_t;
static constexpr INT_TYPE seed = 1;
static constexpr INT_TYPE rand_range = 20;
static constexpr size_t num_iters = 1'000'000;
struct HASH;
class MY_OBJ
{
public:
friend struct HASH;
MY_OBJ(RAND_GEN<INT_TYPE> & rand_gen)
:
_a(rand_gen.get()),
_b(rand_gen.get()),
_c(rand_gen.get()),
_d(rand_gen.get())
{
}
friend bool operator<(const MY_OBJ & a, const MY_OBJ & b)
{
if (a._a != b._a)
{
return a._a < b._a;
}
else if (a._b != b._b)
{
return a._b < b._b;
}
else if (a._c != b._c)
{
return a._c < b._c;
}
else if (a._d != b._d)
{
return a._d < b._d;
}
else
{
return false;
}
}
size_t hash() const
{
return std::hash<INT_TYPE>()(_a ^ _b ^ _c ^ _d);
}
friend bool operator==(const MY_OBJ & a, const MY_OBJ & b)
{
return a._a == b._a &&
a._b == b._b &&
a._c == b._c &&
a._d == b._d;
}
private:
INT_TYPE _a;
INT_TYPE _b;
INT_TYPE _c;
INT_TYPE _d;
};
struct HASH
{
size_t operator()(const MY_OBJ & obj) const
{
return obj.hash();
}
};
using ELEM_TYPE = MY_OBJ;
auto make_rand_gen()
{
return RAND_GEN<INT_TYPE>::make(seed, 1, rand_range);
}
template <class SET_TYPE>
void do_random_insertion(SET_TYPE & my_set)
{
auto rand_gen = make_rand_gen();
for (size_t i = 0; i < num_iters; ++i)
{
my_set.emplace(*rand_gen);
}
}
template <class SET_TYPE>
void do_sequential_traversal(const SET_TYPE & my_set)
{
size_t total_hash = 0;
for (const auto & elem : my_set)
{
total_hash = total_hash ^ elem.hash();
}
std::cout << "Traversal result: " << total_hash << std::endl;
}
void flat_set()
{
PROFILER p("flat_set");
boost::container::flat_set<ELEM_TYPE> my_set;
my_set.reserve(rand_range);
do_random_insertion(my_set);
do_sequential_traversal(my_set);
}
void std_set()
{
PROFILER p("std_set");
std::set<ELEM_TYPE> my_set;
do_random_insertion(my_set);
do_sequential_traversal(my_set);
}
void hash_set()
{
PROFILER p("hash_set");
std::unordered_set<ELEM_TYPE, HASH> my_set;
my_set.reserve(rand_range * 4);
do_random_insertion(my_set);
std::cout << "Load factor: " << my_set.load_factor() << std::endl;
std::vector<ELEM_TYPE> vec;
vec.reserve(my_set.size());
{
PROFILER p("std::copy");
std::copy(my_set.begin(), my_set.end(), std::back_inserter(vec));
}
{
PROFILER p("std::sort");
std::sort(vec.begin(), vec.end());
}
}
int main()
{
std_set();
hash_set();
flat_set();
return 0;
}
| true |
99d88dc631744220fa315c4c9bf16af1bedd4767 | C++ | RosinaGeorgieva/ObjectOrientedProgramming2021 | /Practicum/week 10/MultipleInheritanceTest/Source.cpp | UTF-8 | 1,370 | 3.640625 | 4 | [] | no_license | #include <iostream>
// закоментирайте необходимото за всяка подточка
class BaseClass1 {
public:
int a;
BaseClass1() {
a = 1;
}
BaseClass1(int a) {
this->a = a;
}
BaseClass1(const BaseClass1& rhs) {
a = rhs.a;
}
BaseClass1& operator=(const BaseClass1& rhs) {
if (this != &rhs) {
a = rhs.a;
}
return *this;
}
};
class BaseClass2 {
public:
int b;
BaseClass2() {
b = 2;
}
BaseClass2(int b) {
this->b = b;
}
BaseClass2(const BaseClass2& rhs) {
b = rhs.b;
}
BaseClass2& operator=(const BaseClass2& rhs) {
if (this != &rhs) {
b = rhs.b;
}
return *this;
}
};
class DerivedClass : public BaseClass1, public BaseClass2 {
public:
DerivedClass() {
a = 1;
}
DerivedClass(const DerivedClass& rhs) {
a = rhs.a;
b = rhs.b;
}
DerivedClass& operator=(const DerivedClass& rhs) {
if (this != &rhs) {
a = rhs.a;
b = rhs.b;
}
return *this;
}
};
int main() {
DerivedClass d;
std::cout << d.a << "-" << d.b;
DerivedClass copyD(d);
std::cout << copyD.a << "-" << copyD.b;
DerivedClass c;
c.a = 3;
c.b = 4;
std::cout << c.a << "-" << c.b;
DerivedClass e;
e.a = 5;
e.b = 6;
std::cout << e.a << "-" << e.b;
c = e;
std::cout << c.a << "-" << c.b;
return 0;
} | true |
3211d60cfd104f0c33cb68f241720ff24077ac55 | C++ | gauzinge/MSSD_Analysis | /src/annealing.cc | UTF-8 | 1,631 | 2.609375 | 3 | [] | no_license | //
// annealing.cc
//
//
// Created by Georg Auzinger on 04.12.12.
//
//
#include <stdio.h>
#include <stdlib.h>
#include "TROOT.h"
#include "TStyle.h"
#include "TColor.h"
#include "TLegend.h"
#include "TMath.h"
#include "TF1.h"
#include "TCanvas.h"
#include "TGraph.h"
#include "TMultiGraph.h"
#include "TAxis.h"
#include <iostream>
#include <fstream>
double tauI(double T){ // min
return 1./TMath::Exp(34.1-12.9e3/T); // fit to data in table 5.2
}
double beta(){ // A/cm
return 3.07e-18;
}
double alphaI(){ // A/cm
return 1.23e-17;
}
double alpha0(double T){ // A/cm
return (-8.9e-17 + 4.6e-14/T); // fit to data in table 5.2
}
Double_t alphaFunction(Double_t* x, Double_t* par){ // Eq. 5.4 from M.Moll PhD Thesis
Float_t t = x[0];
double a = alphaI() * TMath::Exp( -t / tauI(par[0]) ) + alpha0(par[0]) - beta() * TMath::Log(t/1.);
return a;
}
double eq_at_RT(double time, double T) {
double alpha=0;
TF1 *f1 = new TF1("alpha",alphaFunction,0,1e7,1);
f1->SetParameter(0, T+273.);
f1->SetNpx(100000);
f1->Update();
// std::cout << "The input time is " << time << " and the temperature is: " << T << std::endl;
alpha = f1->Eval(time);
time = f1->GetX(alpha);
// std::cout << "Time at " << T << " to reach alpha=" << alpha << " is " << time << " min." << std::endl;
f1->SetParameter(0, 294.);
f1->SetNpx(100000);
f1->Update();
double time21 = f1->GetX(alpha,0.,0.,1e-10,1000);
// double alpha21 = f1->Eval(time21);
// std::cout << "Eq. time at 21 degrees to reach " << alpha21 << " is " << time21 << std::endl;
return time21;
} | true |
27e1ad388f6028015fe5bee0f0df08582d8ada69 | C++ | Stektpotet/gloom | /gloom/src/overkill/graphics_internal/IndexBuffer.hpp | UTF-8 | 1,101 | 2.8125 | 3 | [
"MIT"
] | permissive | #pragma once
#include <glad/glad.h>
#include "../gfx.h"
template<typename TIndex>
class IndexBuffer
{
private:
GLuint id;
public:
IndexBuffer(const GLsizeiptr count, const TIndex* data = nullptr)
: count{ count }
{
glGenBuffers(1, &id);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, id);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, count * sizeof(TIndex), data, GL_STATIC_DRAW);
GFX_DEBUG("IBO (%d) bound!", id);
}
inline bool valid() { return id != 0; }
inline void bind() const
{
GFX_DEBUG("IBO (%d) bound!", id);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, id);
}
static inline void unbind()
{
GFX_DEBUG("IBO unbound!");
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
inline void clear()
{
GFX_DEBUG("IBO (%d) deleting...", id);
glDeleteBuffers(1, &id);
}
inline void update(const GLintptr start, const GLsizeiptr size, const void * data)
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, id);
glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, start, size, data);
}
const GLsizeiptr count;
}; | true |
e9a15a151304ab661401aa70ead97b6e0568b539 | C++ | minhnh/hbrs_courses | /15w_air/assignment03/include/environment.hpp | UTF-8 | 697 | 2.859375 | 3 | [] | no_license | #ifndef ENVIRONMENT_HPP
#define ENVIRONMENT_HPP
enum CellType
{
CELL_DIRT = 0,
CELL_SPACE = 1,
CELL_START = 2,
CELL_OBSTACLE = 3
};
class Environment
{
public:
Environment();
void run();
int load_map(int map_index);
void initialize_map();
char get_value_at(int x, int y);
void print_map();
std::string map;
int map_Height;
int map_Width;
int start_X;
int start_Y;
int number_of_dust;
private:
};
class Point
{
public:
Point(int X,int Y);
void set_x(int);
void set_y(int);
void set_xy(int,int);
int x;
int y;
};
#endif
| true |
e4d2c5c70ac329393a4c08e70745c5ab40094290 | C++ | andriy-kuz/Algorithms | /Decrease-and-Conquer/Algos.cpp | UTF-8 | 1,847 | 3.515625 | 4 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int BinarySearch_NonRec(const vector<int>& Ar, int k);
int TernarySearch_NonRec(const vector<int>& Ar, int k);
int MultyplicationLaRus(int n, int m);
int LomutoPartition(vector<int>& Ar, int l, int r);
int QuickSelect(vector<int>& Ar, int l, int r, int k);
int main()
{
//vector<int> Ar = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
//test
//for (int i = 0; i <= Ar.size(); i++)
// cout << TernarySearch_NonRec(Ar, i) << endl;
//cout << MultyplicationLaRus(13, 94);
vector<int> Ar = { 5,7,3,9,2 };
cout << QuickSelect(Ar, 0, Ar.size()-1, 1);
return 0;
}
int BinarySearch_NonRec(const vector<int>& Ar, int k)
{
int l = 0, r = Ar.size() - 1;
while (l <= r)
{
int m = (r + l) / 2;
if (Ar[m] == k)
return m;
else if (k < Ar[m])
r = m - 1;
else
l = m + 1;
}
return -1;
}
int TernarySearch_NonRec(const vector<int>& Ar, int k)
{
int l = 0, r = Ar.size()-1;
while (l <= r)
{
int m = (r + l) / 3;
if (Ar[m] == k)
return m;
else if (k < Ar[m])
r = m - 1;
else
{
m = 2 * (r + l) / 2;
if (Ar[m] == k)
return m;
else if (k < Ar[m])
{
r = m - 1;
}
else
l = m + 1;
}
}
return -1;
}
int MultyplicationLaRus(int n, int m)
{
if (n == 1)
return m;
else
{
int k = 0;
if (n % 2)
{
k = m;
--n;
}
n = n >> 1;
m = m << 1;
return MultyplicationLaRus(n, m) + k;
}
}
int LomutoPartition(vector<int>& Ar, int l, int r)
{
int p = Ar[l], s = l;
for (int i = l + 1; i <= r; i++)
{
if (Ar[i] < p)
{
std::swap(Ar[++s], Ar[i]);
}
}
std::swap(Ar[l], Ar[s]);
return s;
}
int QuickSelect(vector<int>& Ar, int l, int r, int k)
{
int s = LomutoPartition(Ar, l, r);
if (s == k)
return Ar[s];
else if (k < s)
return QuickSelect(Ar, l, s - 1, k);
else
return QuickSelect(Ar, s+1, r, k);
}
| true |
e78e79c762499a7945abbbb1e7e81d8442c66a3d | C++ | twolffpiggott/C-Apollonian-Gasket | /include/point2d.h | UTF-8 | 2,242 | 3.765625 | 4 | [
"MIT"
] | permissive | /*
* point2d.h
*
* Created on: 27 Apr 2015
* Author: Tim
*/
#ifndef POINT2D_H_
#define POINT2D_H_
#include <iostream>
#include <cmath>
using namespace std;
//defining the 2D point class
/**
* \brief A point in \f$\mathbb{R}^2\f$
*/
class Point
{
//overloaded friend operators
/**
* \brief Overloaded ostream operator
* @param out ostream object
* @param inPoint reference to a Point
* @return ostream object displaying coordinates of Point \f$(x,y)\f$
*/
friend ostream& //output functionality
operator<<(ostream& out, const Point& inPoint);
/**
* \brief Overloaded istream operator
* @param in reference to an istream object
* @param inPoint reference to a Point
* @return istream object saving coordinates of Point \f$(x,y)\f$
*/
friend istream& //input functionality
operator>>(istream& in, Point& inPoint);
/**
* \brief Overloaded equality operator
* @param lhs reference to left-hand-side Point
* @param rhs reference to right-hand-side Point
* @return boolean: true if \f$\text{lhs}=\text{rhs}\f$
*/
friend bool //equality operator
operator==(const Point& lhs, const Point& rhs);
/**
* \brief Overloaded inequality operator
* @param lhs reference to left-hand-side Point
* @param rhs reference to right-hand-side Point
* @return boolean: true if \f$\text{lhs}\neq\text{rhs}\f$
*/
friend bool //inequality operator
operator!=(const Point& lhs, const Point& rhs);
public:
/**
* \brief Default constructor for the Point class
*/
Point(): //default constructor
x(0.0),y(0.0)
{}
/**
* \brief Constructor for the Point class
* @param xIn x-coordinate of Point
* @param yIn y-coordinate of Point
*/
Point(const double xIn, const double yIn): //class constructor
x(xIn),y(yIn)
{}
/**
* \brief Destructor for the Point class
*/
virtual ~Point() //class destructor
{}
//overloaded operators
/**
* \brief Overloaded assignment operator
* @param rhs vector to assign to the left hand side
* @return reference to Point equal to right hand side
*/
Point&
operator=(const Point& rhs); //assignment operator
protected:
double x; /**< x-coordinate of Point */
double y; /**< y-coordinate of Point */
};
#endif /* POINT2D_H_ */
| true |
d85a57d2440b7871e115039b9816100abb48e437 | C++ | fushime2/competitive | /AOJ/aoj0511.cpp | UTF-8 | 390 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <map>
#include <vector>
#include <string>
#include <cstdio>
#include <cmath>
using namespace std;
int main(void)
{
bool f[31] = {0};
for(int i=0; i<28; i++) {
int a;
cin >> a;
f[a] = true;
}
for(int i=1; i<=30; i++) {
if(f[i] == false)
cout << i << endl;
}
return 0;
}
| true |
116b9fe5be7cc9783ade10d2f8b3891607622c18 | C++ | alexandraback/datacollection | /solutions_6404600001200128_1/C++/juanplopes2/A.cpp | UTF-8 | 545 | 2.703125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int T[10010];
int main() {
int test=0, tests; cin >> tests;
int N;
while(cin >> N) {
for(int i=0; i<N; i++)
cin >> T[i];
int MD = 0;
int A1 = 0;
for(int i=1; i<N; i++) {
A1 += max(T[i-1]-T[i], 0);
MD = max(MD, T[i-1]-T[i]);
}
int A2 = 0;
for(int i=0; i<N-1; i++) {
A2 += min(T[i], MD);
}
cout << "Case #" << ++test << ": " << A1 << " " << A2 << endl;
}
}
| true |
8c508c5acbf9a6a2a519f26c297c92a30b625772 | C++ | leisheyoufu/study_exercise | /algorithm/leetcode/106_Construct_Binary_Tree_from_Inorder_and_Postorder_Traversal/main.cpp | UTF-8 | 1,641 | 3.6875 | 4 | [] | no_license | /*
Construct Binary Tree from Inorder and Postorder Traversal
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
*/
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<queue>
#include<stack>
#include<cstdio>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder)
{
if(postorder.empty()) {
return NULL;
}
return build(inorder, 0,inorder.size()-1, postorder,0, postorder.size()-1);
}
TreeNode *build(vector<int>& in, int instart, int inend, vector<int>& post, int poststart, int postend)
{
if(poststart > postend) {
return NULL;
}
int rootVal = post[postend];
int i;
for(i=instart; i<=inend; i++) {
if(in[i] == rootVal) {
break;
}
}
int leftlen = i - instart;
TreeNode * root = new TreeNode(rootVal);
root->left = build(in,instart,i-1, post, poststart, poststart+leftlen-1);
root->right = build(in, i+1, inend, post, poststart+leftlen, postend-1);
return root;
}
};
int main()
{
int a1[] = {6,7,3};
int a2[] = {6,3,7};
vector<int> v1(a1, a1+ sizeof(a1)/sizeof(int));
vector<int> v2(a2, a2+ sizeof(a2)/sizeof(int));
Solution sln;
TreeNode* t = sln.buildTree(v1,v2);
system("pause");
return 0;
}
| true |
70f013c511ea85466b99d1a33db36dac6cecffbd | C++ | bestcobe/common-c-library | /livechatmanmanager/LCTextItem.h | UTF-8 | 451 | 2.546875 | 3 | [] | no_license | /*
* author: Samson.Fan
* date: 2015-10-21
* file: LCTextItem.h
* desc: LiveChat文本消息item
*/
#pragma once
#include <string>
using namespace std;
class LCTextItem
{
public:
LCTextItem();
virtual ~LCTextItem();
public:
// 初始化
bool Init(const string& message, bool isSend);
public:
string m_message; // 消息内容
string m_displayMsg; // 用于显示的消息内容
bool m_illegal; // 内容是否非法
};
| true |
6d824b5112d1a73cb875a99328ab24b58c626d1d | C++ | mishra-sid/HarryPotter | /Harry/Window.cpp | UTF-8 | 1,346 | 2.859375 | 3 | [] | no_license | #include "Window.h"
#include "Error.h"
#include <iostream>
Window::Window()
{
}
Window::~Window()
{
}
int Window::createWindow(std::string windowName, int screenWidth, int screenHeight, unsigned int currentFlags)
{
Uint32 flags = SDL_WINDOW_OPENGL;
if (currentFlags & INVISIBLE)
flags |= SDL_WINDOW_HIDDEN;
if (currentFlags & FULLSCREEN)
flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
if (currentFlags & BORDERLESS)
flags |= SDL_WINDOW_BORDERLESS;
//Create Window;
m_sdlWindow = SDL_CreateWindow(windowName.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, screenWidth, screenHeight, flags);
//Error Checking
if (m_sdlWindow == nullptr)
fatalError("SDL Window could not be created");
//Creating context
SDL_GLContext glContext = SDL_GL_CreateContext(m_sdlWindow);
if (glContext == nullptr)
fatalError("SDL_GL context could not be created");
//Initialise GLEW
GLenum error = glewInit();
if (error != GLEW_OK)
fatalError("Glew could not be initialised");
std::cout << "**** OPEN GL Version: " << glGetString(GL_VERSION) << " ****" << std::endl;
//Giving Background Color
glClearColor(0.0f, 0.0f, 1.0f, 1.0f);
//set vsync
SDL_GL_SetSwapInterval(0);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
return 0;
}
void Window::swapBuffer()
{
SDL_GL_SwapWindow(m_sdlWindow);
} | true |
20686a5049807bb472529a718120802152f3cb5c | C++ | edgar-323/leetcode | /MajorityElement.cpp | UTF-8 | 1,878 | 3.828125 | 4 | [] | no_license | /*
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊n/2⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
*/
class Solution {
private:
int solution1(std::vector<int>& nums) {
/*
Time-Complexity: O(N) (Average)
Space-Complexity: O(N)
*/
const int N = nums.size();
if (N == 0) {
return 0;
}
std::unordered_map<int,int> wordCount;
int maxElem = nums[0];
int maxCount = 1;
int newCount;
std::unordered_map<int,int>::iterator it;
wordCount.emplace(maxElem, maxCount);
for (int i = 1; i < N; ++i) {
newCount = 1;
it = wordCount.find(nums[i]);
if (it != wordCount.end()) {
newCount += it->second;
it->second = newCount;
} else {
wordCount.emplace(nums[i], newCount);
}
if (newCount > maxCount) {
maxCount = newCount;
maxElem = nums[i];
}
}
return maxElem;
}
int solution2(std::vector<int>& nums) {
/* Time-Complexity: O( N )
* Space-Complexity: O( 1 )
* */
// UNINTUITIVE SOLUTION
const int N = nums.size();
int count = 1;
int candidate = nums[0];
for (int i = 1; i < N; ++i) {
if (count == 0) {
candidate = nums[i];
}
count += (nums[i] == candidate) ? 1 : -1;
}
return candidate;
}
public:
int majorityElement(vector<int>& nums) {
return solution2(nums);
}
};
| true |
40b730bd1f3354f78aa28d0b09e57312ec69ceaf | C++ | shsanek/Black-Betty | /DTR/DTRRangeLexem.cpp | UTF-8 | 709 | 2.671875 | 3 | [] | no_license | //
// DTRRangeLexem.cpp
// DTR
//
// Created by Alexander Shipin on 12/08/16.
// Copyright © 2016 Alexander Shipin. All rights reserved.
//
#include "DTRRangeLexem.hpp"
using namespace DTR;
RangeLexem::RangeLexem(char startSymbol,char endSymbol) {
if (startSymbol <= endSymbol) {
this->startSymbol = startSymbol;
this->endSymbol = endSymbol;
} else {
this->startSymbol = endSymbol;
this->endSymbol = startSymbol;
}
}
Lexem::LexemSting RangeLexem::stringLexemFromString(string str){
if (str.length() < 1) {
return 0;
}
string value = str.substr(0, 1);
if (value [0] >= startSymbol && value [0] <= endSymbol) {
return value;
}
return 0;
}
| true |
3c9c5820dc30320914fd4964ff56e28477cb451b | C++ | Yutong-Dai/codes-for-courses | /cpp_CS225/daily-exercise/day39-hashing/potd-q39-clean/Hash.cpp | UTF-8 | 332 | 2.71875 | 3 | [
"MIT"
] | permissive | #include <vector>
#include <string>
#include "Hash.h"
using namespace std;
int hashFunction(string s, int M) {
// Your Code Here
//hash function to sum up the ASCII characters of the letters of the string
}
int countCollisions (int M, vector<string> inputs) {
int collisions = 0;
// Your Code Here
return collisions;
}
| true |
eb22b3087a7c665fa9d871f73c43128bf36457b1 | C++ | ProgramSnail/tp_game | /src/game/map_entities/cell.hpp | UTF-8 | 478 | 2.875 | 3 | [] | no_license | #pragma once
namespace map {
enum class CellType {
none,
unit,
weapon,
forest,
moutain
};
enum class CellPlayer {
none,
player0,
player1,
player2,
player3
};
struct Cell {
CellType type;
CellPlayer player;
Cell(CellType type = CellType::none,
CellPlayer player = CellPlayer::none)
: type(type), player(player) {}
};
}
| true |
f90ff4c211a9879a97e43dc475a738dd46f70d3f | C++ | furyanaor/ExpExpert | /MFC V2/blue_card.h | UTF-8 | 1,352 | 2.796875 | 3 | [] | no_license | #pragma once
#include "card.h"
class blue_card : public card {
private:
int blue_stamina;
int blue_energy, blue_energy_temp;
int blue_attack;
//int blue_defence;
//int blue_spell2;
//int blue_power;
int blue_attx;
//int blue_defx2;
public:
blue_card() : blue_attack(0), blue_attx(0) { card_color = "blue"; } //: blue_energy(pow(2, received)) {card_round = received;}
virtual void setCard_Round(const int& recived) { this->card_round = int(recived); blue_energy_temp = blue_energy = int(pow(2, recived)); }
void setBlue_Stamina(const int& recived) { this->blue_stamina = recived; }
void setBlue_Energy(const int& recived) { this->blue_energy = recived; }
void setBlue_Energy_temp(const int& recived) { this->blue_energy_temp = recived; }
void setBlue_Attack(const int& recived) {
this->blue_attack = recived;
this->blue_attx = int(pow(blue_attack, 2));
this->blue_energy_temp = this->blue_energy - recived;
}
//void setblue_Attx556(const int& recived) { this->blue_attx556 = recived; }
//Get
int getBlue_Stamina() { return this->blue_stamina; }
int getBlue_Energy() { return this->blue_energy; }
int getBlue_Energy_temp() { return this->blue_energy_temp; }
int getBlue_Attack() { return this->blue_attack; }
int getBlue_Attx() { return this->blue_attx; }
~blue_card() {}
}; | true |
e77e19b9e1dd45a67755540d848163dfb1301b01 | C++ | Redleaf23477/ojcodes | /codejam/2018-1C/word.cpp | UTF-8 | 2,775 | 2.546875 | 3 | [] | no_license | //
#include <bits/stdc++.h>
#define endl '\n'
#define int ll
using namespace std;
typedef long long ll;
struct Node
{
char ch;
ll leafcnt;
Node *nxt[26];
Node(char ch):ch(ch), leafcnt(0)
{
for(int i = 0; i < 26; i++) nxt[i] = NULL;
}
};
int n, len;
vector<set<char>> charset;
vector<string> arr;
Node *trie;
void init();
void process();
int32_t main()
{
ios::sync_with_stdio(false); cin.tie(0);
int T, caseN = 0; cin >> T;
while(T--)
{
cout << "Case #" << ++caseN << ": ";
init();
process();
}
cout.flush();
return 0;
}
void build(Node *ptr, string &str, int idx)
{
if(idx == len) return;
int nxtidx = str[idx]-'A';
if(ptr->nxt[nxtidx] == NULL) ptr->nxt[nxtidx] = new Node(str[idx]);
ptr->leafcnt++;
build(ptr->nxt[nxtidx], str, idx+1);
}
char stk[100];
void print(Node *ptr, int depth)
{
if(depth == len)
{
for(int i = 0; i < len; i++) cout << stk[i];
cout << endl;
return;
}
for(int i = 0; i < 26; i++)
{
if(ptr->nxt[i] != NULL)
{
stk[depth] = 'A'+i;
print(ptr->nxt[i], depth+1);
}
}
}
void freeTrie(Node *ptr)
{
for(int i = 0; i < 26; i++)
{
if(ptr->nxt[i] != NULL) freeTrie(ptr->nxt[i]);
delete ptr->nxt[i];
}
}
void init()
{
cin >> n >> len;
trie = new Node('X');
charset.resize(len);
for(int i = 0; i < len; i++) charset[i].clear();
arr.resize(n);
for(int i = 0; i < n; i++)
{
cin >> arr[i];
for(int j = 0; j < len; j++) charset[j].insert(arr[i][j]);
}
for(int i = 0; i < n; i++)
{
build(trie, arr[i], 0);
}
// print(trie, 0);
}
string ans;
void dfs(Node *ptr, int depth)
{
if(ans.size() == len) return;
ll mn = (1ll<<60), mnidx = -1;
for(auto c:charset[depth])
{
int i = c-'A';
if(ptr->nxt[i] == NULL)
{
ans.push_back('A'+i);
for(size_t j = ans.size(); j < len; j++)
{
ans.push_back(*charset[j].begin());
}
return;
}
else if(ptr->nxt[i]->leafcnt < mn)
{
mn = ptr->nxt[i]->leafcnt;
mnidx = i;
}
}
ans.push_back('A'+mnidx);
dfs(ptr->nxt[mnidx], depth+1);
}
void process()
{
if(len == 1)
{
cout << "-" << endl;
}
else
{
ll maxNum = 1;
for(int i = 0; i < len; i++) maxNum *= charset[i].size();
if(trie->leafcnt == maxNum) cout << "-" << endl;
else
{
ans.clear();
dfs(trie, 0);
cout << ans << endl;
}
}
freeTrie(trie);
delete trie;
trie = NULL;
}
| true |
c29e282262e846714f589a826ba87509a5aeb2ef | C++ | sundsx/RevBayes | /src/revlanguage/datatypes/basic/Natural.h | UTF-8 | 3,534 | 3.1875 | 3 | [] | no_license | #ifndef Natural_H
#define Natural_H
#include "Integer.h"
#include <ostream>
#include <string>
namespace RevLanguage {
class RealPos;
/**
* Primitive type for Natural numbers (including 0).
*
* Note that we derive this from Integer. To make
* sure inheritance is safe, we restrict the range
* of natural numbers from 0 to to INT_MAX
*/
class Natural : public Integer {
public:
Natural(void); //!< Default constructor (value is 0)
Natural(RevBayesCore::TypedDagNode<int> *v); //!< Constructor with DAG node
Natural(int x); //!< Constructor from int
Natural(unsigned int x); //!< Constructor from int
Natural(unsigned long x); //!< Constructor from size_t
// Basic operator functions
RevObject* add(const RevObject &rhs) const; //!< Addition operator used for example in '+=' statements
Natural* add(const Natural &rhs) const; //!< Addition operator used for example in '+=' statements
RealPos* add(const RealPos &rhs) const; //!< Addition operator used for example in '+=' statements
RevObject* divide(const RevObject &rhs) const; //!< Division operator used for example in '/=' statements
RealPos* divide(const Natural &rhs) const; //!< Division operator used for example in '/=' statements
RealPos* divide(const RealPos &rhs) const; //!< Division operator used for example in '/=' statements
RevObject* multiply(const RevObject &rhs) const; //!< Multiplication operator used for example in '*=' statements
Natural* multiply(const Natural &rhs) const; //!< Multiplication operator used for example in '*=' statements
RealPos* multiply(const RealPos &rhs) const; //!< Multiplication operator used for example in '*=' statements
// Basic utility functions
Natural* clone(void) const; //!< Clone object
RevObject* convertTo(const TypeSpec& type) const; //!< Convert to type
static const std::string& getClassType(void); //!< Get Rev type
static const TypeSpec& getClassTypeSpec(void); //!< Get class type spec
const TypeSpec& getTypeSpec(void) const; //!< Get language type of the object
bool isConvertibleTo(const TypeSpec& type) const; //!< Is convertible to type?
};
}
#endif
| true |
6c121cd43ef5025bca2a9b70edef79f9df67a593 | C++ | tomwhy/Rockstar | /Rockstar/Null.cpp | UTF-8 | 2,699 | 3.34375 | 3 | [] | no_license | #include "Null.h"
#include "Number.h"
#include "String.h"
#include "Mysterious.h"
#include "Boolean.h"
#include "Array.h"
#include "InterpeterExceptions.h"
Null::Null() : ISimpleVariable("Null")
{
}
std::string Null::toString()
{
return "";
}
bool Null::canBeIndex()
{
return false;
}
bool Null::toBool()
{
return false;
}
std::shared_ptr<IVariable> Null::subtract(std::shared_ptr<IVariable> other)
{
if (std::dynamic_pointer_cast<Number>(other) != nullptr)
{
std::shared_ptr<Number> right = std::dynamic_pointer_cast<Number>(other);
return std::make_shared<Number>(-std::stold(right->toString()));
}
else if (std::dynamic_pointer_cast<Null>(other) != nullptr)
{
return std::make_shared<Number>(0); // 0 - 0 = 0
}
else
{
return std::make_shared<Mysterious>();
}
}
std::shared_ptr<IVariable> Null::add(std::shared_ptr<IVariable> other)
{
if (std::dynamic_pointer_cast<Number>(other) != nullptr)
{
std::shared_ptr<Number> right = std::dynamic_pointer_cast<Number>(other);
return std::make_shared<Number>(std::stold(right->toString()));
}
else if (std::dynamic_pointer_cast<Null>(other) != nullptr)
{
return std::make_shared<Number>(0); // 0 + 0 = 0
}
else
{
return std::make_shared<Mysterious>();
}
}
std::shared_ptr<IVariable> Null::multiply(std::shared_ptr<IVariable> other)
{
if (std::dynamic_pointer_cast<Number>(other) != nullptr)
{
return std::make_shared<Number>(0);
}
else if (std::dynamic_pointer_cast<String>(other) != nullptr)
{
return std::make_shared<String>("");
}
else if (std::dynamic_pointer_cast<Null>(other) != nullptr)
{
return std::make_shared<Number>(0); // 0 * 0 = 0
}
else
{
return std::make_shared<Mysterious>();
}
}
std::shared_ptr<IVariable> Null::divide(std::shared_ptr<IVariable> other)
{
if (std::dynamic_pointer_cast<Number>(other) != nullptr)
{
return std::make_shared<Number>(0);
}
else
{
return std::make_shared<Mysterious>();
}
}
bool Null::equal(std::shared_ptr<IVariable> other)
{
if (std::dynamic_pointer_cast<Mysterious>(other) != nullptr ||
std::dynamic_pointer_cast<String>(other) != nullptr)
{
return false;
}
else if (std::dynamic_pointer_cast<Number>(other) != nullptr ||
std::dynamic_pointer_cast<Array>(other) != nullptr)
{
return Number(0).equal(other);
}
else if (std::dynamic_pointer_cast<Boolean>(other) != nullptr)
{
return Boolean(false).equal(other);
}
else // null
{
return true;
}
}
bool Null::less(std::shared_ptr<IVariable> other)
{
if (std::dynamic_pointer_cast<Number>(other) != nullptr ||
std::dynamic_pointer_cast<Array>(other) != nullptr)
{
return Number(0).less(other);
}
else // null
{
return IVariable::less(other);
}
}
| true |
9d64c055777e4aa5eaa537c5f1fb2dd6a600c5a4 | C++ | swarmer/algorithms | /graphs/edmonds-karp/edmonds-karp.cpp | UTF-8 | 2,279 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <vector>
#include <utility>
#include <set>
#include <map>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <climits>
#include <cmath>
#include <iomanip>
#include <cfloat>
#include <queue>
#include <memory>
using namespace std;
typedef long long ll;
struct Edge
{
int i1, i2, capacity, flow;
Edge(int i1, int i2, int capacity) : i1(i1), i2(i2), capacity(capacity), flow(0) {}
Edge() : i1(-1), i2(-1), capacity(-1), flow(-1) {}
int res()
{
return capacity - flow;
}
};
struct Network
{
int V, S, T;
vector<map<int, Edge> > edges;
int flow;
Network() : flow(0) {}
bool bfs()
{
queue<int> q;
vector<bool> visited;
vector<int> prev, minc;
visited.assign(V, false);
prev.assign(V, -1);
minc.assign(V, INT_MAX);
q.push(S);
while (!q.empty()) {
int c = q.front();
q.pop();
visited[c] = true;
if (c == T) {
int df = minc[T];
flow += df;
int p = T;
while (prev[p] != -1) {
int u = prev[p], v = p;
edges[u][v].flow += df;
edges[v][u].flow = -edges[u][v].flow;
p = prev[p];
}
return true;
}
map<int, Edge> &es = edges[c];
map<int, Edge>::iterator it;
for (it = es.begin(); it != es.end(); ++it) {
Edge &e = it->second;
if (!visited[e.i2] && e.res() > 0) {
q.push(e.i2);
prev[e.i2] = e.i1;
minc[e.i2] = min(minc[e.i1], e.res());
}
}
}
return false;
}
int maxflow()
{
while (bfs()) {}
return flow;
}
};
int main(int argc, char **argv)
{
Network n;
cin >> n.V >> n.S >> n.T;
n.edges.resize(n.V);
while (!cin.eof()) {
int i1, i2, c;
cin >> i1 >> i2 >> c;
if (cin.eof())
break;
n.edges[i1][i2] = Edge(i1, i2, c);
n.edges[i2][i1] = Edge(i2, i1, c);
}
cout << n.maxflow() << "\n";
}
| true |
8c3062fa06a89be68573698ce395ce08aab091f0 | C++ | RockyRocks/AsteroidDemo | /Asteroid Demo_RRK/common/utils/HashedString.h | UTF-8 | 794 | 3.3125 | 3 | [] | no_license | #ifndef __HASHEDSTRING_H
#define __HASHEDSTRING_H
#include <string>
/* Encapsulates both the string and it's hashed value */
class HashedString
{
public:
HashedString() {}
explicit HashedString(const char * const pIdentStr)
: m_Ident(hash_name(pIdentStr)), m_IdentStr(pIdentStr)
{}
unsigned long getHashValue() const
{
return reinterpret_cast<unsigned long>(m_Ident);
}
const std::string & getStr() const { return m_IdentStr; }
bool operator< (HashedString const &rhs) const
{
bool r = (getHashValue() < rhs.getHashValue());
return r;
}
bool operator== (HashedString const &rhs) const
{
bool r = (getHashValue() == rhs.getHashValue());
return r;
}
static void * hash_name(char const * pIdentStr);
private:
void * m_Ident;
std::string m_IdentStr;
};
#endif
| true |
3aaf4e61d3aca4b701440c5ab630eba59e64a377 | C++ | go-to-valley/algorithm-problem-solving-strategies | /molang/20-habit.cpp | UTF-8 | 1,717 | 3.140625 | 3 | [] | no_license | #include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
struct Comparator{
const vector<int>& group;
int t;
Comparator(const vector<int>& _group, int _t): group(_group), t(_t){
}
bool operator() (int a, int b){
if(group[a] != group[b]) return group[a] < group[b];
return group[a+t] < group[b+t];
}
};
vector<int> getSuffixArray(const string& s){
int n = s.size();
int t = 1;
vector<int> group(n+1);
for(int i = 0; i < n; i++) group[i] = s[i];
group[n] = -1;
vector<int> perm(n);
for(int i = 0 ;i < n; i++) perm[i] = i;
while(t<n){
Comparator compareUsing2T(group, t);
sort(perm.begin(), perm.end(), compareUsing2T);
t*= 2;
if(t>=n) break;
vector<int> newGroup(n+1);
newGroup[n] = -1;
newGroup[perm[0]] = 0;
for(int i = 1; i < n; i++){
if(compareUsing2T(perm[i-1], perm[i]))
newGroup[perm[i]] = newGroup[perm[i-1]]+1;
else
newGroup[perm[i]] = newGroup[perm[i-1]];
}
group = newGroup;
}
return perm;
}
int commonPrefix(const string &s, int i, int j){
int k = 0;
while(i < s.size() && j < s.size() && s[i] == s[j]){
i++; j++; k++;
}
return k;
}
int max(int a, int b){ return a > b ? a : b; }
int main(){
int c; cin >> c;
while(c--){
int k;
string s;
cin >> k >> s;
vector<int> suffixArray = getSuffixArray(s);
int rst = 0;
for(int i = 0; i+k <= s.size(); i++)
rst = max(rst, commonPrefix(s, suffixArray[i], suffixArray[i+k-1]));
cout << rst << endl;
}
} | true |
2210dd9b4b08a6f22259a7648a99fcd67ef66799 | C++ | c-coutts/suspensionModel | /Arduino Code/suspensionModel/suspensionModel.ino | UTF-8 | 1,411 | 3.1875 | 3 | [] | no_license | #include <Servo.h> //include required library
Servo myServo1; //suspension servo
Servo myServo2; //steering servo
String message, suspensionAngle, steeringAngle; //message & message substrings from Processing
void setup() {
Serial.begin(115200); //set arduino to 115200 baud
}
void loop() {
while (Serial.available()) { //while the serial port is available
if (Serial.available() >= 0) { //if there is a message being received
message = Serial.readStringUntil(' '); //read until a break in the message
if (message.length() == 6) { //confirm length of the message which should be constant based on the Processing script (don't believe this is necessary)
steeringAngle = message.substring(0,3); //take the first half as the steering angle
suspensionAngle = message.substring(3,6); //take the second half as the suspension angle
}
//Serial.println(message); //see last function in Processing script for more detail here
myServo1.attach(6); //indicate which pins the servos are attached to (I found that attaching the servos here instead of in void setup() helps to avoid unwanted motion when the script starts running)
myServo2.attach(7);
myServo1.write(suspensionAngle.toInt()); //send the desired angles to the servos (after converting from a string to integer)
myServo2.write(steeringAngle.toInt());
}
}
}
| true |
8744e48f02ab27231bd401854f68c1f730765323 | C++ | StevensDeptECE/CPE593 | /old/session02Sorting/2022S_simple_sort_review.cc | UTF-8 | 352 | 2.96875 | 3 | [] | no_license | // pseudocode
void bubblesort(int a[])
{
for (int i = 0; i < a.length - 1; i++)
{
for (int j = a.length - 2 - i; j >= 0; j--)
{
if (a[j] > a[j + 1])
{
//swap
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
}
}
} | true |
2bc0113f7cfb9ab70d9f36229b67a3e80752a004 | C++ | wenwen12321/Big_Number | /Project2/Project2/Integer.cpp | UTF-8 | 3,607 | 3.171875 | 3 | [] | no_license | #include "Integer.h"
#define MAX 1000
Integer::Integer() : Number()
{
}
Integer::~Integer()
{
num.clear();
num.shrink_to_fit();
denom.clear();
denom.shrink_to_fit();
}
Integer::Integer(string newNum)
{
dot1 = 0;
isDecimal = 0;
denom.push_back(1);
strnum = newNum;
if (newNum.find('.', 0) != string::npos)
{
while (newNum.find('.') != newNum.size())
{
newNum.pop_back();
}
}
for (int i = newNum.size() - 1; i > 0; i--)
{
num.push_back((int)(newNum[i]) - 48);
}
if (newNum[0] == '+')
{
sign = 1;
}
else if (newNum[0] == '-')
{
sign = -1;
}
else
{
sign = 1;
num.push_back((int)(newNum[0]) - 48);
}
while (num[num.size() - 1] == 0 && num.size() > 1)
{
num.pop_back();
}
}
Integer::Integer(const char *a)
{
string str = a;
if (str != "")
{
char infix[MAX] = { '\0' };
char postfix[MAX] = { '\0' };
int count = 0;
for (int i = 0, j = 0; i < str.size(); i++)
{
if (str[i] == '(')
{
count++;
}
else if (str[i] == ')')
{
if (count < 1)
{
count = -1;
break;
}
count--;
}
if (str[i] != ' ')
{
infix[j++] = str[i];
}
}
int error = 0;
for (int i = 0; infix[i] != '\0'; i++)
{
if ((infix[i] >= 65 && infix[i] <= 90) || (infix[i] >= 97 && infix[i] <= 122))
{
error = 1;
break;
}
}
if (error == 1 || count != 0)
{
num.push_back(0);
sign = 1;
dot1 = 0;
isDecimal = 0;
strnum = "0";
denom.push_back(0);
}
else
{
inToPostfix(infix, postfix);
vector <string> cal;
string temp(postfix);
string c = " ";
splitString(temp, cal, c);
calBigNum(cal, *this);
isDecimal = 0;
}
}
else
{
num.push_back(0);
sign = 1;
dot1 = 0;
isDecimal = 0;
strnum = "0";
denom.push_back(0);
}
}
Integer::Integer(string strNum, string varName, vector<int> newNum, vector<int> newDenom, int isDecimal, int sign)
{
dot1 = 0;
this->isDecimal = 0;
this->sign = sign;
this->strnum = strnum;
this->varName = varName;
num.assign(newNum.begin(), newNum.end());
denom.assign(newDenom.begin(), newDenom.end());
}
Integer::Integer(string newNum, vector<int>& newDemon, int newSign, int decimal)
{
dot1 = 0;
isDecimal = 0;
sign = newSign;
strnum = newNum;
denom.push_back(1);
if (newNum.find('.', 0) != string::npos)
{
isDecimal = 1;
int s = newNum.size() - 1;
while (newNum[s--] == '0')
{
newNum.pop_back();
}
s = newNum.size() - 1;
while (newNum[s--] != '.')
{
dot1++;
denom.insert(denom.begin(), 0);
}
}
mul(denom, newDemon);
for (int i = newNum.size() - 1; i >= 0; i--)
{
if (newNum[i] != '.')
{
num.push_back((int)(newNum[i]) - 48);
}
}
}
Integer::Integer(const Integer & Integer) :Number(Integer)
{
}
Integer & Integer::operator=(const Integer & num1)
{
vector<int>().swap(num);
num.assign(num1.num.begin(), num1.num.end());
vector<int>().swap(denom);
denom.assign(num1.denom.begin(), num1.denom.end());
sign = num1.sign;
dot1 = num1.dot1;
strnum = num1.strnum;
isDecimal = num1.isDecimal;
return *this;
}
ostream & operator<<(ostream & out, const Integer & number)
{
int sign = number.sign;
Number num1, num2;
num1 = number;
num2 = number;
vector<int>().swap(num1.denom);
num2.denom.swap(num2.num);
vector<int>().swap(num2.denom);
num1.denom.push_back(1);
num2.denom.push_back(1);
num1 = num1 / num2;
num1.sign = sign;
if (num1.sign == -1)
{
if (!(num1.num[0] == 0 && num1.num.size() == 1))
{
out << '-';
}
}
string temp = "";
for (int i = num1.num.size() - 1; i >= 0; i--)
{
temp += (char)num1.num[i] + 48;
}
out << temp;
return out;
}
| true |
f9af985cabd0627d9b21a196e930e3e42621c76b | C++ | STDombr/oop_course2_semester2_exam | /Uis/mainwindow.cpp | UTF-8 | 12,890 | 2.640625 | 3 | [] | no_license | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include "addelement.h"
#include "addbook.h"
#include "addserver.h"
int radio_link = 1;
int radio_data = 1;
template<typename T>
ContainerInterface<T> *I1;
template<typename T>
ContainerInterface<T> *I2;
template<typename T>
DLList<T> *DL1;
template<typename T>
DLList<T> *DL2;
template<typename T>
DLList<T> *DL3;
template<typename T>
DLCircularList<T> *DLC1;
template<typename T>
DLCircularList<T> *DLC2;
template<typename T>
DLCircularList<T> *DLC3;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->radioButton_DL->click();
ui->radioButton_Books->click();
DL1<Book> = new DLList<Book>;
I1<Book> = DL1<Book>;
DL2<Book> = new DLList<Book>;
I2<Book> = DL2<Book>;
}
MainWindow::~MainWindow()
{
delete ui;
}
template<typename T>
void MainWindow::add_list(ContainerInterface<T> *temp)
{
ui->List->clear();
for(int i=0;i<temp->get_curr_size();i++)
ui->List->addItem(QString::fromStdString(temp->to_string(i)));
ui->List->setCurrentRow(0);
}
template<typename T>
void MainWindow::add_list2(ContainerInterface<T> *temp)
{
ui->List_2->clear();
for(int i=0;i<temp->get_curr_size();i++)
ui->List_2->addItem(QString::fromStdString(temp->to_string(i)));
ui->List_2->setCurrentRow(0);
}
template<typename T>
void MainWindow::add_list3(ContainerInterface<T> *temp)
{
ui->List_3->clear();
for(int i=0;i<temp->get_curr_size();i++)
ui->List_3->addItem(QString::fromStdString(temp->to_string(i)));
ui->List_3->setCurrentRow(0);
}
void MainWindow::on_pushButton_clicked()
{
if (radio_data == 3)
{
AddElement *AE = new AddElement(this);
AE->setWindowModality(Qt::ApplicationModal);
AE->show();
connect(AE,&AddElement::signalElement,this,&MainWindow::connect_element1);
}
else if (radio_data == 1)
{
AddBook *AE = new AddBook(this);
AE->setWindowModality(Qt::ApplicationModal);
AE->show();
connect(AE,&AddBook::signalElement,this,&MainWindow::connect_book1);
}
else
{
AddServer *AE = new AddServer(this);
AE->setWindowModality(Qt::ApplicationModal);
AE->show();
connect(AE,&AddServer::signalElement,this,&MainWindow::connect_server1);
}
}
void MainWindow::on_pushButton_random_clicked()
{
if (radio_data == 1)
{
I1<Book>->generate(rand()%10);
add_list(I1<Book>);
}
else if (radio_data == 2)
{
I1<Server>->generate(rand()%10);
add_list(I1<Server>);
}
else
{
I1<int>->generate(rand()%10);
add_list(I1<int>);
}
}
void MainWindow::on_pushButton_random_2_clicked()
{
if (radio_data == 1)
{
I2<Book>->generate(rand()%10);
add_list2(I2<Book>);
}
else if (radio_data == 2)
{
I2<Server>->generate(rand()%10);
add_list2(I2<Server>);
}
else
{
I2<int>->generate(rand()%10);
add_list2(I2<int>);
}
}
void MainWindow::on_pushButton_sort_clicked()
{
if (radio_data == 1)
{
I1<Book>->quicksort();
add_list(I1<Book>);
}
else if (radio_data == 2)
{
I1<Server>->quicksort();
add_list(I1<Server>);
}
else
{
I1<int>->quicksort();
add_list(I1<int>);
}
}
void MainWindow::connect_element1(QString temp)
{
I1<int>->add_node(temp.toInt());
ui->List->addItem(temp);
}
void MainWindow::connect_element2(QString temp)
{
I2<int>->add_node(temp.toInt());
ui->List_2->addItem(temp);
}
void MainWindow::connect_book1(Book temp)
{
I1<Book>->add_node(temp);
ui->List->addItem(QString::fromStdString(temp.get_bookName()));
}
void MainWindow::connect_book2(Book temp)
{
I2<Book>->add_node(temp);
ui->List_2->addItem(QString::fromStdString(temp.get_bookName()));
}
void MainWindow::connect_server1(Server temp)
{
I1<Server>->add_node(temp);
ui->List->addItem(QString::fromStdString(temp.get_serverID()));
}
void MainWindow::connect_server2(Server temp)
{
I2<Server>->add_node(temp);
ui->List_2->addItem(QString::fromStdString(temp.get_serverID()));
}
void MainWindow::on_pushButton_sort_2_clicked()
{
if (radio_data == 1)
{
I2<Book>->quicksort();
add_list2(I2<Book>);
}
else if (radio_data == 2)
{
I2<Server>->quicksort();
add_list2(I2<Server>);
}
else
{
I2<int>->quicksort();
add_list2(I2<int>);
}
}
void MainWindow::on_radioButton_DL_clicked()
{
ui->List->clear();
ui->List_2->clear();
if (radio_data == 1)
{
DL1<Book> = new DLList<Book>;
I1<Book> = DL1<Book>;
DL2<Book> = new DLList<Book>;
I2<Book> = DL2<Book>;
}
else if (radio_data == 2)
{
DL1<Server> = new DLList<Server>;
I1<Server> = DL1<Server>;
DL2<Server> = new DLList<Server>;
I2<Server> = DL1<Server>;
}
else if (radio_data == 3)
{
DL1<int> = new DLList<int>;
I1<int> = DL1<int>;
DL2<int> = new DLList<int>;
I2<int> = DL2<int>;
}
radio_link = 1;
}
void MainWindow::on_radioButton_DLC_clicked()
{
ui->List->clear();
ui->List_2->clear();
if (radio_data == 1)
{
DLC1<Book> = new DLCircularList<Book>;
I1<Book> = DLC1<Book>;
DLC2<Book> = new DLCircularList<Book>;
I2<Book> = DLC2<Book>;
}
else if (radio_data == 2)
{
DLC1<Server> = new DLCircularList<Server>;
I1<Server> = DLC1<Server>;
DLC2<Server> = new DLCircularList<Server>;
I2<Server> = DLC2<Server>;
}
else if (radio_data == 3)
{
DLC1<int> = new DLCircularList<int>;
I1<int> = DLC1<int>;
DLC2<int> = new DLCircularList<int>;
I2<int> = DLC2<int>;
}
radio_link = 2;
}
void MainWindow::on_radioButton_Books_clicked()
{
ui->List->clear();
ui->List_2->clear();
if (radio_link == 1)
{
DL1<Book> = new DLList<Book>;
I1<Book> = DL1<Book>;
DL2<Book> = new DLList<Book>;
I2<Book> = DL2<Book>;
} else
{
DLC1<Book> = new DLCircularList<Book>;
I1<Book> = DLC1<Book>;
DLC2<Book> = new DLCircularList<Book>;
I2<Book> = DLC2<Book>;
}
radio_data = 1;
}
void MainWindow::on_radioButton_Servers_clicked()
{
ui->List->clear();
ui->List_2->clear();
if (radio_link == 1)
{
DL1<Server> = new DLList<Server>;
I1<Server> = DL1<Server>;
DL2<Server> = new DLList<Server>;
I2<Server> = DL2<Server>;
} else
{
DLC1<Server> = new DLCircularList<Server>;
I1<Server> = DLC1<Server>;
DLC2<Server> = new DLCircularList<Server>;
I2<Server> = DLC2<Server>;
}
radio_data = 2;
}
void MainWindow::on_radioButton_int_clicked()
{
ui->List->clear();
ui->List_2->clear();
if (radio_link == 1)
{
DL1<int> = new DLList<int>;
I1<int> = DL1<int>;
DL2<int> = new DLList<int>;
I2<int> = DL2<int>;
} else
{
DLC1<int> = new DLCircularList<int>;
I1<int> = DLC1<int>;
DLC2<int> = new DLCircularList<int>;
I2<int> = DLC2<int>;
}
radio_data = 3;
}
void MainWindow::on_pushButton_delete_clicked()
{
if (radio_data == 1)
{
I1<Book>->pop_node();
delete ui->List->takeItem(I1<Book>->get_curr_size());
}
else if (radio_data == 2)
{
I1<Server>->pop_node();
delete ui->List->takeItem(I1<Server>->get_curr_size());
}
else if (radio_data == 3)
{
I1<int>->pop_node();
delete ui->List->takeItem(I1<int>->get_curr_size());
}
}
void MainWindow::on_pushButton_delete_2_clicked()
{
if (radio_data == 1)
{
I2<Book>->pop_node();
delete ui->List_2->takeItem(I2<Book>->get_curr_size());
}
else if (radio_data == 2)
{
I2<Server>->pop_node();
delete ui->List_2->takeItem(I2<Server>->get_curr_size());
}
else if (radio_data == 3)
{
I2<int>->pop_node();
delete ui->List_2->takeItem(I2<int>->get_curr_size());
}
}
void MainWindow::on_pushButton_2_clicked()
{
if (radio_data == 3)
{
AddElement *AE = new AddElement(this);
AE->setWindowModality(Qt::ApplicationModal);
AE->show();
connect(AE,&AddElement::signalElement,this,&MainWindow::connect_element2);
}
else if (radio_data == 1)
{
AddBook *AE = new AddBook(this);
AE->setWindowModality(Qt::ApplicationModal);
AE->show();
connect(AE,&AddBook::signalElement,this,&MainWindow::connect_book2);
}
else
{
AddServer *AE = new AddServer(this);
AE->setWindowModality(Qt::ApplicationModal);
AE->show();
connect(AE,&AddServer::signalElement,this,&MainWindow::connect_server2);
}
}
void MainWindow::on_pushButton_union_clicked()
{
if (radio_data == 1 && radio_link == 1)
{
DL3<Book> = DL1<Book>->union_operation(DL2<Book>);
add_list3(DL3<Book>);
}
else if (radio_data == 2 && radio_link == 1)
{
DL3<Server> = DL1<Server>->union_operation(DL2<Server>);
add_list3(DL3<Server>);
}
else if (radio_data == 3 && radio_link == 1)
{
DL3<int> = DL1<int>->union_operation(DL2<int>);
add_list3(DL3<int>);
}
else if (radio_data == 1 && radio_link == 2)
{
DLC3<Book> = DLC1<Book>->union_operation(DLC2<Book>);
add_list3(DLC3<Book>);
}
else if (radio_data == 2 && radio_link == 2)
{
DLC3<Server> = DLC1<Server>->union_operation(DLC2<Server>);
add_list3(DLC3<Server>);
}
else if (radio_data == 3 && radio_link == 2)
{
DLC3<int> = DLC1<int>->union_operation(DLC2<int>);
add_list3(DLC3<int>);
}
}
void MainWindow::on_pushButton_intersect_clicked()
{
if (radio_data == 1 && radio_link == 1)
{
DL3<Book> = DL1<Book>->intersection_operation(DL2<Book>);
add_list3(DL3<Book>);
}
else if (radio_data == 2 && radio_link == 1)
{
DL3<Server> = DL1<Server>->intersection_operation(DL2<Server>);
add_list3(DL3<Server>);
}
else if (radio_data == 3 && radio_link == 1)
{
DL3<int> = DL1<int>->intersection_operation(DL2<int>);
add_list3(DL3<int>);
}
else if (radio_data == 1 && radio_link == 2)
{
DLC3<Book> = DLC1<Book>->intersection_operation(DLC2<Book>);
add_list3(DLC3<Book>);
}
else if (radio_data == 2 && radio_link == 2)
{
DLC3<Server> = DLC1<Server>->intersection_operation(DLC2<Server>);
add_list3(DLC3<Server>);
}
else if (radio_data == 3 && radio_link == 2)
{
DLC3<int> = DLC1<int>->intersection_operation(DLC2<int>);
add_list3(DLC3<int>);
}
}
void MainWindow::on_pushButton_except_clicked()
{
if (radio_data == 1 && radio_link == 1) {
DL3<Book> = DL1<Book>->except_operation(DL2<Book>);
add_list3(DL3<Book>);
} else if (radio_data == 2 && radio_link == 1) {
DL3<Server> = DL1<Server>->except_operation(DL2<Server>);
add_list3(DL3<Server>);
} else if (radio_data == 3 && radio_link == 1) {
DL3<int> = DL1<int>->except_operation(DL2<int>);
add_list3(DL3<int>);
} else if (radio_data == 1 && radio_link == 2) {
DLC3<Book> = DLC1<Book>->except_operation(DLC2<Book>);
add_list3(DLC3<Book>);
} else if (radio_data == 2 && radio_link == 2) {
DLC3<Server> = DLC1<Server>->except_operation(DLC2<Server>);
add_list3(DLC3<Server>);
} else if (radio_data == 3 && radio_link == 2) {
DLC3<int> = DLC1<int>->except_operation(DLC2<int>);
add_list3(DLC3<int>);
}
}
void MainWindow::on_pushButton_Sexcept_clicked()
{
if (radio_data == 1 && radio_link == 1) {
DL3<Book> = DL1<Book>->symmetric_operation(DL2<Book>);
add_list3(DL3<Book>);
} else if (radio_data == 2 && radio_link == 1) {
DL3<Server> = DL1<Server>->symmetric_operation(DL2<Server>);
add_list3(DL3<Server>);
} else if (radio_data == 3 && radio_link == 1) {
DL3<int> = DL1<int>->symmetric_operation(DL2<int>);
add_list3(DL3<int>);
} else if (radio_data == 1 && radio_link == 2) {
DLC3<Book> = DLC1<Book>->symmetric_operation(DLC2<Book>);
add_list3(DLC3<Book>);
} else if (radio_data == 2 && radio_link == 2) {
DLC3<Server> = DLC1<Server>->symmetric_operation(DLC2<Server>);
add_list3(DLC3<Server>);
} else if (radio_data == 3 && radio_link == 2) {
DLC3<int> = DLC1<int>->symmetric_operation(DLC2<int>);
add_list3(DLC3<int>);
}
} | true |
689c3b6e80da333a72036e08b533143af4300195 | C++ | AmrARaouf/algorithm-detection | /graph-source-code/129-C/12250106.cpp | UTF-8 | 1,118 | 3.15625 | 3 | [
"MIT"
] | permissive | //Language: GNU C++
#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
#include<algorithm>
#include<queue>
#include<set>
using namespace std;
struct Pos{
int x;
int y;
int second;
};
char map[10][10];
int addx[9] = { -1, -1, -1, 0, 0, 0, 1, 1, 1 };
int addy[9] = { -1, 0, 1, -1, 0, 1, -1, 0, 1 };
bool flag;
void dfs(int x, int y, int step)
{
if (step >= 7)
{
flag = true;
return;
}
int nx;
int ny;
for (int i = 0; i < 9; i++)
{
nx = addx[i] + x;
ny = addy[i] + y;
//下一步没有雕像 无法通行 ny-step
//下一步的同列 上一格没有雕像 安全性 ny-step-1
if (nx >= 1 && nx <= 8 && ny >= 1 && ny <= 8 )
{//范围合法
if (nx - step >= 1 && map[nx-step][ny] != 'S')
{//可行
if (nx == 1 || nx - step >= 2 && map[nx-step-1][ny] != 'S')
dfs(nx, ny, step + 1);
}
}
}
}
int main()
{
for (int i = 1; i <= 8; i++)
{
for (int j = 1; j <= 8; j++)
cin >> map[i][j];
cin.get();
}
flag = false;
dfs(8, 1, 0);
if (flag)
cout << "WIN" << endl;
else
cout << "LOSE" << endl;
return 0;
}
| true |
28bf74bd080bca1c5902fae84ef12a47c89491b5 | C++ | GDF22/AwesomeProject | /Component.cpp | UTF-8 | 1,708 | 3.1875 | 3 | [] | no_license | /*
* File: Component.cpp
* Author: GDF
*
* Created on 2 novembre 2013, 16:34
*/
#include "Component.h"
using namespace std;
Component::Component() {
this->visible = true;
this->name ="";
this->parent = this;
}
Component::Component(string name) {
this->visible = true;
this->name = name;
this->parent = this;
}
Component::Component(const Component& orig) {
}
Component::~Component() {
}
bool Component::isVisible(){
return visible;
}
void Component::setVisible(bool isVisible){
this->visible = isVisible;
}
void Component::setName(string name){
this->name = name;
}
string Component::getName(){
return this->name;
}
void Component::draw(Component* par){
}
void Component::setParent(Component* parent){
this->parent = parent;
}
void Component::addComponent(Component* toAdd){
toAdd->setParent(this);
componentList.push_back(toAdd);
}
void Component::toggleVisible(){
visible = !visible;
}
Component* Component::getElementByName(string name){
for(int i = 0 ; i < componentList.size() ; i++){
if (componentList[i]->name == name) return componentList[i];
}
}
Component* Component::getElementByCoord(pair<int,int> coord){
if(visible && coord.first > position.getX() && coord.first < position.getX()+width && coord.second > position.getY() && coord.second < position.getY()+height ){
for(int i = 0 ; i < componentList.size() ; i++){
if (componentList[i]->getElementByCoord(coord) != NULL) return componentList[i]->getElementByCoord(coord) ;
}
return this;
}
else return NULL;
} | true |
cec4a61bf17a8b273d3050cd4f2e3097a3ba437e | C++ | rajsawhoney/Car-Parking-project | /CarClass.h | UTF-8 | 1,258 | 2.921875 | 3 | [] | no_license | //This is the store house of this program Car Parking
#include <ctime> //used for getting local date and time
#include "timeConversion.h" //user defined header file to convert date and time in seconds into date and time format
#include "date_time.h" //user defined header file for getting date and time manually
class ParkingLotControl
{
private:
//For manual date and time
Time entry_time, exit_time; //Created two objects of class Time
Date entry_date, exit_date; //Created two objects of class Date
//For system date and time
string Entry, Exit;
string carId;
string name;
float Pcharge;
public:
static int total_car_parked;
bool entryStatus = false, exitStatus = false;
bool isSystem = false; //to work a/c to date and time mode
bool usingSystem = false;
bool isLotEmpty=true;
void get_entry();
void putcarId(string Id);
double checkTime();
void get_exit();
int checkDate();
float CheckTime();
void calCharge();
void showTotalTime();
void showTotalCarParked();
void showCharge();
void removeCar();
void operator++();
void operator--();
static int getTotalCar();
string getCarId();
} c; //A class obj created
| true |
b55582b477efd11ed051475984bd51756e71bad9 | C++ | Shawn7936/GitTest | /CaptureDirFile/CapDirFile/tools.cpp | UTF-8 | 12,466 | 3.1875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include "tools.h"
#include <time.h>
#define YEAR_SET 1900
#define MON_SET 1
/**
*
* @author Ming
*
* @date 2016/06/08
*
* @fn string Tools::ReadFileLineData( string path ,int lineNumber )
*
* @brief ( 讀取檔案中的指定行數 )
*
* @param ( path : 檔案的路徑+名稱 )
* ( lineNumber : 指定行數 )
* ( isFileEndLine : 是否為最後一行 ( True : 最後一行 ) )
*
* @return none
*
* @note ( 當行的資料 )
*
*/
string Tools::ReadFileLineData( string path ,int lineNumber , bool &isFileEndLine )
{
ifstream filePointer;
char fileLineData[512];
string fileData = "";
/* ( 開啟檔案並設定為讀取模式 ) */
filePointer.open( path , ios::in );
ifstream ifile(path);
/* ( 判斷是否開啟成功 ) */
if( filePointer.good() )
{
/* ( 讀取指定的行數 ) */
for( int getFileLineIndex = 0 ; getFileLineIndex < lineNumber ; getFileLineIndex++ )
{
memset( fileLineData , 0 , sizeof( fileLineData ) );
filePointer.getline( fileLineData , sizeof( fileLineData ) , '\n' );
isFileEndLine = filePointer.eof();
}
/* ( 取得字串 ) */
fileData = string( fileLineData );
}
/* ( 關閉檔案 ) */
filePointer.close();
return fileData;
}
/**
*
* @author Ming
*
* @date 2016/06/08
*
* @fn void Tools::WriteDataToFileAtLast( string path , string addData )
*
* @brief ( 將資料寫入檔案之中最後開始加入資料 )
*
* @param ( path : 檔案的路徑+名稱 )
* ( addData : 要加入的資料 )
*
* @return none
*
* @note none
*
*/
void Tools::WriteDataToFileAtLast( string path , string addData )
{
WriteDataToFile( path , addData , ios::out | ios::app );
}
/**
*
* @author Ming
*
* @date 2016/06/08
*
* @fn void Tools::WriteDataToClearFileData( string path , string addData )
*
* @brief ( 將檔案資料清除並將資料寫入檔案之中 )
*
* @param ( path : 檔案的路徑+名稱 )
* ( addData : 要加入的資料 )
*
* @return none
*
* @note none
*
*/
void Tools::WriteDataToClearFileData( string path , string addData )
{
WriteDataToFile( path , addData , ios::out | ios::trunc );
}
/**
*
* @author Ming
*
* @date 2016/06/08
*
* @fn void Tools::WriteDataToFileAtLastNextLine( string path , string addData )
*
* @brief ( 將資料寫入檔案之中最後資料的下一行 )
*
* @param ( path : 檔案的路徑+名稱 )
* ( addData : 要加入的資料 )
*
* @return none
*
* @note none
*
*/
void Tools::WriteDataToFileAtLastNextLine( string path , string addData )
{
string data = "\n";
data += addData;
WriteDataToFileAtLast( path , data );
}
/**
*
* @author Ming
*
* @date 2016/06/08
*
* @fn void Tools::WriteDataToFile( string path , string addData , int openType )
*
* @brief ( 將資料寫入檔案之中 )
*
* @param ( path : 檔案的路徑+名稱 )
* ( addData : 要加入的資料 )
* ( openType : 開啟檔案的 Type 請參考 std::ios 的說明 )
*
* @return none
*
* @note none
*
*/
void Tools::WriteDataToFile( string path , string addData , int openType )
{
fstream filePointer;
filePointer.open( path , openType );
if( filePointer )
{
filePointer.write( addData.c_str() , addData.length() );
}
}
/**
*
* @author Ming
*
* @date 2016/06/08
*
* @fn string Tools::GetFileName( string path )
*
* @brief ( 取得檔案名稱 : "C:\\123.test" -> return : "123.test" )
*
* @param ( path : 檔案的路徑+名稱 )
*
* @return ( 檔案名稱 )
*
* @note none
*
*/
string Tools::GetFileName( string path )
{
string fileName = "";
int fileIndex = 0;
/* ( 取得 \ or / 的位置 ) */
for( fileIndex = ( path.length() - 1 ) ; fileIndex > 0 ; fileIndex-- )
{
if( ( path[fileIndex] == '\\' ) || ( path[fileIndex] == '/') )
{
/* ( 由於多減一次,所以確定會加回來 ) */
fileIndex++;
break;
}
}
/* ( 依據取得的位置 取得指定字串 ) */
int pathLength = path.length();
for ( int getFineIndex = 0 ; getFineIndex < ( pathLength - fileIndex ) ; getFineIndex++ )
{
fileName += path[ fileIndex + getFineIndex ];
}
return fileName;
}
/**
*
* @author Ming
*
* @date 2016/06/08
*
* @fn vector<string> Tools::split(string str,string pattern)
*
* @brief ( 切割字串 str = "A B" , pattern = " " -> return[0] = "A" , return[1] = "B" )
*
* @param ( str : 要切割的字串 )
* ( pattern : 切割的字串辨別 )
*
* @return ( 切割完的字串 )
*
* @note none
*
*/
vector<string> Tools::split(string str,string pattern)
{
string::size_type pos;
vector<std::string> result;
str+=pattern;
int size=str.size();
for(int i=0; i<size; i++)
{
/* ( 切割指定字串 ) */
pos=str.find(pattern,i);
if((int)pos<size)
{
std::string s=str.substr(i,pos-i);
result.push_back(s);
i=pos+pattern.size()-1;
}
}
return result;
}
/**
*
* @author Ming
*
* @date 2016/06/08
*
* @fn string Tools::GetNowTime()
*
* @brief ( 取得當前時間的字串 )
*
* @param none
*
* @return ( 當前時間的字串 )
*
* @note none
*
*/
string Tools::GetNowTime()
{
/* ( 取得系統時間 ) */
struct tm newtime;
char am_pm[] = "AM";
__time64_t long_time;
errno_t err;
// Get time as 64-bit integer.
_time64( &long_time );
// Convert to local time.
err = _localtime64_s( &newtime, &long_time );
/* ( 系統時間轉換為字串 ) */
string dateTime = FourByteToDecString( newtime.tm_year + YEAR_SET );
dateTime += "/";
dateTime += FourByteToDecString( newtime.tm_mon + MON_SET );
dateTime += "/";
dateTime += FourByteToDecString( newtime.tm_mday );
dateTime += " ";
dateTime += FourByteToDecString( newtime.tm_hour );
dateTime += ":";
dateTime += FourByteToDecString( newtime.tm_min );
dateTime += ":";
dateTime += FourByteToDecString( newtime.tm_sec );
return dateTime;
}
string Tools::GetNowTimeForFile()
{
/* ( 取得系統時間 ) */
struct tm newtime;
char am_pm[] = "AM";
__time64_t long_time;
errno_t err;
// Get time as 64-bit integer.
_time64( &long_time );
// Convert to local time.
err = _localtime64_s( &newtime, &long_time );
/* ( 系統時間轉換為字串 ) */
int zz=newtime.tm_mon;
string dateTime = FourByteToDecString( newtime.tm_year + YEAR_SET );
//補0
if((newtime.tm_mon + MON_SET) < 10)
{
dateTime += "0";
dateTime +=FourByteToDecString( newtime.tm_mon + MON_SET );
}
else
{
dateTime += FourByteToDecString( newtime.tm_mon + MON_SET );
}
if(newtime.tm_mday < 10)
{
dateTime += "0";
dateTime += FourByteToDecString( newtime.tm_mday );
}
else
{
dateTime += FourByteToDecString( newtime.tm_mday );
}
dateTime += "_";
if(newtime.tm_hour < 10)
{
if(0 == newtime.tm_hour )
{
dateTime += "00";
}
else
{
dateTime += "0";
dateTime += FourByteToDecString( newtime.tm_hour );
}
}
else
{
dateTime += FourByteToDecString( newtime.tm_hour );
}
if(newtime.tm_min < 10)
{
if (0 ==newtime.tm_min)
{
dateTime += "00";
}
else
{
dateTime += "0";
dateTime += FourByteToDecString( newtime.tm_min );
}
}
else
{
dateTime += FourByteToDecString( newtime.tm_min );
}
if(newtime.tm_sec < 10)
{
if(0 == newtime.tm_sec )
{
dateTime += "00";
}
else
{
dateTime += "0";
dateTime += FourByteToDecString( newtime.tm_sec );
}
}
else
{
dateTime += FourByteToDecString( newtime.tm_sec );
}
return dateTime;
}
/**
*
* @author Ming
*
* @date 2016/05/09
*
* @fn unsigned int Tools::GetTenToThePowerN( unsigned char powerN )
*
* @brief ( 取得 10 的 N 次方( 1 ~ 1000000000 ) )
*
* @param ( powerN : 10 的 N 次方 )
*
* @return ( 10 的 N 次方值 )
*
* @note none
*
*/
unsigned int Tools::GetTenToThePowerN( unsigned char powerN )
{
unsigned char index = 0;
unsigned int tenPowerN = 1;
/* ( 保護範圍 ) */
if( powerN > 10 )
{
powerN = 10;
}
for( index = 0 ; ( index < powerN ) && ( index <= 10 ) ; index++ )
{
tenPowerN = tenPowerN * 10;
}
return tenPowerN;
}
/**
*
* @author Ming
*
* @date 2016/05/09
*
* @fn string Tools::FourByteToDecString( const unsigned int data )
*
* @brief ( 4 Byte數值轉換 10 進制的字串 )
*
* @param ( data : 4 Byte數值 )
* ( decStr : 10 進制的字串儲存位置 )
* ( decLength : 10 進制要取得的位數 -> 2 : 取得 XX / 3 : 取得 XXX )
*
* @return ( 10進制複製的字串長度 )
*
* @note none
*
*/
string Tools::FourByteToDecString( const unsigned int data )
{
unsigned int getIndex = 0;
string getData = "";
int numberData = 0;
for( getIndex = 10 ; 0 < getIndex ; getIndex-- )
{
/* ( 取得十進制的數值 ) */
numberData = ( ( data / ( GetTenToThePowerN( getIndex - 1 ) ) ) % 10 ) ;
/* ( 前面數值為 0 時不儲存 0 的字串 INT 0x0000000A -> "10" ) */
if( ( numberData > 0 ) || ( getData.length() > 0 ))
{
getData += (char)( numberData + '0' );
}
}
return getData;
}
/**
*
* @author Ming
*
* @date 2016/05/09
*
* @fn unsigned int Tools::StringToFourByte( string numberStr )
*
* @brief (字元轉換 4 Bytes 整數)
*
* @param ( str : 要轉的字元 )
*
* @return ( 轉換後的整數 )
*
* @note none
*
*/
unsigned int Tools::StringToFourByte( string numberStr )
{
unsigned int byteData = 0;
int getStrIndex = 0;
int tenPowerOfN = 0; /* ( 10 次方 ) */
int strLength = numberStr.length();
/* ( 4 個 Byte 最多只有 10 個數值 ) */
if( strLength > 10 )
{
strLength = 10;
}
/* ( 字串的轉換 ) */
for( getStrIndex = strLength ; ( 0 < getStrIndex ) && ( numberStr[ getStrIndex - 1 ] != 0x00 ) ; getStrIndex-- , tenPowerOfN++ )
{
byteData += ( (unsigned int)CharToInt( numberStr[ getStrIndex - 1 ] ) ) * ( GetTenToThePowerN( tenPowerOfN ) );
}
return byteData ;
}
/**
*
* @author Ming
*
* @date 2016/05/09
*
* @fn char Tools::CharToInt(const char str )
*
* @brief (字元轉換整數)
*
* @param ( str : 要轉的字元 )
*
* @return ( 轉換後的整數 )
*
* @note none
*
*/
char Tools::CharToInt(const char str )
{
if( ( str >= '0' ) && ( str <= '9' ) )
{
return ( str - '0' );
}
else if( ( str >= 'a' ) && ( str <= 'f' ) )
{
return ( ( str - 'a' ) + 10 );
}
else if( ( str >= 'A' ) && ( str <= 'F' ) )
{
return ( ( str - 'A' ) + 10 );
}
return 0x00;
}
//取得目前執行檔的路徑
CString Tools::GetAppPath()
{
wchar_t cpath[1024] = {0};
HMODULE hModule = ::GetModuleHandle(NULL);
int Length = ::GetModuleFileNameW(hModule,cpath,1024);
CString strAppPath(cpath);
int index = strAppPath.ReverseFind('\\');
strAppPath = strAppPath.Left(index);
return strAppPath;
}
// 檢查目錄,如果不存在則創建目錄
bool Tools::FindOrCreateDirectory( const char* pszPath )
{
WIN32_FIND_DATA fd;
HANDLE hFind = ::FindFirstFile( pszPath, &fd );
while( hFind != INVALID_HANDLE_VALUE )
{
if ( fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
return true;
}
if ( !::CreateDirectory( pszPath, NULL ) )
{
char szDir[MAX_PATH];
sprintf_s( szDir, sizeof(szDir), "創建目錄[%s]失敗,請檢查權限", pszPath );
//::MessageBox( NULL, szDir, "創建目錄失敗", MB_OK|MB_ICONERROR );
return false;
}
return true;
}
bool Tools::isExistFile(const char *pszFileName)
{
fstream file;
file.open(pszFileName,ios::in);
if(!file)
{
return false;
}
return true;
}
| true |
41bb7686e516e75d2516bf1982f69a0c248cba8f | C++ | elbow95/cpp | /C++Primer/string1.cpp | UTF-8 | 437 | 3.40625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
string str("some string");
// decltype(str.size()) punct_cnt = 0;
// for(auto c:str)
// if(ispunct(c))
// ++punct_cnt;
// cout << punct_cnt
// << "is" << str << endl;
for(decltype(str.size()) index = 0; index != str.size() && !isspace(str[index]); ++index)
str[index] = toupper(str[index]);
cout << str << endl;
} | true |
e56d5bc912abd22559b40b6a325194c29573ea1b | C++ | HangDeYang/Accelerated-cpp | /inputname.cpp | UTF-8 | 232 | 3.140625 | 3 | [] | no_license | #include<iostream>
#include<string>
int main()
{
//ask for user name
std::cout<<"please input your name: \n";
//define name
std::string name;
std::cin>>name;
//show result
std::cout<<"Hello, "<<name<<"! \n";
} | true |
6ae07d59fd919b1ba339e8405242aaaf296a8055 | C++ | ShaiRoitman/clu | /clu/Operators/TrimOperator.cpp | UTF-8 | 810 | 2.90625 | 3 | [
"MIT"
] | permissive | #include "InputFileOperator.h"
#include "CommandLineHandlers/PredicateCommandLineHandler.h"
USING_NAMESPACE(std);
USING_NAMESPACE(clu);
class TrimOperator : public InputFileOperator
{
public:
TrimOperator() {};
virtual bool OnLineRead(string& input)
{
string spaceTrim = Trim(input, ' ');
string tabTrim = Trim(spaceTrim, '\t');
m_OutputHandler->OutputLineFeed(tabTrim);
return true;
}
string Trim(string& input, char c)
{
size_t startOffset = input.find_first_not_of(c);
size_t endOffset = input.find_last_not_of(c);
if (startOffset == string::npos)
return string("");
if (endOffset == string::npos)
return string("");
return input.substr(startOffset, endOffset - startOffset + 1);
}
};
REGISTER_PREDICATE("trim", TrimOperator)->SetHelp("Strips the input from both ends");
| true |
7c1dc5cd63e418c22104ab07602483a5bad195f5 | C++ | silenceinthesky/Tools | /rsa_encryption_decryption/rsa.cpp | UTF-8 | 3,790 | 2.546875 | 3 | [] | no_license | //demo.cpp
// g++ demo.cpp -o demo -lcrypto
#include <openssl/rsa.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <iostream>
#include <string>
#include <cstring>
#include <cassert>
#include <vector>
#include "std_base64.h"
using namespace std;
RSA *createPrivateRSA(std::string key);
//加密
std::string EncodeRSAKeyFile( const std::string& strPemFileName, const std::string& strData )
{
if (strPemFileName.empty() || strData.empty())
{
assert(false);
return "";
}
FILE* hPubKeyFile = fopen(strPemFileName.c_str(), "rb");
if( hPubKeyFile == NULL )
{
assert(false);
return "";
}
std::string strRet;
RSA* pRSAPublicKey = RSA_new();
if(PEM_read_RSA_PUBKEY(hPubKeyFile, &pRSAPublicKey, 0, 0) == NULL)
{
assert(false);
return "";
}
int nLen = RSA_size(pRSAPublicKey);
char* pEncode = new char[nLen + 1];
int ret = RSA_public_encrypt(strData.length(), (const unsigned char*)strData.c_str(), (unsigned char*)pEncode, pRSAPublicKey, RSA_PKCS1_PADDING);
if (ret >= 0)
{
strRet = std::string(pEncode, ret);
}
delete[] pEncode;
RSA_free(pRSAPublicKey);
fclose(hPubKeyFile);
CRYPTO_cleanup_all_ex_data();
return strRet;
}
RSA *createPrivateRSA(std::string key) {
RSA *rsa = NULL;
const char *c_string = key.c_str();
BIO *keybio = BIO_new_mem_buf((void *) c_string, -1);
if (keybio == NULL) {
return 0;
}
rsa = PEM_read_bio_RSAPrivateKey(keybio, &rsa, NULL, NULL);
return rsa;
}
//解密
std::string DecodeRSAKeyFile( const std::string& strPemFileName, const std::string& strData )
{
if (strPemFileName.empty() || strData.empty())
{
assert(false);
return "";
}
FILE* hPriKeyFile = fopen(strPemFileName.c_str(),"rb");
if( hPriKeyFile == NULL )
{
assert(false);
return "";
}
std::string strRet;
std::string strPkey = "-----BEGIN PRIVATE KEY-----\n"
"MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDqBD26a0DhI2Q3\n"
"+fkEK12n8UT27QlTRwiukPQUfqXmMs1NNJHZEO3fBvQUZjqgS85NTEqFdeYqZ1Pp\n"
"7pyDScZUMjryzJiCEiQM2j/3yQethvdAwEHrblIYDjR+k0OU1FKQqGxMoeArvogm\n"
"y1xaOEn1jRaGuqLIrutP/JDysvEnZkzAJTvjxQEy34ITzCPpc0OaaRsqx5WHEq1b\n"
"g/mFpoAyvQmseSi0Vgn8ACULPlEQOajzkvTl/rHAcO4U6OvqeWAd8pp5RP2uXvIU\n"
"UjZejGpcp0sLgiyiUjLUAkQXzsnbMc4RONYJcy5zIZjB8QesSY+stJaSNDblY++n\n"
"dSMjuUeDAgMBAAECggEAXbJVBM7sqzgAaGktyv2SAiwX8MX3deB7GWnwUERlKEYu\n"
"7TqfKsocc6/VClXkI0o2z7w8GjOadF/quT9Qa0CeqBd0gsJoTav1wy+fbRaQfGoN\n"
"lV9lBV6mf/swCX3tESnx5PmKYyRtHRasbNv/nh/rfOWAn3EavD9M+Dmnz4TWCW+o\n"
"R8VEEltX0d53MF72PQBQRCwnu0DGQZnhWc6dyx8P/Loipr9B7QU0A/FGaBqulfX8\n"
"lxtkfNN6enKxLVf1T6tXZE8KTOHKRH6MtZ0gubFImUa1cJd5xXk/QgNGJVM0FDZQ\n"
"6YItp4AXqwvOOBa9vTGasZut1EVBhg9MBZ16zTmMAQKBgQD3njBCAPg2X0b30Q8n\n"
"zf375Hl9UK4HJK6jWwTNJnH4wTMlp9lwd1p9c8ouyrU+fBt8K+3R0DY6k3mtZN0b\n"
"i2VBLA7B3Wctk96fQxoA9PeHI2tPCUETibqlwUyB/yCFTfPOXX9omqLNFXDeUBqI\n"
"E9uAod1+MFExQ15nKxu87wNA1wKBgQDx8C+Nos5BBQR4og3HYrsVF2Az8g5NbLEf\n"
"WfDk8LgCzTmpoQPZhfd69b1aiAR7AGesBxlRDb6PZBiLTU2pRcjQHnie5H1uUzwY\n"
"3UyYd8RRozs3aScVsRHiqSnQr4kuUENBk7G1dJyQZhXx+jgAplQ5yB/XmjU6mH3d\n"
"MuQCgt+dNQKBgQDGuhE217pdQMgfGYyVQJBHOc17EmYo23rBJcpLr0AnCT84SGaN\n"
"CWz5ZBVuykb9l/MjC8p46iarijJMQ7fkZFJmJKrPUhZ9kMBJhzv2aqPBtF5p9x5g\n"
"RNgkMWdqqUv7UF2MUKNxWzGvcDa+ZQF2FqHCsaWmobZ31/6KxCEl15j/zwKBgHeq\n"
"9dp4zMwcTznb7jTRAPhNt6f58lkZigKX2i9jYaEBIaRloCHXwbFwG1jMLmsoqB7O\n"
"5BbTVY5XVEySz/cKLWnDqKXvHpuTUAZ8b4Z6twAqXP/rYwm3q8ERKz2tlYzy5lFp\n"
"XF0EcOx7kh8+RLUNkFuEQTvDatCw3JCsu1sCoNiBAoGBAOntB+eJxCloYN43pTin\n"
"VZPrHINz8SWIfTBtOfVG4DMZcLlHIrHmnN3KLPYe5IAYDnYAXjAqpqHnDpdV1rzz\n"
"tEwgIoPGh2NnLTOTUVu0US6LiojddjauLFsjwqrUcZcwMTAPNMlW/i3DSzm0IrX9\n"
"IUpw/rndwv0cIlb9C+mQg1FI\n"
"-----END PRIVATE KEY-----\n";
//RSA* pRSAPriKey = RSA_new();
RSA* pRSAPriKey = createPrivateRSA(strPkey);
std::cout<<"11111111111"<<std::endl;
std::cout<<"222:"<<std::endl;
//if(PEM_read_RSAPrivateKey(hPriKeyFile, &pRSAPriKey, 0, 0) == NULL)
//{
// assert(false);
// return "";
//}
int nLen = RSA_size(pRSAPriKey);
char* pDecode = new char[nLen+1];
int ret = RSA_private_decrypt(strData.length(), (const unsigned char*)strData.c_str(), (unsigned char*)pDecode, pRSAPriKey, RSA_PKCS1_PADDING);
if(ret >= 0)
{
strRet = std::string((char*)pDecode, ret);
}
delete [] pDecode;
RSA_free(pRSAPriKey);
fclose(hPriKeyFile);
CRYPTO_cleanup_all_ex_data();
return strRet;
}
int main()
{
// g++ rsa.cpp -o rsa.out -I/usr/include/openssl -L/usr/lib64/openssl -lssl -lcrypto
// g++ -o rsa rsa.cpp std_base64.cpp -lssl -lcrypto
//原文
const string one = "skl;dfhas;lkdfhslk;dfhsidfhoiehrfoishfsidf";
cout << "one: " << one << endl;
//密文(二进制数据)
string two = EncodeRSAKeyFile("pubkey.pem", one);
cout << "two: " << two << endl;
string str_data_ = "5Z/MYhzD3oOIueW/+asxM+wO5U2GJ+/lbGTn2MQ9HRGWIXOcDPVydX3D7TyZY49Zui+jRgo7qSI/iIeUs5Ok8/uiA7617OKzeQS7iI8L1o6O8SIab8xr+cjB0HA6DmGjYbbQ30qyJtntNvjfRCACEsrkXbM+K04zqXRndtKQRscjUogOuG7eQ/Iq1TkAPyadVRVeFfF7z1wsBB/WhuE2pXel8XI0gcrKQbv2zfY9BgqhYzoQvFusnVCaqIKMWP1GAO37GseIVboC3DBfPwgf5TAfe3h2fVQR9jUtwaaQsxSQnVI13FINcdLdTQmcEw2/JWQokRJfjk//CoWFAcWiKw==";
// base64 decode
int int_buff_len = str_data_.size() * 2;
vector<unsigned char> vec_b64(int_buff_len, '\0');
int int_result_len = 0;
int ret = Stand_Base64::Decode(str_data_.c_str(), str_data_.size(), &vec_b64[0], int_buff_len, &int_result_len);
if (0 != ret) {
} else {
str_data_ = std::string(vec_b64.begin(), vec_b64.begin() + int_result_len);
}
//顺利的话,解密后的文字和原文是一致的
string three = DecodeRSAKeyFile("prikey.pem", str_data_);
cout << "three: " << three << endl;
return 0;
}
| true |
4fd22f45ba782907dc262eb1e3b31a007fff88b9 | C++ | julienlopez/QWarhammerSimulator | /libs/libwarhammerengine/unit.cpp | UTF-8 | 1,393 | 2.703125 | 3 | [
"MIT"
] | permissive | #include "unit.hpp"
#include <cmath>
#include <gsl/gsl_util>
namespace QWarhammerSimulator::LibWarhammerEngine
{
Unit::Unit(Model model, std::size_t number_of_models, std::size_t number_of_models_in_a_row)
: m_model(std::move(model))
, m_number_of_models(number_of_models)
, m_number_of_models_in_a_row(number_of_models_in_a_row)
, m_rectangle(LibGeometry::Point{0, 0}, 0., rectangleSize())
{
}
LibGeometry::Rectangle Unit::rectangle() const
{
return m_rectangle;
}
std::size_t Unit::numberOfModels() const
{
return m_number_of_models;
}
void Unit::removeModels(const std::size_t number_of_models_to_remove)
{
Expects(number_of_models_to_remove <= m_number_of_models);
const auto previous_rectangle_size = rectangleSize();
m_number_of_models -= number_of_models_to_remove;
const auto width_difference = previous_rectangle_size.y - rectangleSize().y;
if(width_difference > 0)
{
m_rectangle = LibGeometry::Rectangle{m_rectangle.center(), m_rectangle.orientation(), rectangleSize()};
m_rectangle.moveForward(width_difference / 2);
}
}
LibGeometry::Point Unit::rectangleSize() const
{
return {
m_number_of_models_in_a_row * m_model.base_size.x,
std::ceil((double)m_number_of_models / m_number_of_models_in_a_row) * m_model.base_size.y,
};
}
} // namespace QWarhammerSimulator::LibWarhammerEngine
| true |
6732ec9262280c7cf463d07a7157f17882f13098 | C++ | datafl4sh/MeshTriangles | /Efficient integration.cpp | UTF-8 | 4,416 | 3.03125 | 3 | [] | no_license | #include "Mesh triangles.h"
#include "Efficient integration.h"
// Examples of interfaces
double Circle(Point A) {
return pow(A.gety(), 2) + pow(A.getx(), 2) - 2;
}
double CircleYofXpositive(Point A) {
return sqrt(2 - pow(A.getx(), 2));
}
double Parabola(Point A) {
return A.gety() - pow(A.getx(), 2);
}
double ParabolaYofX(double x) {
return pow(x, 2);
}
// The equation of edge y = a*x + b
double EquationOfEdge(double x, double coeff[2]) {
return x*coeff[0] + coeff[1];
}
// Integrating function for curvilinear integral (minus primitive functon by y of initial one)
double IntegFunc(double x, double y) {
return -y;
}
// Corresponding point to z for standart edge [-1,1]
double CorrespPointToStEdge(Edge E, double z) {
return z*(E.getB().getx() - E.getA().getx()) / 2. + (E.getB().getx() + E.getA().getx()) / 2.;
}
// Gaussian quadrature with 5 points for calculating integral on edge
double GaussianQuadrForEdge(Edge E, double * PointsOnStEdge, double * weights, int NumPoints) {
double coeff[2];
coeff[0] = (E.getB().gety() - E.getA().gety()) / (E.getB().getx() - E.getA().getx());
coeff[1] = E.getB().gety() - (E.getB().getx()*(E.getB().gety() - E.getA().gety()) / ((E.getB().getx() - E.getA().getx())));
double a = 0;
for (int i = 0; i < NumPoints; i++) {
a += weights[i] * IntegFunc(CorrespPointToStEdge(E, PointsOnStEdge[i]), EquationOfEdge(CorrespPointToStEdge(E, PointsOnStEdge[i]), coeff));
}
//double a = (5. / 9.*IntegFunc(CorrespPointToStEdge(E, -sqrt(0.6)), EquationOfEdge(CorrespPointToStEdge(E, -sqrt(0.6)), coeff)) + 8. / 9.*IntegFunc(CorrespPointToStEdge(E, 0), EquationOfEdge(CorrespPointToStEdge(E, 0), coeff)) + 5. / 9.*IntegFunc(CorrespPointToStEdge(E, sqrt(0.6)), EquationOfEdge(CorrespPointToStEdge(E, sqrt(0.6)), coeff)));
return (E.getB().getx() - E.getA().getx()) / 2.* a;
}
// Gaussian quadrature with 5 points for calculating integral on part of interface which intersect triangle in points A and B
double GaussianQuadrForCurve(Point A, Point B, double * PointsOnStEdge, double * weights, int NumPoints) {
Edge E(A, B);
double a = 0;
for (int i = 0; i < NumPoints; i++) {
a += weights[i] * IntegFunc(CorrespPointToStEdge(E, PointsOnStEdge[i]), ParabolaYofX(CorrespPointToStEdge(E, PointsOnStEdge[i])));
}
//double a = (5. / 9.*IntegFunc(CorrespPointToStEdge(E, -sqrt(0.6)), ParabolaYofX(CorrespPointToStEdge(E, -sqrt(0.6)))) + 8. / 9.*IntegFunc(CorrespPointToStEdge(E, 0), ParabolaYofX(CorrespPointToStEdge(E, 0))) + 5. / 9.*IntegFunc(CorrespPointToStEdge(E, sqrt(0.6)), ParabolaYofX(CorrespPointToStEdge(E, sqrt(0.6)))));
return (B.getx() - A.getx()) / 2.*a;
}
// Value of integral for curve triangle (need of improvement - for the arbitrary triangle)
double EffIntegration(Triangle T) {
//intersection points
Point one(-1, 1);
Point two(1, 1);
Edge E1(T.getP1(), one);
Edge E2(two, T.getP1());
double I1, I2, I3;
const int NumPoints = 5;
double PointsOnStEdge[NumPoints];
PointsOnStEdge[0] = 0;
PointsOnStEdge[1] = sqrt(5. - 2.*sqrt(10. / 7.)) / 3.;
PointsOnStEdge[2] = -sqrt(5. - 2.*sqrt(10. / 7.)) / 3.;
PointsOnStEdge[3] = sqrt(5. + 2.*sqrt(10. / 7.)) / 3.;
PointsOnStEdge[4] = -sqrt(5. + 2.*sqrt(10. / 7.)) / 3.;
double weights[NumPoints];
weights[0] = 128. / 225.;
weights[1] = (322. + 13.*sqrt(70)) / 900.;
weights[2] = (322. + 13.*sqrt(70)) / 900.;
weights[3] = (322. - 13.*sqrt(70)) / 900.;
weights[4] = (322. - 13.*sqrt(70)) / 900.;
I1 = GaussianQuadrForEdge(E1, PointsOnStEdge, weights, NumPoints);
I2 = GaussianQuadrForCurve(E1.getB(), E2.getA(), PointsOnStEdge, weights, NumPoints);
I3 = GaussianQuadrForEdge(E2, PointsOnStEdge, weights, NumPoints);
return I1 + I2 + I3;
}
// Draw triangle and interface
void PrintSituation(Triangle T) {
vector<Edge> AllEdges;
AllEdges.push_back(T.getD1());
AllEdges.push_back(T.getD2());
AllEdges.push_back(T.getD3());
ofstream fout;
fout.open("DrawTriangleAndCircle.m");
fout << "clf()" << endl;
for (int j = 0; j < AllEdges.size(); j++) {
fout << "drawLine([" << AllEdges.at(j).getA().getx() << "," << AllEdges.at(j).getA().gety() << "], " << "[" << AllEdges.at(j).getB().getx() << ","
<< AllEdges.at(j).getB().gety() << "], '" << AllEdges.at(j).getcolour() << "');" << endl;
fout << "hold on" << endl;
}
fout << "x = -1.5:0.01:1.5;" << endl;
fout << "y = x.*x;" << endl;
fout << "plot(x, y, 'r');" << endl;
fout << "axis([-3 3 0 3]);" << endl;
fout.close();
} | true |