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 |
---|---|---|---|---|---|---|---|---|---|---|---|
a0933d637db701e7457716bf10fac9763c44c55d
|
C++
|
luizfeldmann/Ecliptic
|
/MeeusSeasons.cpp
|
UTF-8
| 3,752 | 2.796875 | 3 |
[] |
no_license
|
#include "MeeusSeasons.h"
#include <iostream>
#include <cmath>
static double calcJDE0(int year, MeeusEvent event)
{
if ((year < 1000) || (year > 3000))
std::cerr << "Attempt calculating events for year " << year << " which is outside the implemented bounds 1000 < Y < 3000!" << std::endl;
double Y = (((double)year) - 2000.0f)/1000.0f;
switch (event)
{
case MARCH_EQUINOX:
return 2451623.80984 + 365242.37404*Y + 0.05169*std::pow(Y, 2) - 0.00411*std::pow(Y, 3) - 0.00057*std::pow(Y, 4);
break;
case JUNE_SOLSTICE:
return 2451716.56767 + 365241.62603*Y + 0.00325*std::pow(Y, 2) + 0.00888*std::pow(Y, 3) - 0.00030*std::pow(Y, 4);
break;
case SEPTEMBER_EQUINOX:
return 2451810.21715 + 365242.01767*Y - 0.11575*std::pow(Y, 2) + 0.00337*std::pow(Y, 3) + 0.00078*std::pow(Y, 4);
break;
case DECEMBER_SOLSTICE:
return 2451900.05952 + 365242.74049*Y - 0.06223*std::pow(Y, 2) - 0.00823*std::pow(Y, 3) + 0.00032*std::pow(Y, 4);
break;
}
return 0;
}
static inline double to_degrees(double radians) {
return radians * (180.0 / M_PI);
}
static inline double to_radians(double degrees) {
return degrees * (M_PI / 180.0);
}
static double calcS(double T)
{
static const double A[] = {485,203,199,182,156,136,77,74,70,58,52,50,45,44,29,18,17,16,14,12,12,12,9,8};
// values given in degrees ... must convert to radians before using in cossine
static const double B[] = {324.96,337.23,342.08,27.85,73.14,171.52,222.54,296.72,243.58,119.81,297.17,21.02,
247.54,325.15,60.93,155.12,288.79,198.04,199.76,95.39,287.11,320.81,227.73,15.45};
static const double C[] = {1934.136,32964.467,20.186,445267.112,45036.886,22518.443,
65928.934,3034.906,9037.513,33718.147,150.678,2281.226,
29929.562,31555.956,4443.417,67555.328,4562.452,62894.029,
31436.921,14577.848,31931.756,34777.259,1222.114,16859.074};
double S = 0;
for(unsigned char i = 0; i < 24; i++)
S += A[i]*std::cos(to_radians( B[i] + (C[i]*T) ));
return S;
}
struct tm GetMeeusEvent(MeeusEvent evt, int year)
{
// calculation of event in JULIAN DAY EPHEMERIS
double JDE;
{
const double JDE0 = calcJDE0(year, evt);
const double T = ( JDE0 - 2451545.0) / 36525;
const double W_deg = 35999.373*T - 2.47;
const double W_rad = to_radians(W_deg);
const double lambda = 1 + 0.0334*cos(W_rad) + 0.0007*cos(2*W_rad);
const double S = calcS( T );
JDE = JDE0 + ( (0.00001*S) / lambda );
}
// conversion to calendar day
JDE += 0.5;
const double Z = floor(JDE);
const double F = JDE - Z;
double A = Z;
if (Z >= 2299161)
{
double alpha = floor( (Z - 1867216.25) / 36524.25 );
A = Z + 1 + alpha - floor( alpha / 4 );
}
const double B = A + 1524;
const double C = floor( (B - 122.1) / 365.25 );
const double D = floor(365.25*C);
const double E = floor( ( B - D )/30.6001 );
// generate TM struct
struct tm utc = {0};
const double day_decimals = B - D - floor(30.6001*E) + F;
utc.tm_mday = std::floor(day_decimals);
const double hour_decimals = 24*(day_decimals - utc.tm_mday);
utc.tm_hour = std::floor(hour_decimals);
const double min_decimals = 60*(hour_decimals - utc.tm_hour);
utc.tm_min = std::floor(min_decimals);
utc.tm_sec = std::floor(60*(min_decimals - utc.tm_min));
utc.tm_mon = (E - ((E <13.5) ? 1 : 13)) - 1;
utc.tm_year = (C - ((utc.tm_mon > 1) ? 4716 : 4715)) - 1900;
const time_t stamp_utc = mktime( &utc );
const time_t stamp_loc = stamp_utc - timezone + ( daylight ? 3600 : 0 );
return *(localtime(&stamp_loc));
}
| true |
aa36a3bc71795bbb64c2e2e1c2713e4e6ccee7ed
|
C++
|
diaaserag/URI-ONLINE-JUDGE-
|
/1557 - Square Matrix III.cpp
|
UTF-8
| 1,316 | 2.765625 | 3 |
[] |
no_license
|
// main.cpp
// answer 1557 - Square Matrix III uri online judge
// solved by diaa serag
// Try hard before using other programmers' codes
#include <iostream>
#include<iomanip>
using namespace std;
int main()
{
int n,l=0,s=0,c=0;
while(cin>>n)
{
if(n==0)
{
break;
}
else
{
int a[100][100];
for(int row=0;row<n;row++)
{
for(int colm=0;colm<n;colm++)
{
a[row][colm]=1;
l=row+colm;
for(int i=0;i<l;i++)
{
a[row][colm]*=2;
}
}
}
s=a[n-1][n-1];
while(s>0)
{
s/=10;
c++;
}
for(int row=0;row<n;row++)
{
for(int colm=0;colm<n;colm++)
{
if(colm==0)
{
cout<<setw(c)<<a[row][colm];
}
else
cout<<" "<<setw(c)<<a[row][colm];
}
cout<<endl;
}
cout<<endl;
c=0;
}
}
return 0;
}
| true |
6604142a3863531cb45e897a8c8b6cb9af5cb92d
|
C++
|
anvesh649/programming-revamp
|
/InterviewBit/Arrays/Max Sum Contiguous Subarray.cpp
|
UTF-8
| 597 | 2.84375 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
int Solution::maxSubArray( const vector<int> &A) {
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details
int global_max = INT_MIN, local_max = 0;
for(int i = 0; i < A.size(); i++)
{
local_max = max(A[i], local_max + A[i]);
global_max = max(local_max, global_max);
}
return global_max;
}
| true |
cce12f6dfd51aae8d18a93fb69978bc078e5e589
|
C++
|
chaowang15/MeshSimplification
|
/mesh_simp/mesh_simp/include/qslim/metric/MxStack.h
|
UTF-8
| 1,450 | 2.75 | 3 |
[] |
no_license
|
#ifndef MXSTACK_INCLUDED // -*- C++ -*-
#define MXSTACK_INCLUDED
#if !defined(__GNUC__)
# pragma once
#endif
/************************************************************************
This provides a very simple typed-access stack class. It's really
just a convenience wrapper for the underlying MxDynBlock class.
Copyright (C) 1998 Michael Garland. See "COPYING.txt" for details.
$Id: MxStack.h,v 1.6 2000/11/20 20:36:38 garland Exp $
************************************************************************/
#include "MxDynBlock.h"
template<class T>
class MxStack : private MxDynBlock<T>
{
public:
MxStack(unsigned int n) : MxDynBlock<T>(n)
{ }
MxStack(const T& val, unsigned int n) : MxDynBlock<T>(n)
{ push(val); }
T& top() { return last(); }
const T& top() const { return last(); }
bool is_empty() { return length()==0; }
T& pop() { return drop(); }
void push(const T& val) { add(val); }
//
// NOTE: In this code, it is *crucial* that we do the add() and
// assignment in separate steps. The obvious alternative
// is something like { add(top()); }. But this is subtly
// broken! The top() will grab a pointer into the block,
// but the add() may reallocate the block before doing the
// assignment. Thus, the pointer will become invalid.
void push() { add(); top() = (*this)[length()-2]; }
};
// MXSTACK_INCLUDED
#endif
| true |
103018484c3ec428ce566c8e8e3a0e38c82cb789
|
C++
|
jwk390/code
|
/lec08/test/geometry.cpp
|
UTF-8
| 590 | 2.546875 | 3 |
[] |
no_license
|
#include "geometry.h"
#include "eecs230.h"
using namespace lec08;
TEST(Posn, X)
{
Posn p;
p.x = 4;
EXPECT_EQ(4, p.x);
}
TEST(Posn, Initialize)
{
Posn p{3, 4};
EXPECT_EQ(3, p.x);
EXPECT_EQ(4, p.y);
}
TEST(Posn, Distance)
{
EXPECT_EQ(13, distance(Posn{3, 9}, Posn{8, 21}));
}
TEST(Circle, PosnWithin)
{
Circle c{Posn{3, 5}, 2};
EXPECT_TRUE(is_within(Posn{3, 5}, c));
EXPECT_TRUE(is_within(Posn{3, 6}, c));
EXPECT_TRUE(is_within(Posn{4, 6}, c));
EXPECT_FALSE(is_within(Posn{3, 7}, c));
EXPECT_FALSE(is_within(Posn{4, 7}, c));
}
| true |
683a45e3b5d6dd3d5448e6011d3eb3795e4c8864
|
C++
|
ccoolliinn/test
|
/Array/Maximal_Rectangle.cpp
|
GB18030
| 2,112 | 3.390625 | 3 |
[] |
no_license
|
#include<vector>
#include<iostream>
#include<algorithm>
using namespace std;
class Solution
{
public:
//άҵ1ľ
int maxRectangle(vector<vector<char>> &nums)
{
if (nums.empty() || nums[0].empty())
return 0;
int m = nums.size();//
int n = nums[0].size();//
////֮ͬǰֱͼһתΪֱͼ
vector<vector<int>> height(m, vector<int>(n, 0));//Ƕһvectorʼ൱ڳʼһm*n0
for(int i=0;i<m;i++){
for (int j = 0; j < n; j++)
{
if (nums[i][j] == '0') {
height[i][j] = 0;
}
else
{
height[i][j] = (i == 0) ? 1 : height[i - 1][j] + 1;
}
}
}
int maxera = 0;
for (int i = 0; i < m; i++)
{
maxera = max(maxera, findlargestrectangle(height[i]));
}
return maxera;
}
int findlargestrectangle(vector<int> &high)//ֱͼĺ
{
int size = high.size();
if (size == 0)
return 0;
if (size == 1)
{
return high[0];
}
vector<int> s;
high.push_back(0);
int sum = 0;
int i = 0;
while (i<high.size())
{
if (s.empty() || high[i] > high[s.back()])
{
s.push_back(i);
i++;
}
else
{
int t = s.back();
s.pop_back();
sum = max(sum, high[t] * (s.empty() ? i : i - s.back() - 1));
}
}
return sum;
}
};
//int main()
//{
//
// ////char a1[] = { '0','0', '0', '0' };
// ////char a2[] = { '1','1', '1', '1' };
// ////char a3[] = { '1','1', '1', '0' };
// ////char a4[] = { '0','1', '0', '0' };///εľ
// vector< vector<char> > res;//ڶ> >мĿոҪʡԣɺϰ
// res.resize(4);//4УʼĴС
// //res[0].resize(0);
// for (int k = 0; k < 4; ++k) {
// res[k].resize(4);//ÿΪ4
// }
//
// for (int i = 0; i < 4; i++) {
// for(int j=0;j<4;j++)
// {
// cin >> res[i][j];//
// }
// }
//
// Solution A;
// int max=A.maxRectangle(res);
//
// return 0;
//
//}
| true |
bdd46086b02e0f3864e62cee471526996aa97690
|
C++
|
fh666z/IncomeStats
|
/SQLStorage.cpp
|
UTF-8
| 6,134 | 2.765625 | 3 |
[] |
no_license
|
#include <QSqlDatabase>
#include <QSqlDriver>
#include <QSqlError>
#include <QSqlQuery>
#include <QDebug>
#include "SQLStorage.hpp"
#include "Definitions.hpp"
//==================================================================================================
// Constructors/Descrutctor
//==================================================================================================
//--------------------------------------------------------------------------------------------------
// Purpose:
// Input:
// Output:
//--------------------------------------------------------------------------------------------------
SQLStorage::SQLStorage()
{
}
//--------------------------------------------------------------------------------------------------
// Purpose:
// Input:
// Output:
//--------------------------------------------------------------------------------------------------
SQLStorage::~SQLStorage()
{
close();
}
//==================================================================================================
// Public methods
//==================================================================================================
//--------------------------------------------------------------------------------------------------
// Purpose:
// Input:
// Output:
//--------------------------------------------------------------------------------------------------
void SQLStorage::create()
{
if (m_pDataStorage == nullptr)
{
m_pDataStorage = new SQLStorage();
m_pDataStorage->prepareStorage();
}
else
qDebug() << "Storage has already been created!!!" << endl;
}
//--------------------------------------------------------------------------------------------------
// Purpose:
// Input:
// Output:
//--------------------------------------------------------------------------------------------------
bool SQLStorage::prepareStorage()
{
m_dbConnDefault = new QSqlDatabase(QSqlDatabase::addDatabase(QSQL_DB_TYPE));
m_dbConnDefault->setHostName(QSQL_HOSTNAME);
m_dbConnDefault->setPort(QSQL_HOST_PORT);
m_dbConnDefault->setDatabaseName(QSQL_DB_NAME);
m_dbConnDefault->setUserName(QSQL_USER);
m_dbConnDefault->setPassword(QSQL_USER_PASS);
if (m_dbConnDefault->isValid() == false)
qDebug() << "Invalid Database!" << endl;
m_state = StorageState::Prepared;
return open();
}
//--------------------------------------------------------------------------------------------------
// Purpose:
// Input:
// Output:
//--------------------------------------------------------------------------------------------------
bool SQLStorage::open()
{
bool success = m_dbConnDefault->open();
if (success)
{
qDebug() << "Connection to:" << m_dbConnDefault->hostName() << ":" << m_dbConnDefault->port() << endl << "Driver:" << m_dbConnDefault->driver() << "successfull." << endl;
m_state = StorageState::Opened;
QSqlQuery createTable(*m_dbConnDefault);
success = createTable.prepare("create table if not exists "
"records(id integer unique not null auto_increment, "
"date DATE, "
"amount DOUBLE, "
"type ENUM('Salary','Bonus','Other'), "
"comment VARCHAR(100),"
"PRIMARY KEY(id))");
// Prepare succeeded
if (success)
success = createTable.exec();
else
qDebug() << "Prepare SQL query failed:" << m_dbConnDefault->lastError().text() << endl;
// Exec succeeded
if (success == false)
qDebug() << "Create table 'records' failed:" << m_dbConnDefault->lastError().text() << endl;
}
else
qDebug() << "Connection failed:"<< m_dbConnDefault->hostName() << ":" << m_dbConnDefault->port() << endl << "Driver:" << m_dbConnDefault->driver() << "Error:"<< m_dbConnDefault->lastError().text() << endl;
return success;
}
//--------------------------------------------------------------------------------------------------
// Purpose:
// Input:
// Output:
//--------------------------------------------------------------------------------------------------
bool SQLStorage::close()
{
m_dbConnDefault->close();
delete m_dbConnDefault;
m_state = StorageState::Closed;
return true;
}
//--------------------------------------------------------------------------------------------------
// Purpose:
// Input:
// Output:
//--------------------------------------------------------------------------------------------------
void SQLStorage::writeRecord(IncomeOrder *new_order)
{
}
//--------------------------------------------------------------------------------------------------
// Purpose:
// Input:
// Output:
//--------------------------------------------------------------------------------------------------
void SQLStorage::writeRecord(double amount, QString date, QString type, QString comment)
{
}
//--------------------------------------------------------------------------------------------------
// Purpose:
// Input:
// Output:
//--------------------------------------------------------------------------------------------------
IncomeOrder *SQLStorage::readRecordByID(int id) const
{
return nullptr;
}
//--------------------------------------------------------------------------------------------------
// Purpose:
// Input:
// Output:
//--------------------------------------------------------------------------------------------------
std::vector<IncomeOrder *> *SQLStorage::readAllRecords() const
{
return nullptr;
}
//--------------------------------------------------------------------------------------------------
// Purpose:
// Input:
// Output:
//--------------------------------------------------------------------------------------------------
void* SQLStorage::getConnection()
{
return m_dbConnDefault;
}
| true |
075e990d8f43b456bbd52e17e6b34691316d2d75
|
C++
|
MarwanG/Graal
|
/oldies/c++/DeltaVarIntEncoder.cpp
|
UTF-8
| 1,232 | 3.109375 | 3 |
[] |
no_license
|
#include "DeltaVarIntEncoder.h"
DeltaVarIntEncoder::DeltaVarIntEncoder(){
prev = 0;
}
void DeltaVarIntEncoder::encodeVarint(uint64_t value, uint8_t* output, uint8_t* outputSizePtr) {
uint8_t outputSize = 0;
while (value > 127) {
output[outputSize] = ((uint8_t)(value & 127)) | 128;
value >>= 7;
outputSize++;
}
output[outputSize++] = ((uint8_t)value) & 127;
*outputSizePtr = outputSize;
}
void DeltaVarIntEncoder::AppendInt32(int value){
if (value > 0){
cout << "value : " << value << endl;
char * c;
int tmp = value - prev;
prev = tmp;
uint64_t v = (uint64_t) tmp;
uint8_t *output = (uint8_t*) malloc(sizeof(uint8_t)*8);
uint8_t *outputSizePtr = (uint8_t*) malloc(sizeof(uint8_t)*8);
encodeVarint(v,output,outputSizePtr);
for(int i = 0; i < *outputSizePtr; i ++)
cout << "output [" << i << "] =" << bitset<8>(output[i]) << endl;
c = (char *)output;
data_.append(c);
}else{
//rien wht should i do ? ignore or throw.
}
}
// int main()
// {
// DeltaVarIntEncoder dd;
// dd.AppendInt32(5);
// dd.AppendInt32(40);
// dd.AppendInt32(50);
// dd.AppendInt32(60);
// cout << dd.data().size() << endl;
// cout << dd.data() << endl;
// }
| true |
e88c13bdd440e3dfcd64c67fae081d162759d177
|
C++
|
blake-boswell/algorithms_review
|
/red_black_tree/redBlackTree.h
|
UTF-8
| 934 | 3.015625 | 3 |
[] |
no_license
|
#define BLACK true
#define RED false
#include <iostream>
struct Node {
int data;
bool color;
Node* left;
Node* right;
Node* parent;
Node() {
data = -1;
color = RED;
left = NULL;
right = NULL;
parent = NULL;
}
};
class RedBlackTree {
private:
Node* root;
void rightRotate(Node* node);
void leftRotate(Node* node);
void transplant(Node* original, Node* donor);
void insertFixUp(Node* z);
void removeFixUp();
bool isLeftChild(Node* node);
bool isRightChild(Node* node);
Node* getUncle(Node* node);
void showInorder(Node* node);
void showPostorder(Node* node);
public:
RedBlackTree();
RedBlackTree(RedBlackTree *rbt);
~RedBlackTree();
bool search(int key);
bool insert(int key);
bool remove(int key);
void show();
};
| true |
e4510f08c4ddd9867c06d9e8cc31895ae13460b9
|
C++
|
mockingbirdnest/Principia
|
/base/not_null.hpp
|
UTF-8
| 15,064 | 3.109375 | 3 |
[
"MIT"
] |
permissive
|
#pragma once
#include <algorithm>
#include <memory>
#include <type_traits>
#include <utility>
#include "base/not_constructible.hpp"
#include "base/traits.hpp"
#include "glog/logging.h"
// This file defines a pointer wrapper |not_null| that statically ensures
// non-nullness where possible, and performs runtime checks at the point of
// conversion otherwise.
// The point is to replace cases of undefined behaviour (dereferencing a null
// pointer) by well-defined, localized, failure.
// For instance, when dereferencing a null pointer into a reference, a segfault
// will generally not occur when the pointer is dereferenced, but where the
// reference is used instead, making it hard to track where an invariant was
// violated.
// The static typing of |not_null| also optimizes away some unneeded checks:
// a function taking a |not_null| argument will not need to check its arguments,
// the caller has to provide a |not_null| pointer instead. If the object passed
// is already a |not_null|, no check needs to be performed.
// The syntax is as follows:
// not_null<int*> p // non-null pointer to an |int|.
// not_null<std::unique_ptr<int>> p // non-null unique pointer to an |int|.
// |not_null| does not have a default constructor, since there is no non-null
// default valid pointer. The only ways to construct a |not_null| pointer,
// other than from existing instances of |not_null|, are (implicit) conversion
// from a nullable pointer, the factory |check_not_null|, and
// |make_not_null_unique|.
//
// The following example shows uses of |not_null|:
// void Accumulate(not_null<int*> const accumulator,
// not_null<int const*> const term) {
// *accumulator += *term; // This will not dereference a null pointer.
// }
//
// void InterfaceAccumulator(int* const dubious_accumulator,
// int const* const term_of_dubious_c_provenance) {
// // The call below performs two checks. If either parameter is null, the
// // program will fail (through a glog |CHECK|) at the callsite.
// Accumulate(dubious_accumulator, term_of_dubious_c_provenance);
// }
//
// void UseAccumulator() {
// not_null<std::unique_ptr<int>> accumulator =
// make_not_null_unique<int>(0);
// not_null<int> term = // ...
// // This compiles, no check is performed.
// Accumulate(accumulator.get(), term);
// // ...
// }
//
// If implicit conversion from a nullable pointer to |not_null| does not work,
// e.g. for template deduction, use the factory |check_not_null|.
// template<typename T>
// void Foo(not_null<T*> not_null_ptr);
//
// SomeType* ptr;
// // The following will not compile:
// Foo(ptr);
// // The following works:
// Foo(check_not_null(ptr));
// // It is more concise than the alternative:
// Foo(not_null<SomeType*>(ptr))
//
// The following optimization is made possible by the use of |not_null|:
// |term == nullptr| can be expanded to false through inlining, so the branch
// will likely be optimized away.
// if (term == nullptr) // ...
// // Same as above.
// if (term) // ...
namespace principia {
namespace base {
namespace _not_null {
namespace internal {
using namespace principia::base::_not_constructible;
using namespace principia::base::_traits;
template<typename Pointer>
class not_null;
// Type traits.
// |remove_not_null<not_null<T>>::type| is |remove_not_null<T>::type|.
// The recurrence ends when |T| is not an instance of |not_null|, in which case
// |remove_not_null<T>::type| is |T|.
template<typename Pointer>
struct remove_not_null : not_constructible {
using type = Pointer;
};
template<typename Pointer>
struct remove_not_null<not_null<Pointer>> {
using type = typename remove_not_null<Pointer>::type;
};
// Wrapper struct for pointers with move assigment compatible with not_null.
template <typename Pointer, typename = void>
struct NotNullStorage;
// Case: move assignment is equvalent to copy (raw pointer).
template <typename P>
struct NotNullStorage<
P, std::enable_if_t<std::is_trivially_move_assignable_v<P>>> {
explicit NotNullStorage(P&& pointer) : pointer(std::move(pointer)) {}
NotNullStorage(NotNullStorage const&) = default;
NotNullStorage(NotNullStorage&&) = default;
NotNullStorage& operator=(NotNullStorage const&) = default;
NotNullStorage& operator=(NotNullStorage&&) = default;
P pointer;
};
// Case: move assignent is nontrivial (unique_ptr).
template <typename P>
struct NotNullStorage<
P, std::enable_if_t<!std::is_trivially_move_assignable_v<P>>> {
explicit NotNullStorage(P&& pointer) : pointer(std::move(pointer)) {}
NotNullStorage(NotNullStorage const&) = default;
NotNullStorage(NotNullStorage&&) = default;
NotNullStorage& operator=(NotNullStorage const&) = default;
// Implemented as a swap, so the argument remains valid.
NotNullStorage& operator=(NotNullStorage&& other) {
std::swap(pointer, other.pointer);
return *this;
}
P pointer;
};
// When |T| is not a reference, |_checked_not_null<T>| is |not_null<T>| if |T|
// is not already an instance of |not_null|. It fails otherwise.
// |_checked_not_null| is invariant under application of reference or rvalue
// reference to its template argument.
template<typename Pointer>
using _checked_not_null = typename std::enable_if<
!is_instance_of_v<not_null, typename std::remove_reference<Pointer>::type>,
not_null<typename std::remove_reference<Pointer>::type>>::type;
// We cannot refer to the template |not_null| inside of |not_null|.
template<typename Pointer>
inline constexpr bool is_instance_of_not_null_v =
is_instance_of_v<not_null, Pointer>;
// |not_null<Pointer>| is a wrapper for a non-null object of type |Pointer|.
// |Pointer| should be a C-style pointer or a smart pointer. |Pointer| must not
// be a const, reference, rvalue reference, or |not_null|. |not_null<Pointer>|
// is movable and may be left in an invalid state when moved, i.e., its
// |storage_.pointer| may become null.
// |not_null<not_null<Pointer>>| and |not_null<Pointer>| are equivalent.
// This is useful when a |template<typename T>| using a |not_null<T>| is
// instanced with an instance of |not_null|.
template<typename Pointer>
class not_null final {
public:
// The type of the pointer being wrapped.
// This follows the naming convention from |std::unique_ptr|.
using pointer = typename remove_not_null<Pointer>::type;
// Smart pointers define this type.
using element_type = typename std::pointer_traits<pointer>::element_type;
not_null() = delete;
// Copy constructor from an other |not_null<Pointer>|.
not_null(not_null const&) = default;
// Copy contructor for implicitly convertible pointers.
template<typename OtherPointer,
typename = typename std::enable_if<
std::is_convertible<OtherPointer, pointer>::value>::type>
not_null(not_null<OtherPointer> const& other);
// Constructor from a nullable pointer, performs a null check.
template<typename OtherPointer,
typename = typename std::enable_if<
std::is_convertible<OtherPointer, pointer>::value &&
!is_instance_of_not_null_v<pointer>>::type>
not_null(OtherPointer other); // NOLINT(runtime/explicit)
// Explicit copy constructor for static_cast'ing.
template<typename OtherPointer,
typename = typename std::enable_if<
!std::is_convertible<OtherPointer, pointer>::value>::type,
typename = decltype(static_cast<pointer>(
std::declval<OtherPointer>()))>
explicit not_null(not_null<OtherPointer> const& other);
// Move constructor from an other |not_null<Pointer>|. This constructor may
// invalidate its argument.
not_null(not_null&&) = default;
// Move contructor for implicitly convertible pointers. This constructor may
// invalidate its argument.
template<typename OtherPointer,
typename = typename std::enable_if<
std::is_convertible<OtherPointer, pointer>::value>::type>
not_null(not_null<OtherPointer>&& other);
// Explicit move constructor for static_cast'ing. This constructor may
// invalidate its argument.
template<typename OtherPointer,
typename = typename std::enable_if<
!std::is_convertible<OtherPointer, pointer>::value>::type,
typename = decltype(static_cast<pointer>(
std::declval<OtherPointer>()))>
explicit not_null(not_null<OtherPointer>&& other);
// Copy assigment operators.
not_null& operator=(not_null const&) = default;
template<typename OtherPointer,
typename = typename std::enable_if<
std::is_convertible<OtherPointer, pointer>::value>::type>
not_null& operator=(not_null<OtherPointer> const& other);
// Move assignment operators.
not_null& operator=(not_null&& other) = default;
// This operator may invalidate its argument.
template<typename OtherPointer,
typename = typename std::enable_if<
std::is_convertible<OtherPointer, pointer>::value>::type>
not_null& operator=(not_null<OtherPointer>&& other);
// Returns |storage_.pointer|, by const reference to avoid a copy if |pointer|
// is |unique_ptr|.
// If this were to return by |const&|, ambiguities would arise where an rvalue
// of type |not_null<pointer>| is given as an argument to a function that has
// overloads for both |pointer const&| and |pointer&&|.
// Note that the preference for |T&&| over |T const&| for overload resolution
// is not relevant here since both go through a user-defined conversion,
// see 13.3.3.2.
// GCC nevertheless incorrectly prefers |T&&| in that case, while clang and
// MSVC recognize the ambiguity.
// The |RValue| test gives two examples of this.
operator pointer const&&() const&;
template<typename OtherPointer,
typename = std::enable_if_t<
std::is_convertible<pointer, OtherPointer>::value &&
!std::is_same<pointer, OtherPointer>::value &&
!is_instance_of_not_null_v<OtherPointer>>>
operator OtherPointer() const&;
// Used to convert a |not_null<unique_ptr<>>| to |unique_ptr<>|.
operator pointer&&() &&;
template<typename OtherPointer,
typename = std::enable_if_t<
std::is_convertible<pointer, OtherPointer>::value &&
!is_instance_of_not_null_v<OtherPointer>>>
operator OtherPointer() &&; // NOLINT(whitespace/operators)
// Returns |*storage_.pointer|.
std::add_lvalue_reference_t<element_type> operator*() const;
std::add_pointer_t<element_type> operator->() const;
// When |pointer| has a |get()| member function, this returns
// |storage_.pointer.get()|.
template<typename P = pointer, typename = decltype(std::declval<P>().get())>
not_null<decltype(std::declval<P>().get())> get() const;
// When |pointer| has a |release()| member function, this returns
// |storage_.pointer.release()|. May invalidate its argument.
template<typename P = pointer,
typename = decltype(std::declval<P>().release())>
not_null<decltype(std::declval<P>().release())> release();
// When |pointer| has a |reset()| member function, this calls
// |storage_.pointer.reset()|.
template<typename Q,
typename P = pointer,
typename = decltype(std::declval<P>().reset())>
void reset(not_null<Q> ptr);
// The following operators are redundant for valid |not_null<Pointer>|s with
// the implicit conversion to |pointer|, but they should allow some
// optimization.
// Returns |false|.
bool operator==(std::nullptr_t other) const;
// Returns |true|.
bool operator!=(std::nullptr_t other) const;
// Returns |true|.
operator bool() const;
// Equality.
bool operator==(pointer other) const;
bool operator==(not_null other) const;
bool operator!=(pointer other) const;
bool operator!=(not_null other) const;
// Ordering.
bool operator<(not_null other) const;
bool operator<=(not_null other) const;
bool operator>=(not_null other) const;
bool operator>(not_null other) const;
private:
struct unchecked_tag final {};
// Creates a |not_null<Pointer>| whose |storage_.pointer| equals the given
// |pointer|, dawg. The constructor does *not* perform a null check. Callers
// must perform one if needed before using it.
explicit not_null(pointer other, unchecked_tag tag);
NotNullStorage<Pointer> storage_;
static constexpr unchecked_tag unchecked_tag_{};
template<typename OtherPointer>
friend class not_null;
template<typename P>
friend _checked_not_null<P> check_not_null(P pointer);
template<typename T, typename... Args>
friend not_null<std::shared_ptr<T>> make_not_null_shared(Args&&... args);
template<typename T, typename... Args>
friend not_null<std::unique_ptr<T>> make_not_null_unique(Args&&... args);
};
// We want only one way of doing things, and we can't make
// |not_null<Pointer> const| and |not_null<Pointer const>| etc. equivalent
// easily.
// Use |not_null<Pointer> const| instead.
template<typename Pointer>
class not_null<Pointer const>;
// Use |not_null<Pointer>&| instead.
template<typename Pointer>
class not_null<Pointer&>;
// Use |not_null<Pointer>&&| instead.
template<typename Pointer>
class not_null<Pointer&&>;
// Factory taking advantage of template argument deduction. Returns a
// |not_null<Pointer>| to |*pointer|. |CHECK|s that |pointer| is not null.
template<typename Pointer>
_checked_not_null<Pointer> check_not_null(Pointer pointer);
#if 0
// While the above factory would cover this case using the implicit
// conversion, this results in a redundant |CHECK|.
// This function returns its argument.
template<typename Pointer>
not_null<Pointer> check_not_null(not_null<Pointer> pointer);
#endif
template<typename T, typename... Args>
not_null<std::shared_ptr<T>> make_not_null_shared(Args&&... args);
// Factory for a |not_null<std::unique_ptr<T>>|, forwards the arguments to the
// constructor of T. |make_not_null_unique<T>(args)| is interchangeable with
// |check_not_null(make_unique<T>(args))|, but does not perform a |CHECK|, since
// the result of |make_unique| is not null.
template<typename T, typename... Args>
not_null<std::unique_ptr<T>> make_not_null_unique(Args&&... args);
// For logging.
template<typename Pointer>
std::ostream& operator<<(std::ostream& stream,
not_null<Pointer> const& pointer);
template<typename Result, typename T>
not_null<Result> dynamic_cast_not_null(not_null<T*> const pointer);
template<typename Result, typename T>
not_null<Result> dynamic_cast_not_null(not_null<std::unique_ptr<T>>&& pointer);
} // namespace internal
using internal::check_not_null;
using internal::dynamic_cast_not_null;
using internal::make_not_null_shared;
using internal::make_not_null_unique;
using internal::not_null;
using internal::remove_not_null;
} // namespace _not_null
} // namespace base
} // namespace principia
#include "base/not_null_body.hpp"
| true |
1bedc34e3ad05e896742d00743853a51e70f4789
|
C++
|
jiaaaaaaaqi/ACM_Code
|
/HDU/1698/14010530_AC_873ms_7960kB.cpp
|
UTF-8
| 2,113 | 2.671875 | 3 |
[] |
no_license
|
#include<map>
#include<queue>
#include<string>
#include<vector>
#include<math.h>
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#define inf 0x3f3f3f3f
typedef unsigned long long int ull;
typedef long long int ll;
using namespace std;
const int maxn = 400005;
int n, m;
ll node[maxn];
ll add[maxn];
void init() {
memset(add, 0, sizeof(add));
memset(node, 0, sizeof(node));
}
void pushdown(int root, int num) {
if(add[root]) {
add[root << 1] = add[root];
add[root << 1 | 1] = add[root];
node[root << 1] = add[root] * (num - (num >> 1));
node[root << 1 | 1] = add[root] * (num >> 1);
add[root] = 0;
}
return ;
}
void pushup(int root) {
node[root] = node[root << 1] + node[root << 1 | 1];
}
void build(int left, int right, int root) {
if(left == right) {
node[root] = 1;
return ;
}
ll mid = (left + right) >> 1;
build(left, mid, root << 1);
build(mid + 1, right, root << 1 | 1);
pushup(root);
}
void update(int left, int right, int prel, int prer, int val, int root) {
if(prel <= left && prer >= right) {
node[root] = (ll)val * (right - left + 1);
add[root] = (ll)val;
return ;
}
pushdown(root, right - left + 1);
int mid = (left + right) >> 1;
if(prel <= mid)
update(left, mid, prel, prer, val, root << 1);
if(prer > mid)
update(mid + 1, right, prel, prer, val, root << 1 | 1);
pushup(root);
return ;
}
ll query(int left, int right, int prel, int prer, int root) {
if(prel <= left && prer >= right)
return node[root];
pushdown(root, right - left + 1);
int mid = (left + right) >> 1;
ll ans = 0;
if(prel <= mid)
ans += query(left, mid, prel, prer, root << 1);
if(prer > mid)
ans += query(mid + 1, right, prel, prer, root << 1 | 1);
return ans;
}
int main() {
int T;
int cas = 1;
scanf("%d", &T);
while(T--) {
init();
scanf("%d", &n);
build(1, n, 1);
scanf("%d", &m);
while(m--) {
int prel, prer, val;
scanf("%d%d%d", &prel, &prer, &val);
update(1, n, prel, prer, val, 1);
}
ll ans = query(1, n, 1, n, 1);
printf("Case %d: The total value of the hook is %lld.\n", cas++, ans);
}
return 0;
}
| true |
54cc1ead3fbbfc743fd760503239d3ab1151e0e2
|
C++
|
jenzou/Fluid-Simulator
|
/simulator/code/OptimizationLib/SoftUnilateralConstraint.cpp
|
UTF-8
| 1,043 | 3.28125 | 3 |
[] |
no_license
|
#include "SoftUnilateralConstraint.h"
SoftUnilateralConstraint::SoftUnilateralConstraint(double stiffness, double epsilon) {
this->epsilon = epsilon;
a1 = stiffness;
b1 = -0.5 * a1 * epsilon;
c1 = -1.0 / 3 * (-b1 - a1 * epsilon) * epsilon - 1.0 / 2 * a1 * epsilon * epsilon - b1 * epsilon;
a2 = (-b1 - a1 * epsilon) / (epsilon * epsilon);
b2 = a1;
c2 = b1;
d2 = c1;
}
SoftUnilateralConstraint::~SoftUnilateralConstraint() {
}
// returns 1/2 C'C, where C is the current set of equality constraint values
double SoftUnilateralConstraint::computeValue(double x) {
if (x < 0)
return 0.5 * a1 * x * x + b1 * x + c1;
if (x < epsilon)
return 1.0 / 3 * a2 * x * x * x + 0.5 * b2 * x * x + c2 * x + d2;
return 0;
}
double SoftUnilateralConstraint::computeDerivative(double x) {
if (x < 0)
return a1 * x + b1;
if (x < epsilon)
return a2 * x * x + b2 * x + c2;
return 0;
}
double SoftUnilateralConstraint::computeSecondDerivative(double x) {
if (x < 0)
return a1;
if (x < epsilon)
return 2 * a2 * x + b2;
return 0;
}
| true |
757812dbecde7e32fd96319e1646371e26844416
|
C++
|
anandaditya444/Competitive-Coding
|
/Codeforces/Codeforces_448A.cpp
|
UTF-8
| 463 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int cups = 0, medals = 0, temp;
for(int i = 0; i < 3; i ++) {
scanf("%d",&temp);
cups += temp;
}
for(int i = 0; i < 3; i ++) {
scanf("%d",&temp);
medals += temp;
}
int n;
scanf("%d",&n);
int count = 0;
count += cups/5;
count += medals/10;
if(cups%5 != 0)
count++;
if(medals%5 != 0)
count++;
if(count <= n) {
printf("YES\n");
}
else {
printf("NO\n");
}
return 0;
}
| true |
238eb0dbdb463c440ccf23cdf4e86e247929e87b
|
C++
|
mamengchen/-Data_Structure
|
/vector/my_vector.cpp
|
GB18030
| 4,644 | 3.625 | 4 |
[] |
no_license
|
#include <iostream>
#include <algorithm>
#include <string>
#include <assert.h>
using namespace std;
namespace mmc
{
template<class T>
class My_vector
{
public:
//vectorĵһԭָ
typedef T* Iterator;
typedef const T* const_Iterator;
Iterator my_begin() { return _start; }
Iterator my_end() { return _finish; }
const_Iterator my_cbegin() const { return _start; }
const_Iterator my_cend() const { return _finish; }
size_t my_size() const { return _finish - _start; }
size_t my_capacity() const { return _endOfStorage - _start; }
My_vector()
:_start(nullptr)
, _finish(nullptr)
, _endOfStorage(nullptr)
{}
My_vector(int n, const T& value = T())
:_start(nullptr)
, _finish(nullptr)
, _endOfStorage(nullptr)
{
Reserve(n);
while (n--)
{
PushBack(value);
}
}
//ʹIteratorᵼ³ʼĵ[first, last]ֻ
//vectorĵ[first, last]ĵ.
template<class Input_Iterator>
My_vector(Input_Iterator first, Input_Iterator last)
{
Reserve(last - first);
while (first != last)
{
PushBack(*first);
++first;
}
}
My_vector(const My_vector<T>& v)
:_start(nullptr)
, _finish(nullptr)
, _endOfStorage(nullptr)
{
Reserve(v.my_capacity());
Iterator it = my_begin();
const_Iterator cit = v.my_cbegin();
while (cit != v.my_cend())
{
*it++ = *cit++;
}
_finish = _start + v.my_size();
_endOfStorage = _start + v.my_capacity();
}
My_vector<T>& operator= (My_vector<T> v)
{
my_swap(v);
return *this;
}
~My_vector()
{
delete[] _start;
_start = _finish = _endOfStorage = nullptr;
}
void my_swap(My_vector<T>& v)
{
swap(_start, v._start);
swap(_finish, v._finish);
swap(_endOfStorage, v._endOfStorage);
}
void PushBack(const T& x)
{
Insert(my_end(), x);
}
void PopBack()
{
Iterator end = my_end();
end--;
Erase(end);
}
void Resize(size_t n, const T& value = T())
{
//1.nСڵǰsize,ݸСN
if (n <= my_size())
{
_finish = _start + n;
return;
}
//2.ռ䲻
if (n > my_capacity())
{
Reserve(n);
}
//3.sizen
Iterator it = _finish;
Iterator _finish = _start + n;
while (it != _finish)
{
*it = value;
++it;
}
}
void Reserve(size_t n)
{
if (n > my_capacity())
{
size_t size = my_size();
T* tmp = new T[n];
if (_start)
{
for (size_t i = 0; i < size; ++i)
{
tmp[i] = _start[i];
}
}
_start = tmp;
_finish = _start + size;
_endOfStorage = _start + n;
}
}
void Print()
{
Iterator begin = my_begin();
Iterator end = my_end();
for (; begin != end; begin++)
{
cout << *begin << " ";
}
cout << endl;
}
Iterator Insert(Iterator pos, const T& x)
{
assert(pos <= _finish);
int count = 0;
Iterator begin = my_begin();
while (begin++ != pos)
{
count++;
}
//ռ䲻Ƚ
if (_finish == _endOfStorage)
{
size_t newCapacity = my_capacity() == 0 ? 1 : my_capacity() * 2;
Reserve(newCapacity);
//ݣpos
pos = _start + count;
}
Iterator end = _finish - 1;
while (end >= pos)
{
*(end + 1) = *end;
--end;
}
*pos = x;
++_finish;
return pos;
}
Iterator Erase(Iterator pos)
{
//ƶݽɾ
Iterator begin = pos + 1;
while (begin != _finish)
{
*(begin - 1) = *begin;
++begin;
}
--_finish;
return pos;
}
T& operator[](size_t pos)
{
return _start[pos];
}
Iterator Find(const T& x)
{
Iterator begin = my_begin();
Iterator end = my_end();
for (; begin != end; begin++)
{
if (*begin == x)
{
break;
}
}
return begin;
}
private:
Iterator _start; //ָݿĿʼ
Iterator _finish; //ָЧݵβ
Iterator _endOfStorage; //ָ洢β
};
}
int main()
{
mmc::My_vector<int> num;
mmc::My_vector<int> num1(3, 10);
mmc::My_vector<int> num2(num1.my_begin(), num1.my_end());
mmc::My_vector<int> num3(num2);
num1.Print();
num2.Print();
num3.Print();
int testInts[] = { 13, 23, 77, 87, 45 };
mmc::My_vector<int> num4(testInts, testInts + sizeof(testInts) / sizeof(int));
num4.PopBack();
num4.PushBack(100);
mmc::My_vector<int>::Iterator it = num4.my_begin();
num4.Insert(it, 10);
num4.Print();
return 0;
}
| true |
8d324d8cf9c11f31e0a7bb878b67b85935762ae4
|
C++
|
liyinan1001/hangman-AI-CPP
|
/function.cpp
|
UTF-8
| 5,947 | 2.65625 | 3 |
[] |
no_license
|
#include "function.hpp"
using namespace std;
void buildDicts(vector<string>& dicts, vector<long long>& counts, vector<double>& freq) {
string filePath = "./count_1w.txt";
ifstream fin(filePath);
long long sum = 0;
while(!fin.eof()) {
string word;
long long count;
fin >> word >> count;
sum += count;
transform(word.begin(), word.end(), word.begin(), ::toupper);
dicts.push_back(word);
counts.push_back(count);
}
long long n = dicts.size();
for(long long i = 0; i < n; i++) {
freq.push_back(counts[i] * 1.0 / sum);
}
fin.close();
}
static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
void downloadUrl(const string& url, string& content) {
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &content);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
}
string getJson(const string& all, const string& name) {
if(name == "remaining_guesses") {
size_t nameEndPos = all.find(name) + name.length();
size_t valStart = all.find(":", nameEndPos + 1) + 1;
size_t valEnd = all.find(",", nameEndPos + 1) - 1;
return all.substr(valStart, valEnd - valStart + 1);
}
else {
size_t nameEndPos = all.find(name) + name.length();
size_t valStart = all.find("\"", nameEndPos + 1) + 1;
size_t valEnd = all.find("\"", valStart) - 1;
return all.substr(valStart, valEnd - valStart + 1);
}
}
void fetchInitialEvi(vector<int>& e_wordLen, int& life, const string initialUrl, string& token) {
string content;
downloadUrl(initialUrl, content);
if(getJson(content, "status") == "DEAD") {life = 0; return;}
token = getJson(content, "token");
life = stoi(getJson(content, "remaining_guesses"));
string sentence = getJson(content, "state");
int wordLen = 0;
for(int i = 0; i < sentence.length(); i++) {
if(sentence[i] == '_') {
wordLen++;
if(i + 1 == sentence.length()) {e_wordLen.push_back(wordLen);}
}
else if(sentence[i] != '_' && wordLen != 0) {
e_wordLen.push_back(wordLen);
wordLen = 0;
}/*
else { //punctuation
if(sentence[i] == '\'' && i + 1 < sentence.length() && sentence[i + 1] == '_') {hasS = true;} // I assume When ' appear, only s or nothing is followed.
if(wordLen != 0) {
e_wordLen.push_back(wordLen);
wordLen = 0;
i++;
}
}*/
}
}
string getNextGuess(const vector<unordered_set<char> >& e_notInLetter, const vector<unordered_map<int, char> >& e_pos_inLetter, const vector<string>& dicts, const vector<double>& freq, const vector<int>& e_wordLen) {
unordered_map<char, double> letter_freq;
for(int i = 0; i < e_wordLen.size(); i++) {
double validWordFreqSum = 0;
for(int idict = 0; idict < dicts.size(); idict++) {
validWordFreqSum += isValidWord(dicts[idict], e_notInLetter[i], e_pos_inLetter[i], e_wordLen[i]) ? freq[i] : 0;
}
for(int idict = 0; idict < dicts.size(); idict++) {
string dictWord = dicts[idict];
if(isValidWord(dictWord, e_notInLetter[i], e_pos_inLetter[i], e_wordLen[i])) {
for(int wordPos = 0; wordPos < dictWord.length(); wordPos++) {
letter_freq[dictWord[wordPos]] += e_pos_inLetter[i].find(wordPos) == e_pos_inLetter[i].end() ? freq[idict] / validWordFreqSum : 0;
}
}
}
}
return getNextLetter(letter_freq);
}
void pushGuessUpDateEvi(const string& nextUrl, vector<unordered_set<char> >& e_notInLetter, vector<unordered_map<int, char> >& e_pos_inLetter, vector<int>& e_wordLen, int& life, bool& success, const string& guess) {
string content;
for(int j = 0; j < e_wordLen.size(); j++) {
e_notInLetter[j].insert(guess[0]);
}
downloadUrl(nextUrl, content);
string sentence = getJson(content, "state");
if(getJson(content, "status") == "DEAD") {cout << sentence << endl; life = 0; return;}
life = stoi(getJson(content, "remaining_guesses"));
if(getJson(content, "status") == "FREE") {cout << sentence << endl; success = true; return;}
int pos = 0;
int iWord = 0;
while(pos < sentence.length()) {
while(sentence[pos] != '_' && !(sentence[pos] <= 'Z' && sentence[pos] >= 'A')) {pos++;}
for(int i = 0; i < e_wordLen[iWord]; i++) {
if(sentence[pos] <= 'Z' && sentence[pos] >= 'A') {
e_pos_inLetter[iWord][i] = sentence[pos];
}
pos++;
}
//while(pos < sentence.length() && sentence[pos] != ' ') {pos++;} // jump over possible 'S
iWord++;
}
}
bool isValidWord(const string& word, const unordered_set<char>& notInLetter, const unordered_map<int, char>& pos_inLetter, const int wordLen) {
if(word.length() != wordLen) {return false;}
for(int i = 0; i < word.size(); i++) {
if(pos_inLetter.find(i) != pos_inLetter.end()) {
if(word[i] != pos_inLetter.at(i)) {return false;}
}
else {
if(notInLetter.find(word[i]) != notInLetter.end()) {return false;}
}
}
return true;
}
string getNextLetter(const unordered_map<char, double>& letter_freq) {
char maxLetter = 'A';
double maxFreq = 0;
for(auto pair : letter_freq) {
if(pair.second > maxFreq) {
maxLetter = pair.first;
maxFreq = pair.second;
}
}
string res;
res += maxLetter;
return res;
}
| true |
bc0edb5265a1b0d837d7900c0c52435c22425d36
|
C++
|
Whu-wxy/AmbientLightLab
|
/hysteresisloginterval.cpp
|
UTF-8
| 2,193 | 2.609375 | 3 |
[] |
no_license
|
#include "hysteresisloginterval.h"
HysteresisLogInterval::HysteresisLogInterval(int numTh)
{
m_numTh = numTh;
m_lastStable = -1;
m_methodName = "HysteresisLogInterval";
}
HysteresisLogInterval::HysteresisLogInterval(LightChart* pChart, int numTh)
{
m_pOutChart = pChart;
m_numTh = numTh;
m_lastStable = -1;
m_methodName = "HysteresisLogInterval";
}
int HysteresisLogInterval::stableLux(int lux)
{
m_luxQue.enqueue(lux);
if(m_luxQue.size() >= m_numTh)
{
int meanVal = mean(m_luxQue);
int stableLux = stablize(m_luxQue);
if(lastMean == -1) lastMean = stableLux;
else
{
qDebug()<<"last: "<<lastMean<<"---"<<"stableLux: "<<stableLux<<"---"<<"delta: "<<stableLux-lastMean;
}
// qDebug()<<"stable1: "<<stableLux;
if(m_lastStable == -1)
{
m_lastStable = stableLux;
return m_lastStable;
}
else
{
double log_last = log(m_lastStable+1);
double last_max = std::max(0.0, log_last*1.1);
double last_min = std::max(log(10), log_last-log_last*0.1);
int res = filt(m_lastStable, stableLux);
QString str;
if(m_pOutChart)
{
str = QString("min:%1--max:%2--").arg(last_min,0,'g',4).arg(last_max,0,'g',4); // --偏度:%4 .arg(sk,0,'g',3)
}
if(log(res) <= last_max && log(res) >= last_min)
{
res = m_lastStable;
str += "IN";
}
else
str += "OUT";
m_pOutChart->appendString(str);
// qDebug()<<"stable2: "<<res;
m_lastStable = res;
return res;
}
}
else
return -1;
}
int HysteresisLogInterval::stablize(QQueue<int>& que)
{
int mean = 0;
int count = 0;
while(!que.empty())
{
int lux = que.head();
mean += lux;
count++;
que.dequeue();
}
mean /= count;
return mean;
}
int HysteresisLogInterval::filt(int stableLux, int newLux)
{
return stableLux * 0.3 + newLux * 0.7;
}
| true |
6e0b1ac40e6e806e2ae0c90a54614212789c955c
|
C++
|
valery-kirichenko/spbu
|
/Bushev/C++/3_if_else_for_while_etc/exception.cpp
|
UTF-8
| 287 | 3.15625 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
int main(){
int i, j;
cin >> i >> j;
try{
if(j == 0) throw "Error, you can't devide by 0";
}catch(char c[]){
cout << c << endl;
system("pause");
return 0;
}
cout << "Devision: " << i / j << endl;
system("pause");
return 0;
}
| true |
1db8c6227291a94a7c53e77e4f89d5e49d40b5ef
|
C++
|
Abdul-Haddi/1st-2019005
|
/2019005 LAB 11 T2.cpp
|
UTF-8
| 335 | 3.453125 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
#include<math.h>
int pow(int x, int y)
{
if (y > 1)
{
return x * pow(x, y - 1);
}
else
{
return x;
}
}
int main()
{
int base, exp;
cout << "Enter base: \n";
cin >> base;
cout << "Enter exponent: \n";
cin >> exp;
cout <<base<< "^"<<exp<<" = "<<pow(base,exp);
return 0;
}
| true |
0783f5d271d82b690b8cb154ce02321c64451f1d
|
C++
|
sebastienPatte/Archives
|
/Info121/TP4/ex4.cpp
|
UTF-8
| 606 | 3.65625 | 4 |
[] |
no_license
|
#include <iostream>
using namespace std;
/** calcule la suite de syracuse en partant d'un terme de départ '&n'
* @param '&n' un entier
**/
void syracuse(int &n){
if(n<=0)cout<<"erreur, le terme de départ est inférieur à zéro"<<endl;
if(n%2==0){
n = n/2;
}else{
n = (n*3)+1;
}
}
/** Calcule le nombre de termes entre le terme de départ et 1 par la suite de syracuse
* @param 'un' un entier
* @return un entier
**/
int longueurTransient (int un){
int i=0;
while (un != 1) { syracuse(un); i++; }
return i;
}
int main(){
for(int i=1; i<=1000;i++)cout<<longueurTransient(i)<<endl;
}
| true |
c76ed7630100dab22f4771f42bb9f2af06a897b9
|
C++
|
WillardGithub/Beauty
|
/Android_SourceCode/BeautyAlgorithm.cpp
|
GB18030
| 47,975 | 2.625 | 3 |
[] |
no_license
|
#include "BeautyAlgorithm.h"
using namespace cv;
#define PI 3.1415926
#define DETECT_BUFFER_SIZE 0x20000
#define max_uchar(a, b) (((a) > (b)) ? (a) : (b))
#define min_uchar(a, b) (((a) < (b)) ? (a) : (b))
#define MIN2(a, b) ((a) < (b) ? (a) : (b))
#define MAX2(a, b) ((a) > (b) ? (a) : (b))
#define CLIP3(x, a, b) MIN2(MAX2(a,x), b)
#define LOG_PRINT
#ifdef LOG_PRINT
#define PRINTLOG(x,y,w,h)\
LOGD("x:%d,y:%d,w:%d,h:%d\n",x,y,w,h)
#else
#define PRINTLOG(x,y,w,h)
#endif
void CompMeanAndVariance(Mat& img, Vec3f& mean3f, Vec3f& variance3f)
{
int row = img.rows;
int col = img.cols;
int total = row * col;
float sum[3] = { 0.0f };
// ֵ
uchar* pImg = img.data;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
sum[0] += pImg[3 * j + 0];
sum[1] += pImg[3 * j + 1];
sum[2] += pImg[3 * j + 2];
}
pImg += img.step;
}
mean3f[0] = sum[0] / total;
mean3f[1] = sum[1] / total;
mean3f[2] = sum[2] / total;
memset(sum, 0, sizeof(sum));
//
pImg = img.data;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
sum[0] += (pImg[3 * j + 0] - mean3f[0]) * (pImg[3 * j + 0] - mean3f[0]);
sum[1] += (pImg[3 * j + 1] - mean3f[1]) * (pImg[3 * j + 1] - mean3f[1]);
sum[2] += (pImg[3 * j + 2] - mean3f[2]) * (pImg[3 * j + 2] - mean3f[2]);
}
pImg += img.step;
}
variance3f[0] = sqrt(sum[0] / total);
variance3f[1] = sqrt(sum[1] / total);
variance3f[2] = sqrt(sum[2] / total);
}
Mat BilinearInterpolation(Mat& img, int startX, int startY, int endX, int endY, float radius) //ƽƼ죨ֵ㷨
{
if (radius> startX)
{
radius = startX - 1;
}
if (radius > img.cols - startX)
{
radius = img.cols - startX - 1;
}
if (radius > startY)
{
radius = startY - 1;
}
if (radius > img.rows - startY)
{
radius = img.rows - startY -1;
}
double ddradius = float(radius * radius);
Mat copyImg;
copyMakeBorder(img, copyImg, 0, 0, 0, 0, BORDER_REPLICATE);
double ddmc = (endX - startX) * (endX - startX) + (endY - startY) * (endY - startY);
int H = img.rows;
int W = img.cols;
int C = 3;
for (int i = 0; i < W; i++)
{
for (int j = 0; j < H; j++)
{
if (fabs(i - startX) > radius || fabs(j - startY) > radius)
{
continue;
}
double distance = (i - startX) * (i - startX) + (j - startY) * (j - startY);
if (distance < ddradius)
{
double ratio = (ddradius - distance) / (ddradius - distance + ddmc);
ratio = ratio * ratio;
double UX = i - ratio * (endX - startX);
double UY = j - ratio * (endY - startY);
int x1 = UX;
int x2 = x1 + 1;
int y1 = UY;
int y2 = y1 + 1;
float a0 = float(img.ptr<Vec3b>(y1)[x1][0]) * (float(x2) - UX) * (float(y2) - UY);
float a1 = float(img.ptr<Vec3b>(y1)[x1][1]) * (float(x2) - UX) * (float(y2) - UY);
float a2 = float(img.ptr<Vec3b>(y1)[x1][2]) * (float(x2) - UX) * (float(y2) - UY);
float b0 = float(img.ptr<Vec3b>(y1)[x2][0]) * (UX - float(x1)) * (float(y2) - UY);
float b1 = float(img.ptr<Vec3b>(y1)[x2][1]) * (UX - float(x1)) * (float(y2) - UY);
float b2 = float(img.ptr<Vec3b>(y1)[x2][2]) * (UX - float(x1)) * (float(y2) - UY);
float c0 = float(img.ptr<Vec3b>(y2)[x1][0]) * (float(x2) - UX) * (UY - float(y1));
float c1 = float(img.ptr<Vec3b>(y2)[x1][1]) * (float(x2) - UX) * (UY - float(y1));
float c2 = float(img.ptr<Vec3b>(y2)[x1][2]) * (float(x2) - UX) * (UY - float(y1));
float d0 = float(img.ptr<Vec3b>(y2)[x2][0]) * (UX - float(x1)) * (UY - float(y1));
float d1 = float(img.ptr<Vec3b>(y2)[x2][1]) * (UX - float(x1)) * (UY - float(y1));
float d2 = float(img.ptr<Vec3b>(y2)[x2][2]) * (UX - float(x1)) * (UY - float(y1));
copyImg.ptr<Vec3b>(j)[i][0] = int(a0 + b0 + c0 + d0);
copyImg.ptr<Vec3b>(j)[i][1] = int(a1 + b1 + c1 + d1);
copyImg.ptr<Vec3b>(j)[i][2] = int(a2 + b2 + c2 + d2);
}
}
}
return copyImg;
}
Mat BilinearInterpolation1(Mat& img, int startX, int startY, float moudxnorm, float radius) //
{
if (radius> startX)
{
radius = startX - 1;
}
if (radius > img.cols - startX)
{
radius = img.cols - startX - 1;
}
if (radius > startY)
{
radius = startY - 1;
}
if (radius > img.rows - startY)
{
radius = img.rows - startY -1;
}
double ddradius = float(radius * radius);
Mat copyImg;
img.copyTo(copyImg);
//copyMakeBorder(img, copyImg, 0, 1, 0, 1, BORDER_REPLICATE);
int H = img.rows;
int W = img.cols;
int C = 3;
for (int i = 0; i < W; i++)
{
for (int j = 0; j < H; j++)
{
if (fabs(i - startX) > radius || fabs(j - startY) > radius)
{
continue;
}
double distance = (i - startX) * (i - startX) + (j - startY) * (j - startY);
if (distance < ddradius)
{
double rnorm = sqrt(distance) / radius;
double a = 1 - (rnorm - 1) * (rnorm - 1) * moudxnorm;
double UX = startX + a * (i - startX);
double UY = startY + a * (j - startY);
//˫Բֵڵ㷨//
int x1 = UX;
int x2 = x1 + 1;
int y1 = UY;
int y2 = y1 + 1;
float a0 = float(img.ptr<Vec3b>(y1)[x1][0]) * (float(x2) - UX) * (float(y2) - UY);
float a1 = float(img.ptr<Vec3b>(y1)[x1][1]) * (float(x2) - UX) * (float(y2) - UY);
float a2 = float(img.ptr<Vec3b>(y1)[x1][2]) * (float(x2) - UX) * (float(y2) - UY);
float b0 = float(img.ptr<Vec3b>(y1)[x2][0]) * (UX - float(x1)) * (float(y2) - UY);
float b1 = float(img.ptr<Vec3b>(y1)[x2][1]) * (UX - float(x1)) * (float(y2) - UY);
float b2 = float(img.ptr<Vec3b>(y1)[x2][2]) * (UX - float(x1)) * (float(y2) - UY);
float c0 = float(img.ptr<Vec3b>(y2)[x1][0]) * (float(x2) - UX) * (UY - float(y1));
float c1 = float(img.ptr<Vec3b>(y2)[x1][1]) * (float(x2) - UX) * (UY - float(y1));
float c2 = float(img.ptr<Vec3b>(y2)[x1][2]) * (float(x2) - UX) * (UY - float(y1));
float d0 = float(img.ptr<Vec3b>(y2)[x2][0]) * (UX - float(x1)) * (UY - float(y1));
float d1 = float(img.ptr<Vec3b>(y2)[x2][1]) * (UX - float(x1)) * (UY - float(y1));
float d2 = float(img.ptr<Vec3b>(y2)[x2][2]) * (UX - float(x1)) * (UY - float(y1));
copyImg.ptr<Vec3b>(j)[i][0] = int(a0 + b0 + c0 + d0);
copyImg.ptr<Vec3b>(j)[i][1] = int(a1 + b1 + c1 + d1);
copyImg.ptr<Vec3b>(j)[i][2] = int(a2 + b2 + c2 + d2);
}
}
}
return copyImg;
}
Mat BilinearInterpolation2(Mat& img, int startX, int startY, float strength, float radius) //ֲ
{
if (radius> startX)
{
radius = startX - 1;
}
if (radius > img.cols - startX)
{
radius = img.cols - startX - 1;
}
if (radius > startY)
{
radius = startY - 1;
}
if (radius > img.rows - startY)
{
radius = img.rows - startY -1;
}
double ddradius = float(radius * radius);
Mat copyImg;
copyMakeBorder(img, copyImg, 0, 0, 0,0, BORDER_REPLICATE);
int H = img.rows;
int W = img.cols;
int C = 3;
for (int i = 0; i < W; i++)
{
for (int j = 0; j < H; j++)
{
if (fabs(i - startX) > radius && fabs(j - startY) > radius)
{
continue;
}
double distance = (i - startX) * (i - startX) + (j - startY) * (j - startY);
if (distance < ddradius)
{
double rnorm = sqrt(distance) / radius;
int a = (1.0 - rnorm) * strength;
int B = float(img.ptr<Vec3b>(j)[i][0]) + a;
int G = float(img.ptr<Vec3b>(j)[i][1]) + a;
int R = float(img.ptr<Vec3b>(j)[i][2]) + a;
//ֹԽ
copyImg.ptr<Vec3b>(j)[i][0] = min(255, max(0, B));
copyImg.ptr<Vec3b>(j)[i][1] = min(255, max(0, G));
copyImg.ptr<Vec3b>(j)[i][2] = min(255, max(0, R));
}
}
}
return copyImg;
}
Mat white(Mat& img, int startX, int startY, int x, int y ,int w, int h,float strength, float radius) //ר
{
if (radius> startX)
{
radius = startX - 1;
}
if (radius > img.cols - startX)
{
radius = img.cols - startX - 1;
}
if (radius > startY)
{
radius = startY - 1;
}
if (radius > img.rows - startY)
{
radius = img.rows - startY -1;
}
double ddradius = float(radius * radius);
Mat copyImg;
copyMakeBorder(img, copyImg,0,0,0,0,BORDER_REPLICATE);
for (int i = x; i < x+w; i+=2)
{
for (int j = y; j < y+h; j+=2)
{
if (fabs(i - startX) >= radius && fabs(j - startY) >= radius)
{
continue;
}
double distance = (i - startX) * (i - startX) + (j - startY) * (j - startY);
if (distance < ddradius)
{
double rnorm = sqrt(distance) / radius;
int a = (1.0 - rnorm) * strength;
int B = float(img.ptr<Vec3b>(j)[i][0]) + a;
int G = float(img.ptr<Vec3b>(j)[i][1]) + a;
int R = float(img.ptr<Vec3b>(j)[i][2]) + a;
copyImg.ptr<Vec3b>(j)[i][0] = min(255, max(0, B));
copyImg.ptr<Vec3b>(j)[i][1] = min(255, max(0, G));
copyImg.ptr<Vec3b>(j)[i][2] = min(255, max(0, R));
B = float(img.ptr<Vec3b>(j)[i+1][0]) + a;
G = float(img.ptr<Vec3b>(j)[i+1][1]) + a;
R = float(img.ptr<Vec3b>(j)[i+1][2]) + a;
copyImg.ptr<Vec3b>(j)[i+1][0] = min(255, max(0, B));
copyImg.ptr<Vec3b>(j)[i+1][1] = min(255, max(0, G));
copyImg.ptr<Vec3b>(j)[i+1][2] = min(255, max(0, R));
B = float(img.ptr<Vec3b>(j+1)[i][0]) + a;
G = float(img.ptr<Vec3b>(j+1)[i][1]) + a;
R = float(img.ptr<Vec3b>(j+1)[i][2]) + a;
copyImg.ptr<Vec3b>(j+1)[i][0] = min(255, max(0, B));
copyImg.ptr<Vec3b>(j+1)[i][1] = min(255, max(0, G));
copyImg.ptr<Vec3b>(j+1)[i][2] = min(255, max(0, R));
B = float(img.ptr<Vec3b>(j+1)[i+1][0]) + a;
G = float(img.ptr<Vec3b>(j+1)[i+1][1]) + a;
R = float(img.ptr<Vec3b>(j+1)[i+1][2]) + a;
copyImg.ptr<Vec3b>(j+1)[i+1][0] = min(255, max(0, B));
copyImg.ptr<Vec3b>(j+1)[i+1][1] = min(255, max(0, G));
copyImg.ptr<Vec3b>(j+1)[i+1][2] = min(255, max(0, R));
}
}
}
return copyImg;
}
Mat guidedfilter(Mat& srcImage, Mat& srcClone, int r, double eps) //˲
{
// תԴͼϢ
srcImage.convertTo(srcImage, CV_64FC1);
srcClone.convertTo(srcClone, CV_64FC1);
int nRows = srcImage.rows;
int nCols = srcImage.cols;
r = 2 * r + 1;
Mat boxResult;
// һ: ֵ
//boxFilter(Mat::ones(nRows, nCols, srcImage.type()),boxResult, CV_64FC1, Size(r, r));
// ɵֵmean_I
Mat mean_I;
boxFilter(srcImage, mean_I, CV_64FC1, Size(r, r));
// ԭʼֵmean_p
Mat mean_p;
boxFilter(srcClone, mean_p, CV_64FC1, Size(r, r));
// ɻؾֵmean_Ip
Mat mean_Ip;
boxFilter(srcImage.mul(srcClone), mean_Ip,CV_64FC1, Size(r, r));
Mat cov_Ip = mean_Ip - mean_I.mul(mean_p);
// ؾֵmean_II
Mat mean_II;
boxFilter(srcImage.mul(srcImage), mean_II, CV_64FC1, Size(r, r));
// ϵ
Mat var_I = mean_II - mean_I.mul(mean_I);
// ϵab
Mat a = cov_Ip / (var_I + eps);
Mat b = mean_p - a.mul(mean_I);
// ģϵabֵ
Mat mean_a;
boxFilter(a, mean_a, CV_64FC1, Size(r, r));
//mean_a = mean_a / boxResult;
Mat mean_b;
boxFilter(b, mean_b, CV_64FC1, Size(r, r));
//mean_b = mean_b / boxResult;
//壺
Mat resultMat = mean_a.mul(srcImage) + mean_b;
return resultMat;
}
//
double SlimFace(Mat src, double ratio, Mat& dst, short* p)
{
LOGD("start to deal %s\n", __FUNCTION__);
if (src.empty() || !p) //жͼؼָǷΪ
{
LOGE("the mat src is null or p is null\n");
return -1;
}
double rate = ratio * 0.01;
float r_left1 = sqrt((p[4 + 2 * 1] - p[4 + 2 * 30]) * (p[4 + 2 * 1] - p[4 + 2 * 30]) + (p[4 + 2 * 1 + 1] - p[4 + 2 * 30 + 1]) * (p[4 + 2 * 1 + 1] - p[4 + 2 * 30 + 1]));
float r_right1 = sqrt((p[4 + 2 * 15] - p[4 + 2 * 30]) * (p[4 + 2 * 15] - p[4 + 2 * 30]) + (p[4 + 2 * 15 + 1] - p[4 + 2 * 30 + 1]) * (p[4 + 2 * 15 + 1] - p[4 + 2 * 30 + 1]));
Mat data = BilinearInterpolation(src, p[4 + 2 * 1], p[4 + 2 *1 + 1], p[4 + 2 * 30], p[4 + 2 * 30 + 1], rate * r_left1 * 0.35);
Mat data1 = BilinearInterpolation(data, p[4 + 2 * 15], p[4 + 2 * 15 + 1], p[4 + 2 * 30], p[4 + 2 * 30 + 1], rate * r_right1 * 0.35);
float r_left2 = sqrt((p[4 + 2 * 4] - p[4 + 2 * 51]) * (p[4 + 2 * 4] - p[4 + 2 * 51]) + (p[4 + 2 * 4 + 1] - p[4 + 2 * 51 + 1]) * (p[4 + 2 * 4 + 1] - p[4 + 2 * 51 + 1]));
float r_right2 = sqrt((p[4 + 2 * 12] - p[4 + 2 * 51]) * (p[4 + 2 * 12] - p[4 + 2 * 51]) + (p[4 + 2 * 12 + 1] - p[4 + 2 * 51 + 1]) * (p[4 + 2 * 12 + 1] - p[4 + 2 * 51+ 1]));
Mat data2 = BilinearInterpolation(data1, p[4 + 2 * 4], p[4 + 2 * 4 + 1], p[4 + 2 * 51], p[4 + 2 * 51 + 1], rate * r_left1 * 0.35);
Mat data3 = BilinearInterpolation(data2, p[4 + 2 * 12], p[4 + 2 * 12 + 1], p[4 + 2 * 51], p[4 + 2 * 51 + 1], rate * r_right1 * 0.35);
//ͷ
//Mat data4 = BilinearInterpolation(data3, p[4 + 2 * 20], 2 * p[4 + 2 * 20 + 1] - p[4 + 2 * 29 + 1], p[4 + 2 * 20], p[4 + 2 * 20 + 1], p[4 + 2 * 29 + 1] - p[4 + 2 * 20 + 1]);
//Mat data5 = BilinearInterpolation(data4, p[4 + 2 * 25], 2 * p[4 + 2 * 20 + 1] - p[4 + 2 * 29 + 1], p[4 + 2 * 20], p[4 + 2 * 20 + 1], p[4 + 2 * 29 + 1] - p[4 + 2 * 20 + 1]);
//Mat data6 = BilinearInterpolation(data5, p[4 + 2 * 29], 2 * p[4 + 2 * 20 + 1] - p[4 + 2 * 29 + 1], p[4 + 2 * 20], p[4 + 2 * 20 + 1], p[4 + 2 * 29 + 1] - p[4 + 2 * 20 + 1]);
//float radius_left_eye = sqrt((p[4 + 2 * 19] - p[4 + 2 * 37]) * (p[4 + 2 * 19] - p[4 + 2 * 37]) + (p[4 + 2 * 19 + 1] - p[4 + 2 * 37 + 1]) * (p[4 + 2 *19 + 1] - p[4 + 2 * 37 + 1]));
//float radius_right_eye = sqrt((p[4 + 2 * 24] - p[4 + 2 * 44]) * (p[4 + 2 * 24] - p[4 + 2 * 44]) + (p[4 + 2 * 24 + 1] - p[4 + 2 * 44 + 1]) * (p[4 + 2 * 24 + 1] - p[4 + 2 * 44 + 1]));
//Mat data4 = BilinearInterpolation(data3, p[4 + 2 * 19], (int)(p[4 + 2 * 19 + 1]*0.75), p[4 + 2 * 19], (int)(p[4 + 2 * 19 + 1] + radius_left_eye*1.1), rate * radius_left_eye*1.25);
//Mat data5 = BilinearInterpolation(data4, p[4 + 2 * 24], (int)(p[4 + 2 * 24 + 1]*0.75), p[4 + 2 * 24], (int)(p[4 + 2 * 24 + 1]+ radius_right_eye*1.1), rate * radius_right_eye*1.25);
//Mat data6 = BilinearInterpolation(data5, p[4 + 2 * 27], (int)((p[4 + 2 * 21 + 1] + p[4 + 2 * 22 + 1])*0.5*0.8), p[4 + 2 * 27], p[4 + 2 * 27 + 1] * 0.75, rate * (r_right1+r_right2) *0.5* 0.8);
//Mat data6 = BilinearInterpolation(data5, p[4 + 2 * 29], 2 * p[4 + 2 * 20 + 1] - p[4 + 2 * 29 + 1], p[4 + 2 * 20], p[4 + 2 * 20 + 1], rate * (r_right1+ r_left1) * 0.25);
data3.copyTo(dst);
PRINTLOG(p[0],p[1],p[2],p[3]);
LOGD("leave to deal %s\n", __FUNCTION__);
return 0;
}
//
double ZoomEyes(Mat src, double ratio, Mat& dst,short* p)
{
if (src.empty() || !p) //жͼؼָǷΪ
{
return -1;
}
double rate = ratio * 0.01;
int left_landmark = 37; //߽
int left_landmark_down = 40; //ұ߽
int right_landmark = 43; //߽
int right_landmark_down = 46; //ұ߽
float r_left = sqrt((p[4 + 2 * left_landmark] - p[4 + 2 * left_landmark_down]) * (p[4 + 2 * left_landmark] - p[4 + 2 * left_landmark_down]) + (p[4 + 2 * left_landmark + 1] - p[4 + 2 * left_landmark_down + 1]) * (p[4 + 2 * left_landmark + 1] - p[4 + 2 * left_landmark_down + 1]));
float r_right = sqrt((p[4 + 2 * right_landmark] - p[4 + 2 * right_landmark_down]) * (p[4 + 2 * right_landmark] - p[4 + 2 * right_landmark_down]) + (p[4 + 2 * right_landmark + 1] - p[4 + 2 * right_landmark_down + 1]) * (p[4 + 2 * right_landmark + 1] - p[4 + 2 * right_landmark_down + 1]));
Mat data = BilinearInterpolation1(src, (p[4 + 2 * left_landmark] + p[4 + 2 * left_landmark_down])/2, (p[4 + 2 * left_landmark+1] + p[4 + 2 * left_landmark_down+1]) / 2, 0.8*rate, r_left );
Mat data1 = BilinearInterpolation1(data, (p[4 + 2 * right_landmark] + p[4 + 2 * right_landmark_down]) / 2, (p[4 + 2 * right_landmark + 1] + p[4 + 2 * right_landmark_down + 1]) / 2, 0.8*rate, r_right);
data1.copyTo(dst);
return 0;
}
//ݱ
double SlimNose(Mat src, double ratio, Mat& dst, short* p)
{
if (src.empty() || !p) //жͼؼָǷΪ
{
return -1;
}
double rate = ratio * 0.01;
int left_landmark = 31;
int left_landmark_down = 30;
int right_landmark = 35;
int right_landmark_down = 30;
int endPt = 30;
float r_left = sqrt((p[4 + 2 * left_landmark] - p[4 + 2 * left_landmark_down]) * (p[4 + 2 * left_landmark] - p[4 + 2 * left_landmark_down]) + (p[4 + 2 * left_landmark + 1] - p[4 + 2 * left_landmark_down + 1]) * (p[4 + 2 * left_landmark + 1] - p[4 + 2 * left_landmark_down + 1]));
float r_right = sqrt((p[4 + 2 * right_landmark] - p[4 + 2 * right_landmark_down]) * (p[4 + 2 * right_landmark] - p[4 + 2 * right_landmark_down]) + (p[4 + 2 * right_landmark + 1] - p[4 + 2 * right_landmark_down + 1]) * (p[4 + 2 * right_landmark + 1] - p[4 + 2 * right_landmark_down + 1]));
Mat data = BilinearInterpolation(src, p[4 + 2 * left_landmark], p[4 + 2 * left_landmark + 1], p[4 + 2 * endPt], p[4 + 2 * endPt + 1], rate * r_left*0.75);
Mat data1 = BilinearInterpolation(data, p[4 + 2 * right_landmark], p[4 + 2 * right_landmark + 1], p[4 + 2 * endPt], p[4 + 2 * endPt + 1], rate * r_right*0.75);
data1.copyTo(dst);
return 0;
}
//Ч
//double __stdcall AwlFace(Mat src, double ratio, Mat& dst, short* p)
//{
// if (src.empty() || !p) //жͼؼָǷΪ
// {
// return -1;
// }
// double rate = ratio * 0.01;
// /*unsigned char* pBuffer = (unsigned char*)malloc(DETECT_BUFFER_SIZE);
// Mat gray;
// cvtColor(src, gray, COLOR_BGR2GRAY);
// auto pResults = facedetect_multiview_reinforce(pBuffer, (unsigned char*)(gray.ptr(0)), gray.cols, gray.rows, (int)gray.step, 1.2f, 2, 48, 0, 1);
// short* p = (short*)(pResults + 1);*/
//
// //SlimFace(src, ratio, dst);
//
// //float r_left1 = sqrt((p[4 + 2 * 3] - p[4 + 2 * 5]) * (p[4 + 2 * 3] - p[4 + 2 * 5]) + (p[4 + 2 * 3 + 1] - p[4 + 2 * 5 + 1]) * (p[4 + 2 * 3 + 1] - p[4 + 2 * 5 + 1]));
// //float r_right1 = sqrt((p[4 + 2 * 13] - p[4 + 2 * 15]) * (p[4 + 2 * 13] - p[4 + 2 * 15]) + (p[4 + 2 * 13 + 1] - p[4 + 2 * 15 + 1]) * (p[4 + 2 * 13 + 1] - p[4 + 2 * 15 + 1]));
// //Mat data_slim1 = BilinearInterpolation(src, p[4 + 2 * 3], p[4 + 2 * 3 + 1], p[4 + 2 * 30], p[4 + 2 * 30 + 1], rate*r_left1*0.9);
// //Mat data1_slim2 = BilinearInterpolation(data_slim1, p[4 + 2 * 13], p[4 + 2 * 13 + 1], p[4 + 2 * 30], p[4 + 2 * 30 + 1], rate*r_right1*0.9);
//
// int left_landmark = 6;
// int left_landmark_down = 8;
// int right_landmark = 10;
// int right_landmark_down = 8;
//
// float r_left = sqrt((p[4 + 2 * left_landmark] - p[4 + 2 * left_landmark_down]) * (p[4 + 2 * left_landmark] - p[4 + 2 * left_landmark_down]) + (p[4 + 2 * left_landmark + 1] - p[4 + 2 * left_landmark_down + 1]) * (p[4 + 2 * left_landmark + 1] - p[4 + 2 * left_landmark_down + 1]));
// float r_right = sqrt((p[4 + 2 * right_landmark] - p[4 + 2 * right_landmark_down]) * (p[4 + 2 * right_landmark] - p[4 + 2 * right_landmark_down]) + (p[4 + 2 * right_landmark + 1] - p[4 + 2 * right_landmark_down + 1]) * (p[4 + 2 * right_landmark + 1] - p[4 + 2 * right_landmark_down + 1]));
//
// Mat data1 = BilinearInterpolation(dst, p[4 + 2 * right_landmark_down], p[4 + 2 * right_landmark_down + 1], p[4 + 2 * right_landmark_down], p[4 + 2 * right_landmark_down + 1] + 10, rate * (r_right+ r_left)*0.35);
// Mat data2 = BilinearInterpolation(data1, p[4 + 2 * left_landmark], p[4 + 2 * left_landmark + 1], p[4 + 2 * right_landmark_down], p[4 + 2 * right_landmark_down + 1] + 10, rate * (r_right + r_left) * 0.35);
// Mat data3 = BilinearInterpolation(data2, p[4 + 2 * right_landmark], p[4 + 2 * right_landmark + 1], p[4 + 2 * right_landmark_down], p[4 + 2 * right_landmark_down + 1] + 10, rate * (r_right + r_left)* 0.35);
//
// Mat data4 = BilinearInterpolation(data3, p[4 + 2 * (left_landmark-1)], p[4 + 2 * (left_landmark-1) + 1], p[4 + 2 * right_landmark_down], p[4 + 2 * right_landmark_down + 1] + 10, rate * (r_right + r_left) * 0.35);
// Mat data5 = BilinearInterpolation(data4, p[4 + 2 * (right_landmark+1)], p[4 + 2 * (right_landmark+1) + 1], p[4 + 2 * right_landmark_down], p[4 + 2 * right_landmark_down + 1] + 10, rate * (r_right + r_left) * 0.35);
//
// Mat data6 = BilinearInterpolation(data5, p[4 + 2 * (left_landmark - 2)], p[4 + 2 * (left_landmark - 2) + 1], p[4 + 2 * right_landmark_down], p[4 + 2 * right_landmark_down + 1] + 10, rate * (r_right + r_left) * 0.35);
// Mat data7 = BilinearInterpolation(data6, p[4 + 2 * (right_landmark + 2)], p[4 + 2 * (right_landmark + 2) + 1], p[4 + 2 * right_landmark_down], p[4 + 2 * right_landmark_down + 1] + 10, rate * (r_right + r_left) * 0.35);
//
// data7.copyTo(dst);
//
// free(pBuffer);
// pBuffer = NULL;
//
// return 0;
//}
//added at 2020-5-10
double GlobalBuffing(Mat src, double ratio, Mat& dst) //ĥƤ
{
if (src.empty())
{
return -1;
}
double rate = ratio * 0.01;
//Mat srcGray(src.size(), CV_8UC1);
//cvtColor(src, srcGray, COLOR_BGR2GRAY);
// ͨ
vector<Mat> vSrcImage, vResultImage;
split(src, vSrcImage);
Mat resultMat;
for (int i = 0; i < 3; i++)
{
// ͨתɸ
Mat tempImage;
vSrcImage[i].convertTo(tempImage, CV_64FC1, 1.0 / 255.0);
Mat p = tempImage.clone();
// ֱе˲
Mat resultImage = guidedfilter(tempImage, p, 4, 0.01);
vResultImage.push_back(resultImage);
}
// ͨϲ
merge(vResultImage, resultMat);
//
//Mat img3;
//resultMat.copyTo(img3);
//cv::imwrite("filter.jpg", img3 * 255);
//Mat img11 = imread("filter.jpg", 1);
Mat img11;
resultMat.copyTo(img11);
img11 = img11 * 255;
img11.convertTo(img11, CV_8UC3);
//add by hyg
//IplImage* img1 = &IplImage(img11);
IplImage hygTemp1 = (IplImage)img11;
IplImage* img1 = &hygTemp1;
////////
Mat temp1;
src.copyTo(temp1);
//add by hyg
IplImage hygTemp2 = (IplImage)temp1;
IplImage* img2 = &hygTemp2;
//IplImage* img2 = &IplImage(temp1);
//////
//CvRect roi1 = cvRect(0, 0, src.cols, src.rows);
//////ݸͼROI(Region of Interesting)
//cvSetImageROI(img1, roi);
//cvSetImageROI(img2, roi1);
//////һͼеROIڶͼĸȤ
cvCopy(img1, img2);
//ȡimgimg1ϵĸȤ
//cvResetImageROI(img1);
//cvResetImageROI(img2);
temp1.copyTo(dst);
return 0;
}
double LocalBuffing(Mat src, double ratio, Mat& dst, short* p)//ֲ(λ)ĥƤ
{
if (src.empty() || !p) //жͼؼָǷΪ
{
return -1;
}
double rate = ratio * 0.01+0.001;
;
int x = p[0];
int y = p[1];
int w = p[2];
int h = p[3];
int expandRows = 0;
//ο
if (y > h)
{
expandRows = h / 2;
}
else
{
expandRows = y*2 / 3;
}
y = y - expandRows;
h = h + 2 * expandRows;
if (y + h > src.rows - 1)
{
h = src.rows - 1 - y;
}
Mat faceImage = src(Rect(x, y, w, h)); //ȡο
if (faceImage.empty())
{
return -1;
}
// ͨ
vector<Mat> vSrcImage, vResultImage;
split(faceImage, vSrcImage);
Mat resultMat;
for (int i = 0; i < 3; i++)
{
// ͨתɸ
Mat tempImage;
vSrcImage[i].convertTo(tempImage, CV_64FC1, 1.0 / 255.0);
Mat p = tempImage.clone();
// ֱе˲
Mat resultImage = guidedfilter(tempImage, p, 4, 0.001*rate);
vResultImage.push_back(resultImage);
}
// ͨϲ
merge(vResultImage, resultMat);
Mat img11;
resultMat.copyTo(img11);
img11 = img11 * 255;
img11.convertTo(img11, CV_8UC3);
Mat temp1;
src.copyTo(temp1);
img11.copyTo(temp1(Rect(x, y, w, h)));
temp1.copyTo(dst);;
return 0;
}
double GlobalWhitening(Mat src, double ratio, Mat& dst, short* p)//ȫ
{
if (src.empty() || !p) //жͼؼָǷΪ
{
return -1;
}
double rate = 2.6 - 0.002 * ratio; //ϵϵԽСЧԽ(1-10)
Mat dstImage;
vector<Mat> Channels;
split(src, Channels);
Mat B = Channels[0];
Mat G = Channels[1];
Mat R = Channels[2];
double Baver = mean(B)[0];
double Gaver = mean(G)[0];
double Raver = mean(R)[0];
double K = (Baver + Gaver + Raver) / rate; //ϵ
double Kb = K / Baver;
double Kg = K / Gaver;
double Kr = K / Raver;
//ƽͨ
Mat dstB, dstG, dstR;
dstB = B * Kb;
dstG = G * Kg;
dstR = R * Kr;
vector<Mat> dstChanges;
dstChanges.push_back(dstB);
dstChanges.push_back(dstG);
dstChanges.push_back(dstR);
merge(dstChanges, dstImage);//ϲͨ
dstImage.copyTo(dst);
return 0;
}
double Whitening(Mat src, double ratio, Mat& dst, short* p)//ֲ
{
/*#if 0
if (src.empty() || !p) //жͼؼָǷΪ
{
return -1;
}
double rate = 0.01 * ratio;
Mat temp1;
src.copyTo(temp1);
int x = p[0];
int y = p[1];
int w = p[2];
int h = p[3];
Mat faceImage = src(Range(y, y + h), Range(x, x + w)); //ȡο
float radius = sqrt(faceImage.rows * faceImage.rows / 4 + faceImage.cols * faceImage.cols / 4) ;
Mat data1 = BilinearInterpolation2(faceImage, faceImage.cols/2, faceImage.rows/2, rate * 15, radius);
data1.copyTo(temp1(Rect(x, y, w, h)));
memcpy(dst.data, temp1.data, sizeof(unsigned char) * temp1.rows * temp1.cols * 3);
#endif*/
if (src.empty() || !p) //жͼؼָǷΪ
{
return -1;
}
Mat temp1;
src.copyTo(temp1);
//add at 2021-3-23
int x1 = p[4 + 2 * 1];
int y1 = p[4 + 2 * 1 + 1] - 1.2 * (p[4 + 2 * 9 + 1] - p[4 + 2 * 1 + 1]);
int w1 = p[4 + 2 * 16] - p[4 + 2 * 1];
int h1 = p[4 + 2 * 9 + 1] - (p[4 + 2 * 1 + 1] - 1.2 * (p[4 + 2 * 9 + 1] - p[4 + 2 * 1 + 1]));
LOGD("x1:%d,y1:%d,w1:%d,h1:d%\n",x1,y1,w1,h1);
Mat structKernel = getStructuringElement(MORPH_RECT, Size(3, 3));//С
Mat imageROI = src(Range(y1, y1 + h1), Range(x1, x1 + w1));
Mat ycrcb_image;
cvtColor(imageROI, ycrcb_image, CV_BGR2YCrCb); //תYCrCbռ
Mat detect;
vector<Mat> channels;
split(ycrcb_image, channels);
Mat output_mask = channels[1];
threshold(output_mask, output_mask, 0, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);
imageROI.copyTo(detect, output_mask);
Mat img0;
erode(detect, img0, structKernel, Point(0, 0), 2);//㣬
//added at 2021-03-21
vector<Point> faceContours;
Mat faceMask(src.rows,src.cols, CV_8UC3,Scalar(0,0,0));
CvPoint** point1 = new CvPoint * [1];
point1[0] = new CvPoint[19];
for (size_t j = 0; j < 17; j++)
{
Point edgeP;
edgeP.x = p[4 + 2 * j];
edgeP.y = p[4 + 2 * j + 1];
point1[0][j] = edgeP;
}
Point edgeP;
edgeP.x = p[4 + 2 * 16]- w1/15;
edgeP.y = p[4 + 2 * 24+1]*0.85;
point1[0][17] = edgeP;
edgeP.x = p[4 + 2 * 0]+w1/15;
edgeP.y = p[4 + 2 * 19 + 1] * 0.85;
point1[0][18] = edgeP;
IplImage face1 = cvIplImage(faceMask);
int npts = { 19 };
cvFillPoly(&face1, point1, &npts, 1,Scalar(255, 255, 255));
faceContours.clear();
delete[] point1[0];
point1[0] = NULL;
point1 = NULL;
//Mat dstImage = cvarrToMat(&face1);
int linePos = 0; //üëڵ
int iFlag = 0;
for (int row = 0; row < faceMask.rows; row++)
{
for (int col = 0; col < faceMask.cols; col++)
{
if (faceMask.at<Vec3b>(row, col)[0] ==255 && faceMask.at<Vec3b>(row, col)[1] ==255 &&faceMask.at<Vec3b>(row, col)[2] == 255)
{
linePos = row;
iFlag = 1;
break;
}
}
if (iFlag == 1)
{
break;
}
}
for (int i = 0; i < linePos*0.95; i++)
{
if (i >= y1 && i < y1 + h1)
{
for (int j = 0; j < faceMask.cols; j++)
{
if (j >= x1 && j < x1 + w1)
{
if (img0.at<Vec3b>(i - y1, j - x1)[0] * img0.at<Vec3b>(i - y1, j - x1)[1] * img0.at<Vec3b>(i - y1, j - x1)[2] != 0)
{
faceMask.at<Vec3b>(i, j)[0] = 255;
faceMask.at<Vec3b>(i, j)[1] = 255;
faceMask.at<Vec3b>(i, j)[2] = 255;
}
}
}
}
}
double rate = 0.006 * ratio;
for (int row = 0; row < faceMask.rows; row++)
{
for (int col = 0; col < faceMask.cols; col++)
{
if (faceMask.at<Vec3b>(row, col)[0] == 0 && faceMask.at<Vec3b>(row, col)[1] == 0 && faceMask.at<Vec3b>(row, col)[2] == 0)
{
continue;
}
temp1.at<Vec3b>(row, col)[0] += (255 - temp1.at<Vec3b>(row, col)[0]) * rate * 0.045;
temp1.at<Vec3b>(row, col)[1] += (255 - temp1.at<Vec3b>(row, col)[1]) * rate * 0.045;
temp1.at<Vec3b>(row, col)[2] += (255 - temp1.at<Vec3b>(row, col)[2]) * rate * 0.045;
}
}
temp1.copyTo(dst);
LOGD("end copy ROI\n");
//imwrite("dst.jpg",dst);
LOGD("finish!");
return 0;
}
double AdjustLip(Mat src, double ratio, Mat& dst, short* p)
{
if (src.empty() || !p) //жͼؼָǷΪ
{
return -1;
}
double rate = ratio * 0.005;
Mat data = BilinearInterpolation(src, p[4 + 2 * 48], p[4 + 2 * 48 + 1], p[4 + 2 * 48] - 15, p[4 + 2 * 48 + 1], (p[4 + 2 * 59 + 1] - p[4 + 2 * 48 + 1]) * rate);
Mat data1 = BilinearInterpolation(data, p[4 + 2 * 54], p[4 + 2 * 54 + 1], p[4 + 2 * 54] + 15, p[4 + 2 * 54 + 1], (p[4 + 2 * 55 + 1] - p[4 + 2 * 54 + 1]) * rate);
data1.copyTo(dst);
return 0;
}
double AdjustForeHead(Mat src, double ratio, Mat& dst, short* p)
{
if (src.empty() || !p) //жͼؼָǷΪ
{
return -1;
}
double rate = ratio * 0.005;
//int a = rate*(p[4 + 2 * 37 + 1] - p[4 + 2 * 19 + 1])*0.8;
//int b = (p[4 + 2 * 37 + 1] - p[4 + 2 * 19 + 1])*0.6;
int a1 = rate * (p[4 + 2 * 37 + 1] - p[4 + 2 * 19 + 1]) * 0.6;
int b1 = (p[4 + 2 * 37 + 1] - p[4 + 2 * 19 + 1])*0.65;
int a2 = rate * (p[4 + 2 * 44 + 1] - p[4 + 2 * 24 + 1]) * 0.6;
int b2 = (p[4 + 2 * 44 + 1] - p[4 + 2 * 24 + 1])*0.65;
Mat data1 = BilinearInterpolation(src, p[4 + 2 * 18], p[4 + 2 * 19 + 1] - b1, p[4 + 2 * 18], p[4 + 2 * 19 + 1], a1);
Mat data2 = BilinearInterpolation(data1, p[4 + 2 * 19], p[4 + 2 * 19 + 1] - b1, p[4 + 2 * 19], p[4 + 2 * 19 + 1], a1);
Mat data3 = BilinearInterpolation(data2, p[4 + 2 * 20], p[4 + 2 * 19 + 1] - b1, p[4 + 2 * 20], p[4 + 2 * 19 + 1], a1);
Mat datat = BilinearInterpolation(data3, p[4 + 2 * 21], p[4 + 2 * 19 + 1] - b1, p[4 + 2 * 21], p[4 + 2 * 19 + 1], a1);
Mat data4 = BilinearInterpolation(datat, p[4 + 2 * 25], p[4 + 2 * 24 + 1] - b2, p[4 + 2 * 25], p[4 + 2 * 24 + 1],a2);
Mat data5 = BilinearInterpolation(data4, p[4 + 2 * 24], p[4 + 2 * 24 + 1] - b2, p[4 + 2 * 24], p[4 + 2 * 24 + 1], a2);
Mat data6 = BilinearInterpolation(data5, p[4 + 2 * 23], p[4 + 2 * 24 + 1] - b2, p[4 + 2 * 23], p[4 + 2 * 24 + 1], a2);
Mat data7 = BilinearInterpolation(data6, p[4 + 2 * 22], p[4 + 2 * 24 + 1] - b2, p[4 + 2 * 22], p[4 + 2 * 24 + 1], a2);
//Mat data4 = BilinearInterpolation(data3, p[4 + 2 * 21], p[4 + 2 * 19 + 1] - b, p[4 + 2 * 21], p[4 + 2 * 19 + 1],a);
//Mat data5 = BilinearInterpolation(data4, p[4 + 2 * 22], p[4 + 2 * 19 + 1] - b, p[4 + 2 * 22], p[4 + 2 * 19 + 1], a);
//Mat data6 = BilinearInterpolation(data5, p[4 + 2 * 28], p[4 + 2 * 20 + 1] - b, p[4 + 2 * 28], p[4 + 2 * 28 + 1], a);
LOGD("adjust head finished only left side\n");
LOGD("a:%d,b:%d\n",a,b);
LOGD("p[44]=%d,p[45]=%d,p[50]=%d,p[51]=%d,p[46]=%d,p[47]=%d,p[48]=%d,p[49]=%d,p[60]=%d,p[61]=%d,p[81]=%d\n",p[44],p[45],p[50],p[51],p[46],p[47],p[48],p[49],p[60],p[61],p[81]);
data7.copyTo(dst);
return 0;
}
double ColourCorrect(Mat src, double ratio, Mat& dst, short* p)
{
if (src.empty() || !p) //жͼؼָǷΪ
{
return -1;
}
Mat srcLab;
cvtColor(src, srcLab, COLOR_BGR2Lab); //ɫռת
//added at 2021-03-21 //λ
int x1 = p[4 + 2 * 1];
int y1 = p[4 + 2 * 1 + 1] - 1.2 * (p[4 + 2 * 9 + 1] - p[4 + 2 * 1 + 1]);
int w1 = p[4 + 2 * 16] - p[4 + 2 * 1];
int h1 = p[4 + 2 * 9 + 1] - (p[4 + 2 * 1 + 1] - 1.2 * (p[4 + 2 * 9 + 1] - p[4 + 2 * 1 + 1]));
Mat structKernel = getStructuringElement(MORPH_RECT, Size(3, 3));//С
Mat imageROI = src(Range(y1, y1 + h1), Range(x1, x1 + w1));
Mat ycrcb_image;
cvtColor(imageROI, ycrcb_image, CV_BGR2YCrCb); //תYCrCbռ
Mat detect;
vector<Mat> channels;
split(ycrcb_image, channels);
Mat output_mask = channels[1];
threshold(output_mask, output_mask, 0, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);
imageROI.copyTo(detect, output_mask);
Mat img0;
erode(detect, img0, structKernel, Point(0, 0), 2);//㣬
vector<Point> faceContours;
Mat faceMask(src.rows, src.cols, CV_8UC3, Scalar(0, 0, 0));
CvPoint** point1 = new CvPoint * [1];
point1[0] = new CvPoint[19];
for (size_t j = 0; j < 17; j++)
{
Point edgeP;
edgeP.x = p[4 + 2 * j];
edgeP.y = p[4 + 2 * j + 1];
point1[0][j] = edgeP;
}
int temp_dist = p[4 + 2 * 8 + 1] - p[4 + 2 * 27 + 1];
Point edgeP;
edgeP.x = p[4 + 2 * 16]-w1/10;
edgeP.y = p[4 + 2 * 24 + 1] -temp_dist/5;
point1[0][17] = edgeP;
edgeP.x = p[4 + 2 * 0]+w1/10;
edgeP.y = p[4 + 2 * 19 + 1] - temp_dist / 5;
point1[0][18] = edgeP;
IplImage face1 = cvIplImage(faceMask);
int npts = { 19 };
cvFillPoly(&face1, point1, &npts, 1, Scalar(255, 255, 255));
faceContours.clear();
delete[] point1[0];
point1[0] = NULL;
point1 = NULL;
Mat result;
bitwise_and(src, faceMask, result);
double rate = 0.2+ 0.005 * ratio;
Mat dstImage;
vector<Mat> Channels;
split(result, Channels);
Mat B = Channels[0];
Mat G = Channels[1];
Mat R = Channels[2];
double Baver = mean(B)[0];
double Gaver = mean(G)[0];
double Raver = mean(R)[0];
double K = (Baver + Gaver + Raver) / 3;
double Kb = K / Baver;
double Kg = K / Gaver;
double Kr = K / Raver;
/*R * 0.299 + G * 0.587 + B * 0.114*/
//ƽͨ
Mat dstB = B * Kb* rate;
Mat dstG = G * Kg* rate;
Mat dstR = R * Kr* rate;
vector<Mat> dstChanges;
dstChanges.push_back(dstB);
dstChanges.push_back(dstG);
dstChanges.push_back(dstR);
merge(dstChanges, dstImage); //ϲͨ
uchar* pImg = srcLab.data;
// ɫתֵ
for (int i = 0; i < srcLab.rows; i++)
{
for (int j = 0; j < srcLab.cols; j++)
{
if (faceMask.at<Vec3b>(i, j)[0] == 0 && faceMask.at<Vec3b>(i, j)[1] == 0 && faceMask.at<Vec3b>(i, j)[2] == 0)
{
continue;
}
pImg[3 * j + 0] = (uchar)min_uchar(255, max_uchar(0, pImg[3 * j + 0]+ rate * 2));
pImg[3 * j + 1] = (uchar)min_uchar(255, max_uchar(0, pImg[3 * j + 1] + rate * 5));
pImg[3 * j + 2] = (uchar)min_uchar(255, max_uchar(0, pImg[3 * j + 2]+ rate * 3));
}
pImg += srcLab.step;
}
Mat temp1;
cvtColor(srcLab, temp1, COLOR_Lab2BGR);
for (int row = 0; row < dstImage.rows; row++)
{
for (int col = 0; col < dstImage.cols; col++)
{
if (faceMask.at<Vec3b>(row, col)[0] == 0 && faceMask.at<Vec3b>(row, col)[1] == 0 && faceMask.at<Vec3b>(row, col)[2] == 0)
{
continue;
}
temp1.at<Vec3b>(row, col)[0] += (255 - temp1.at<Vec3b>(row, col)[0]) * rate * 0.025;
temp1.at<Vec3b>(row, col)[1] += (255 - temp1.at<Vec3b>(row, col)[1]) * rate * 0.025;
temp1.at<Vec3b>(row, col)[2] += (255 - temp1.at<Vec3b>(row, col)[2]) * rate * 0.025;
}
}
temp1.copyTo(dst);
return 0;
}
double Sharpen(Mat src, double ratio, Mat& dst, short* p)
{
if (src.empty() || !p) //жͼؼָǷΪ
{
return -1;
}
src.copyTo(dst);
Mat imgBlur, imgLow;
imgLow.create(src.size(), CV_8UC1);
int thre = 0; //ı 1.ֵ 2.Amount ֵı仯ͼʾЧںܴӰ
double radius = 0.5*ratio; //3. 뾶 뾶ı仯ӦԱȶȵı仯
double amount = 3;
GaussianBlur(src, imgBlur, Size(3, 3), radius, radius); //˹ͨ˲ ע뾶ıDZֵSIGMMA Size 3,3 ̫СĻЧ
imgLow = abs(src - imgBlur) < thre; //Ĥ ԭͼ-ͨ==ͨ˲ֵ ͷֵȽ СڵӦֵΪ1 Ϊ0
dst = src * (1 + amount) + imgBlur * (-amount); //ԭͼ+ֵͨ*amount
src.copyTo(dst, imgLow); //Сڷֵصֵ
return 0;
}
double EnhanceRed(Mat src, double ratio, Mat& dst, short* p)
{
if (src.empty() || !p) //жͼؼָǷΪ
{
return -1;
}
double rate = 0.25+ratio * 0.005;
cvtColor(src, src, COLOR_RGB2BGR); //ͨ⣬ȡעͼɽ
// BGRռתLabռ
Mat srcLab;
cvtColor(src, srcLab, COLOR_BGR2Lab);
//added at 2021-03-21 //λ
int x1 = p[4 + 2 * 1];
int y1 = p[4 + 2 * 1 + 1] - 1.2 * (p[4 + 2 * 9 + 1] - p[4 + 2 * 1 + 1]);
int w1 = p[4 + 2 * 16] - p[4 + 2 * 1];
int h1 = p[4 + 2 * 9 + 1] - (p[4 + 2 * 1 + 1] - 1.2 * (p[4 + 2 * 9 + 1] - p[4 + 2 * 1 + 1]));
Mat structKernel = getStructuringElement(MORPH_RECT, Size(3, 3));//С
Mat imageROI = src(Range(y1, y1 + h1), Range(x1, x1 + w1));
Mat ycrcb_image;
cvtColor(imageROI, ycrcb_image, CV_BGR2YCrCb); //תYCrCbռ
Mat detect;
vector<Mat> channels;
split(ycrcb_image, channels);
Mat output_mask = channels[1];
threshold(output_mask, output_mask, 0, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);
imageROI.copyTo(detect, output_mask);
Mat img0;
erode(detect, img0, structKernel, Point(0, 0), 2);//㣬
vector<Point> faceContours;
Mat faceMask(src.rows, src.cols, CV_8UC3, Scalar(0, 0, 0));
CvPoint** point1 = new CvPoint * [1];
point1[0] = new CvPoint[19];
for (size_t j = 0; j < 17; j++)
{
Point edgeP;
edgeP.x = p[4 + 2 * j];
edgeP.y = p[4 + 2 * j + 1];
point1[0][j] = edgeP;
}
Point edgeP;
edgeP.x = p[4 + 2 * 16] - w1 / 15;
edgeP.y = p[4 + 2 * 24 + 1] * 0.85;
point1[0][17] = edgeP;
edgeP.x = p[4 + 2 * 0] + w1 / 15;
edgeP.y = p[4 + 2 * 19 + 1] * 0.85;
point1[0][18] = edgeP;
IplImage face1 = cvIplImage(faceMask);
int npts = { 19 };
cvFillPoly(&face1, point1, &npts, 1, Scalar(255, 255, 255));
faceContours.clear();
delete[] point1[0];
point1[0] = NULL;
point1 = NULL;
//Mat dstImage = cvarrToMat(&face1);
int linePos = 0; //üëڵ
int iFlag = 0;
for (int row = 0; row < faceMask.rows; row++)
{
for (int col = 0; col < faceMask.cols; col++)
{
if (faceMask.at<Vec3b>(row, col)[0] == 255 && faceMask.at<Vec3b>(row, col)[1] == 255 && faceMask.at<Vec3b>(row, col)[2] == 255)
{
linePos = row;
iFlag = 1;
break;
}
}
if (iFlag == 1)
{
break;
}
}
for (int i = 0; i < linePos*0.95; i++)
{
if (i >= y1 && i < y1 + h1)
{
for (int j = 0; j < faceMask.cols; j++)
{
if (j >= x1 && j < x1 + w1)
{
if (img0.at<Vec3b>(i - y1, j - x1)[0] * img0.at<Vec3b>(i - y1, j - x1)[1] * img0.at<Vec3b>(i - y1, j - x1)[2] != 0)
{
faceMask.at<Vec3b>(i, j)[0] = 255;
faceMask.at<Vec3b>(i, j)[1] = 255;
faceMask.at<Vec3b>(i, j)[2] = 255;
}
}
}
}
}
uchar* pImg = srcLab.data;
// ɫתֵ
for (int i = 0; i < srcLab.rows; i++)
{
for (int j = 0; j < srcLab.cols; j++)
{
if (faceMask.at<Vec3b>(i, j)[0] == 0 && faceMask.at<Vec3b>(i, j)[1] == 0 && faceMask.at<Vec3b>(i, j)[2] == 0)
{
continue;
}
pImg[3 *j + 0] = (uchar)min_uchar(255, max_uchar(0, pImg[3 * j + 0]));
pImg[3 *j + 1] = (uchar)min_uchar(255, max_uchar(0, pImg[3 * j + 1]+ rate*5));
pImg[3 *j + 2] = (uchar)min_uchar(255, max_uchar(0, pImg[3 * j + 2]));
}
pImg += srcLab.step;
}
cvtColor(srcLab, dst, COLOR_Lab2BGR);
cvtColor(dst, dst, COLOR_BGR2RGB);
return 0;
}
double FrozenFilter(Mat src, Mat& dst, short* p) //˾
{
if (src.empty() || !p) //жͼؼָǷΪ
{
return -1;
}
src.copyTo(dst);
for (size_t i = 0; i < src.rows; i++)
{
for (size_t j = 0; j < src.cols; j++)
{
dst.at<cv::Vec3b>(i, j)[0] = cv::saturate_cast<uchar>(std::abs(src.at<cv::Vec3b>(i, j)[0] - src.at<cv::Vec3b>(i, j)[1] - src.at<cv::Vec3b>(i, j)[2]) * 3 >> 2);// blue
dst.at<cv::Vec3b>(i, j)[1] = cv::saturate_cast<uchar>(std::abs(src.at<cv::Vec3b>(i, j)[1] - src.at<cv::Vec3b>(i, j)[0] - src.at<cv::Vec3b>(i, j)[2]) * 3 >> 2);// green
dst.at<cv::Vec3b>(i, j)[2] = cv::saturate_cast<uchar>(std::abs(src.at<cv::Vec3b>(i, j)[2] - src.at<cv::Vec3b>(i, j)[0] - src.at<cv::Vec3b>(i, j)[1]) * 3 >> 2);// red
}
}
return 0;
}
int calmp(int value, int minValue = 0, int maxValue = 255)
{
if (value < minValue)
return minValue;
else if (value > maxValue)
return maxValue;
return value;
}
double AnaglyphFilter(Mat src, Mat& dst, short* p)
{
if (src.empty() || !p) //жͼؼָǷΪ
{
return -1;
}
src.copyTo(dst);
int rowNumber = dst.rows;
int colNumber = dst.cols;
for (int i = 1; i < rowNumber - 1; ++i)
{
for (int j = 1; j < colNumber - 1; ++j)
{
dst.at<Vec3b>(i, j)[0] = calmp(src.at<Vec3b>(i + 1, j + 1)[0] - src.at<Vec3b>(i - 1, j - 1)[0] + 128);
dst.at<Vec3b>(i, j)[1] = calmp(src.at<Vec3b>(i + 1, j + 1)[1] - src.at<Vec3b>(i - 1, j - 1)[1] + 128);
dst.at<Vec3b>(i, j)[2] = calmp(src.at<Vec3b>(i + 1, j + 1)[2] - src.at<Vec3b>(i - 1, j - 1)[2] + 128);
}
}
return 0;
}
double CastingFilter(Mat src, Mat& dst, short* p)
{
if (src.empty() || !p) //жͼؼָǷΪ
{
return -1;
}
src.copyTo(dst);
for (size_t i = 0; i < src.rows; i++)
{
for (size_t j = 0; j < src.cols; j++)
{
dst.at<cv::Vec3b>(i, j)[0] = cv::saturate_cast<uchar>(128 * src.at<cv::Vec3b>(i, j)[0] / (src.at<cv::Vec3b>(i, j)[1] + src.at<cv::Vec3b>(i, j)[2] + 1));// blue
dst.at<cv::Vec3b>(i, j)[1] = cv::saturate_cast<uchar>(128 * src.at<cv::Vec3b>(i, j)[1] / (src.at<cv::Vec3b>(i, j)[0] + src.at<cv::Vec3b>(i, j)[2] + 1));// green
dst.at<cv::Vec3b>(i, j)[2] = cv::saturate_cast<uchar>(128 * src.at<cv::Vec3b>(i, j)[2] / (src.at<cv::Vec3b>(i, j)[0] + src.at<cv::Vec3b>(i, j)[1] + 1));// red
}
}
return 0;
}
double FreehandFilter(Mat src, Mat& dst, short* p)
{
if (src.empty() || !p) //жͼؼָǷΪ
{
return -1;
}
src.copyTo(dst);
Mat Image_out(src.size(), CV_32FC3);
src.convertTo(Image_out, CV_32FC3);
Mat I(src.size(), CV_32FC1);
cv::cvtColor(Image_out, I, COLOR_BGR2GRAY);
I = I / 255.0;
Mat I_invert;
I_invert = -I + 1.0;
Mat I_gau;
GaussianBlur(I_invert, I_gau, Size(25, 25), 0, 0);
float delta = 0.01;
I_gau = -I_gau + 1.0 + delta;
Mat I_dst;
cv::divide(I, I_gau, I_dst);
I_dst = I_dst;
Mat b(src.size(), CV_32FC1);
Mat g(src.size(), CV_32FC1);
Mat r(src.size(), CV_32FC1);
Mat rgb[] = { b,g,r };
float alpha = 0.75;
r = alpha * I_dst + (1 - alpha) * 200.0 / 255.0;
g = alpha * I_dst + (1 - alpha) * 205.0 / 255.0;
b = alpha * I_dst + (1 - alpha) * 105.0 / 255.0;
cv::merge(rgb, 3, Image_out);
Image_out = Image_out * 255;
Image_out.convertTo(dst, CV_8UC3);
return 0;
}
double SketchFilter(Mat src, Mat& dst, short* p)
{
if (src.empty() || !p) //жͼؼָǷΪ
{
return -1;
}
src.copyTo(dst);
//1ȥɫ
cv::Mat gray(src.size(), CV_8UC3);
for (size_t i = 0; i < src.rows; i++)
{
for (size_t j = 0; j < src.cols; j++)
{
int max = std::max(std::max(src.at<cv::Vec3b>(i, j)[0], src.at<cv::Vec3b>(i, j)[1]),src.at<cv::Vec3b>(i, j)[2]);
int min = std::min(std::min(src.at<cv::Vec3b>(i, j)[0], src.at<cv::Vec3b>(i, j)[1]),src.at<cv::Vec3b>(i, j)[2]);
for (size_t k = 0; k < 3; k++)
{
gray.at<cv::Vec3b>(i, j)[k] = (max + min) / 2;
}
}
}
//2ȥɫͼ㣬ҷɫ
cv::Mat gray_revesal(src.size(), CV_8UC3);
for (size_t i = 0; i < gray.rows; i++)
{
for (size_t j = 0; j < gray.cols; j++)
{
for (size_t k = 0; k < 3; k++)
{
gray_revesal.at<cv::Vec3b>(i, j)[k] = 255 - gray.at<cv::Vec3b>(i, j)[k];
}
}
}
//3Էɫͼи˹ģ
cv::GaussianBlur(gray_revesal, gray_revesal, cv::Size(7, 7), 0);
//4ģͼģʽѡɫЧ
// ʽC =MIN( A +AB/255-B,255)CΪϽAΪȥɫص㣬BΪ˹ģص㡣
cv::Mat result(gray.size(), CV_8UC3);
for (size_t i = 0; i < gray.rows; i++)
{
for (size_t j = 0; j < gray.cols; j++)
{
for (size_t k = 0; k < 3; k++)
{
int a = gray.at<cv::Vec3b>(i, j)[k];
int b = gray_revesal.at<cv::Vec3b>(i, j)[k];
int c = std::min(a + (a * b) / (255 - b), 255);
result.at<cv::Vec3b>(i, j)[k] = c;
}
}
}
result.copyTo(dst);
return 0;
}
void GetTexTransMatrix(float x1, float y1, float x2, float y2, float x3, float y3, float tx1, float ty1, float tx2, float ty2, float tx3, float ty3, float* texMatrix)
{
float detA;
detA = tx1 * ty2 + tx2 * ty3 + tx3 * ty1 - tx3 * ty2 - tx1 * ty3 - tx2 * ty1;
float A11, A12, A13, A21, A22, A23, A31, A32, A33;
A11 = ty2 - ty3;
A21 = -(ty1 - ty3);
A31 = ty1 - ty2;
A12 = -(tx2 - tx3);
A22 = tx1 - tx3;
A32 = -(tx1 - tx2);
A13 = tx2 * ty3 - tx3 * ty2;
A23 = -(tx1 * ty3 - tx3 * ty1);
A33 = tx1 * ty2 - tx2 * ty1;
texMatrix[0] = (x1 * A11 + x2 * A21 + x3 * A31) / detA;
texMatrix[1] = (x1 * A12 + x2 * A22 + x3 * A32) / detA;
texMatrix[2] = (x1 * A13 + x2 * A23 + x3 * A33) / detA;
texMatrix[3] = (y1 * A11 + y2 * A21 + y3 * A31) / detA;
texMatrix[4] = (y1 * A12 + y2 * A22 + y3 * A32) / detA;
texMatrix[5] = (y1 * A13 + y2 * A23 + y3 * A33) / detA;
}
int Trent_Sticker(unsigned char* srcData, int width, int height, int stride, unsigned char* mask, int maskWidth, int maskHeight, int maskStride, int srcFacePoints[6], int maskFacePoints[6], int ratio)
{
int ret = 0;
float H[6] = { 0 };
GetTexTransMatrix(maskFacePoints[0], maskFacePoints[1], maskFacePoints[2], maskFacePoints[3], maskFacePoints[4], maskFacePoints[5], srcFacePoints[0], srcFacePoints[1], srcFacePoints[2], srcFacePoints[3], srcFacePoints[4], srcFacePoints[5], H);
for (int j = 0; j < height; j++)
{
for (int i = 0; i < width; i++)
{
float x = (float)i;
float y = (float)j;
float tx = 0;
float ty = 0;
tx = (int)((H[0] * (x)+H[1] * (y)+H[2]) + 0.5);
ty = (int)((H[3] * (x)+H[4] * (y)+H[5]) + 0.5);
tx = CLIP3(tx, 0, maskWidth - 1);
ty = CLIP3(ty, 0, maskHeight - 1);
int mb = mask[(int)tx * 4 + (int)ty * maskStride];
int mg = mask[(int)tx * 4 + (int)ty * maskStride + 1];
int mr = mask[(int)tx * 4 + (int)ty * maskStride + 2];
int alpha = mask[(int)tx * 4 + (int)ty * maskStride + 3];
int b = srcData[i * 3 + j * stride];
int g = srcData[i * 3 + j * stride + 1];
int r = srcData[i * 3 + j * stride + 2];
srcData[(int)i * 3 + (int)j * stride] = CLIP3((b * (255 - alpha) + mb * alpha) / 255, 0, 255);
srcData[(int)i * 3 + (int)j * stride + 1] = CLIP3((g * (255 - alpha) + mg * alpha) / 255, 0, 255);
srcData[(int)i * 3 + (int)j * stride + 2] = CLIP3((r * (255 - alpha) + mr * alpha) / 255, 0, 255);
}
}
return ret;
};
double Mask(Mat src, Mat& dst, short* p, const char* sConfig)
{
if (src.empty() || !p) //жͼؼָǷΪ
{
return -1;
}
src.copyTo(dst);
if(sConfig == NULL)
{
return -1;
}
LOGD("Mask config =%s\n", sConfig);
//Mat maskImg = imread("mask_b1.png", -1);
Mat maskImg = imread(sConfig, -1);
int a1 = p[4 + 2 * 37];
int a11 = p[4 + 2 * 37 + 1];
int a2 = p[4 + 2 * 44];
int a22 = p[4 + 2 * 44 + 1];
int a3 = p[4 + 2 * 62];
int a33 = p[4 + 2 * 62 + 1];
int pSrcPoint[6] = {a1,a11,a2,a22,a3,a33};
int MaskPoint[6] = {307, 364, 423, 364, 365, 490};
#if 0
LOGD("mask.channels=%d\n", maskImg.channels());
for(int i = 290; i < 300; i++)
{
for (int j = 235; j < 255; j++)
{
LOGD("data[%d][%d]=%d\n",i,j, maskImg.at<Vec4b>(i, j)[0]);
LOGD("data[%d][%d]=%d\n",i,j, maskImg.at<Vec4b>(i, j)[1]);
LOGD("data[%d][%d]=%d\n",i,j, maskImg.at<Vec4b>(i, j)[2]);
LOGD("data[%d][%d]=%d\n",i,j, maskImg.at<Vec4b>(i, j)[3]);
}
}
#endif
Trent_Sticker(dst.data, dst.cols, dst.rows, dst.cols*3, maskImg.data, maskImg.cols, maskImg.rows, maskImg.cols*4, pSrcPoint, MaskPoint, 100);
return 0;
}
| true |
5549ff255ecdf7bb9053ad40d8b6278e8ed8158b
|
C++
|
hatlonely/leetcode-2018
|
/c++/164_maximum_gap.cpp
|
UTF-8
| 663 | 3.34375 | 3 |
[] |
no_license
|
#include <gtest/gtest.h>
#include <iostream>
#include <vector>
class Solution {
public:
int maximumGap(std::vector<int>& nums) {
if (nums.size() < 2) {
return 0;
}
std::sort(nums.begin(), nums.end());
int max = 0;
for (int i = 0; i < nums.size() - 1; i++) {
max = std::max(max, nums[i + 1] - nums[i]);
}
return max;
}
};
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
TEST(test, case1) {
Solution solution;
auto nums = std::vector<int>({3, 6, 9, 1});
EXPECT_EQ(solution.maximumGap(nums), 3);
}
| true |
8567b132feab807b403dcedcf280a89a335e19e6
|
C++
|
Klein-CK/C-Web
|
/QT_XViewer/src/XVideoEdit/XFilter.h
|
GB18030
| 1,060 | 2.640625 | 3 |
[] |
no_license
|
#pragma once
#include <opencv2/core.hpp>
#include <vector>
enum XTaskType {
XTASK_NONE,
XTASK_GAIN, // Աȶȵ
XTASK_ROTATE90, // ͼת
XTASK_ROTATE180,
XTASK_ROTATE270,
XTASK_FLIPX, // ͼ
XTASK_FLIPY,
XTASK_FLIPXY,
XTASK_RESIZE, // ıߴ
XTASK_PYDOWN, // ˹
XTASK_PYUP, // ˹
XTASK_CLIP, // ͼü
XTASK_GRAY, // תɻҶͼ
XTASK_MARK, // ˮӡ
XTASK_BLEND, // ͼں
XTASK_MERGE, // ͼϲ
};
struct XTask {
XTaskType type; //
std::vector<double> para; // ӦIJ
};
class XFilter
{
public:
virtual cv::Mat Filter(cv::Mat mat1, cv::Mat mat2) = 0;
virtual void Add(XTask task) = 0; // һΪ麯ӿڣʵ
virtual void Clear() = 0; // һ
// ģʽ
static XFilter * Get();
virtual ~XFilter(); // ΪȻڴи
protected:
XFilter();
};
| true |
808be4c1b208398917a0d09bef91254a11ad7b46
|
C++
|
leslier94/RodriguezLeslie_CSC17A_42824
|
/homework/Assignment 3/problem_7/main.cpp
|
UTF-8
| 966 | 2.984375 | 3 |
[] |
no_license
|
/*
* File: main.cpp
* Author: Leslie Rodriguez
*
* Created on April 4, 2016, 11:13 AM
*/
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <cctype>
using namespace std;
/*
*
*/
int main(int argc, char** argv) {
const int SIZE = 100;
char fileName1[SIZE];
char fileName2[SIZE];
char ch, ch2;
ifstream inFile;
ofstream outFile("file2.txt");
cout << "Enter two file names " << endl;
cin >> fileName1;
cin >> fileName2;
inFile.open(fileName1);
while (!inFile.eof()) {
inFile.get(ch);
ch2 = toupper(ch);
outFile.put((ch2));
while (!inFile.eof()) {
inFile.get(ch);
ch2 = tolower(ch);
outFile.put((ch2));
if (ch2 == '.') {
inFile.get(ch);
ch2 = toupper(ch);
outFile.put((ch2));
}
}
}
inFile.close();
outFile.close();
cout << endl;
return 0;
}
| true |
c36b18fb76c5585054fca6117e47282203be0e16
|
C++
|
Youssab-William/Competitive-Programming
|
/USACO/USACO 19feb-gold-cowland.cpp
|
UTF-8
| 3,614 | 2.625 | 3 |
[] |
no_license
|
/*
problem : http://usaco.org/index.php?page=viewproblem2&cpid=921
sol: standard HLD
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll OO= 0;
struct SGTR
{
int sz;
vector<ll>segment;
void calcsz(int n)
{
segment.clear();
sz=1;
while(sz<n)sz*=2;
segment.assign( (sz*2)+1 , OO);
}
ll query(int left , int right , int idx , int l , int r)
{
if(right<l||left>r)
return OO;
if(left<=l && right>=r)
return segment[idx];
int m=(l+r)/2;
return (query( left , right , idx*2 , l , m ))^(query( left , right , idx*2+1 , m+1 , r ));
}
ll query(int left , int right)
{
return query( left , right , 1 , 1 , sz);
}
void update(int index , int val , int idx , int l , int r)
{
if(l==r)
segment[idx]=val;
else
{
int m = (l+r)/2 ;
if(index<=m)
update(index , val , idx*2 , l , m);
else update(index , val , idx*2 +1 , m+1 , r);
segment[idx]=(segment[idx*2]^segment[idx*2+1]);
}
}
void update(int index , int val)
{
update(index , val , 1 , 1, sz);
}
};
vector<int> parent, depth, heavy, head, pos;
int cur_pos;
int dfs(int v, vector<vector<int>> const& adj) {
int sz = 1;
int max_c_size = 0;
for (int c : adj[v]) {
if (c != parent[v]) {
parent[c] = v, depth[c] = depth[v] + 1;
int c_size = dfs(c, adj);
sz += c_size;
if (c_size > max_c_size)
max_c_size = c_size, heavy[v] = c;
}
}
return sz;
}
SGTR segtree;
ll arr[100001];
void decompose(int v, int h, vector<vector<int >> const& adj) {
head[v] = h, pos[v] = cur_pos++;
segtree.update(pos[v] , arr[v]);
if (heavy[v] != -1)
decompose(heavy[v], h, adj);
for (int c : adj[v]) {
if (c != parent[v] && c != heavy[v])
decompose(c, c, adj);
}
}
void init(vector<vector< int >> const& adj) {
int n = adj.size();
parent = vector<int>(n+1);
depth = vector<int>(n+1);
heavy = vector<int>(n+1, -1);
head = vector<int>(n+1);
pos = vector<int>(n+1);
cur_pos = 1;
int tmm = dfs(1, adj);
segtree.calcsz(n);
decompose(1, 1, adj);
}
ll query(int a, int b) {
ll res = 0;
for (; head[a] != head[b]; b = parent[head[b]]) {
if (depth[head[a]] > depth[head[b]])
swap(a, b);
ll cur_heavy_path_max = segtree.query(pos[head[b]], pos[b]);
res = (res^cur_heavy_path_max);
}
if (depth[a] > depth[b])
swap(a, b);
ll last_heavy_path_max = segtree.query(pos[a], pos[b]);
res = (res^last_heavy_path_max);
return res;
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
freopen("cowland.in" , "r" , stdin);
freopen("cowland.out" , "w" , stdout);
int num,q;
cin >> num >> q;
for(int i =1; i<=num ; i++)
{
cin >> arr[i];
}
segtree.calcsz(num);
vector<vector<int> >v(num+1);
for(int i = 0 ;i < num-1 ; i++)
{
//cout << i << "\n";
int a, b;
cin >> a >>b;
v[a].push_back(b);
v[b].push_back(a);
}
init(v);
while(q--)
{
int a, b,c;
cin >> c>> a >> b;
if(c==2)cout << query(a,b)<< "\n";
else
{
segtree.update(pos[a], b);
}
}
return 0;
}
| true |
3d2abf9939bc16e42a56bc34e50fc2df1b39635d
|
C++
|
g-4-gagan/Algorithm
|
/topologicalordering.cpp
|
UTF-8
| 2,890 | 3.296875 | 3 |
[] |
no_license
|
#include<iostream>
#include<queue>
using namespace std;
class node
{
node* prev;
int val;
node* next;
public:
node(node* ptr=0,int a=0,node* ptr1=0)
{
prev=ptr;
val=a;
next=ptr1;
return;
}
friend class DLL;
friend class graph;
};
class DLL
{
node* head;
node* tail;
public:
DLL()
{
head = new node(0,0,tail);
tail= new node(head,0,0);
head->next = tail;
return;
}
void add(node* ptr,int a);
void insertattail(int a);
void print();
friend class graph;
};
void DLL::add(node* ptr,int a)
{
node* current=ptr->prev;
current->next=ptr->prev=new node(current,a,ptr);
return;
}
void DLL::insertattail(int a)
{
add(tail,a);
return;
}
void DLL::print()
{
if(head->next!=tail)
{
node* current=head->next;
while(current!=tail)
{
cout<<current->val;
current=current->next;
if(current!=tail)
{
cout<<"->";
}
}
cout<<endl;
}
return;
}
class graph{
DLL *d;
int v;
public:
graph()
{
}
graph(int n)
{
d = new DLL[n];
v=n;
for(int i=0;i<n;i++)
{
d[i].insertattail(i+1);
}
}
int vertices()
{
return v;
}
void inputnodes(int n);
void display();
void topologicalordering();
};
void graph::inputnodes(int n){
d = new DLL[n];
v=n;
for(int i=0;i<n;i++)
{
d[i].insertattail(i+1);
}
int e;
cout<<"Enter the number of edges in the Graph: ";
cin>>e;
for(int i=0;i<e;i++)
{
cout<<"Enter both vertices having "<<i+1<<" edge from and to respectively: ";
int a,b;
cin>>a>>b;
if(a<=n&&b<=n)
{
d[a-1].insertattail(b);
}
else{
cout<<"Input node not exist.\n";
i--;
}
}
}
void graph::display(){
cout<<endl;
for(int i=0;i<v;i++)
{
d[i].print();
}
}
void graph::topologicalordering()
{
cout<<"\nTopological ordering start:-\n\n";
int *indegree = new int[v];
for(int i=0;i<v;i++)
{
indegree[i]=0;
}
for(int i=0;i<v;i++)
{
node* temp = d[i].head->next->next;
for(;temp!=d[i].tail;temp=temp->next)
{
indegree[temp->val-1]++;
}
}
queue<int> q;
for(int i=0;i<v;i++)
{
if(!indegree[i])
{
q.push(i);
}
}
int count=0;
while(!q.empty())
{
int n = q.front();
q.pop();
node* temp = d[n].head->next->next;
for(;temp!=d[n].tail;temp=temp->next)
{
indegree[temp->val-1]--;
if(!indegree[temp->val-1])
{
q.push(temp->val-1);
}
}
cout<<n+1<<" ";
count++;
}
if(count!=v)
{
cout<<"\n\nTopological ordering stopped due to acyclic graph!!!!";
}
}
int main()
{
int ch,n;
graph g;
cout<<"Enter the number of vertices in the Graph: ";
cin>>n;
g.inputnodes(n);
cout<<"The input Graph is: ";
g.display();
g.topologicalordering();
}
| true |
f7840d359f5370a8b9a005129633a513a5ad86f6
|
C++
|
axel36/some_stuff
|
/sphere_cpp_task/main.cpp
|
UTF-8
| 5,206 | 3.640625 | 4 |
[] |
no_license
|
#include <iostream>
#include <fstream>
#include <string>
#include <set>
#include <vector>
#include <algorithm>
class LinesController{
public:
void AddLine(const std::string& line){
std::vector<std::string> new_line;
auto start = 0U;
auto end = line.find(delim_);
while (end != std::string::npos)
{
const auto& token = line.substr(start, end - start);
new_line.push_back(token);
start = end + delim_.length();
end = line.find(delim_, start);
}
storage_.push_back(new_line);
}
void PrintData(){
for (const auto& line : storage_){
for(const auto & elem: line){
std::cout << elem << "\t";
}
std::cout << std::endl;
}
}
void ApplyCommandsStr(const std::vector<std::string>& commands){
for(const auto& command: commands){
ApplyCommand(ParseCommand(command));
}
}
private:
std::vector<std::vector<std::string>> storage_;
std::string delim_ = "\t";
struct Command{
enum CommandType {UPPER, LOWER, REPLACE};
CommandType type_;
int field;
char a_;
char b_;
};
Command ParseCommand(const std::string& str_command) {
int pos = 0;
// Get field number
std::string number;
for (; pos < str_command.size(); pos++) {
if (!isdigit(str_command[pos])) {
break;
}
number += str_command[pos];
}
int field;
try {
field = std::stoi(number);
} catch (std::invalid_argument &e) {
throw std::runtime_error("invalid command field number - not int: " + str_command);
}
catch (std::out_of_range &e) {
throw std::runtime_error("invalid command field number - too large: " + str_command);
}
if (str_command.size() <= pos || str_command.size() <= pos+1 || str_command[pos] != ':') {
throw std::runtime_error("invalid command: " + str_command);
}
// Get command_type
pos++; // skip ':' charracter
Command::CommandType command_type;
switch (str_command[pos]) {
case 'u':command_type = Command::LOWER;
break;
case 'U':command_type = Command::UPPER;
break;
case 'R':command_type = Command::REPLACE;
break;
default:
throw std::runtime_error("invalid type in command " + str_command);
}
// get characters
if (command_type == Command::REPLACE){
if (str_command.size() - 1 != pos+2 ) { // count of characters for replace
throw std::runtime_error("invalid command: " + str_command);
}
return Command{command_type, field, str_command[pos+1], str_command[pos+2]};
}
return Command{command_type, field};
}
void ApplyCommand(const Command& command){
switch (command.type_) {
case Command::LOWER:
ApplyLower(command.field);
break;
case Command::UPPER:
ApplyUpper(command.field);
break;
case Command::REPLACE:
ApplyReplace(command.field, command.a_, command.b_);
break;
default:
throw std::runtime_error("invalid command in ApplyCommand");
}
}
void ApplyLower(int field){
for (auto& line: storage_){
if (line.size() <= field){
throw std::runtime_error("can't apply command LOWER to all data, N: " + std::to_string(field));
}
std::transform(line[field].begin(), line[field].end(), line[field].begin(), ::tolower);
}
}
void ApplyUpper(int field){
for (auto& line: storage_){
if (line.size() <= field){
throw std::runtime_error("can't apply command UPPER to all data, N: " + std::to_string(field));
}
std::transform(line[field].begin(), line[field].end(), line[field].begin(), ::toupper);
}
}
void ApplyReplace(int field, char a, char b){
for (auto& line: storage_){
if (line.size() <= field){
throw std::runtime_error("can't apply command REPLACE to all data, N: " + std::to_string(field));
}
std::replace(line[field].begin(), line[field].end(), a, b);
}
}
};
// test_input.txt 1:u 0:U 2:RjH - arguments
int main(int argc, char* argv[]) {
std::string input_file_name = std::string(argv[1]);
std::vector<std::string> commands;
commands.reserve(argc - 2);
for (int i = 2; i < argc; i++){
commands.emplace_back(argv[i]);
}
std::ifstream input_file(input_file_name);
if (!input_file.is_open()) {
std::cout << "can't open file " << input_file_name
<< " sry, try again next time" << std::endl;
return 0;
}
LinesController lc;
std::string line;
while (std::getline(input_file, line)) {
lc.AddLine(line);
}
std::cout << "input data: " << std::endl;
lc.PrintData();
try {
lc.ApplyCommandsStr(commands);
} catch (const std::runtime_error& ex) {
std::cout << "raise error during commands processing: " << ex.what();
return 0;
} catch (const std::exception& ex) {
std::cout << "something went wrong: " << ex.what();
return 0;
}
std::cout << std::endl;
std::cout << "input commands: " << std::endl;
for(const auto& com: commands){
std::cout << com << " ";
}
std::cout << std::endl;
std::cout << std::endl;
std::cout << "output data: " << std::endl;
lc.PrintData();
return 0;
}
| true |
fa3911f86412ddbc68405dd5b2c9ade003e301d6
|
C++
|
iYefeng/DesignPatterns
|
/src/Prototype/Product.cc
|
UTF-8
| 881 | 2.78125 | 3 |
[] |
no_license
|
/************************************************************
* Use of this source code is governed by a BSD-style license
* that can be found in the License file.
*
* Author : yefeng
* Email : yefeng38083120@126.com
* Create time : 2016-10-04 17:04
* Last modified : 2016-10-04 17:04
* Filename : Product.cc
* Description :
* *********************************************************/
#include <iostream>
#include "Product.h"
using namespace std;
Product::Product(string name, int id)
: name_(name),
id_(id)
{
}
Product::Product(const Product& other)
{
name_ = other.name_;
id_ = other.id_;
}
Product* Product::clone() const
{
return new Product(*this);
}
void Product::toString() const
{
cout << "name: " << name_ << endl;
cout << "id: " << id_ << endl;
}
void Product::initialize(string name, int id)
{
name_ = name;
id_ = id;
}
| true |
04358891c3ebd2c60fb159646d75325f6f987066
|
C++
|
LorenzGonda/Car-Parking-System
|
/Car-Park-System/Main.cpp
|
UTF-8
| 2,111 | 3.0625 | 3 |
[] |
no_license
|
#include "Carpark.h"
#include "CarparkSlot.h"
#include "Staff.h"
#include "Driver.h"
#include <iostream>
#include <typeinfo>
using namespace std;
int main(int argc, char** argv) {
Carpark** carparkList = new Carpark*[3];
// Car Parks:
string name = "Happy Parking", location = "Happy Valley";
int numSlots[3] = { 6,30,20 }, int fees[3] = { 25,28,28 };
carparkList[0] = new Carpark(1, name, location, numSlots, fees);
string name = "Weathly Parking", location = "Mong Kok";
int numSlots[3] = { 1, 5, 3 }, int fees[3] = { 30, 36, 32 };
carparkList[1] = new Carpark(2, name, location, numSlots, fees);
string name = "Come Parking", location = "Kowloon Tong";
int numSlots[3] = { 8, 20, 10 }, int fees[3] = { 15, 22, 20 };
carparkList[2] = new Carpark(3, name, location, numSlots, fees);
// Users:
int userNum = 4;
User** userList = new User*[4];
// Staff:
string username = "ken"; name = "Ken Lee";
userList[0] = new Staff(1, username, name);
username = "aaron"; name = "Aaron Chan";
string vehicleType = "Motor cycle", number = "AC1234";
userList[1] = new Driver(2, username, name, vehicleType, number, 1580.0);
// Driver:
username = "ben"; name = "Ben Wong";
string vehicleType = "Light goods vehicle", number = "BW88";
userList[2] = new Driver(2, username, name, vehicleType, number, 805.5);
username = "carman"; name = "Carman Lam";
string vehicleType = "Private car", number = "CL660";
userList[3] = new Driver(3, username, name, vehicleType, number, 50);
int input = 1;
bool loggedIn = false;
bool isDriver = false; // True if driver, false if staff
while (input != 0) {
if (!loggedIn) {
string input;
cout << "Please enter your id";
cin >> input;
for (int i = 0; i < userNum; i++) {
if (userList[i]->getName() == input) {
loggedIn = true;
isDriver = typeid(*userList[i]).name() == typeid(Driver).name() ? true : false;
break;
}
}
}
else {
cout << "Invalid Input \n Please try again \n";
}
}
system("pause");
return 0;
}
// If logged in, do sth:
// If driver, go to driver home page
// If staff, go to staff home page
| true |
f9385b1ab2880da02683ef6efd71c0da80c11f35
|
C++
|
zhujiang73/pytorch_mingw
|
/torch/csrc/jit/codegen/cuda/index_compute.h
|
UTF-8
| 3,858 | 2.515625 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
#pragma once
#include <torch/csrc/jit/codegen/cuda/iter_visitor.h>
#include <vector>
/*
* Index compute takes in a list of indices typically generated from the
* surrounding for loop nest. The number of indicies are intended to match the
* number of dimensions of the incomming TensorView which may have less or more
* dimensions than its root due to split/merge operations.
* Split/merge operations are then replayed backwards produce resulting
* indices (based on input indices) that match the root dimension.
*
* For example with GLOBAL tensor:
* TV[I, J]
* TV[Io, Ii{4}, J] = TV.split(I, factor=4)
* ALLOC: NONE
* INDEX: indexCompute {i, j, k} -> {i * 4 + j, k}
* FLATTENED_INDEX: {i * 4 + j, k} -> {i * 4 + j * J + k}
* PREDICATE: {i * 4 + j, k} -> i * 4 + j < I
*
*
* For example with SHARED tensor:
*
* global_TV[I, J]
* global_TV[Io, Ii{4}, J] = global_TV.split(I, factor=4)
* smem_TV.compute_at(global_TV, 1)
* global_TV.parallelize(1, threadIDx.x)
*
* ALLOC: alloc(smem_TV, 4 x J)
* INDEX: indexCompute(smem_TV, {threadIdx.x, k}) -> {threadIdx.x, k}
* FLATTENED_INDEX: {threadIdx.x * 4 + j, k} -> {threadIdx.x * 4 + j * J + k}
* PREDICATE: {threadIdx.x * 4 + j, k} -> threadIdx.x * 4 + j < I // Same as if
* global
*
*
* For example with LOCAL tensor:
* global_TV[I, J, K]
* global_TV[Io, Ii{4}, J] = global_TV.split(I, factor=4)
* reg_TV.compute_at(global_TV, 1)
* global_TV.parallelize(1, threadIDx.x)
* global_TV{i, j, k, l} -> { i * 4 + j, k, l }
* global_TV{ i * 4 + j, k, l } -> { i * 4 + j * J * K + k * K + l}
*
* ALLOC: alloc(reg_TV, J x K)
* INDEX: {k, l} -> {k, l}
* FLATTENED_INDEX: {k, l} -> {k * J + l}
* PREDICATE: i * 4 + j < I && k < J && l < K -> // Same as if global
*
* These indices can then be flattened later based on strides.
*/
namespace torch {
namespace jit {
namespace fuser {
struct IndexCompute : public BackwardVisitor {
private:
using BackwardVisitor::handle;
void handle(Split*) override;
void handle(Merge*) override;
void handle(Expr*) override;
// Otherwise warning on runBackward as it hides an overloaded virtual
// using TransformIter::runBackward;
IndexCompute(TensorDomain* td, const std::vector<Val*>& _indices);
std::unordered_map<IterDomain*, Val*> index_map_;
std::vector<Val*> indices_;
public:
static std::vector<Val*> get(
TensorDomain* td,
const std::vector<Val*>& _indices);
};
// Simple interface for IndexCompute
struct Index {
private:
// Producer indexing if it's in shared or local memory
static TensorIndex* getProducerIndex_impl(
TensorView* producer,
TensorView* consumer,
const std::vector<ForLoop*>& loops);
// Consumer indexing if it's in shared or local memory
static TensorIndex* getConsumerIndex_impl(
TensorView* consumer,
const std::vector<ForLoop*>& loops);
public:
// Producer if it's in global memory
static TensorIndex* getGlobalProducerIndex(
TensorView* producer,
TensorView* consumer,
const std::vector<ForLoop*>& loops);
// Consumer indexing if it's in global memory
static TensorIndex* getGlobalConsumerIndex(
TensorView* consumer,
const std::vector<ForLoop*>& loops);
// Indexing functions
// Consumer = Producer
// i.e. T0 = T1... -> T0 is the consumer, T1 is the producer
// Producer indexing dispatch
static TensorIndex* getProducerIndex(
TensorView* producer,
TensorView* consumer,
const std::vector<ForLoop*>& loops);
// Consumer index dispatch
static TensorIndex* getConsumerIndex(
TensorView* consumer,
const std::vector<ForLoop*>& loops);
// Will run inds through back prop index computation for tv
static TensorIndex* manualBackprop(TensorView tv, std::vector<Val*> inds);
};
} // namespace fuser
} // namespace jit
} // namespace torch
| true |
c6a64ebcbe844e9692bb9a8c42ae59724ced1f0d
|
C++
|
SimplyKnownAsG/argreffunc
|
/tests/PositionalTests.cpp
|
UTF-8
| 1,978 | 3.40625 | 3 |
[
"Apache-2.0"
] |
permissive
|
#include "arf/argreffunc.hpp"
#include "catch.hpp"
#include <iostream>
using namespace arf;
class SomeClass {
public:
double member_dubs;
};
TEST_CASE("positional", "[positional]") {
Parser parser("prog");
int int_val;
float float_val = 0.0f;
SomeClass sc;
std::function<void(double)> func = [&](double arg) -> void { sc.member_dubs = arg; };
sc.member_dubs = 0.0;
parser.add_positional("first", "f", int_val);
parser.add_positional("second", "s", float_val);
parser.add_positional("third", "t", func);
SECTION("success with argc argv") {
int argc = 4;
char* argv[] = { (char*)"program", (char*)"12", (char*)"11.11", (char*)"99e99" };
parser.parse(argc, argv);
REQUIRE(int_val == 12);
REQUIRE(float_val == 11.11f);
REQUIRE(sc.member_dubs == 99e99);
}
SECTION("success with vector") {
std::vector<std::string> args = { "4", "19.19", "99e99" };
parser.parse(args);
REQUIRE(int_val == 4);
REQUIRE(float_val == 19.19f);
REQUIRE(sc.member_dubs == 99e99);
}
SECTION("too few") {
std::vector<std::string> args = { "7" };
REQUIRE_THROWS_AS(parser.parse(args), Exception);
}
SECTION("too many") {
std::vector<std::string> args = { "9", "12.12", "42e42", "barf" };
REQUIRE_THROWS_AS(parser.parse(args), Exception);
}
}
TEST_CASE("positional multile-values", "[positional][multi]") {
Parser parser("prog");
SECTION("multiple values") {
std::vector<std::string> values;
std::vector<std::string> args = { "This", "is", "a", "sentence." };
std::function<void(ArgIterator&)> func = [&](ArgIterator& iterator) {
iterator.get_values("values", values);
};
parser.add_positional("values", "all values", func);
parser.parse(args);
REQUIRE(values.size() == args.size());
REQUIRE(values.at(2) == "a");
}
}
| true |
062cf1163b2d8509761691b5514ffd93296e88da
|
C++
|
VA-007/CP-Code
|
/79-Byterace-C.cpp
|
UTF-8
| 676 | 2.5625 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <cmath>
#define int long long
using namespace std;
main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while (t--)
{
int n, q;
cin >> n >> q;
vector<int> ans(n + 1, 0);
while (q--)
{
int des = 1;
int l, r;
cin >> l >> r;
for (int i = l; i <= r; i++)
{
ans[i] += des;
des++;
}
}
for (int i = 1; i < ans.size(); i++)
{
cout << ans[i] << " ";
}
cout << endl;
}
return 0;
}
| true |
9d98daec6f71c0367a007a54fab052845d6b701b
|
C++
|
iddeepak/Student_Management_System
|
/Database_Manager.h
|
UTF-8
| 521 | 2.59375 | 3 |
[] |
no_license
|
#include "sqlite3.h"
#include "Student.h"
using namespace std;
class DatabaseManager
{
private:
sqlite3 *DB;
public:
void setupDatabase();
void createTable();
void closeDatabase();
void saveStudentData(Student x);
void saveResultData(Result x, int rollno);
void getStudentData();
Student getStudentData(int rollno);
void getResultData();
Result getResultData(int rollno);
void deleteData(int rollno);
void updateData(int rollno);
};
| true |
40e3b0b6a8a586fd611ec714bf43012a7ee784d1
|
C++
|
EthanGriffee/SoftwareDev
|
/assignment4/part1/submitted_test_2.cpp
|
UTF-8
| 1,965 | 3.125 | 3 |
[] |
no_license
|
#include <gtest/gtest.h>
#include "dataframe.h"
#define GT_TRUE(a) ASSERT_EQ((a),true)
#define GT_FALSE(a) ASSERT_EQ((a),false)
#define GT_EQUALS(a, b) ASSERT_EQ(a, b)
#define ASSERT_EXIT_ZERO(a) \
ASSERT_EXIT(a(), ::testing::ExitedWithCode(0), ".*")
/*******************************************************************************
* Rower::
* A Rower that only displays rows where all bool values are true
*/
class OnlyTrueRower : public Rower {
public:
/** This method is called once per row. The row object is on loan and
should not be retained as it is likely going to be reused in the next
call. The return value is used in filters to indicate that a row
should be kept. */
virtual bool accept(Row& r) {
for (int x = 0; x < r.width(); x++) {
if (r.col_type(x) == 'B' && !r.get_bool(x)) {
return false;
}
}
return true;
}
/** Once traversal of the data frame is complete the rowers that were
split off will be joined. There will be one join per split. The
original object will be the last to be called join on. The join method
is reponsible for cleaning up memory. */
virtual void join_delete(Rower* other) {
delete other;
}
};
void rower_filter_dataframe_test() {
Schema s("IBB");
DataFrame df(s);
Row r(df.get_schema());
r.set(0,1);
r.set(1, false);
r.set(2, true);
df.add_row(r);
r.set(0, 0);
r.set(1, true);
r.set(2, true);
df.add_row(r);
r.set(0, 2);
r.set(0, true);
r.set(1, false);
df.add_row(r);
OnlyTrueRower rower;
DataFrame* df2 = df.filter(rower);
GT_TRUE(df2->get_int(0, 0) == df.get_int(0, 1));
GT_TRUE(df2->nrows() == 1);
df2->add_row(r);
GT_TRUE(df2->get_int(0, 1) == 2);
exit(0);
}
TEST(DataFrameTest, rower_filter_dataframe_test){ ASSERT_EXIT_ZERO(rower_filter_dataframe_test); }
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| true |
904869a0ff14a53dc10af9e5eb3cfad6f1aa23a4
|
C++
|
p-gonzo/cpp_practice
|
/chp12/listing_12_1.cpp
|
UTF-8
| 1,198 | 4.15625 | 4 |
[] |
no_license
|
#include <iostream>
#include <sstream>
#include <string>
class Date
{
private:
int day, month, year;
std::string dateString;
public:
Date(int m, int d, int y)
: month(m), day(d), year(y) { };
Date& operator++ () // preifx
{
++ day;
return *this;
}
Date operator++ (int) // postfix
{
Date copy(*this);
++ day;
return copy;
}
Date& operator-- ()
{
-- day;
return *this;
}
Date operator-- (int)
{
Date copy(*this);
-- day;
return copy;
}
operator const char*() // conversion operator
{
std::ostringstream formattedDate;
formattedDate << month << "/" << day << "/" << year;
dateString = formattedDate.str();
return dateString.c_str();
}
};
int main()
{
Date birthday (11, 19, 1988);
std::cout << "My birthday is on " << birthday << std::endl;
birthday++;
++birthday;
std::cout << "Two days after my birthday is " << birthday << std::endl;
std::cout << "We can also now convert Dates directly to strings: " << std::string(Date(1,1,1)) << std::endl;
return 0;
}
| true |
70c5caa8f8adfac095b4a8471288f9179994d0ad
|
C++
|
mkut/cf
|
/01-99/03/3C/c++.cpp
|
UTF-8
| 1,226 | 3.28125 | 3 |
[] |
no_license
|
#include <iostream>
#include <map>
using namespace std;
class solver
{
map<string, string> ans;
public:
solver()
{
_solve(".........", true);
}
string solve(string str)
{
if(ans.count(str) != 0) return ans[str];
return "illegal";
}
private:
void _solve(string str, bool first)
{
if(ans.count(str) != 0) return;
if(win(str) != "")
{
ans[str] = win(str);
return;
}
else ans[str] = first ? "first" : "second";
for(int i = 0; i < 9; i++)
{
if(str[i] == '.')
{
string tstr = str;
tstr[i] = first ? 'X' : '0';
_solve(tstr, !first);
}
}
}
string win(string str)
{
int check[8][3] = {{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};
for(int i = 0; i < 8; i++)
{
if(str[check[i][0]] == str[check[i][1]] && str[check[i][0]] == str[check[i][2]] && str[check[i][0]] != '.')
{
return str[check[i][0]] == 'X' ? "the first player won" : "the second player won";
}
}
for(int i = 0; i < 9; i++)
{
if(str[i] == '.') return "";
}
return "draw";
}
};
int main()
{
solver prob;
string input[3];
cin >> input[0] >> input[1] >> input[2];
cout << prob.solve(input[0] + input[1] + input[2]) << endl;
return 0;
}
| true |
c9a46c8cfd4d7f5a4e7851013059473031d98c15
|
C++
|
Tomcc/dojo
|
/src/Renderable.cpp
|
UTF-8
| 3,089 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
#include "Renderable.h"
#include "Game.h"
#include "Viewport.h"
#include "Mesh.h"
#include "GameState.h"
#include "Object.h"
#include "Platform.h"
#include "Renderer.h"
using namespace Dojo;
Renderable::Renderable(Object& parent, RenderLayer::ID layer) :
Component(parent),
layer(layer) {
color = Color::White;
}
Renderable::Renderable(Object& parent, RenderLayer::ID layer, Mesh& m, Shader& shader) :
Renderable(parent, layer) {
setMesh(m);
mShader = shader;
DEBUG_ASSERT(mesh.unwrap().supportsShader(mShader.unwrap()), "cannot use this mesh with this shader");
}
Renderable::Renderable(Object& parent, RenderLayer::ID layer, utf::string_view meshName, utf::string_view shaderName) :
Renderable(
parent,
layer,
parent.getGameState().getMesh(meshName).unwrap(),
parent.getGameState().getShader(shaderName).unwrap()) {
DEBUG_ASSERT(mesh.unwrap().supportsShader(mShader.unwrap()), "cannot use this mesh with this shader");
}
Renderable::~Renderable() {
}
void Renderable::startFade(const Color& start, const Color& end, float duration) {
DEBUG_ASSERT(duration > 0, "The duration of a fade must be greater than 0");
fadeStartColor = start;
fadeEndColor = end;
color = start;
currentFadeTime = 0;
fadeEndTime = duration;
fading = true;
setVisible(true);
}
void Renderable::startFade(float startAlpha, float endAlpha, float duration) {
color.a = startAlpha;
Color end = color;
end.a = endAlpha;
startFade(color, end, duration);
}
void Renderable::update(float dt) {
if (auto m = mesh.to_ref()) {
auto trans = glm::scale(object.getWorldTransform(), scale);
advanceFade(dt);
auto& meshBounds = m.get().getBounds();
if (trans != mTransform or meshBounds != mLastMeshBB) {
AABB bounds = m.get().getBounds();
bounds.max = Vector::mul(bounds.max, scale);
bounds.min = Vector::mul(bounds.min, scale);
//TODO this caching is really fiddly and 6 floats just for it is hmmm
mWorldBB = object.transformAABB(bounds);
mTransform = trans;
mLastMeshBB = meshBounds;
}
}
}
bool Renderable::canBeRendered() const {
if (auto m = mesh.to_ref()) {
return isVisible() and m.get().isLoaded() and m.get().getVertexCount() > 2;
}
else {
return false;
}
}
void Renderable::stopFade() {
fading = false;
}
void Renderable::advanceFade(float dt) {
if (fading) { //fade is scheduled
float fade = currentFadeTime / fadeEndTime;
float invf = 1.f - fade;
color.r = fadeEndColor.r * fade + invf * fadeStartColor.r;
color.g = fadeEndColor.g * fade + invf * fadeStartColor.g;
color.b = fadeEndColor.b * fade + invf * fadeStartColor.b;
color.a = fadeEndColor.a * fade + invf * fadeStartColor.a;
if (currentFadeTime > fadeEndTime) {
fading = false;
if (fadeEndColor.a == 0) {
setVisible(false);
}
}
currentFadeTime += dt;
}
}
GameState& Renderable::getGameState() const {
return getObject().getGameState();
}
void Renderable::onAttach() {
Platform::singleton().getRenderer().addRenderable(self);
}
void Renderable::onDetach() {
Platform::singleton().getRenderer().removeRenderable(self);
}
| true |
4b5b0ff30f87b18370dfa8f7ac6095fa7da889a8
|
C++
|
yanbcxf/cpp
|
/MyToolKit/GB28181Client/AbstractCommand.h
|
GB18030
| 542 | 2.78125 | 3 |
[] |
no_license
|
#pragma once
class UsageEnvironment;
class AbstractCommand
{
public:
AbstractCommand(bool bSnyc);
virtual ~AbstractCommand(void);
int Call(UsageEnvironment & environ);
void CommandExecute(UsageEnvironment* pThis);
virtual int Execute(UsageEnvironment* pThis) = 0;
bool IsSnyc(){ return m_bSnyc; }
virtual string CommandType() = 0;
public:
HANDLE hSempaphore;
int m_nResult;
int m_nSerialNumber; // UsageEnvironment ǰ к
protected:
bool m_bSnyc; // 첽 ͬ flag
};
| true |
cc205e0e7c1d17c8986693f1bf0f80d35954419a
|
C++
|
wojciech-goledzinowski/Zadania-z-programowania-STL-III-sem
|
/cpp/z31.cpp
|
UTF-8
| 527 | 3.3125 | 3 |
[] |
no_license
|
//BB31. W kontenerze <list> umieścić 10 liczb (od 0 do 9). Wyświetl elementy. Przy pomocy iteratora ustawionego na 3 element wstaw liczbę 1313 do kontenera. Wyświetl ponownie elementy kontenera.
#include <iostream>
#include <list>
using namespace std;
int main()
{
list<int> k1;
list<int>::iterator i1;
for(int i=0;i<10;i++) k1.push_back(i);
for(auto i:k1) cout << i <<", ";
i1=k1.begin();
advance(i1,2);
cout << endl;
k1.insert(i1,1313);
for(auto i:k1) cout << i <<", ";
}
| true |
d49aa2538b5e2b6de55f0b26d5cff54735e139fc
|
C++
|
ckupetz/SeamCarving
|
/main.cpp
|
UTF-8
| 1,562 | 3.078125 | 3 |
[] |
no_license
|
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include "Seam.cpp"
int main(int argc, char * argv[]) {
//Make sure we have the right number of arguments
if (argc != 4) { std::cout << "Please use the following format: '[filename] [VERTICAL_SEAMS] [HORIZTONAL_SEAMS]'\n"; return 0; }
//Initialize our width/height variables, as well as the max B/W value (0-255)
int MAX_VALUE, X_WIDTH, Y_HEIGHT;
int VERTICAL_SEAMS = atoi(argv[2]);
int HORIZTONAL_SEAMS = atoi(argv[3]);
//Open the file and load it into a string
std::ifstream input(argv[1]);
std::string filename = argv[1];
//Get values from infile
GetValuesFromFile(X_WIDTH, Y_HEIGHT, MAX_VALUE, input);
//Create initial Matrix to read in from infile
std::vector<std::vector<int>> ValueMatrix (Y_HEIGHT, std::vector<int> (X_WIDTH, 0 ));
FillValueMatrix (ValueMatrix, input);
RemoveSeam (Y_HEIGHT, X_WIDTH, VERTICAL_SEAMS, ValueMatrix);
TransposeMatrix (ValueMatrix);
std::swap (X_WIDTH, Y_HEIGHT);
RemoveSeam (Y_HEIGHT, X_WIDTH, HORIZTONAL_SEAMS, ValueMatrix);
TransposeMatrix (ValueMatrix);
//Create new filename for outfile
std::size_t pos = filename.find_last_of(".");
if (pos != std::string::npos) filename = filename.substr(0, pos) + "_processed" + filename.substr(pos, pos + 2);
//Create the outfile and fill it with the decompressed string
std::ofstream output(filename);
OutputFinalMatrix(ValueMatrix, output, MAX_VALUE);
output.close();
input.close();
}
| true |
9538ba79de137cf2366449cb4d8fed8177ca8725
|
C++
|
mryoshio/hackerrank
|
/cpp/quicksort.cpp
|
UTF-8
| 938 | 3.109375 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
void d(vector<int> ar, int l, int r) {
for (int i = l; i <= r; i++)
cout << ar[i] << " ";
cout << endl;
}
void quickSort(vector<int> &ar, int l, int r) {
vector<int> tmp(ar.size());
int i, l_idx = l, r_idx = r;
int piv = ar[l];
for (i = l+1; i <= r; i++)
if (ar[i] < piv) tmp[l_idx++] = ar[i];
else tmp[r_idx--] = ar[i];
for (i = l; i < l_idx; i++)
ar[i] = tmp[i];
ar[l_idx] = piv;
for (i = r; i > r_idx; i--)
ar[++l_idx] = tmp[i];
if (r-l <= 1) {
if (r-l == 1)
d(ar, l, r);
return;
}
quickSort(ar, l, r_idx-1);
quickSort(ar, r_idx+1, r);
d(ar, l, r);
}
int main(void) {
vector <int> _ar;
int _ar_size;
cin >> _ar_size;
for(int _ar_i=0; _ar_i<_ar_size; _ar_i++) {
int _ar_tmp;
cin >> _ar_tmp;
_ar.push_back(_ar_tmp);
}
quickSort(_ar, 0, _ar_size-1);
return 0;
}
| true |
4482af06efabd5b8044db52629f37d18650f25dc
|
C++
|
shivangigoel1302/leetcode_solutions
|
/minimum_add_to_make_parenthesis_valid.cpp
|
UTF-8
| 558 | 2.6875 | 3 |
[] |
no_license
|
class Solution {
public:
int minAddToMakeValid(string S) {
int count = 0;
stack<char>parenthesis;
for(auto c: S){
if(c == '('){
parenthesis.push(c);
}
else{
if(parenthesis.empty()){
count++;
}
else{
parenthesis.pop();
}
}
}
while(!parenthesis.empty()){
count++;
parenthesis.pop();
}
return count;
}
};
| true |
aa3b4232601e8434d72e4cba260b00d3f70b9ed4
|
C++
|
CTDL-18CTT5A/FinalProject
|
/Source/CompressFileText/jpeg_encoder.h
|
UTF-8
| 2,965 | 2.90625 | 3 |
[] |
no_license
|
#ifndef __JPEG_ENCODER_HEADER__
#define __JPEG_ENCODER_HEADER__
class JpegEncoder
{
private:
int m_width; // Chiều rộng
int m_height; // Chiều cao
unsigned char* m_rgbBuffer; // Mảng chứa toàn bộ điểm ảnh m_width*m_height*3
unsigned char m_YTable[64]; // Chứa độ sáng khi chuyển đổi không gian màu
unsigned char m_CbCrTable[64]; // Chứa độ màu khi chuyển đổi khôn gian màu bao gồm Cb và Cr
// Một bitstring khi mã hóa sẽ được lưu dưới dạng 1 cặp giá trị (độ dài bit biểu diễn giá trị value, giá trị value)
struct BitString
{
int length;
int value;
};
// Bảng mã code huffman để mã hóa entropy trên DC và ACs
BitString m_Y_DC_Huffman_Table[12];
BitString m_Y_AC_Huffman_Table[256];
BitString m_CbCr_DC_Huffman_Table[12];
BitString m_CbCr_AC_Huffman_Table[256];
public:
// Renew lại bộ đệm
void clean(void);
// Đọc dữ liệu ảnh BMP 24 bit deepth (Nén ảnh BMP sang chuản JPEG)
bool readFromBMP(const char* fileName);
// Mã hóa thành ảnh JPEG
bool encodeToJPG(const char* fileName, int quality_scale);
private:
// Phương thức khởi tạo các giá trị mặc định cho table
void initHuffmanTables(void);
// Khởi tạo các thay đổi về chất lượng nén ảnh. Tham số càng lớn thì dung lượng ảnh nén càng nhỏ. Đầu vào là một số nguyên từ 1 đến 99.
void initQualityTables(int quality);
// Được gọi khi đã init bảng Table. Khởi tạo ban đầu
void computeHuffmanTable(const char* nr_codes, const unsigned char* std_table, BitString* huffman_table);
// Phương thứuc trả về số lượng bit cần tối thiểu để biểu diễn số nguyên value
BitString getBitCode(int value);
// Chuyển đổi không gian màu từ RGB sang Y(Độ sáng) Cb Cr (Độ màu)
void convertColorSpace(int xPos, int yPos, char* yData, char* cbData, char* crData);
// biến đổi cosin rời rạc 2 chiều
void foword_FDC(const char* channel_data, short* fdc_data);
// Mã hóa huffman
void doHuffmanEncoding(const short* DU, short& prevDC, const BitString* HTDC, const BitString* HTAC, BitString* outputBitString, int& bitStringCounts);
private:
// ghi header file JPEG
void write_jpeg_header(FILE* fp);
// Các bién thể của phương thức ghi xuống file
void write_byte(unsigned char value, FILE* fp); // ghi lần 1 byte
void write_word(unsigned short value, FILE* fp); // ghi lần 1 word (2 byte)
void write_bitstring(const BitString* bs, int counts, int& newByte, int& newBytePos, FILE* fp); // ghi lần 1 đối tượng của mảng Bitstring theo số lượng biến count byte
void write(const void* p, int byteSize, FILE* fp); // hia lần 1 byte nhưng đặc biệt để ghi header file
public:
// Phương thức tạo và phương thức hủy
JpegEncoder();
~JpegEncoder();
};
#endif
| true |
60bd2eaf23f5f8ffec5d530149321a61d9c9814e
|
C++
|
Spetsnaz-Dev/CPP
|
/Misc/efficient_janitor.cpp
|
UTF-8
| 1,116 | 3.453125 | 3 |
[] |
no_license
|
#include<bits/stdc++.h>
using namespace std;
void insertionSort(vector<float> arr, int n)
{
int i, j;
float key;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i - 1;
/* Move elements of arr[0..i-1], that are
rer than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
for(int i=0;i<n;i++)
cout<<arr[i]<<" ";
}
int checkCount(vector<float> arr) {
insertionSort(arr, arr.size());
int n= arr.size();
int i=0, j= n-1, count=0;
while(i<=j) {
if((arr[i] + arr[j]) > 3.0) {
count++;
j--;
} else {
count++;
i++;
j--;
}
}
return count+1;
}
int main() {
int n;
cin>>n;
float t;
vector<float> arr(n);
for(int i=0;i<n;i++)
{
cin>>t;
arr.push_back(t);
}
cout<<checkCount(arr)<<endl;;
return 0;
}
| true |
ab56911ed742f0dfb1d107591cbd4c104f11cfa4
|
C++
|
muhammadadji17/quiz1
|
/menentukanJenisBilangan.cpp
|
UTF-8
| 365 | 3.140625 | 3 |
[] |
no_license
|
#include<iostream>
using namespace std;
int main(){
int Z;
cout<<"silahkan masukan bilangan: ";cin>>Z;
cout<<""<<endl;
if (Z < 0)
{
cout<<"yang anda input adalah bilangan negatif"<<endl;
}
else if (Z>0)
{
cout<<"yang anda input adalah bilangan positif"<<endl;
}
else if (Z==0)
cout<<"yang anda input adalah bilangan nol "<<endl;
return 0;
}
| true |
9347b311ebdd49c1e5c0f3915711ae623d33d4d1
|
C++
|
YC-YC/JNI
|
/TestBin/jni/pattern/component/Component.h
|
UTF-8
| 1,485 | 2.9375 | 3 |
[] |
no_license
|
/*
* Component.h
*
* Created on: 2018-5-7
* Author: Administrator
*/
#ifndef COMPONENT_H_
#define COMPONENT_H_
#include "Log.h"
#include "comdef.h"
#include <vector>
using namespace std;
class Component {
public:
virtual ~Component() {
}
virtual void action() = 0;
virtual void add(Component* pCom) {
LOGI("Component add");
}
virtual void remove(Component* pCom) {
LOGI("Component remove");
}
virtual Component* getChild(int index) {
LOGI("Component getChild index = %d", index);
return NULL;
}
protected:
Component() {
}
};
class Leaf: public Component {
public:
Leaf() {
}
~Leaf() {
}
void action() {
LOGI("Leaf action");
}
};
class Tree: public Component {
public:
Tree() {
}
~Tree() {
}
void action() {
LOGI("Tree action");
vector<Component*>::iterator it = mComponents.begin();
for (; it != mComponents.end(); it++) {
(*it)->action();
}
}
virtual void add(Component* pCom) {
LOGI("Tree add");
mComponents.push_back(pCom);
}
virtual void remove(Component* pCom) {
LOGI("Tree remove");
vector<Component*>::iterator it = mComponents.begin();
for (; it != mComponents.end(); it++) {
if (*it == pCom) {
mComponents.erase(it);
break;
}
}
}
virtual Component* getChild(int index) {
LOGI("Tree getChild index = %d", index);
if (index < 0 || index > mComponents.size()) {
return NULL;
}
return mComponents[index];
}
private:
vector<Component*> mComponents;
};
#endif /* COMPONENT_H_ */
| true |
acce644e0e0b8d8b40e2cddfe9087431c0832c90
|
C++
|
luthfihm/Tubes-2-Jarkom
|
/server.cpp
|
UTF-8
| 1,762 | 2.875 | 3 |
[] |
no_license
|
#include "server.h"
Server::Server()
{
// buka socket TCP (SOCK_STREAM) dengan alamat IPv4 dan protocol IP
if((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_IP)) < 0){
close(sock);
printf("Cannot open socket\n");
exit(1);
}
// ganti opsi socket agar dapat di-reuse addressnya
int yes = 1;
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1) {
perror("Cannot set option\n");
exit(1);
}
// buat address untuk server
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY; // semua address pada network interface
serv_addr.sin_port = htons(9000); // port 9000
// bind server ke address
if (bind(sock, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0){
close(sock);
printf("Cannot bind socket\n");
exit(1);
}
listen(sock,10); // listen ke maksimal 5 koneksi klien
}
Server::~Server()
{
close(sock);
}
void Server::readmessage(int sockid)
{
int len;
message fromclient;
while(connected)
{
len = read(sockid,fromclient,sizeof(message));
if(len >= 0)
{
writemessage(fromclient);
}
else
{
connected = false;
}
}
close(sockid);
}
void Server::writemessage(message m)
{
}
void Server::connect()
{
while(1)
{
// terima koneksi dari klien
clilen = sizeof(cli_addr);
client_sock = accept(sock, (struct sockaddr *) &cli_addr, &clilen);
threadvector.push_back(thread(readmessage,client_sock));
}
}
void Server::login()
{
}
void Server::logout()
{
}
void Server::signup()
{
}
void Server::writefile(int type)
{
}
void Server::readfile(int type)
{
}
| true |
b03cf3b57f1522d47df0d526f6a40d578ccc3ba1
|
C++
|
elensalustiano/chrome-t-rex
|
/chrome_t_rex.ino
|
UTF-8
| 5,267 | 2.890625 | 3 |
[
"LicenseRef-scancode-public-domain"
] |
permissive
|
#include <LiquidCrystal.h>
// Defines the pins that will be used for the display
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
//bitmap array for the dino character
byte dino [8]
{ B00000,
B00111,
B00101,
B10111,
B11100,
B11111,
B01101,
B01100,
};
//character for the tree
byte tree [8]
{
B00011,
B11011,
B11011,
B11011,
B11011,
B11111,
B01110,
B01110
};
const int BUTTON_ENTER = 8;
const int BUTTON_SELECT = 9;
const int MENU_SIZE = 2;
const int LCD_COLUMN = 16;
const int TREE_CHAR = 6;
const int DINO_CHAR = 7;
const String ALPHABET[26] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
boolean isPlaying = false;
boolean isShowScore = false;
boolean isDinoOnGround = true;
int currentIndexMenu = 0;
int score = 0;
int scoreListSize = 0;
String scoreList[20];
void setup() {
lcd.begin(16, 2);
lcd.createChar(DINO_CHAR, dino);
lcd.createChar(TREE_CHAR, tree);
Serial.begin(9600);
pinMode(BUTTON_ENTER, INPUT);
pinMode(BUTTON_SELECT, INPUT);
}
void loop() {
lcd.clear();
handleMenu();
delay(300);
}
void handleMenu() {
String menu[MENU_SIZE] = { "START", "SCORE" };
for (int i = 0; i < MENU_SIZE; i++) {
if (i == currentIndexMenu) {
lcd.setCursor(0, i);
lcd.print("-> ");
}
lcd.setCursor(3, i);
lcd.print(menu[i]);
}
if (digitalRead(BUTTON_SELECT) == LOW) {
currentIndexMenu = currentIndexMenu == 0 ? 1 : 0;
}
if (digitalRead(BUTTON_ENTER) == LOW) {
currentIndexMenu == 0 ? startGame() : showScore();
}
}
void showScore () {
isShowScore = true;
delay(200);
int currentIndex = 0;
const int lastIndex = scoreListSize - 1;
printScore(currentIndex, lastIndex);
while (isShowScore) {
if (digitalRead(BUTTON_SELECT) == LOW) {
currentIndex = currentIndex < lastIndex ? currentIndex + 1 : 0;
printScore(currentIndex, lastIndex);
}
if (digitalRead(BUTTON_ENTER) == LOW) {
isShowScore = false;
}
delay(200);
}
}
void printScore(int index, int lastIndex) {
lcd.clear();
if (lastIndex == -1) {
lcd.print("NO SCORE");
}
else {
lcd.print(scoreList[index]);
if (index < lastIndex) {
lcd.setCursor(0, 1);
lcd.print(scoreList[index + 1]);
}
}
}
void startGame () {
isPlaying = true;
while (isPlaying) {
handleGame();
}
}
void handleGame() {
lcd.clear();
int buttonPressedTimes = 0;
// Generate two random distances for the space between the trees
int secondPosition = random(4, 9);
int thirdPosition = random(4, 9);
int firstTreePosition = LCD_COLUMN;
const int columnValueToStopMoveTrees = -(secondPosition + thirdPosition);
// this loop is to make the trees move, this loop waiting until
// all the trees moved
for (; firstTreePosition >= columnValueToStopMoveTrees; firstTreePosition--) {
lcd.setCursor(13, 0);
lcd.print(score);
defineDinoPosition();
int secondTreePosition = firstTreePosition + secondPosition;
int thirdTreePosition = secondTreePosition + thirdPosition;
showTree(firstTreePosition);
showTree(secondTreePosition);
showTree(thirdTreePosition);
if (isDinoOnGround) {
if (firstTreePosition == 1 || secondTreePosition == 1 || thirdTreePosition == 1) {
handleGameOver();
delay(5000);
break;
}
buttonPressedTimes = 0;
} else {
if (buttonPressedTimes > 3) {
score -= 3;
}
buttonPressedTimes++;
}
score++;
delay(500);
}
}
void handleGameOver () {
lcd.clear();
lcd.print("GAME OVER");
lcd.setCursor(0, 1);
lcd.print("SCORE: ");
lcd.print(score);
delay(2000);
saveScore();
}
void saveScore () {
lcd.clear();
String nick = "";
int nickSize = 0;
int alphabetCurrentIndex = 0;
lcd.print("TYPE YOUR NICK");
while (nickSize != 3) {
lcd.setCursor(nickSize, 1);
lcd.print(ALPHABET[alphabetCurrentIndex]);
if (digitalRead(BUTTON_SELECT) == LOW) {
alphabetCurrentIndex = alphabetCurrentIndex != 25 ? alphabetCurrentIndex + 1 : 0;
}
if (digitalRead(BUTTON_ENTER) == LOW) {
nick += ALPHABET[alphabetCurrentIndex];
nickSize++;
alphabetCurrentIndex = 0;
}
delay(300);
}
scoreList[scoreListSize] = nick + " " + score;
scoreListSize++;
isPlaying = false;
score = 0;
}
void showTree (int position) {
lcd.setCursor(position, 1);
lcd.write(TREE_CHAR);
// clean the previous position
lcd.setCursor(position + 1, 1);
lcd.print(" ");
}
void defineDinoPosition () {
int buttonState = digitalRead(BUTTON_ENTER);
buttonState == HIGH ? putDinoOnGround() : putDinoOnAir();
}
void putDinoOnGround () {
lcd.setCursor(1, 1);
lcd.write(DINO_CHAR);
lcd.setCursor(1, 0);
lcd.print(" ");
isDinoOnGround = true;
}
void putDinoOnAir () {
lcd.setCursor(1, 0);
lcd.write(DINO_CHAR);
lcd.setCursor(1, 1);
lcd.print(" ");
isDinoOnGround = false;
}
| true |
2d5a64b93e6b6dafe6a5dc04298fdae800b89bec
|
C++
|
UbiquityRobotics/fiducials
|
/fiducial_slam/include/fiducial_slam/helpers.h
|
UTF-8
| 217 | 3.09375 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
#include <cmath>
#include <memory>
// Degrees to radians
constexpr double deg2rad(double deg) { return deg * M_PI / 180.0; }
// Radians to degrees
constexpr double rad2deg(double rad) { return rad * 180.0 / M_PI; }
| true |
506f5cee87bc63761aefd32e02209db869ca1c99
|
C++
|
RipeTomatoe/Capstone
|
/Capstone/Destroyer.h
|
UTF-8
| 1,123 | 3.453125 | 3 |
[] |
no_license
|
#ifndef __DESTROYER_H_
#define __DESTROYER_H_
template<class T>
class Destroyer
{
public:
/********************************************************************************************
Summary: Default Constructor
Parameters: [in] dest - The pointer of the singleton to be destroyed.
********************************************************************************************/
Destroyer(T* dest = 0)
{
pToDie = dest;
}
/********************************************************************************************
Summary: Default Destructor
Parameters: None.
********************************************************************************************/
virtual ~Destroyer(void)
{
delete pToDie;
}
/********************************************************************************************
Summary: Sets the singleton to be destroyed
Parameters: [in] dest - The pointer of the singleton to be destroyed.
********************************************************************************************/
void setSingleton(T* dest)
{
pToDie = dest;
}
private:
T* pToDie;
};
#endif //__DESTROYER_H_
| true |
aeb66667ad5d1588c6258e9eca463c0b4436d88c
|
C++
|
ygalkin/coding-challenges
|
/src/leetcode/roman-to-integer.h
|
UTF-8
| 619 | 3.34375 | 3 |
[] |
no_license
|
// https://leetcode.com/problems/roman-to-integer/
class Solution {
private:
const unordered_map<char, int> _lookup_tbl = {
{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50},
{'C', 100}, {'D', 500}, {'M', 1000}
};
public:
int romanToInt(string& s) {
auto n{ 0 }; // result
int i{ 0 };
auto prev{ 0 };
auto curr{ 0 };
const size_t last = s.size() - 1;
for (i = last; i >= 0; --i) {
curr = _lookup_tbl.at(s[i]);
n = (i < last && curr < prev) ? n - curr : n + curr;
prev = curr;
}
return n;
}
};
| true |
9e8b1e56c422f6bde31ceb2fd3de6e0c3ba96b50
|
C++
|
ZeCroque/study-uppa
|
/L2/S2/POO/TP6/main.cpp
|
UTF-8
| 876 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
#include <iostream>
#include "adherents.h"
#include "oeuvre.h"
using namespace std;
int main()
{
Adherent moi("Croquefer", "Gaëtan", "140996", 21, "Louis Lacaze", "Pau", "64000", 16);
Adherents ad;
ad.addAdherent(moi);
ad.afficheAdherent(0);
Exemplaire exp1(1);
Exemplaire exp2(2);
Exemplaire exp3(3);
moi.addExemplaire(exp1);
moi.addExemplaire(exp2);
moi.addExemplaire(exp3);
for(int i=0; i<3; i++)
{
moi.afficheExemplaire(i);
}
Oeuvre o1("Titanic", "Il meurt à la fin");
cout<<o1;
OeuvreInterprete o2("Kermesse de Trifouillis-Les-Oies", "Un spectacle assez navrant", "CM2 B option ZEP");
cout<<o2;
OeuvreNonInterprete o3("Skyrim", "Le jeu qui te rend asocial");
cout<<o3;
CD c("Minutes to Midnight", "Album d'anthologie", "Linkin Park", 45);
cout<<c;
Livre l("Harry Potter", "Un chateux cheaté", 1458);
cout<<l;
return 0;
}
| true |
928815b885175fe847d49cb55257e1b20b7e2067
|
C++
|
junbrot/algorithm
|
/programmers/p42748.cpp
|
UTF-8
| 845 | 3.03125 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> solution(vector<int> array, vector<vector<int>> commands) {
vector<int> answer;
for(int i=0; i<commands.size();i++)
{
vector<int> temp;
for(int j=commands[i][0]-1; j<commands[i][1]; j++)
temp.push_back(array[j]);
sort(temp.begin(),temp.end());
answer.push_back(temp[commands[i][2]-1]);
}
return answer;
}
int main() {
int N;
scanf("%d",&N);
vector<int> a(N,0);
for(int i=0; i<N; i++)
scanf("%d",&a[i]);
scanf("%d",&N);
vector<vector<int>> commands(N,vector<int>(3,0));
for(int i=0; i<N; i++)
scanf("%d %d %d",&commands[i][0],&commands[i][1],&commands[i][2]);
vector<int> sol = solution(a,commands);
printf("%d %d %d\n",sol[0],sol[1],sol[2]);
return 0;
}
| true |
3c7142c3528f50ada11583c6d4441ca8351f92a5
|
C++
|
kohlerricardo/simulator
|
/main_memory/memory_controller.hpp
|
UTF-8
| 1,492 | 2.59375 | 3 |
[] |
no_license
|
#ifndef MEMORY_CONTROLLER_H
#define MEMORY_CONTROLLER_H
class memory_controller_t{
private:
uint64_t requests_made; //Data Requests made
uint64_t operations_executed; // number of operations executed
uint64_t requests_emc; //Data Requests made to DRAM
uint64_t requests_llc; //Data Requests made to LLC
public:
// ==========================================================================
// Memory Controller Atributes
// ==========================================================================
emc_t *emc;
uint8_t emc_active;
cache_t *data_cache;
// ==========================================================================
// Memory Controller Methods
// ==========================================================================
void allocate(); //Aloca recursos do Memory Controller
// ==========================================================================
memory_controller_t();
~memory_controller_t();
void clock();
void statistics();
//statistiscs methods
INSTANTIATE_GET_SET_ADD(uint64_t,requests_made)
INSTANTIATE_GET_SET_ADD(uint64_t,operations_executed)
INSTANTIATE_GET_SET_ADD(uint64_t,requests_emc)
INSTANTIATE_GET_SET_ADD(uint64_t,requests_llc)
//request DRAM data
uint64_t requestDRAM();
};
#endif // MEMORY_CONTROLLER_H
| true |
38a50b33e7ac91459a46309e3b9857ea6272b16d
|
C++
|
nathaniel-mohr/undergrad_coursework
|
/CS162/labs/lab7/shape.h
|
UTF-8
| 316 | 2.96875 | 3 |
[] |
no_license
|
#ifndef SHAPE_H
#define SHAPE_H
#include <string>
#include <iostream>
using namespace std;
class Shape{
protected:
string name;
string color;
public:
string get_name() const;
string get_color() const;
void set_name(string);
void set_color(string);
virtual float calculate_area() = 0;
};
#endif
| true |
3d30c590dc9ff6329ff2cdf7733cc46cd801863b
|
C++
|
MartinTownley/ampify-placement-p1
|
/source/resultChecker.h
|
UTF-8
| 2,109 | 3.546875 | 4 |
[] |
no_license
|
//
// resultChecker.h
// Calculator
//
// Created by sierra on 18/02/2021.
//
#pragma once
#ifndef resultChecker_h
#define resultChecker_h
#include "calculator.h"
/* The following function constitutes one solution
to the std::abs error (see README for details)
*/
double ABS (double input)
{
return input < 0 ? -(input) : input;
}
class ResultChecker
{
public:
static void check (double value, double expected, double range = 1e-3)
{
// If <cmath> is permitted (see README):
return assert (std::abs (value - expected) <= range);
// -------
// If <cmath> is not permitted (see README):
//return assert (ABS (value - expected) <= range);
}
};
void test ()
{
auto result = Tokeniser ().tokenise ("6 * 9");
assert (result.has_value ());
ResultChecker::check (result->lhs, 6);
ResultChecker::check (result->rhs, 9);
assert (result->type == Tokeniser::Type::multiply);
result = Tokeniser ().tokenise ("6 + 9");
assert (result.has_value ());
ResultChecker::check (result->lhs, 6);
ResultChecker::check (result->rhs, 9);
assert (result->type == Tokeniser::Type::add);
result = Tokeniser ().tokenise ("25 - 4");
assert (result.has_value ());
ResultChecker::check (result->lhs, 25);
ResultChecker::check (result->rhs, 4);
assert (result->type == Tokeniser::Type::subtract);
result = Tokeniser ().tokenise ("32 / 8");
assert (result.has_value ());
ResultChecker::check (result->lhs, 32);
ResultChecker::check (result->rhs, 8);
assert (result->type == Tokeniser::Type::divide);
ResultChecker::check (Calculator ().calculate ({ 10, 4, Tokeniser::Type::multiply }), 40);
ResultChecker::check (Calculator ().calculate ({ 25.3, 18.6, Tokeniser::Type::add }), 43.9);
ResultChecker::check (Calculator ().calculate ({ 3, 5.6, Tokeniser::Type::subtract }), -2.6);
ResultChecker::check (Calculator ().calculate ({ 18, 6, Tokeniser::Type::divide }), 3);
std::cout << "Tests passed!" << std::endl;
}
#endif /* resultChecker_h */
| true |
43faf61ca605608efade7be72179673cb1f82bfd
|
C++
|
nvs-abhilash/OSNtrust
|
/CST/partition.cpp
|
UTF-8
| 3,264 | 2.828125 | 3 |
[] |
no_license
|
#include <iostream>
#include <fstream>
#include <string.h>
#include "graph.h"
#include "tree.h"
#include <bits/stdc++.h>
#include <vector>
const char FILE_NAME[] = "CST_out.bin";
int *partHash;
int *part;
// Compares two intervals according to staring times.
bool compare(Node i1, Node i2)
{
return ((i1.edgeWeight)/(i1.nodeWeight) < (i2.edgeWeight) / (i2.nodeWeight));
}
void sortAmortized (std::vector<Node> &CST, int k)
{
sort(CST.begin(), CST.end(), compare);
//Hash partition
partHash = new int[(int)CST.size()] ();
part = new int[k] ();
}
/*
* @params: CST node array, node id(whose subtree contains the child node) and the child node id
* @returns: edge-cut cost
*/
void unPropagate (std::vector<Node> &CST, int nodeWeight, int nodeId)
{
int i;
while(nodeId != HEAD_PARENT_ID)
{
for(i = 0; i < (int)CST.size(); i++)
{
if(CST[i].userId == nodeId)
{
CST[i].nodeWeight -= nodeWeight;
nodeId = CST[i].parentUserId;
break;
}
}
}
}
int getSuitableNode (std::vector<Node> &CST, int partSize)
{
for(std::vector<int>::size_type i = 0; i != CST.size(); i++)
if (partHash[i] == 0 && CST[i].nodeWeight <= partSize && CST[i].userId != HEAD_USER_ID)
return i;
return -1;
}
void assignPart (std::vector<Node> &CST, int nodeIdx, int currPart)
{
partHash[nodeIdx] = currPart;
if(CST[nodeIdx].nodeWeight == 1)
return;
for(std::vector<int>::size_type i = 0; i != CST.size(); i++)
{
if ((CST[i].parentUserId == CST[nodeIdx].userId) && partHash[i] == 0)
{
assignPart (CST, i, currPart);
}
}
}
void partitionGraph (std::vector<Node> &CST, int k)
{
int currPart = 1;
int partSize = ceil ((CST.size() - 1) / (float) k);
int threshold = ceil (partSize / (float) 2);
int nodeIdx = -1;
while(true)
{
currPart = 1;
nodeIdx = -1;
while(nodeIdx == -1)
{
if(part[currPart - 1] >= threshold)
nodeIdx = -1;
else
nodeIdx = getSuitableNode (CST, partSize - part[currPart - 1]);
if(nodeIdx != -1)
break;
currPart ++;
if(currPart > k)
{
//Place rem nodes
for (std::vector<int>::size_type i = 0; i != CST.size(); i++)
{
if (partHash[i] == 0 && CST[i].userId != HEAD_USER_ID)
{
partHash[i] = k;//last partition
}
}
return;
}
}
part[currPart - 1] += CST[nodeIdx].nodeWeight;
assignPart (CST, nodeIdx, currPart);
unPropagate (CST, CST[nodeIdx].nodeWeight, CST[nodeIdx].parentUserId);
}
}
void writePartition (std::vector<Node> &CST, int k)
{
std::ofstream *fPtr = new std::ofstream[k];
char **fileName = new char *[k];
for (int i = 0; i < k; i++)
fileName[i] = new char[50];
for (int i = 0; i < k; i++)
{
sprintf (fileName[i], "part_%d.txt", i + 1);
fPtr[i].open (fileName[i], std::ios::out);
}
for (std::vector<int>::size_type i = 0; i != CST.size(); i++)
{
if (partHash[i] >= 1 && partHash[i] <= k)
fPtr[partHash[i] - 1] << CST[i].userId << std::endl;
}
for (int i = 0; i < k; i++)
fPtr[i].close();
for (int i = 0; i < k; i++)
delete[] fileName[i];
delete[] fileName;
delete[] fPtr;
}
| true |
0861600ec12e87919cb6daac210df793cdcd4590
|
C++
|
eXpliCo/SimCraft
|
/Source/GraphicsEngine/Text.cpp
|
UTF-8
| 318 | 2.65625 | 3 |
[] |
no_license
|
#include "Text.h"
Text::Text(string text, D3DXVECTOR2 position, float size)
{
this->text = text;
this->position = position;
this->size = size;
this->font.texture = NULL;
for(int i = 0; i < 256; i++)
this->font.charTexCoords[i] = 0;
}
Text::~Text()
{
if(this->font.texture)
this->font.texture->Release();
}
| true |
896c0c85f19d2aae0bdea9a0db5823729a60382c
|
C++
|
daveying/learn-algorithm
|
/linked-list.h
|
UTF-8
| 4,498 | 3.875 | 4 |
[] |
no_license
|
#ifndef DDLINKED_LIST_H
#define DDLINKED_LIST_H
#include <functional>
template<class T>
class LinkedListNode {
public:
T data;
LinkedListNode<T>* next;
LinkedListNode() : next(nullptr) {}
LinkedListNode(T data, LinkedListNode<T>* next = nullptr) : data(data), next(next) {}
~LinkedListNode();
};
template<typename T>
LinkedListNode<T>::~LinkedListNode() {
delete next;
}
template<class T>
class LinkedList {
private:
LinkedListNode<T>* dummyHead;
int count;
public:
LinkedList();
~LinkedList();
bool isEmpty();
bool isLast(LinkedListNode<T>* node);
int length();
// find index of a node with specified value, -1 will returned if the node doesn't exist
// NOTE: the returned index may become invalid after any node insert/delete operation
int find(LinkedListNode<T> target);
int find(T target);
// retrieve the pointer which point to the node indexed by index
// NOTE: the index of node which the returned pointer point to may change after any node insert/add/delete operation
LinkedListNode<T>* retrieve(int index);
// insert a node to position index, and move all node behind one step back
// i.e. if index set to zero, the new node will be first node
// this function cannot append a node, if you want to do that, use add()
void insert(T data, int index);
void insert(LinkedListNode<T>* node, int index);
// add a node back to the linked list
void add(T data);
// traverse through all node of the linked list, and for each node call provided function
// first int value in callback function is index of the node, and second value is the value of the node
void traverse(std::function<void(int, T)> callback);
void traverse(std::function<void(int, LinkedListNode<T>* node)> callback);
};
template<typename T>
LinkedList<T>::LinkedList() {
dummyHead = new LinkedListNode<T>();
count = 0;
}
template<typename T>
LinkedList<T>::~LinkedList() {
LinkedListNode<T>* p = dummyHead->next;
while (p) {
LinkedListNode<T>* temp = p->next;
delete p;
p = temp;
}
}
template<typename T>
bool LinkedList<T>::isEmpty() {
return dummyHead->next == nullptr;
}
template<typename T>
bool LinkedList<T>::isLast(LinkedListNode<T>* node) {
return node->next == nullptr;
}
template<typename T>
int LinkedList<T>::length() {
return count;
}
template<typename T>
int LinkedList<T>::find(LinkedListNode<T> target) {
return find(target.data);
}
template<typename T>
int LinkedList<T>::find(T target) {
int index = 0;
bool flag = false;
LinkedListNode<T>* p = dummyHead->next;
while(p) {
if (target == p->data) {
flag = true;
break;
}
index++;
}
return flag ? index : -1;
}
template<typename T>
LinkedListNode<T>* LinkedList<T>::retrieve(int index) {
if (index >= count || index < 0) {
return nullptr;
}
LinkedListNode<T>* p = dummyHead->next;
int i = 0;
while(p) {
if ( index == i) {
return p;
}
p = p->next;
i++;
}
return nullptr;
}
template<typename T>
void LinkedList<T>::insert(T data, int index) {
if (index >= count || index < 0) return;
LinkedListNode<T>* nodePrev;
if (index == 0) {
nodePrev = dummyHead;
} else {
nodePrev = retrieve(index - 1);
}
LinkedListNode<T>* newNode = new LinkedListNode<T>(data);
newNode->next = nodePrev->next;
nodePrev->next = newNode;
count++;
}
template<typename T>
void LinkedList<T>::insert(LinkedListNode<T>* node, int index) {
insert(node->data, index);
}
template<typename T>
void LinkedList<T>::add(T data) {
LinkedListNode<T>* last;
if (isEmpty()) {
last = dummyHead;
} else {
last = retrieve(count - 1);
}
LinkedListNode<T>* newNode = new LinkedListNode<T>(data);
last->next = newNode;
count++;
}
template<typename T>
void LinkedList<T>::traverse(std::function<void(int, T)> callback) {
LinkedListNode<T>* p = dummyHead->next;
int index = 0;
while(p) {
callback(index, p->data);
index++;
p = p->next;
}
}
template<typename T>
void LinkedList<T>::traverse(std::function<void(int, LinkedListNode<T>* node)> callback) {
LinkedListNode<T>* p = dummyHead->next;
int index = 0;
while(p) {
callback(index, p);
index++;
p = p->next;
}
}
#endif
| true |
13cb075e23b8d1c07a693e72c36b2d313d249e43
|
C++
|
Sumanzaheer/ComplexNumber
|
/header.h
|
UTF-8
| 2,074 | 3.75 | 4 |
[] |
no_license
|
#include<iostream>
#include<cmath>
using namespace std;
class ComplexNum
{
private:
double real;
double imaginary;
public:
ComplexNum()
{
this->real=0.0;
this->imaginary=0.0;
}
ComplexNum(double r, double i)
{
this->real=r;
this->imaginary=i;
}
ComplexNum(ComplexNum& copy)
{
this->real=copy.real;
this->imaginary=copy.imaginary;
}
double getreal()
{
return this->real;
}
double getimaginary()
{
return this->imaginary;
}
void set(int re,int img)
{
this->real=re;
this->imaginary=img;
}
ComplexNum add(ComplexNum a)
{
ComplexNum result(this->real+a.real , this->imaginary+a.imaginary);
return result;
}
ComplexNum sub(ComplexNum b)
{
ComplexNum result(this->real-b.real , this->imaginary-b.imaginary);
return result;
}
ComplexNum conjugate()
{
ComplexNum c(this->real,this->imaginary*-1);
return c;
}
ComplexNum modulus()
{
double mod= (sqrt(pow(this->real,2) + pow(this->imaginary,2)));
}
ComplexNum operator + (ComplexNum z)
{
ComplexNum z1(this->real+z.real,this->imaginary+z.imaginary);
return z1;
}
ComplexNum operator - (ComplexNum z)
{
ComplexNum z2(this->real-z.real,this->imaginary-z.imaginary);
return z2;
}
ComplexNum operator * (ComplexNum z)
{
ComplexNum z3(this->real*z.real - this->imaginary*z.imaginary , this->real*z.imaginary + this->imaginary*z.real);
return z3;
}
ComplexNum operator / (ComplexNum z)
{
double a = this->real;
double b = this->imaginary;
double c = z.real;
double d = z.imaginary;
ComplexNum z4((a*c + b * d) / (pow(c, 2) + pow(d, 2)), (b*c - a * d) / (pow(c, 2) + pow(d, 2)));
return z4;
}
void Display()
{
// cout << "I am a Complex number"<< endl<<" ";
cout << this->real<< "+" <<this->imaginary<< "i"<<endl;
}
};
ostream& operator<<(ostream& o,ComplexNum z)
{
return o <<z.getreal()<<","<<z.getimaginary()<<"i"<<endl;
}
| true |
d1afa77c618a8d45829c9fd374b4909ba59d5669
|
C++
|
sridharreddy7/Algos
|
/ekt.cpp
|
UTF-8
| 1,079 | 2.828125 | 3 |
[] |
no_license
|
#include <utility>
#include <stdio.h>
#include <iostream>
#include <map>
#include <algorithm>
using namespace std;
int main(){
string str1, str2;
long long int wgt;
map<string, long long int> map1;
map<string, long long int>map2;
map<string, string>map3;
map<long long int, string>map4;
long long int n,m;
cin>>n;
while(n--){
cin>>str1>>str2>>wgt;
map1.insert( pair<string,long long int>(str1,wgt));
map2.insert( pair<string,long long int>(str2,wgt));
map4.insert( pair<long long int, string>(wgt, str2));
map3.insert( pair<string, string>(str1,str2));
}
cin>>m;
long long int a[100000];
long long int len=0;
while(m--){
string s;
cin>>s;
if(map1.count(s)>0){
a[len]=map1.find(s)->second;
len++;
}
}
sort(a, a+len, greater<long long int>());
for(long long int j=0;j<len;j++){
// std::map<string, long long int>::const_iterator it;
// for(it = map2.begin(); it!=map2.end();++it){
// if(it->second == a[j]){
// cout<<it->first<<" ";
// continue;
// }
// }
cout<<map4.find(a[j])->second<<" ";
}
return 0;
}
| true |
b44505ab4de4551b1485384267dcbf8ca7d36694
|
C++
|
ehsanpanahy/SocketUDP
|
/serverinterface.h
|
UTF-8
| 1,543 | 2.90625 | 3 |
[] |
no_license
|
#ifndef SERVERINTERFACE_H
#define SERVERINTERFACE_H
#include <string>
/**
* @brief An interface for Server infrastructure.
* @details This interface decouples the implementation of server infrastrucure
* from the underlying library(Unix, boost, win32,...). That way the user of the
* Server class does not need to be concerned about the platform which
* app is running in.
*/
class ServerInterface
{
public:
ServerInterface();
virtual ~ServerInterface();
virtual bool initServer() = 0;
virtual bool bindServer() = 0;
virtual void listenToClients(int backLog) = 0;
virtual bool acceptClient(std::string address, int port) = 0;
virtual bool writeToClient(std::string word,
std::string peerAddrees, int peerPort) = 0;
virtual bool readFromClient(std::string &read) = 0;
virtual bool closeServer() = 0;
std::string getServerAddress() const;
void setServerAddress(const std::string &value);
int getServerPort() const;
void setServerPort(int value);
int getSocketType() const;
void setSocketType(int value);
int getProtocol() const;
void setProtocol(int value);
uint16_t getBufferSize() const;
void setBufferSize(const uint16_t &value);
std::string getClientAddress() const;
int getClientPort() const;
protected:
std::string serverAddress;
int serverPort;
int SocketType;
int Protocol;
uint16_t bufferSize;
std::string clientAddress;
int clientPort;
};
#endif // SERVERINTERFACE_H
| true |
05bb2386302663e4fba1df3f65ca3010b1be6224
|
C++
|
ThreeInches/Total_review
|
/总复习/异常处理/异常处理/1异常的概念.cpp
|
GB18030
| 707 | 3.34375 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
//C++쳣ķʽһԼʱͿ׳쳣úֱӻӵĵ
//throwֵʱ׳һ쳣ͨthrowؼɵ
//catchͨcatchؼ쳣жcatchв
//trytryеĴʶض쳣һcatch
int main()
{
try
{
//ıʶ
}catch (ExceptionName e1)
{
//catch
}catch (ExceptionName e2)
{
//catch
}catch (ExceptionName eN)
{
//catch
}
system("pause");
return 0;
}
| true |
707f68dafc0b2e5772c51cfffec2091575fac059
|
C++
|
CosmicHunter/Various-Codes-in-C
|
/C-Codes/no of path.cpp
|
UTF-8
| 419 | 2.984375 | 3 |
[] |
no_license
|
#include<stdio.h>
int m;
void fun(int x,int y);
int ans=0;
int main(){
int i,j;
int n;
printf("Enter the no of rows");
scanf("%d",&n);
printf("enter the no of columns");
scanf("%d",&m);
fun(n,1);
printf("%d",ans);
}
void fun(int x,int y){
y>=1&&y<=m;
if(x==1&&y==m){
ans++;
return;
}
if(x>1)
fun(x-1,y);
if(y<m)
fun(x,y+1);
}
| true |
104b933136d03855b71899d4a7c00849910d32a9
|
C++
|
xelomit/advancedCpp
|
/assignment5/L5.1FileLockerRPN/fraction.h
|
UTF-8
| 2,099 | 2.984375 | 3 |
[] |
no_license
|
//
// Created by timo on 26.11.18.
//
#ifndef L5_1FILELOCKERRPN_FRACTION_H
#define L5_1FILELOCKERRPN_FRACTION_H
#include <iostream>
int gcf(int a, int b) {
return b == 0 ? a : gcf(b, a % b);
}
int lcm(int a, int b) {
return (a*b) / gcf(a, b);
}
class fraction {
int c;
int d;
public:
fraction(int cntr=0, int denom=1) : c(cntr), d(denom) {}
int get_counter() {
return c;
}
int get_denominator() {
return d;
}
fraction operator+(fraction b){
int denom = lcm(d, b.get_denominator());
int count = (c*denom/d) + (b.get_counter()*denom/b.get_denominator());
return fraction(count, denom);
}
fraction operator-(fraction b){
fraction subtrahend = fraction (0-b.get_counter(), b.get_denominator());
return subtrahend + (*this);
}
fraction operator*(fraction b) {
int f1 = gcf(c, b.get_denominator());
int f2 = gcf(b.get_counter(), d);
return fraction((c/f1) * (b.c/f2),
(d/f2) * (b.d/f1));
}
fraction operator/(fraction bRev) {
fraction b = fraction(bRev.get_denominator(), bRev.get_counter());
return (*this) * b;
}
bool operator<(const fraction b){
int dnm = lcm(d, b.d);
return c * dnm / d < b.c * dnm / b.d;
}
bool operator>(const fraction b){
int dnm = lcm(d, b.d);
return c * dnm / d > b.c * dnm / b.d;
}
friend std::ostream &operator<<(std::ostream &os, fraction f) {
os << '(' << f.get_counter() << '/' << f.get_denominator() << ')';
}
inline static void check_char(std::istream &is, char ch) {
char c;
is >> c;
if(c!=ch) {
is.putback(c);
is.setstate(std::ios::badbit);
}
}
friend std::istream &operator>>(std::istream &is, fraction &f) {
fraction g;
check_char(is, '('); is >> g.c;
check_char(is, '/'); is >> g.d;
check_char(is, ')');
if (is) f=g;
return is;
}
};
#endif //L5_1FILELOCKERRPN_FRACTION_H
| true |
b54d0ac616d8a63edfbaf0d8232ba334c6eb91dd
|
C++
|
srishti26/ray
|
/include/spotlight.h
|
UTF-8
| 1,539 | 2.828125 | 3 |
[] |
no_license
|
#ifndef RAY_SPOTLIGHT_H
#define RAY_SPOTLIGHT_H
#include "light.h"
#include "random.h"
class Spotlight : public Light {
public: /* Methods: */
Spotlight (const SceneSphere& sceneSphere, Colour intensity, const Point& p, const Vector& d, floating a)
: Light {sceneSphere, intensity, true, true}
, m_position {p}
, m_frame {d}
, m_cosAngle {clamp (cos (a), 0, 1)}
, m_emissionPdfW {1.0 / (2.0 * M_PI * (1.0 - m_cosAngle)) }
{ }
virtual IlluminateResult illuminate (Point pos) const override {
Vector direction = m_position - pos;
const floating distSqr = direction.sqrlength ();
const floating distance = std::sqrt (distSqr);
direction = direction / distance;
if (m_frame.normal().dot(-direction) < m_cosAngle)
return {};
return {intensity (), direction, distance, distSqr, m_emissionPdfW, 1.0};
}
virtual EmitResult emit () const override {
auto dir = Vector {0, 0, 0};
while (true) {
dir = sampleUniformHemisphere ().get ();
if (dir.z >= m_cosAngle)
break;
}
return {intensity (), m_position, m_frame.normal (), dir, m_emissionPdfW, 1.0, 1.0};
}
virtual RadianceResult radiance (Point, Vector) const override {
return {{0, 0, 0}, m_emissionPdfW, 1.0};
}
private: /* Fields: */
const Point m_position;
const Frame m_frame;
const floating m_cosAngle;
const floating m_emissionPdfW;
};
#endif
| true |
267a0b323720acb285277762c0cc258ecc5adaa7
|
C++
|
Kawser-nerd/CLCDSA
|
/Source Codes/AtCoder/arc051/C/715890.cpp
|
UTF-8
| 1,980 | 2.609375 | 3 |
[] |
no_license
|
#include <algorithm>
#include <cassert>
#include <cstdio>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <sstream>
#include <unordered_map>
#include <vector>
#define INF 1000000002486618624LL
#define MOD 1000000007
#define ALL(x) std::begin(x), std::end(x)
class log_t {
public:
log_t(double base) : base_(base), loga_(log(base)) {};
public:
double operator()(double x) const {
if (base_ == 1) {
return x;
}
else {
return log(x) / loga_;
}
};
private:
double base_;
double loga_;
};
class number_t {
public:
number_t(double xx, long long yy, int zz = 0) : x(xx), y(yy), z(zz) {};
public:
inline bool operator>(const number_t& a) const {
return x > a.x;
};
public:
double x;
long long y;
int z;
};
long long modpow(long long x, long long y)
{
long long p = 1;
for ( ; y; (x *= x) %= MOD, y >>= 1)
if (y & 1)
(p *= x) %= MOD;
return p;
}
int main(int argc, char** argv)
{
std::cin.tie(0);
std::ios_base::sync_with_stdio(0);
int N;
long long A, B, a[55];
std::cin >> N >> A >> B;
log_t loga(A);
int x = std::max((B - 55 * N) / N, 0LL);
long long M = modpow(A, x);
std::vector<number_t> aa;
for (int i = 0; i < N; i ++) {
std::cin >> a[i];
aa.emplace_back(loga(a[i]) + x, (a[i] * M) % MOD);
}
B -= x * N;
std::priority_queue<number_t, std::vector<number_t>, std::greater<number_t>> pq;
for (int i = 0; i < N; i ++)
pq.push(aa[i]);
for (int i = 0; i < B; i ++) {
number_t a = pq.top();
pq.pop();
pq.emplace(a.x + 1, (a.y * A) % MOD, a.z + 1);
}
while (! pq.empty()) {
number_t a = pq.top();
pq.pop();
std::cout << a.y << std::endl;
}
return 0;
}
| true |
fd9ca3d1db1f09547d163798ef952621aaf9faa1
|
C++
|
Chicaogo/WinCode
|
/刷题/一本通提高篇/第一部分/第一章 贪心算法/1.1活动安排.cpp
|
UTF-8
| 941 | 2.71875 | 3 |
[] |
no_license
|
//https://www.luogu.org/problemnew/show/U48369
#include<bits/stdc++.h>
using namespace std;
inline int read()
{
int x = 0,t = 1; char ch = getchar();
while(ch < '0' || ch > '9'){if(ch == '-') t = -1; ch = getchar();}
while(ch >= '0' && ch <= '9'){x = x*10 + ch - '0'; ch = getchar();}
return x*t;
}
struct edge{
int l,r;
bool operator < (const edge &a) const{
return r < a.r;
}
}num[1005];
int n,ans;
inline void init()
{
n = read();
for(int i = 1;i <= n;++i)
{
num[i].l = read();
num[i].r = read();
}
}
inline void greed()
{
sort(num+1,num+n+1);
int cnt = num[1].r;
for(int i = 2;i <= n;++i)
{
if(num[i].l >= cnt)
{
ans++;
cnt = num[i].r;
}
}
}
int main(int argc, char const *argv[])
{
init();
greed();
++ans;
cout << ans;
getchar();getchar();getchar();
return 0;
}
| true |
073b96f2339a3a30238127e295cf538ea5fb1491
|
C++
|
hannachoi24/Data_Structure
|
/termProject/project2(directionO).cpp
|
UTF-8
| 15,138 | 3.21875 | 3 |
[] |
no_license
|
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <map>
#include <iterator>
#include <vector>
#include <algorithm>
#include <cmath>
#include <time.h>
#define NUMBER 500
#define MAX_VTXS 5000
using namespace std;
class AdjMatGraph
{
protected:
int vertices[MAX_VTXS]; // 각 Vertex의 이름 (한 글자로...)
int **adj;
public:
AdjMatGraph()
{
adj = new int *[MAX_VTXS];
if (adj)
{
for (int i = 0; i < MAX_VTXS; i++)
{
adj[i] = new int[MAX_VTXS];
}
}
reset();
}
~AdjMatGraph() {}
int size; // 전체 Graph의 사이즈 (Vertex의 수)
int getVertex(int i) { return vertices[i]; }
int getEdge(int i, int j) { return adj[i][j]; }
int getEdge_count(int i, int j)
{
if (0 <= adj[i][j] && adj[i][j] <= 9999)
{
return adj[i][j];
}
else
{
return 0;
}
}
void setEdge(int i, int j, int val) { adj[i][j] = val; }
bool isEmpty() { return size == 0; }
bool isFull() { return size >= MAX_VTXS; }
void reset()
{
size = 0;
for (int i = 0; i < MAX_VTXS; i++)
{
for (int j = 0; j < MAX_VTXS; j++)
{
setEdge(i, j, 0);
}
}
}
void insertVertex(int name)
{
if (!isFull())
{
vertices[size++] = name;
}
else
{
std::cout << "Exceeding maximum number of vertices";
}
}
void insertEdge(int u, int v)
{
if (u < 0 || u >= size)
{
std::cout << "out of range";
exit(0);
}
setEdge(u, v, 1);
setEdge(v, u, 1);
} // 방향이 없는 그래프이기 때문에 양쪽 edge를 동시에 추가해 주어야 합니다.
void display()
{
std::cout << size << "\n";
for (int i = 0; i < size; i++)
{
std::cout << getVertex(i) << " ";
for (int j = 0; j < size; j++)
std::cout << getEdge(i, j) << " ";
std::cout << "\n";
}
}
void load(std::string filename)
{
std::ifstream ifs(filename);
std::string line;
std::getline(ifs, line);
std::cout << line << std::endl;
std::stringstream ls(line);
int n;
ls >> n;
for (int i = 0; i < n; i++)
{
std::getline(ifs, line);
int str;
int val;
std::stringstream ls(line);
ls >> str;
insertVertex(str);
for (int j = 0; j < n; j++)
{
ls >> val;
if (val != 0)
{
insertEdge(i, j);
}
}
}
ifs.close();
}
void store(std::string filename)
{
std::ofstream ofs(filename);
ofs << size << "\n";
for (int i = 0; i < size; i++)
{
ofs << getVertex(i) << " ";
for (int j = 0; j < size; j++)
ofs << getEdge(i, j) << " ";
ofs << "\n";
}
ofs.close();
}
};
#define INF 9999
class WGraph : public AdjMatGraph
{
public:
WGraph() {}
~WGraph() {}
bool hasEdge(int i, int j) { return (getEdge(i, j) < INF); }
void insertEdge(int u, int v, int weight)
{
if (weight >= INF)
{
weight = INF;
}
setEdge(u, v, weight);
}
void load(std::string filename)
{
std::ifstream ifs(filename);
std::string line;
std::getline(ifs, line);
std::cout << line << std::endl;
std::stringstream ls(line);
int n;
ls >> n;
for (int i = 0; i < n; i++)
{
std::getline(ifs, line);
int str;
int val;
std::stringstream ls(line);
ls >> str;
insertVertex(str);
for (int j = 0; j < n; j++)
{
ls >> val;
if (val != 0)
{
insertEdge(i, j, val);
}
}
}
ifs.close();
}
};
class RandomWalker
{
public:
int start;
int next;
int probability = 0;
int time;
RandomWalker() {}
RandomWalker(int start_, int time_)
{
start = start_;
time = time_;
}
~RandomWalker() {}
int setProb(int a, WGraph g)
{
int arr[MAX_VTXS] = {
0,
}; // 해당 노드의 행 성분
float prob[MAX_VTXS] = {
0,
}; // 해당 노드 행 성분이 걸릴 확률
int count = 0; // 해당 노드의 행 성분들의 합
////////////////////////////arr 배열 설정////////////////////////////
for (int i = 0; i < g.size; i++)
{
if (0 <= g.getEdge_count(a, i) && g.getEdge_count(a, i) < 9999)
{
count += g.getEdge_count(a, i);
arr[i] = g.getEdge_count(a, i);
} // 행 성분이 0~9998 일 경우 배열에 추가 및 count값 증가
// 행 성분이 0 인 경우는 간선(Edge)는 존재하나 가중치가 0인경우
else if (g.getEdge_count(a, i) == 9999)
{
arr[i] = g.getEdge_count(a, i);
} // 행 성분이 9999 (INF) 일 경우 배열에만 추가
// 행 성분이 9999 (INF) 인 경우는 간선(Edge)가 존재X
}
////////////////////////////////////////////////////////////////////
////////////////////////////prob 배열 설정///////////////////////////
//std:: cout <<"해당 노드의 count값 : " << count ;
for (int i = 0; i < g.size; i++)
{
if (0 <= arr[i] && arr[i] < 9999)
{
if (count == 0)
{
return -1;
}
float tmp = arr[i] / float(count);
prob[i] = round(tmp * 100) / 100; // 소수점 2자리까지 확률 표현
}
}
////////////////////////////////////////////////////////////////////
// std::cout << "해당 idx의 확률 배열 : ";
// for (int i = 0 ; i < g.size; i++){
// std::cout << prob[i] << " ";
// }
/////////////////////////////예외 처리///////////////////////////////
float check = 0;
for (int i = 0; i < g.size; i++)
{
check += prob[i];
}
// std::cout <<"해당 노드 확률 배열 : ";
// for (int i = 0 ; i < g.size; i++){
// std::cout << prob[i] <<" ";
// }
if (check == 0)
{ // 확률 배열의 합이 0인 경우 갈 곳이 없는 노드이기에 예외 처리
//std::cout <<"경로가 없습니다."<<std::endl;
return -1;
}
////////////////////////////////////////////////////////////////////
/////////////////////////////확률 계산///////////////////////////////
else
{ // 확률 배열의 합이 0이 아닌 경우 밑의 코드 시행
float random = (float)(rand() % 100) / 100; // 확률 0.00~0.99
//std::cout << random;
int match = 1;
int idx = 0;
float init = 0.00;
for (int i = 0; i < g.size; i++)
{
if (prob[i] == 0)
{
idx++;
}
else if (prob[i] != 0)
{
init += prob[i];
if (init >= random)
{
start = idx;
break;
}
else
{
idx++;
}
}
}
}
return 0;
}
};
////////////////////////일정시간마다 일정확률로 다른 node로 jump////////////////////////
int changeNode(int old_node, int graph_size)
{ // old_node = 현재 위치
int arr[4653] = {
0,
}; // tsv파일 source,target중 max의 값 + 1
std::string array1[2000]; // 임의로 설정
int array2[825]; // tsv파일의 line수 * 3 크기로 설정
int source[274]; // tsv파일의 line수 -1 크기로 설정
int target[274]; // tsv파일의 line수 -1 크기로 설정
int weight[274]; // tsv파일의 line수 -1 크기로 설정
std::string arr3[3];
std::ifstream fin("C:/Users/choihanna/Desktop/C++/Data_Structure/termProject/dataset/bicycle/bicycle_trips_over_100.tsv");
if (!fin)
{
std::cout << "파일 오픈 실패" << std::endl;
exit(100);
}
for (int i = 0; i < 825; i++)
{ // tsv파일의 line수 * 3 크기로 설정
fin >> array1[i];
//std::cout << array1[i] << " ";
}
for (int i = 3; i < 825; i++)
{ // tsv파일의 line수 * 3 크기로 설정
//std::cout << array1[i] << " ";
array2[i - 3] = stoi(array1[i]);
//std::cout << array2[i-3] << " ";
}
for (int i = 0; i < 274; i++)
{ // tsv파일의 line수 -1 크기로 설정
int r = i * 3;
int v = i * 3 + 1;
int z = i * 3 + 2;
source[i] = array2[r];
target[i] = array2[v];
weight[i] = array2[z];
}
int random = rand() % 274;
//std::cout << "새로운 노드: " << source[random];
return source[random];
}
/////////////////////////////////////////////////////////////////////////////////
///////////////////////////////pageRank함수 구현/////////////////////////////////
typedef std::pair<int, int> int_int_pair; // pair(해당노드 방문횟수, 노드 인덱스)
bool comparator(const int_int_pair &l, const int_int_pair &r)
{
return l.first > r.first;
}
void pageRank(RandomWalker rw, int *arr, std::vector<int_int_pair> A)
{
for (int i = 0; i < 4653; i++)
{ // 루프의 범위 : tsv파일 source,target중 max의 값 + 1
// tsv파일 source,target중 max의 값 + 1 = node의 갯수, 인접행렬의 size
A.push_back(int_int_pair(arr[i], i));
}
std::cout << "TOP3 최다 방문 노드 순서 출력 (0회 방문시 출력 X)" << std::endl;
stable_sort(A.begin(), A.end(), comparator);
for (int i = 0; i < 3; i++)
{ // TOP N번째까지 출력 설정
if (A[i].first == 0)
{ // 0회 방문했을 경우부터는 출력 X
break;
}
printf("%d번 노드 : %d번 방문\n", A[i].second, A[i].first);
}
}
////////////////////////////////////////////////////////////////////////////////
int main(void)
{
WGraph g;
g.load("graph.txt");
//g.display();
RandomWalker rw;
rw.start = 207; // start하는 노드 설정
rw.time = NUMBER; // 노드를 이동하는 횟수 설정
rw.next = rw.start;
int arr[4653] = {
0,
}; // tsv파일 source,target중 max의 값 + 1
std::vector<int_int_pair> A;
std::string array1[2000]; // 임의로 설정
int array2[825]; // tsv파일의 line수 * 3 크기로 설정
int source[274]; // tsv파일의 line수 -1 크기로 설정
int target[274]; // tsv파일의 line수 -1 크기로 설정
int weight[274]; // tsv파일의 line수 -1 크기로 설정
std::string arr3[3];
std::ifstream fin("C:/Users/choihanna/Desktop/C++/Data_Structure/termProject/dataset/bicycle/bicycle_trips_over_100.tsv");
if (!fin)
{
std::cout << "파일 오픈 실패" << std::endl;
exit(100);
}
///////////////////////////////tsv파일 읽어서 배열 저장/////////////////////////////////
for (int i = 0; i < 825; i++)
{ // tsv파일의 line수 * 3 크기로 설정
fin >> array1[i];
//std::cout << array1[i] << " ";
}
for (int i = 3; i < 825; i++)
{ // tsv파일의 line수 * 3 크기로 설정
//std::cout << array1[i] << " ";
array2[i - 3] = stoi(array1[i]);
//std::cout << array2[i-3] << " ";
}
for (int i = 0; i < 274; i++)
{ // tsv파일의 line수 -1 크기로 설정
int r = i * 3;
int v = i * 3 + 1;
int z = i * 3 + 2;
source[i] = array2[r];
target[i] = array2[v];
weight[i] = array2[z];
}
// for (int i = 0 ; i < 274; i++){ // tsv파일의 line수 -1 크기로 설정
// std::cout << target[i] << " ";
// }
//////////////////////////////////////////////////////////////////////////////////////
///////////max값(현재 사용X)/////////////
int max;
int max_source = source[0];
for (int i = 1; i < 274; i++)
{ // tsv파일의 line수 -1 크기로 설정
if (max_source < source[i])
{
max_source = source[i];
}
}
int max_target = target[0];
for (int i = 1; i < 274; i++)
{ // tsv파일의 line수 -1 크기로 설정
if (max_target < target[i])
{
max_target = target[i];
}
}
if (max_source >= max_target)
{
max = max_source;
}
if (max_source < max_target)
{
max = max_target;
}
//std::cout << "max값은 : "<<max; // max값 확인
// for (int i = 0 ; i < 274; i++){ // tsv파일의 line수 -1 크기로 설정
// std::cout << source[i] << " ";
// }
////////////////////////////////////////
/////////////////tsv파일로부터 저장한 배열로 그래프 생성////////////////////
WGraph h;
int graph_size = 0;
for (int i = 0; i < 4653; i++)
{
h.insertVertex(i);
graph_size++;
}
for (int i = 0; i < 274; i++)
{
h.insertEdge(source[i], target[i], weight[i]);
}
/////////////////////////////////////////////////////////////////////////
////////////////////////Random Walker함수 실행////////////////////////////
std::cout << rw.start << "->";
arr[rw.start]++;
srand((unsigned int)time(NULL)); // srand함수를 통해 난수 생성
for (int i = 0; i < rw.time; i++)
{
int k = i + 1;
rw.setProb(rw.start, h);
if (rw.setProb(rw.start, h) == -1)
{
std::cout << rw.start << std::endl
<< "더 이상 경로가 없습니다" << std::endl;
arr[rw.start]++;
break;
}
arr[rw.start]++;
if ((k % 3) == 0)
{
rw.start = changeNode(rw.start, graph_size);
rw.setProb(rw.start, h);
i++;
}
std::cout << rw.start << "->";
}
// for (int i = 0; i < 38; i++){
// std::cout<<arr[i]<<" ";
// }
// std::cout<<std::endl;
////////////////////////////////////////////////////////////////////////
pageRank(rw, arr, A);
return 0;
}
| true |
3db604dc68a004c052f7312333676c7b468ac874
|
C++
|
SerxLee/acm
|
/hlg/26-H.cpp
|
UTF-8
| 664 | 2.671875 | 3 |
[] |
no_license
|
#include <cstdio>
int main()
{
int n;
int i, j ,k;
scanf("%d", &n);
int a[105][105];
int max = 0, sum = 0;
for (i = 1; i <= n; ++i)
for (j = 1; j <= n; ++j)
scanf("%d", &a[i][j]);
for (i = 1; i <= n; i++){
for (k = 1; k < i; k++)
sum -= a[k][i];
for (j = i + 1; j <= n; ++j){
sum += a[i][j];
if (sum > max)
max = sum;
}
}
sum = 0;
for (i = n; i >= 1; i--){
for (k = n; k > i; k--)
sum -= a[k][i];
for (j = i - 1; j >= 1; j--){
sum += a[i][j];
if (sum > max)
max = sum;
}
}
if (max % 36 == 0) {
max = max / 36;
}else{
max = max / 36 + 1;
}
printf("%d\n", max);
return 0;
}
| true |
6212b3fdd4f2e0e2326125a2d4afbf6ffa682aa6
|
C++
|
noahaim/Ex3_b
|
/Main.cpp
|
UTF-8
| 1,359 | 2.96875 | 3 |
[
"MIT"
] |
permissive
|
#include <iostream>
#include <fstream>
// #include <sstream>
// #include <stdexcept>
using namespace std;
#include "NumberWithUnits.hpp"
using namespace ariel;
int main() {
ofstream Myunits_file;
Myunits_file.open("Myunits_file.txt");
Myunits_file<<"1 km = 1000 m"<<endl;
Myunits_file<<"1 m = 100 cm"<<endl;
Myunits_file<<"1 year = 12 month"<<endl;
Myunits_file<<"1 day = 24 hour"<<endl;
Myunits_file<<"1 hour = 60 min"<<endl;
Myunits_file<<"1 min = 60 sec"<<endl;
Myunits_file.close();
ifstream units_file{"Myunits_file.txt"};
NumberWithUnits::read_units(units_file);
cout<<"Enter 2 NumberWithUnits:"<<endl;
NumberWithUnits num1(1,"day");
NumberWithUnits num2(1,"day");
try{
cin>>num1>>num2;
cout<<num1<<"+"<<num2<<"="<<num1+num2<<endl;
cout<<num1<<"-"<<num2<<"="<<num1-num2<<endl;
cout<<num1<<"+="<<num2<<"="<<(num1+=num2)<<endl;
cout<<num1<<"-="<<num2<<"="<<(num1-=num2)<<endl;
cout<<num1<<"*"<<"2"<<"="<<(num1*2)<<endl;
cout<<"2"<<"*"<<num1<<"="<<(2*num1)<<endl;
cout<<"-"<<num2<<"="<<(-num2)<<endl;
cout<<"+"<<num1<<"="<<(+num1)<<endl;
cout<<num1<<"++"<<"="<<(num1++)<<endl;
cout<<num1<<"--"<<"="<<(num1--)<<endl;
cout<<"++"<<num1<<"="<<(++num1)<<endl;
cout<<"--"<<num1<<"="<<(--num1)<<endl;
}
catch (const std::exception& ex) {
cout << ex.what() << endl;
}
}
| true |
d61b7303536425e166ad0afdf9f68f4b81486066
|
C++
|
fonxsirax/Analysis-and-Project-of-Algorithms
|
/EditDistance/main.cpp
|
UTF-8
| 967 | 2.84375 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <stdlib.h>
#include <iostream>
using namespace std;
char a[2000];
char b[2000];
int n = 0;
int editDistance()
{
int table[strlen(a) + 1][strlen(b) + 1];
int minimun;
int aux1 = 0;
int aux2 = 0;
int aux3 = 0;
unsigned int i = 0;
for (i=0;i<=strlen(a);i++) {
table[i][0] = i;
}
unsigned int j = 0;
for (j=0;j<=strlen(b);j++) {
table[0][j] = j;
}
for (i=1;i<=strlen(a);i++) {
for (j = 1; j <= strlen(b); ++j) {
if (a[i - 1] == b[j - 1]) {
table[i][j] = table[i - 1][j - 1];
} else {
aux1 = min(table[i][j - 1],table[i - 1][j]);
aux2 = min(table[i][j - 1],table[i - 1][j - 1]);
minimun = min(aux1,aux2);
table[i][j] = 1 + minimun;
}
}
}
aux3 = table[strlen(a)][strlen(b)];
return aux3;
}
int main()
{
int T;
cin>>T;
while (T >0) {
scanf("%s", a);
scanf("%s", b);
n = editDistance();
cout<<n<<endl;
T--;
}
return 0;
}
| true |
511d12e774c0b9192abb25f3ce92644ce3f1eac6
|
C++
|
LoyieKing/anNESlie
|
/anNESlie/Emulator/CPU/Instruction.cpp
|
UTF-8
| 5,616 | 2.5625 | 3 |
[] |
no_license
|
#pragma once
#include "CPU.h"
void CPU::JSR()
{
PushWord(Register.PC + 1);
Register.PC = NextWord();
}
void CPU::RTI()
{
NextByte();
Register.setP(Pop());
Register.PC = PopWord();
}
void CPU::RTS()
{
NextByte();
Register.PC = PopWord() + 1;
}
void CPU::INY()
{
Register.setY(Register.getY() + 1);
}
void CPU::DEY()
{
Register.setY(Register.getY() - 1);
}
void CPU::INX()
{
Register.setX(Register.getX() + 1);
}
void CPU::DEX()
{
Register.setX(Register.getX() - 1);
}
void CPU::TAY()
{
Register.setY(Register.getA());
}
void CPU::TYA()
{
Register.setA(Register.getY());
}
void CPU::TAX()
{
Register.setX(Register.getA());
}
void CPU::TXA()
{
Register.setA(Register.getX());
}
void CPU::TSX()
{
Register.setX(Register.SP);
}
void CPU::TXS()
{
Register.SP = Register.getX();
}
void CPU::PHP()
{
Push(Register.P.BreakSource ? Register.BreakSourceBit : 0);
}
void CPU::PLP()
{
Register.setP(Pop() & ~Register.BreakSourceBit);
}
void CPU::PLA()
{
Register.setA(Pop());
}
void CPU::PHA()
{
Push(Register.getA());
}
void CPU::BIT()
{
Word val = AddressRead();
Register.P.Overflow = ((val & 0x40) > 0);
Register.P.Zero = ((val & Register.getA()) == 0);
Register.P.Negative = ((val & 0x80) > 0);
}
void CPU::JMP()
{
if (currentInstruction == 0x4C)
Register.PC = NextWord();
else if (currentInstruction == 0x6C)
{
Word off = NextWord();
Word hi = (off & 0xFF) == 0xFF ? off - 0xFF : off + 1;
Word oldPC = Register.PC;
Register.PC = (ReadByte(off) | ReadByte(hi) << 8);
if ((oldPC & 0xFF00) != (Register.PC & 0xFF00))
cycle += 2;
}
}
void CPU::BCS()
{
Branch(Register.P.Carry);
}
void CPU::BCC()
{
Branch(!Register.P.Carry);
}
void CPU::BEQ()
{
Branch(Register.P.Zero);
}
void CPU::BNE()
{
Branch(!Register.P.Zero);
}
void CPU::BVS()
{
Branch(Register.P.Overflow);
}
void CPU::BVC()
{
Branch(!Register.P.Overflow);
}
void CPU::BPL()
{
Branch(!Register.P.Negative);
}
void CPU::BMI()
{
Branch(Register.P.Negative);
}
void CPU::STA()
{
AddressWrite(Register.getA());
}
void CPU::STX()
{
AddressWrite(Register.getX());
}
void CPU::STY()
{
AddressWrite(Register.getY());
}
void CPU::CLC()
{
Register.P.Carry = false;
}
void CPU::SEC()
{
Register.P.Carry = true;
}
void CPU::CLI()
{
Register.P.InterruptDisabled = false;
}
void CPU::SEI()
{
Register.P.InterruptDisabled = true;
}
void CPU::CLV()
{
Register.P.Overflow = false;
}
void CPU::CLD()
{
Register.P.DecimalMode = false;
}
void CPU::SED()
{
Register.P.DecimalMode = true;
}
void CPU::NOP()
{
}
void CPU::LDA()
{
Register.setA(AddressRead());
}
void CPU::LDY()
{
Register.setY(AddressRead());
}
void CPU::LDX()
{
Register.setX(AddressRead());
}
void CPU::ORA()
{
Register.setA(Register.getA() | AddressRead());
}
void CPU::AND()
{
Register.setA(Register.getA() & AddressRead());
}
void CPU::EOR()
{
Register.setA(Register.getA() ^ AddressRead());
}
void CPU::SBC()
{
ADCImpl((Byte)~AddressRead());
}
void CPU::ADC()
{
ADCImpl(AddressRead());
}
void CPU::BRK()
{
NextByte();
Push( Register.getP() | Register.BreakSourceBit);
Register.P.InterruptDisabled = true;
Register.PC = ReadByte(0xFFFE) | ReadByte(0xFFFF) << 8;
}
void CPU::CMP()
{
CMPImpl(Register.getA());
}
void CPU::CPX()
{
CMPImpl(Register.getX());
}
void CPU::CPY()
{
CMPImpl(Register.getY());
}
// HACK: Word D = AdressRead(); END LINE 262
void CPU::LSR()
{
Byte D = AddressRead();
Register.P.Carry = (D & 0x1) > 0;
D >>= 1;
Register.setFlagNZ(D);
AddressWrite(D);
}
void CPU::ASL()
{
Byte D = AddressRead();
Register.P.Carry = (D & 0x80) > 0;
D <<= 1;
Register.setFlagNZ(D);
AddressWrite(D);
}
void CPU::ROR()
{
Byte D = AddressRead();
bool c = Register.P.Carry;
Register.P.Carry = (D & 0x1) > 0;
D >>= 1;
if (c)
D |= 0x80;
Register.setFlagNZ(D);
AddressWrite(D);
}
void CPU::ROL()
{
Byte D = AddressRead();
bool c = Register.P.Carry;
Register.P.Carry = (D & 0x80) > 0;
D <<= 1;
if (c)
D |= 0x1;
Register.setFlagNZ(D);
AddressWrite(D);
}
void CPU::INC()
{
Byte D = (Byte)(AddressRead() + 1);
Register.setFlagNZ(D);
AddressWrite(D);
}
void CPU::DEC()
{
Byte D = (Byte)(AddressRead() - 1);
Register.setFlagNZ(D);
AddressWrite(D);
}
//unofficial opcodes
void CPU::SKB()
{
NextByte();
}
void CPU::ANC()
{
Register.setA(Register.getA() & AddressRead());
Register.P.Carry = Register.P.Negative;
}
void CPU::ALR()
{
Register.setA(Register.getA() & AddressRead());
Register.P.Carry = (Register.getA() & 0x1) > 0;
Register.setA(Register.getA() >> 1);
Register.setFlagNZ(Register.getA());
}
void CPU::ARR()
{
Register.setA(Register.getA() & AddressRead());
bool c = Register.P.Carry;
Register.P.Carry = (Register.getA() & 0x1) > 0;
Register.setA(Register.getA() >> 1);
if (c)
{
Register.setA(Register.getA() | 0x80);
}
Register.setFlagNZ(Register.getA());
}
void CPU::ATX()
{
Register.setA(Register.getA() | ReadByte(0xEE));
Register.setA(Register.getA() & AddressRead());
Register.setX(Register.getA());
}
void CPU::Branch(bool cond)
{
// WARN: DO NOT! use NextByte() here, it will cause a compile error
Word nPC = Register.PC + (SByte)ReadByte(Register.PC) + 1;
Register.PC++;
if (cond)
{
Register.PC = nPC;
cycle++;
}
}
void CPU::ADCImpl(Byte val)
{
int nA = (SByte)Register.getA() + (SByte)val + (SByte)(Register.P.Carry ? 1 : 0);
Register.P.Overflow = nA < -128 || nA > 127;
Register.P.Carry = (Register.getA() + val + (Byte)(Register.P.Carry ? 1 : 0)) > 0xFF;
Register.setA(nA & 0xFF);
}
void CPU::CMPImpl(Byte reg)
{
short d = reg - AddressRead();
Register.P.Negative = (d & 0x80) > 0 && d != 0;
Register.P.Carry = d >= 0;
Register.P.Zero = d == 0;
}
| true |
afd32fccb76e4feb43bc4126d714a19e32ffb2f2
|
C++
|
agudeloandres/C_Struct_Files
|
/C_Tutorships/OOP_C/CAP6/P90.CPP
|
UTF-8
| 152 | 2.90625 | 3 |
[] |
no_license
|
#include "iostream.h"
int x,y;
int &F(int &y) {
y = 3;
return x;
}
main() {
int &F(int &);
F(y) = 100;
cout << x << endl;
cout << y << endl;
}
| true |
1b1383def6855d61837e61b9881ddcbdde26e211
|
C++
|
ivanhu42/p
|
/codeforces/cpp/534a.cpp
|
UTF-8
| 685 | 2.5625 | 3 |
[] |
no_license
|
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <iomanip>
using namespace std;
typedef long double db;
typedef long long ll;
int main()
{
int n, i = 1;
cin >> n;
if (n == 1)
cout << "1\n1" << endl;
else if (n == 2)
cout << "1\n1" << endl;
else if (n == 3)
cout << "2\n1 3" << endl;
else if (n == 4)
cout << "4\n3 1 4 2" << endl;
else
{
cout << n << endl;
while (i <= n)
{
cout << i << " ";
i += 2;
}
i = 2;
while (i <= n)
{
cout << i << " ";
i += 2;
}
cout << endl;
}
return 0;
}
| true |
61e90a64ab096d7f3139c57f191865dde4f146a9
|
C++
|
aalok-sathe/cs301-prog2
|
/MachLangParser.cpp
|
UTF-8
| 13,759 | 3.34375 | 3 |
[] |
no_license
|
// aalok sathe
#include "MachLangParser.h"
/*
* Public class methods go here
*/
MachLangParser::MachLangParser(string inputfile)
// Default constructor for the MachLangParser class.
// Initializes using a string filename of an input file,
// and processes each line in that input file to decode
// the binary and assemble an assembly instruction.
//
// Parameters:
// string inputfile := path of inputfile relative to
// current directory
{
// initialize private variables 'myFormatCorrect' and 'myIndex'
myFormatCorrect = true;
myIndex = 0;
// Initialize 'Instruction' to store decoded instruction
Instruction i;
// open input filestream for reading
ifstream in;
in.open(inputfile.c_str());
// if failed to open the file for reading, stop
if (in.bad())
{
myFormatCorrect = false;
return;
}
// process for each line in the file
string line;
while (getline(in, line))
{
// make sure the line meets basic format requirements
// such as length and valid characters
if (not isLineCorrect(line))
{
myFormatCorrect = false;
break;
}
i.setEncoding(line);
// call the 'decode' method that splits the string
// into relevant pieces
decode(i);
// check if the instruction is supported
if (i.getOpcode() == UNDEFINED)
{
myFormatCorrect = false;
break;
}
// call the 'encode' method to put together
// the assembly syntax
assemble(i);
// store instructions in private container
// after processing them
myInstructions.push_back(i);
}
}
MachLangParser::~MachLangParser()
// Default deconstructor for the MachLangParser class
{}
Instruction MachLangParser::getNextInstruction()
// Method that returns the next instruction using a
// private 'myIndex' index variable
// If index is greater than the size of our container,
// return an empty/default 'Instruction' object whose
// opcode is equivalent to UNDEFINED
{
if (myIndex < (int)(myInstructions.size()))
return myInstructions[myIndex++];
Instruction i;
return i;
}
bool MachLangParser::isLineCorrect(string line)
// takes in an input binary line and
// checks to see if each of these conditions is matched:
// 1. length == ARCH_NUM_BITS
// 2. contains only 1s and 0s
//
// Parameters:
// string line := input line in binary that is
// a machine instruction
{
// check if line has appropriate length
if (line.length() != ARCH_NUM_BITS)
return false;
// check if line contains only 1s and 0s only
for (int i = 0; i < (int)line.length(); i++)
if (line[i] != '0' and line[i] != '1')
return false;
return true;
}
void MachLangParser::decode(Instruction& i)
// a method that takes in an Instruction object i by
// reference, with an initialized encoding field that
// is a binary string, and decodes it to figure out
// its opcode, and registers, imm, shamt, and funct field,
// as applicable
//
// Parameters:
// Instruction i := the instruction whose fields need to be
// initialized to their respective values
// based on machine code encoding
{
string opc = i.getEncoding().substr(0, OPCODE_LEN);
string funct = i.getEncoding().substr(
ARCH_NUM_BITS-OPCODE_LEN,
OPCODE_LEN
);
Opcode instOpcode = opcodes.getInstr(opc, funct);
InstType type = opcodes.getInstType(instOpcode);
if (type == RTYPE)
decodeRType(i);
else if (type == ITYPE)
decodeIType(i);
else // type == JTYPE
decodeJType(i);
}
void MachLangParser::decodeRType(Instruction& i)
// a decode helper method specific to R-type instructions
//
// Parameters:
// Instruction i := the instruction whose fields need to be
// initialized to their respective values
// based on machine code encoding
{
// start with the binary string
string encoding = i.getEncoding();
// figure out the various field and operands according
// to their known order, and pre-specified lengths
int index = 0;
string opstr = encoding.substr(index, OPCODE_LEN);
index += OPCODE_LEN;
string rs = encoding.substr(index, REG_WIDTH);
index += REG_WIDTH;
string rt = encoding.substr(index, REG_WIDTH);
index += REG_WIDTH;
string rd = encoding.substr(index, REG_WIDTH);
index += REG_WIDTH;
string shamt = encoding.substr(index, SHAMT_LEN);
index += SHAMT_LEN;
string funct = encoding.substr(index, FUNCT_LEN);
Opcode opc = opcodes.getInstr(opstr, funct);
// set the appropriate values of the instruction
// and pass 'NumRegisters' to the places that are
// not applicable
i.setValues(
opc,
convertToInt(rs, UNSIGNED),
convertToInt(rt, UNSIGNED),
convertToInt(rd, UNSIGNED),
convertToInt(shamt, UNSIGNED)
);
}
void MachLangParser::decodeIType(Instruction& i)
// a decode helper method specific to I-type instructions
//
// Parameters:
// Instruction i := the instruction whose fields need to be
// initialized to their respective values
// based on machine code encoding
{
string encoding = i.getEncoding();
// figure out the various field and operands according
// to their known order, and pre-specified lengths
int index = 0;
string opstr = encoding.substr(index, OPCODE_LEN);
index += OPCODE_LEN;
string rs = encoding.substr(index, REG_WIDTH);
index += REG_WIDTH;
string rt = encoding.substr(index, REG_WIDTH);
index += REG_WIDTH;
string imm = encoding.substr(index, IMM_WIDTH);
Opcode opc = opcodes.getInstr(opstr, "");
// set the appropriate values of the instruction
// and pass 'NumRegisters' to the places that are
// not applicable
i.setValues(
opc,
convertToInt(rs, UNSIGNED),
convertToInt(rt, UNSIGNED),
NumRegisters,
convertToInt(imm, SIGNED)
);
}
void MachLangParser::decodeJType(Instruction& i)
// a decode helper method specific to J-type instructions
//
// Parameters:
// Instruction i := the instruction whose fields need to be
// initialized to their respective values
// based on machine code encoding
{
string encoding = i.getEncoding();
// figure out the various field and operands according
// to their known order, and pre-specified lengths
int index = 0;
string opstr = encoding.substr(index, OPCODE_LEN);
index += OPCODE_LEN;
string addr = encoding.substr(index, J_ADDR_WIDTH);
Opcode opc = opcodes.getInstr(opstr, "");
// set the appropriate fields of the instruction
// and pass 'NumRegisters' to the places that are
// not applicable
i.setValues(
opc,
NumRegisters,
NumRegisters,
NumRegisters,
convertToInt(addr, SIGNED)
);
}
int MachLangParser::convertToInt(string s, SignFlag f)
// Helper method that takes in a string of up to
// ARCH_NUM_BITS bits, and treats it as either signed
// unsigned based on the passed flag SignFlag f
{
// if we need signed, sign extend it to match the
// bitset width
if ((int)f == 1)
{
int extn = ARCH_NUM_BITS - s.size();
string signextend(extn, s[0]);
signextend += s;
std::bitset<ARCH_NUM_BITS> bits(signextend);
return (int)(bits.to_ulong());
}
// unsigned is straightforward: just initialize
// bitset and convert to unsigned int assuming
// no sign bit
std::bitset<ARCH_NUM_BITS> bits(s);
return (int)(bits.to_ulong());
}
void MachLangParser::assemble(Instruction& i)
// method that takes an instruction with all the
// appropriate fields filled in, and puts together
// an assembly instruction
//
// Parameters:
// Instruction i := the instruction whose fields are initialized
// to appropriate values and the instruction
// needs to be converted to assembly
{
string assembled;
// pick which helper method to call based on instruction's InstType
InstType type = opcodes.getInstType(i.getOpcode());
if (type == RTYPE)
assembled = assembleRType(i);
else if (type == ITYPE)
assembled = assembleIType(i);
else // type == JTYPE
assembled = assembleJType(i);
i.setAssembly(assembled);
}
string MachLangParser::assembleRType(Instruction i)
// assemble helper method specific to R-type
//
// Parameters:
// Instruction i := the instruction whose fields are initialized
// to appropriate values and the instruction
// needs to be converted to assembly
{
ostringstream assembled;
// start with the instruction name corresponding to opcode
assembled << opcodes.getName(i.getOpcode()) + "\t";
Opcode opc = i.getOpcode();
// go through each operand position and add only if the
// operand's position matches the current position being
// assembled.
for (int it = 0; it < opcodes.numOperands(opc); it++)
{
if (opcodes.RSposition(opc) == it)
assembled << "$" << i.getRS();
else if (opcodes.RTposition(opc) == it)
assembled << "$" << i.getRT();
else if (opcodes.RDposition(opc) == it)
assembled << "$" << i.getRD();
else if (opcodes.IMMposition(opc) == it)
assembled << i.getImmediate();
// we don't want a comma at the end
if (it < opcodes.numOperands(opc) - 1)
assembled << ", ";
}
return assembled.str();
}
string MachLangParser::assembleIType(Instruction i)
// assemble helper method specific to I-type
//
// Parameters:
// Instruction i := the instruction whose fields are initialized
// to appropriate values and the instruction
// needs to be converted to assembly
{
ostringstream assembled;
// start with the instruction name corresponding to opcode
assembled << opcodes.getName(i.getOpcode()) + "\t";
Opcode opc = i.getOpcode();
// case: if instruction is arithmetic-function
if (opcodes.getInstFunc(opc) == ARITHM_I)
{
// go through each operand position and add only if the
// operand's position matches the current position being
// assembled.
for (int it = 0; it < opcodes.numOperands(opc); it++)
{
if (opcodes.RSposition(opc) == it)
assembled << "$" << i.getRS();
else if (opcodes.RTposition(opc) == it)
assembled << "$" << i.getRT();
else if (opcodes.RDposition(opc) == it)
assembled << "$" << i.getRD();
else if (opcodes.IMMposition(opc) == it)
assembled << i.getImmediate();
// we don't want a comma at the end
if (it < opcodes.numOperands(opc) - 1)
assembled << ", ";
}
}
// case: if instruction is memory-function
else if (opcodes.getInstFunc(opc) == MEMORY_I)
{
for (int it = 0; it < opcodes.numOperands(opc); it++)
{
if (opcodes.RSposition(opc) == it)
assembled << "$" << i.getRS() << ")";
else if (opcodes.RTposition(opc) == it)
assembled << "$" << i.getRT() << ", ";
else if (opcodes.IMMposition(opc) == it)
assembled << i.getImmediate() << "(";
}
}
// case: if instruction is flow control-function
else if (opcodes.getInstFunc(opc) == CONTROL_I)
{
for (int it = 0; it < opcodes.numOperands(opc); it++)
{
if (opcodes.RSposition(opc) == it)
assembled << "$" << i.getRS();
else if (opcodes.RTposition(opc) == it)
assembled << "$" << i.getRT();
else if (opcodes.IMMposition(opc) == it)
// multiply by 4 to account for truncation of 2 bits;
// pass 'hex' flag for hex output
assembled << "0x" << hex << i.getImmediate()*4;
// we don't want a comma at the end
if (it < opcodes.numOperands(opc) - 1)
assembled << ", ";
}
}
return assembled.str();
}
string MachLangParser::assembleJType(Instruction i)
// assemble method specific to J-type: put together J-types
// that involve an address
//
// Parameters:
// Instruction i := the instruction whose fields are initialized
// to appropriate values and the instruction
// needs to be converted to assembly
{
ostringstream assembled;
// start with the instruction name corresponding to opcode
assembled << opcodes.getName(i.getOpcode()) + "\t";
Opcode opc = i.getOpcode();
// go through each operand position and add only if the
// operand's position matches the current position being
// assembled
for (int it = 0; it < opcodes.numOperands(opc); it++)
{
if (opcodes.RSposition(opc) == it)
assembled << "$" << i.getRS();
else if (opcodes.RTposition(opc) == it)
assembled << "$" << i.getRT();
else if (opcodes.IMMposition(opc) == it)
// multiply by 4 to account for truncation of
// last two 0 bits; pass 'hex' flag for hex output
assembled << "0x" << hex << i.getImmediate()*4;
// we don't want a comma at the end
if (it < opcodes.numOperands(opc) - 1)
assembled << ", ";
}
return assembled.str();
}
| true |
f2cd43443e35010aa13a2231c4fabaaa9efe4868
|
C++
|
awebkit/cppbuilding
|
/cpp-building/myown/meson.cpp
|
UTF-8
| 1,138 | 2.765625 | 3 |
[] |
no_license
|
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long LL;
LL Mul(LL a, LL b, LL m)
{
LL ans = 0;
while(b)
{
if(b & 1)
ans = (ans + a) % m;
a = (a*2)%m;
b /= 2;
}
return ans;
}
LL Mul2(LL a, LL b, LL m)
{
return a * b % m;
}
LL data[70];
int Lucas_Lehmer(int p)
{
LL MOD = (1LL<<p)-1;
data[1] = 4;
for(int i = 2; i <= p-1; i++)
{
//LL ans = Mul(data[i-1], data[i-1], MOD);
LL ans = Mul2(data[i-1], data[i-1], MOD);
//printf("ans is %lld, mod %lld\n", ans, MOD);
data[i] = (ans-2) % MOD;
//printf("data is %lld\n", data[i]);
}
if(data[p-1] == 0) return 1;
return 0;
}
void solve()
{
LL n;
scanf("%lld", &n);
if(n == 2) { printf("yes\n"); return ;}
if(Lucas_Lehmer(n)) printf("yes\n");
else printf("no\n");
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
solve();
}
return 0;
}
| true |
e277ea8873cbaab4457ea0f6633cbe77fafe9aac
|
C++
|
kusosk/cvim-ide
|
/cxx/test/zigzagString.cc
|
UTF-8
| 2,641 | 3.09375 | 3 |
[] |
no_license
|
#include <iostream>
#include <climits>
#include <string>
#include <exception>
#include <stdexcept>
using namespace std;
string convert(string s, int nRows) {
if (s.size()<2 || nRows < 2) return s;
int len=s.size(), pos;
int stp = (nRows<<1)-2;
char c;
string res;
int cnt=0;
for (int i = 1; i<=nRows; ++i) {
pos = 0;
if (i<=(nRows>>1)) {
for (int j = 0; pos < len; ++j) {
if (j%2)
pos = i==1 ? j*stp : (j ? ((j+1)>>1)*stp-(i-1) : i-1);
else
pos = i==1 ? j*stp : (j ? ((j+1)>>1)*stp+(i-1) : i-1);
cout <<"!"<< pos<< " " << i << " " << j<<endl;
if (cnt>len||pos>=len) break;
c = s[pos];
res.push_back(c);
cnt++;
cout << pos <<"["<<c<<"]";
}
} else {
for (int j = 0; pos < len; ++j) {
if (j%2== 0) {
pos = i==nRows ? (nRows-1)+j*stp : (j>>1)*stp+i-1;
}else
pos = i==nRows ? (nRows-1)+j*stp : (j>>1)*stp+stp-i+1;
cout <<"!"<< pos<< " " << i << " " << j<<endl;
if (cnt>len||pos>=len) break;
c = s[pos];
cout << pos<<"["<<c<<"]"<<endl;
res.push_back(c);
cnt++;
}
}
cout << endl;
}
return res;
}
string n(string s, int nRows)
{
if (s.size()<2 || nRows < 2) return s;
int len=s.size(), pos;
int stp = (len<<1)-2;
char c;
string res;
int cnt=0;
for (int i = 1; i<=nRows; ++i) {
pos = 0;
if (i<=(nRows>>1)) {
for (int j = 0; pos < len; ++j) {
if (j%2)
pos = i==1 ? j*stp : (j ? ((j+1)>>1)*stp-(i-1) : i-1);
else
pos = i==1 ? j*stp : (j ? ((j+1)>>1)*stp+(i-1) : i-1);
if (cnt>len||pos>=len) break;
c = s[pos];
res.push_back(c);
cnt++;
}
} else {
for (int j = 0; pos < len; ++j) {
if (j%2 == 0)
pos = i==nRows ? (nRows-1)+j*stp : (j>>1)*stp+i-1;
else
pos = i==nRows ? (nRows-1)+j*stp : (j>>1)*stp+stp-i+1;
if (cnt>len||pos>=len) break;
c = s[pos];
res.push_back(c);
cnt++;
}
}
}
return res;
}
int main()
{
cout << convert("AB", 3) << endl;
cout << n("AB", 3) << endl;
return 0;
}
| true |
9d409a3e9663bdb21949693a02e97c8c5f92fd05
|
C++
|
cli851/noi
|
/P58L4.3.cpp
|
WINDOWS-1252
| 260 | 2.765625 | 3 |
[] |
no_license
|
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int sum_ji=0,sum_ou=0;
for(int i=1;i<=100;i++)
{
if(i%2==0)//ż
{
sum_ou +=i;//sum_ou=sum_ou+i;
}
else
{
sum_ji +=i;
}
}
cout<<sum_ji<<" "<<sum_ou;
return 0;
}
| true |
b42b3704f98908fbdbc62b1a2b17463836e55528
|
C++
|
kjellhar/QLibUsb
|
/usbimpl.cpp
|
UTF-8
| 570 | 2.59375 | 3 |
[] |
no_license
|
#include "usbimpl.h"
/// Used by shared_ptr to delete a libusb context
class ContextDeleter
{
public:
void operator()(libusb_context* ctx) { libusb_exit(ctx); };
};
QLibUsb::UsbImpl::UsbImpl()
{
// Create the libusb context
libusb_context* pContext = 0;
int Result = libusb_init(&pContext);
if (Result != LIBUSB_SUCCESS)
{
//throw std::exception("libusb_init() failed.");
}
// Store in a shared_ptr
m_pLibusb_context.reset(pContext, ContextDeleter());
}
QSharedPointer<libusb_context> QLibUsb::UsbImpl::m_pLibusb_context;
| true |
c5178999d5107a06c8b4daad6fa319399b08b933
|
C++
|
jiaxinchenxx/TreeAlgorithm
|
/HuffmanTree/HuffmanTree.cpp
|
UTF-8
| 3,439 | 3.765625 | 4 |
[] |
no_license
|
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class HuffmanTreeNode {
public:
char element;
float weight;
HuffmanTreeNode * parent;
HuffmanTreeNode * leftChild;
HuffmanTreeNode * rightChild;
HuffmanTreeNode() {
leftChild = NULL;
rightChild = NULL;
}
HuffmanTreeNode(char x, float weight) {
this->element = x;
this->weight = weight;
leftChild = NULL;
rightChild = NULL;
}
HuffmanTreeNode(char x, HuffmanTreeNode * lc, HuffmanTreeNode *rc, float weight) {
this->element = x;
this->weight = weight;
this->leftChild = lc;
this->rightChild = rc;
}
HuffmanTreeNode(float weight) {
this->weight = weight;
this->element = ' ';
this->leftChild = NULL;
this->rightChild = NULL;
}
HuffmanTreeNode * getLeftChild() { return this->leftChild; }
HuffmanTreeNode * getRightChild() { return this->rightChild; }
void setLeftChild(HuffmanTreeNode *lc) { this->leftChild = lc; }
void setRightChild(HuffmanTreeNode * rc) { this->rightChild = rc; }
char getValue() { return this->element; }
void setValue(char x) { this->element = x; }
bool isLeaf() { return (this->leftChild == NULL && this->rightChild == NULL) ? true : false; }
};
class MinHeap {
public:
HuffmanTreeNode** HeapArr;
int curCount;
MinHeap();
~MinHeap();
void BuildHeap(HuffmanTreeNode** arr, int num);
void Insert(HuffmanTreeNode* x);
void SiftDown(int inx);
void SiftUp();
HuffmanTreeNode* RemoveMin();
};
MinHeap::MinHeap() {
HeapArr = new HuffmanTreeNode *[36];
}
MinHeap::~MinHeap() {
delete[] HeapArr;
}
void MinHeap::BuildHeap(HuffmanTreeNode** arr, int num) {
curCount = num;
for (int i = 0; i < num; i++)
HeapArr[i] = arr[i];
for (int i = num / 2 - 1; i >= 0; i--)
SiftDown(i);
}
void MinHeap::SiftDown(int inx) {
int j = 2 * inx + 1;
int temp = HeapArr[inx]->weight;
HuffmanTreeNode* tmp = HeapArr[inx];
while (j < curCount) {
if (j < curCount - 1 && HeapArr[j]->weight > HeapArr[j + 1]->weight)
j++;
if (HeapArr[j]->weight < temp) {
HeapArr[inx] = HeapArr[j];
inx = j;
j = 2 * j + 1;
}
else
break;
}
HeapArr[inx] = tmp;
}
void MinHeap::SiftUp() {
int inx = curCount;
int tmp = -1, p = HeapArr[inx]->weight;
HuffmanTreeNode * origin = HeapArr[inx];
while (inx != 0) {
tmp = inx / 2 - 1 + (inx % 2);
if (HeapArr[tmp]->weight > p) {
HeapArr[inx] = HeapArr[tmp];
inx = tmp;
}
else
break;
}
HeapArr[inx] = origin;
}
HuffmanTreeNode* MinHeap::RemoveMin() {
HuffmanTreeNode* min = HeapArr[0];
HeapArr[0] = HeapArr[curCount - 1];
curCount--;
for (int i = curCount / 2 - 1; i >= 0; i--)
SiftDown(i);
return min;
}
void MinHeap::Insert(HuffmanTreeNode* x) {
HeapArr[curCount] = x;
SiftUp();
curCount++;
}
class HuffmanTree {
public:
HuffmanTreeNode * root;
HuffmanTree(float weight[], int n) {
char c = 'A';
MinHeap heap;
HuffmanTreeNode** nodeList = new HuffmanTreeNode*[n];
HuffmanTreeNode * parent, *lc, *rc;
for (int i = 0; i < n; i++) {
nodeList[i] = new HuffmanTreeNode(c + i,weight[i]);
heap.Insert(nodeList[i]);
}
for (int i = 0; i < n - 1; i++) {
parent = new HuffmanTreeNode;
parent->leftChild = heap.RemoveMin();
parent->rightChild = heap.RemoveMin();
heap.Insert(parent);
root = parent;
}
delete[] nodeList;
}
};
void main() {
float weight[8] = {0.05, 0.29, 0.07, 0.08, 0.14, 0.23, 0.03, 0.11};
HuffmanTree hf(weight, 8);
}
| true |
dcd2975affdc2b2d656bafd5471394383b56909f
|
C++
|
Mdlglobal-atlassian-net/orbit
|
/OrbitBase/MainThreadExecutorTest.cpp
|
UTF-8
| 1,489 | 2.75 | 3 |
[
"LicenseRef-scancode-free-unknown",
"BSD-2-Clause"
] |
permissive
|
// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <gmock/gmock-matchers.h>
#include <gtest/gtest.h>
#include <memory>
#include <utility>
#include "OrbitBase/MainThreadExecutor.h"
TEST(MainThreadExecutor, Smoke) {
std::unique_ptr<MainThreadExecutor> executor = MainThreadExecutor::Create();
bool called = false;
executor->Schedule([&]() { called = true; });
EXPECT_FALSE(called);
executor->ConsumeActions();
EXPECT_TRUE(called);
called = false;
// There should be no actions to consume
executor->ConsumeActions();
EXPECT_FALSE(called);
}
TEST(MainThreadExecutor, CheckThread) {
std::unique_ptr<MainThreadExecutor> executor = MainThreadExecutor::Create();
// Let's make sure we execute action on main thread
std::thread::id action_thread_id;
std::thread scheduling_thread([&]() {
executor->Schedule([&] { action_thread_id = std::this_thread::get_id(); });
});
scheduling_thread.join();
EXPECT_NE(action_thread_id, std::this_thread::get_id());
executor->ConsumeActions();
EXPECT_EQ(action_thread_id, std::this_thread::get_id());
}
TEST(MainThreadExecutor, InvalidConsumer) {
std::unique_ptr<MainThreadExecutor> executor;
std::thread create_executor_thread(
[&]() { executor = MainThreadExecutor::Create(); });
create_executor_thread.join();
EXPECT_DEATH(executor->ConsumeActions(), "");
}
| true |
e2d284ebb603604c4bb75c29385346c6e364ae01
|
C++
|
mohsinenur/URIOnlineJudge
|
/S Sequence.cpp
|
UTF-8
| 316 | 3.09375 | 3 |
[] |
no_license
|
#include<iostream>
#include<iomanip>
using namespace std;
main()
{
//s= 1/1 + 1/2 + 1/3 + ....+ 1/100
double S = 0;
double tS = 0;
int i;
cout << fixed;
for (i=1; i<=100; i++)
{
S = (double)1/i;
tS += S;
}
cout << setprecision(2) << tS << endl;
return 0;
}
| true |
f7d02e3b5546417afe21b68b948d7cc4fe7b41ff
|
C++
|
youtube/cobalt
|
/base/allocator/partition_allocator/spin_lock.h
|
UTF-8
| 1,550 | 2.671875 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef BASE_ALLOCATOR_PARTITION_ALLOCATOR_SPIN_LOCK_H
#define BASE_ALLOCATOR_PARTITION_ALLOCATOR_SPIN_LOCK_H
#include <atomic>
#include <memory>
#include <mutex>
#include "base/base_export.h"
#include "base/compiler_specific.h"
// Spinlock is a simple spinlock class based on the standard CPU primitive of
// atomic increment and decrement of an int at a given memory address. These are
// intended only for very short duration locks and assume a system with multiple
// cores. For any potentially longer wait you should use a real lock, such as
// |base::Lock|.
namespace base {
namespace subtle {
class BASE_EXPORT SpinLock {
public:
constexpr SpinLock() = default;
~SpinLock() = default;
using Guard = std::lock_guard<SpinLock>;
ALWAYS_INLINE void lock() {
static_assert(sizeof(lock_) == sizeof(int),
"int and lock_ are different sizes");
if (LIKELY(!lock_.exchange(true, std::memory_order_acquire)))
return;
LockSlow();
}
ALWAYS_INLINE void unlock() { lock_.store(false, std::memory_order_release); }
private:
// This is called if the initial attempt to acquire the lock fails. It's
// slower, but has a much better scheduling and power consumption behavior.
void LockSlow();
std::atomic_int lock_{0};
};
} // namespace subtle
} // namespace base
#endif // BASE_ALLOCATOR_PARTITION_ALLOCATOR_SPIN_LOCK_H
| true |
731f00850fb5be16eea641624f5213edf1f643a6
|
C++
|
victorhbc/Estruturas-de-dados-
|
/Projeto 1/insertSort.cpp
|
UTF-8
| 1,002 | 3.28125 | 3 |
[] |
no_license
|
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define len 20000
#include "header.h"
using namespace std;
void select(int v[]);
int main(int argc, char const *argv[])
{
int x;
int v0[len], v1[len], v2[len];
cout << "Ordenado: " << endl;
sorted(v0);
select(v0);
cout << "Desordenado: " << endl;
unsorted(v1);
select(v1);
cout << "Randomico: " << endl;
random(v2);
select(v2);
return 0;
}
void select(int v[]){
int equal = 0, change = 0, aux, j;
time_t tStart;
tStart = clock();
for (int i = 1; i < len; i++) {
aux = v[i];
int j = i - 1;
while ((j >= 0) && (v[j] > aux)) {
equal++;
v[j + 1] = v[j];
j--;
change++;
}
v[j + 1] = aux;
}
tStart = clock() - tStart;
double timeTaken = ((double)tStart) / CLOCKS_PER_SEC;
cout << "\tTempo: \t\t" << timeTaken << "segundos" << endl;
cout << "\tTrocas: \t" << change << endl;
cout << "\tComparacoes: \t" << equal << endl;
}
| true |
4de10919cfc363710bbfc0c9bdfcc9825d370881
|
C++
|
FJNU-spicey/software-test
|
/VirtualQueryEx.cpp
|
GB18030
| 2,344 | 2.859375 | 3 |
[] |
no_license
|
#include<windows.h>
#include<iostream>
#include<shlwapi.h>
#include<iomanip>
#pragma comment(lib,"shlwapi.lib")
inline bool TestSet(DWORD dwTarget, DWORD dwMask)
{
return((dwTarget & dwMask)==dwMask);
}
#define SHOWMASK(dwTarget,type)\
if(TestSet(dwTarget,PAGE_##type))\
{std::cout<<","<<#type;}
void ShowProtection(DWORD dwTarget)
{
SHOWMASK(dwTarget,READONLY);
SHOWMASK(dwTarget,GUARD);
SHOWMASK(dwTarget,NOCACHE);
SHOWMASK(dwTarget,READWRITE);
SHOWMASK(dwTarget,WRITECOPY);
SHOWMASK(dwTarget,EXECUTE);
SHOWMASK(dwTarget,EXECUTE_READ);
SHOWMASK(dwTarget,EXECUTE_READWRITE);
SHOWMASK(dwTarget,EXECUTE_WRITECOPY);
SHOWMASK(dwTarget,NOACCESS);
}
void WalkVM(HANDLE hProcess)
{
// ȣϵͳϢ
SYSTEM_INFO si;
::ZeroMemory(&si,sizeof(si));
::GetSystemInfo(&si);
// ҪϢĻ
MEMORY_BASIC_INFORMATION mbi;
::ZeroMemory(&mbi,sizeof(mbi));
// ѭӦóַռ
LPCVOID pBlock=(LPVOID)si.lpMinimumApplicationAddress;
while(pBlock<si.lpMaximumApplicationAddress)
{
// һڴϢ
if(::VirtualQueryEx(
hProcess, // صĽ
pBlock, // ʼλ
&mbi, //
sizeof(mbi))==sizeof(mbi)) // Сȷ
{
LPCVOID pEnd=(PBYTE)pBlock+mbi.RegionSize;
TCHAR szSize[MAX_PATH];
::StrFormatByteSize(mbi.RegionSize,szSize,MAX_PATH);
std::cout.fill('0');
std::cout<<std::hex<<std::setw(8)<<(DWORD)pBlock<<" "<<std::hex<<std::setw(8)<<(DWORD)pEnd<<" ("<<szSize<<")";
// ʾڴ״̬
switch(mbi.State)
{
case MEM_COMMIT:
std::cout<<" Committed\n\n";
break;
case MEM_FREE:
std::cout<<" Free\n\n";
break;
case MEM_RESERVE:
std::cout<<" Reserved\n\n";
break;
}
std::cout<<std::endl;
// ƶָ뵽һڴ
pBlock=pEnd;
}
}
}
void main()
{
// ǰ̵ڴ
std::cout<<"\n * * * VirtualQueryExڴ * * *\n\nʼַ ַֹ ڴ״̬\n\n";
::WalkVM(::GetCurrentProcess());
}
| true |
68be087039806f18a7c40775e779bbb4f5b04b81
|
C++
|
Veirisa/MathLogic
|
/Homework1/main.cpp
|
UTF-8
| 1,274 | 2.8125 | 3 |
[] |
no_license
|
#include "expression.h"
vector<expression*> hypotheses;
vector<expression*> derivations;
void add_hypotheses(const string& s) {
size_t i = 0;
string new_hypo = "";
while (s[i] != '|' || s[i + 1] != '-') {
if (s[i] == '\0' || s[i] == ' ' || s[i] == '\t') {
++i;
continue;
}
new_hypo += s[i];
++i;
if (s[i] == ',') {
++i;
hypotheses.push_back(new expression(new_hypo));
new_hypo = "";
}
}
if (new_hypo.size() > 0) {
hypotheses.push_back(new expression(new_hypo));
}
}
void full_check() {
string s;
while (getline(cin, s)) {
expression* expr = new expression(s);
derivations.push_back(expr);
cout << "(" << derivations.size() << ")" << " " << expr->string_of_expr() << " ";
if (!expr->check_hypotheses() && !expr->check_axioms() && !expr->check_MP()) {
cout << "(" << "Не доказано" << ")" << "\n";
}
}
}
int main() {
cin.tie();
ios_base::sync_with_stdio(0);
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
string s;
getline(cin, s);
add_hypotheses(s);
cout << s << "\n";
full_check();
return 0;
}
| true |
77ec196d929d2c7ee17e28dfe256a2f4eee383f0
|
C++
|
YongHoonJJo/BOJ
|
/2493.cpp
|
UTF-8
| 466 | 2.734375 | 3 |
[] |
no_license
|
#include <cstdio>
#include <stack>
using namespace std;
stack<int> S;
int ans[500001];
int main()
{
int n, k;
int tower[500001];
scanf("%d", &n);
for(int i=1; i<=n; i++)
scanf("%d", tower+i);
for(int i=1; i<=n; i++) {
while(!S.empty()) {
int prev = S.top();
if(tower[prev] > tower[i]) {
ans[i] = prev;
break;
}
S.pop();
}
if(S.empty()) ans[i] = 0;
S.push(i);
}
for(int i=1; i<=n; i++)
printf("%d ", ans[i]);
puts("");
}
| true |
537d3a95df722b5be25092d45e999b60ccba7206
|
C++
|
ucsb-cs16-s19-nichols/code-from-class
|
/05-09/centroid.cpp
|
UTF-8
| 695 | 4.03125 | 4 |
[] |
no_license
|
#include <iostream>
using namespace std;
struct Point {
double x;
double y;
};
// Point *arr ≡ Point arr[]
Point* centroid(const Point *arr, int size) {
Point *ret = new Point;
(*ret).x = 0;
ret->y = 0;
// average all the points
for (int i = 0; i < size; i++) {
ret->x += arr[i].x;
ret->y += arr[i].y;
}
ret->x = ret->x / size;
ret->y = ret->y / size;
return ret;
}
int main(int argc, char *argv[])
{
Point points[] = {{1, 2}, {3, 4}, {5, 6}, {7, 8}};
Point *c = centroid(points, 4); // c is a new Point on the heap
cout << "centroid is: (" << c->x << ", " << c->y << ")" << endl;
delete c;
return 0;
}
| true |
32c0bffff1cca0e22e3ea7a9e2427d87836820a7
|
C++
|
KristiyanGergov/DataStructuresAndAlgorithms
|
/Week 07 - Tree Algorithms/BinarySearchTree/TreeExcercice/BinarySearchTree.cpp
|
UTF-8
| 1,143 | 3.625 | 4 |
[] |
no_license
|
#include "BinarySearchTree.h"
BinarySearchTree::BinarySearchTree()
{
this->head = NULL;
}
BinarySearchTree::~BinarySearchTree()
{
delete head;
}
void BinarySearchTree::insert(int data)
{
if (head == NULL)
{
head = new Node(data);
return;
}
Node * curr = head;
Node * temp = new Node(data);
while (curr != nullptr)
{
if (data > curr->data)
{
if (curr->right == NULL)
{
curr->right = temp;
break;
}
curr = curr->right;
}
else if (data < curr->data)
{
if (curr->left == NULL)
{
curr->left = temp;
break;
}
curr = curr->left;
}
else
{
return;
}
}
}
void BinarySearchTree::inOrder(Node* root)
{
if (root == NULL)
return;
inOrder(root->left);
cout << root->data << " ";
inOrder(root->right);
}
void BinarySearchTree::postOrder(Node* root)
{
if (root == NULL)
return;
postOrder(root->left);
postOrder(root->right);
cout << root->data << " ";
}
void BinarySearchTree::preOrder(Node* root)
{
if (root == NULL)
return;
cout << root->data << " ";
preOrder(root->left);
preOrder(root->right);
}
void BinarySearchTree::levelOrder(Node* root)
{
}
| true |
4b69d42485dfa72f0871859188907ee43b39a254
|
C++
|
ramzani97/Alpro-II---semester-2
|
/array.TUGAS.cpp
|
UTF-8
| 579 | 3.203125 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
int main() {
int i,x;
cout << endl ;
cout << "-_-_-_-_Aplikasi ini menggunakan ARRAY-_-_-_-_" <<endl ;
cout << "Tentukan banyaknya data!: " ;
cin >> x ;
cout << "=============" << endl;
string nama[x]; // ARRAY //
for (i=0;i<x;i++) { // Pengulangan //
cout << "silahkan isi index" <<i<< ": ";
cin >> nama[i];
}
cout << "=============" << endl;
cout << "berikut "<<x<<" data yang telah dimasukan :" << endl ;
cout << "|";
for (i=0;i<x;i++) { // Pengulangan //
cout << nama[i] <<"|";
}
return (0);
}
| true |
b0831a115c1fdc8b767467834282043a1346aab2
|
C++
|
rodrigobmg/201503_direct3d_demo
|
/engine/header/util/Texture2DFromBytes.h
|
UTF-8
| 5,031 | 2.59375 | 3 |
[] |
no_license
|
/*
Texture2DFromBytes.h
--------------------
Created for: COMP3501A Assignment 6
Fall 2014, Carleton University
Authors:
Bernard Llanos
Created November 7, 2014
Primary basis: None
Description
-A Texture class encapsulating texture creation from in-memory data
-Note that textures are created CPU read-only,
but with GPU read and write access.
-Note that the Direct3D device context will automatically
unbind resources from their existing bind locations
before adding a conflicting bind location (e.g. to prevent
a resource being bound for reading and writing simultaneously).
However, the Direct3D device debug layer
will still output warnings in these cases.
-The texture has a DXGI format of DXGI_FORMAT_R32G32B32A32_FLOAT
and a single mip level.
*/
#pragma once
#include <windows.h>
#include <d3d11.h>
#include <string>
#include "Texture.h"
class Texture2DFromBytes : public Texture {
public:
template<typename ConfigIOClass> Texture2DFromBytes(
const bool enableLogging, const std::wstring& msgPrefix,
ConfigIOClass* const optionalLoader,
const std::wstring filename,
const std::wstring path = L""
);
virtual ~Texture2DFromBytes(void);
public:
/* The client is responsible for calling this function.
It is just a proxy for the protected base class function.
*/
virtual HRESULT configure(const std::wstring& scope, const std::wstring* configUserScope = 0, const std::wstring* logUserScope = 0) override;
/* Creates texture and texture sampler
Note: If this function was passed a device context,
it could make use of the DirectXTK DDSTextureLoader's
functionality for generating mip-maps.
However, I think mip-map auto-generation would
only work with Direct3D 11 and above.
'width' and 'height' define the pixel dimensions
of the texture, whereas 'data' holds
its initial contents. The client
is responsible for deallocating 'data'.
If 'renderTarget' is true, the texture will
be created with the render target bind flag
and will have an associated render target view.
*/
virtual HRESULT initialize(ID3D11Device* device, const DXGI_FORMAT format, const UINT width, const UINT height, const void* const data = 0,
bool renderTarget = false);
/* Bind the texture to the pipeline
as the first render target. Other render targets
are preserved.
Note that the OMSetRenderTargets()
method of the device context will unbind this texture
at all locations where it was currently bound,
although it will result in warnings being output
by the debug layer.
'depthStencilView' is the depth stencil to set along
with the render target (as the OMSetRenderTargets()
method of the device context simultaneously sets the
depth stencil texture). If null, the current
depth stencil view is used instead.
I am not sure if calling OMSetRenderTargets() with a null
depth stencil state parameter unbinds the current depth
stencil state, but have assumed this to be the case,
just to be careful.
*/
virtual HRESULT bindAsRenderTarget(ID3D11DeviceContext* const context,
ID3D11DepthStencilView *depthStencilView = 0);
/* Copies the entire texture resource contents of the 'other'
parameter into the texture of 'this'. This member function
does not alter the resource views and auxiliary/metadata
associated with the texture.
Returns a failure result and does nothing if the two
textures have different dimensions or formats, or if either
of the two objects have not been fully initialized.
*/
virtual HRESULT getDataFrom(ID3D11DeviceContext* const context, Texture2DFromBytes& other);
/* Similar to getDataFrom(ID3D11DeviceContext* const, Texture2DFromBytes&),
but operates on a non-wrapped Direct3D texture resource.
*/
virtual HRESULT getDataFrom(ID3D11DeviceContext* const context, ID3D11Texture2D* const other);
/* Clears this object's texture data to the given colour.
Returns false and does nothing if this object does not
have a render target view.
*/
virtual HRESULT clearRenderTarget(ID3D11DeviceContext* const context,
const DirectX::XMFLOAT4& color);
// Data members
private:
// Texture data format
DXGI_FORMAT m_format;
// Texture width
UINT m_width;
// Texture height
UINT m_height;
// Null if the texture is not created with the render target bind flag
ID3D11RenderTargetView* m_renderTargetView;
// Currently not implemented - will cause linker errors if called
private:
Texture2DFromBytes(const Texture2DFromBytes& other);
Texture2DFromBytes& operator=(const Texture2DFromBytes& other);
};
template<typename ConfigIOClass> Texture2DFromBytes::Texture2DFromBytes(
const bool enableLogging, const std::wstring& msgPrefix,
ConfigIOClass* const optionalLoader,
const std::wstring filename,
const std::wstring path
) :
Texture(
enableLogging, msgPrefix,
optionalLoader,
filename,
path
),
m_format(DXGI_FORMAT_UNKNOWN),
m_width(0), m_height(0),
m_renderTargetView(0)
{}
| true |
303d2b87c61fb975dadcec876fa5e792dd17fce4
|
C++
|
dmaulikr/sushi
|
/sushicpp/sushiapplication/sushiapplication/application.hpp
|
UTF-8
| 3,026 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
// application.hpp
// sushiapplication - sushicpp
//
// Created: 01:19 08/15/2017
// Author: Michael Ong
#pragma once
#include <functional>
#include <vector>
#include <string>
#include <sushicore/Rectangle.h>
#include <sushicore/CoreObject.h>
#include <sushicore/PointerOwnership.h>
namespace sushi::window {
class Window;
class WindowLogic;
}
namespace sushi::graphics {
class GraphicsDevice;
}
namespace sushi::drivers {
class ApplicationDriver;
}
namespace sushi::application {
/**
\brief `Application` class
Object that initialises Sushi.
This object should be only initialised once. Usually at `main.cpp` file.
Use `initialise` to initialise the application.
Use `Application::instance` to get the necessary properties such as the `driver`, `graphicsDevice`, and `storageManager`.
Use `spawnWindow()` to create a window. **DO NOT INITIALISE BY CREATING A WINDOW INSTANCE**
*/
class Application final: public core::CoreObject {
friend class drivers::ApplicationDriver;
public:
typedef std::function<void(Application const*)> initialiseCallback;
SUSHI_PO_STRONG
static Application* instance;
/**
Method to initalise sushi
*/
static void initialise (SUSHI_PT_TRANSFER drivers::ApplicationDriver* platformDriver,
const initialiseCallback& initCallback);
static void destroy ();
private:
SUSHI_PO_STRONG
drivers::ApplicationDriver* platformDriver;
SUSHI_PO_STRONG
graphics::GraphicsDevice* graphicsDevice;
SUSHI_PO_STRONG
void* storageManager;
initialiseCallback initialisationCallback;
SUSHI_PO_WEAK mutable
std::vector<window::Window*> trackedWindows;
public:
explicit Application (SUSHI_PT_TRANSFER drivers::ApplicationDriver* platformDriver);
~Application ();
SUSHI_PT_REF
const drivers::ApplicationDriver* getPlatformDriver () const;
SUSHI_PT_REF
const graphics::GraphicsDevice* getGraphicsDevice () const;
SUSHI_PT_REF
const void* getStorageManager () const;
const std::vector<window::Window*>& getTrackedWindows () const;
const initialiseCallback& getInitCallback () const;
public:
SUSHI_PO_STRONG
window::Window* spawnWindow (SUSHI_PT_TRANSFER window::WindowLogic* logic,
const std::u16string& title,
const core::Rectangle& location) const;
};
}
| true |
b11d0a86468ddb8b8428e9606b79f22966a317c6
|
C++
|
chandreshsharma/Cpp11
|
/22_lambdas_2.cpp
|
UTF-8
| 3,037 | 4.0625 | 4 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <limits>
#include <algorithm>
#include <list>
#include <functional>
/******
A program to use lambdas with STL containers and User defined Classes.
It also shows how to use the std::function() to point to a lambda function.
******/
class Height {
public:
int _feet;
int _inches;
public:
Height(int feet = 0, int inches = 0): _feet(feet), _inches(inches) {
}
void print() { std::cout << _feet << "\'" << _inches << "\""; }
int ft() { return _feet; }
};
std::function<int(int, int)> larger()
{
std::cout << "inside larger" << std::endl;
return [] (int x, int y) -> int { return ( x > y ? x : y); };
}
int main() {
std::vector<int> vals = { 10, 5, 23, 19, 9, 20 };
int biggest = std::numeric_limits<int>::min();
/// Find the largest element in the vector
// Use a lambda to set 'biggest' to the largest value in the vector.
// The local variables, 'biggest' is passed by reference.
std::for_each( vals.begin(), vals.end(),
[&](int val) { if( val > biggest ) biggest = val; }
);
std::cout << "Largest value: " << biggest << std::endl;
/// Replace the negative elements in the list with a zero, using a lambda expression.
std::list <int> nums = { 20, -34, 55, -1090, 600, -780, -5 };
std::cout << "\nOriginal nums list:" << std::endl;
for(auto i:nums)
std::cout << i << ", "; std::cout << std::endl;
std::replace_if( nums.begin(), nums.end(),
[&](int n) { return (n<0); }, 0 );
std::cout << "nums list post replacing negative numbers:" << std::endl;
for(auto i:nums)
std::cout << i << ", "; std::cout << std::endl;
/// Sort the heights using a lambda function
std::vector<Height> heights = { {5, 23}, {2, 60}, {0, 100}, {3,36}, {2, 20}, {0, 200} };
std::cout << "Heights, Original list:" << std::endl;
for(auto h:heights) {
h.print();
std::cout << ", ";
}
std::sort( heights.begin(), heights.end(),
[] (const Height & i, const Height & j) { return ( ((i._feet * 12) + i._inches) < ((j._feet * 12) + j._inches) ); });
std::cout << "\nHeights, Post sort:" << std::endl;
for(auto h:heights) {
h.print();
std::cout << ", ";
}
std::cout << std::endl;
/// Use the lambda to point to the function wrapper created using std::function
int i=10, j=20;
// Function that accepts two integers and returns an integer
// This though is an overhead since the lambda can be called directly, without binding it to the wrapper.
std::function<int(int,int)> bigger = [] (int x, int y) { return ( x > y ? x : y); };
std::cout << "bigger: " << bigger(i,j) << std::endl;
std::cout << "bigger: " << bigger(200, 100) << std::endl;
auto l = larger();
std::cout << "larger: " << l(i,j) << std::endl;
std::cout << "larger: " << l(200, 100) << std::endl;
std::cout << "larger: " << l(200, 1000) << std::endl;
return 0;
}
| true |
2434497ef08991132553697d5d444587239ea5f3
|
C++
|
TheLogicalNights/CPP-Programing-Assignments
|
/Assignment_3/Program_3/Helper.cpp
|
UTF-8
| 1,722 | 3.25 | 3 |
[] |
no_license
|
#include "Header.h"
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Function Name : Number
// Parameters : None
// Return Value : None
// Description : It is default constructor used to initialize the object
// Author : Swapnil Ramesh Adhav
// Date : 15 Nov 2020
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Number::Number()
{
this->iNo = 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Function Name : Number
// Parameters : Integer
// Return Value : None
// Description : It is parameterized constructor used to initialize the object
// Author : Swapnil Ramesh Adhav
// Date : 15 Nov 2020
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Number::Number(int iNo)
{
this->iNo = iNo;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Function Name : EvenFactors
// Parameters : None
// Return Value : None
// Description : It is used to display even factors
// Author : Swapnil Ramesh Adhav
// Date : 15 Nov 2020
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Number::EvenFactors()
{
int iCnt = 0;
if(iNo<0)
{
iNo = -iNo;
}
for(iCnt=1;iCnt<=iNo/2;iCnt++)
{
if(((iCnt%2)==0) && ((iNo%iCnt)==0))
{
cout<<iCnt<<"\t";
}
}
cout<<"\n";
}
| true |
6b4a14112651535d369d44ac3cee5eaa989872e3
|
C++
|
star-217/DXTK-Effekseer
|
/DirectX12 Game Solution/DirectXTK9/Inc/Model.h
|
UTF-8
| 5,450 | 2.578125 | 3 |
[] |
no_license
|
#pragma once
#include <d3dx9.h>
#include <wrl/client.h>
#include <memory>
#include <vector>
#include <DirectXMath.h>
#include <DirectXCollision.h>
namespace DX9 {
class Model {
public:
Model() = default;
Model(
IDirect3DDevice9* device,
ID3DXMesh* mesh,
const DWORD meshes
);
virtual ~Model() {}
void Draw();
inline void SetMaterial(const D3DMATERIAL9& material, const DWORD index)
{ m_materials[index] = material; }
void SetMaterial(const D3DMATERIAL9& material);
inline void SetTexture(LPCWSTR texture, const DWORD index)
{
D3DXCreateTextureFromFile(
m_device.Get(), texture,
m_textures[index].ReleaseAndGetAddressOf()
);
}
void SetTexture(LPCWSTR texture);
inline void SetTexture(IDirect3DTexture9* texture, const DWORD index)
{ m_textures.at(index) = texture; }
void SetTexture(IDirect3DTexture9* texture);
inline void SetPosition(const float x, const float y, const float z)
{ m_position.f[0] = x; m_position.f[1] = y; m_position.f[2] = z; }
inline void SetPosition(const DirectX::XMFLOAT3& position)
{ m_position.v = DirectX::XMLoadFloat3(&position); }
inline void SetScale(const float x, const float y, const float z)
{ m_scale.x = x; m_scale.y = y; m_scale.z = z; }
inline void SetScale(const DirectX::XMFLOAT3& scale)
{ m_scale = scale; }
inline void SetScale(const float scale)
{ m_scale.x = scale; m_scale.y = scale; m_scale.z = scale; }
inline void SetRotation(const float x, const float y, const float z)
{ m_rotation = DirectX::XMMatrixRotationRollPitchYaw(x, y, z); }
inline void SetRotation(const DirectX::XMFLOAT3& rotation)
{ SetRotation(rotation.x, rotation.y, rotation.z); }
inline DirectX::XMFLOAT3 GetPosition() const
{ return DirectX::XMFLOAT3(m_position.f[0], m_position.f[1], m_position.f[2]); }
inline DirectX::XMFLOAT3 GetScale() const
{ return m_scale; }
DirectX::XMFLOAT3 GetRotation() const;
inline DirectX::XMMATRIX GetWorldTransform() const
{
DirectX::XMMATRIX world(
DirectX::XMMatrixScaling(m_scale.x, m_scale.y, m_scale.z)
);
world *= m_rotation;
world.r[3] = m_position.v;
return world;
}
inline DirectX::XMFLOAT3 GetRightVector() const
{
DirectX::XMFLOAT3 right;
DirectX::XMStoreFloat3(&right, m_rotation.r[0]);
return right;
}
inline DirectX::XMFLOAT3 GetUpVector() const
{
DirectX::XMFLOAT3 up;
DirectX::XMStoreFloat3(&up, m_rotation.r[1]);
return up;
}
inline DirectX::XMFLOAT3 GetForwardVector() const
{
DirectX::XMFLOAT3 foward;
DirectX::XMStoreFloat3(&foward, m_rotation.r[2]);
return foward;
}
inline D3DMATERIAL9 GetMaterial(const DWORD index)
{ return m_materials[index]; }
void Move(const float x, const float y, const float z);
inline void Move(const DirectX::XMFLOAT3& move)
{ Move(move.x, move.y, move.z); }
void Rotate(const float x, const float y, const float z);
inline void Rotate(const DirectX::XMFLOAT3& rotation)
{ Rotate(rotation.x, rotation.y, rotation.z); }
bool IntersectRay(
const DirectX::XMFLOAT3& raypos,
const DirectX::XMFLOAT3& raydir,
float* distance = nullptr,
DirectX::XMFLOAT3* normal = nullptr
);
inline bool RayCast(
const DirectX::XMFLOAT3& origin,
const DirectX::XMFLOAT3& direction,
float* distance = nullptr,
DirectX::XMFLOAT3* normal = nullptr
)
{ return IntersectRay(origin, direction, distance, normal); }
DirectX::BoundingSphere GetBoundingSphere();
DirectX::BoundingBox GetBoundingBox();
DirectX::BoundingOrientedBox GetBoundingOrientedBox();
std::unique_ptr<Model> Clone();
__declspec(property(get = GetPosition)) DirectX::XMFLOAT3 Position;
__declspec(property(get = GetRotation)) DirectX::XMFLOAT3 Rotation;
__declspec(property(get = GetRightVector)) DirectX::XMFLOAT3 RightVector;
__declspec(property(get = GetUpVector)) DirectX::XMFLOAT3 UpVector;
__declspec(property(get = GetFowardVector)) DirectX::XMFLOAT3 FowardVector;
static std::unique_ptr<Model> CreateFromFile(
IDirect3DDevice9* device, LPCWSTR file
);
static std::unique_ptr<Model> CreateBox(
IDirect3DDevice9* device,
const float width, const float height, const float depth
);
static std::unique_ptr<Model> CreateCylinder(
IDirect3DDevice9* device,
const float radius1, const float radius2,
const float length,
const UINT slices, const UINT stacks
);
static std::unique_ptr<Model> CreatePolygon(
IDirect3DDevice9* device,
const float length, const UINT slices
);
static std::unique_ptr<Model> CreateSphere(
IDirect3DDevice9* device,
const float radius, const UINT slices, const UINT stacks
);
static std::unique_ptr<Model> CreateTorus(
IDirect3DDevice9* device,
const float innnerRadius, const float outerRadius,
const UINT slides, const UINT rings
);
static std::unique_ptr<Model> CreateTeapot(IDirect3DDevice9* device);
private:
Microsoft::WRL::ComPtr<IDirect3DDevice9> m_device;
Microsoft::WRL::ComPtr<ID3DXMesh> m_mesh;
DWORD m_meshes;
std::vector<D3DMATERIAL9> m_materials;
std::vector<Microsoft::WRL::ComPtr<IDirect3DTexture9>> m_textures;
DirectX::XMVECTORF32 m_position;
DirectX::XMFLOAT3 m_scale;
DirectX::XMMATRIX m_rotation;
};
typedef std::unique_ptr<Model> MODEL;
}
| true |
1119df7d8455d4319fde65134083e35689dd286c
|
C++
|
terngkub/gomoku_cmake
|
/gomoku/history/history.cpp
|
UTF-8
| 319 | 2.59375 | 3 |
[] |
no_license
|
#include <gomoku/history/history.hpp>
History::History()
: _actions{}
, current_action{}
{}
void History::push_action()
{
_actions.push(current_action);
current_action = Action{};
}
Action History::pop_action()
{
Action last_action = _actions.top();
_actions.pop();
return last_action;
}
| true |
b20bce80591ebbab72bb482a9ae6583e752d4e67
|
C++
|
nilrum/Property
|
/Serialization.h
|
UTF-8
| 2,632 | 2.640625 | 3 |
[] |
no_license
|
//
// Created by user on 26.08.2019.
//
#ifndef TESTAPP_SERIALIZATION_H
#define TESTAPP_SERIALIZATION_H
#include "PropertyClass.h"
class TSerializationInterf
{
public:
virtual TString SaveTo(TPropertyClass *value) const = 0;
virtual TResult LoadFrom(const TString& text, TPropertyClass *value) const = 0;
virtual TPtrPropertyClass CreateFrom(const TString& text) const = 0;
virtual TResult SaveToFile(const TString& path, TPropertyClass *value) const = 0;
virtual TResult LoadFromFile(const TString& path, TPropertyClass *value) const = 0;
virtual TResult SavePropToFile(const TString& path, TPropertyClass *value, const TPropInfo &prop) const = 0;
virtual TResult LoadPropFromFile(const TString& path, TPropertyClass *value, const TPropInfo& prop) const = 0;
};
enum class TSerializationKind{skXml = 0, skBin, skCount};
enum class TSerializationResult{ Ok, FileNotOpen, FileNotSave, ErrorData};
class TSerialization : public TSerializationInterf{
public:
TSerialization(TSerializationKind kind = TSerializationKind::skXml);
TString SaveTo(TPropertyClass *value) const override;
TResult LoadFrom(const TString& text, TPropertyClass *value) const override;
TPtrPropertyClass CreateFrom(const TString& text) const override;
TResult SaveToFile(const TString& path, TPropertyClass *value) const override;
TResult LoadFromFile(const TString& path, TPropertyClass *value) const override;
TResult SavePropToFile(const TString& path, TPropertyClass *value, const TPropInfo &prop) const override;
TResult LoadPropFromFile(const TString& path, TPropertyClass *value, const TPropInfo& prop) const override;
inline TResult SavePropToFileName(const TString& path, TPropertyClass *value, const TString& name) const;
inline TResult LoadPropFromFileName(const TString& path, TPropertyClass *value, const TString& name) const;
protected:
std::shared_ptr<TSerializationInterf> impl;
static std::shared_ptr<TSerializationInterf> SerFromKind(TSerializationKind kind);
};
TResult TSerialization::SavePropToFileName(const TString &path, TPropertyClass *value, const TString &name) const
{
const TPropInfo & prop = value->Manager().FindProperty(name);
if(prop.IsValid() == false) return false;
return SavePropToFile(path, value, prop);
}
TResult TSerialization::LoadPropFromFileName(const TString &path, TPropertyClass *value, const TString &name) const
{
const TPropInfo & prop = value->Manager().FindProperty(name);
if(prop.IsValid() == false) return false;
return LoadPropFromFile(path, value, prop);
}
#endif //TESTAPP_SERIALIZATION_H
| true |
74c883dc14601acd091f099f474a837727e2dfd9
|
C++
|
blackzhy/PAT-Basic-Level
|
/1031.cpp
|
UTF-8
| 1,017 | 2.921875 | 3 |
[] |
no_license
|
#include <iostream>
#include <string>
using namespace std;
int main()
{
int number = 0;
int weight[17] = { 7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};
int z = 0;
char m[11] = { '1','0','X','9','8','7','6','5','4','3','2' };
bool flag = true;
bool character = false;
string IDtemp;
cin >> number;
for (int i = 0; i < number; i++)
{
cin >> IDtemp;
if (IDtemp.length() != 18)
{
cout << IDtemp;
flag = false;
continue;
}
else
{
for (int j = 0; j < 17; j++)
{
if (IDtemp[j]<'0' || IDtemp[j]>'9')
{
cout << IDtemp << endl;
flag = false;
character = true;
break;
}
}
if (character)
{
character = false;
continue;
}
}
int temp = 0;
for (int j = 0; j < 17; j++)
temp += (IDtemp[j] - '0')*weight[j];
z = temp % 11;
if (IDtemp[17] != m[z])
{
cout << IDtemp<<endl;
flag = false;
continue;
}
}
if (flag)
cout << "All passed";
system("pause");
return 0;
}
| true |
3ea9d40d5af983e983c2c6293fd33aed82c93e8d
|
C++
|
kartikeytripathi/hackerrank-Algorithms
|
/WarmUp/diagonalDifference.cpp
|
UTF-8
| 856 | 3.0625 | 3 |
[] |
no_license
|
//Hackerrank Algorithm Warmup Challenge #7
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int a[100][100], n, diagonal1 = 0, diagonal2 = 0, difference = 0;
cin >> n;
for(int i = 0 ; i < n ; i++)
{
for(int j = 0 ; j < n ; j++)
{
cin>>a[i][j];
}
}
for(int i = 0 ; i < n ; i++)
{
for(int j = 0 ; j < n ; j++)
{
if(i == j)
{
diagonal1 += a[i][j];
}
if(i+j == (n-1))
{
diagonal2 += a[i][j];
}
}
}
difference = abs(diagonal1 - diagonal2);
cout<<difference;
return 0;
}
| true |
80c798a6d3f6d5cf8aa609dda04d33b0c6521dd2
|
C++
|
JonahtCheyette/SteampunkGame
|
/Sprite.cpp
|
UTF-8
| 2,172 | 3.203125 | 3 |
[] |
no_license
|
#include "stdafx.h"
void Sprite::load(std::string path, SDL_Renderer* renderer, int scaleBy) {
//Load image at specified path
SDL_Surface* loadedSurface = IMG_Load(path.c_str());
if(loadedSurface == NULL){
std::cout << "Img didn't load at " + path << std::endl;
}
w = loadedSurface -> w;
h = loadedSurface -> h;
w *= scaleBy;
h *= scaleBy;
//Create texture from surface pixels
Texture = SDL_CreateTextureFromSurface(renderer, loadedSurface);
if(Texture == NULL) {
printf( "Unable to create texture from rendered text! SDL Error: %s\n", SDL_GetError() );
}
//Get rid of old loaded surface
SDL_FreeSurface(loadedSurface);
}
void Sprite::free() {
if (Texture != nullptr) {
SDL_DestroyTexture(Texture);
Texture = nullptr;
w = 0;
h = 0;
}
}
void Sprite::loadText(std::string textureText, SDL_Color textColor, TTF_Font* gFont, SDL_Renderer* renderer){
//Render text surface
SDL_Surface* textSurface = TTF_RenderText_Solid( gFont, textureText.c_str(), textColor );
if(textSurface == NULL) {
printf( "Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError() );
}
//Create texture from surface pixels
Texture = SDL_CreateTextureFromSurface( renderer, textSurface );
if(Texture == NULL) {
printf( "Unable to create texture from rendered text! SDL Error: %s\n", SDL_GetError() );
}
w = textSurface -> w;
h = textSurface -> h;
//Get rid of old surface
SDL_FreeSurface( textSurface );
}
void Sprite::render(SDL_Renderer* renderer, int x, int y, int cx, int cy, int width, int height, SDL_Rect* clip, float angle, SDL_Point* center, SDL_RendererFlip flip) {
//set rendering space
SDL_Rect renderQuad;
if(width == -1 && height == -1){
renderQuad = {x - cx - (w/2), y - cy - (h/2), w, h};
} else {
renderQuad = {x - cx - (width/2), y - cy - (height/2), width, height};
}
//Render to screen
SDL_RenderCopyEx(renderer, Texture, clip, &renderQuad, angle, center, flip);
}
int Sprite::getWidth(){
return w;
}
int Sprite::getHeight(){
return h;
}
| true |