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 |
---|---|---|---|---|---|---|---|---|---|---|---|
1ed00899d611a13c518faaeb046704c623debb2e
|
C++
|
ABGEO/ABGEOs_CodeForces_Projects
|
/A/22/main.cpp
|
UTF-8
| 520 | 3.0625 | 3 |
[
"MIT"
] |
permissive
|
#include <cstdio>
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
int n = 0;
cin >> n;
int item[n];
for (int i = 0; i < n; i++)
cin >> item[i];
int x = *min_element(item, item + n);
int result(x);
for (int i = 0; i < n; i++)
if (item[i] > x)
if (result == x || item[i] < result)
result = item[i];
if (result != x)
cout << result;
else
cout << "NO";
return result;
}
| true |
1b5cd1d5fcfe8ab057d04c8e5d3395a4c280938b
|
C++
|
anuwu/Competitive-Programming
|
/Leetcode/critical_connection.cpp
|
UTF-8
| 2,393 | 2.84375 | 3 |
[] |
no_license
|
class Solution {
public:
unordered_set<int> dfs (int u, int pi, unordered_set<int> &ancestors, vector<bool> &vis, vector<vector<int>> &adj, vector<vector<int>> &crit)
{
int v ;
vis[u] = true ;
ancestors.insert(u) ;
unordered_set<int> my_back, neigh_back ;
printf("pi = %d, Ancestors of %d -> ", pi, u) ;
for (auto it = ancestors.begin() ; it != ancestors.end() ; it++)
printf("%d, ", *it) ;
printf("\n") ;
for (int i = 0 ; i < adj[u].size() ; i++)
{
v = adj[u][i] ;
if (vis[v])
{
if (ancestors.find(v) != ancestors.end() && v != pi)
my_back.insert(v) ;
}
else
{
neigh_back = dfs(v, u, ancestors, vis, adj, crit) ;
ancestors.erase(ancestors.find(v)) ;
bool is_crit = true ;
for (auto it = neigh_back.begin() ; it != neigh_back.end() ; it++)
{
my_back.insert(*it) ;
if (ancestors.find(*it) != ancestors.end())
is_crit = false ;
}
if (is_crit)
{
vector<int> cri {u, v} ;
crit.push_back(cri) ;
}
}
}
printf("Back of %d -> ", u) ;
for (auto it = my_back.begin() ; it != my_back.end() ; it++)
printf("%d, ", *it) ;
printf("\n") ;
return my_back ;
}
vector<vector<int>> criticalConnections(int n, vector<vector<int>>& connections)
{
int i, j, u, v, seed ;
vector<vector<int>> crit ;
vector<vector<int>> adj(n, vector<int> ()) ;
vector<bool> vis(n, false) ;
for (i = 0 ; i < connections.size() ; i++)
{
u = connections[i][0] ;
v = connections[i][1] ;
adj[u].push_back(v) ;
adj[v].push_back(u) ;
}
seed = 0 ;
do
{
unordered_set<int> ancestors ;
dfs(seed, -1, ancestors, vis, adj, crit) ;
do seed++ ; while (seed < n && vis[seed]) ;
} while (seed < n) ;
return crit ;
}
};
| true |
88915d479b5555e13d253820b1de6e5350ed24bd
|
C++
|
theJ8910/Brimstone
|
/include/brimstone/factory/BasicFactory.hpp
|
UTF-8
| 1,775 | 2.9375 | 3 |
[
"MIT"
] |
permissive
|
/*
factory/BasicFactory.hpp
-----------------------
Copyright (c) 2014, theJ89
Description:
Defines a basic concrete factory class, whose .create() method will instantiate
a concrete class with its default constructor.
Part of the engine's implementation of the Abstract Factory pattern.
Provides a macro, BS_MAKE_FACTORY, to automate the creation of a basic factory and
its registration with a factory manager.
*/
#ifndef BS_FACTORY_BASICFACTORY_HPP
#define BS_FACTORY_BASICFACTORY_HPP
//Includes
#include <brimstone/factory/IFactory.hpp> //IFactory
namespace Brimstone {
template< typename Abstract, typename Concrete >
class BasicFactory : public IFactory< Abstract > {
public:
virtual Abstract create() const;
};
template< typename Abstract, typename Concrete >
Abstract BasicFactory< Abstract, Concrete >::create() const {
return Concrete();
}
//Specialization for pointer types
template< typename Abstract, typename Concrete >
class BasicFactory< Abstract*, Concrete* > : public IFactory< Abstract* > {
public:
virtual Abstract* create() const;
};
template< typename Abstract, typename Concrete >
Abstract* BasicFactory< Abstract*, Concrete* >::create() const {
return new Concrete;
}
//Make a BasicFactory (with the given abstract and concrete types) that adds itself
//to the given manager under the given key when it has constructed itself.
#define BS_MAKE_FACTORY( abstractClassName, concreteClassName, manager, key ) \
class concreteClassName##_Factory : public Brimstone::BasicFactory< abstractClassName*, concreteClassName* > { \
public:\
concreteClassName##_Factory() { manager.add( key, *this ); }\
\
} concreteClassName##_FactoryInst{};
}
#endif //BS_FACTORY_BASICFACTORY_HPP
| true |
a43d244f460a2d6682ed8f2e82ed28ac9241ada2
|
C++
|
PraveenDubey01/Apna_College_Programs
|
/Bubble_SORT.cpp
|
UTF-8
| 637 | 3.78125 | 4 |
[] |
no_license
|
#include<iostream>
using namespace std;
void BubbleSort( int arr[], int size)
{
int temp;
for( int i=0;i<size-1;i++)
{
for(int j=0;j<size-i-1;j++)
{
if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
}
void PrintArray(int arr[], int size)
{
for(int i=0;i<size;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
}
int main()
{
int arr[]={3, 1, 6, 2, 9};
int size=sizeof(arr)/sizeof(int);
cout<<"Unsorted Array is:";
PrintArray(arr,size);
BubbleSort(arr,size);
cout<<"\nSorted Array is:";
PrintArray(arr,size);
return 0;
}
| true |
47e303f415031de0dff8ccef4cadf8f4b3e222be
|
C++
|
fritzethegreat/Arduino
|
/Blink/blink.cpp
|
UTF-8
| 738 | 3.515625 | 4 |
[] |
no_license
|
/*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.
This example code is in the public domain, as far as I know.
*/
#include <avr/Arduino.h>
int main() {
// run Arduino initialization script for setting delay vectors and timing
// variables
init();
// initialize the digital pin as an output.
// Pin 13 has an LED connected on most Arduino boards:
pinMode(13, OUTPUT);
// actual loop for blinking the led each second
while( 1 ){
digitalWrite(13, HIGH); // set the LED on
delay(1000); // wait for a second
digitalWrite(13, LOW); // set the LED off
delay(1000); // wait for a second
}
// complete
return 0;
} // end int main()
| true |
dbf6e57330ded45f37e74361ac09c8fef177dde5
|
C++
|
laniakea1990/VS_Essential_Cplusplus
|
/Exercise_Chapter1/1_5_b.cpp
|
UTF-8
| 742 | 3.53125 | 4 |
[] |
no_license
|
/*
#include<iostream>
#include<iomanip>
#include<cstring>
using namespace std;
int main()
{
const int nm_size = 128;
char user_name[nm_size];
cout << "Please enter your name: ";
cin >> setw(nm_size) >> user_name;
switch (strlen(user_name))
{
case 0:
cout << "Ah, the user with no name."
<< "Well, ok, hi, user with no name.\n";
break;
getchar();
case 1:
cout << "A 1-character name? Hmm, have your read Kafka?: "
<< "Hello, " << user_name << endl;
getchar();
break;
case 127:
cout << "That is a very big name, indeed --"
<< "we may have needed to shorten it!\n"
<< "In any case,\n";
default:
cout << "Hello, " << user_name
<< " --happy to make your acquaintance!\n";
getchar();
break;
}
}
*/
| true |
13e94aa68ea3c4f8aa3eca3096ea75c0c993f182
|
C++
|
briancpark/deitel-cpp
|
/VCB600ENU1/MSDN_VCB/SAMPLES/VC98/SDK/COM/INOLE2/INTERFAC/IENUMCON.CPP
|
UTF-8
| 4,899 | 2.578125 | 3 |
[] |
no_license
|
/*
* IENUMCON.CPP
*
* Standard implementation of an enumerator with the
* IEnumConnections interface that will generally not need
* modification.
*
* Copyright (c)1993-1995 Microsoft Corporation, All Rights Reserved
*
* Kraig Brockschmidt, Microsoft
* Internet : kraigb@microsoft.com
* Compuserve: >INTERNET:kraigb@microsoft.com
*/
#include "ienumcon.h"
/*
* CEnumConnections::CEnumConnections
* CEnumConnections::~CEnumConnections
*
* Parameters (Constructor):
* pUnkRef LPUNKNOWN to use for reference counting.
* cConn ULONG number of connections in prgpConn
* prgConnData LPCONNECTDATA to the array to enumerate.
*/
CEnumConnections::CEnumConnections(LPUNKNOWN pUnkRef, ULONG cConn
, LPCONNECTDATA prgConnData)
{
UINT i;
m_cRef=0;
m_pUnkRef=pUnkRef;
m_iCur=0;
m_cConn=cConn;
m_rgConnData=new CONNECTDATA[(UINT)cConn];
if (NULL!=m_rgConnData)
{
for (i=0; i < cConn; i++)
m_rgConnData[i]=prgConnData[i];
}
return;
}
CEnumConnections::~CEnumConnections(void)
{
if (NULL!=m_rgConnData)
delete [] m_rgConnData;
return;
}
/*
* CEnumConnections::QueryInterface
* CEnumConnections::AddRef
* CEnumConnections::Release
*
* Purpose:
* IUnknown members for CEnumConnections object.
*/
STDMETHODIMP CEnumConnections::QueryInterface(REFIID riid
, LPVOID *ppv)
{
*ppv=NULL;
/*
* Enumerators are separate objects, so we only need to support
* ou IUnknown and IEnumConnections interfaces here with no
* concern for aggregation.
*/
if (IID_IUnknown==riid || IID_IEnumConnections==riid)
*ppv=(LPVOID)this;
if (NULL!=*ppv)
{
((LPUNKNOWN)*ppv)->AddRef();
return NOERROR;
}
return ResultFromScode(E_NOINTERFACE);
}
STDMETHODIMP_(ULONG) CEnumConnections::AddRef(void)
{
++m_cRef;
m_pUnkRef->AddRef();
return m_cRef;
}
STDMETHODIMP_(ULONG) CEnumConnections::Release(void)
{
m_pUnkRef->Release();
if (0L!=--m_cRef)
return m_cRef;
delete this;
return 0;
}
/*
* CEnumConnections::Next
*
* Purpose:
* Returns the next element in the enumeration.
*
* Parameters:
* cConn ULONG number of connections to return.
* pConnData LPCONNECTDATA in which to store the returned
* structures.
* pulEnum ULONG * in which to return how many we
* enumerated.
*
* Return Value:
* HRESULT NOERROR if successful, S_FALSE otherwise,
*/
STDMETHODIMP CEnumConnections::Next(ULONG cConn
, LPCONNECTDATA pConnData, ULONG *pulEnum)
{
ULONG cReturn=0L;
if (NULL==m_rgConnData)
return ResultFromScode(S_FALSE);
if (NULL==pulEnum)
{
if (1L!=cConn)
return ResultFromScode(E_POINTER);
}
else
*pulEnum=0L;
if (NULL==pConnData || m_iCur >= m_cConn)
return ResultFromScode(S_FALSE);
while (m_iCur < m_cConn && cConn > 0)
{
*pConnData++=m_rgConnData[m_iCur];
m_rgConnData[m_iCur++].pUnk->AddRef;
cReturn++;
cConn--;
}
if (NULL!=pulEnum)
*pulEnum=cReturn;
return NOERROR;
}
/*
* CEnumConnections::Skip
*
* Purpose:
* Skips the next n elements in the enumeration.
*
* Parameters:
* cSkip ULONG number of elements to skip.
*
* Return Value:
* HRESULT NOERROR if successful, S_FALSE if we could not
* skip the requested number.
*/
STDMETHODIMP CEnumConnections::Skip(ULONG cSkip)
{
if (((m_iCur+cSkip) >= m_cConn) || NULL==m_rgConnData)
return ResultFromScode(S_FALSE);
m_iCur+=cSkip;
return NOERROR;
}
/*
* CEnumConnections::Reset
*
* Purpose:
* Resets the current element index in the enumeration to zero.
*
* Parameters:
* None
*/
STDMETHODIMP CEnumConnections::Reset(void)
{
m_iCur=0;
return NOERROR;
}
/*
* CEnumConnections::Clone
*
* Purpose:
* Returns another IEnumConnections with the same state as ourselves.
*
* Parameters:
* ppEnum LPENUMCONNECTIONPOINTS * in which to return the
* new object.
*/
STDMETHODIMP CEnumConnections::Clone(LPENUMCONNECTIONS *ppEnum)
{
PCEnumConnections pNew;
*ppEnum=NULL;
//Create the clone
pNew=new CEnumConnections(m_pUnkRef, m_cConn, m_rgConnData);
if (NULL==pNew)
return ResultFromScode(E_OUTOFMEMORY);
pNew->AddRef();
pNew->m_iCur=m_iCur;
*ppEnum=pNew;
return NOERROR;
}
| true |
efeedd7a4bc82a0823c4ce8cd273a49346fd9a34
|
C++
|
jtesquibel/Professional-C-Projects
|
/pa2/PasswordCrack.cpp
|
UTF-8
| 6,228 | 2.90625 | 3 |
[] |
no_license
|
//
// PasswordCrack.cpp
// password-mac
//
// Created by Jonathan Esquibel on 2/8/17.
// Copyright © 2017 Sanjay Madhav. All rights reserved.
//
#include "PasswordCrack.hpp"
PasswordCrack::PasswordCrack(std::string fileName1, std::string fileName2)
{
this->file1 = fileName1;
this->file2 = fileName2;
myUnMap.rehash(100000);
this->ReadFile();
}
void PasswordCrack::ReadFile()
{
timer.start();
std::ifstream dictFile(file1);
std::string line;
while (std::getline(dictFile, line))
{
unsigned char hash[20];
char hex_str[41];
sha1::calc(line.c_str(), line.length(), hash);
sha1::toHexString(hash, hex_str);
myUnMap.insert(std::make_pair(hex_str, line));
}
dictFile.close();
this->DictionaryLookup();
}
void PasswordCrack::DictionaryLookup()
{
std::ifstream passFile(file2);
std::string line2;
int entryNum = 0;
while (std::getline(passFile, line2))
{
std::unordered_map<std::string, std::string>::const_iterator it = myUnMap.find(line2);
if (it == myUnMap.end())
{
// then it was not found
Password *p = new Password(entryNum, line2, "??");
unsolved.push_back(*p);
myMap.insert(std::make_pair(entryNum, *p));
}
else
{
// then it was found
Password *p = new Password(entryNum, line2, it->second);
myMap.insert(std::make_pair(entryNum, *p));
}
entryNum++;
}
passFile.close();
this->BruteForce(35, 4);
}
void PasswordCrack::BruteForce(int base, int length)
{
std::vector<int> attempt = {0,0,0,0};
int size = 1;
for (int j = 0; j < pow(36, size); j++)
{
unsigned char hash[20];
char hex_str[41];
sha1::calc(this->NumtoString(attempt).substr(this->NumtoString(attempt).size()-size).c_str(), size, hash);
// sha1::calc(this->NumtoString(attempt).c_str(), size, hash);
sha1::toHexString(hash, hex_str);
for (std::vector<Password>::iterator it = unsolved.begin(); it != unsolved.end(); ++it)
{
// std::cout << *it << std::endl;
if (it->hash == hex_str)
{
// then brute force cracked the password
std::cout << "Brute force worked" << std::endl;
std::map<int, Password>::iterator itt = myMap.find(it->row);
if (itt != myMap.end())
{
itt->second.solution = this->NumtoString(attempt).substr(this->NumtoString(attempt).size()-size);
}
}
}
if (attempt[attempt.size()-1] == 35)
{
if (size == 1)
{
size++;
}
attempt[attempt.size()-1] = 0;
if (attempt[attempt.size()-2] == 35)
{
if (size == 2)
{
size++;
}
attempt[attempt.size()-2] = 0;
if (attempt[attempt.size()-3] == 35)
{
if (size == 3)
{
size++;
}
attempt[attempt.size()-3] = 0;
if (attempt[attempt.size()-4] == 35)
{
size++;
break;
}
// attempt
else
{
attempt[attempt.size()-4]++;
// unsigned char hash[20];
// char hex_str[41];
// sha1::calc(this->NumtoString(attempt).substr(this->NumtoString(attempt).size()-size).c_str(), size, hash);
// // sha1::calc(this->NumtoString(attempt).c_str(), size, hash);
// sha1::toHexString(hash, hex_str);
// for (std::vector<Password>::iterator it = unsolved.begin(); it != unsolved.end(); ++it)
// {
// // std::cout << *it << std::endl;
// if (it->hash == hex_str)
// {
// // then brute force cracked the password
// std::cout << "Brute force worked" << std::endl;
// std::map<int, Password>::iterator itt = myMap.find(it->row);
// if (itt != myMap.end())
// {
// itt->second.solution = this->NumtoString(attempt).substr(this->NumtoString(attempt).size()-size);
// }
//
// }
// }
}
}
else
{
attempt[attempt.size()-3]++;
}
}
else
{
attempt[attempt.size()-2]++;
}
}
else
{
attempt[attempt.size()-1]++;
}
// std::cout << attempt[0] << " " << attempt[1] << " " << attempt[2] << " " << attempt[3] << std::endl;
}
double elapsed = timer.getElapsed();
std::cout << "Time to load dictionary = " << elapsed << std::endl;
this->PrintToFile();
}
std::string PasswordCrack::NumtoString(std::vector<int> attempt)
{
char alphabetNum[37] = "abcdefghijklmnopqrstuvwxyz0123456789";
char pass[5];
for (int i = 0; i < attempt.size(); i++)
{
pass[i] = alphabetNum[attempt[i]];
}
// std::cout << pass << std::endl;
return pass;
}
//void PasswordCrack::ParallelBrute()
//{
// tbb::parallel_invoke([this]
// {
//
// });
//}
void PasswordCrack::PrintToFile()
{
std::ofstream outFile;
outFile.open("pass_solved.txt");
for (std::map<int, Password>::iterator it = myMap.begin(); it != myMap.end(); ++it)
{
outFile << it->second.hash << "," << it->second.solution << std::endl;
}
outFile.close();
}
| true |
15a9d6d50d33bcb90bf80007d753df0a6e5b546c
|
C++
|
yoshipaulbrophy/xrtl
|
/xrtl/base/threading/event_test.cc
|
UTF-8
| 13,134 | 2.828125 | 3 |
[
"Apache-2.0"
] |
permissive
|
// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "xrtl/base/threading/event.h"
#include "xrtl/base/stopwatch.h"
#include "xrtl/base/threading/thread.h"
#include "xrtl/testing/gtest.h"
namespace xrtl {
namespace {
bool ShouldBlock(ref_ptr<Event> event) {
return Thread::Wait(event, kImmediateTimeout) == Thread::WaitResult::kTimeout;
}
bool ShouldNotBlock(ref_ptr<Event> event) {
return Thread::Wait(event, kImmediateTimeout) == Thread::WaitResult::kSuccess;
}
class EventTest : public ::testing::Test {
public:
// We need high resolution timing to ensure our waits are measured correctly.
static void SetUpTestCase() { Process::EnableHighResolutionTiming(); }
static void TearDownTestCase() { Process::DisableHighResolutionTiming(); }
};
// Tests the basic behavior of a manual reset event.
TEST_F(EventTest, ManualResetEvent) {
// Create unset and expect blocking.
auto event = Event::CreateManualResetEvent(false);
EXPECT_NE(nullptr, event);
EXPECT_TRUE(ShouldBlock(event));
// Set and expect passing.
event->Set();
EXPECT_TRUE(ShouldNotBlock(event));
// Reset and expect blocking again.
event->Reset();
EXPECT_TRUE(ShouldBlock(event));
}
// Tests a manual reset event with an initial value of signaled.
TEST_F(EventTest, ManualResetEventInitiallySet) {
// Create set and expect passing.
auto event = Event::CreateManualResetEvent(true);
EXPECT_NE(nullptr, event);
EXPECT_TRUE(ShouldNotBlock(event));
// Reset and expect blocking.
event->Reset();
EXPECT_TRUE(ShouldBlock(event));
}
// Tests that manual reset events wake waiting threads.
TEST_F(EventTest, ManualResetEventWaking) {
// Create unset and expect blocking.
auto event = Event::CreateManualResetEvent(false);
EXPECT_NE(nullptr, event);
EXPECT_TRUE(ShouldBlock(event));
// Spin up a thread that should block on the event.
auto fence_event = Event::CreateManualResetEvent(false);
auto thread = Thread::Create({}, [&]() {
// Expect us to block.
EXPECT_TRUE(ShouldBlock(event));
// Continue test on the main thread.
fence_event->Set();
// Now actually wait until we are signaled. This will block.
EXPECT_EQ(Thread::WaitResult::kSuccess, Thread::Wait(event));
});
// Wait until the thread hits the fence.
EXPECT_EQ(Thread::WaitResult::kSuccess, Thread::Wait(fence_event));
// Set the event and let the thread return.
event->Set();
// Wait for thread to cleanly exit.
EXPECT_TRUE(thread->Join());
}
// Tests the basic behavior of an auto reset event.
TEST_F(EventTest, AutoResetEvent) {
// Create unset and expect blocking.
auto event = Event::CreateAutoResetEvent(false);
EXPECT_NE(nullptr, event);
EXPECT_TRUE(ShouldBlock(event));
// Set and expect passing.
event->Set();
EXPECT_TRUE(ShouldNotBlock(event));
// The event should have been automatically reset and block.
EXPECT_TRUE(ShouldBlock(event));
// Set and then manually reset. Should block.
event->Set();
event->Reset();
EXPECT_TRUE(ShouldBlock(event));
}
// Tests an auto reset event with an initial value of signaled.
TEST_F(EventTest, AutoResetEventInitiallySet) {
// Create set and expect passing.
auto event = Event::CreateAutoResetEvent(true);
EXPECT_NE(nullptr, event);
EXPECT_TRUE(ShouldNotBlock(event));
// The event should have been automatically reset and block.
EXPECT_TRUE(ShouldBlock(event));
}
// Tests that auto reset events wake waiting threads.
TEST_F(EventTest, AutoResetEventWaking) {
// Create unset and expect blocking.
auto event = Event::CreateAutoResetEvent(false);
EXPECT_TRUE(ShouldBlock(event));
// Spin up a thread that should block on the event.
auto fence_event = Event::CreateAutoResetEvent(false);
auto thread = Thread::Create({}, [&]() {
// Expect us to block.
EXPECT_TRUE(ShouldBlock(event));
// Continue test on the main thread.
fence_event->Set();
// Now actually wait until we are signaled. This will block.
EXPECT_EQ(Thread::WaitResult::kSuccess, Thread::Wait(event));
// Event will be auto reset to unsignaled and should block.
EXPECT_TRUE(ShouldBlock(event));
});
// Wait until the thread hits the fence.
EXPECT_EQ(Thread::WaitResult::kSuccess, Thread::Wait(fence_event));
// Set the event and let the thread return.
event->Set();
// Wait for thread to cleanly exit.
EXPECT_TRUE(thread->Join());
// Event should have been reset to unsignaled.
EXPECT_TRUE(ShouldBlock(event));
}
// Tests waiting on a single event and timeouts.
TEST_F(EventTest, WaitEvent) {
auto signaled_event = Event::CreateManualResetEvent(true);
auto unsignaled_event = Event::CreateManualResetEvent(false);
// Waiting on a signaled event should pass immediately.
EXPECT_TRUE(ShouldNotBlock(signaled_event));
// Waiting on a signaled event with a timeout should still pass immediately.
Stopwatch stopwatch;
EXPECT_EQ(Thread::WaitResult::kSuccess,
Thread::Wait(signaled_event, std::chrono::milliseconds(100)));
EXPECT_LE(stopwatch.elapsed_micros(), std::chrono::milliseconds(10));
// Waiting on an unsignaled event should block.
EXPECT_TRUE(ShouldBlock(unsignaled_event));
// Waiting on an unsignaled event with a timeout should wait a bit before
// timing out.
stopwatch.Reset();
EXPECT_EQ(Thread::WaitResult::kTimeout,
Thread::Wait(unsignaled_event, std::chrono::milliseconds(100)));
EXPECT_GE(stopwatch.elapsed_micros(), std::chrono::milliseconds(10));
// Waits should return before the timeout if the event is signaled.
auto early_event = Event::CreateManualResetEvent(false);
auto fence_event = Event::CreateAutoResetEvent(false);
auto thread = Thread::Create({}, [&]() {
// Wait until the main thread enters its wait.
Thread::Wait(fence_event);
// Wait a bit to ensure the main thread gets into its wait.
Thread::Sleep(std::chrono::milliseconds(10));
// Signal the event.
early_event->Set();
});
fence_event->Set();
stopwatch.Reset();
EXPECT_EQ(Thread::WaitResult::kSuccess,
Thread::Wait(early_event, std::chrono::seconds(100)));
EXPECT_LE(stopwatch.elapsed_micros(), std::chrono::milliseconds(100));
}
// Tests signal and wait as a single operation.
TEST_F(EventTest, SignalAndWaitEvent) {
auto signaled_event = Event::CreateManualResetEvent(true);
auto unsignaled_event = Event::CreateManualResetEvent(false);
// No-op: signal the signaled event and wait on the unsignaled event.
EXPECT_TRUE(ShouldNotBlock(signaled_event));
EXPECT_TRUE(ShouldBlock(unsignaled_event));
EXPECT_EQ(Thread::WaitResult::kTimeout,
Thread::SignalAndWait(signaled_event, unsignaled_event,
kImmediateTimeout));
EXPECT_TRUE(ShouldNotBlock(signaled_event));
EXPECT_TRUE(ShouldBlock(unsignaled_event));
// Signal the unsignaled event and wait on the signaled event.
EXPECT_EQ(Thread::WaitResult::kSuccess,
Thread::SignalAndWait(unsignaled_event, signaled_event,
kImmediateTimeout));
// Unsignaled should be signaled by the call and should not block.
EXPECT_TRUE(ShouldNotBlock(unsignaled_event));
EXPECT_TRUE(ShouldNotBlock(signaled_event));
unsignaled_event->Reset();
signaled_event->Set();
// Waiting on an unsignaled event with a timeout should wait a bit before
// timing out.
Stopwatch stopwatch;
EXPECT_EQ(Thread::WaitResult::kTimeout,
Thread::SignalAndWait(signaled_event, unsignaled_event,
std::chrono::milliseconds(100)));
EXPECT_GE(stopwatch.elapsed_micros(), std::chrono::milliseconds(10));
}
// Tests waiting on any event.
TEST_F(EventTest, WaitAnyEvents) {
auto signaled_event_1 = Event::CreateManualResetEvent(true);
auto signaled_event_2 = Event::CreateManualResetEvent(true);
auto unsignaled_event_1 = Event::CreateManualResetEvent(false);
auto unsignaled_event_2 = Event::CreateManualResetEvent(false);
// Waiting on a signaled event should pass immediately.
Thread::WaitAnyResult result = Thread::WaitAny({signaled_event_1});
EXPECT_EQ(Thread::WaitResult::kSuccess, result.wait_result);
EXPECT_EQ(0, result.wait_handle_index);
// Waiting on an unsignaled event should block.
result = Thread::WaitAny({unsignaled_event_1}, kImmediateTimeout);
EXPECT_EQ(Thread::WaitResult::kTimeout, result.wait_result);
// Waiting on a mix of events should return the right index.
result = Thread::WaitAny({signaled_event_1, unsignaled_event_1});
EXPECT_EQ(Thread::WaitResult::kSuccess, result.wait_result);
EXPECT_EQ(0, result.wait_handle_index);
result = Thread::WaitAny({unsignaled_event_1, signaled_event_1});
EXPECT_EQ(Thread::WaitResult::kSuccess, result.wait_result);
EXPECT_EQ(1, result.wait_handle_index);
// Waiting on multiple signaled events should succeed.
result = Thread::WaitAny({signaled_event_1, signaled_event_2});
EXPECT_EQ(Thread::WaitResult::kSuccess, result.wait_result);
EXPECT_LE(0, result.wait_handle_index);
EXPECT_GE(1, result.wait_handle_index);
// Waiting on an unsignaled event with a timeout should wait a bit before
// timing out.
Stopwatch stopwatch;
result = Thread::WaitAny({unsignaled_event_1, unsignaled_event_2},
std::chrono::milliseconds(100));
EXPECT_EQ(Thread::WaitResult::kTimeout, result.wait_result);
EXPECT_GT(stopwatch.elapsed_micros(), std::chrono::milliseconds(10));
// Waits should return before the timeout if an event is signaled.
auto fence_event = Event::CreateAutoResetEvent(false);
auto thread = Thread::Create({}, [&]() {
// Wait until the main thread enters its wait.
Thread::Wait(fence_event);
// Wait a bit to ensure the main thread gets into its wait.
Thread::Sleep(std::chrono::milliseconds(100));
// Signal the event.
unsignaled_event_2->Set();
});
fence_event->Set();
result = Thread::WaitAny({unsignaled_event_1, unsignaled_event_2},
std::chrono::seconds(100));
EXPECT_EQ(Thread::WaitResult::kSuccess, result.wait_result);
EXPECT_EQ(1, result.wait_handle_index);
unsignaled_event_2->Reset();
}
// Tests waiting on all events.
TEST_F(EventTest, WaitAllEvents) {
auto signaled_event_1 = Event::CreateManualResetEvent(true);
auto signaled_event_2 = Event::CreateManualResetEvent(true);
auto unsignaled_event_1 = Event::CreateManualResetEvent(false);
auto unsignaled_event_2 = Event::CreateManualResetEvent(false);
// Waiting on a signaled event should pass immediately.
EXPECT_EQ(Thread::WaitResult::kSuccess, Thread::WaitAll({signaled_event_1}));
// Waiting on an unsignaled event should block.
EXPECT_EQ(Thread::WaitResult::kTimeout,
Thread::WaitAll({unsignaled_event_1}, kImmediateTimeout));
// Waiting on a mix of events should return only when all are set.
EXPECT_EQ(Thread::WaitResult::kSuccess,
Thread::WaitAll({signaled_event_1, signaled_event_2}));
// Waiting on an unsignaled event with a timeout should wait a bit before
// timing out.
Stopwatch stopwatch;
EXPECT_EQ(Thread::WaitResult::kTimeout,
Thread::WaitAll({signaled_event_1, unsignaled_event_1},
std::chrono::milliseconds(100)));
EXPECT_GE(stopwatch.elapsed_micros(), std::chrono::milliseconds(10));
// Waits should timeout if not all events are set.
auto fence_event = Event::CreateAutoResetEvent(false);
auto thread = Thread::Create({}, [&]() {
// Wait until the main thread enters its wait.
Thread::Wait(fence_event);
// Signal one of the events after a moment.
Thread::Sleep(std::chrono::milliseconds(100));
unsignaled_event_2->Set();
});
fence_event->Set();
EXPECT_EQ(Thread::WaitResult::kTimeout,
Thread::WaitAll({unsignaled_event_1, unsignaled_event_2},
std::chrono::milliseconds(100)));
// Waits should return before the timeout if all events are signaled.
thread = Thread::Create({}, [&]() {
// Wait until the main thread enters its wait.
Thread::Wait(fence_event);
// Wait a bit to ensure the main thread gets into its wait.
Thread::Sleep(std::chrono::milliseconds(100));
// Signal the events.
unsignaled_event_1->Set();
unsignaled_event_2->Set();
});
fence_event->Set();
EXPECT_EQ(Thread::WaitResult::kSuccess,
Thread::WaitAll({unsignaled_event_1, unsignaled_event_2},
std::chrono::seconds(100)));
unsignaled_event_1->Reset();
unsignaled_event_2->Reset();
}
} // namespace
} // namespace xrtl
| true |
c803cae0b7a74fcfc711856a3e2fbd40adb020c9
|
C++
|
antsoh161/Graphics
|
/lab1/lab1-4.cpp
|
UTF-8
| 6,535 | 2.53125 | 3 |
[] |
no_license
|
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <cstdlib>
#include <iostream>
#include "readfile.hpp"
#include "my_shader.hpp"
my_shader shader0;
static void error_callback(int error, const char* description)
{
std::cerr << description;
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if ((key == GLFW_KEY_ESCAPE || key == GLFW_KEY_Q) && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
if ((key == GLFW_KEY_R) && action == GLFW_PRESS) {
//-----------------------------------------------------------------------------------------------------------------------------------------------------------//
// Reload shaders
//-----------------------------------------------------------------------------------------------------------------------------------------------------------//
shader0.update("../lab1-4_vs.glsl","../lab1-4_fs.glsl");
}
//-----------------------------------------------------------------------------------------------------------------------------------------------------------//
// Update some parameter for the vertex shader here.
//-----------------------------------------------------------------------------------------------------------------------------------------------------------//
if ((key == GLFW_KEY_LEFT) && ( (action == GLFW_PRESS) || (action == GLFW_REPEAT))){
shader0.x_offset = shader0.x_offset-0.1;
}
if ((key == GLFW_KEY_RIGHT) && ( (action == GLFW_PRESS) || (action == GLFW_REPEAT))){
shader0.x_offset = shader0.x_offset+0.1;
}
if ((key == GLFW_KEY_UP) && ( (action == GLFW_PRESS) || (action == GLFW_REPEAT))){
shader0.y_offset = shader0.y_offset+0.1;
}
if ((key == GLFW_KEY_DOWN) && ( (action == GLFW_PRESS) || (action == GLFW_REPEAT))){
shader0.y_offset = shader0.y_offset-0.1;
}
}
static void scroll_callback(GLFWwindow* window, double scroll_v, double scroll_h)
{
//-----------------------------------------------------------------------------------------------------------------------------------------------------------//
// Update some parameter for the fragment shader here.
//-----------------------------------------------------------------------------------------------------------------------------------------------------------//
if(scroll_h > 0){
if(shader0.modifier>0)
shader0.modifier = shader0.modifier-0.1;
}
else{
if(shader0.modifier<5)
shader0.modifier = shader0.modifier+0.1;
}
}
static void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
int main(int argc, char const *argv[])
{
// start GL context and O/S window using the GLFW helper library
glfwSetErrorCallback(error_callback);
if( !glfwInit() )
exit(EXIT_FAILURE);
GLFWwindow* window = glfwCreateWindow (640, 480, "Hello Triangle", NULL, NULL);
glfwSetKeyCallback( window, key_callback);
glfwSetScrollCallback( window, scroll_callback);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
if (!window) {
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwMakeContextCurrent (window);
// start GLEW extension handler
glewExperimental = GL_TRUE;
glewInit ();
//-----------------------------------------------------------------------------------------------------------------------------------------------------------//
// Set up geometry, VBO, VAO
//-----------------------------------------------------------------------------------------------------------------------------------------------------------//
GLfloat vertices[] = {-0.5f,-0.5f ,0.0f,
0.5f,-0.5f,0.0f,
0.0f,0.5f,0.0f};
GLuint VAO,VBO;
//VAO
glGenVertexArrays(1,&VAO);
glBindVertexArray(VAO);
//VBO
glGenBuffers(1,&VBO);
glBindBuffer(GL_ARRAY_BUFFER,VBO);
glBufferData(GL_ARRAY_BUFFER,sizeof(vertices),vertices,GL_STATIC_DRAW);
glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,3*sizeof(GLfloat),(GLvoid*)0);
glEnableVertexAttribArray(0);
//-----------------------------------------------------------------------------------------------------------------------------------------------------------//
// load and compile shaders "../lab1-4_vs.glsl" and "../lab1-4_fs.glsl"
//-----------------------------------------------------------------------------------------------------------------------------------------------------------//
shader0.update("../lab1-4_vs.glsl","../lab1-4_fs.glsl");
//-----------------------------------------------------------------------------------------------------------------------------------------------------------//
// attach and link vertex and fragment shaders into a shader program // Done in shader0.update()
//-----------------------------------------------------------------------------------------------------------------------------------------------------------//
while (!glfwWindowShouldClose (window))
{
//-----------------------------------------------------------------------------------------------------------------------------------------------------------//
// Update uniform variables in your shader_program
//-----------------------------------------------------------------------------------------------------------------------------------------------------------//
shader0.position_offset_loc = glGetUniformLocation(shader0.shader_program,"position_offset");
shader0.modifier_loc = glGetUniformLocation(shader0.shader_program,"modifier");
glUniform1f(shader0.modifier_loc,shader0.modifier);
glUniform2f(shader0.position_offset_loc,shader0.x_offset,shader0.y_offset);
// update other events like input handling
glfwPollEvents ();
// clear the drawing surface
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//-----------------------------------------------------------------------------------------------------------------------------------------------------------//
// Issue an appropriate glDraw*() command.
//-----------------------------------------------------------------------------------------------------------------------------------------------------------//
glDrawArrays(GL_TRIANGLES,0,3);
glfwSwapBuffers (window);
}
// close GL context and any other GLFW resources
glfwTerminate();
exit(EXIT_SUCCESS);
}
| true |
365c9e7cb685f42f23eddbf25615a38193b90abf
|
C++
|
xmyqsh/leetcode2016
|
/084_largest-rectangle-in-histogram.cpp
|
UTF-8
| 563 | 2.96875 | 3 |
[] |
no_license
|
class Solution {
public:
int largestRectangleArea(vector<int>& height) {
if (height.empty()) return 0;
height.push_back(-1);
stack<int> sk;
int maxArea = 0;
for (int i = 0; i < height.size();) {
if (sk.empty() || height[i] >= height[sk.top()]) {
sk.push(i++);
} else {
int idx = sk.top();
sk.pop();
maxArea = max(maxArea, height[idx] * (sk.empty() ? i : i - sk.top() - 1));
}
}
return maxArea;
}
};
| true |
89d1cd9e170ec9785209dcffac0239c6a2b32182
|
C++
|
mpindaro/garbage-collector
|
/motoresemplice/motoresemplice.ino
|
UTF-8
| 623 | 2.609375 | 3 |
[] |
no_license
|
//Testing the DC Motors
//Define Pins
//Motor A
int enableA = 10;
int pinA1 = 2;
int pinA2 = 3;
//Motor B
int enableB = 9;
int pinB1 = 4;
int pinB2 = 5;
//define time for run
// in milliseconds
int running = 10000; //10 secons
boolean play;
void setup() {
Serial.begin (9600);
//configure pin modes
pinMode (enableA, OUTPUT);
pinMode (pinA1, OUTPUT);
pinMode (pinA2, OUTPUT);
pinMode (enableB, OUTPUT);
pinMode (pinB1, OUTPUT);
pinMode (pinB2, OUTPUT);
play = true;
}
void loop(){
digitalWrite (pinA1, HIGH);
digitalWrite (pinA2, LOW);
digitalWrite (pinB1, LOW);
digitalWrite (pinB2, HIGH);
}
| true |
7a9a962fd8b573e5af6d132529909b72dc76def7
|
C++
|
BackupTheBerlios/useoa-rose-svn
|
/trunk/OAWraps/LoopIRInterface.h
|
UTF-8
| 7,845 | 2.546875 | 3 |
[] |
no_license
|
/*
* LoopIRInterface.h
*
* Created on: May 3, 2011
* Author: snarayan
*/
#ifndef _LOOPINTERFACE_H
#define _LOOPINTERFACE_H
#include "Sage2OA.h"
#include <rose.h>
using namespace std;
using namespace OA;
using namespace Loop;
class LoopAnalStatistics {
public:
enum Rejection {
BAD_INIT = 0,
BAD_LOWER_BOUND,
BAD_UPPER_BOUND,
BAD_STEP,
REDEFINITION,
INCLUDES_FUNCTION_CALL,
INCLUDES_DEREF
};
static const char *rejectionStr[];
LoopAnalStatistics() :
mnAccepted(0),
mnRejected_BadLowerBound(0),
mnRejected_BadUpperBound(0),
mnRejected_BadStep(0),
mnForLoops(0),
mnWhileLoops(0),
mnDoWhileLoops(0)
{ }
void incrementAcceptedCounter() { mnAccepted++; }
void encounteredForLoop() { mnForLoops++; }
void encounteredWhileLoop() { mnWhileLoops++; }
void encounteredDoWhileLoop() { mnDoWhileLoops++; }
void incrementRejectedCounter(Rejection reason);
int getNumForLoops() { return mnForLoops; }
int getNumWhileLoops() { return mnWhileLoops; }
int getNumDoWhileLoops() { return mnDoWhileLoops; }
int getNumAccepted() { return mnAccepted; }
int getNumBadInit() { return mnRejected_BadInit; }
int getNumBadLowerBound() { return mnRejected_BadLowerBound; }
int getNumBadUpperBound() { return mnRejected_BadUpperBound; }
int getNumBadStep() { return mnRejected_BadStep; }
int getNumRedfinition() { return mnRejected_Redefinition; }
int getNumLoopsWithFunctionCall() { return mnRejected_FunctionCall; }
int getNumLoopsWithDeref() { return mnRejected_Deref; }
int getNumRejected() {
return getNumBadInit() +
getNumBadLowerBound() +
getNumBadUpperBound() +
getNumBadStep() +
getNumRedfinition() +
getNumLoopsWithFunctionCall() +
getNumLoopsWithDeref();
}
void output() {
cerr << "Number of for loops: " << getNumForLoops()
<< "\nNumber of while loops: " << getNumWhileLoops()
<< "\nNumber of do while loops: " << getNumDoWhileLoops()
<< "\nNumber of loops accepted: " << getNumAccepted()
<< "\nNumber of loops rejected: " << getNumRejected()
<< "\n Rejected for bad initi: " << getNumBadInit()
<< "\n Rejected for bad lower bound: " << getNumBadLowerBound()
<< "\n Rejected for bad upper bound: " << getNumBadUpperBound()
<< "\n Rejected for bad step: " << getNumBadStep()
<< "\n Rejected for ivar redfinition: " << getNumRedfinition()
<< "\n Rejected for function call: "
<< getNumLoopsWithFunctionCall()
<< "\n Rejected for pointer deref: " << getNumLoopsWithDeref()
<< endl;
}
private:
int mnAccepted;
int mnRejected_BadInit;
int mnRejected_BadLowerBound;
int mnRejected_BadUpperBound;
int mnRejected_BadStep;
int mnRejected_Redefinition;
int mnRejected_FunctionCall;
int mnRejected_Deref;
int mnForLoops;
int mnWhileLoops;
int mnDoWhileLoops;
};
static LoopAnalStatistics gStatistics;
/*! Inherited attribute for a ROSE AST traversal. This attribute will
keep track of what, and how many loops have been encountered, while
performing a top-down traversal. */
class LoopNestAttribute {
public:
LoopNestAttribute();
LoopNestAttribute(const LoopNestAttribute &orig);
/*! Add a new loop to this attribute. Every time the traversal visits
a loop it should be added, this running list of loops will keeps track
of what loops any given node in the AST is nested under. */
void addNestedLoop(OA_ptr<LoopAbstraction> loop);
/*! Returns the last loop added to the attribute. This is usually the
parent of a new loop being constructed. If the list is empty
NULL is returned */
OA_ptr<LoopAbstraction> getLastLoop() const {
OA_ptr<LoopAbstraction> ret;
if(!mNestedLoops.empty()) {
ret = mNestedLoops.back();
}
return ret;
}
private:
list<OA_ptr<LoopAbstraction> > mNestedLoops;
};
/*! Analysis to determine the loop nesting structure */
class LoopNestProcessor : public AstTopDownProcessing<LoopNestAttribute>
{
public:
LoopNestProcessor(
OA_ptr<list<OA_ptr<LoopAbstraction> > > results,
SageIRInterface &ir,
ProcHandle proc)
:
mResults(results),
mIR(ir),
mProc(proc)
{ }
/*! Called as the traversal visits nodes in the AST, the attribute
calculated for the parent node is passed by the traversal as an
argument. */
LoopNestAttribute evaluateInheritedAttribute(
SgNode *astNode,
LoopNestAttribute attrib);
/*! Return the a list of LoopAbstraction elements for valid loops */
OA_ptr<list<OA_ptr<LoopAbstraction> > > getResults()
{ return mResults;}
private:
/*! Given a node to a for statement in a SAGE AST construct a loop
abstraction object if possible. If no such object can be
constructed return NULL. Abstractions are prevented from being
built when they don't fall neatly into the format:
'for(int idxVariable = lowerBound; idxVariable < upperBound;
idxVariabl++);' */
OA_ptr<LoopAbstraction> buildLoopAbstraction(
SgNode *forStatementNode,
LoopNestAttribute const &attrib);
/* Given a SAGE for-statement initialization node, extract the named
location where the loop's index variable resides. If an index
variable can not be determined return NULL and set error to true. */
OA_ptr<MemRefExpr> extractIndexVariable(
SgForInitStatement *forStatementNode,
bool *error,
bool *isCStyleLoop);
/* Extract the index variable in a C-style loop. */
OA_ptr<MemRefExpr> extractIndexVariableInCStyleLoop(
SgForInitStatement *forStatementNode,
bool *error);
/* Extract the index variable in a C++ style loop. */
OA_ptr<MemRefExpr> extractIndexVariableInCPPStyleLoop(
SgForInitStatement *forStatementNode,
bool *error);
/* Determine the lower bound specified in a well-formatted for statement */
int extractLowerBound(
OA_ptr<MemRefExpr> indexVariable,
SgForInitStatement *init,
bool *error,
bool isCStyleLoop);
/* Extract the lower bound a C-style loop. */
int extractLowerBoundInCStyleLoop(
OA_ptr<MemRefExpr> indexVariable,
SgForInitStatement *init,
bool *error);
/* Extract the lower bound in a C++ style loop. */
int extractLowerBoundInCPPStyleLoop(
OA_ptr<MemRefExpr> indexVariable,
SgForInitStatement *init,
bool *error);
/* Determine the upper bound specified in a well-formatted for statement */
int extractUpperBound(
OA_ptr<MemRefExpr> indexVariable,
SgStatement *condition,
bool *error);
/* Determine the loop step */
int extractLoopStep(
OA_ptr<MemRefExpr> indexVariable,
SgExpression *stepExpr,
bool *error);
/* Given a node to a variable reference and an OA location abstraction
to an index variable determine if they refer to the same thing */
bool isIndexVariable(SgVarRefExp *varRef, OA_ptr<MemRefExpr> idxVar);
/* Given a statement handle for a loop extract the last statement
the loop contains. If the last statement is a loop recurse. */
StmtHandle extractLastLoopStmt(StmtHandle stmt);
// Member vars:
OA_ptr<list<OA_ptr<LoopAbstraction> > > mResults;
SageIRInterface &mIR;
ProcHandle mProc;
};
#endif
| true |
172582d9266d3ff3a92566c5b81df37e686052f7
|
C++
|
moble/PostNewtonian
|
/C++/PNEvolution.hpp
|
UTF-8
| 3,363 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
#ifndef PNEVOLUTION_HPP
#define PNEVOLUTION_HPP
#include <vector>
#include "Quaternions.hpp"
namespace PostNewtonian {
/// These functions evolve the PN orbital system, returning (by
/// reference) the orbital speed, spin vectors, and frame
/// information, as well as the completely redundant but
/// occassionally useful phase information `Phi`. Additional
/// functions are given to calculate the basis vectors of the
/// system's frame given the quaternion information on the frame.
void EvolvePN(const std::string& Approximant,
const double v_i, const double m1, const double m2,
const std::vector<double>& chi1_i, const std::vector<double>& chi2_i,
std::vector<double>& t, std::vector<double>& v,
std::vector<std::vector<double> >& chi1, std::vector<std::vector<double> >& chi2,
std::vector<Quaternions::Quaternion>& R_frame,
std::vector<double>& Phi, std::vector<std::vector<double> >& L
);
void EvolvePN(const std::string& Approximant, const double PNOrbitalEvolutionOrder,
const double v0, const double v_i,
const double m1, const double m2,
const std::vector<double>& chi1_i, const std::vector<double>& chi2_i,
const Quaternions::Quaternion& R_frame_i,
std::vector<double>& t, std::vector<double>& v,
std::vector<std::vector<double> >& chi1, std::vector<std::vector<double> >& chi2,
std::vector<Quaternions::Quaternion>& R_frame,
std::vector<double>& Phi, std::vector<std::vector<double> >& L,
const bool ForwardInTime=true
);
void EvolvePN_Q(const std::string& Approximant,
const double v_i, const double m1, const double m2,
const std::vector<double>& chi1_i, const std::vector<double>& chi2_i,
std::vector<double>& t, std::vector<double>& v,
std::vector<std::vector<double> >& chi1, std::vector<std::vector<double> >& chi2,
std::vector<Quaternions::Quaternion>& R_frame,
std::vector<double>& Phi, std::vector<std::vector<double> >& L
);
void EvolvePN_Q(const std::string& Approximant, const double PNOrbitalEvolutionOrder,
const double v0, const double v_i,
const double m1, const double m2,
const std::vector<double>& chi1_i, const std::vector<double>& chi2_i,
const Quaternions::Quaternion& R_frame_i,
std::vector<double>& t, std::vector<double>& v,
std::vector<std::vector<double> >& chi1, std::vector<std::vector<double> >& chi2,
std::vector<Quaternions::Quaternion>& R_frame,
std::vector<double>& Phi, std::vector<std::vector<double> >& L,
const unsigned int MinStepsPerOrbit=32,
const bool ForwardInTime=true
);
std::vector<std::vector<double> > ellHat(const std::vector<Quaternions::Quaternion>& R);
std::vector<std::vector<double> > nHat(const std::vector<Quaternions::Quaternion>& R);
std::vector<std::vector<double> > lambdaHat(const std::vector<Quaternions::Quaternion>& R);
};
#endif // PNEVOLUTION_HPP
| true |
3190d19b3e5a268d75bbed5660e8b378f119dae2
|
C++
|
urykhy/stuff
|
/networking/CoreSocket.hpp
|
UTF-8
| 4,648 | 2.59375 | 3 |
[] |
no_license
|
#pragma once
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <exception/Error.hpp>
namespace Util {
struct CoreSocket
{
using Error = Exception::ErrnoError;
private:
CoreSocket(const CoreSocket&) = delete;
CoreSocket& operator=(const CoreSocket&) = delete;
protected:
int m_Fd = -1;
template <class T>
ssize_t checkCall(T t, const char* msg)
{
ssize_t sRes = t();
if (sRes < 0 and errno != EAGAIN)
throw Error("fail to " + std::string(msg));
return sRes;
}
public:
CoreSocket() {}
// call bind(0) to make getsockname return port number
void bind(uint16_t aPort = 0)
{
struct sockaddr_in sAddr;
memset(&sAddr, 0, sizeof(sAddr));
sAddr.sin_family = AF_INET;
sAddr.sin_port = htons(aPort);
sAddr.sin_addr.s_addr = htonl(INADDR_ANY);
if (::bind(m_Fd, (struct sockaddr*)&sAddr, sizeof(sAddr)))
throw Error("fail to bind");
}
virtual void close()
{
if (m_Fd != -1) {
::close(m_Fd);
m_Fd = -1;
}
}
// FIONREAD on a UDP socket returns the size of the first datagram.
ssize_t ionread()
{
int sAvail = 0;
if (ioctl(m_Fd, FIONREAD, &sAvail))
throw Error("fail to get ionread");
return sAvail;
}
// Get the number of bytes in the output buffer
ssize_t outq()
{
int sSize = 0;
if (ioctl(m_Fd, TIOCOUTQ, &sSize))
throw Error("fail to get tiocoutq");
return sSize;
}
void set_buffer(int aRcv, int aSnd)
{
if (aRcv > 0 and setsockopt(m_Fd, SOL_SOCKET, SO_RCVBUF, &aRcv, sizeof(aRcv)))
throw Error("fail to set recv buffer size");
if (aSnd > 0 and setsockopt(m_Fd, SOL_SOCKET, SO_SNDBUF, &aSnd, sizeof(aSnd)))
throw Error("fail to set send buffer size");
}
std::pair<int, int> get_buffer() const
{
socklen_t sDummy = sizeof(int);
int sRcv = 0;
int sSnd = 0;
if (getsockopt(m_Fd, SOL_SOCKET, SO_RCVBUF, &sRcv, &sDummy))
throw Error("fail to get recv buffer size");
if (getsockopt(m_Fd, SOL_SOCKET, SO_SNDBUF, &sSnd, &sDummy))
throw Error("fail to get send buffer size");
return std::make_pair(sRcv, sSnd);
}
int get_error()
{
socklen_t sDummy = sizeof(int);
int sError = 0;
if (getsockopt(m_Fd, SOL_SOCKET, SO_ERROR, &sError, &sDummy))
throw Error("fail to get socket error");
return sError;
}
uint16_t get_port()
{
struct sockaddr_in sTmp;
socklen_t sLen = sizeof(sTmp);
if (getsockname(m_Fd, (struct sockaddr*)&sTmp, &sLen) == -1)
throw Error("fail to get socket addr");
return ntohs(sTmp.sin_port);
}
sockaddr_in get_peer()
{
struct sockaddr_in sTmp;
socklen_t sLen = sizeof(sTmp);
if (getpeername(m_Fd, (struct sockaddr*)&sTmp, &sLen) == -1)
throw Error("fail to get socket peer");
return sTmp;
}
int get_fd() const { return m_Fd; }
void set_reuse_port()
{
int sReuse = 1;
if (setsockopt(m_Fd, SOL_SOCKET, SO_REUSEPORT, &sReuse, sizeof(sReuse)))
throw Error("fail to set reuse port");
}
void set_nonblocking()
{
int sOld = fcntl(m_Fd, F_GETFL);
if (fcntl(m_Fd, F_SETFL, O_NONBLOCK | sOld))
throw Error("fail to set nonblocking");
}
void set_timeout()
{
struct timeval sTimeout
{
0, 100 * 1000
}; // 0.1 sec
if (setsockopt(m_Fd, SOL_SOCKET, SO_RCVTIMEO, &sTimeout, sizeof(sTimeout)))
throw Error("fail to set timeout");
if (setsockopt(m_Fd, SOL_SOCKET, SO_SNDTIMEO, &sTimeout, sizeof(sTimeout)))
throw Error("fail to set timeout");
}
virtual ~CoreSocket() { close(); }
};
} // namespace Util
| true |
277c825205033d43a24a56c4915fe3d31995fb0b
|
C++
|
kdw9502/algoHW
|
/HW3_S20141494/MAIN_SAMPLE_OPEN/MAIN_SAMPLE/heap_sort.cpp
|
UTF-8
| 940 | 3.265625 | 3 |
[] |
no_license
|
#include <stdio.h>
#include "my_types.h"
#define ELEMENT_SWAP(a,b) {ELEMENT temp;temp=a;a=b;b=temp;}
void heapify(ELEMENT data[], int left,int right, int i)
{
int size = right - left + 1;
int left_child = left+ 2 * i + 1;
int right_child =left+ 2 * i + 2;
int max =left+ i;
if (left_child <=right && data[left_child].key > data[max].key)
max = left_child;
if (right_child <=right && data[right_child].key > data[max].key)
max = right_child;
if (max != left+i)
{
ELEMENT_SWAP(data[left+i], data[left+max]);
heapify(data, left,right, max);
}
}
int HEAP_SORT(ELEMENT data[], int left, int right) {
// must return 1 if the function finishes normally or return 0 otherwise
// return 0;
int size = right - left + 1,i;
for (int i = size / 2 - 1; i >= 0; i--)
heapify(data, left,right, i);
for (int i = right; i >= left; i--)
{
ELEMENT_SWAP(data[left], data[i]);
heapify(data, left,right, 0);
}
return 1;
}
| true |
d3cde23e99f3a2573b1eba0332ee8e0429ed7d73
|
C++
|
Ryuk07/CodingSolutions
|
/Motivation Lunchtime March21.cpp
|
UTF-8
| 2,029 | 3.390625 | 3 |
[] |
no_license
|
Task: Chef has been searching for a good motivational movie that he can watch during his exam time. His hard disk has X GB of space remaining. His friend has N movies represented with (Si,Ri)
representing (space required, IMDB rating). Help Chef choose the single best movie (highest IMDB rating) that can fit in his hard disk.
Input
The first line of the input contains a single integer T
denoting the number of test cases. The description of T
test cases follows.
The first line of each test case contains two space-separated integers N
and X
.
N
lines follow. For each valid i, the i-th of these lines contains two space-separated integers Si and Ri
.
Output
For each test case, print a single line containing one integer - the highest rating of an IMDB movie which Chef can store in his hard disk.
Constraints
1≤T≤10
1≤N≤5⋅104
1≤X≤109
1≤Si,Ri≤109
for each valid i
X≥Si
for atleast one valid i
Subtasks
Subtask #1 (100 points): original constraints
Example Input
3
1 1
1 1
2 2
1 50
2 100
3 2
1 51
3 100
2 50
Example Output
1
100
51
Explanation
Example case 1: Since there is only 1
movie available and requires space equivalent to the empty space in the hard disk, Chef can only obtain maximum IMDB rating of 1
.
Example case 2: Since out of the 2
available movies, both can fit in the free memory, we only care to take the one with higher rating, i.e, rating of max(50,100)=100
.
Example case 3: Since out of the 3
available movies, only the first and the last movies fit in the free memory, we only care to take the one with higher rating amongstthese 2, i.e, rating of max(51,50)=51
Solution:
#include <bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int t;
cin>>t;
while(t--){
int x,n,s,r,a,max=0;
cin>>n>>x;
while(n--){
cin>>s>>r;
if(r>max&&s<=x){
max=r;
}
}
cout<<max<<endl;
}
return 0;
}
| true |
60ba31b4f2b2891afcd52cea98313e0d932ae730
|
C++
|
suraj98/Data-Structures-And-Algoritms
|
/Recursion - Dynamic Programing/recur_minsum_path.cpp
|
UTF-8
| 457 | 2.984375 | 3 |
[] |
no_license
|
int min(int a , int b)
{
return (a<b)?a:b;
}
int minsum(vector<vector<int> >&A,int m , int n)
{
if ( (m<0) || (n<0) )
{
return INT_MAX ;
}
else if( (m==0) && (n==0) )
{
return A[0][0];
}
else
{
return A[m][n]+min(minsum(A,m-1,n),minsum(A,m,n-1) ) ;
}
}
int Solution::minPathSum(vector<vector<int> > &A)
{
int m = A.size();
int n = A[0].size();
return minsum(A,m-1,n-1);
}
| true |
0842a7c9469f3452c07883a726e008c3f520f574
|
C++
|
gouarin/JMM_CPPLibs
|
/JMM_CPPLibs/DataStructures/RangeAccessor.h
|
UTF-8
| 1,139 | 2.734375 | 3 |
[
"Apache-2.0"
] |
permissive
|
// Copyright 2017 Jean-Marie Mirebeau, University Paris-Sud, CNRS, University Paris-Saclay
// Distributed WITHOUT ANY WARRANTY. Licensed under the Apache License, Version 2.0, see http://www.apache.org/licenses/LICENSE-2.0
#ifndef RangeAccessor_h
#define RangeAccessor_h
template<typename Pointer> class RangeAccessor {
Pointer _begin, _end;
public:
typedef Pointer pointer;
RangeAccessor(pointer __begin, pointer __end):_begin(__begin),_end(__end){};
pointer begin() const {return _begin;}
pointer end() const {return _end;}
size_t size() const {return _end - _begin;}
typedef decltype(*_begin) value_type;
value_type & operator[](size_t i) {assert(i<size()); return _begin[i];}
const value_type & operator[](size_t i) const {assert(i<size()); return _begin[i];}
value_type & back() {assert(size()>0); pointer ptr(_end); return *(--ptr);}
const value_type & back() const {assert(size()>0); pointer ptr(_end); return *(--ptr);}
value_type & front() {assert(size()>0); return *_begin;}
const value_type & front() const {assert(size()>0); return *_begin;}
};
#endif /* RangeAccessor_h */
| true |
37e6e59951f2fa4f43e6f2f7fc283156935f834d
|
C++
|
TurkeyScratch/c2001-work
|
/FIT1048/SimonSays/Dialogue.h
|
UTF-8
| 1,363 | 3.0625 | 3 |
[
"MIT"
] |
permissive
|
/*
* author : James Jefferson Luu
* project : Simon Says
* purpose : Dialogue Class Header file
* created : 2019-11-05
* updated : 2019-11-10
*
* This file contains the Dialogue class structure with its member variables
* and function prototypes. It is responsible for the obtaining and returning
* of dialogue strings in Simon Says.
*/
#ifndef DIALOGUE_H
#define DIALOGUE_H
#include <fstream> // required for reading a file
#include <string> // required for dialogue
#include <sstream> // required for dialogue
#include <vector> // required for holding the dialogue lists
class Dialogue
{
private:
std::vector<std::string*> dialogueResponses;
std::string dialogueBorderTop;
std::string dialogueGamePrompt;
std::string dialogueGameOver;
std::string dialogueBorderBottom;
static int const MAX_LENGTH = 42;
// private function for constructor
void getDialogueFile(std::string fileName);
void getUIFile(std::string fileName);
// private function for accessor
std::string getDialoguePromptOptions();
public:
// constructors
Dialogue();
Dialogue(std::string fileDialogueName, std::string fileUIName);
// destructor
~Dialogue();
// accessors
std::vector<std::string*>* getDialogueResponse();
size_t getDialogueResponseSize();
std::string getDialogueResponseLine(int index);
std::string getDialogueResponseUI(int index);
};
#endif
| true |
b90d6bb70c4f98ce74a20c56a6f4f267573bf0ed
|
C++
|
NandaPL/knuth-morris-pratt
|
/exemplos reais/stringMatching.cpp
|
UTF-8
| 769 | 2.625 | 3 |
[] |
no_license
|
// questão https://cses.fi/problemset/task/1753
#include <bits/stdc++.h>
using namespace std;
string s, t;
vector<int> p(1001233), match;
vector<int> matching(string t, string s)
{
int n = t.size(), m = s.size();
p[0] = 0;
for (int i = 1, j = 0; i < m; i++)
{
while (j > 0 && s[j] != s[i])
{
j = p[j - 1];
}
if (s[j] == s[i])
j++;
p[i] = j;
}
for (int i = 0, j = 0; i < n; i++)
{
while (j > 0 && t[i] != s[j])
j = p[j - 1];
if (s[j] == t[i])
j++;
if (j == m)
match.push_back(i - j + 1);
}
return match;
}
int main()
{
cin >> t >> s;
matching(t, s);
cout << match.size() << endl;
return 0;
}
| true |
290a2acc724f0ab38d768d4223aacbc4a56574c0
|
C++
|
dvarasm/Laboratorios-Estructuras-de-datos
|
/Labs Estructuras/Lab10/p3.cpp
|
UTF-8
| 709 | 2.859375 | 3 |
[] |
no_license
|
#include <unordered_map>
#include <cstdio>
#include <iomanip>
#include <ctime>
#include <cstdlib>
#include <map>
using namespace std;
int main(){
srand(time(NULL));
map<int,int> ma;
unordered_map<int,int> uno_ma;
clock_t start = clock();
for(int i= 0; i<10000;i++){
ma.insert(pair<int,int>(rand()%10000,i));
}
float s = ((double)clock() - start) / CLOCKS_PER_SEC;
printf("Tiempo transcurrido para insertar en Map (STL): %f\n",s);
int k=0;
start = clock();
for(int i= 0; i<10000;i++){
uno_ma.insert(pair<int,int>(rand()%10000,i));
}
float s1 = ((double)clock() - start) / CLOCKS_PER_SEC;
printf("Tiempo transcurrido para insertar en Unordered Map (STL): %f\n", s1);
return 0;
}
| true |
76c2e7a73212dd1dfcc173f943f7d7a904a9c599
|
C++
|
ProjetosLucas/AutomaTIK
|
/RFID/RFID.ino
|
UTF-8
| 1,019 | 2.765625 | 3 |
[] |
no_license
|
//Programa: Leitor RFID RDM6300
//Alteracoes e adaptacoes: Arduino e Cia
//Baseado no programa original de Stephane Driussi
#include <SoftwareSerial.h>
#include <RDM6300.h>
//Inicializa a serial nos pinos 2 (RX) e 3 (TX)
SoftwareSerial RFID(2, 3);
int Led = 13;
uint8_t Payload[6]; // used for read comparisons
RDM6300 RDM6300(Payload);
void setup()
{
pinMode(Led, OUTPUT);
//Inicializa a serial para o leitor RDM6300
RFID.begin(9600);
//Inicializa a serial para comunicacao com o PC
Serial.begin(9600);
//Informacoes iniciais
Serial.println("Leitor RFID RDM6300\n");
}
void loop()
{
//Aguarda a aproximacao da tag RFID
while (RFID.available() > 0)
{
digitalWrite(Led, HIGH);
uint8_t c = RFID.read();
if (RDM6300.decode(c))
{
Serial.print("ID TAG: ");
//Mostra os dados no serial monitor
for (int i = 0; i < 5; i++) {
Serial.print(Payload[i], HEX);
Serial.print(" ");
}
Serial.println();
}
}
digitalWrite(Led, LOW);
delay(100);
}
| true |
704e7c0286f50fcc433af461a5c90b225b8c41da
|
C++
|
WeiX728/Performance-System
|
/ManagementSystem/System.cpp
|
GB18030
| 6,668 | 3.265625 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
/*ѧϢṹ*/
typedef struct Node
{
char Name[10]; //ѧ
char ID[15]; //ѧѧ
int Score[3]; //ƳɼѧӢݽṹ
float Ave_Sco;
struct Node *next;
}Lnode;
void Display(); /*ʾ*/
void GetScore(Lnode *&h); /*ɼ¼뺯*/
void PrintScore(Lnode *h); /*ɼӡ*/
void ModifyScore(Lnode *h); /*ɼĺ*/
void FindInf(Lnode *h); /*Ϣ*/
void Delete(Lnode *h); /*ɾ*/
void Quit(Lnode *h); /*˳*/
void SaveInf(Lnode *h);
void LoadInf(Lnode *h);
/*ʼ*/
void InitList(Lnode *&head)
{
head = (Lnode *)malloc(sizeof(Lnode));
if (head == NULL)
{
printf("error!");
exit(1);
}
head->next = NULL; //ʹͷڵָΪ
}
int main()
{
Lnode *ScoreList; //ɼѧϢڴ
int Function;
char flag;
int t = 0;
InitList(ScoreList);
LoadInf(ScoreList);
while (1)
{
Display();
printf("ѡ ");
scanf("%d", &Function);
switch (Function)
{
case 1: while (1)
{
GetScore(ScoreList);
printf("Ƿ Y/N");
scanf("%s", &flag);
if (flag == 'N' || flag == 'n')break;
} system("cls"); break;
case 2: PrintScore(ScoreList); _getch(); system("cls"); break;
case 3: ModifyScore(ScoreList); system("cls"); break;
case 4: FindInf(ScoreList); _getch(); system("cls"); break;
case 5: Delete(ScoreList); _getch(); system("cls"); break;
case 6: Quit(ScoreList); break;
default: printf("Error 룺");
break;
} //switch
}
return 0;
}
/*ϵͳʾ*/
void Display()
{
printf("\t\t**********************************************\n");
printf("\t\t*************ӭʹóɼϵͳ*************\n");
printf("\t\t**********************************************\n");
printf("\t\t\t\t1¼ɼ\n");
printf("\t\t\t\t2ӡɼ\n");
printf("\t\t\t\t3ijɼ\n");
printf("\t\t\t\t4ѧϢ\n");
printf("\t\t\t\t5ɾѧϢ\n");
printf("\t\t\t\t6˳ϵͳ\n");
printf("\n\n\n\n\n\n");
}
/*ɼ¼*/
void GetScore(Lnode *&h)
{
Lnode *p, *q = h;
char name[10], id[15];
int Math, English, Datastruct;
p = (Lnode *)malloc(sizeof(Lnode)); //ΪѧϢڵ
printf("ѧϢ\n");
printf(" ѧ ѧ Ӣ ݽṹ\n");
scanf("%s %s %d %d %d", &name, &id, &Math, &English, &Datastruct);
for (; q->next != NULL; q = q->next){;} //ƶβڵ
strcpy(p->Name, name);
strcpy(p->ID, id);
p->Score[0] = Math;
p->Score[1] = English;
p->Score[2] = Datastruct;
p->Ave_Sco = ((float)((p->Score[0] + p->Score[1] + p->Score[2]) - 150)) / 30;
p->next = NULL;
q->next = p;
q = p;
}
/*ɼӡ*/
void PrintScore(Lnode *h)
{
Lnode *p = h->next;
printf("%-14s%-8s%-8s%-8s%-8s%-8s\n","", "ѧ", "", "ѧ", "Ӣ", "ݽṹ", "ƽ");
while (p != NULL)
{
printf("%-14s%-8s%-8d%-8d%-8d%.2f\n", p->ID, p->Name, p->Score[0], p->Score[1], p->Score[2], p->Ave_Sco);
p = p->next;
}
}
/*ɼ*/
void ModifyScore(Lnode *h)
{
Lnode *p = h->next;
char name[10], id[15];
int Math, English, Datastruct;
printf("ѧ");
scanf("%s", name);
printf("ѧѧţ");
scanf("%s", id);
while (p)
{
if (strcmp(p->Name, name)==0 && strcmp(p->ID, id)==0)
{
printf("ǰѧϢ:\n");
printf("%-14s%-8s%-8s%-8s%-8s\n", "ѧ", "", "ѧ", "Ӣ", "ݽṹ");
printf("%-14s%-8s%-8d%-8d%-8d\n", p->ID, p->Name, p->Score[0], p->Score[1], p->Score[2]);
printf("ѧɼ");
scanf("%d", &Math);
printf("Ӣɼ");
scanf("%d", &English);
printf("ݽṹɼ");
scanf("%d", &Datastruct);
p->Score[0] = Math;
p->Score[1] = English;
p->Score[2] = Datastruct;
break;
}
else
{
p = p->next;
}
}//whileѭ
}
/*Ϣ*/
void FindInf(Lnode *h)
{
Lnode *p = h->next;
char name[10], id[15];
printf("ѧ");
scanf("%s", name);
printf("ѧѧţ");
scanf("%s", id);
while (p)
{
if (strcmp(p->Name, name) == 0 && strcmp(p->ID, id) == 0)
{
printf("ǰѧϢ:\n");
printf("%-14s%-8s%-8s%-8s%-8s\n", "ѧ", "", "ѧ", "Ӣ", "ݽṹ");
printf("%-14s%-8s%-8d%-8d%-8d\n", p->ID, p->Name, p->Score[0], p->Score[1], p->Score[2]);
break;
}
else
{
p = p->next;
}
}//whileѭ
}
/*ɾ*/
void Delete(Lnode *h)
{
Lnode *p = h, *q;
q = p->next;
char name[10], id[15];
printf("ѧ");
scanf("%s", name);
printf("ѧѧţ");
scanf("%s", id);
while (q)
{
if (strcmp(q->Name, name) == 0 && strcmp(q->ID, id) == 0)
{
p->next = q->next;
free(q); //ɾpڵ
printf("ɾɹ\n");
break;
}
else
{
p = p->next;
q = q->next;
}
}//whileѭ
}
/*˳ϵͳ*/
void Quit(Lnode *h)
{
SaveInf(h); //˳ʱϢ
exit(0);
}
/*ļ*/
void LoadInf(Lnode *h)
{
Lnode *p = h;
Lnode *q; //ʱ ڱļжȡϢ
FILE* file = fopen("./Information.dat", "rb");
if (!file)
{
printf("ļʧܣ");
return ;
}
/*
ʹfeofжļǷΪҪע⣺
ȡļʱfeofñ־Ϊ-1
ҪٶȡһκŻáҪȶһΡ
*/
q = (Lnode *)malloc(sizeof(Lnode));
fread(q, sizeof(Lnode), 1, file);
while (!feof(file)) //һֱļĩβ
{
p->next = q;
p = q;
q = (Lnode *)malloc(sizeof(Lnode));
fread(q, sizeof(Lnode), 1, file);
} //whileѭ
p->next = NULL;
fclose(file);
}
/*Ϣļ*/
void SaveInf(Lnode *h)
{
Lnode *p = h->next;
int flag;
FILE* file = fopen("./Information.dat", "wb");
if (!file)
{
printf("ļʧܣ");
return;
}
while (p != NULL)
{
flag = fwrite(p, sizeof(Lnode), 1, file); //pдļ
if (flag != 1)
{
break;
}
p = p->next;
}
fclose(file);
}
| true |
6808b5cf7e7f9308c63b8fb9b1cfaafe5d0dc1f6
|
C++
|
conwnet/way-of-algorithm
|
/poj-cpp/2260/14827283_PE.cc
|
UTF-8
| 945 | 2.578125 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <string.h>
int mat[128][128], N, row[128], col[128];
int main()
{
while(scanf("%d", &N) && N) {
memset(row, 0, sizeof(row));
memset(col, 0, sizeof(col));
for(int i=0; i<N; i++) {
for(int j=0; j<N; j++) {
scanf("%d", &mat[i][j]);
row[i] += mat[i][j];
col[j] += mat[i][j];
}
}
int rcnt = 0, ccnt = 0, y, x;
for(int i=0; i<N; i++) {
if(row[i]&1) { rcnt++; y = i+1; }
if(col[i]&1) { ccnt++; x = i+1; }
}
if(rcnt+ccnt==0) printf("OK\n");
else if(rcnt>1 || ccnt>1) printf("Corrupt\n");
else printf("Change bit (%d, %d)\n", y, x);
}
return 0;
}
| true |
bcf10808d96b6f90725b19a017d8186a3f3c5442
|
C++
|
Kapatsa/optim_gui
|
/RectArea.hpp
|
UTF-8
| 1,112 | 3 | 3 |
[] |
no_license
|
//
// RectArea.hpp
// optimization_console
//
// Created by David Kapatsa on 06.10.2019.
// Copyright © 2019 David Kapatsa. All rights reserved.
//
#ifndef RectArea_hpp
#define RectArea_hpp
#include <stdio.h>
#include <iostream>
#include "Area.hpp"
/**
* Rectangle Area Class
*
* This class is an instance of Area class. It allows to declare rectangular areas in an n-dimensional space.
*
**/
class RectArea : public Area {
protected:
double long tolIn = 1e-10;
double long *range; // [( , );( , );( , )] // 4 when dim = 2, 6 when dim = 3
public:
//int dim;
RectArea(){};
~RectArea(){ delete [] range; };
RectArea(double long *x, int dimen);
/**
* Is in function
*
* This function tells if a given point @param point lies inside the rectanlular area, defined bu the class
* @return 0 if outside, 1 if inside
**/
bool isIn(double long *point) override;
double long * getRange() override { return range; };
void setRange(double long *x) override;
void setDim(int dimen) override;
void printExpr() override;
};
#endif /* RectArea_hpp */
| true |
bd1cc58a923c1049aeb1d6acaea581e534f365f5
|
C++
|
MinGleP/Data_structure_Lecture_MP3_Player
|
/PlayListInfo.h
|
UTF-8
| 442 | 2.546875 | 3 |
[] |
no_license
|
#ifndef _PLAYLISTINFO_H
#define _PLAYLISTINFO_H
#include<string>
#include<iostream>
using namespace std;
class PlayListInfo {
public:
PlayListInfo();
PlayListInfo(string, string);
string getName() const;
string getTitle() const;
string getPlaylistName() const;
void setName(string);
void setTitle(string);
void setPlaylistName(string);
private:
string playlistName;
string title;
string name;
};
#endif // _PLAYLISTINFO_H
| true |
282f5f8050725b7d95cdaae92a2750a21fc4f9fc
|
C++
|
agreene22/OfficeSimulation
|
/Student.cpp
|
UTF-8
| 1,340 | 3.4375 | 3 |
[] |
no_license
|
/* Anna Greene - 2314663
Brandon Kleinman - 2291703
Assignment 4 - Registrar Office Simulation
*/
#include "Student.h"
Student::Student(){//default constructor
m_timeNeeded = 0;
m_arrivalTime = 0;
m_timeIdle = 0;
m_windowStartTime = 0;
}
Student::Student(int windowTime, int arrival){//overloaded constructor
m_timeNeeded = windowTime;
m_arrivalTime = arrival;
m_timeIdle = 0;
m_windowStartTime = 0;
}
//this function sets the time when the student started at the window
void Student::setWindowTime(int startTime){
m_windowStartTime = startTime;
}
//this function returns the time when the student leaves the window
int Student::getEndTime(){
return(m_windowStartTime + m_timeNeeded);
}
//this function returns true if the student is done at the window
bool Student::checkTime(int currTick){
return (getEndTime() == currTick);
}
//increments idle time
void Student::incrementIdleTime(int currTick){
if(currTick >= m_arrivalTime){
m_timeIdle++;
}
}
//returns the time at which the student arrived at the office
int Student::getArrival(){
return m_arrivalTime;
}
//calculates the amount of time which the student was idle
void Student::calculateWaitTime(){
m_timeIdle = m_windowStartTime - m_arrivalTime;
}
//returns the amount of time the student was idle
int Student::getWaitTime(){
return m_timeIdle;
}
| true |
bf4c1bcbff11bfb0a014d50cb3dda2475449c454
|
C++
|
leandro1623/Todos-los-proyectos-que-hice-mientras-aprendia-cpp
|
/Nomina_de_pago.cpp
|
UTF-8
| 1,494 | 2.96875 | 3 |
[] |
no_license
|
#include<iostream>
#include<conio.h>
using namespace std;
int main(){
cout<<"\n\n\t**NOMINA DE PAGO**\n\n";
//variables necesrias
char nombre_empleado[30];
char cedula[30],departamento[30];
double sueldo_bruto,afp,ars,cooperativa,club,prestamos,total_descuento,sueldo_neto;
//solicitando datos
cout<<"Nombre del empleado: ";
cin.getline(nombre_empleado,30,'\n');
cout<<"\nCedula: ";
cin.getline(cedula,30,'\n');
cout<<"\nDepartamento: ";
cin.getline(departamento,30,'\n');
cout<<"\nSueldo bruto: ";
cin>>sueldo_bruto;
//condicional
if(sueldo_bruto==45000){
afp=sueldo_bruto*(2.87/100);
ars=sueldo_bruto*(3.04/100);
cooperativa=sueldo_bruto*(2/100);
club=sueldo_bruto*(0.60/100);
prestamos=sueldo_bruto*(1.3/100);
}
else{
afp=sueldo_bruto*(2.87/100);
ars=sueldo_bruto*(3.04/100);
cooperativa=sueldo_bruto*(1.5/100);
club=sueldo_bruto*(1/100);
prestamos=sueldo_bruto*(1.8/100);
}
//sacando total de descuento y suedo neto
total_descuento= afp+ars+cooperativa+club+prestamos;
sueldo_neto= sueldo_bruto-total_descuento;
//mostrando datos
cout<<"------------------------------------------------"<<endl<<endl;
cout<<"Nombre del empleado: "<<nombre_empleado<<endl;
cout<<"\nCedula: "<<cedula<<endl;
cout<<"\nDepartamento: "<<departamento<<endl;
cout<<"\nSueldo bruto: "<<sueldo_bruto<<endl;
cout<<"\nTotal de descuento: "<<total_descuento<<endl;
cout<<"\nSueldo neto: "<<sueldo_neto<<endl;
//fin del programa
getch();
return 0;
}
| true |
edb9127da7ab236367a8377988d50aad2f6771bb
|
C++
|
arangodb/arangodb
|
/3rdParty/boost/1.78.0/libs/compute/example/time_copy.cpp
|
UTF-8
| 1,878 | 2.734375 | 3 |
[
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause",
"ICU",
"Zlib",
"GPL-1.0-or-later",
"OpenSSL",
"ISC",
"LicenseRef-scancode-gutenberg-2020",
"MIT",
"GPL-2.0-only",
"CC0-1.0",
"LicenseRef-scancode-autoconf-simple-exception",
"LicenseRef-scancode-pcre",
"Bison-exception-2.2",
"LicenseRef-scancode-public-domain",
"JSON",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"Unlicense",
"BSD-4-Clause",
"Python-2.0",
"LGPL-2.1-or-later"
] |
permissive
|
//---------------------------------------------------------------------------//
// Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
// See http://boostorg.github.com/compute for more information.
//---------------------------------------------------------------------------//
//[time_copy_example
#include <vector>
#include <cstdlib>
#include <iostream>
#include <boost/compute/event.hpp>
#include <boost/compute/system.hpp>
#include <boost/compute/algorithm/copy.hpp>
#include <boost/compute/async/future.hpp>
#include <boost/compute/container/vector.hpp>
namespace compute = boost::compute;
int main()
{
// get the default device
compute::device gpu = compute::system::default_device();
// create context for default device
compute::context context(gpu);
// create command queue with profiling enabled
compute::command_queue queue(
context, gpu, compute::command_queue::enable_profiling
);
// generate random data on the host
std::vector<int> host_vector(16000000);
std::generate(host_vector.begin(), host_vector.end(), rand);
// create a vector on the device
compute::vector<int> device_vector(host_vector.size(), context);
// copy data from the host to the device
compute::future<void> future = compute::copy_async(
host_vector.begin(), host_vector.end(), device_vector.begin(), queue
);
// wait for copy to finish
future.wait();
// get elapsed time from event profiling information
boost::chrono::milliseconds duration =
future.get_event().duration<boost::chrono::milliseconds>();
// print elapsed time in milliseconds
std::cout << "time: " << duration.count() << " ms" << std::endl;
return 0;
}
//]
| true |
f27a943b1be45bf4b30934d1c5535a646d4ca591
|
C++
|
jovechiang/LGraphlib
|
/traversal.h
|
UTF-8
| 1,198 | 3.203125 | 3 |
[] |
no_license
|
#ifndef TRAVERSAL_H
#define TRAVERSAL_H
#include "graph_adj.h"
#include <set>
#include <queue>
//Graph Traversal
//DFS
//BFS
class traversal{
public:
traversal(graph_adj & g){G=&g;}
void DFS(int start);
void BFS(int start);
void clearVisited(){visited.clear();}
private:
graph_adj* G;
//Auxilary Datastructure
//set can find elements with logN (red-black tree)
set<int> visited;
set<int> inQueue;
};
void traversal::DFS(int startId){
//You can also put processor here
//in next version there should be a functor
cout<<"DFSvisiting "<<startId<<endl;
visited.insert(startId);
edge* e=G->getAdj().at(startId);
while(e){
if(visited.find(e->toNodeId)!=visited.end())
return;
DFS(e->toNodeId);
e=e->next;
}
}
void traversal::BFS(int startId){
queue<int> Q;
Q.push(startId);
inQueue.insert(startId);
while(!Q.empty()){
int id=Q.front();
Q.pop();
inQueue.erase(id);
cout<<"BFSvisiting "<<id<<endl;
visited.insert(id);
edge* e= G->getAdj().at(id);
while(e){
if(visited.find(e->toNodeId)==visited.end()&&inQueue.find(e->toNodeId)==inQueue.end()){
Q.push(e->toNodeId);
inQueue.insert(e->toNodeId);
}
e=e->next;
}
}
}
#endif
| true |
0f9f3b43db9a3e151fa327105a307531e953b5fc
|
C++
|
maherabdoualy/CarDealership
|
/main.cpp
|
UTF-8
| 8,624 | 3.28125 | 3 |
[] |
no_license
|
#include <iostream>
#include <string>
#include "NewCar.h"
#include "OldCar.h"
#include <vector>
#include "Car.h"
#include <typeinfo>
using namespace std;
//old
OldCar oldcar1("101010","Toyota","Camry",2014,14000,"Old",5000);
OldCar oldcar2("202020","Nissan","Rogue",2017,20000,"Old",2000);
OldCar oldcar3("303030","Ford","Fusion",2013,12000,"Old", 10000);
OldCar oldcar4("404040","Jeep","Renegade", 2018, 18000, "Old", 6000);
OldCar oldcar5("505050", "Peugeot", "206", 2016, 11000, "Old", 15000);
//new
NewCar newcar1("010101","Lamborghini","Huracan",2019,90000,"New", "Provider1");
NewCar newcar2("020202","Audi", "R8", 2016, 50000,"New","Provider2");
NewCar newcar3("030303","Renault","Clio",2019, 12000,"New","Provider3");
NewCar newcar4("040404","Ferarri","Portofino",2020, 100000,"New","Provider4");
NewCar newcar5("050505","Telsa","Model X", 2017,55000,"New","Provider4");
//add car global variables
OldCar anOldCar;
NewCar aNewCar;
//global vectors
vector<Car*> cars;
vector<Car*>::iterator it;
vector<Car*> leasedCars;
// INVENTORY FUNCTION
void inventory(){
for (it = cars.begin(); it != cars.end(); it++){
(*it)->printCar();
}
cout << endl;
}
// SEARCH FUNCTION
void search(){
int choice;
cout << "1. Search by make." << endl;
cout << "2. Search by model." << endl;
cout << "3. Search by category." << endl;
cout << "4. Search by range of price." << endl;
cout << "Your choice: ";
cin >> choice;
cout << endl;
//search by make
if (choice == 1){
string make;
cout << "Enter make: ";
cin >> make;
cout << endl;
for (it = cars.begin(); it != cars.end(); it++){
if ((*it)->getMake().compare(make) == 0){
(*it)->printCar();
}
}
}
else if (choice == 2){
string model;
cout << "Enter model: ";
cin >> model;
cout << endl;
for (it = cars.begin(); it != cars.end(); it++){
if ((*it)->getModel().compare(model) == 0){
(*it)->printCar();
}
}
}
else if (choice == 3){
string category;
cout << "Enter category: ";
cin >> category;
cout << endl;
for (it = cars.begin(); it != cars.end(); it++){
if ((*it)->getCategory().compare(category) == 0){
(*it)->printCar();
}
}
}
else if (choice == 4){
int lowerPrice, higherPrice;
cout << "Enter the lower price: ";
cin >> lowerPrice;
cout << endl;
cout << "Enter the higher price: ";
cin >> higherPrice;
cout << endl;
for (it = cars.begin(); it != cars.end(); it++){
if (((*it)->getPrice() >= lowerPrice) && ((*it)->getPrice() <= higherPrice)){
(*it)->printCar();
}
}
}
else{
cout << "Choice not valid" << endl;
search();
}
cout << endl;
}
void SellOrleaseCar(){
//lease car
string make;
int answer;
cout <<"Press 0 to lease a car. Press 1 to sell a car: ";
cin >> answer;
cout << endl;
if (answer == 0){
cout << "Enter the make of the car you want to lease: ";
cin >> make;
for (it = cars.begin(); it != cars.end(); it++){
if ((*it)->getMake().compare(make) == 0){
leasedCars.push_back((*it));
cars.erase(it);
break;
}
}
cout << "Car successfully leased and taken off the inventory." << endl;
}
else if (answer == 1){
cout << "Enter the make of the car you want to sell: ";
cin >> make;
for (it = cars.begin(); it != cars.end(); it++){
if ((*it)->getMake().compare(make) == 0){
cars.erase (it);
break;
}
}
cout << "Car successfully sold." << endl;
}
else {
SellOrleaseCar();
}
}
void returnCar(){
for (it = leasedCars.begin(); it != leasedCars.end(); it++){
(*it)->printCar();
}
string make;
cout << "Enter the make of the car you want to return: ";
cin >> make;
for (it = leasedCars.begin(); it != leasedCars.end(); it++){
if (((*it)->getMake()).compare(make) == 0 ){
cars.push_back(*it);
leasedCars.erase(it);
break;
}
}
cout << "Car successfully return to the inventory." << endl;
}
void addCar(){
string VIN;
string make;
string model;
int year;
float price;
string category;
string warranty;
int milage;
int answer;
cout << "Press 0 to add a new car or 1 to add an old car: ";
cin >> answer; cout << endl;
// ADD NEW CAR
if (answer == 0){
aNewCar.setCategory("New");
cout << "Enter the make of the vehicle: ";
cin >> make;
aNewCar.setMake(make); cout << endl;
cout << "Enter the model of the vehicle: ";
cin >> model;
aNewCar.setModel(model); cout << endl;
cout << "Enter the year: ";
cin >> year;
aNewCar.setYear(year); cout << endl;
cout << "Enter the VIN: ";
cin >> VIN;
aNewCar.setVIN(VIN); cout << endl;
cout << "Enter the price: ";
cin >> price;
aNewCar.setPrice(price); cout << endl;
cout << "Enter the warranty provider: ";
cin >> warranty;
aNewCar.setWarranty(warranty); cout << endl;
cars.push_back(&aNewCar);
cout << "Car successfully added." << endl;
}
//ADD OLD CAR
else if (answer == 1){
anOldCar.setCategory("Old");
cout << "Enter the make of the vehicle: ";
cin >> make;
anOldCar.setMake(make); cout << endl;
cout << "Enter the model of the vehicle: ";
cin >> model;
anOldCar.setModel(model); cout << endl;
cout << "Enter the year: ";
cin >> year;
anOldCar.setYear(year); cout << endl;
cout << "Enter the VIN: ";
cin >> VIN;
anOldCar.setVIN(VIN); cout << endl;
cout << "Enter the price: ";
cin >> price;
anOldCar.setPrice(price); cout << endl;
cout << "Enter the milage: ";
cin >> milage;
anOldCar.setMilage(milage); cout << endl;
cars.push_back(&anOldCar);
cout << "Car successfully added." << endl;
}
//if not 0 nor 1
else{
addCar();
}
}
void menu(){
int option;
while (option != 6){
try{
cout << "================================================= " << endl;
cout << "Press 1 to show the inventory." << endl;
cout << "Press 2 to search the inventory." << endl;
cout << "Press 3 to sell or lease a car." << endl;
cout << "Press 4 to return a leased car." << endl;
cout << "Press 5 to add a car to the inventory." << endl;
cout << "Press 6 to exit..." << endl << endl;
cout << "Enter your option: ";
cin >> option;
cout << endl;
if (option == 1){
inventory();
}
else if (option == 2){
search();
}
else if (option == 3){
SellOrleaseCar();
}
else if (option == 4){
returnCar();
}
else if (option == 5){
addCar();
}
else if (option == 6){
cout << "PROGRAM ENDED" << endl;
exit (0);
}
else{
cout <<"Invalid option. Try again." << endl << endl;
}
}
catch (exception e)
{
cout << e.what() << endl;
cin.clear();
cin >> option;
}
}
}
int main(){
cars.push_back(&oldcar1);
cars.push_back(&oldcar2);
cars.push_back(&oldcar3);
cars.push_back(&oldcar4);
cars.push_back(&oldcar5);
cars.push_back(&newcar1);
cars.push_back(&newcar2);
cars.push_back(&newcar3);
cars.push_back(&newcar4);
cars.push_back(&newcar5);
menu();
}
| true |
c40ecb66eaaa413a1d9a3b5d894a6874deac20c5
|
C++
|
narrth/Intro-to-C-
|
/Assignment 5/a51.cpp
|
UTF-8
| 11,205 | 3.734375 | 4 |
[] |
no_license
|
/* Author: Narrthanan Seevananthan
Subject: ECOR 1606
Assignment#5, Question #1
Purpose: You are given a certain amount of money, and you are tasked with
buying the meal wigh most Vitamin C with that amount.
USING SAMPLE CODE FROM ANSWER PROVIDED ON WEBSITE!!!!
*/
#include <iostream>
#include <cmath>
#include <iomanip>
#include <cstdlib>
using namespace std;
// getMaxDollars()
// (1) Requests the user the amount of money they want to spend
// (2) If the values are not valid, has the user
// try again, until a value in the range desired is
// entered
// Returns: the maximum dollars to spend.
//
double getMaxDollars( void ){
double aTotal;
for (;;) {
cout << "Please enter the total amout of money you wish to spend on Food & Drinks:";
cin >> aTotal ;
if ( aTotal < 0) {
cout << "Error: amount must be positive" << endl;
}
else if ( aTotal > 35 ) {
cout << "Error: maximum amount you may spend is $35" << endl;
}
else {
break;
}
}
return aTotal;
}
// fequals() tests if two floating point values are (approximately) equal
//
// Returns: true if ||b - a|| < 0.0001
// false otherwise
bool fequals( double a , double b ){
double x;
x = fabs(b - a);
if (x < 0.0001){
return true;
}else{
return false;
}
}
// selectFood()
// Selects a food choice, given a maximum amount of money, but
//does not print anything.
// Returns : cost of most expensive food that could be bought for
// the given 'amount'
// Also populates/"returns" the vitamin - C, and calories for the selection
double selectFood( double amount, int &vcFood, int &calFood ){
//amount is now being used as the cost of the food/ drink selection
if (amount >= 24) {
amount =24;
calFood = 300;
vcFood = 148;
} else if (amount >= 14.99) {
amount =14.99;
calFood = 80;
vcFood = 30;
} else if (amount >= 6.75) {
amount =6.75;
calFood = 200;
vcFood = 9;
} else if (amount >= 3.50) {
amount =3.5;
calFood = 250;
vcFood = 6;
} else if (amount >= 2.50) {
amount =2.5;
calFood = 301;
vcFood = 12;
} else if (amount >= 1.00) {
amount =1.0;
calFood = 452;
vcFood = 2;
} else if (amount >= 0.35) {
amount =0.35;
calFood = 436;
vcFood = 0;
} else {
amount =calFood = vcFood = 0;
} // end if
return amount;
}
// selectDrink()
// Selects a drink choice, given a maximum amount of money, but
//does not print anything.
// Returns: cost of most expensive drink that could be bought for
//the given 'amount'
// Also populates/"returns" the vitamin-C and calories for the
//selected drink
double selectDrink( double amount, int &vcDrink, int &calDrink ){
if (amount >= 8.99) {
amount =8.99;
calDrink = 101;
vcDrink = 236;
} else if (amount >= 4.99) {
amount =4.99;
calDrink = 112;
vcDrink = 207;
} else if (amount >= 3.50) {
amount =3.5;
calDrink = 203;
vcDrink = 50;
} else if (amount >= 2.50) {
amount =2.5;
calDrink = 250;
vcDrink = 149;
} else if (amount >= 1.75) {
amount =1.75;
calDrink = 2;
vcDrink = 7;
} else if (amount >= 1.25) {
amount =1.25;
calDrink = 0;
vcDrink = 0;
} else if (amount >= 0.95) {
amount =0.95;
calDrink = 0;
vcDrink = 0;
} else if (amount >= 0.25) {
amount =0.25;
calDrink = 160;
vcDrink = 0;
} else {
amount = calDrink = vcDrink = 0;
} // end if selecting the most expensive meal
return amount;
}
// Prints the name of the drink selected, for a given dollar value.
// This function should use the fequals() function defined above
// The function only prints the food (e.g. "a Strawberry Milkshake")
// so that the same function can be used in a table and elsewhere.
void printDrink( double amount ) {
if ( fequals( amount, 8.99)) {
cout << "OJ with Carrots & Spinach";
} else if ( fequals( amount, 4.99)) {
cout << "an OJ";
} else if ( fequals( amount, 3.50)) {
cout << "an Asparagus Milkshake";
} else if ( fequals( amount, 2.50)) {
cout << "a Strawberry Milkshake";
} else if ( fequals( amount, 1.75)) {
cout << "a Tea";
} else if ( fequals( amount, 1.25)) {
cout << "a Water";
} else if ( fequals( amount, 0.95)) {
cout << "a Coffee";
} else if ( fequals( amount, 0.25)) {
cout << "a Pop";
} else {
cout << "no drink";
} // end if selecting the most expensive meal
}
// Prints the name of the food selected, for a given dollar value.
// This function uses the fequals() function defined above
// The function should only print the food (e.g. "a Hamburger")
// so that the same function can be used in a table or
// as in an output string.
void printFood( double amount ) {
if ( fequals( amount, 24.00 ) ) {
cout << "Steak & Broccoli";
} else if ( fequals( amount, 14.99)) {
cout << "a Veggie Platter";
} else if ( fequals( amount, 6.75)) {
cout << "a Submarine Sandwich";
} else if ( fequals( amount, 3.50)) {
cout << "a Pepperoni Pizza";
} else if ( fequals( amount, 2.50)) {
cout << "an all dressed Hamburger";
} else if ( fequals( amount, 1.00)) {
cout << "a Doughnut";
} else if ( fequals( amount, 0.35)) {
cout << "a Noodle soup";
} else {
cout << "no food";
} // end if
}
int main (void) {
// Variables
double aTotal, aDrink, aFood, // Will hold the amount of money available
costDrink, costFood,
mostExpensiveMeal,
bestVC, // The meal combination with the most vitamin C
bestComboFood,
bestComboDrink;
int calFood,
calDrink,
vcFood,
vcDrink,
leastCalories,
greatestVC,
totalVC = 0,
cal650Count = 0,
mealCount = 0,
iFor,
iMax,
count = 0;
// Sentinel loop. Exit if amount to spend is zero.
for (;;) {
aTotal = getMaxDollars();
if ( aTotal == 0 ) {
break;
}
iMax=int(aTotal/0.05 + 0.001);
cout<<"Some options are:"<< endl;
cout<<"Option Cost Calories Vit.C Description\n";
// Now loop through all the possible values to determine the best meal
for ( iFor = 0 ; iFor <= iMax ; iFor++ ) {
aFood=iFor*0.05;
aDrink = aTotal - aFood;
// Go through the list of possible drinks
// From most expensive to least
// Process valid money amounts
costDrink = selectDrink(aDrink, vcDrink, calDrink);
// Process valid money amounts
costFood = selectFood(aFood, vcFood, calFood);
if ( aFood == 0 || bestVC < (vcFood + vcDrink) ) {
bestVC = vcFood + vcDrink;
bestComboFood = aFood;
bestComboDrink = aDrink;
count++;
cout<<" "<<count<<" "<<" "<<costDrink+costFood<<" "<<calDrink + calFood <<" "<<bestVC<<" ";
printFood(costFood);
cout<<" with ";
printDrink(costDrink);
cout<<endl;
}
}
// Now Print the best solution:
aFood = bestComboFood;
aDrink = bestComboDrink;
if (aDrink >= 8.99) {
cout << "We recommend you purchase an OJ with Carrots & Spinach, for $8.99";
} else if (aDrink >= 4.99) {
cout << "We recommend you purchase an OJ, for $4.99";
} else if (aDrink >= 3.50) {
cout << "We recommend you purchase an Asparagus Milkshake, for $3.50";
} else if (aDrink >= 2.50) {
cout << "We recommend you purchase a Strawberry Milkshake, for $2.50";
} else if (aDrink >= 1.75) {
cout << "We recommend you purchase a Tea, for $1.75";
} else if (aDrink >= 1.25) {
cout << "We recommend you purchase a Water, for $1.25";
} else if (aDrink >= 0.95) {
cout << "We recommend you purchase a Coffee, for $0.95";
} else if (aDrink >= 0.25) {
cout << "You could purchase a Pop, for $0.25";
} else {
cout << "You cannot afford any drink";
} // end if selecting the most expensive meal
cout << endl;
if (aFood >= 24) {
cout << "We recommend you purchase Steak & Broccoli, for $24.00";
} else if (aFood >= 14.99) {
cout << "We recommend you purchase an Veggie Platter, for $14.99";
} else if (aFood >= 6.75) {
cout << "We recommend you purchase an Submarine Sandwich, for $6.75";
} else if (aFood >= 3.50) {
cout << "We recommend you purchase a Pepperoni Pizza, for $3.50";
} else if (aFood >= 2.50) {
cout << "We recommend you purchase an all dressed Hamburger, for $2.50";
} else if (aFood >= 1.00) {
cout << "We recommend you purchase a Doughnuts, for $1.00";
} else if (aFood >= 0.35) {
cout << "We recommend you purchase a Noodle soup, for $0.35";
} else {
cout << "You cannot afford any food";
} // end if
cout << endl;
// Gather statistics
if (costFood+costDrink > 0) {
cout << "This meal would cost $" << costFood+costDrink
<< ", with " << calFood+calDrink
<< " Calories and " << vcFood+vcDrink
<< "% of the daily required Vitamin C" << endl;
cout << endl;
mealCount++;
if ( mealCount == 1 || mostExpensiveMeal < (costFood+costDrink) ) {
mostExpensiveMeal = costFood+costDrink;
}
if ( mealCount == 1 || leastCalories > (calFood+calDrink)) {
leastCalories = calFood+calDrink;
}
totalVC += vcFood + vcDrink;
if ( mealCount == 1 || greatestVC < (vcFood+vcDrink)/(costFood+costDrink) ) {
greatestVC = (vcFood+vcDrink)/(costFood+costDrink);
}
if ( calFood+calDrink > 650) {
cal650Count++;
}
}
} // End of sentinal loop.
if (mealCount > 0) {
cout << "The most expensive meal costs: $" << mostExpensiveMeal
<< endl;
cout << "The meal with the least calories had: "
<< leastCalories << " calories"
<< endl;
cout << "The average vitamin C per meal was: " << totalVC/mealCount
<< endl;
cout << "The most econmical source of 'C' was: " << greatestVC << "%/dollar"
<< endl;
cout << 100*cal650Count/mealCount << "% of the meals had more than 650 calories."
<< endl;
}
system("PAUSE"); return 0;
}
| true |
abe251ac47ae9833d0ef5f91b261ae96938feb38
|
C++
|
shooshx/libDRD
|
/drd_arraymap.h
|
UTF-8
| 1,380 | 3.578125 | 4 |
[] |
no_license
|
#pragma once
// implementation of a simple mapping using a static array and O(n) search
// TKey and TKey should be some integral value (int, unsinged int, pointer etc')
template<typename TKey, typename TVal, int MaxSize>
class ArrayMap
{
public:
ArrayMap() : m_count(0)
{}
bool add(TKey k, TVal v) {
// check if it was already added
int freeCell = -1;
for (int i = 0; i < m_count; ++i) {
if (m_data[i].k == k) {
m_data[i].v = v;
if (v == 0)
m_data[i].k = 0; // remove the entry
return true;
}
else if (m_data[i].k == 0 && freeCell == -1) // found a free spot, remember
freeCell = i;
}
if (freeCell != -1) {
m_data[freeCell] = Entry(k, v);
return true;
}
if (m_count >= MaxSize) {
return false;
}
m_data[m_count++] = Entry(k, v);
return true;
}
TVal get(TKey k) {
for (int i = 0; i < m_count; ++i) {
if (k == m_data[i].k && m_data[i].v != 0) {
return m_data[i].v;
}
}
return 0;
}
private:
struct Entry {
Entry(TKey _k = 0, TVal _v = 0) : k(_k), v(_v) {}
TKey k;
TVal v;
};
Entry m_data[MaxSize];
int m_count;
};
| true |
4ed13bd22a09afea3fc0c1d61206ea13106bb2d2
|
C++
|
ousttrue/refrange
|
/tests/json_test.cpp
|
UTF-8
| 1,046 | 2.765625 | 3 |
[] |
no_license
|
#include <sstream>
#include <refrange/text/json.h>
#include <gtest/gtest.h>
TEST(JsonTest, parse)
{
// json to msgpack
const char *json_object="{\"key\":1}";
std::istringstream ss(json_object);
std::vector<unsigned char> buffer;
auto p = ::refrange::msgpack::create_external_vector_packer(buffer);
refrange::text::json::reader_t reader=[&ss](unsigned char *p, size_t len)->size_t{
ss.read((char*)p, len);
return static_cast<size_t>(ss.gcount());
};
refrange::text::json::parser parser(reader);
ASSERT_TRUE(parser.parse(p));
// msgpack to json
{
auto u=refrange::msgpack::create_unpacker(buffer);
std::string out;
refrange::text::json::writer_t writer=[&out](const unsigned char *p, size_t len)->size_t{
for(size_t i=0; i<len; ++i, ++p){
out.push_back(*p);
}
return len;
};
refrange::text::json::converter converter(writer);
converter.convert(u);
EXPECT_EQ(out, json_object);
}
}
| true |
525540facbd77bdf306a0faf2365b546b8499444
|
C++
|
qq911712051/Hrpc
|
/src/util/src/hrpc_lock.cpp
|
UTF-8
| 4,034 | 2.71875 | 3 |
[] |
no_license
|
#include <hrpc_lock.h>
namespace Hrpc
{
Hrpc_MutexLock::Hrpc_MutexLock()
{
// 初始化为error check类型的锁
_mutex = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
_count = 0;
}
Hrpc_RecMutexLock::Hrpc_RecMutexLock()
{
// 初始化为error check类型的锁
_mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
_count = 0;
}
Hrpc_MutexLock::~Hrpc_MutexLock()
{
// 释放mutex资源
int res = pthread_mutex_destroy(&_mutex);
if (res > 0)
{
// mutex还没有解锁释放 解锁
pthread_mutex_unlock(&_mutex);
// 释放
pthread_mutex_destroy(&_mutex);
}
}
Hrpc_RecMutexLock::~Hrpc_RecMutexLock()
{
while (_count > 0 && _count--)
{
pthread_mutex_unlock(&_mutex);
}
// 释放mutex资源
int res = pthread_mutex_destroy(&_mutex);
}
void Hrpc_MutexLock::lock() const
{
int res = pthread_mutex_lock(&_mutex);
if (res > 0)
{
if (res == EINVAL)
{
throw Hrpc_LockException("[Hrpc_MutexLock::lock]: error-check mutex uninitialied");
}
else
{
throw Hrpc_LockException("[Hrpc_MutexLock::lock]:error-check mutex dead lock");
}
}
}
void Hrpc_RecMutexLock::lock() const
{
int res = pthread_mutex_lock(&_mutex);
if (res > 0)
{
throw Hrpc_LockException("[Hrpc_RecMutexLock::lock]: recurisive mutex uninitialied");
}
// 加锁数量增加
_count++;
}
void Hrpc_MutexLock::unlock() const
{
int res = pthread_mutex_unlock(&_mutex);
if (res > 0)
{
if (res == EINVAL)
{
throw Hrpc_LockException("[Hrpc_MutexLock::unlock]: error-check mutex uninitialied");
}
else
{
throw Hrpc_LockException("[Hrpc_MutexLock::unlock]: error-check mutex not owned the lock");
}
}
}
void Hrpc_RecMutexLock::unlock() const
{
int res = pthread_mutex_unlock(&_mutex);
if (res > 0)
{
if (res == EINVAL)
{
throw Hrpc_LockException("[Hrpc_RecMutexLock::unlock]: recurisive mutex uninitialied");
}
else
{
throw Hrpc_LockException("[Hrpc_RecMutexLock::unlock]: recurisive mutex not owned the lock");
}
}
// 加锁次数-1
_count--;
}
bool Hrpc_MutexLock::tryLock() const
{
int res = pthread_mutex_trylock(&_mutex);
if (res > 0)
{
if (res == EINVAL)
{
throw Hrpc_LockException("[Hrpc_MutexLock::trylock]: error-check mutex uninitialied");
}
else
{
return false;
}
}
return true;
}
bool Hrpc_RecMutexLock::tryLock() const
{
int res = pthread_mutex_trylock(&_mutex);
if (res > 0)
{
if (res == EINVAL)
{
throw Hrpc_LockException("[Hrpc_RecMutexLock::trylock]: recurisive mutex uninitialied");
}
else
{
return false;
}
}
// 加锁次数+1
_count++;
return true;
}
void Hrpc_ThreadLock::lock()
{
_lock.lock();
// 通知为0
_count = 0;
}
void Hrpc_ThreadLock::unlock()
{
// 发送通知
emitAllNotify();
_lock.unlock();
}
bool Hrpc_ThreadLock::tryLock()
{
bool res = _lock.tryLock();
if (res)
{
_count = 0;
}
return res;
}
void Hrpc_ThreadLock::wait()
{
// wait调用后,锁会被释放,这里先提前发送所有通知信号
emitAllNotify();
_cond.wait(_lock);
}
bool Hrpc_ThreadLock::timeWait(int millseconds)
{
emitAllNotify();
return _cond.timeWait(_lock, millseconds);
}
void Hrpc_ThreadLock::notify()
{
if (_count != -1)
_count++;
}
void Hrpc_ThreadLock::notifyAll()
{
_count = -1;
}
void Hrpc_ThreadLock::emitAllNotify()
{
if (_count < 0)
{
// 广播信号
_cond.broadcast();
_count = 0;
}
else
{
while (_count > 0)
{
_cond.signal();
_count--;
}
}
}
}
| true |
58207a2d712b9c1190d8358a106bad70641c3aa4
|
C++
|
aecolumna/Spartan-Space-Invaders
|
/Project1/Bunker.h
|
UTF-8
| 1,569 | 3.03125 | 3 |
[] |
no_license
|
/**
* \file Bunker.h
*
* \author Andres Columna
*
* Bunker Base Class
*/
#pragma once
#include <string>
#include <memory>
#include "Game.h"
/// Forward declaration of CGame to avoid Circular includes
class CGame;
/**
* Class denotes a Bunker in Space Invaders game
*/
class CBunker : public CItem
{
public:
CBunker()=delete;
CBunker(CGame * game);
virtual ~CBunker();
/// Copy constructor (disabled)
CBunker(const CBunker &) = delete;
void Draw(Gdiplus::Graphics * graphics) override;
/// getter for mHits
int GetHits() {return mHits;}
/// setter for mHits
void SetHits(int hit) { mHits = hit; }
void setHit();
///Others to come, such as hit tests, change in the image per hit, etc
virtual void Accept(CItemVisitor* visitor) { visitor->VisitBunker(this); }
private:
/// whether Bunker has been hit
bool mHit = false;
/// Number of times Bunker has been hit
int mHits = 0;
///Stuff like setting locations
/// Original loaded image of bunker
std::unique_ptr<Gdiplus::Bitmap> mInitial;
/// Image when it hasn't been hit
std::unique_ptr<Gdiplus::Bitmap> mNoHit;
/// slightly shrunken bunker for when Bunker is hit first time
std::unique_ptr<Gdiplus::Bitmap> mFirstHit;
/// Even smaller bunker for when Bunker is hit second time
std::unique_ptr<Gdiplus::Bitmap> mSecondHit;
/// Smallest bunker for when Bunker is hit third time
std::unique_ptr<Gdiplus::Bitmap> mThirdHit;
/// Image for exit sequence of Bunker
std::unique_ptr<Gdiplus::Bitmap> mLastHit;
};
| true |
82375401d8311daab28242aea001a1327c545dbb
|
C++
|
rubenglezortiz/Proyectos2-2020-21
|
/PaintlLess/Assets/game/network_types.h
|
UTF-8
| 6,328 | 3.25 | 3 |
[
"CC0-1.0"
] |
permissive
|
// This file is part of the course TPV2@UCM - Samir Genaim
#pragma once
#include <SDL_net.h>
#include <iostream>
#pragma pack(push,1)
// print an IPv4
inline void print_ip(Uint32 ip, bool newline = false) {
std::cout << (ip & 0xFF) << "." //
<< ((ip >> 8) & 0xFF) << "." //
<< ((ip >> 16) & 0xFF) << "." //
<< ((ip >> 24) & 0xFF);
if (newline)
std::cout << "\n";
}
// these are the classical functions for converting
// host to network integers and vice versa. Apparently
// there is no common library that works on all OS. They
// basically use SDLNet_Write and SDLNet_Read but have an
// API similar to the original ones.
inline Uint32 sdlnet_htonl(Uint32 v) {
Uint32 nv;
SDLNet_Write32(v, &nv);
return nv;
}
inline Uint32 sdlnet_ntohl(Uint32 nv) {
return SDLNet_Read32(&nv);
}
inline Uint16 sdlnet_htons(Uint16 v) {
Uint16 nv;
SDLNet_Write16(v, &nv);
return nv;
}
inline Uint16 sdlnet_ntohs(Uint16 nv) {
return SDLNet_Read16(&nv);
}
// numeric type that can be transmitted over
// a connection. Internally they keep the value
// using network format (big Endian) and whenever
// the value is used it is converted to little
// Endian. They are based on using the functions
// above. They do not have constructor on purpose,
// so they can be easily used in union types
//
// uint32_nt
// int32_nt
// uint16_nt
// int16_nt
// uint8_nt -- just aliased to Uint8
// int8_nt
// float32_nt -- asserts that float is 32bit, and some other stuff
//
// for Uint32
struct uint32_nt {
inline uint32_nt& operator=(Uint32 v) {
v_ = sdlnet_htonl(v);
return *this;
}
inline operator Uint32() {
return sdlnet_ntohl(v_);
}
private:
Uint32 v_;
};
// for Sint32
// ==========
//
// We transmit the sign and the unsigned value and construct it back, this is the safest
// we could do. A more efficient is to cast to Uint32 and back to Sint32, but for this
// we have to make sure that both machine use the same representation for negative
// numbers, e.g., Two's complement (which is most likely true as it is use almost everywhere)
//
struct int32_nt {
inline int32_nt& operator=(Sint32 v) {
if (v < 0) {
s_ = 1;
v_ = sdlnet_htonl(static_cast<Uint32>(-v));
}
else {
s_ = 0;
v_ = sdlnet_htonl(static_cast<Uint32>(v));
}
return *this;
}
inline operator Sint32() {
Sint32 v = static_cast<Sint32>(sdlnet_ntohl(v_));
if (s_ == 1)
v = -v;
return v;
}
private:
Uint32 v_;
Uint8 s_;
};
// for Uint16
// ==========
//
struct uint16_nt {
inline uint16_nt& operator=(Uint16 v) {
v_ = sdlnet_htons(v);
return *this;
}
inline operator Uint16() {
return sdlnet_ntohs(v_);
}
private:
Uint16 v_;
};
// for Sint16
// ==========
//
// We transmit the sign and the unsigned value and construct it back, this is the safest
// we could do. A more efficient is to cast to Uint32 and back to Sint32, but for this
// we have to make sure that both machine use the same representation for negative
// numbers, e.g., Two's complement (which is most likely true as it is use almost everywhere)
//
struct int16_nt {
inline int16_nt& operator=(Sint16 v) {
if (v < 0) {
s_ = 1;
v_ = sdlnet_htons(static_cast<Uint16>(-v));
}
else {
s_ = 0;
v_ = sdlnet_htons(static_cast<Uint16>(v));
}
return *this;
}
inline operator Sint16() {
Sint16 v = static_cast<Sint16>(sdlnet_ntohs(v_));
if (s_ == 1)
v = -v;
return v;
}
private:
Uint16 v_;
Uint8 s_;
};
// for Uint8
// =========
//
typedef Uint8 uint8_nt;
// for Sint8
// =========
//
// We transmit the sign and the unsigned value and construct it back, this is the safest
// we could do. A more efficient is to cast to Uint32 and back to Sint32, but for this
// we have to make sure that both machine use the same representation for negative
// numbers, e.g., Two's complement (which is most likely true as it is use almost everywhere)
//
struct int8_nt {
inline int8_nt& operator=(Sint8 v) {
if (v < 0) {
s_ = 1;
v_ = static_cast<Uint8>(-v);
}
else {
s_ = 0;
v_ = static_cast<Uint8>(v);
}
return *this;
}
inline operator Sint16() {
Sint16 v = static_cast<Sint16>(v_);
if (s_ == 1)
v = -v;
return v;
}
private:
Uint8 v_;
Uint8 s_;
};
// for float
// =========
//
// just an attempt based on the representation in:
//
// https://sites.uclouvain.be/SystInfo/usr/include/ieee754.h.html
//
// there seem no standards for how floating point are
// represented using big-endian and little-endian
//
// we assume that a float is represented as in ieee754, i.e.,
// the order of its parts is
//
// Big-Endian : Sign Exp Mantisa
// Little-Endian : Mantisa Exp Sign
//
// where Sign is a 1-bit, Exp is an unsigned integer of 8bit, and
// Mantisa is unsigned integer of 23 bit. The bytes of each unsigned
// integer follows the corresponding Endiannes
//
// We transmit the different parts and construct them back.
//
struct float32_nt {
static_assert(sizeof(float) == 4, "float is not 32 bits");
// ieee754 float on big endian
typedef union {
float value;
struct {
Uint32 sign : 1;
Uint32 exponent : 8;
Uint32 mantissa : 23;
};
} IEEE_754_float_big_endian;
static_assert(sizeof(IEEE_754_float_big_endian) == 4, "IEEE_754_float_big_endian is not 4 bytes, something is wrong with packing");
// ieee754 float on little endian
typedef union {
float value;
struct {
Uint32 mantissa : 23;
Uint32 exponent : 8;
Uint32 sign : 1;
};
} IEEE_754_float_little_endian;
static_assert(sizeof(IEEE_754_float_little_endian) == 4, "IEEE_754_float_little_endian is not 4 bytes, something is wrong with packing");
inline float32_nt& operator=(float v) {
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
IEEE_754_float_little_endian f = { };
f.value = v;
m_ = sdlnet_htonl(f.mantissa);
e_ = f.exponent;
s_ = f.sign;
#else
IEEE_754_float_big_endian f = { };
f.value = v;
m_ = f.mantissa;
e_ = f.exponent;
s_ = f.sign;
#endif
return *this;
}
inline operator float() {
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
IEEE_754_float_little_endian f = { };
f.mantissa = sdlnet_ntohl(m_);
f.exponent = e_;
f.sign = s_;
#else
IEEE_754_float_big_endian f = { };
f.mantissa = m_;
f.exponent = e_;
f.sign = s_;
#endif
return f.value;
}
private:
Uint32 m_;
Uint8 e_;
Uint8 s_;
};
#pragma pack(pop)
| true |
30136354c4d53a0e57733de908b4cde3a392628c
|
C++
|
Xeelot/BinaryTreeFun
|
/TreeFun/TreeFun.cpp
|
UTF-8
| 2,188 | 3.578125 | 4 |
[
"MIT"
] |
permissive
|
// TreeFun.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <cstdlib>
#include <iostream>
#include <string>
class Leaf
{
public:
Leaf(int value) { left = NULL; right = NULL; depth = value; }
~Leaf() {}
Leaf* left;
Leaf* right;
int depth;
};
class Tree
{
public:
Tree() { root = NULL; }
~Tree() {}
void fillTree(int maxDepth);
void traverseTree();
private:
void recursiveFill(Leaf* branch, int currDepth, int maxDepth);
void recursiveTraverse(Leaf* branch);
Leaf* root;
};
void Tree::fillTree(int maxDepth)
{
// Tree will only be filled once for now
if (root == NULL)
{
root = new Leaf(0);
recursiveFill(root, 1, maxDepth);
}
}
void Tree::recursiveFill(Leaf* branch, int currDepth, int maxDepth)
{
// Check for an empty left leaf off the branch and make sure not to surpass the max depth
if ((branch->left == NULL) && (currDepth < maxDepth))
{
branch->left = new Leaf(currDepth);
recursiveFill(branch->left, (currDepth + 1), maxDepth);
}
// Check for an empty right leaf off the branch and make sure not to surpass the max depth
if ((branch->right == NULL) && (currDepth < maxDepth))
{
branch->right = new Leaf(currDepth);
recursiveFill(branch->right, (currDepth + 1), maxDepth);
}
}
void Tree::traverseTree()
{
std::cout << "Root: " << root->depth;
recursiveTraverse(root);
std::cout << std::endl;
}
void Tree::recursiveTraverse(Leaf* branch)
{
// Traverse down the left branches first
if (branch->left != NULL)
{
std::cout << " Left: " << branch->left->depth;
recursiveTraverse(branch->left);
}
// Then traverse down the right branches
if (branch->right != NULL)
{
std::cout << " Right: " << branch->right->depth;
recursiveTraverse(branch->right);
}
}
int main()
{
Tree tree;
tree.fillTree(4);
tree.traverseTree();
system("PAUSE");
return 0;
}
/*
O0
L1 R1
L2 R2 L2 R2
L3 R3 L3 R3 L3 R3 L3 R3
*/
| true |
1ed2bba2c8523a8354229bc41c95e2d97d1690d7
|
C++
|
lscholte/SnowSimulation
|
/lib/atlas/include/atlas/utils/BVNode.hpp
|
UTF-8
| 846 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
#ifndef ATLAS_INCLUDE_ATLAS_UTILS_BV_NODE_HPP
#define ATLAS_INCLUDE_ATLAS_UTILS_BV_NODE_HPP
#pragma once
#include "Utils.hpp"
#include "atlas/math/Math.hpp"
#include <vector>
namespace atlas
{
namespace utils
{
enum class NodeType : int
{
Node = 0,
Leaf
};
template <class Type, class BVType>
class BVNode
{
BVNode()
{ }
virtual ~BVNode()
{ }
virtual BVNodePtr<NodeType, BVType> cloneShared() = 0;
virtual NodeType getType() const = 0;
virtual std::vector<Type> visit(
atlas::math::Point const& p) const = 0;
virtual std::vector<Type> visit(BVType const& bv) const = 0;
virtual BVType getVolume() const = 0;
};
}
}
#endif
| true |
56486e4cf530565745448011d48d3e842da6f44c
|
C++
|
tristanschneider/syx
|
/syx/Engine.Shared/DebugDrawer.cpp
|
UTF-8
| 4,064 | 2.53125 | 3 |
[] |
no_license
|
#include "Precompile.h"
#include "DebugDrawer.h"
#include "asset/Shader.h"
#include <gl/glew.h>
namespace {
const int sStartingSize = 1000;
}
const AssetInfo DebugDrawer::SHADER_ASSET("shaders/debug.vs");
DebugDrawer::DebugDrawer(std::shared_ptr<Asset> shader) {
mShader = std::move(shader);
//Generate a vertex buffer name
glGenBuffers(1, &mVBO);
//Bind vertexBuffer as "Vertex attributes"
glBindBuffer(GL_ARRAY_BUFFER, mVBO);
_resizeBuffer(sStartingSize);
//Generate a vertex array name
glGenVertexArrays(1, &mVAO);
//Bind this array so we can fill it in
glBindVertexArray(mVAO);
glEnableVertexAttribArray(0);
//Interleave position and color
//Position
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), nullptr);
//Color
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<void*>(sizeof(float)*3));
glBindVertexArray(0);
}
DebugDrawer::~DebugDrawer() {
}
void DebugDrawer::drawLine(const Syx::Vec3& a, const Syx::Vec3& b, const Syx::Vec3& colorA, const Syx::Vec3& colorB) {
std::unique_lock<std::mutex> vLock(mVertsMutex);
Vertex vA, vB;
for(int i = 0; i < 3; ++i) {
vA.mPos[i] = a[i];
vB.mPos[i] = b[i];
vA.mColor[i] = colorA[i];
vB.mColor[i] = colorB[i];
}
mVerts.push_back(vA);
mVerts.push_back(vB);
}
void DebugDrawer::drawLine(const Syx::Vec3& a, const Syx::Vec3& b, const Syx::Vec3& color) {
drawLine(a, b, color, color);
}
void DebugDrawer::drawLine(const Syx::Vec3& a, const Syx::Vec3& b) {
drawLine(a, b, mColor);
}
void DebugDrawer::drawVector(const Syx::Vec3& point, const Syx::Vec3& dir) {
float tipSize = 0.1f;
Syx::Vec3 ortho = dir.safeNormalized().getOrthogonal();
Syx::Vec3 end = point + dir;
drawLine(point, end);
drawLine(end, end - dir*tipSize + ortho*tipSize);
}
void DebugDrawer::DrawSphere(const Syx::Vec3&, float, const Syx::Vec3&, const Syx::Vec3&) {
}
void DebugDrawer::DrawCube(const Syx::Vec3&, const Syx::Vec3&, const Syx::Vec3&, const Syx::Vec3&) {
}
void DebugDrawer::DrawPoint(const Syx::Vec3& point, float size) {
float hSize = size*0.5f;
for(int i = 0; i < 3; ++i) {
Syx::Vec3 start, end;
start = end = point;
start[i] -= hSize;
end[i] += hSize;
drawLine(start, end);
}
}
void DebugDrawer::setColor(const Syx::Vec3& color) {
mColor = color;
}
void DebugDrawer::_render(const Syx::Mat4& wvp) {
std::unique_lock<std::mutex> vLock(mVertsMutex);
auto* shader = mShader->cast<Shader>();
if(!shader || mVerts.empty() || shader->getState() != AssetState::PostProcessed) {
return;
}
//Bind buffer so we can update it
glBindBuffer(GL_ARRAY_BUFFER, mVBO);
//Resize buffer if necessary
if(mVerts.size() > mBufferSize) {
_resizeBuffer(mVerts.size()*2);
}
//Upload latest lines to buffer
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(Vertex)*mVerts.size(), mVerts.data());
//Draw lines
glBindVertexArray(mVAO);
{
Shader::Binder b(*shader);
glUniformMatrix4fv(shader->getUniform("wvp"), 1, GL_FALSE, wvp.mData);
glDrawArrays(GL_LINES, 0, GLsizei(mVerts.size()));
}
glBindVertexArray(0);
mVerts.clear();
}
void DebugDrawer::_resizeBuffer(size_t newSize) {
//Upload to gpu as vertexBuffer
glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex)*newSize, nullptr, GL_DYNAMIC_DRAW);
mBufferSize = newSize;
}
IDebugDrawer& DebugDrawerExt::getNullDrawer() {
struct Empty : public IDebugDrawer {
void drawLine(const Syx::Vec3&, const Syx::Vec3&, const Syx::Vec3&, const Syx::Vec3&) {}
void drawLine(const Syx::Vec3&, const Syx::Vec3&, const Syx::Vec3&) {}
void drawLine(const Syx::Vec3&, const Syx::Vec3&) {}
void drawVector(const Syx::Vec3&, const Syx::Vec3&) {}
void DrawSphere(const Syx::Vec3&, float, const Syx::Vec3&, const Syx::Vec3&) {}
void DrawCube(const Syx::Vec3&, const Syx::Vec3&, const Syx::Vec3&, const Syx::Vec3&) {}
void DrawPoint(const Syx::Vec3&, float) {}
void setColor(const Syx::Vec3&) {}
};
static Empty singleton;
return singleton;
}
| true |
56dc7c6cf8326befc591388192d38656cfe0dc3d
|
C++
|
shubhpy/Cpp-Programs
|
/Longest_single_letter_string.cpp
|
UTF-8
| 1,558 | 2.9375 | 3 |
[] |
no_license
|
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int solve(int l,int e,string s,vector<int> &v,int count,int &ans,vector<vector<int> > &dp){
if (count==0){
ans = max(ans,e-l+1);
dp[l][e] = 1;
return dp[l][e];
}
else{
dp[l][e] = 0;
if (dp[l+1][e]!=1 && l+1<s.length()){
int inc = 0;
if (v[(int)(s[l] - 'a')] ==2){
count--;
inc = 1;
}
v[(int)(s[l] - 'a')]--;
dp[l+1][e] = solve(l+1,e,s,v,count,ans,dp);
v[(int)(s[l] - 'a')]++;
if (inc){
count++;
}
}
if (dp[l][e-1]!=1 && e-1>=0){
int inc = 0;
v[(int)(s[e-1] - 'a')]--;
if (v[(int)(s[e-1] - 'a')] >=2){
count--;
inc = 1;
}
dp[l][e-1] = solve(l,e-1,s,v,count,ans,dp);
v[(int)(s[e-1] - 'a')]++;
if (inc){
count++;
}
}
return dp[l][e];
}
}
int main() {
string s = "ababcde";
//cin >> s;
vector<int> v(26,0);
int count = 0;
for(int i = 0;i<s.length();i++){
v[(int)(s[i] - 'a')]++;
if (v[(int)(s[i] - 'a')] >=2){
count++;
}
}
int ans = 0;
vector<vector<int> > dp(s.length()+1,vector<int> (s.length()+1,-1));
int t = solve(0,s.length()-1,s,v,count,ans,dp);
cout << ans;
return 0;
}
| true |
1b37be688c81030d2037996a0c1ad4f50dd491ae
|
C++
|
Marchello00/Heaps
|
/BinomialHeap/BinomialHeap.cpp
|
UTF-8
| 5,465 | 2.8125 | 3 |
[] |
no_license
|
#ifndef BINHEAP_DONE
#define BINHEAP_DONE
#ifndef INCLUDE_BINHEAP
#include "BinomialHeap.h"
#endif
template<typename Type>
BinomialTree<Type> *BinomialTree<Type>::connect(BinomialTree *nchild) {
nchild->father = this;
childrens.push(nchild);
return this;
}
template<typename Type>
BinomialTree<Type>::BinomialTree(Type *key):
key(key), father(nullptr) {}
template<typename Type>
BinomialTree<Type>::~BinomialTree() {
if (key) delete key;
for (auto *tree : childrens) {
delete tree;
}
}
template<typename Type>
const bool BinomialHeap<Type>::empty() const {
return !size_;
}
template<typename Type>
BinomialHeap<Type>::BinomialHeap(): size_(0), mini(-1) {}
template<typename Type>
const Type BinomialHeap<Type>::getMin() const {
Base::check();
return roots[mini]->key->key;
}
template<typename Type>
const Type BinomialHeap<Type>::extractMin() {
Base::check();
Type ret = roots[mini]->key->key;
BinomialTree<HData> *mem = roots[mini];
roots[mini] = nullptr;
size_ -= (1U << mini);
BinomialHeap<Type> newHeap(mem->childrens);
merge(newHeap);
mem->childrens.clear();
norm();
delete mem;
return ret;
}
template<typename Type>
BinomialHeap<Type>::BinomialHeap(const Array<BinomialTree<HData> *> &arr):
roots(arr), mini(-1), size_((1U << arr.size()) - 1) {
recalc();
}
template<typename Type>
void BinomialHeap<Type>::merge(BinomialHeap &otherHeap) {
BinomialTree<HData> *rem = nullptr;
for (int i = 0; i < otherHeap.roots.size() || rem; ++i) {
if (i >= roots.size()) {
roots.push(nullptr);
}
if (i >= otherHeap.roots.size()) {
otherHeap.roots.push(nullptr);
}
int num = bool(roots[i]) + bool(otherHeap.roots[i]) + bool(rem);
if (num == 1) {
roots[i] = connect(connect(roots[i], otherHeap.roots[i]), rem);
rem = nullptr;
} else if (num == 2) {
rem = connect(connect(roots[i], otherHeap.roots[i]), rem);
roots[i] = nullptr;
} else {
rem = connect(rem, otherHeap.roots[i]);
}
}
size_ += otherHeap.size_;
recalc();
otherHeap.die();
}
template<typename Type>
BinomialHeap<Type> &BinomialHeap<Type>::operator+=(BinomialHeap &otherHeap) {
merge(otherHeap);
return *this;
}
template<typename Type>
BinomialTree<typename BinomialHeap<Type>::HData> *BinomialHeap<Type>::connect(
BinomialTree<HData> *a, BinomialTree<HData> *b) {
if (!a) return b;
if (!b) return a;
if (a->key->key < b->key->key) {
return a->connect(b);
} else {
return b->connect(a);
}
}
template<typename Type>
void BinomialHeap<Type>::die() {
for (auto &c : roots) {
c = nullptr;
}
size_ = 0;
roots.clear();
}
template<typename Type>
template<typename Iterator>
BinomialHeap<Type>::BinomialHeap(Iterator begin, Iterator end): BinomialHeap() {
for (; begin != end; ++begin) {
insert(*begin);
}
}
template<typename Type>
const typename BinomialHeap<Type>::Pointer BinomialHeap<Type>::insert(const Type &key) {
return insert(new HData(key));
}
template<typename Type>
void BinomialHeap<Type>::erase(const BinomialHeap::Pointer &ptr) {
static_cast<HData *>(&*ptr)->toDelete = true;
Base::change(ptr, getMin());
extractMin();
}
template<typename Type>
void BinomialHeap<Type>::recalc() {
mini = -1;
for (int i = 0; i < roots.size(); ++i) {
if (!roots[i]) continue;
roots[i]->father = nullptr;
if (mini == -1 || roots[i]->key->key < roots[mini]->key->key ||
roots[i]->key->toDelete) {
mini = i;
}
}
}
template<typename Type>
void BinomialHeap<Type>::swap(BinomialTree<HData> *ftree, BinomialTree<HData> *stree) {
std::swap(ftree->key, stree->key);
std::swap(ftree->key->fatherTree, stree->key->fatherTree);
}
template<typename Type>
void BinomialHeap<Type>::siftUp(Pointer ptr) {
for (auto *now = static_cast<HData *>(&*ptr)->fatherTree, *nt = now->father;
nt && now->key->key <= nt->key->key; now = nt, nt = nt->father) {
swap(now, nt);
}
recalc();
}
template<typename Type>
void BinomialHeap<Type>::siftDown(Pointer ptr) {
auto rem = ptr->get();
auto *save = static_cast<HData *>(&*ptr);
static_cast<HData *>(&*ptr)->toDelete = true;
Base::change(ptr, getMin());
static_cast<HData *>(&*ptr)->fatherTree->key = new HData(rem);
static_cast<HData *>(&*ptr)->toDelete = false;
extractMin();
save->key = rem;
insert(save);
}
template<typename Type>
const typename BinomialHeap<Type>::Pointer BinomialHeap<Type>::insert(
BinomialHeap::HData *dt) {
auto *bt = new BinomialTree<HData>(dt);
bt->key->fatherTree = bt;
BinomialHeap<Type> tmp;
tmp.roots.push(bt);
tmp.size_++;
*this += tmp;
recalc();
return Pointer(dt, this);
}
template<typename Type>
void BinomialHeap<Type>::norm() {
for (; !roots.empty() && !roots[-1]; roots.pop());
}
template<typename Type>
const unsigned BinomialHeap<Type>::size() const {
return size_;
}
template<typename Type>
BinomialHeap<Type>::~BinomialHeap() {
for (auto *tree : roots) {
if (tree) delete tree;
}
}
template<typename Type>
BinomialHeap<Type>::HData::HData(const Type &key, BinomialTree<HData> *father):
Data(key), fatherTree(father) { }
#endif
| true |
d056e8f759371855cc967edd87d372308be0397c
|
C++
|
xucaimao/netlesson
|
/pa1-c/test10-4.cpp
|
UTF-8
| 1,887 | 3.40625 | 3 |
[] |
no_license
|
/*
程序设计实习MOOC / 程序设计与算法(一)第十周测验(2017冬季)
4:mysort
write by xucaimao,2018-01-10 17:20,AC 2018-01-10 18:17:32
考察自己写排序函数,以及函数指针的运用
*/
#include <iostream>
using namespace std;
struct A {
int nouse1;
int nouse2;
int n;
};
// 在此处补充你的代码
void mycopy(char * dest,char * source,int size){
//拷贝size个字节
for(int i=0;i<size;i++)
* (dest+i)=*(source+i);
}
void mysort(void * array,int elementNum,int elementSize,int (*cmp)(const void *,const void*) ){
//插入排序
char * arr=(char*)array;
char * v=new char[elementSize];
for(int i=1;i<elementNum;i++){
mycopy(v,arr+i*elementSize,elementSize);
//v=arr[i];
int j;
for(j=i;j>=0 && cmp(arr+(j-1)*elementSize,v)>0;j--){
mycopy(arr+j*elementSize,arr+(j-1)*elementSize,elementSize);
//arr[j]=arr[j-1];
}
mycopy(arr+j*elementSize,v,elementSize);
//arr[j]=v;
}
delete[] v;
}
int MyCompare1( const void * e1,const void * e2) {
int * p1 = (int * ) e1;
int * p2 = (int * ) e2;
return * p1 - * p2;
}
int MyCompare2( const void * e1,const void * e2) {
int * p1 = (int * ) e1;
int * p2 = (int * ) e2;
if( (* p1 %10) - (* p2 % 10))
return (* p1 %10) - (* p2 % 10);
else
return * p1 - * p2;
}
int MyCompare3( const void * e1,const void * e2) {
A * p1 = (A*) e1;
A * p2 = (A*) e2;
return p1->n - p2->n;
}
int a[20];
A b[20];
int main (){
freopen("in.txt","r",stdin);
int n;
while(cin >> n) {
for(int i = 0;i < n; ++i) {
cin >> a[i];
b[i].n = a[i];
}
mysort(a,n,sizeof(int),MyCompare1);
for(int i = 0;i < n; ++i)
cout << a[i] << "," ;
cout << endl;
mysort(a,n,sizeof(int),MyCompare2);
for(int i = 0;i < n; ++i)
cout << a[i] << "," ;
cout << endl;
mysort(b,n,sizeof(A),MyCompare3);
for(int i = 0;i < n; ++i)
cout << b[i].n << "," ;
cout << endl;
}
return 0;
}
| true |
10d5760b1023bdd5e13443b161aca15e9c9cbbe6
|
C++
|
AzureCodeing/RubbishCode
|
/now_coder/数组中出现超过一半的数/main.cpp
|
UTF-8
| 1,990 | 3.828125 | 4 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
class Solution {
public:
//1. 排序统计 时间复杂度 O(nlogn) 空间复杂度O(1)
int MoreThanHalfNum_Solution1(vector<int> numbers) {
sort(numbers.begin(), numbers.end()); //排序算法
int sum = 0;
for(auto num:numbers){//计算中间数个数是否大于整个数组的一半
if(numbers[numbers.size()/2] == num){
sum++;
}
}
return (sum > numbers.size()/2 ? numbers[numbers.size()/2]:0);
}
//2. hash_map统计 时间复杂度 O(nlogn) 空间复杂度O(n)
int MoreThanHalfNum_Solution2(vector<int> numbers) {
map<int, int> temp_map;
for(auto num: numbers){
temp_map[num]++;
}
for(int i = 0; i < numbers.size(); i++){
if(temp_map[numbers[i]] > numbers.size()/2){
return numbers[i];
}
}
return 0;
}
//3. 重复元素计数法 时间复杂度O(n) 空间复杂度O(1)
int MoreThanHalfNum_Solution(vector<int> numbers) {
int numberCount = 0;
int last_number = 0;
for(auto num: numbers){
if(numberCount == 0){
last_number = num;
numberCount = 1;
}else{
if(num == last_number) numberCount++;
else numberCount--;
}
}
if(numberCount == 0) return 0;
else{
numberCount = 0;
for(auto num: numbers){
if(last_number == num) numberCount++;
}
}
return numberCount > (numbers.size()>>1) ? last_number: 0;
}
};
int main(int argc, char *argv[])
{
Solution sol;
std::vector<int> vec1 = {1,2,3,2,2,2,5,4,2,11,33};
std::cout << "超过数组一半的元素是: " << sol.MoreThanHalfNum_Solution3(vec1) << std::endl;
return 0;
}
| true |
4365148c0003eeeb2ee4ad838736457a235ae156
|
C++
|
Att4ck3rS3cur1ty/e12
|
/e12.cpp
|
UTF-8
| 1,525 | 4 | 4 |
[] |
no_license
|
#include <iostream>
#include <cmath>
int fatorial(const int n) {
// Calcula recursivamente o fatorial de n
// Insira o código aqui
int x = 0;
while (n > 1) x += n * (x - 1);
return n;
}
int primalidade(const int n, int i) {
// Testa recursivamente os divisores ímpares de i até a raiz quadrada do N
// Insira o código aqui
int x = 0;
int y = i;
x += sqrt(n);
while (i =! x){
if(i % y != 0){
y--;
return y;
}
}
return 0;
}
int primo(const int n) {
// Testa se é divisível por 2 executa a função primalidade() para testar os
// divisores ímpares de 3 até a raiz quadrada do N
if (n%2==0)
return 0;
return primalidade(n,3);
}
int maior_primo_anterior (int valor) {
// Busca recursiva pelo maior valor primo anterior a valor
// Insira o código aqui
valor--;
int x = valor - 2;
while (valor > 1){
if (valor % x != 0) {
x--;
if (x == 2) return valor;
else valor--;
}
}
return 0;
}
int main(int argc, char const *argv[])
{
int x = 5;
// Imprime: X =5 (5! = 120) => 113
std::cout << "X = " << x << "(" << x << "! = " << fatorial(x) << ") => "
<< maior_primo_anterior(fatorial(x)) << std::endl;
x = 3;
// Imprime: X =3 (3! = 6) => 5
std::cout << "X = " << x << "(" << x << "! = "
<< fatorial(x) << ") => " << maior_primo_anterior(fatorial(x)) << std::endl;
x = 9;
// Imprime: X =9 (9! = 362880) => 362867
std::cout << "X = " << x << "(" << x << "! = "
<< fatorial(x) << ") => " << maior_primo_anterior(fatorial(x)) << std::endl;
return 0;
}
| true |
443499482deda8c739b8aeade4951a0c6d585bd7
|
C++
|
lasicuefs/augmented-tattoo
|
/augmented-tattoo-rt/contourextractor.h
|
UTF-8
| 1,620 | 3.015625 | 3 |
[] |
no_license
|
#ifndef CONTOUREXTRACTOR_H
#define CONTOUREXTRACTOR_H
class ContourExtractor {
public:
float minArea = 50.0f;
float maxArea = 2000.0f;
/// Returns true if passed the filter
typedef bool (*FilterContourCallback)(vector<Point> &contour, void* userdata);
/// Filter contours by size
static bool SizeFilterCB(vector<Point> &contour, void* userdata = NULL){
ContourExtractor* c = (ContourExtractor*) userdata;
double area = contourArea(contour);
if(area > c->minArea && area < c->maxArea) return true;
return false;
}
/// Extract contours running the filters
void process(Mat img, vector< vector<Point> >& candidates,
vector< FilterContourCallback > &filters){
// Get the contours
vector <Vec4i> hierarchy;
vector < vector<Point> > contours;
findContours(img.clone(), contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_NONE);
// For each blob we run each filter. If the blob pass all tests
// we include it in the selection list.
for(int i = 0; i < contours.size(); i++){
// Little injection. Only consider leaf contours.
if(hierarchy[i][2] != -1) continue;
bool filtered = false;
for(int j = 0; j < filters.size(); j++){
if(!filters[j](contours[i], this)){
filtered = true;
break;
}
}
if(!filtered) candidates.push_back(contours[i]);
}
}
};
#endif // CONTOUREXTRACTOR_H
| true |
70219dd30cd99707eec8c69fb7d7a5c628427333
|
C++
|
gustavobiage/URI_Solutions
|
/DataStructures/2519.cpp
|
UTF-8
| 1,239 | 2.65625 | 3 |
[] |
no_license
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
struct query {
int x1, y1;
int x2, y2;
};
int byte[1001][1001];
int arr[1001][1001];
int N, M, Q;
int v, a, b, x, y;
struct query q;
int get(int x, int y) {
int ans = 0;
for (; x; x-=x&-x) {
for (int b = y; b; b-=b&-b) {
ans += byte[x][b];
}
}
return ans;
}
int getQuery(struct query &q) {
return get(q.x2, q.y2) - get(q.x1-1, q.y2) - get(q.x2, q.y1-1) + get(q.x1-1, q.y1-1);
}
void update(int x, int y, int val) {
for (; x <= N; x+=x&-x) {
for (int b = y; b <= M; b+=b&-b) {
byte[x][b] += val;
}
}
}
int main() {
while (scanf("%d %d ", &N, &M) != EOF) {
for (int i = 0; i <= N; i++) {
for (int j = 0; j <= M; j++) {
byte[i][j] = 0;
}
}
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= M; j++) {
scanf("%d ", &v);
if (v) {
update(i, j, v);
arr[i][j] = 1;
}
}
}
scanf("%d ", &Q);
for (int i = 0; i < Q; i++) {
scanf("%d %d %d %d %d ", &v, &x, &y, &a, &b);
if (v) {
q.x1 = fmin(x, a);
q.x2 = fmax(x, a);
q.y1 = fmin(y, b);
q.y2 = fmax(y, b);
printf("%d\n", getQuery(q));
} else {
update(x, y, -1);
update(a, b, 1);
}
}
}
return 0;
}
| true |
a639feb462826bf56226707b2b159ccf7960bba9
|
C++
|
skapfer/sphmink
|
/Vector.h
|
UTF-8
| 2,824 | 3.234375 | 3 |
[] |
no_license
|
#ifndef VECTOR_H_INCLUDED
#define VECTOR_H_INCLUDED
#include "./common.h"
#include <assert.h>
#include <math.h>
#include <ostream>
class Vector {
public:
Vector () {
d_[0] = d_[1] = d_[2] = 0.;
}
Vector (double x_, double y_, double z_) {
d_[0] = x_;
d_[1] = y_;
d_[2] = z_;
}
//
// accessors
//
double &operator[] (int i) {
assert (i == 2 || i == 1 || i == 0);
return d_[i];
}
double operator[] (int i) const {
assert (i == 2 || i == 1 || i == 0);
return d_[i];
}
//
// operators
//
Vector &operator+= (const Vector &rhs) {
d_[0] += rhs[0];
d_[1] += rhs[1];
d_[2] += rhs[2];
return *this;
}
Vector &operator-= (const Vector &rhs) {
d_[0] -= rhs[0];
d_[1] -= rhs[1];
d_[2] -= rhs[2];
return *this;
}
Vector &operator*= (double rhs) {
d_[0] *= rhs;
d_[1] *= rhs;
d_[2] *= rhs;
return *this;
}
Vector &operator/= (double rhs) {
d_[0] /= rhs;
d_[1] /= rhs;
d_[2] /= rhs;
return *this;
}
private:
double d_[3];
};
inline Vector operator+ (const Vector &lhs, const Vector &rhs) {
return Vector (lhs[0]+rhs[0], lhs[1]+rhs[1], lhs[2]+rhs[2]);
}
inline Vector operator- (const Vector &lhs, const Vector &rhs) {
return Vector (lhs[0]-rhs[0], lhs[1]-rhs[1], lhs[2]-rhs[2]);
}
inline Vector operator* (double f, const Vector &v) {
return Vector (f*v[0], f*v[1], f*v[2]);
}
inline Vector operator* (const Vector &v, double f) {
return f * v;
}
inline Vector operator/ (const Vector &v, double f) {
return Vector (v[0]/f, v[1]/f, v[2]/f);
}
inline std::ostream &operator<< (std::ostream &lhs, const Vector &rhs) {
lhs << "(" << rhs[0] << ", " << rhs[1] << " , "<< rhs[2] <<")";
return lhs;
}
inline bool operator== (const Vector &lhs, const Vector &rhs) {
return lhs[0] == rhs[0] and lhs[1] == rhs[1] and lhs[2] == rhs[2];
}
// standard euclidean 2-norm
inline double norm_sq (const Vector &v) {
return v[0]*v[0] + v[1]*v[1] + v[2]*v[2];
}
inline double norm (const Vector &v) {
return sqrt (norm_sq (v));
}
// dot product
inline double dot (const Vector &lhs, const Vector &rhs) {
return lhs[0]*rhs[0] + lhs[1]*rhs[1] + lhs[2]*rhs[2];
}
inline bool vector_isnan (const Vector &x) {
return is_nan (x[0]) || is_nan (x[1]) || is_nan (x[2]);
}
inline void vector_normalize (Vector *x) {
*x /= norm (*x);
}
// cross product
inline Vector cross_product (const Vector &lhs, const Vector &rhs){
Vector a;
a[0] = lhs[1]*rhs[2] - lhs[2]*rhs[1];
a[1] = lhs[2]*rhs[0] - lhs[0]*rhs[2];
a[2] = lhs[0]*rhs[1] - lhs[1]*rhs[0];
return a;
}
#endif // VECTOR_H_INCLUDED
| true |
4be30d4d80552892262731e8ab2118dea7689ccd
|
C++
|
Kuutio/TAMK-Olio-ohjelmointi-C
|
/Viikko46/Teht3ja4/Opettaja.cpp
|
UTF-8
| 1,446 | 2.84375 | 3 |
[] |
no_license
|
#include "Opettaja.h"
#include <iostream>
using std::cout; using std::endl; using std::cin;
Opettaja::Opettaja()
:opetusala("Kalastus")
{
//cout << "Opettaja: Oletus rakentaja" << endl;
}
Opettaja::Opettaja(string etunimi_, string osoite_, string puhelinnumero_, string sukunimi_, string palkka_, string tunnus_, string opetusala_)
: Tyontekija(etunimi_, osoite_, puhelinnumero_, sukunimi_, palkka_, tunnus_), opetusala(opetusala_)
{
//cout << "Opettaja: Parametri rakentaja" << endl;
}
Opettaja::Opettaja(const Opettaja& Opettaja_) : Tyontekija(Opettaja_), opetusala(Opettaja_.opetusala)
{
//cout << "Opettaja: Kopio rakentaja" << endl;
}
Opettaja::~Opettaja()
{
//cout << "Opettaja: Tuhotaan oliota" << endl;
}
string Opettaja::annaOpetusala()
{
return opetusala;
}
void Opettaja::asetaOpetusala(string opetusala_)
{
opetusala = opetusala_;
}
void Opettaja::kysyTiedot()
{
Tyontekija::kysyTiedot();
cout << "Anna opetusala! >>";
getline(cin, opetusala);
while (!cin) { //virheentarkistus
cin.clear();
cin.ignore(std::numeric_limits<int>::max(), '\n');
cout << "Invalid argument!" << endl;
cout << "Anna opetusala! >>";
getline(cin, opetusala);
}
}
void Opettaja::tulosta() const
{
Tyontekija::tulosta();
cout << "Opetusala: " << opetusala << endl;
}
void Opettaja::operator=(Opettaja& toinenOpettaja)
{
opetusala = toinenOpettaja.annaOpetusala();
}
| true |
f4fdc05f98a775e97b2d1a58921b3448e0702819
|
C++
|
seriouszyx/leetcode
|
/algorithms/cpp/122.买卖股票的最佳时机-ii.cpp
|
UTF-8
| 398 | 3 | 3 |
[
"MIT"
] |
permissive
|
/*
* @lc app=leetcode.cn id=122 lang=cpp
*
* [122] 买卖股票的最佳时机 II
*/
class Solution {
public:
int maxProfit(vector<int>& prices) {
int maxPro = 0, tmp = 0;
for (int i = 1; i < prices.size(); ++i) {
tmp = prices[i] - prices[i-1];
if (tmp > 0)
maxPro += tmp;
}
return maxPro;
}
};
| true |
e6a7bf50364374067bdd75f08eee79ae6ceca769
|
C++
|
sdwvskyo/C-Cplusplus
|
/Complex/Complex.cc
|
UTF-8
| 1,794 | 3.5 | 4 |
[] |
no_license
|
#include "Complex.h"
using namespace std;
Complex::Complex(double real, double img)
: real_(real), img_(img)
{
}
Complex::~Complex()
{
}
Complex::Complex(const Complex &c)
{
real_ = c.real_;
img_= c.img_;
}
Complex & Complex::operator= (const Complex &c)
{
real_ = c.real_;
img_ = c.img_;
return *this;
}
Complex & Complex::operator= (double real)
{
real_ = real;
return *this;
}
double Complex::getMod() const
{
return sqrt(real_*real_ + img_*img_);
}
std::ostream & operator<< (std::ostream &os, const Complex &c)
{
return os << c.real_ << "+" << c.img_ << "i";
}
const Complex operator+ (const Complex &c1, const Complex &c2)
{
return Complex(c1.real_ + c2.real_, c1.img_ + c2.img_);
}
const Complex operator+ (const Complex &c, double real)
{
return c + Complex(real);
}
const Complex operator+ (double real, const Complex &c)
{
return Complex(real) + c;
}
const Complex operator- (const Complex &c1, const Complex &c2)
{
return Complex(c1.real_ - c2.real_, c1.img_ - c2.img_);
}
const Complex operator- (const Complex &c, double real)
{
return c - Complex(real);
}
const Complex operator- (double real, const Complex &c)
{
return Complex(real) - c;
}
const Complex operator* (const Complex &c1, const Complex &c2)
{
return Complex(c1.real_ * c2.real_, c1.img_ * c2.img_);
}
const Complex operator* (const Complex &c, double real)
{
return c * Complex(real);
}
const Complex operator* (double real, const Complex &c)
{
return Complex(real) * c;
}
const Complex operator/ (const Complex &c1, const Complex &c2)
{
return Complex(c1.real_ / c2.real_, c1.img_ / c2.img_);
}
const Complex operator/ (const Complex &c, double real)
{
return c / Complex(real);
}
const Complex operator/ (double real, const Complex &c)
{
return Complex(real) / c;
}
| true |
659a67e0dcf9effa97e131db50cc2cd4e6563e96
|
C++
|
Fredoun21/ESP8266_Radiateur
|
/test/main.ino
|
UTF-8
| 8,306 | 2.546875 | 3 |
[] |
no_license
|
/*
Projet d'apprentissage d'un objet connecté (IoT) pour réaliser une sonde de température
ESP8266 + DS12B20 + LED + MQTT + Home-Assistant
Projets DIY (https://www.projetsdiy.fr) - Mai 2016
Licence : MIT
*/
// Include the libraries we need
#include <Arduino.h>
#include <stdfred.h>
#include <sensor.h>
#include <Ticker.h>
#include "..\include\config.h"
#include "..\include\domoticzConfig.h"
#define DEBUG
/*
PIN SETTINGS
*/
#define PIN_FILPILOTE_PLUS 12 // N° de Pin fil pilote
#define PIN_FILPILOTE_MOINS 13 // N° de Pin fil pilote
#define PIN_ACS712 A0 // Mesure de courant
#define PIN_ONE_WIRE_BUS 14 // Mesure de température
long i = 0;
/*
Création des objets
*/
// client MQTT
WiFiClient espClient;
PubSubClient clientMQTT(espClient);
// bus I2C
OneWire oneWire(PIN_ONE_WIRE_BUS);
DallasTemperature DS18B20(&oneWire);
// Création tache tempo pour mode confort 1 et 21
Ticker tickerSetHigh;
Ticker tickerSetLow;
/*
* The setup function. We only start the sensors here
*/
void setup(void)
{
Serial.begin(115200);
pinMode(PIN_FILPILOTE_PLUS, OUTPUT);
pinMode(PIN_FILPILOTE_MOINS, OUTPUT);
// Positionne en mode Hors Gel à la mise sous tension
digitalWrite(PIN_FILPILOTE_PLUS, HIGH);
digitalWrite(PIN_FILPILOTE_MOINS, HIGH);
// Start LE DS18b20
DS18B20.begin();
Serial.printf("\nID MQTT: %s", MQTT_ID);
// Connexion au réseau wifi
setup_wifi(LOCAL_IP, LOCAL_GATEWAY, LOCAL_SUBNET, LOCAL_SSID, LOCAL_PASSWORD);
delay(500);
//Configuration de la connexion au serveur MQTT
setserverMQTT(clientMQTT, MQTT_SERVER, MQTT_PORT);
//La fonction de callback qui est executée à chaque réception de message
clientMQTT.setCallback(callback);
}
/*
* Main function, get and show the temperature
*/
void loop(void)
{
// Connexion client MQTT
if (!clientMQTT.connected())
{
reconnect(clientMQTT, MQTT_ID, TOPIC_DOMOTICZ_OUT, MQTT_USER, MQTT_PASSWORD);
}
clientMQTT.loop();
unsigned long currentMillis = millis();
String cmd = "";
// ajout d'un delais de 60s apres chaque trame envoyés pour éviter d'envoyer
// en permanence des informations à domoticz et de créer des interférences
if ((currentMillis - previousMillis > watchdog) || firstLoop == LOW)
{
previousMillis = currentMillis;
if (!firstLoop)
{ // Demande état d'un device
askMqttToDomoticz(clientMQTT, IDXDomoticz, "getdeviceinfo", TOPIC_DOMOTICZ_IN);
firstLoop = HIGH;
}
// Envoi MQTT température du DS18B20
sendMqttToDomoticz(clientMQTT, IDXDS18B20, String(valeurDS18B20(DS18B20)), TOPIC_DOMOTICZ_IN);
// Envoi MQTT mesure de courant du AC712
sendMqttToDomoticz(clientMQTT, IDXACS712, String(valeurACS712(PIN_ACS712)), TOPIC_DOMOTICZ_IN);
}
}
/*
callback
Déclenche les actions à la réception d'un message
topic -> nom du topic de réception des message (domoticz/out)
payload -> message reçu
length -> longueur message reçu
*/
void callback(char *topic, byte *payload, unsigned int length)
{
DynamicJsonDocument jsonBuffer(MQTT_MAX_PACKET_SIZE);
String messageReceived = "";
// Affiche le topic entrant - display incoming Topic
Serial.print("\nMessage arrived [");
Serial.print(topic);
Serial.println("] ");
// decode payload message
for (uint i = 0; i < length; i++)
{
messageReceived += ((char)payload[i]);
}
// display incoming message
Serial.println("Message recu:");
Serial.print(messageReceived);
// if domoticz message
if (strcmp(topic, TOPIC_DOMOTICZ_OUT) == 0)
{
DeserializationError error = deserializeJson(jsonBuffer, messageReceived);
if (error)
{
Serial.print(F("parsing Domoticz/out JSON Received Message failed with code: "));
Serial.println(error.c_str());
return;
}
int idx = jsonBuffer["idx"];
int nvalue = jsonBuffer["nvalue"];
float svalue = jsonBuffer["svalue"];
float svalue1 = jsonBuffer["svalue1"];
const char *name = jsonBuffer["name"];
#ifdef DEBUG
Serial.println();
Serial.printf("\nIDX: %i, name: %s, nVALUE: %i, sVALUE: %.2f, sVALUE1: %i\n", idx, name, nvalue, float(svalue), int(svalue1));
#endif
if (idx == IDXDomoticz)
{
// MAJ de l'état du radiateur
updateFilpilote(PIN_FILPILOTE_PLUS, PIN_FILPILOTE_MOINS, int(svalue1), idx);
}
}
}
// MAJ des sorties fil pilote en fonction du message Domoticz
void updateFilpilote(int pinP, int pinM, int svalue, int idx)
{
String message;
Serial.println(F("Mise a jour fil Pilote depuis DOMOTICZ: "));
// Etat de 00 à 10: Radiateur sur Arrêt
// Etat de 11 à 20: Radiateur sur Hors Gel
// Etat de 21 à 30: Radiateur sur ECO
// Etat de 31 à 40: Radiateur sur Confort 2 (T° Confort - 2°C)
// Etat de 41 à 50: Radiateur sur Confort 1 (T° Confort - 1°C)
// Etat de 51 à 100: Radiateur sur Confort
if (0 <= svalue && svalue < 10)
{
digitalWrite(pinP, HIGH);
digitalWrite(pinM, LOW);
confortStopTask();
Serial.println(F("Radiateur sur ARRET"));
message = "Pin ";
message += String(pinP);
message += " = HIGH / Pin ";
message += String(pinM);
message += " = LOW";
Serial.println(message);
}
else if (10 <= svalue && svalue < 20)
{
digitalWrite(pinP, LOW);
digitalWrite(pinM, HIGH);
confortStopTask();
Serial.println(F("Radiateur sur HORS GEL"));
message = "Pin ";
message += String(pinP);
message += " = LOW / Pin ";
message += String(pinM);
message += " = HIGH";
Serial.println(message);
}
else if (20 <= svalue && svalue < 30)
{
digitalWrite(pinP, HIGH);
digitalWrite(pinM, HIGH);
confortStopTask();
Serial.println(F("Radiateur sur ECO"));
message = "Pin ";
message += String(pinP);
message += " = HIGH / Pin ";
message += String(pinM);
message += " = HIGH";
Serial.println(message);
}
else if (30 <= svalue && svalue < 40)
{
confortStopTask();
confortSetPin(pinP, pinM, 7, 293);
Serial.println(F("Radiateur sur CONFORT 2"));
// Absence de courant pendant 293s, puis présence pendant 7s
}
else if (40 <= svalue && svalue < 50)
{
confortStopTask();
confortSetPin(pinP, pinM, 3, 297);
Serial.println(F("Radiateur sur CONFORT 1"));
// Absence de courant pendant 297s, puis présence pendant 3s
}
else if (50 <= svalue && svalue <= 100)
{
digitalWrite(pinP, LOW);
digitalWrite(pinM, LOW);
confortStopTask();
Serial.println(F("Radiateur sur CONFORT"));
message = "Pin ";
message += String(pinP);
message += " = LOW / Pin ";
message += String(pinM);
message += " = LOW";
Serial.println(message);
}
else
{
Serial.println(F("Valeur erronee!"));
}
}
// Procédure MAJ sortie pour mode confort 1 & 2
void setPinConfort(int state)
{
digitalWrite(PIN_FILPILOTE_PLUS, state);
digitalWrite(PIN_FILPILOTE_MOINS, state);
i++;
// Serial.print(F("Compteur: ")); Serial.println(i);
// Serial.print(F("STATE: ")); Serial.println(state);
if (state == 1)
{
Serial.println(F("Tempo HIGH"));
}
else if (state == 0)
{
Serial.println(F("Tempo LOW"));
}
}
// Lancement tempo pour mode confort 1 & 2
void confortSetPin(int aPinHigh, int aPinLow, float aTempoHigh, float aTempoLow)
{
tickerSetHigh.attach(aTempoHigh, setPinConfort, 1);
tickerSetLow.attach(aTempoLow, setPinConfort, 0);
}
// Arrêt tempo pour mode confort 1 & 2
void confortStopTask()
{
tickerSetHigh.detach();
tickerSetLow.detach();
}
| true |
b8ae066886564d7c9e9b7224a4a502ce965af1b6
|
C++
|
botezatumihaicatalin/ChaoticImageCrypto
|
/src/ruleT_generator3.hpp
|
UTF-8
| 1,266 | 2.984375 | 3 |
[
"MIT"
] |
permissive
|
#pragma once
#include <cmath>
#include "generator3.hpp"
#include "skew_tent_generator1.hpp"
// Composed of three skew_tent maps.
class ruleT_generator3 : public generator3 {
protected:
skew_tent_generator1 skew_tent1_;
skew_tent_generator1 skew_tent2_;
skew_tent_generator1 skew_tent3_;
public:
ruleT_generator3(const dvec3& start, const double& exp1, const double& exp2, const double& exp3)
: generator3(start), skew_tent1_(start.x, exp1), skew_tent2_(start.y, exp2), skew_tent3_(start.z, exp3) {}
ruleT_generator3(const skew_tent_generator1& gen1, const skew_tent_generator1& gen2, const skew_tent_generator1& gen3)
: generator3(gen1.current(), gen2.current(), gen3.current()), skew_tent1_(gen1), skew_tent2_(gen2), skew_tent3_(gen3) {}
ruleT_generator3(const double& x, const double& y, const double& z,
const double& exp1, const double& exp2, const double& exp3)
: generator3(x, y, z), skew_tent1_(x, exp1), skew_tent2_(y, exp2), skew_tent3_(z, exp3) {}
const dvec3& next() override;
};
inline const dvec3& ruleT_generator3::next() {
current_.x = skew_tent1_.next();
if (current_.x < 0.5) {
current_.y = skew_tent2_.next();
}
else {
current_.z = skew_tent3_.next();
}
return current_;
}
| true |
91ea7223e916cef8033593fae7f37bf0d6b47706
|
C++
|
PW486/leetcode
|
/solutions/cpp/49-group-anagrams.cc
|
UTF-8
| 1,114 | 3.703125 | 4 |
[
"Unlicense"
] |
permissive
|
#include <iostream>
#include <map>
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string> &strs) {
map<vector<int>, vector<string>> store;
for (auto it = strs.begin(); it != strs.end(); it++) {
vector<int> alphabet(26);
for (char c : *it) {
alphabet[c - 'a']++;
}
store[alphabet].push_back(*it);
}
vector<vector<string>> result;
for (auto map_it = store.begin(); map_it != store.end(); map_it++) {
vector<string> group;
for (auto vec_it = map_it->second.begin(); vec_it != map_it->second.end();
vec_it++) {
group.push_back(*vec_it);
}
result.push_back(group);
}
return result;
}
};
int main() {
vector<string> strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
vector<vector<string>> result = Solution().groupAnagrams(strs);
for (auto it_1 = result.begin(); it_1 != result.end(); it_1++) {
for (auto it_2 = (*it_1).begin(); it_2 != (*it_1).end(); it_2++) {
cout << *it_2 << ' ';
}
cout << endl;
}
return 0;
}
| true |
6288fe8c36b1a368ed3362387129457fa5352f2a
|
C++
|
jptang2/huffman_compression
|
/source/FileTree/Tree.h
|
UTF-8
| 520 | 3.5 | 4 |
[] |
no_license
|
#pragma once
class Tree
{
public :
char ch;
int weight;
Tree* left;
Tree* right;
Tree(){left = right = NULL; weight=0;ch ='\0';}
Tree(Tree* l,Tree* r,int w,char c){left = l; right = r; weight=w; ch=c;}
~Tree(){delete left; delete right;}
bool Isleaf(){return !left && !right; }
};
class Compare_tree
{
public:
bool operator () (Tree* t1, Tree* t2)
{
if (t1->weight == t2->weight)
{
return t1->ch > t2->ch;
}
return t1->weight > t2->weight;
}
};
| true |
e5886b9627d66e84399af380e802d28f1af1317f
|
C++
|
Shmosh001/CSC3022H-Assignment-1
|
/Driver.cpp
|
UTF-8
| 1,996 | 3.890625 | 4 |
[] |
no_license
|
#include <iostream>
#include "StudentDatabase.h"
int main()
{
using namespace SHMOSH001;
using namespace std;
//all possible variables that the user may enter about a student
string name;
string surname;
string StudentNumber;
string ClassRecord;
while (true)
{
//char used for user selection
char c;
cout << "Enter a number (or 'q' to quit) followed by enter (return key):\n";
cout << "1: Add student\n2: Read database\n3: Save database\n4: Display given student data\n5: Grade student\n";
cout << "q: Quit\n";
cin >> c;
//This lets the user add a student to the database
if(c == '1')
{
cout << "Enter student first name:\n";
cin >> name;
cout << "Enter student surname:\n";
cin >> surname;
cout << "Enter student number:\n";
cin >> StudentNumber;
cout << "Enter student grades seperated by a space:\n";
cin.ignore(); //ignores the new line as an input
getline(cin, ClassRecord); //reads the whole line input instead of up to a whitespace
cout << "function addStudent() called\n";
//method addStudent called
addStudent(name,surname,StudentNumber,ClassRecord);
}
//reads the database
else if(c == '2')
{
cout << "function readDatabase() called\n";
readDatabase();
}
//saves changes to database
else if(c == '3')
{
cout << "function saveDatabase() called\n";
saveDatabase();
}
//displays a particular student based on student number
else if(c == '4')
{
string StudentNumber;
cout << "function displayStudent() called\n";
cout << "Enter student number(uppercase):\n";
cin >> StudentNumber;
displayStudent(StudentNumber);
}
//gets average grade of student based on student number
else if(c == '5')
{
string StudentNumber;
cout << "function gradeStudent() called\n";
cout << "Enter student number(uppercase):\n";
cin >> StudentNumber;
gradeStudent(StudentNumber);
}
//quits program
else if(c == 'q')
{
break;
}
}
return 0;
}
| true |
138c7d707d9108d1fecafc2e7dca37dd0da0d2cc
|
C++
|
httt-dev/sale-management-system
|
/SMS Project/Invoice.h
|
UTF-8
| 643 | 2.984375 | 3 |
[] |
no_license
|
#pragma once
#include <iostream>
#include <string>
#include "GlobalFunction.h"
using namespace std;
class Invoice
{
private:
string id, date, customerID, type;
public:
Invoice(string s = "");
friend ostream &operator <<(ostream &os, Invoice &s);
void setID(string id) { this->id = id; }
void setDate(string date) { this->date = date; }
void setCustomerID(string customerID) { this->customerID = customerID; }
void setType(string type) { this->type = type; }
string getID() { return this->id; }
string getDate() { return this->date; }
string getCustomerID() { return this->customerID; }
string getType() { return this->type; }
};
| true |
941d9726494e16286c0458ffc24d7398980e6b42
|
C++
|
toniou/liam-esp
|
/src/mowing_schedule.cpp
|
UTF-8
| 4,590 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
#include "mowing_schedule.h"
#include "configuration.h"
#include <Preferences.h>
#include <ArduinoJson.h>
#include <ArduinoLog.h>
MowingSchedule::MowingSchedule() {}
/**
* Adds a new entry to the schedule list.
* @param activeWeekdays represent the seven days in a week (MUST always sized seven)
* @param time to start mowing, the format MUST be "HH:MM"
* @param time to stop mowing, the format MUST be "HH:MM"
* @return -1 malformated activeWeekdays, -2 malformated startTime, -3 malformated stopTime, -4 too many entries. 0 or greater = success
*/
int8_t MowingSchedule::addScheduleEntry(std::deque<bool> activeWeekdays, String startTime, String stopTime) {
const std::regex timeRegex("(00|01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|16|17|18|19|20|21|22|23):(0|1|2|3|4|5)\\d");
if (mowingSchedule.size() >= 10) {
return -4;
}
if (activeWeekdays.size() < 7 || activeWeekdays.size() > 7) {
return -1;
}
if (!std::regex_match(startTime.c_str(), timeRegex)) {
return -2;
}
if (!std::regex_match(stopTime.c_str(), timeRegex)) {
return -3;
}
scheduleEntry entry;
entry.activeWeekdays = activeWeekdays;
entry.startTime = startTime;
entry.stopTime = stopTime;
mowingSchedule.push_front(entry);
saveSchedulesToFlash();
return 1;
}
const std::deque<scheduleEntry>& MowingSchedule::getScheduleEntries() const {
return mowingSchedule;
}
/**
* Removes an entry from the list
* @param position the position of the entry in the list that should be removed (first position = 0)
*/
void MowingSchedule::removeScheduleEntry(uint8_t position) {
if (position < mowingSchedule.size()) {
mowingSchedule.erase(mowingSchedule.begin() + position);
saveSchedulesToFlash();
}
}
/**
* Override schedule to force mower to start mowing outside of schedule, this is used when manually launching mower from API.
*/
void MowingSchedule::setManualMowingOverride(bool enable) {
manualMowingOverride = enable;
}
/**
* Check if the mower should mow now, according to the mowing schedule and the current time.
*/
bool MowingSchedule::isTimeToMow() {
if (manualMowingOverride) {
return true;
}
struct tm timeinfo;
if (!getLocalTime(&timeinfo, 200)) { // tries for 200 ms
return false;
}
// fix day-of-week to follow ISO-8601
int8_t dayOfWeek = timeinfo.tm_wday == 0 ? 6 : timeinfo.tm_wday - 1;
for (auto schedule : mowingSchedule) {
if (schedule.activeWeekdays[dayOfWeek]) {
int currentTimeInMinutes = timeinfo.tm_hour * 60 + timeinfo.tm_min;
int startTimeInMinutes = schedule.startTime.substring(0, 2).toInt() * 60 + schedule.startTime.substring(3).toInt(); // turn string, like "08:45", into minutes.
int stopTimeInMinutes = schedule.stopTime.substring(0, 2).toInt() * 60 + schedule.stopTime.substring(3).toInt();
if (currentTimeInMinutes >= startTimeInMinutes && currentTimeInMinutes < stopTimeInMinutes) {
return true;
}
}
}
return false;
}
void MowingSchedule::start() {
loadSchedulesFromFlash();
}
void MowingSchedule::loadSchedulesFromFlash() {
mowingSchedule.clear();
Configuration::preferences.begin("liam-esp", false);
auto jsonString = Configuration::preferences.getString("schedules", "[]");
DynamicJsonBuffer jsonBuffer(1200);
JsonArray& root = jsonBuffer.parseArray(jsonString);
if (root.success()) {
for (auto schedule : root) {
scheduleEntry entry;
std::deque<bool> activeWeekdays;
for (const auto& day : schedule["activeWeekdays"].as<JsonArray>()) {
activeWeekdays.push_back(day);
}
entry.activeWeekdays = activeWeekdays;
entry.startTime = schedule["startTime"].as<char*>();
entry.stopTime = schedule["stopTime"].as<char*>();
mowingSchedule.push_back(entry);
}
Log.notice(F("Loaded %i schedules" CR), root.size());
}
}
void MowingSchedule::saveSchedulesToFlash() {
// persist mowing schedules in case of power failure.
DynamicJsonBuffer jsonBuffer(1200);
JsonArray& root = jsonBuffer.createArray();
for (auto schedule : mowingSchedule) {
JsonObject& entry = root.createNestedObject();
JsonArray& activeWeekdays = entry.createNestedArray("activeWeekdays");
for (auto day : schedule.activeWeekdays) {
activeWeekdays.add(day);
}
entry["startTime"] = schedule.startTime;
entry["stopTime"] = schedule.stopTime;
}
String jsonString;
root.printTo(jsonString);
Configuration::preferences.begin("liam-esp", false);
Configuration::preferences.putString("schedules", jsonString);
}
| true |
39f6f827e421db4874a83970b59419d909a66b6d
|
C++
|
mateoatr/Competitive-Programming
|
/UVa/507.cpp
|
UTF-8
| 722 | 2.78125 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
int ruta[20002];
int main(){
int N, r; cin >> N;
for(int i = 1; i <= N; i++){
cin >> r;
int max = 0, current = 0, k = 0, pi, ui, cc = 0;
for(int j = 1; j < r; j++){
cin >> ruta[j];
current += ruta[j]; k++;
if(current < 0){ current = 0; k = 0; }
if(max == current && k > cc){
cc = k;
max = current;
ui = j + 1;
pi = ui - k;
}
else if(max < current){
cc = k; max = current;
ui = j + 1; pi = ui - k;
}
}
if(max > 0)
cout << "The nicest part of route " << i << " is between stops " << pi << " and " << ui << endl;
else
cout << "Route " << i << " has no nice parts" << endl;
}
return 0;
}
| true |
c29a138aa2332634b421bc4064e373e01d93cea1
|
C++
|
GabrieleCosta00/Prova_per_Calendario
|
/main.cpp
|
UTF-8
| 9,942 | 2.9375 | 3 |
[] |
no_license
|
#include <iostream>
#define n_giorno 5
#define n_slot 6
//#define n_aula 4
#define n_esame 20
#define n_max_gruppo 5
using namespace std;
struct exam {
int id;
bool piazzato;
__attribute__((unused)) bool gruppo_piazzato; // WTF?!?!
int durata;
int prof;
int n_gruppo;
int id_gruppo[n_max_gruppo];
};
struct date {
int id_esame;
int durata_esame;
int prof_esame;
};
// Procedure
void print_esami(const exam* esame){
cout<<endl;
for(int i=0; i<n_esame; i++)
{
cout<<"Esame id: "<<esame[i].id<<"\tStato: ";
for (int j : esame[i].id_gruppo)
{
if(j!=0)
{
cout<<esame[j-1].piazzato<<" ";
}
else
{
cout<<"0 ";
}
}
cout<<"\tDurata: "<<esame[i].durata<<
"\t Prof: "<<esame[i].prof<<"\tGruppo: ";
for (int j : esame[i].id_gruppo)
{
cout<<j<<" ";
}
cout<<endl;
}
cout<<endl<<endl;
}
/*void print_calendario(date m[][n_slot][n_aula]){
cout<<"Calendario: "<<endl<<endl;
cout<<"Id esame - Durata - Prof > Aule"<<endl<<endl<<" v"<<endl<<" Slot e Giorni"<<endl<<endl<<endl;
for(int i=0; i<n_giorno; i++)
{
for(int j=0; j<n_slot; j++)
{
for(int k=0; k<n_aula; k++)
{
cout<<"\t"<<m[i][j][k].id_esame<<" - "<<m[i][j][k].durata_esame<<" - "<<m[i][j][k].prof_esame;
}
cout<<endl;
}
cout<<endl<<endl;
}
}*/
void print_calendario_no_aule(date cell[][n_slot]){
cout<<"Calendario no aule: "<<endl<<endl;
cout<<"Id esame - Durata - Prof > Slot"<<endl<<endl<<" v"<<endl<<" Giorni"<<endl<<endl<<endl;
for(int i=0; i<n_giorno; i++)
{
for(int j=0; j<n_slot; j++)
{
cout<<"\t"<<cell[i][j].id_esame<<" - "<<cell[i][j].durata_esame<<" - "<<cell[i][j].prof_esame;
}
cout<<endl;
}
}
/*
void Mettibile(exam* esame, date m[][n_slot][n_aula], int cont_esami, int cont_gruppo, int giorno, int slot, int aula, bool* mettibile){
for(int j=0; j<esame[esame[cont_esami].id_gruppo[cont_gruppo]-1].durata; j++)
{
if (m[giorno][slot+j][aula].id_esame!=0)
*mettibile = false;
}
}
*/
void Mettibile_no_aule(exam* esame, date cell[][n_slot], int cont_esami, int cont_gruppo, int giorno, int slot, bool* mettibile){
for(int j=0; j<esame[esame[cont_esami].id_gruppo[cont_gruppo]-1].durata; j++)
{
if(cell[giorno][slot+j].id_esame!=0)
*mettibile = false;
}
}
/*void Prof_libero(exam* esame, date m[][n_slot][n_aula], int cont_esami, int cont_gruppo, int giorno, int slot, int aula, bool* prof_libero){
for(int j=0; j<esame[esame[cont_esami].id_gruppo[cont_gruppo]-1].durata; j++)
{
for (int k=0; k<n_aula; k++)
{
if(m[giorno][slot+j][k].prof_esame==esame[esame[cont_esami].id_gruppo[cont_gruppo]-1].prof && aula!=k)
*prof_libero = false;
}
}
}*/
/*void Inizializza_date(date m[][n_slot][n_aula]){
for(int i=0; i<n_giorno; i++)
{
for(int j=0; j<n_slot; j++)
{
for(int k=0; k<n_aula; k++)
{
m[i][j][k].id_esame=0;
m[i][j][k].durata_esame=0;
m[i][j][k].prof_esame=0;
}
}
}
}*/
void Inizializza_date_no_aule(date cell[][n_slot]){
for(int i=0; i<n_giorno; i++)
{
for(int j=0; j<n_slot; j++)
{
cell[i][j].id_esame=0;
cell[i][j].durata_esame=0;
cell[i][j].prof_esame=0;
}
}
}
void Inizializza_exam_default(exam* esame){
for(int i=0; i<n_esame; i++)
{
esame[i].id=i+1;
esame[i].piazzato=false;
esame[i].gruppo_piazzato=false;
esame[i].durata=1;
esame[i].prof=1001+i;
esame[i].n_gruppo=1;
for (int & j : esame[i].id_gruppo)
{
j=0;
}
esame[i].id_gruppo[0]=esame[i].id;
}
}
void Personalizza_exam(exam* esame){
for(int i=1; i<n_esame; i=i+2)
{
esame[i].piazzato=false;
esame[i].durata=2;
}
for(int i=0; i<n_esame; i=i+3)
{
esame[i].piazzato=false;
esame[i].durata=4;
}
for(int i=0; i<n_esame; i=i+4)
{
esame[i].piazzato=false;
esame[i].durata=3;
}
for(int i=0; i<n_esame-5; i=i+5)
{
esame[i].prof = esame[i+2].prof = esame[i+5].prof;
}
esame[0].n_gruppo=2;
esame[0].id_gruppo[1]=esame[8].id;
esame[8].n_gruppo=2;
esame[8].id_gruppo[1]=esame[0].id;
}
/*void Inserisci_esame(exam* esame, date m[][n_slot][n_aula], int cont_esami, int cont_gruppo, int giorno, int slot, int aula){
esame[esame[cont_esami].id_gruppo[cont_gruppo]-1].piazzato=true;
for(int j=0; j<esame[esame[cont_esami].id_gruppo[cont_gruppo]-1].durata; j++)
{
m[giorno][slot+j][aula].id_esame = esame[esame[cont_esami].id_gruppo[cont_gruppo]-1].id;
m[giorno][slot+j][aula].durata_esame = esame[esame[cont_esami].id_gruppo[cont_gruppo]-1].durata;
m[giorno][slot+j][aula].prof_esame = esame[esame[cont_esami].id_gruppo[cont_gruppo]-1].prof;
}
}*/
void Inserisci_esame_no_aule(exam* esame, date cell[][n_slot], int cont_esami, int cont_gruppo, int giorno, int slot){
esame[esame[cont_esami].id_gruppo[cont_gruppo]-1].piazzato=true;
for(int j=0; j<esame[esame[cont_esami].id_gruppo[cont_gruppo]-1].durata; j++)
{
cell[giorno][slot+j].id_esame = esame[esame[cont_esami].id_gruppo[cont_gruppo]-1].id;
cell[giorno][slot+j].durata_esame = esame[esame[cont_esami].id_gruppo[cont_gruppo]-1].durata;
cell[giorno][slot+j].prof_esame = esame[esame[cont_esami].id_gruppo[cont_gruppo]-1].prof;
}
}
int main()
{
int giorno=0, slot=0/*, aula=0*/;
// date m[n_giorno][n_slot][n_aula];
date cell[n_giorno][n_slot];
exam esame[n_esame];
bool mettibile = true;
// bool prof_libero = true;
// inizializzazioni
// Inizializza_date(m);
Inizializza_date_no_aule(cell);
Inizializza_exam_default(esame);
Personalizza_exam(esame);
// Stampa dell'elenco degli esami
print_esami(esame);
// Procedura di inserimento degli esami nel calendario
/*for (int cont_esami=0; cont_esami<n_esame; cont_esami++)
{
for (int cont_gruppo=0; cont_gruppo<esame[cont_esami].n_gruppo; cont_gruppo++)
{
esame[cont_esami].gruppo_piazzato = true;
for (int cont_gruppo_interno=0; cont_gruppo_interno<esame[cont_esami].n_gruppo; cont_gruppo_interno++)
{
if (!esame[esame[cont_esami].id_gruppo[cont_gruppo_interno]-1].piazzato)
{
esame[cont_esami].gruppo_piazzato = false;
}
}
while((giorno<n_giorno) && !esame[esame[cont_esami].id_gruppo[cont_gruppo]-1].piazzato)
{
while(((slot + esame[esame[cont_esami].id_gruppo[cont_gruppo]-1].durata - 1)<n_slot) &&
!esame[esame[cont_esami].id_gruppo[cont_gruppo]-1].piazzato)
{
while ((aula<n_aula) && !esame[esame[cont_esami].id_gruppo[cont_gruppo]-1].piazzato)
{
Mettibile(esame, m, cont_esami, cont_gruppo, giorno, slot, aula, &mettibile);
Prof_libero(esame, m, cont_esami, cont_gruppo, giorno, slot, aula, &prof_libero);
if(mettibile && prof_libero)
{
Inserisci_esame(esame, m, cont_esami, cont_gruppo, giorno, slot, aula);
}
else
{
aula++;
mettibile = true;
}
}
aula=0;
slot++;
prof_libero = true;
}
slot=0;
giorno++;
}
giorno=0;
}
}*/
for (int cont_esami=0; cont_esami<n_esame; cont_esami++)
{
for (int cont_gruppo=0; cont_gruppo<esame[cont_esami].n_gruppo; cont_gruppo++)
{
esame[cont_esami].gruppo_piazzato = true;
for (int cont_gruppo_interno=0; cont_gruppo_interno<esame[cont_esami].n_gruppo; cont_gruppo_interno++)
{
if (!esame[esame[cont_esami].id_gruppo[cont_gruppo_interno]-1].piazzato)
{
esame[cont_esami].gruppo_piazzato = false;
}
}
while((giorno<n_giorno) && !esame[esame[cont_esami].id_gruppo[cont_gruppo]-1].piazzato)
{
while(((slot + esame[esame[cont_esami].id_gruppo[cont_gruppo]-1].durata - 1)<n_slot) &&
!esame[esame[cont_esami].id_gruppo[cont_gruppo]-1].piazzato)
{
Mettibile_no_aule(esame, cell, cont_esami, cont_gruppo, giorno, slot, &mettibile);
if(mettibile)
{
Inserisci_esame_no_aule(esame, cell, cont_esami, cont_gruppo, giorno, slot);
}
else
{
mettibile = true;
slot++;
}
}
slot=0;
giorno++;
}
giorno=0;
}
}
cout<<"\t----------------------------------------------------------------------"<<endl<<endl<<endl;
// Stampa del calendario compilato e dell'elenco degli esami per sapere quali sono rimasti eventualmente non messi
// print_calendario(m);
print_calendario_no_aule(cell);
print_esami(esame);
}
| true |
faca26575db4d96d820c5e7cd77e95aef03a14ca
|
C++
|
CGQZtoast/c_plus
|
/test/作业训练三/16成绩大排队.cpp
|
UTF-8
| 582 | 3.703125 | 4 |
[] |
no_license
|
#include <iostream>
#include <algorithm>
using namespace std;
struct student
{
string name;
string id;
int grade;
};
bool cmp(student a, student b)
{
return a.grade > b.grade;
}
int main()
{
int n;
cin >> n;
student students[n];
for (int i = 0; i < n; i++)
{
cin >> students[i].name >> students[i].id >> students[i].grade;
}
sort(students, students + n, cmp);
cout << students[0].name << ' ' << students[0].id << endl;
cout << students[n - 1].name << ' ' << students[n - 1].id << endl;
}
| true |
d03e4ae55035b6d05f2a6d9d12e5f0c0dec6a5fc
|
C++
|
mlavik1/HikariOnline
|
/Source/Core/Object/object.cpp
|
UTF-8
| 961 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
#include "object.h"
#include <sstream>
#include "function.h"
IMPLEMENT_CLASS(Hikari::Object)
#define ADD_OBJECT_FLAG(flag) mObjectFlags |= (ObjectFlagRegister)(flag)
#define REMOVE_OBJECT_FLAG(flag) mObjectFlags &= ~(ObjectFlagRegister)(flag)
namespace Hikari
{
Object::Object()
{
mObjectRefHandle = new ObjectRefHandle(this);
std::stringstream ss;
ss << GetClass()->GetName() << GetClass()->mCreatedInstanceCount;
mObjectName = ss.str();
GetClass()->mCreatedInstanceCount++;
}
Object::~Object()
{
mObjectRefHandle->SetObject(nullptr);
}
void Object::CallFunction(Function* arg_function, FunctionArgContainer args)
{
(this->*(arg_function->mFunctionPointer))(args);
}
void Object::Destroy()
{
ADD_OBJECT_FLAG(ObjectFlag::PendingDestroy);
}
void Object::InitialiseObject(ObjectInitialiserParams arg_params)
{
}
std::string Object::GetMemoryHash() const
{
std::stringstream ss;
ss << this;
return ss.str();
}
}
| true |
2bf7c6e213a666ae6447b2b5b93524ecc62a829c
|
C++
|
fanzcsoft/windows_embedded_compact_2013_2015M09
|
/windows_embedded_compact_2013_2015M09/WINCE800/private/test/BaseOS/Filesys/reg/PerfTests/perf_regEx/reghlpr.cpp
|
UTF-8
| 9,406 | 2.53125 | 3 |
[] |
no_license
|
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// Use of this source code is subject to the terms of the Microsoft shared
// source or premium shared source license agreement under which you licensed
// this source code. If you did not accept the terms of the license agreement,
// you are not authorized to use this source code. For the terms of the license,
// please see the license agreement between you and Microsoft or, if applicable,
// see the SOURCE.RTF on your install media or the root of your tools installation.
// THE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES OR INDEMNITIES.
//
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <tchar.h>
#include "reghlpr.h"
///////////////////////////////////////////////////////////////////////////////
//
// Function : Hlp_GenStringData
//
// Description : Generates string data.
//
// Params:
// dwFlags PERF_FLAG_READABLE
// PERF_FLAG_RANDOM (default)
// PERF_FLAG_ALPHA
// PERF_FLAG_ALPHA_NUM
//
// cChars is the count of characters that the buffer
// can hold, including the NULL character.
//
///////////////////////////////////////////////////////////////////////////////
LPTSTR Hlp_GenStringData(__out_ecount(cChars) LPTSTR pszString, DWORD cChars, DWORD dwFlags)
{
UINT i=0;
BYTE bData=0;
BOOL fDone=FALSE;
ASSERT(pszString);
ASSERT(cChars);
if (!cChars)
return NULL;
// Generate cChars-1 characters (leaving space for the terminating NULL)
for (i=0; i<cChars-1; i++)
{
fDone = FALSE;
while(!fDone)
{
bData=(BYTE)Random();
if (bData<0) bData *= (BYTE)-1;
bData = bData % 0xFF; // generate random chars between 0 and 255
switch (dwFlags)
{
case PERF_FLAG_READABLE :
if ((bData >= 32) && (bData <= 126))
fDone=TRUE;
break;
case PERF_FLAG_ALPHA_NUM :
if ((bData >= '0') && (bData <= '9')
|| (bData >= 'a') && (bData <= 'z')
|| (bData >= 'A') && (bData <= 'Z'))
fDone=TRUE;
break;
case PERF_FLAG_ALPHA :
if ((bData >= 'a') && (bData <= 'z')
|| (bData >= 'A') && (bData <= 'Z'))
fDone=TRUE;
break;
case PERF_FLAG_NUMERIC :
if ((bData >= '0') && (bData <= '9'))
fDone=TRUE;
break;
default :
TRACE(_T("Should never reach here. Unknown Flags\n"));
ASSERT(FALSE);
GENERIC_FAIL(L_GenStringData);
}
}
pszString[i] = (TCHAR) bData;
}// for
// NULL terminate
pszString[i] = _T('\0');
return pszString;
ErrorReturn :
return NULL;
}
///////////////////////////////////////////////////////////////////////////////
//
// Function : Hlp_GenStringData
//
// Description : Generate random registry data to fill in there.
//
// Params:
//
// pdwType : Specify the type of data you want generated.
// If type is not specified, then a random type is selected.
// pbData : Buffer to contain the data. pbData cannot be NULL.
// cbData : Buffer size that controls the amount of data to generate.
//
// The function by default will resize the buffer if needed.
// If dwtype is not specified, then a randomly selected type will dictate
// the size of the data generated.
//
// For example, if you pass in a 100 byte buffer and specify DWORD, then just 4 bytes
// of random data will be generated.
//
///////////////////////////////////////////////////////////////////////////////
BOOL Hlp_GenRandomValData(DWORD *pdwType, __out_ecount(*pcbData) PBYTE pbData, DWORD *pcbData)
{
BOOL fRetVal=FALSE;
DWORD dwChars=0;
DWORD i=0;
size_t szlen = 0;
ASSERT(pbData);
ASSERT(*pcbData);
if (!pbData)
{
TRACE(TEXT("ERROR : Null buffer specified to Hlp_GetValueData. %s %u \n"), _T(__FILE__), __LINE__);
goto ErrorReturn;
}
// If no type is specified, then choose a random type
if (0==*pdwType)
{
UINT uNumber = 0;
rand_s(&uNumber);
*pdwType = rg_RegTypes[uNumber % PERF_NUM_REG_TYPES]; // set a random data type
}
UINT uNumber = 0;
switch(*pdwType)
{
case REG_NONE :
case REG_BINARY :
case REG_LINK :
case REG_RESOURCE_LIST :
case REG_RESOURCE_REQUIREMENTS_LIST :
case REG_FULL_RESOURCE_DESCRIPTOR :
for (i=0; i<*pcbData; i++)
{
rand_s(&uNumber);
pbData[i]=(BYTE)uNumber;
}
break;
case REG_SZ :
dwChars = *pcbData/sizeof(TCHAR);
ASSERT(dwChars);
if(!Hlp_GenStringData((LPTSTR)pbData, dwChars, PERF_FLAG_ALPHA_NUM))
goto ErrorReturn;
break;
case REG_EXPAND_SZ :
StringCchLength(_T("%SystemRoot%"), STRSAFE_MAX_CCH, &szlen);
ASSERT(*pcbData >= (szlen+1) * sizeof(TCHAR) );
StringCchCopy((LPTSTR)pbData, (*pcbData)-1, _T("%SystemRoot%"));
*pcbData= (szlen+1)*sizeof(TCHAR);
break;
case REG_DWORD_BIG_ENDIAN :
case REG_DWORD :
ASSERT(*pcbData >= sizeof(DWORD));
if (*pcbData < sizeof(DWORD))
{
TRACE(TEXT("Insufficient mem passed to Hlp_GenValueData. Send %d bytes, required %d. %s %u\r\n"),
*pcbData, sizeof(DWORD), _T(__FILE__), __LINE__);
goto ErrorReturn;
}
rand_s(&uNumber);
*(DWORD*)pbData = uNumber;
*pcbData = sizeof(DWORD);
break;
// This generates 3 strings in 1.
case REG_MULTI_SZ :
dwChars = *pcbData/sizeof(TCHAR);
memset(pbData, 33, *pcbData);
ASSERT(dwChars > 6);
// First Generate a string
if(!Hlp_GenStringData((LPTSTR)pbData, dwChars, PERF_FLAG_ALPHA_NUM))
goto ErrorReturn;
// Now throw in some random terminating NULLs to make it a multi_sz
for (i=dwChars/3; i<dwChars; i+=dwChars/3)
{
ASSERT(i<dwChars);
*((LPTSTR)pbData+i) = _T('\0');
}
// and make sure the last 2 chars are also NULL terminators.
*((LPTSTR)pbData+dwChars-1)= _T('\0');
*((LPTSTR)pbData+dwChars-2)= _T('\0');
break;
default :
TRACE(TEXT("TestError : Unknown reg type sent to Hlp_GenValueData : %d. %s %u\n"), *pdwType, _T(__FILE__), __LINE__);
goto ErrorReturn;
}
fRetVal=TRUE;
ErrorReturn :
return fRetVal;
}
///////////////////////////////////////////////////////////////////////////////
//
// Function: Hlp_HKeyToTLA
//
///////////////////////////////////////////////////////////////////////////////
TCHAR* Hlp_HKeyToTLA(HKEY hKey, __out_ecount(cBuffer) TCHAR *pszBuffer, DWORD cBuffer)
{
if (NULL == pszBuffer)
goto ErrorReturn;
StringCchCopy(pszBuffer, cBuffer-1, _T(""));
switch((DWORD)hKey)
{
case HKEY_LOCAL_MACHINE :
StringCchCopy(pszBuffer, cBuffer-1, _T("HKLM"));
break;
case HKEY_USERS :
StringCchCopy(pszBuffer, cBuffer-1, _T("HKU"));
break;
case HKEY_CURRENT_USER :
StringCchCopy(pszBuffer, cBuffer-1, _T("HKCU"));
break;
case HKEY_CLASSES_ROOT :
StringCchCopy(pszBuffer, cBuffer-1, _T("HKCR"));
break;
default :
{
TRACE(_T("WARNING : WinCE does not support this HKey 0x%x\n"), hKey);
ASSERT(0);
}
}
ErrorReturn :
return pszBuffer;
}
///////////////////////////////////////////////////////////////////////////////
//
// Function: Hlp_FillBuffer
//
// Proposed Flags :
// HLP_FILL_RANDOM
// HLP_FILL_SEQUENTIAL
// HLP_FILL_DONT_CARE - fastest
//
///////////////////////////////////////////////////////////////////////////////
BOOL Hlp_FillBuffer(__out_ecount(cbBuffer) PBYTE pbBuffer, DWORD cbBuffer, DWORD dwFlags)
{
DWORD i=0;
switch (dwFlags)
{
case HLP_FILL_RANDOM :
for (i=0; i<cbBuffer; i++)
{
pbBuffer[i] = (BYTE)Random();
}
break;
case HLP_FILL_SEQUENTIAL :
for (i=0; i<cbBuffer; i++)
{
pbBuffer[i] = (BYTE)i;
}
break;
case HLP_FILL_DONT_CARE :
memset(pbBuffer, 33, cbBuffer);
break;
}
return TRUE;
}
| true |
9d0bb1be038c3fd3984db0769eec963037fb2baf
|
C++
|
AnantheshJShet/Cpp_Practise_Projects
|
/Balanced_Brackets/Balanced_Brackets/helper_functions.cpp
|
UTF-8
| 1,439 | 3.34375 | 3 |
[] |
no_license
|
#include "helper_functions.h"
#include "typedefs.h"
#include "macros.h"
bool isWithinBounds(const uint32 var, const uint32 min, const uint32 max){
bool retVal = TRUE;
if((var < min) || (var > max))
{
retVal = FALSE;
}
return retVal;
}
bool isOpeningBracket(const char ch){
bool retVal = FALSE;
if((ch == '(') || (ch == '{') || (ch == '['))
{
retVal = TRUE;
}
return retVal;
}
bool isClosingBracket(const char ch){
bool retVal = FALSE;
if((ch == ')') || (ch == '}') || (ch == ']'))
{
retVal = TRUE;
}
return retVal;
}
bool isBracket(const char ch){
bool retVal = FALSE;
if((TRUE == isOpeningBracket(ch)) || (TRUE == isClosingBracket(ch))){
retVal = TRUE;
}
return retVal;
}
bool seqContainsOnlyBrackets(const std::string seq){
bool retVal = TRUE;
for(uint32 iSeq=0; iSeq<seq.length(); ++iSeq){
char tChar = seq[iSeq];
if(FALSE == isBracket(tChar)){
retVal = FALSE;
break;
}
else{
/* Do nothing */
}
}
return retVal;
}
bool areBracketsBalanced(const char open, const char close){
bool retVal = FALSE;
if(('(' == open) && (')' == close)){
retVal = TRUE;
}
else if(('{' == open) && ('}' == close)){
retVal = TRUE;
}
else if(('[' == open) && (']' == close)){
retVal = TRUE;
}
else{
/* Do nothing */
}
return retVal;
}
| true |
296611f03fb90d26dccd561f717c2284e0d691e4
|
C++
|
michalsvagerka/competitive
|
/arch/rychlostne/rychlostne-vs-vyberko/3dpoly.cpp
|
UTF-8
| 3,378 | 2.703125 | 3 |
[] |
no_license
|
#include "../l/lib.h"
// #include "../l/mod.h"
int steps[] = {2,3,2,1,0,0};
class poly {
public:
typedef pair<int, pii> point;
point rotate(point &p, int r) {
if (r==0) {
return {-p.y.x, {p.x, p.y.y}};
} else if (r==1) {
return {-p.y.y, {p.y.x,p.x}};
} else if (r==2){
return {p.x, {-p.y.y, p.y.x}};
} else if (r==3) {
return {-p.x, p.y};
} else if (r==4) {
return {p.x, {-p.y.x, p.y.y}};
} else {
return {p.x, {p.y.x, -p.y.y}};
}
}
void normalize(vector<point>&E) {
int mx = 100000, my = 100000, mz = 100000;
for (point&e:E) {
mx = min(mx, e.x);
my = min(my, e.y.x);
mz = min(mz, e.y.y);
}
for (point&e: E) {
e.x -= mx;
e.y.x -= my;
e.y.y -= mz;
}
sort(E.begin(), E.end());
}
vector<point> rotate(const vector<point> &E, int r) {
vector<point> R;
for (point e: E) R.push_back({rotate(e, r)});
return R;
}
bool contained(vector<point> &a, const set<vector<point>> &R, int i) {
if (i==6) {
normalize(a);
return R.find(a) != R.end();
}
if (contained(a,R,i+1)) return true;
for (int j = 0; j < steps[i]; ++j) {
a=rotate(a,i);
if (contained(a,R,i+1)) return true;
}
return false;
}
void insert(const vector<point> &P, const point& np, set<vector<point>> &R) {
if (find(P.begin(),P.end(), np) == P.end()) {
vector<point> NP(P);
NP.push_back(np);
if (!contained(NP,R,0)) {
normalize(NP);
R.insert(NP);
// cerr << "New poly: " << NP.size() << ": ";
// for (point&p:NP) cerr << " (" << p.x << ',' << p.y.x << ',' << p.y.y << ") ";
// cerr << endl;
}
}
}
void generateNeighbors(const vector<point> &P, set<vector<point>> &R) {
for (point e:P) {
e.x++;
insert(P, e, R);
e.x -= 2;
insert(P, e, R);
e.x++;
e.y.x++;
insert(P, e, R);
e.y.x -= 2;
insert(P, e, R);
e.y.x++;
e.y.y++;
insert(P, e, R);
e.y.y -= 2;
insert(P, e, R);
e.y.y++;
}
}
vector<int> size(const vector<point> &p) {
int mx = 0, my = 0, mz = 0;
for (auto &e:p) {
mx = max(mx, e.x);
my = max(my, e.y.x);
mz = max(mz, e.y.y);
}
vector<int> R{mx+1,my+1,mz+1};
sort(R.begin(),R.end());
return R;
}
void solve(istream& cin, ostream& cout) {
int N; cin >> N;
vector<int> D(3); cin >> D;
sort(D.begin(),D.end());
vector<set<vector<point>>> R(N);
R[0].insert({{0,{0,0}}});
for (int i = 1; i < N; ++i) {
for (auto &points:R[i-1]) {
generateNeighbors(points, R[i]);
}
}
int ans = 0;
for (auto&poly: R[N-1]) {
auto s = size(poly);
ans += s[0] <= D[0] && s[1] <= D[1] && s[2] <= D[2];
}
cout << ans << endl;
}
};
| true |
351b6ba6d3bb4bca12b7cff50b8b3bbcdfef489e
|
C++
|
WhiZTiM/coliru
|
/Archive2/e8/8572fdda9eadf4/main.cpp
|
UTF-8
| 5,460 | 2.96875 | 3 |
[] |
no_license
|
#include <typeinfo>
#include <boost/type_traits.hpp>
#include <iostream>
////// STUBS
struct move_only { // apparently boost::noncopyable prohibits move too
move_only(move_only const&) = delete;
move_only(move_only&&) = default;
move_only() = default;
};
namespace Model { namespace ClientModel {
struct cClientVerticesObject : move_only {};
struct cRawClientObject : move_only {};
struct cFunkyClientObject : move_only {};
} }
namespace Controller {
namespace QtOpenGL {
struct cQOpenGLContext : move_only {};
}
struct cConsoleContext : move_only {};
struct cDevNullContext : move_only {};
}
namespace traits
{
template <typename T> struct supports_console_ctx : boost::mpl::false_ {};
template <>
struct supports_console_ctx<Model::ClientModel::cFunkyClientObject> : boost::mpl::true_ {};
}
////// END STUBS
/////////////////////////////////////////////////////////////////////
// Why not **just** make it a polymorphic functor?
//
// You can make it use an extension point if you're so inclined:
// (note the use of Enable to make it Sfinae-friendly)
namespace UserTypeHooks
{
template <typename ClientObject, typename Context, typename Enable = void>
struct RenderClientObjectsImpl
{
void static call(ClientObject const& clientObject, Context const& context)
{
// static_assert(false, "not implemented");
// throw?
std::cout << "NOT IMPLEMENTED:\t" << __PRETTY_FUNCTION__ << "\n";
}
};
template <typename ClientObject>
struct RenderClientObjectsImpl<ClientObject, Controller::QtOpenGL::cQOpenGLContext>
{
void static call(ClientObject const& clientObject, Controller::QtOpenGL::cQOpenGLContext const& context)
{
std::cout << "cQOpenGLContext:\t" << typeid(ClientObject).name() << "\n";
}
};
template <typename ClientObject>
struct RenderClientObjectsImpl<ClientObject, Controller::cDevNullContext>
{
void static call(ClientObject const& clientObject, Controller::cDevNullContext const& context)
{
std::cout << "devnull:\t\t" << typeid(ClientObject).name() << "\n";
}
};
}
struct RenderClientObjects
{
typedef void result_type;
template <typename ClientObject, typename Context>
void operator()(ClientObject const& clientObject, Context const& context) const
{
return UserTypeHooks::RenderClientObjectsImpl<ClientObject, Context>::call(clientObject, context);
}
};
/////////////////////////////////////////////////////////////////////
// Demonstrating the user-defined extension point mechanics:
namespace UserTypeHooks
{
template <typename ClientObject>
struct RenderClientObjectsImpl<ClientObject, Controller::cConsoleContext,
typename boost::enable_if<traits::supports_console_ctx<ClientObject> >::type>
{
void static call(
ClientObject const& clientObject,
Controller::cConsoleContext const& context)
{
std::cout << "This type has cConsoleContext support due to the supports_console_ctx trait! " << typeid(ClientObject).name() << "\n";
}
};
}
/////////////////////////////////////////////////////////////////////
// Added: Dynamic interface
//
// Making this a bit more complex than you probably need, but hey, assuming the
// worst:
#include <memory>
struct IPolymorphicRenderable
{
// you likely require only one of these, and it might not need to be
// virtual
virtual void render(Controller::QtOpenGL::cQOpenGLContext& ctx) = 0;
virtual void render(Controller::cConsoleContext& ctx) = 0;
virtual void render(Controller::cDevNullContext& ctx) = 0;
};
struct IClientObject : IPolymorphicRenderable
{
template <typename T> IClientObject(T&& val) : _erased(new erasure<T>(std::forward<T>(val))) { }
virtual void render(Controller::QtOpenGL::cQOpenGLContext& ctx) { return _erased->render(ctx); }
virtual void render(Controller::cConsoleContext& ctx) { return _erased->render(ctx); }
virtual void render(Controller::cDevNullContext& ctx) { return _erased->render(ctx); }
private:
template <typename T> struct erasure : IPolymorphicRenderable
{
erasure(T val) : _val(std::move(val)) { }
void render(Controller::QtOpenGL::cQOpenGLContext& ctx) { return RenderClientObjects()(_val, ctx); }
void render(Controller::cConsoleContext& ctx) { return RenderClientObjects()(_val, ctx); }
void render(Controller::cDevNullContext& ctx) { return RenderClientObjects()(_val, ctx); }
T _val;
};
std::unique_ptr<IPolymorphicRenderable> _erased;
};
int main()
{
Controller::QtOpenGL::cQOpenGLContext glContext;
Controller::cConsoleContext console;
Controller::cDevNullContext devnull;
std::cout << "// Fully virtual dispatch\n";
std::cout << "//\n";
IClientObject obj = Model::ClientModel::cClientVerticesObject();
obj.render(glContext);
obj.render(console);
obj.render(devnull);
//
obj = Model::ClientModel::cRawClientObject();
obj.render(glContext);
obj.render(console);
obj.render(devnull);
//
obj = Model::ClientModel::cFunkyClientObject();
obj.render(glContext);
obj.render(console);
obj.render(devnull);
}
| true |
4d71c78a4b92d1aa9bb4a52086b437e82ba1f16b
|
C++
|
alexfordc/zq
|
/FastTrader/Module-VerifyCode/VirtualKeyButton.cpp
|
UTF-8
| 2,336 | 2.578125 | 3 |
[] |
no_license
|
#include "stdafx.h"
#include "VirtualKeyButton.h"
const wxColor BACKGROUND_BOTTON_NORMAL = wxColor(214,214,214);
const wxColor FOREGROUND_BOTTON_NORMAL = wxColor(0,0,0);
const wxColor BACKGROUND_BOTTON_PRESS = wxColor(0,255,255);
const wxColor FOREGROUND_BOTTON_PRESS = wxColor(0,0,0);
const wxColor BACKGROUND_BOTTON_OVER = wxColor(255,255,0);
const wxColor FOREGROUND_BOTTON_OVER = wxColor(255,0,0);
VirtualKeyButton::VirtualKeyButton(wxWindow *parent, wxWindowID id, const wxString& text,const wxPoint& pos,
const wxSize& size, long style, const wxValidator& validator, const wxString& name)
{
Create(parent, id, text, pos, size, style, validator, name);
m_bLocked = false;
m_nButtonStyle = -1;
}
VirtualKeyButton::~VirtualKeyButton()
{
}
BEGIN_EVENT_TABLE(VirtualKeyButton,wxButton)
EVT_MOTION(VirtualKeyButton::OnMotion)
EVT_LEFT_DOWN(VirtualKeyButton::OnLeftDown)
EVT_LEFT_UP(VirtualKeyButton::OnLeftUp)
EVT_ENTER_WINDOW(VirtualKeyButton::OnEnterWindow)
EVT_LEAVE_WINDOW(VirtualKeyButton::OnLeaveWindow)
END_EVENT_TABLE()
void VirtualKeyButton::ChangeButtonBitmap( int state )
{
if (BUTTON_NORMAL == state)
{
Change2Normal();
}
else if (BUTTON_PRESS == state)
{
Change2Press();
}
else if (BUTTON_OVER == state)
{
Change2Over();
}
}
void VirtualKeyButton::OnMotion(wxMouseEvent& evt)
{
evt.Skip();
}
void VirtualKeyButton::OnLeftDown(wxMouseEvent& evt)
{
if (BUTTON_STYLE_LOCK == m_nButtonStyle)
{
m_bLocked = !m_bLocked;
}
Change2Press();
evt.Skip();
}
void VirtualKeyButton::OnLeftUp(wxMouseEvent& evt)
{
if (BUTTON_STYLE_LOCK == m_nButtonStyle && m_bLocked)
{
Change2Press();
}
else
{
Change2Normal();
}
evt.Skip();
}
void VirtualKeyButton::OnEnterWindow(wxMouseEvent& evt)
{
if (!m_bLocked)
{
Change2Over();
}
evt.Skip();
}
void VirtualKeyButton::OnLeaveWindow(wxMouseEvent& evt)
{
if (!m_bLocked)
{
Change2Normal();
}
evt.Skip();
}
void VirtualKeyButton::Change2Over()
{
SetBackgroundColour(BACKGROUND_BOTTON_OVER);
SetForegroundColour(FOREGROUND_BOTTON_OVER);
}
void VirtualKeyButton::Change2Normal()
{
SetBackgroundColour(BACKGROUND_BOTTON_NORMAL);
SetForegroundColour(FOREGROUND_BOTTON_NORMAL);
}
void VirtualKeyButton::Change2Press()
{
SetBackgroundColour(BACKGROUND_BOTTON_PRESS);
SetForegroundColour(FOREGROUND_BOTTON_PRESS);
}
| true |
2c774a72929e7146eaa5526910b8860a32bc8066
|
C++
|
EngineerZhang/PAT-Basic-Level
|
/small test/1018.cpp
|
UTF-8
| 1,297 | 3 | 3 |
[] |
no_license
|
#include<stdio.h>
#include<iostream>
using namespace std;
int main(){
int N;
scanf("%d", &N);
char x, y;
int win_1, win_2, loose_1, loose_2, draw_1, draw_2;
win_1 = win_2 = loose_1 = loose_2 = draw_1 = draw_2 = 0;
int numB_1, numC_1, numJ_1, numB_2, numC_2, numJ_2;
numB_1 = numC_1 = numJ_1 = numB_2 = numC_2 = numJ_2 = 0;
while (N--){
getchar();
scanf("%c %c", &x, &y);
//cin >> x >> y;
if ((x == 'B' && y == 'C') || (x == 'C' && y == 'J') || (x == 'J' && y == 'B')){
win_1++;
loose_2++;
if (x == 'B')
numB_1++;
else if (x == 'C')
numC_1++;
else
numJ_1++;
}
else if ((y == 'B' && x == 'C') || (y == 'C' && x == 'J') || (y == 'J' && x == 'B')){
win_2++;
loose_1++;
if (y == 'B')
numB_2++;
else if (y == 'C')
numC_2++;
else
numJ_2++;
}
else{
draw_1++;
draw_2++;
}
}
printf("%d %d %d\n", win_1, draw_1, loose_1);
printf("%d %d %d\n", win_2, draw_2, loose_2);
if (numB_1 >= numC_1){
if (numB_1 >= numJ_1)
printf("B ");
else
printf("J ");
}
else{
if (numC_1 >= numJ_1)
printf("C ");
else
printf("J ");
}
if (numB_2 >= numC_2){
if (numB_2 >= numJ_2)
printf("B");
else
printf("J");
}
else{
if (numC_2 >= numJ_2)
printf("C");
else
printf("J");
}
return 0;
}
| true |
b8aff97bfd6135d767bdb6735114f7a2c7d5471a
|
C++
|
speps/attractouch
|
/sources/gameplay/receiver.cpp
|
UTF-8
| 2,838 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
#include "gameplay/receiver.h"
namespace AT {
bool Receiver::loaded = false;
sf::Image Receiver::image;
sf::Sprite Receiver::sprite;
Receiver::Receiver(const sf::Vector2f Position, int MaximumParticles, float Radius)
:sf::Drawable(Position, sf::Vector2f(1, 1), 0.0f), maximumParticles(Helper::Max(1, MaximumParticles)), receivedParticles(0), radius(Radius)
{
colorStart = sf::Color(151, 151, 151);
colorEnd = sf::Color(255, 255, 0);
alpha = 0.0f;
if(!loaded) {
if(!image.LoadFromFile("content/sprites/receiver.png"))
throw std::exception("Can't load receiver sprite");
sprite.SetImage(image);
sprite.SetBlendMode(sf::Blend::Add);
sprite.SetCenter(image.GetWidth() / 2.0f, image.GetHeight() / 2.0f);
sprite.SetColor(sf::Color(255, 255, 0));
loaded = true;
}
}
Receiver::~Receiver()
{
}
void Receiver::Update(float TimeStep, ParticleSystem& particleSystem)
{
for(Particles::iterator it = particleSystem.GetParticles().begin(); it != particleSystem.GetParticles().end();) {
GameplayParticle& particle = *static_cast<GameplayParticle*>(*it);
bool removed = false;
if(particle.IsReceived()) {
sf::Vector2f delta = GetPosition() - particle.GetPosition();
float distance = Helper::Distance(GetPosition(), particle.GetPosition());
/*if(particle.IsDead()) {
removed = true;
it = particleSystem.GetParticles().erase(it);
}*/
float stiffness = 0.01f;
particle.ApplyImpulse(delta * stiffness);
particle.ApplyImpulse(sf::Vector2f(sf::Randomizer::Random(-1.0f, +1.0f), sf::Randomizer::Random(-1.0f, +1.0f)) * distance * 0.01f);
} else {
float distance = Helper::Distance(GetPosition(), particle.GetPosition());
if(distance < radius) {
particle.SetReceived(true);
++receivedParticles;
OSCMessenger::Instance().ParticleReceived();
float particleRatio = Helper::Clamp(receivedParticles / (float)maximumParticles, 0.0f, 1.0f);
std::cout << "received:" << receivedParticles << " max:" << maximumParticles << " ratio:" << particleRatio << std::endl;
}
}
if(!removed)
++it;
}
}
void Receiver::Render(sf::RenderTarget& Target) const
{
float particleRatio = Helper::Clamp((float)receivedParticles / maximumParticles, 0.0f, 1.0f);
sprite.SetColor(Helper::Blend(colorStart, colorEnd, particleRatio));
Target.Draw(sprite);
}
}
| true |
aecad3174baa8f451c2e1c7fd7c211ff79dd6b00
|
C++
|
night0205/zorejudge
|
/a022.cpp
|
UTF-8
| 296 | 2.890625 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
main(){
string input;
string s;
while(cin >> s){
int flag = 0;
int l = s.length();
for(int i = 0; i < l/2; i++){
if(s[i] != s[l-1-i]){
flag++;
break;
}
}
if(flag)
cout << "no";
else
cout << "yes";
cout << '\n';
}
}
| true |
576c8b08581c860e8d52089c10bbf9f4d3378e8d
|
C++
|
kabuki0111/ProjectEuler1
|
/Problem2/ProjectEuler.cpp
|
UTF-8
| 16,158 | 3.109375 | 3 |
[] |
no_license
|
//
// ProjectEuler.cpp
// Problem1
//
// Created by T.S on 2014/04/04.
// Copyright (c) 2014年 T.S. All rights reserved.
//
#include "ProjectEuler.h"
inline int_64 square(int_64 targetNum){return targetNum * targetNum;}
//Problem1の結果を算出する関数
int_64 ProjectEuler::p1(int_64 maxNaturalNumber){
int_64 sumNaturalNumber = 0;
for (int_64 i=1; i<maxNaturalNumber; i++) {
if(i%3 == 0 || i%5 == 0){
sumNaturalNumber += i;
}
}
return sumNaturalNumber;
}
//Problem2のフィボナッチ数列
int_64 ProjectEuler::p2(int_64 maxLoop){
std::vector<int_64> fibonacciNumList;
int_64 sumFibonaci = 1;
int_64 prevOne = 1;
int_64 prevTwo = 1;
int_64 maxLimitFibonaci = 4000000;
for (int_64 i_naturalNum=0; i_naturalNum<maxLoop; i_naturalNum++) {
if(i_naturalNum <= 1){
fibonacciNumList.push_back(1);
}else{
sumFibonaci = prevOne + prevTwo;
prevTwo = prevOne;
prevOne = sumFibonaci;
if(sumFibonaci < maxLimitFibonaci){
fibonacciNumList.push_back(sumFibonaci);
}else{
break;
}
}
}
int_64 sumEventFobonaci = 0;
for(int_64 j_fibonaci = 0; j_fibonaci < fibonacciNumList.size(); j_fibonaci++ ){
if(fibonacciNumList[j_fibonaci] % 2 == 0){
sumEventFobonaci += fibonacciNumList[j_fibonaci];
}
}
printf("sum even fibonaci %lld\n", sumEventFobonaci);
return sumEventFobonaci;
}
//Problem3の結果を算出する関数
int_64 ProjectEuler::p3(int_64 maxNumber){
int_64 primeNum = 2;
int_64 divisionNum = maxNumber;
bool isPrimeNum;
while (divisionNum > 1){
if(divisionNum % primeNum == 0){
divisionNum = divisionNum / primeNum;
printf("primeNum = %lld divisionNum = %lld\n", primeNum, divisionNum);
}else{
for (long i=0; i<=divisionNum; i++) {
isPrimeNum = true;
for (long j=2; j<i; j++) {
if(i % j == 0){
isPrimeNum = false;
}
}
if (isPrimeNum && primeNum < i) {
primeNum = i;
break;
}
}
}
}
return primeNum;
}
//Problem4の結果を算出する関数
int_64 ProjectEuler::p4(){
std::vector<int_64> sumList;
for(int_64 i_left=100; i_left<=999; i_left++) {
for(int_64 j_right=999; j_right>=100; j_right--){
int_64 sum = i_left * j_right;
std::string ansNumberStr = std::to_string(sum);
int_64 fullNumberSize = static_cast<int_64>(ansNumberStr.size());
int_64 count = 0;
if(fullNumberSize%2 != 0){
count = 1;
}
int_64 halfNumbeSize = (fullNumberSize - count) / 2;
bool isHoge = true;
for(int_64 k_right=0; k_right<halfNumbeSize+count; k_right++){
int_64 k_left = (fullNumberSize-1) - k_right;
if(ansNumberStr[k_right] != ansNumberStr[k_left]){
isHoge = false;
}
}
if(isHoge){
printf("okay!! sum = %lld i = %lld j =%lld \n", sum, i_left, j_right);
sumList.push_back(sum);
}
}
}
int_64 maxNumber = 0;
for(int_64 i_list=0; i_list<(int_64)sumList.size(); i_list++){
if(sumList[i_list] > maxNumber){
maxNumber = sumList[i_list];
}
}
printf("get!! %lld\n", maxNumber);
return maxNumber;
}
//Problem5の結果を算出する関数
int_64 ProjectEuler::p5(int_64 maxDenomNum){
bool isStopWhile = false;
int_64 ansNaturalNumber = maxDenomNum;
while(!isStopWhile){
printf("%lld \n", ansNaturalNumber);
ansNaturalNumber += maxDenomNum;
isStopWhile = p5MiniMultiple(ansNaturalNumber, maxDenomNum);
}
return ansNaturalNumber;
}
//Problem6の結果を算出する関数
int_64 ProjectEuler::p6(int_64 targetNum){
int_64 sumAllNumber = p6SumNumberAll(targetNum);
int_64 ansProblemNumber = square(sumAllNumber) - p6SumSquare(targetNum);
return ansProblemNumber;
}
//Problem7の結果を算出する関数
int_64 ProjectEuler::p7(int_64 targetPrimeOrdinalNum){
int_64 ansPrimeNaturalNum = 0;
int_64 countPrimeOrdinalNum = 1;
for(int_64 i_natuNum = 1; countPrimeOrdinalNum<=targetPrimeOrdinalNum; i_natuNum++){
bool isPrimeFlag = false;
isPrimeFlag = p7PrimeCheck(i_natuNum);
if(isPrimeFlag){
printf("count = %lld, number = %lld\n", countPrimeOrdinalNum, i_natuNum);
ansPrimeNaturalNum = i_natuNum;
countPrimeOrdinalNum++;
}
}
return ansPrimeNaturalNum;
}
//Problem8の結果を出力する関数
int_64 ProjectEuler::p8(){
const std::string problemNumberStr(
"73167176531330624919225119674426574742355349194934"
"96983520312774506326239578318016984801869478851843"
"85861560789112949495459501737958331952853208805511"
"12540698747158523863050715693290963295227443043557"
"66896648950445244523161731856403098711121722383113"
"62229893423380308135336276614282806444486645238749"
"30358907296290491560440772390713810515859307960866"
"70172427121883998797908792274921901699720888093776"
"65727333001053367881220235421809751254540594752243"
"52584907711670556013604839586446706324415722155397"
"53697817977846174064955149290862569321978468622482"
"83972241375657056057490261407972968652414535100474"
"82166370484403199890008895243450658541227588666881"
"16427171479924442928230863465674813919123162824586"
"17866458359124566529476545682848912883142607690042"
"24219022671055626321111109370544217506941658960408"
"07198403850962455444362981230987879927244284909188"
"84580156166097919133875499200524063689912560717606"
"05886116467109405077541002256983155200055935729725"
"71636269561882670428252483600823257530420752963450");
int_64 ansGreatestTotalNum = 0;
int_64 castProblemSize = static_cast<int_64>(problemNumberStr.size());
for(int_64 i_numStr=0; i_numStr<castProblemSize; i_numStr+=4){
char memoNumChar[8];
int_64 memoNumInt[8];
for(int_64 j_memo=0; j_memo<8; j_memo++){
memoNumChar[j_memo] = problemNumberStr[i_numStr + j_memo];
memoNumInt[j_memo] = p8IntConvFromChar(memoNumChar[j_memo]);
printf("%lld ", memoNumInt[j_memo]);
}
printf("\n");
int_64 commonTotalNum = 0;
int_64 totalNum[4];
commonTotalNum = memoNumInt[3] * memoNumInt[4];
totalNum[0] = commonTotalNum * memoNumInt[0] * memoNumInt[1] * memoNumInt[2];
totalNum[1] = commonTotalNum * memoNumInt[1] * memoNumInt[2] * memoNumInt[5];
totalNum[2] = commonTotalNum * memoNumInt[2] * memoNumInt[5] * memoNumInt[6];
totalNum[3] = commonTotalNum * memoNumInt[5] * memoNumInt[6] * memoNumInt[7];
printf("common = %lld\na = %lld\nb = %lld\nc = %lld\nd = %lld\n", commonTotalNum, totalNum[0], totalNum[1], totalNum[2], totalNum[3]);
int_64 maxTotalNum = p8GetMaxNum(totalNum);
if(ansGreatestTotalNum < maxTotalNum){
ansGreatestTotalNum = maxTotalNum;
}
printf("top total num = %lld\n\n", ansGreatestTotalNum);
}
return ansGreatestTotalNum;
}
//Problem9を回答する関数
int_64 ProjectEuler::p9(int_64 findSumPythagoNum){
int_64 vertexA = 0;
int_64 vertexB = 0;
int_64 vertexC = 0;
for(int_64 i_naturalNum=1; i_naturalNum<findSumPythagoNum; i_naturalNum++){
for(int_64 j_naturalNum=1; j_naturalNum<i_naturalNum; j_naturalNum++){
int_64 oddNaturalNum = i_naturalNum - j_naturalNum;
if(oddNaturalNum%2 != 0){
vertexA = square(i_naturalNum) - square(j_naturalNum);
vertexB = 2 * i_naturalNum * j_naturalNum;
vertexC = square(i_naturalNum) + square(j_naturalNum);
int_64 sumPythagoreanAll = vertexA + vertexB + vertexC;
if(sumPythagoreanAll == findSumPythagoNum){
return vertexA * vertexB * vertexC;
}
}
}
}
return 0;
}
//Problem10を回答する関数
int_64 ProjectEuler::p10(int_64 maxNaturalNum){
std::vector<int_64> primeVector;
for(int_64 i_naturalNum=2; i_naturalNum<=maxNaturalNum; i_naturalNum++){
bool isPrime = p7PrimeCheck(i_naturalNum);
if(isPrime){
printf("%lld\n", i_naturalNum);
primeVector.push_back(i_naturalNum);
}
}
int_64 ansSumPrimeNumber = 0;
for(int_64 k_primeVector=0; k_primeVector<primeVector.size(); k_primeVector++){
ansSumPrimeNumber += primeVector[k_primeVector];
}
printf("%lld\n", ansSumPrimeNumber);
return ansSumPrimeNumber;
}
//Problem11を回答するメソッド
int_64 ProjectEuler::p11(){
int_64 problemNumInt[20][20] ={
{8 , 2 , 22, 97, 38, 15, 0 , 40, 0 , 75, 4 , 5 , 7, 78, 52, 12, 50, 77, 91, 8 },
{49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4 , 56, 62, 0 },
{81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65},
{52, 70, 95, 23, 4 , 60, 11, 42, 69, 24, 68, 56, 1 , 32, 56, 71, 37, 2 , 36, 91},
{22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80},
{24, 47, 32, 60, 99, 3 , 45, 2 , 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50},
{32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70},
{67, 26, 20, 68, 2 , 62, 12, 20, 95, 63, 94, 39, 63, 8 , 40, 91, 66, 49, 94, 21},
{24, 55, 58, 5 , 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72},
{21, 36, 23, 9 , 75, 0 , 76, 44, 20, 45, 35, 14, 0 , 61, 33, 97, 34, 31, 33, 95},
{78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 3 , 80, 4 , 62, 16, 14, 9 , 53, 56, 92},
{16, 39, 5 , 42, 96, 35, 31, 47, 55, 58, 88, 24, 0 , 17, 54, 24, 36, 29, 85, 57},
{86, 56, 0 , 48, 35, 71, 89, 7 , 5 , 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58},
{19, 80, 81, 68, 5 , 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 4 , 89, 55, 40},
{4 , 52, 8 , 83, 97, 35, 99, 16, 7 , 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66},
{88, 36, 68, 87, 57, 62, 20, 72, 3 , 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69},
{4 , 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 8 , 46, 29, 32, 40, 62, 76, 36},
{20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 4 , 36, 16},
{20, 73, 35, 29, 78, 31, 90, 1 , 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 5 , 54},
{1 , 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1 , 89, 19, 67, 48}};
int_64 maxSumDiagonalNum = 0;
int_64 totalRightDiag = 0;
int_64 totalLeftDiag = 0;
for(int_64 i_width=0; i_width<17; i_width++){
for(int_64 j_height=0; j_height<17; j_height++){
totalRightDiag =
problemNumInt[i_width][j_height] * problemNumInt[i_width+1][j_height+1] * problemNumInt[i_width+2][j_height+2] * problemNumInt[i_width+3][j_height+3];
totalLeftDiag =
problemNumInt[i_width+3][j_height] * problemNumInt[i_width+2][j_height+1] * problemNumInt[i_width+1][j_height+2] * problemNumInt[i_width][j_height+3];
if(totalRightDiag < totalLeftDiag){
if(totalLeftDiag > maxSumDiagonalNum){
maxSumDiagonalNum = totalLeftDiag;
}
}else{
if(totalRightDiag > maxSumDiagonalNum){
maxSumDiagonalNum = totalRightDiag;
}
}
}
}
return maxSumDiagonalNum;
}
//ProjectEulerのProblem12のメソッド
int_64 ProjectEuler::p12(){
std::vector<int_64> ansVector;
int_64 primeNumber = 1;
int_64 test = 500;
while(static_cast<int_64>(ansVector.size()) < test){
int_64 ansPrime = p6SumNumberAll(primeNumber);
for(int_64 i_prime=ansPrime; i_prime>0; i_prime--){
int_64 ansNum = ansPrime % i_prime;
if(ansNum == 0){
printf("%lld\n", i_prime);
ansVector.push_back(i_prime);
}
if(static_cast<int_64>(ansVector.size()) == test){
printf("ans okay!!\n");
return ansPrime;
}
}
if(static_cast<int_64>(ansVector.size()) != test){
ansVector.clear();
}
printf("\n");
primeNumber++;
}
return 0;
}
/*ProjectEulerの処理をサポートする関数*/
//Problem2の試作関数
int_64 ProjectEuler::fibonaci(int_64 targetFibonaciCount){
int ansFibonaci = 0;
switch (targetFibonaciCount){
case 0:
case 1:
return 1;
break;
default:
ansFibonaci += fibonaci(targetFibonaciCount - 1) + fibonaci(targetFibonaciCount - 2);
break;
}
return ansFibonaci;
}
//Problem5に関連する関数
bool ProjectEuler::p5MiniMultiple(int_64 targetNumerator, int_64 maxDenomNum){
bool isAnsFlag = true;
for(int_64 i_Denominator=maxDenomNum; i_Denominator>0; i_Denominator--){
if( targetNumerator%i_Denominator != 0){
isAnsFlag = false;
break;
}
}
return isAnsFlag;
}
//Project 6 二乗の和
int_64 ProjectEuler::p6SumSquare(int_64 targetNum){
if(targetNum != 0){
return square(targetNum) + p6SumSquare(targetNum - 1);
}
return 0;
}
//Project 6 指定した値の合計値
int_64 ProjectEuler::p6SumNumberAll(int_64 targetNum){
if(targetNum != 0){
return targetNum + p6SumNumberAll(targetNum - 1);
}
return 0;
}
//指定した値が素数かどうかを判定する関数
bool ProjectEuler::p7PrimeCheck(int_64 targetNaturalNum){
if(targetNaturalNum < 2){
return false;
}else if(targetNaturalNum == 2){
return true;
}if(targetNaturalNum % 2 == 0){
return false;
}
for(int_64 i_denom=3; i_denom<=targetNaturalNum/i_denom; i_denom+=2){
if(targetNaturalNum % i_denom == 0){
return false;
}
}
return true;
}
//char型の数字からint型の数字に変換する処理
int_64 ProjectEuler::p8IntConvFromChar(const char& numChar){
int_64 ansNumInt = 0;
switch(numChar){
case '0':
ansNumInt = 0;
break;
case '1':
ansNumInt = 1;
break;
case '2':
ansNumInt = 2;
break;
case '3':
ansNumInt = 3;
break;
case '4':
ansNumInt = 4;
break;
case '5':
ansNumInt = 5;
break;
case '6':
ansNumInt = 6;
break;
case '7':
ansNumInt = 7;
break;
case '8':
ansNumInt = 8;
break;
case '9':
ansNumInt = 9;
break;
}
return ansNumInt;
}
//配列に格納されている最大値を取得する関数
int_64 ProjectEuler::p8GetMaxNum(int_64* arrayInt){
int_64 maxTotalNum = 0;
for(int_64 i_array = 0; i_array<4; i_array++){
if(maxTotalNum < arrayInt[i_array]){
maxTotalNum = arrayInt[i_array];
}
}
return maxTotalNum;
}
| true |
d7ef3540b92835ff109070e54bb7fc62c78cf4a7
|
C++
|
dave12311/RoomGen
|
/Header.h
|
UTF-8
| 1,508 | 2.625 | 3 |
[] |
no_license
|
#ifndef HEADER_H
#define HEADER_H
#include <string>
#include <vector>
using namespace std;
#define Precision 1000
#define Iterations 5000000
void clr();
float rnd(float min, float max);
class Data {
public:
string Name;
float A[7];
Data();
};
class Database {
public:
vector<Data> BaseFloors;
vector<Data> BaseWalls;
vector<Data> BaseCeilings;
vector<Data> FixedFloors;
vector<Data> FixedWalls;
vector<Data> FixedCeilings;
vector<Data> AcousticFloors;
vector<Data> AcousticWalls;
vector<Data> AcousticCeilings;
Database();
private:
void readData();
};
class Room {
struct surface {
float S, SW, SF, SC;
};
public:
float H, W, D;
float V;
surface S;
surface availableS;
float T;
Room(Database*dbIn);
private:
struct Best {
vector<Data*> Floor, Wall, Ceiling;
vector<float> FloorSurf, WallSurf, CeilingSurf;
float Ts[7];
float Score = 1000;
};
float myT[7];
float myScore;
Database*myDB;
Data *myFloor, *myWall, *myCeiling;
vector<Data*> fixedFloor, fixedWall, fixedCeiling;
vector<float> fixedFloorS, fixedWallS, fixedCeilingS;
vector<Data*> myAcousticFloors, myAcousticWalls, myAcousticCeilings;
vector<float> myFloorSurfaces, myWallSurfaces, myCeilingSurfaces;
Best Bests[5];
void init();
void calculate();
void incorrectIn(int errReturn);
void baseMaterialLister();
void fixedMaterialLister();
void acousticMaterialLister();
void getT();
void generateSurfaces();
void solve();
void insertBest(int n);
void printResults();
};
#endif
| true |
17bc3869678a70fa0389a2fb834d5544744178e3
|
C++
|
nguyenanhductb23/SDL2-Project
|
/Project_SDL2/mouse_and_keyboard.cpp
|
UTF-8
| 8,407 | 2.65625 | 3 |
[] |
no_license
|
#include "Headers/mouse_and_keyboard.h"
using namespace std;
void RandomMove(const int& mode, Object& enemy, const Object* wall, const int& WALLS, int** pos) {
int step = SQ_SIZE[mode];
unsigned int dir = rand() % 4;
SDL_Rect rect = enemy.getRect();
pos[rect.x / SQ_SIZE[mode]][rect.y / SQ_SIZE[mode]] --;
const int LEFT = 0, RIGHT = 1, DOWN = 2, UP = 3;
switch (dir) {
case LEFT: rect.x = rect.x - step;
break;
case RIGHT: rect.x = rect.x + step;
break;
case DOWN: rect.y = rect.y + step;
break;
case UP: rect.y = rect.y - step;
break;
}
//if (CanMove(rect, wall, WALLS)) {
if (CanMove(mode, rect, pos)) {
enemy.setRect(rect);
}
pos[enemy.getRect().x / SQ_SIZE[mode]][enemy.getRect().y / SQ_SIZE[mode]] ++;
}
void KeyboardMove(const int& mode, SDL_Event &e, Object& Werner, Object* wall, int &WALLS, int** pos) {
SDL_Rect rect = Werner.getRect();
if (e.type == SDL_KEYDOWN) {
switch (e.key.keysym.sym) {
case SDLK_LEFT: rect.x = rect.x - SQ_SIZE[mode];
break;
case SDLK_RIGHT: rect.x = rect.x + SQ_SIZE[mode];
break;
case SDLK_DOWN: rect.y = rect.y + SQ_SIZE[mode];
break;
case SDLK_UP: rect.y = rect.y - SQ_SIZE[mode];
break;
default: break;
}
}
//if (CanMove(rect, wall, WALLS))
if (CanMove(mode, rect, pos)) {
Werner.setRect(rect);
}
}
void startMenu(Media* media) {
SDL_Event e;
SDL_Texture* menu_texture = media->start_menu_png;
SDL_RenderCopy(media->renderer, menu_texture, NULL, &BIG_RECT);
SDL_RenderPresent(media->renderer);
Mix_Chunk* ping = media->ping;
const SDL_Rect PLAY_RECT = {235,200,545,95};
const SDL_Rect INSTRUCTION_RECT = {235,350,545,90};
while (true) {
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) exit(0);
if (e.type != SDL_MOUSEBUTTONDOWN || e.button.button != SDL_BUTTON_LEFT) {
continue;
}
SDL_Point mouse_pos = {e.motion.x, e.motion.y};
if (isIn(mouse_pos, PLAY_RECT)) {
Mix_PlayChannel( -1, ping, 0 );
int mode = chooseMode(media);
Play(media, mode);
return;
}
if (isIn(mouse_pos, INSTRUCTION_RECT)) {
Mix_PlayChannel( -1, ping, 0 );
Instruction(media);
}
}
}
}
void playAgain(Media* media, const int& mode, const int& score) {
SDL_Renderer* renderer = media->renderer;
SDL_Event e;
Mix_Chunk* ping = media->ping;
SDL_RenderCopy(renderer, media->game_over_png, NULL, &BIG_RECT);
const SDL_Rect MAIN_MENU_RECT = {50,310,300,70};
const SDL_Rect PLAY_AGAIN_RECT = {370,310,300,70};
const SDL_Rect QUIT_RECT = {690,310,290,70};
int* high_score = new int [NUM_OF_MODES];
high_score = getHighScore();
string high_score_str = intToString(high_score[mode]);
string your_score_str = intToString(score);
delete high_score;
TTF_Font* font = media->font;
SDL_Texture* your_score_text = loadFromRenderedText(your_score_str, {255,0,0}, font, renderer);
SDL_Texture* high_score_text = loadFromRenderedText(high_score_str, {255,0,0}, font, renderer);
const SDL_Rect YOUR_SCORE_RECT = {540, 135, 25* your_score_str.size(), 45};
const SDL_Rect HIGH_SCORE_RECT = {540, 200, 25* high_score_str.size(), 45};
copyText(your_score_text, YOUR_SCORE_RECT, renderer);
copyText(high_score_text, HIGH_SCORE_RECT, renderer);
SDL_RenderPresent(renderer);
while (true) {
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) exit(0);
if (e.type != SDL_MOUSEBUTTONDOWN || e.button.button != SDL_BUTTON_LEFT) {
continue;
}
SDL_Point mouse_pos = {e.motion.x, e.motion.y};
if (isIn(mouse_pos, PLAY_AGAIN_RECT)) {
Mix_PlayChannel( -1, ping, 0 );
int mode = chooseMode(media);
Play(media, mode);
}
if (isIn(mouse_pos, MAIN_MENU_RECT)) {
Mix_PlayChannel( -1, ping, 0 );
startMenu(media);
}
if (isIn(mouse_pos, QUIT_RECT)) {
Mix_PlayChannel( -1, ping, 0 );
exit(0);
}
}
}
}
void pauseMenu(Media* media, const int& score) {
SDL_Event e;
SDL_Renderer* renderer = media->renderer;
SDL_Texture* menu_texture = media->pause_png;
SDL_RenderCopy(media->renderer, menu_texture, NULL, &BIG_RECT);
SDL_RenderPresent(renderer);
Mix_Chunk* ping = media->ping;
const SDL_Rect MAIN_MENU_RECT = {50,310,300,70};
const SDL_Rect RESUME_RECT = {370,310,300,70};
const SDL_Rect QUIT_RECT = {690,310,290,70};
string your_score_str = intToString(score);
TTF_Font* font = media->font;
SDL_Texture* your_score_text = loadFromRenderedText(your_score_str, {255,0,0}, font, renderer);
const SDL_Rect YOUR_SCORE_RECT = {540, 155, 25* your_score_str.size(), 45};
copyText(your_score_text, YOUR_SCORE_RECT, renderer);
SDL_RenderPresent(renderer);
while (true) {
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) exit(0);
if (e.type != SDL_MOUSEBUTTONDOWN || e.button.button != SDL_BUTTON_LEFT) {
continue;
}
SDL_Point mouse_pos = {e.motion.x, e.motion.y};
if (isIn(mouse_pos, RESUME_RECT)) {
Mix_PlayChannel( -1, ping, 0 );
return;
}
if (isIn(mouse_pos, MAIN_MENU_RECT)) {
Mix_PlayChannel( -1, ping, 0 );
startMenu(media);
return;
}
if (isIn(mouse_pos, QUIT_RECT)) {
Mix_PlayChannel( -1, ping, 0 );
exit(0);
}
}
}
}
void Instruction(Media* media) {
SDL_Event e;
Mix_Chunk* ping = media->ping;
SDL_Texture* menu_texture = media->instruction_png;
SDL_Texture* menu_texture2 = media->instruction2_png;
SDL_RenderCopy(media->renderer, menu_texture, NULL, &BIG_RECT);
SDL_RenderPresent(media->renderer);
SDL_Delay(5000);
SDL_RenderCopy(media->renderer, menu_texture2, NULL, &BIG_RECT);
SDL_RenderPresent(media->renderer);
while (true) {
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) exit(0);
if (e.type != SDL_MOUSEBUTTONDOWN || e.button.button != SDL_BUTTON_LEFT) {
continue;
}
SDL_Point mouse_pos = {e.motion.x, e.motion.y};
if (isIn(mouse_pos, BIG_RECT)) {
Mix_PlayChannel( -1, ping, 0 );
startMenu(media);
}
}
}
}
int chooseMode(Media* media) {
SDL_Renderer* renderer = media->renderer;
SDL_Event e;
const SDL_Rect BUTTON_RECT[3] = { {50,250,300,150}, {370,250,300,150}, {690,250,265,150} };
const SDL_Rect TEXT_RECT = {400, 500, 280, 35};
SDL_RenderCopy(renderer, media->choose_mode_png, NULL, &BIG_RECT);
SDL_RenderPresent(renderer);
while (true) {
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) exit(0);
if (e.type != SDL_MOUSEBUTTONDOWN || e.button.button != SDL_BUTTON_LEFT) {
continue;
}
SDL_Point mouse_pos = {e.motion.x, e.motion.y};
for (int i = 0; i < 3; i++) {
if (isIn(mouse_pos, BUTTON_RECT[i])) {
Mix_PlayChannel( -1, media->ping, 0 );
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 0);
SDL_RenderDrawRect(renderer, &BUTTON_RECT[i]);
SDL_Texture* text = loadFromRenderedText("Loading, please wait ...", {255,0,0}, media->font, renderer);
copyText(text, TEXT_RECT, renderer);
SDL_RenderPresent(renderer);
return i;
}
}
}
}
}
| true |
808781797d1cb9898bbf9131e194790488e782fc
|
C++
|
JinyuChata/leetcode_cpp
|
/leetcode/editor/cn/315_count-of-smaller-numbers-after-self.cpp
|
UTF-8
| 3,340 | 3.1875 | 3 |
[] |
no_license
|
//给你`一个整数数组 nums ,按要求返回一个新数组 counts 。数组 counts 有该性质: counts[i] 的值是 nums[i] 右侧小于
//nums[i] 的元素的数量。
//
//
//
// 示例 1:
//
//
//输入:nums = [5,2,6,1]
//输出:[2,1,1,0]
//解释:
//5 的右侧有 2 个更小的元素 (2 和 1)
//2 的右侧仅有 1 个更小的元素 (1)
//6 的右侧有 1 个更小的元素 (1)
//1 的右侧有 0 个更小的元素
//
//
// 示例 2:
//
//
//输入:nums = [-1]
//输出:[0]
//
//
// 示例 3:
//
//
//输入:nums = [-1,-1]
//输出:[0,0]
//
//
//
//
// 提示:
//
//
// 1 <= nums.length <= 10⁵
// -10⁴ <= nums[i] <= 10⁴
//
// Related Topics 树状数组 线段树 数组 二分查找 分治 有序集合 归并排序 👍 643 👎 0
#include "bits/stdc++.h"
using namespace std;
//leetcode submit region begin(Prohibit modification and deletion)
class LineNode {
public:
LineNode* left;
LineNode* right;
int minVal; int maxVal;
int count = 0;
};
class Solution {
public:
LineNode* buildNode(int minVal, int maxVal) {
if (minVal > maxVal) return nullptr;
LineNode* root = new LineNode;
root->minVal = minVal; root->maxVal = maxVal;
if (minVal == maxVal) return root;
int mid = minVal + (maxVal - minVal) / 2;
LineNode* leftNode = buildNode(minVal, mid);
LineNode* rightNode = buildNode(mid+1, maxVal);
root->left = leftNode; root->right = rightNode;
return root;
}
// [l,r] 工作区间
// [L,R] 要查询的区间
int queryCounter(int l, int r, int L, int R, LineNode* root) {
if (L > R) return 0; if (l > r) return 0;
if (L > r || R < l) return 0;
if (L <= l && r <= R) return root->count;
if (l == r) {
if (L <= l && r <= R) return root->count;
return 0;
}
int ret = 0;
int mid = l + (r-l)/2;
ret += queryCounter(l, mid, L, R, root->left);
ret += queryCounter(mid+1, r, L, R, root->right);
return ret;
}
void insertValue(int l, int r, int val, LineNode* root) {
if (r < l) return;
if (l <= val && val <= r) root->count++;
if (l == r) return;
int mid = l + (r-l)/2;
if (l <= val && val <= mid) insertValue(l, mid, val, root->left);
if (mid+1 <= val && val <= r) insertValue(mid+1, r, val, root->right);
}
vector<int> countSmaller(vector<int>& nums) {
int minVal = nums[0]; int maxVal = nums[0];
int n = nums.size();
for (int i = 1; i < n; i++) {
if (nums[i] < minVal) minVal = nums[i];
if (nums[i] > maxVal) maxVal = nums[i];
}
// 建树
LineNode* root = buildNode(minVal, maxVal);
vector<int> res;
// 从右向左遍历,边遍历边查
for (int i = n-1; i >= 0; i--) {
int num = nums[i];
// 先查询现有线段树中,小于 num 的元素
res.insert(res.begin(), queryCounter(minVal, maxVal, minVal, num-1, root));
// 再将num插入线段树
insertValue(minVal, maxVal, num, root);
}
return res;
}
};
//leetcode submit region end(Prohibit modification and deletion)
int main() {
Solution s;
}
| true |
1adb764bc7be27fa1e21203d80ca9876efa194cb
|
C++
|
GabeOchieng/ggnn.tensorflow
|
/program_data/PKU_raw/61/51.c
|
UTF-8
| 237 | 2.96875 | 3 |
[] |
no_license
|
int f(int);
int main()
{
int n;
cin >> n;
for(int i=0; i < n; i++)
{
int a;
cin>>a;
cout<<f(a)<<endl;
}
}
int f(int x)
{
if(x==1)
{
return 1;
}
if(x == 2)
{
return 1;
}
return f(x-1)+f(x-2);
}
| true |
bcf5bfd809f6ac74a63ae7f86a518dcf8e49ebeb
|
C++
|
sanhaji182/3-Mei-2016
|
/mahasiswa.cpp
|
UTF-8
| 891 | 3.21875 | 3 |
[] |
no_license
|
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int n;
int no=1;
cout<<"Jumlah mahasiswa : ";
cin >>n;
int nim[n];
string nama[n];
system("cls");
for (int i=0;i<n;i++)
{
cout <<"Masukan nim dan nama mahasiswa ke "<<no<<endl;
cout <<"NIM : ";
cin >> nim[i];
cout <<"Nama : ";
cin >> nama[i];
system("cls");
}
cout<<"|----------------------------------|"<<endl;
cout<<"| Data mahasiswa "<<endl;
cout<<"|----------------------------------|"<<endl;
for (int i=0;i<n;i++)
{
cout<<"| No. | "<<no<<endl;
no++;
cout<<"|----------------------------------|"<<endl;
cout<<"| NIM | "<<nim[i]<<endl;
cout<<"| Nama | "<<nama[i]<<endl<<endl;
cout<<"|----------------------------------|"<<endl;
}
}
| true |
74a054a2021003dd2ded2ccdfb8812fee2a864b4
|
C++
|
wyager/SystemNFC
|
/Mifare Classic/MifareClassicCard.h
|
UTF-8
| 2,280 | 2.6875 | 3 |
[] |
no_license
|
//
// MifareClassicCard.h
// NFCSystem2
//
// Created by Will Yager on 7/26/13.
// Copyright (c) 2013 Will Yager. All rights reserved.
//
#ifndef __NFCSystem2__MifareClassicCard__
#define __NFCSystem2__MifareClassicCard__
#include <iostream>
#include <nfc/nfc.h>
#include <vector>
#include <array>
#include "nfc_defines.h"
class MifareClassicCard {
bool ready = false;
////////all LibNFC specific members/////////
nfc_device *pnd;
nfc_target nt; //This is the big kahuna. It holds a lot of important data about the target. It's a union of a bunch of types that can hold data about any kind of NFC tag.
/////////////////////////////////////////////
public:
bool is_ready(){
return this->ready;
}
//Tries to scan for a card. If successful return MifareClassicCard with
//ready bit set to true.
MifareClassicCard(nfc_device* pnd);
std::vector<uint8_t> answer_to_request();//ATQA
std::vector<uint8_t> unique_identifier();//UID
std::vector<uint8_t> select_acknowledge();//SAK
std::vector<uint8_t> answer_to_select();//ATS
std::string basic_card_info();
static bool is_first_block_in_sector(int block);
static bool is_trailer_block_in_sector(int block);
static bool next_trailer_block_in_sector(int block);
//returns response from device
std::vector<uint8_t> transmit_bytes(std::vector<uint8_t> bytes_to_send);
bits_container transmit_bits(bits_container bits_to_send);
std::vector<uint8_t> auth_unique_identifier();
//using_key_a means "Try to auth by guessing key a"
//returns a vector containing the key on success, an empty vector on failure
std::vector<uint8_t> authenticate(int block, bool using_key_a);
bool authenticate(int block, std::vector<uint8_t> key, std::vector<uint8_t> uid, bool using_key_a);
int guess_card_size();
//Request for Answer To Select (RATS)
std::vector<uint8_t> request_for_answer_to_select();
std::vector<uint8_t> read_entire_card();
std::vector<uint8_t> read_sector(int sector);
bool write_sector(int sector, std::vector<uint8_t> data); //true on success. Write 64 bytes to specified sector (except zero and trailers. So really only 32-48 bytes)
};
#endif /* defined(__NFCSystem2__MifareClassicCard__) */
| true |
915961222edf2480e72b6db38663d994aa885614
|
C++
|
quintanasergio/ARAP-Compare
|
/dialog.cpp
|
UTF-8
| 2,043 | 2.65625 | 3 |
[] |
no_license
|
#include "dialog.h"
#include "ui_dialog.h"
#include <QDebug>
Dialog::Dialog(QList<QString> experimentos, QList<QString> showExp, QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
allExp = experimentos;
addExp = showExp;
//rellenar lista de Exp. a mostrar
for(int i = 0; i<addExp.size(); i++){
ui->listWidget_2->addItem(addExp[i]);
}
//rellenar lista de Exp que no se mostraran
for(int i = 0; i < allExp.size(); i++){
if(!addExp.contains(allExp[i]))
ui->listWidget->addItem(allExp[i]);
}
}
QList<QString> Dialog::getList()
{
return(addExp);
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::on_pushButton_clicked()
{
if(ui->listWidget->currentItem()){
//agregar a add
addExp.append(ui->listWidget->currentItem()->text());
//agregar a lista add
ui->listWidget_2->addItem(ui->listWidget->currentItem()->text());
//borrar acá
ui->listWidget->takeItem(ui->listWidget->currentRow());
}
}
void Dialog::on_pushButton_2_clicked()
{
if(ui->listWidget_2->currentItem()){
//remover de add
addExp.removeOne(ui->listWidget_2->currentItem()->text());
//agregar a lista sub
ui->listWidget->addItem(ui->listWidget_2->currentItem()->text());
//borrar acá
ui->listWidget_2->takeItem(ui->listWidget_2->currentRow());
}
}
void Dialog::on_pushButton_3_clicked()
{
//vaciar add
addExp.clear();
//vaciar addList
ui->listWidget_2->clear();
//llenar subL (sacar de ALL o ir pasando 1 por 1)
ui->listWidget->clear();
ui->listWidget->addItems(allExp);
}
void Dialog::on_pushButton_4_clicked()
{
// add = all
addExp = allExp;
//vaciar subList
ui->listWidget->clear();
//llenar add (sacar de ALL o 1 por 1)
ui->listWidget_2->clear();
ui->listWidget_2->addItems(allExp);
}
void Dialog::on_pushButton_5_clicked()
{
done(1);
}
void Dialog::on_pushButton_6_clicked()
{
done(0);
}
| true |
27d2f125e96663a94bf33b141e70cf172df9d52e
|
C++
|
smunix/hobbes
|
/include/hobbes/util/func.H
|
UTF-8
| 2,015 | 2.53125 | 3 |
[
"Apache-2.0"
] |
permissive
|
#ifndef HOBBES_UTIL_FUNC_HPP_INCLUDED
#define HOBBES_UTIL_FUNC_HPP_INCLUDED
namespace hobbes {
template <typename T>
struct func {
};
template <typename R, typename ... Args>
struct func<R(Args...)> {
static const std::size_t arity = sizeof...(Args);
typedef R (*type)(Args...);
typedef R result_type;
};
template <typename R, typename ... Args>
struct func<R(*)(Args...)> {
static const std::size_t arity = sizeof...(Args);
typedef R (*type)(Args...);
typedef R result_type;
};
template <typename R, typename C, typename ... Args>
struct func<R(C::*)(Args...)> {
static const std::size_t arity = sizeof...(Args);
typedef R (*type)(C*, Args...);
typedef R result_type;
};
template <typename T>
struct mfnTraits {
};
template <typename R, typename C, typename ... Args>
struct mfnTraits<R(C::*)(Args...)const> {
static const int arity = sizeof...(Args);
typedef R result_type;
typedef C class_type;
};
template <typename R, typename C, typename ... Args>
struct mfnTraits<R(C::*)(Args...)> {
static const int arity = sizeof...(Args);
typedef R result_type;
typedef C class_type;
};
template <typename X, typename T, T f>
struct mfnThunk {
};
template <typename R, typename C, typename ... Args, typename T, T f>
struct mfnThunk<R(C::*)(Args...), T, f> {
static R fn(C* c, Args... args) {
return (c->*f)(args...);
}
};
template <typename R, typename C, typename ... Args, typename T, T f>
struct mfnThunk<R(C::*)(Args...)const, T, f> {
static R fn(C* c, Args... args) {
return (c->*f)(args...);
}
};
template <typename C, typename ... Args, typename T, T f>
struct mfnThunk<void(C::*)(Args...), T, f> {
static void fn(C* c, Args... args) {
(c->*f)(args...);
}
};
template <typename C, typename ... Args, typename T, T f>
struct mfnThunk<void(C::*)(Args...)const, T, f> {
static void fn(C* c, Args... args) {
(c->*f)(args...);
}
};
}
#endif
| true |
fa5121f89683f9f07a7127075c48e6f2a319ec6d
|
C++
|
mge19/analysis-of-algorithms
|
/algo2 homework1.cpp
|
ISO-8859-3
| 4,453 | 3.125 | 3 |
[] |
no_license
|
/*BLG336E - Analysis of Algorithms
Project - 1
Mehmet Gencay Ertrk - 150130118*/
#include <iostream>
#include <ctime>
#include <list>
#include <deque>
#include <cstdlib>
#include <cstring>
using namespace std;
class Coordinate
{
public:
int x,y;
bool placed;
Coordinate(int i,int j);
};
Coordinate::Coordinate(int i,int j)
{
x=i;
y=j;
placed=false;
}
class Table{
public:
Table(char* str);
bool can_place_miner(int i,int j);
void place_miner(int i,int j);
void find_solution(char* str1,char* str2);
char** table;
list<Coordinate> sites;
~Table();
int row,col,*row_max,*col_max,number_of_miners;
};
Table::Table(char* str)
{
FILE* input=fopen(str,"r+");
if(input==NULL)
{
cerr<<"Error opening file.";
exit(1);
}
fscanf(input,"%d\t%d\n\t",&col,&row);
col_max=new int[col];
row_max=new int[row];
table=new char*[row];
for(int i=0;i<=row;i++)
{
if(i<row){table[i]=new char[col];}
for(int j=0;j<=col;j++)
{
char x;
if(j==col && i<row){fscanf(input,"%c\n",&x);}
else if(!(i==0 && j==0)){fscanf(input,"%c\t",&x);}
else if(j==col && i==row){fscanf(input,"%c",&x);}
if(i==0)
{
if(j>0){col_max[j-1]=x-48;}
}
else if(j==0){row_max[i-1]=x-48;}
else
{
table[i-1][j-1]=x;
if(x=='s'){sites.push_back(Coordinate(i-1,j-1));}
}
cout<<x<<endl;
}
}
fclose(input);
}
bool Table::can_place_miner(int i,int j)
{
if(i<0 || j<0 || i>=row || j>=col){return false;}
if(table[i][j]=='s' || table[i][j]=='m'){return false;}
if(row_max[i]<0 || col_max[j]<0){return false;}
if(i>0 && table[i-1][j]=='m'){return false;}
if(j>0 && table[i][j-1]=='m'){return false;}
if(i<row-1 && table[i+1][j]=='m'){return false;}
if(j<col-1 && table[i][j+1]=='m'){return false;}
return true;
}
void Table::place_miner(int i,int j)
{
table[i][j]='m';
row_max[i]--;
col_max[j]--;
number_of_miners++;
}
void Table::find_solution(char* str1,char* str2)
{
int maximum_nodes_kept_in_stack=1,number_of_visited_nodes=1;
Table t=*this;
deque<Table> d;
clock_t time_start=clock();
d.push_back(t);
while(t.number_of_miners!=sites.size())
{
if(strcmp(str1,"bfs")==0)
{
t=d.front();
d.pop_front();
}
else
{
t=d.back();
d.pop_back();
}
list<Coordinate>::iterator it;
for(it=t.sites.begin();it!=t.sites.end();++it)
{
if(t.can_place_miner((it->x)-1,it->y))
{
Table a=t;
a.place_miner((it->x)-1,it->y);
number_of_visited_nodes++;
d.push_back(a);
}
if(t.can_place_miner((it->x)+1,it->y))
{
cout<<"x"<<endl;
Table a=t;
cout<<"x"<<endl;
a.place_miner((it->x)+1,it->y);
cout<<"x"<<endl;
number_of_visited_nodes++;
cout<<"x"<<endl;
}
if(t.can_place_miner(it->x,(it->y)-1))
{
Table a=t;
a.place_miner(it->x,(it->y)-1);
number_of_visited_nodes++;
d.push_back(a);
}
if(t.can_place_miner(it->x,(it->y)+1))
{
Table a=t;
a.place_miner(it->x,(it->y)+1);
number_of_visited_nodes++;
d.push_back(a);
}
}
if(d.size()>maximum_nodes_kept_in_stack){maximum_nodes_kept_in_stack=d.size();}
}
clock_t time_end=(double)(clock()-time_start)/CLOCKS_PER_SEC;
cout<<"Algorithm: "<<str1<<endl<<"Number of visited nodes: "<<number_of_visited_nodes<<endl<<"Maximum number of nodes kept in memory: "<<maximum_nodes_kept_in_stack<<endl<<"Running time: "<<time_end<<"seconds"<<endl;
FILE* output=fopen(str2,"w+");
if(output==NULL)
{
cerr<<"Error opening file";
exit(1);
}
fprintf(output,"%d\t%d\n\t",col,row);
for(int i=0;i<=row;i++)
{
for(int j=0;i<=col;j++)
{
if(i==0)
{
if(j>0)
{
if(j==t.col){fprintf(output,"%d\n",col_max[j-1]);}
else{fprintf(output,"%d\t",col_max[j-1]);}
}
}
else if(j==0){fprintf(output,"%d\t",row_max[i-1]);}
else if(j==t.col){fprintf(output,"%c\n",t.table[i-1][j-1]);}
else{fprintf(output,"%c\t",t.table[i-1][j-1]);}
}
}
cout<<"Solution is written to the file";
fclose(output);
}
Table::~Table()
{
delete row_max;
delete col_max;
delete* table;
}
int main(int argc,char** argv)
{
if(argc==4 && (strcmp(argv[1],"bfs")==0 || strcmp(argv[1],"dfs")==0))
{
Table t(argv[2]);
t.find_solution(argv[1],argv[3]);
}
else
{
cerr<<"Invalid command";
exit(1);
}
system("pause");
return 0;
}
| true |
ddf62096c849c1b493ab8768e4f45282bea7557b
|
C++
|
BBBBchan/C_CPP_ACM
|
/ACM暑期培训/Day_2/day2_G.cpp
|
UTF-8
| 369 | 2.703125 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <math.h>
int main(){
float n;
int kase = 0;
scanf("%f", &n);
while(n != 0){
for(int i = 0;i < 50; i++){
float a = (1/sqrt(5))*(pow((1+sqrt(5))/2,i)-pow((1-sqrt(5))/2,i));
if(n == a){
printf("Second win\n");
kase = 1;
break;
}
}
if(!kase)
printf("First win\n");
kase = 0;
scanf("%f", &n);
}
return 0;
}
| true |
5adf0d1167915b8c45e26eacbc8b506c145d70b7
|
C++
|
Illusionist5/StudFiles
|
/6 семестр/урвс/учебка/лабы/лр4/Dofiga_vashe_dofiga_boyanov/dofiga_vashe_dofiga_boyanov/lab4+(2)/br/pot.cpp
|
KOI8-R
| 1,888 | 3.109375 | 3 |
[] |
no_license
|
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
float r_rand() // 0 1
{ static char c=0;
char a=11, b=19, d=50;
c=(a*c+b)%d;
return (float)c/(d-1);
}
void errors(int er) //
{ switch(er)
{ case 1 : printf(" N !\n"); break;
case 2 : printf(" %s !\n",File); break;
case 3 : printf(" N !\n"); break;
case 4 : printf(" !\n"); break;
}
}
void main(int argn,char *argv[])
{ int status=0, i, wri, ka;
unsigned int n=0;
float po[1000];
if(argn > 1) ka = atoi(argv[1]);
printf(" - N (10 sek):\n");
scanf("%d",&n); // N
if(n>0 && n<1000) // N 0 1000, ...
{ wri = write(ka,&n,sizeof(unsigned int));// N
if(wri == sizeof(unsigned int)) // , ...
{ for(i=0; i<n; i++) //
po[i] = r_rand(); // N
wri = write(ka,po,n*sizeof(float)); //
if(wri != n*sizeof(float)) status=3; // , status=3
}
else status=2; // status=2
} // status=1
else status=1; //
errors(status); //
exit(status);
}
| true |
ea526d4fd96f2577bf841d1902ea2338627c2a47
|
C++
|
mathbrook/learningCpp
|
/voltage___temperature_crude_logging.ino
|
UTF-8
| 1,176 | 2.765625 | 3 |
[] |
no_license
|
const int sensorPin = A0;
const int voltagethree = A3;
const int voltagetwo = A2;
const float baselineTemp=22;
void setup() {
Serial.begin(9600);
for(int pinNumber = 2; pinNumber<5; pinNumber++){
pinMode(pinNumber, OUTPUT);
digitalWrite(pinNumber, LOW);
}
// put your setup code here, to run once:
}
void loop() {
int sensorVal = analogRead(sensorPin);
//Serial.print("Sensor value: ");
//Serial.print(sensorVal);
int voltagereading = analogRead(voltagetwo);
int potentiometer = analogRead(voltagethree);
float potvalue = potentiometer;
float battvolt = (voltagereading/1034.0) * 5.0;
Serial.print("potvalue: ");
Serial.print(potvalue);
Serial.print(", batt voltage: ");
Serial.print(battvolt);
// convert the ADC reading to voltage
float voltage = (sensorVal/1034.0) * 5.0;
Serial.print(", temp sensor volts: ");
Serial.print(voltage);
Serial.print(", degrees C: ");
//convert the voltage into temperature in degrees
float temperature = (voltage - .5) * 100;
Serial.println(temperature);
//Serial.println(battvolt);
// put your main code here, to run repeatedly:
delay(1);
}
| true |
edb3547408217a290059b25b34dd3f2c6c1f991d
|
C++
|
evanw/cs224final
|
/util/raytracer.cpp
|
UTF-8
| 4,496 | 2.796875 | 3 |
[] |
no_license
|
#include "raytracer.h"
#include <qgl.h>
#include <iostream>
using namespace std;
void HitTest::mergeWith(const HitTest &other)
{
if (other.t > 0 && other.t < t)
{
t = other.t;
hit = other.hit;
normal = other.normal;
}
}
static Vector3 unProject(float winX, float winY, double *modelview, double *projection, int *viewport)
{
double objX, objY, objZ;
gluUnProject(winX, winY, 1, modelview, projection, viewport, &objX, &objY, &objZ);
return Vector3(objX, objY, objZ);
}
Raytracer::Raytracer()
{
// read camera information from opengl
double modelview[16];
double projection[16];
glGetIntegerv(GL_VIEWPORT, viewport);
glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
glGetDoublev(GL_PROJECTION_MATRIX, projection);
// reconstruct the eye position
Vector3 xaxis(modelview[0], modelview[1], modelview[2]);
Vector3 yaxis(modelview[4], modelview[5], modelview[6]);
Vector3 zaxis(modelview[8], modelview[9], modelview[10]);
Vector3 offset(modelview[12], modelview[13], modelview[14]);
eye = -Vector3(offset.dot(xaxis), offset.dot(yaxis), offset.dot(zaxis));
// generate the four corner rays
int xmin = viewport[0];
int ymin = viewport[1];
int xmax = xmin + viewport[2] - 1;
int ymax = ymin + viewport[3] - 1;
ray00 = unProject(xmin, ymin, modelview, projection, viewport) - eye;
ray10 = unProject(xmax, ymin, modelview, projection, viewport) - eye;
ray01 = unProject(xmin, ymax, modelview, projection, viewport) - eye;
ray11 = unProject(xmax, ymax, modelview, projection, viewport) - eye;
}
Vector3 Raytracer::getRayForPixel(int x, int y) const
{
float fx = (float)(x - viewport[0]) / (float)viewport[2];
float fy = 1 - (float)(y - viewport[1]) / (float)viewport[3];
Vector3 ray0 = Vector3::lerp(ray00, ray10, fx);
Vector3 ray1 = Vector3::lerp(ray01, ray11, fx);
return Vector3::lerp(ray0, ray1, fy).unit();
}
bool Raytracer::hitTestCube(const Vector3 &cubeMin, const Vector3 &cubeMax, const Vector3 &origin, const Vector3 &ray, HitTest &result)
{
// This uses the slab intersection method
Vector3 tMin = (cubeMin - origin) / ray;
Vector3 tMax = (cubeMax - origin) / ray;
Vector3 t1 = Vector3::min(tMin, tMax);
Vector3 t2 = Vector3::max(tMin, tMax);
float tNear = t1.max();
float tFar = t2.min();
if (tNear > 0 && tNear < tFar)
{
const float epsilon = 1.0e-6;
result.hit = origin + ray * tNear;
if (result.hit.x < cubeMin.x + epsilon) result.normal = Vector3(-1, 0, 0);
else if (result.hit.y < cubeMin.y + epsilon) result.normal = Vector3(0, -1, 0);
else if (result.hit.z < cubeMin.z + epsilon) result.normal = Vector3(0, 0, -1);
else if (result.hit.x > cubeMax.x - epsilon) result.normal = Vector3(1, 0, 0);
else if (result.hit.y > cubeMax.y - epsilon) result.normal = Vector3(0, 1, 0);
else result.normal = Vector3(0, 0, 1);
result.t = tNear;
return true;
}
return false;
}
bool Raytracer::hitTestSphere(const Vector3 ¢er, float radius, const Vector3 &origin, const Vector3 &ray, HitTest &result)
{
Vector3 offset = origin - center;
float a = ray.lengthSquared();
float b = 2 * ray.dot(offset);
float c = offset.lengthSquared() - radius * radius;
float discriminant = b * b - 4 * a * c;
if (discriminant > 0)
{
result.t = (-b - sqrtf(discriminant)) / (2 * a);
result.hit = origin + ray * result.t;
result.normal = (center - result.hit) / radius;
return true;
}
return false;
}
bool Raytracer::hitTestTriangle(const Vector3 &a, const Vector3 &b, const Vector3 &c, const Vector3 &origin, const Vector3 &ray, HitTest &result)
{
Vector3 ab = b - a;
Vector3 ac = c - a;
result.normal = ab.cross(ac).unit();
result.t = result.normal.dot(a - origin) / result.normal.dot(ray);
if (result.t > 0)
{
result.hit = origin + ray * result.t;
Vector3 toHit = result.hit - a;
float dot00 = ac.lengthSquared();
float dot01 = ac.dot(ab);
float dot02 = ac.dot(toHit);
float dot11 = ab.lengthSquared();
float dot12 = ab.dot(toHit);
float divide = dot00 * dot11 - dot01 * dot01;
float u = (dot11 * dot02 - dot01 * dot12) / divide;
float v = (dot00 * dot12 - dot01 * dot02) / divide;
return (u >= 0 && v >= 0 && u + v <= 1);
}
return false;
}
| true |
938e107e3a79c140de01ac42a5ecd9eaec7dba2c
|
C++
|
HTMLlama/ArduinoFun
|
/motor/motor.ino
|
UTF-8
| 797 | 2.984375 | 3 |
[] |
no_license
|
#include "Servo.h"
const int SERVO_PIN = 11;
Servo servo;
//int fanSpeed = 0;
//bool isFanUp = true;
void setup() {
// put your setup code here, to run once:
// pinMode(SERVO_PIN, OUTPUT);
servo.attach(SERVO_PIN);
}
void loop() {
servo.write(random(0, 180));
delay(random(150, 1000));
// // Make servo go to 0 degrees
// servo.write(0);
// delay(1000);
// // Make servo go to 90 degrees
// servo.write(90);
// delay(1000);
// // Make servo go to 180 degrees
// servo.write(180);
// delay(1000);
//
// servo.write(60);
// delay(1000);
// digitalWrite(SERVO_PIN, LOW);
//
// if(fanSpeed >= 255 || fanSpeed <= 0) {
// isFanUp = !isFanUp;
// }
//
// if(isFanUp) {
// fanSpeed++;
// } else {
// fanSpeed--;
// }
//
// delay(50);
}
| true |
112569b00bf4f279cf7a9e98a583c41cbd1efe3e
|
C++
|
Alohahah/leetcode-1
|
/Project1/Project1/Source.cpp
|
GB18030
| 5,381 | 3.359375 | 3 |
[] |
no_license
|
#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>
using namespace std;
/*
* @Author: Gu Tiankai
* @Desc: K-Sort in Memory
* @Date: 2017.05.13
*/
/*
* ==============================================>
* Declaration Part
* ==============================================>
*/
//#define DEBUG_SWITCH //Ϣ
#define GEN_FACTOR ((int)1000)
#define TOP_K ((int)100)
class Sorter
{
public:
auto rev_generate() -> vector<unsigned int>; //
auto ord_generate() -> vector<unsigned int>; //˳
auto rnd_generate() -> vector<unsigned int>; //
auto inorder_generate() -> vector<unsigned int>; //ԭ
/*Default: vector<unsigned int>().max_size()/GEN_FACTOR*/
Sorter() : generator(Generator(/*Customization Number*/)){}
private:
class Generator //
{
public:
Generator(int _genTols = vector<unsigned int>().max_size()/GEN_FACTOR) : genTols(_genTols)
{
vals.reserve(genTols);
vals.resize(genTols);
init();
}
auto get() -> vector<unsigned int> {return vals;} //ģ
private:
vector<unsigned int> vals;
int genTols;
void init();
};
Generator generator;
};
class Solution
{
#define PAR(i) ((i-1)/2) //ȡڵ
#define LEFT(i) (2*i+1) //ȡڵ
#define RIGHT(i) (2*i+2) //ȡҽڵ
public:
Solution() {}
Solution(vector<unsigned int> _vals):vals(_vals){ initHeap(); }
void changeVals(vector<unsigned int> _vals) { vals.clear(); vals = _vals; initHeap();} //Ľ
void selelectK(vector<unsigned int>& __klist, int k); //ѡǰK
private:
vector<unsigned int> vals;
void initHeap();
void matinHeap(int i, int length);
};
/*
* ==============================================<
* Declaration Part End
* ==============================================<
*/
/*
* ==============================================
* Implementation Part
* ==============================================
*/
inline void Sorter :: Generator :: init()
{
srand(time(NULL));
//for (int i = 0; i < genTols; ++i)
// vals.push_back(unsigned int(rand()));
// for high efficiency
for_each(begin(vals), end(vals), [=](unsigned int& val) mutable -> void {
val = unsigned int(rand());
});
sort(vals.begin(), vals.end());
}
////
inline vector<unsigned int> Sorter::rev_generate()
{
vector<unsigned int> _vals = generator.get();
int i = 0, j = _vals.size() - 1;
while (i < j)
{
auto tmp = _vals[i];
_vals[i] = _vals[j];
_vals[j] = tmp;
i++; j--;
}
return move(_vals);
}
//˳
inline vector<unsigned int> Sorter::ord_generate()
{
return move(generator.get());
}
//
inline vector<unsigned int> Sorter::rnd_generate()
{
vector<unsigned int> _vals = generator.get();
for (int i = 0; i < _vals.size(); ++i)
{
int rndindex = (int)rand()%_vals.size();
auto tmp = _vals[rndindex];
_vals[rndindex] = _vals[i];
_vals[i] = tmp;
}
return move(_vals);
}
inline vector<unsigned int> Sorter:: inorder_generate()
{
return move(generator.get());
}
inline void Solution::initHeap()
{
int size = vals.size() - 1;
for (int i = PAR(size); i >= 0; i --)
matinHeap(i, size);
}
inline void Solution::matinHeap(int i, int length)
{
while (i >= 0 && i <= PAR(length) && vals[i] < max(vals[LEFT(i)], vals[RIGHT(i)<length?RIGHT(i):LEFT(i)]))
{
int maxindex = vals[LEFT(i)] > vals[RIGHT(i)<length?RIGHT(i):LEFT(i)] ? LEFT(i) : RIGHT(i)<length?RIGHT(i):LEFT(i);
int tmp = vals[i];
vals[i] = vals[maxindex];
vals[maxindex] = tmp;
i = maxindex;
}
}
//ѡǰK
inline void Solution::selelectK(vector<unsigned int>& __klist, int k)
{
__klist.clear();
for (int i = vals.size() - 1; vals.size() -1 - i != k && i >= 0; i--)
{
__klist.push_back(vals[0]);
vals[0] = vals[i];
matinHeap(0, i);
}
}
/*
* ==============================================
* Implementation Part End
* ==============================================
*/
/*
* ==============================================
* Test Part Start
* ==============================================
*/
int main()
{
Sorter sorter;
vector<unsigned int> list = sorter.ord_generate();
Solution s(sorter.ord_generate());
cout << "Default Toltal: vector<unsigned int>().max_size()/GEN_FACTOR" << endl;
cout << "Top-K: " << TOP_K << "\n" << endl;
vector<unsigned int> klist;
s.selelectK(klist, TOP_K);
cout << "Test Case 1(In Ord): ";
#ifdef DEBUG_SWITCH
for (const auto& e: list)
cout << e << " ";
cout << endl << endl;
#endif
for (const auto& e: klist)
cout << e << " ";
cout << endl << endl;
list = sorter.rev_generate();
s.changeVals(sorter.rev_generate());
s.selelectK(klist, TOP_K);
cout << "Test Case 2(Rev Ord): ";
#ifdef DEBUG_SWITCH
for (const auto& e: list)
cout << e << " ";
cout << endl << endl;
#endif
for (const auto& e: klist)
cout << e << " ";
cout << endl << endl;
list = sorter.rnd_generate();
s.changeVals(sorter.rnd_generate());
s.selelectK(klist, TOP_K);
cout << "Test Case 3(Rnd Ord): ";
#ifdef DEBUG_SWITCH
for (const auto& e: list)
cout << e << " ";
cout << endl << endl;
#endif
for (const auto& e: klist)
cout << e << " ";
cout << endl << endl;
}
/*
* ==============================================
* Test Part End
* ==============================================
*/
| true |
fd654a0682140cdf91550cf73c555856bfc68bdf
|
C++
|
NatadecocoSeijin/If-I-m-not-brave-men
|
/Enemy.h
|
SHIFT_JIS
| 506 | 2.5625 | 3 |
[] |
no_license
|
#pragma once
#include "Character.h"
class Player;
typedef unsigned long long stagedata;
class Enemy :public Character// G̍\
{
private:
public:
Enemy(char name[], int x, int y, int hp, int attack, int diffence, int magic_power, int dex, int image, int image_dead); //O,x,y,hp,U,h,,q
virtual bool move(int dx, int dy, Player** p, int size_p, Enemy** e, int size_e, stagedata stage);
virtual void battle(int x, int y, Player** players, int size_players);
};
| true |
c5c1b8e4afb0d630d47a5890ef6e2c412654a407
|
C++
|
lord-przemas/learn_cpp
|
/standard_library/memory_management/main.cpp
|
UTF-8
| 1,492 | 3.875 | 4 |
[] |
no_license
|
#include <iostream>
#include <memory>
#include <algorithm>
class Data
{
public:
int x {123};
Data() = default;
Data(int num)
: x {num}
{
}
Data(const Data& data)
: x { data.x }
{
std::cout << "Data(const Data& data)" << std::endl;
}
Data(Data&& data)
: x { data.x }
{
std::cout << "Data(Data&& data)" << std::endl;
}
void operator=(const Data& data) {
std::cout << "operator=(const Data& data)" << std::endl;
}
~Data() {
std::cout << "~Data()" << std::endl;
}
};
int main()
{
constexpr uint32_t SIZE { 3 };
std::cout << "------ Simple copy ------" << std::endl;
{
Data tbl1 [SIZE];
Data tbl2 [SIZE];
std::copy(tbl1, tbl1 + std::size(tbl1), tbl2);
}
std::cout << "------ Uninitialized copy ------" << std::endl;
{
Data data_src [SIZE] {11, 22, 33};
constexpr uint32_t BUF_SIZE { sizeof(Data) * SIZE };
uint8_t buffer1[BUF_SIZE];
Data* data_dest = reinterpret_cast<Data*>(buffer1);
std::uninitialized_copy(data_src, data_src + SIZE, data_dest);
// std::uninitialized_fill(data_dest, data_dest + SIZE, data_src[1]);
// std::uninitialized_default_construct(data_dest, data_dest + SIZE);
// std::uninitialized_move(data_src, data_src + SIZE, data_dest);
for(int i {}; i < SIZE; i++)
std::cout << data_dest[i].x << ", ";
std::cout << std::endl;
std::destroy(data_dest, data_dest + SIZE);
}
return 0;
}
| true |
2840c029ade4cca8c855efdbe8cec09f841df3f7
|
C++
|
mrdooz/nesthing
|
/src/file_utils.cpp
|
UTF-8
| 1,092 | 2.65625 | 3 |
[] |
no_license
|
#include "file_utils.hpp"
#include <sys/stat.h>
#ifdef _WIN32
#include <io.h>
#include <direct.h>
#else
#include <sys/stat.h>
#include <unistd.h>
#endif
namespace nes
{
//---------------------------------------------------------------------------
string CurrentDirectory()
{
char buf[256];
getcwd(buf, sizeof(buf));
return string(buf);
}
//---------------------------------------------------------------------------
bool FileExists(const char* filename)
{
struct stat status;
return access(filename, 0) == 0 && stat(filename, &status) == 0 && (status.st_mode & S_IFREG);
}
//---------------------------------------------------------------------------
bool DirectoryExists(const char* name)
{
struct stat status;
return access(name, 0) == 0 && stat(name, &status) == 0 && (status.st_mode & S_IFDIR);
}
//---------------------------------------------------------------------------
Status LoadTextFile(const char* filename, vector<char>* buf)
{
Status err = LoadFile(filename, buf);
buf->push_back(0);
return err;
}
}
| true |
2641b828065f8520944134077e47014de41fa150
|
C++
|
alexandraback/datacollection
|
/solutions_5751500831719424_0/C++/paladin8/A.cc
|
UTF-8
| 1,089 | 2.734375 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
vector<int> h[110];
string base[110];
int main() {
int t; cin >> t;
for (int c = 1; c <= t; c++) {
int n; cin >> n;
for (int i = 0; i < n; i++) {
h[i].clear(); base[i] = "";
string s; cin >> s;
for (int j = 0; j < s.size(); j++) {
if (j == 0 || s[j] != s[j-1]) {
h[i].push_back(0);
base[i] += s[j];
}
h[i][h[i].size()-1]++;
}
}
bool poss = true;
for (int i = 0; i < n; i++)
if (base[i] != base[0])
poss = false;
cout << "Case #" << c << ": ";
if (!poss) cout << "Fegla Won" << endl;
else {
int res = 0;
for (int i = 0; i < h[0].size(); i++) {
int best = 1000000000;
for (int len = 1; len <= 100; len++) {
int cur = 0;
for (int j = 0; j < n; j++) cur += abs(h[j][i] - len);
best = min(best, cur);
}
res += best;
}
cout << res << endl;
}
}
return 0;
}
| true |
860044253c7044fc3f1ea7084aad360b23d40ee0
|
C++
|
MarkoMackic/Republicko-takmicenje-2017
|
/Suma/main.cpp
|
UTF-8
| 901 | 3.1875 | 3 |
[] |
no_license
|
#include <iostream>
#include <algorithm>
using namespace std;
bool sort_function (int i,int j) { return (i<j); }
int main()
{
long long sum = 0;
int n;
cin >> n;
vector<long long> brojevi;
for(int i = 0; i < n ; i++){
long long temp;
cin >>temp;
brojevi.push_back(temp);
}
sort(brojevi.begin(), brojevi.end(), sort_function);
for(vector<long long>::iterator it = brojevi.end()-1;it>=brojevi.begin();--it){
if(*it % 2 == 0 ){
sum += *it;
brojevi.erase(it);
}
}
if(brojevi.size() % 2 == 0){
for(vector<long long>::iterator it = brojevi.begin(); it != brojevi.end(); it++){
sum+= *it;
}
}else{
for(vector<long long>::iterator it = brojevi.begin()+1; it != brojevi.end(); it++){
sum+= *it;
}
}
cout << sum << endl;
return 0;
}
| true |
7152bf5c5ab40563985965e6911fec661a59c90f
|
C++
|
ajalsingh/PFMS-A2020
|
/quizzes/quiz3/a/analysis.cpp
|
UTF-8
| 1,443 | 2.890625 | 3 |
[] |
no_license
|
#include "analysis.h"
#include <iostream>
#include <cmath>
Analysis::Analysis()
{
}
void Analysis::setShapes(std::vector<Shape*> shapes) {
shapes_=shapes;
}
void Analysis::setLine(Line line) {
line_=line;
}
std::vector<bool> Analysis::intersectsLine(){
for (auto s:shapes_){
radius_.push_back(sqrt(s->getArea()/M_PI)); //can't use getRadius method from Circle class (not sure why), so radius is calculated using area
}
std::vector<double> eqn; //dx,dy,dr,D
eqn = line_.getEquations();
double discrim;
for (int i= 0; i<shapes_.size();i++){
discrim = pow(radius_.at(i),2)*eqn.at(2) - pow(eqn.at(3),2);
if (discrim >= 0){
intersect_.push_back(1);
}
else{
intersect_.push_back(0);
}
}
return intersect_;
}
//! TODO - TASK 3: Implement the missing function(s) in Analysis Class
//!
//! HINT: Analysis inherits from AnalysisInterface which is an abstract class
//! What type of class is AnalysisInterface, what does this mean?
//!
//! Use the following webiste to assist in developing the code
//! https://mathworld.wolfram.com/Circle-LineIntersection.html
//!
//! BONUS QUESTION (FOR DISCUSSION)
//! At the moment we are implementing check intersect for a Circle
//! as the only question used.
//! If we had a Rectangle shape, how could we differentiate between the approach
//! to intersect for the Rectangle and the Circle?
| true |
719ff1ab1f686449b25820afc7db8efe2ea72960
|
C++
|
alexeev509/RUCODE_3_0
|
/SECOND_DAY/d2.cpp
|
UTF-8
| 2,280 | 2.828125 | 3 |
[] |
no_license
|
#include "iostream"
#include "vector"
using namespace std;
vector<vector<long>> v;
string sequence;
//https://e-maxx.ru/algo/bracket_sequences
//https://neerc.ifmo.ru/wiki/index.php?title=%D0%9F%D1%80%D0%B0%D0%B2%D0%B8%D0%BB%D1%8C%D0%BD%D1%8B%D0%B5_%D1%81%D0%BA%D0%BE%D0%B1%D0%BE%D1%87%D0%BD%D1%8B%D0%B5_%D0%BF%D0%BE%D1%81%D0%BB%D0%B5%D0%B4%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D1%8C%D0%BD%D0%BE%D1%81%D1%82%D0%B8
long const MODULE = 1e9+7;
void findIndex(){
v[0][0]=1;
for(int i =1; i<=sequence.size();++i){
v[i][0]=v[i-1][1];
for(int j =1;j<=sequence.size(); ++j){
v[i][j]=(v[i-1][j-1]%MODULE+v[i-1][j+1]%MODULE)%MODULE;
}
}
// for(int i = 0;i<=sequence.size();++i){
// for(int j =0;j<=sequence.size(); ++j){
// cout<<v[i][j]<<" ";
// }
// cout<<"\n";
// }
}
void restoreAnswer(){
int depth=0;
long answer=1;
for(int i =0; i<sequence.size();++i){
if(sequence[i]=='(')
++depth;
else{
answer=(answer%MODULE + v[sequence.size()-i-1][depth+1]%MODULE)%MODULE;
--depth;
}
}
cout<<answer;
}
int main(){
cin>>sequence;
v.resize(sequence.size()+2,vector<long>(sequence.size()+2));
findIndex();
restoreAnswer();
return 0;
}
//(()())()
//1 0 0 0 0 0 0 0 0
//0 1 0 0 0 0 0 0 0
//1 0 1 0 0 0 0 0 0
//0 2 0 1 0 0 0 0 0
//2 0 3 0 1 0 0 0 0
//0 5 0 4 0 1 0 0 0
//5 0 9 0 5 0 1 0 0
//0 14 0 14 0 6 0 1 0
//14 0 28 0 20 0 7 0 1
//n=8;
//4+
//(()())()
//(((()))) 1
//((()())) 2
//((())()) 3
//((()))() 4
//(()(())) 5
//(()()()) 6
//(()())() 7
//Идея такая: закрывающиеся скобки - пропускаем
//Если скобка отркывается - предположим - что она наооборот закрыта - тогда сколько вариантов поставить после нее скобки - чтобы баланс был равен 0?
//(()())()
//Предположим третья закрывается:((( - тогда 4 варианта поставить скобки после неё (1,2,3,4)
//Предположим 5-ая скобка закрывается: (()(( - тогда остается 1 вариант
//и тд
| true |
db842ea7023934070d6ef59ec3c336db0dd635cd
|
C++
|
cselab/CubismNova
|
/docs/source/examples/Grid/Cartesian_01.cpp
|
UTF-8
| 1,207 | 3.125 | 3 |
[
"BSD-2-Clause",
"BSD-3-Clause"
] |
permissive
|
#include <Cubism/Grid/Cartesian.h>
#include <Cubism/Mesh/StructuredUniform.h>
#include <algorithm>
int main(void)
{
// 3D mesh
constexpr size_t dim = 3; // 3D problem
using Mesh = Cubism::Mesh::StructuredUniform<double, dim>;
using MIndex = typename Mesh::MultiIndex;
// cell centered scalar grid using integer data
constexpr size_t rank = 0; // rank-0 field (scalar)
using Grid =
Cubism::Grid::Cartesian<int, Mesh, Cubism::EntityType::Cell, rank>;
const MIndex nblocks(3); // number of blocks in the topology (27 blocks)
const MIndex block_cells(8); // number of cells per block (512 cells)
// allocate the grid in the domain [0, 1] (memory is not touched)
Grid grid(nblocks, block_cells);
// initialize the block fields using the master thread with some examples to
// access state.
for (auto bf : grid) {
std::fill(bf->begin(), bf->end(), 0); // initialize data to 0
const auto &fs = bf->getState(); // get state for this field
const Mesh &bm = *fs.mesh; // get the block mesh for this field
const MIndex bi = fs.block_index; // get the block index for this field
}
return 0;
}
| true |
08075cf09ada9a74df8125bda9bd019074a0709b
|
C++
|
seanmarks/wham
|
/src/wham/FileSystem.cpp
|
UTF-8
| 3,342 | 3.34375 | 3 |
[
"MIT"
] |
permissive
|
#include "FileSystem.h"
#include "Assert.hpp"
namespace FileSystem {
char separator() noexcept
{
#ifndef _WIN_32
return '/'; // Unix
#else
return '\\'; // Windows
#endif
}
std::string root()
{
#ifndef _WIN_32
std::stringstream ss;
ss << separator();
return ss.str();
#else
static_assert(false, "missing implementation");
#endif
}
std::string join(const std::string& left, const std::string right)
{
std::stringstream ss;
ss << left << FileSystem::separator() << right;
return ss.str();
}
std::string realpath(const std::string& path)
{
#ifndef _WIN_32
if ( path.length() < 1 ) {
throw std::runtime_error("get_realpath() was given an empty path");
}
// Use POSIX realpath()
char* buffer = ::realpath(&path[0], nullptr);
if ( buffer == nullptr ) {
throw std::runtime_error("Error resolving path \"" + path + "\"");
}
// Move the path to a std string and clean up
std::string resolved_path(buffer);
free(buffer); buffer = nullptr;
return resolved_path;
#else
// TODO: Windows version
static_assert(false, "missing implementation");
#endif // ifndef _WIN_32
}
std::string dirname(const std::string& full_path)
{
size_t i = full_path.rfind(FileSystem::separator(), full_path.length());
if ( i != std::string::npos ) {
return full_path.substr(0, i);
}
else {
return "."; // TODO: Windows
}
}
bool isAbsolutePath(const std::string& path)
{
FANCY_ASSERT( ! path.empty(), "no input provided" );
#ifndef _WIN32
return ( path.front() == FileSystem::separator() );
#else
static_assert(false, "missing implementation");
#endif // ifndef _WIN32
}
std::string resolveRelativePath(const std::string& rel_path, const std::string& base_path)
{
std::stringstream ss;
if ( isAbsolutePath(rel_path) ) {
ss << rel_path;
}
else {
ss << join(base_path, rel_path);
}
return realpath( ss.str() );
}
void readFilesList(
const std::string& files_list, const int file_col, std::vector<std::string>& files)
{
std::ifstream list_ifs(files_list);
if ( not list_ifs.is_open() ) {
throw std::runtime_error("Failed to open file \'" + files_list + "\'");
}
std::string files_list_path = FileSystem::dirname(files_list);
const char comment_char = '#';
auto skip = [=](const std::string& s) {
return ( s.empty() || s.front() == comment_char );
};
int i = 0;
std::string line, token;
std::vector<std::string> tokens;
files.clear();
while ( getline(list_ifs, line) ) {
// Ignore possible comments and blank lines
std::stringstream ss(line);
ss >> token;
if ( skip(token) ) {
continue;
}
// Split the line into tokens
tokens = {{ token }};
while ( ss >> token ) {
if ( ! skip(token) ) {
tokens.push_back( token );
}
else {
break;
}
}
// Check for too few columns
const int num_tokens = tokens.size();
FANCY_ASSERT( file_col < num_tokens,
"Error reading files list from " << files_list << "\n"
<< " A non-empty, non-comment line has fewer than " << file_col+1 << " columns\n"
<< " line: " << line << "\n" );
// Process the file name
auto file = resolveRelativePath(tokens[file_col], files_list_path);
files.push_back( file );
++i;
}
list_ifs.close();
}
} // end namespace FileSystem
| true |
13077bd5ccc3574616e5397f69c3334eb1748cbd
|
C++
|
yameenjavaid/Online-Judge-Solutions
|
/Kattis/control.cpp
|
UTF-8
| 1,131 | 2.53125 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
// Association for Control Over Minds
const int m = 500001;
int par[m + 3], ran[m + 3], siz[m + 3];
int ufind(int u){
return (u == par[u]) ? u : (par[u] = ufind(par[u]));
}
void umerge(int u, int v){
int i = ufind(u), j = ufind(v);
if(i == j)
return;
if(ran[i] > ran[j]){
par[j] = i;
siz[i] += siz[j];
}
else{
par[i] = j;
siz[j] += siz[i];
if(ran[i] == ran[j])
ran[j]++;
}
}
map<int, int> cnt;
int main(){
iota(par, par + m, 0);
fill_n(siz, m, 1);
int n, ans = 0;
cin >> n;
while(n--){
cnt.clear();
int r, x;
cin >> r;
while(r--)
cin >> x, cnt[ufind(x)]++;
bool ok = true;
for(pair<int, int> u : cnt)
if(u.second < siz[u.first]){
ok = false;
break;
}
if(ok){
ans++;
int u = cnt.begin()->first;
for(pair<int, int> v : cnt)
umerge(u, v.first);
}
}
cout << ans << endl;
}
| true |
0e3e793d4efc2f3c0690f1dae1b705af0af7b97b
|
C++
|
itz-siddharth/Advanced-DataStructures-in-C
|
/10-19-2020 18_Binary Tree.cpp
|
UTF-8
| 782 | 3.78125 | 4 |
[] |
no_license
|
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
node *left, *right;
};
struct node *root=NULL;
struct node* insert()
{
int x;
struct node *p;
printf("Enter data(-1 for no data):");
scanf("%d",&x);
if(x==-1)
return NULL;
p=(struct node*)malloc(sizeof(struct node));
p->data=x;
printf("Enter left child of %d:\n",x);
p->left=insert();
printf("Enter right child of %d:\n",x);
p->right=insert();
return p;
}
void preorder(node *t) //address of root node is passed in t
{
if(t!=NULL)
{
printf("\n%d",t->data); //visit the root
preorder(t->left); //preorder traversal on left subtree
preorder(t->right); //preorder traversal om right subtree
}
}
int main()
{
root=insert();
preorder(root);
}
| true |
e35fcd55c3b4e59c28fdb878948255f13e5a7bf6
|
C++
|
valentinvstoyanov/fmi
|
/introduction-to-programming-cpp/jump_search.cpp
|
UTF-8
| 924 | 3.828125 | 4 |
[] |
no_license
|
#include<iostream>
#include<cmath>
int linear_search(const int arr[], const unsigned begin_index, const unsigned end_index, const int element) {
for(unsigned i = begin_index; i <= end_index; ++i)
if(arr[i] == element)
return i;
return -1;
}
int jump_search(const int arr[], const unsigned size, const int element) {
const unsigned block_size = sqrt(size);
unsigned begin_index = 0;
for(unsigned end_index = block_size; end_index < size; end_index += block_size) {
if(arr[begin_index] <= element && arr[end_index] >= element)
return linear_search(arr, begin_index, end_index, element);
begin_index = end_index;
}
return -1;
}
int main() {
const unsigned size = 10;
const int arr[size] = {1, 2, 3, 4, 5, 55, 60, 100, 555, 999};
const int search_element = 2;
const int search_result = jump_search(arr, size, search_element);
std::cout << "Result: " << search_result << std::endl;
return 0;
}
| true |
279d5e59db72d30bd563dbcfbdfec4f81c99d33a
|
C++
|
bennyber01/two-wheeled-robot
|
/Projects/Arduino/Code/Cerebellum/SensorsModule.cpp
|
UTF-8
| 4,466 | 2.84375 | 3 |
[] |
no_license
|
#include "SensorsModule.h"
inline double ConvertAnalogValueToCM_SharpSensor_2D120X(int val)
{
double volts = double(val) * 0.0048828125; // value from sensor * (5/1024) - if running 3.3.volts then change 5 to 3.3
double distance = 2076.0 / (val - 11.0);
// double distance = -(3.078*pow(volts,5))+(29.645*pow(volts,4))-(110.68*pow(volts,3))+(201.94*pow(volts,2))-(186.84*pow(volts,1))+81.524;
return distance;
}
inline double ConvertAnalogValueToCM_SharpSensor_GP2D12(int val)
{
double volts = double(val);// * 0.0048828125; // value from sensor * (5/1024) - if running 3.3.volts then change 5 to 3.3
double distance = (6787.0 / (volts - 3.0)) - 4.0;
return distance;
}
inline double ConvertAnalogValueToCM_SonarSensor(int val)
{
return double(val) / double(US_ROUNDTRIP_CM);
}
inline double ConvertAnalogValueToAmpers(int val)
{
return double(val) / double(US_ROUNDTRIP_CM);
// Remap the ADC value into a voltage number (5V reference)
double sensorValue = double(val * VOLTAGE_REF) / 1023.0;
// Follow the equation given by the INA169 datasheet to
// determine the current flowing through RS. Assume RL = 10k
// Is = (Vout x 1k) / (RS x RL)
double current = sensorValue / double(10 * RS);
// Output value (in amps)
return current;
}
SensorsModule::SensorsModule() : sonar(TRIGGER_PIN, ECHO_PIN, MAX_SONAR_SENSOR_DISTANCE) // NewPing setup of pins and maximum distance.
{
frontSensorsData.LSensorDist = 0.0f;
frontSensorsData.CSensorDist = 0.0f;
frontSensorsData.RSensorDist = 0.0f;
bumpersData.LBumper = 0;
bumpersData.RBumper = 0;
sonarData.dist = 0;
lastSonarUpdateTime = 0;
currentVal = 0.0f;
}
SensorsModule::~SensorsModule()
{
}
void SensorsModule::Init()
{
// no need to init alanog pins for input
// sonar pins are init in ping module
pinMode(L_BUMPER_PIN, INPUT_PULLUP);
pinMode(R_BUMPER_PIN, INPUT_PULLUP);
}
void SensorsModule::Update()
{
bumpersData.LBumper = digitalRead(L_BUMPER_PIN);
//delay(2);
UpdateFrontLeftDistanceSensorValue();
//delay(2);
UpdateFrontCenterDistanceSensorValue();
//delay(2);
UpdateFrontRightDistanceSensorValue();
//delay(2);
UpdateCurrentValue();
//delay(2);
bumpersData.RBumper = digitalRead(R_BUMPER_PIN);
//delay(2);
// Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
unsigned long time_millisec = millis();
if (lastSonarUpdateTime < time_millisec - 50)
{
UpdateSonarDistanceSensorValue();
lastSonarUpdateTime = time_millisec;
}
delay(2);
}
void SensorsModule::UpdateFrontLeftDistanceSensorValue()
{
int val = analogRead(FRONT_LEFT_DISTANCE_SENSOR_PIN); // read the input pin
int filteredVal = frontLeftDistanceSensorFilter.Filter(val);
frontSensorsData.LSensorDist = ConvertAnalogValueToCM_SharpSensor_GP2D12(filteredVal);
}
void SensorsModule::UpdateFrontCenterDistanceSensorValue()
{
int val = analogRead(FRONT_CENTER_DISTANCE_SENSOR_PIN) - 4; // read the input pin
int filteredVal = frontCenterDistanceSensorFilter.Filter(val);
frontSensorsData.CSensorDist = ConvertAnalogValueToCM_SharpSensor_2D120X(filteredVal);
}
void SensorsModule::UpdateFrontRightDistanceSensorValue()
{
int val = analogRead(FRONT_RIGHT_DISTANCE_SENSOR_PIN) - 15; // read the input pin
int filteredVal = frontRightDistanceSensorFilter.Filter(val);
frontSensorsData.RSensorDist = ConvertAnalogValueToCM_SharpSensor_2D120X(filteredVal);
}
void SensorsModule::UpdateSonarDistanceSensorValue()
{
unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS).
int filteredVal = sonarDistanceSensorFilter.Filter(uS);
sonarData.dist = ConvertAnalogValueToCM_SonarSensor(filteredVal);
}
void SensorsModule::UpdateCurrentValue()
{
int val = analogRead(CURRENT_SENSOR_PIN); // read the input pin
currentVal = ConvertAnalogValueToAmpers(val);
}
FrontSensorsData SensorsModule::GetFrontSensorsData()
{
return frontSensorsData;
}
BumpersData SensorsModule::GetBumpersData()
{
return bumpersData;
}
SonarData SensorsModule::GetSonarData()
{
return sonarData;
}
float SensorsModule::GetCurrent()
{
return currentVal;
}
| true |