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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
0f3e3b8e61df9064df218765d3ce5f31458a841b | C++ | LinkItONEDevGroup/LASS | /Device_mbed/Example_Geiger/mbed/PortInOut.h | UTF-8 | 2,833 | 2.65625 | 3 | [
"MIT"
] | permissive | /* mbed Microcontroller Library
* Copyright (c) 2006-2013 ARM Limited
*
* 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.
*/
#ifndef MBED_PORTINOUT_H
#define MBED_PORTINOUT_H
#include "platform.h"
#if DEVICE_PORTINOUT
#include "port_api.h"
#include "critical.h"
namespace mbed {
/** A multiple pin digital in/out used to set/read multiple bi-directional pins
*
* @Note Synchronization level: Interrupt safe
*/
class PortInOut {
public:
/** Create an PortInOut, connected to the specified port
*
* @param port Port to connect to (Port0-Port5)
* @param mask A bitmask to identify which bits in the port should be included (0 - ignore)
*/
PortInOut(PortName port, int mask = 0xFFFFFFFF) {
core_util_critical_section_enter();
port_init(&_port, port, mask, PIN_INPUT);
core_util_critical_section_exit();
}
/** Write the value to the output port
*
* @param value An integer specifying a bit to write for every corresponding port pin
*/
void write(int value) {
port_write(&_port, value);
}
/** Read the value currently output on the port
*
* @returns
* An integer with each bit corresponding to associated port pin setting
*/
int read() {
return port_read(&_port);
}
/** Set as an output
*/
void output() {
core_util_critical_section_enter();
port_dir(&_port, PIN_OUTPUT);
core_util_critical_section_exit();
}
/** Set as an input
*/
void input() {
core_util_critical_section_enter();
port_dir(&_port, PIN_INPUT);
core_util_critical_section_exit();
}
/** Set the input pin mode
*
* @param mode PullUp, PullDown, PullNone, OpenDrain
*/
void mode(PinMode mode) {
core_util_critical_section_enter();
port_mode(&_port, mode);
core_util_critical_section_exit();
}
/** A shorthand for write()
*/
PortInOut& operator= (int value) {
write(value);
return *this;
}
PortInOut& operator= (PortInOut& rhs) {
write(rhs.read());
return *this;
}
/** A shorthand for read()
*/
operator int() {
return read();
}
private:
port_t _port;
};
} // namespace mbed
#endif
#endif
| true |
ca4516506a163dbdae32c4444afe70d244f4b299 | C++ | akb825/VertexFormatConvert | /lib/include/VFC/Converter.h | UTF-8 | 13,590 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2020-2021 Aaron Barany
*
* 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.
*/
#pragma once
#include <VFC/Config.h>
#include <VFC/Export.h>
#include <VFC/IndexData.h>
#include <VFC/VertexFormat.h>
#include <VFC/VertexValue.h>
#include <cstdint>
#include <functional>
#include <vector>
namespace vfc
{
/**
* @brief Converter for vertex and index data.
*
* This class takes multiple vertex streams as inputs, optionally with index values, and converts
* them into a single vertex stream.
*/
class VFC_EXPORT Converter
{
public:
/**
* @brief Enum for the transform to apply to a vertex value.
*/
enum class Transform
{
Identity, ///< Use the value is used as-is.
/**
* Normalizes the values to the bounds. This will take the bounding box for all of the
* vertex values for the element, then the values are converted to a value in the range
* [0, 1] for UNorm types or [-1, 1] for SNorm types. When used with non-normalized types,
* this will be the same as Identity.
*/
Bounds,
UNormToSNorm, ///< Converts a value in the range [0, 1] to the range [-1, 1].
SNormToUNorm ///< Converts a value in the range [-1, 1] to the range [0, 1].
};
/**
* @brief Type for a function to handle errors.
* @param message The message to log.
*/
using ErrorFunction = std::function<void(const char* message)>;
/**
* @brief Error function that prints the message to stderr.
* @param message The message to log.
*/
static void stderrErrorFunction(const char* message);
/**
* @brief Constructs the converter with information for what to convert to.
*
* This uses the default maximum index value.
*
* @param vertexFormat The vertex format to convert to.
* @param indexType The index type to convert to.
* @param primitiveType The primitive type for the geometry. This is used to guarantee
* correctness if multiple index buffers are created due to exceeding the maximum index
* value.
* @param patchPoints The number of points when primitiveType is PrimitiveType::PatchList.
* @param errorFunction Function to report error messages.
*/
Converter(VertexFormat vertexFormat, IndexType indexType, PrimitiveType primitiveType,
unsigned int patchPoints = 0, ErrorFunction errorFunction = &stderrErrorFunction);
/**
* @brief Constructs the converter with information for what to convert to.
* @param vertexFormat The vertex format to convert to.
* @param indexType The index type to convert to.
* @param primitiveType The primitive type for the geometry. This is used to guarantee
* correctness if multiple index buffers are created due to exceeding the maximum index
* value.
* @param patchPoints The number of points when primitiveType is PrimitiveType::PatchList.
* @param maxIndexValue The maximum index value to use.
* @param errorFunction Function to report error messages.
*/
Converter(VertexFormat vertexFormat, IndexType indexType, PrimitiveType primitiveType,
unsigned int patchPoints, std::uint32_t maxIndexValue,
ErrorFunction errorFunction = &stderrErrorFunction);
/**
* @brief Constructs the converter with information for what to convert to.
*
* This uses the default maximum index value.
*
* @param vertexFormat The vertex format to convert to. This has multiple formats used to
* populate multiple output streams.
* @param indexType The index type to convert to.
* @param primitiveType The primitive type for the geometry. This is used to guarantee
* correctness if multiple index buffers are created due to exceeding the maximum index
* value.
* @param patchPoints The number of points when primitiveType is PrimitiveType::PatchList.
* @param errorFunction Function to report error messages.
*/
Converter(std::vector<VertexFormat> vertexFormat, IndexType indexType,
PrimitiveType primitiveType, unsigned int patchPoints = 0,
ErrorFunction errorFunction = &stderrErrorFunction);
/**
* @brief Constructs the converter with information for what to convert to.
* @param vertexFormat The vertex format to convert to. This has multiple formats used to
* populate multiple output streams.
* @param indexType The index type to convert to.
* @param primitiveType The primitive type for the geometry. This is used to guarantee
* correctness if multiple index buffers are created due to exceeding the maximum index
* value.
* @param patchPoints The number of points when primitiveType is PrimitiveType::PatchList.
* @param maxIndexValue The maximum index value to use.
* @param errorFunction Function to report error messages.
*/
Converter(std::vector<VertexFormat> vertexFormat, IndexType indexType,
PrimitiveType primitiveType, unsigned int patchPoints, std::uint32_t maxIndexValue,
ErrorFunction errorFunction = &stderrErrorFunction);
Converter(const Converter& other) = delete;
Converter& operator=(const Converter& other) = delete;
/**
* @brief Move constructor.
* @param other The other instance to move.
*/
Converter(Converter&& other) = default;
/**
* @brief Move assignment.
* @param other The other instance to move.
* @return A reference to this.
*/
Converter& operator=(Converter&& other) = default;
/**
* @brief Returns whether or not the converter is valid.
* @return True if the format is valid.
*/
bool isValid() const
{
return !m_vertexFormat.empty();
}
/**
* @brief Returns whether or not the converter is valid.
* @return True if the format is valid.
*/
explicit operator bool() const
{
return isValid();
}
/**
* @brief Gets the vertex format to convert to.
* @return The vertex format.
*/
const std::vector<VertexFormat>& getVertexFormat() const
{
return m_vertexFormat;
}
/**
* @brief Gets the index type to convert to.
* @return The index type.
*/
IndexType getIndexType() const
{
return m_indexType;
}
/**
* @brief Gets the primitive type for the geometry.
* @return The primitive type.
*/
PrimitiveType getPrimitiveType() const
{
return m_primitiveType;
}
/**
* @brief Gets the number of patch points.
* @return The patch points.
*/
unsigned int getPatchPoints() const
{
return m_patchPoints;
}
/**
* @brief Gets the max allowed index value.
* @return The max index value.
*/
std::uint32_t getMaxIndexValue() const
{
return m_maxIndexValue;
}
/**
* @brief Gets the transform for a vertex element by index.
* @param stream The index of the vertex stream. (i.e. which vertex format in the vector)
* @param element The index of the vertex element within the vertex stream.
* @return The transform.
*/
Transform getElementTransform(std::size_t stream, std::size_t element) const
{
assert(stream < m_elementMapping.size());
assert(element < m_elementMapping[stream].size());
return m_elementMapping[stream][element].transform;
}
/**
* @brief Gets the transform for a vertex element by name.
* @param name The name of the element.
* @return The transform.
*/
Transform getElementTransform(const char* name) const;
/**
* @brief Gets the transform for a vertex element by name.
* @param name The name of the element.
* @return The transform.
*/
Transform getElementTransform(const std::string& name) const
{
return getElementTransform(name.c_str());
}
/**
* @brief Sets the transform for a vertex element by index.
* @param stream The index of the vertex stream. (i.e. which vertex format in the vector)
* @param element The index of the vertex element within the vertex stream.
* @param transform The transform to set.
*/
void setElementTransform(std::size_t stream, std::size_t element, Transform transform)
{
assert(stream < m_elementMapping.size());
assert(element < m_elementMapping[stream].size());
m_elementMapping[stream][element].transform = transform;
}
/**
* @brief Sets the transform for a vertex element by name.
* @param name The name of the element.
* @param transform The transform to set.
* @return False if the element wasn't found.
*/
bool setElementTransform(const char* name, Transform transform);
/**
* @brief Sets the transform for a vertex element by name.
* @param name The name of the element.
* @param transform The transform to set.
* @return False if the element wasn't found.
*/
bool setElementTransform(const std::string& name, Transform transform)
{
return setElementTransform(name.c_str(), transform);
}
/**
* @brief Adds a vertex stream to convert without indices.
* @param vertexFormat The vertex format.
* @param vertexData The vertex data.
* @param vertexCount The number of vertices.
* @return False if the vertex stream couldn't be added.
*/
bool addVertexStream(VertexFormat vertexFormat, const void* vertexData,
std::uint32_t vertexCount)
{
return addVertexStream(std::move(vertexFormat), vertexData, vertexCount,
IndexType::NoIndices, nullptr, 0);
}
/**
* @brief Adds a vertex stream to convert with indices.
* @param vertexFormat The vertex format.
* @param vertexData The vertex data.
* @param vertexCount The number of vertices.
* @param indexType The type of the index data.
* @param indexData The index data.
* @param indexCount The number of indices.
* @return False if the vertex stream couldn't be added.
*/
bool addVertexStream(VertexFormat vertexFormat, const void* vertexData,
std::uint32_t vertexCount, IndexType indexType, const void* indexData,
std::uint32_t indexCount);
/**
* @brief Performs the conversion from the input streams to the converted vertex and index data.
* @return False if an error occurred.
*/
bool convert();
/**
* @brief Gets the converted indices.
* @return The index data. More than one buffer will be returned if multiple base vertex values
* are required.
*/
const std::vector<IndexData>& getIndices() const
{
return m_indexData;
}
/**
* @brief Gets the bounds for a vertex element.
*
* The bounds are based on the input values before any transforms are applied.
*
* @param[out] outMin The minimum value for the bounds.
* @param[out] outMax The maximum value for the bounds.
* @param stream The index of the vertex stream. (i.e. which vertex format in the vector)
* @param element The index of the vertex element within the vertex stream.
*/
void getVertexElementBounds(VertexValue& outMin, VertexValue& outMax, std::size_t stream,
std::size_t element) const
{
assert(stream < m_elementMapping.size());
const std::vector<VertexElementRef>& curElementMapping = m_elementMapping[stream];
assert(element < curElementMapping.size());
const VertexElementRef& curElement = curElementMapping[element];
outMin = curElement.minVal;
outMax = curElement.maxVal;
}
/**
* @brief Gets the bounds for a vertex element.
*
* The bounds are based on the input values before any transforms are applied.
*
* @param[out] outMin The minimum value for the bounds.
* @param[out] outMax The maximum value for the bounds.
* @param name The name of the vertex element.
* @return False if the element wasn't found.
*/
bool getVertexElementBounds(VertexValue& outMin, VertexValue& outMax, const char* name) const;
/**
* @brief Gets the bounds for a vertex element.
*
* The bounds are based on the input values before any transforms are applied.
*
* @param[out] outMin The minimum value for the bounds.
* @param[out] outMax The maximum value for the bounds.
* @param name The name of the vertex element.
* @return False if the element wasn't found.
*/
bool getVertexElementBounds(VertexValue& outMin, VertexValue& outMax,
const std::string& name) const
{
return getVertexElementBounds(outMin, outMax, name.c_str());
}
/**
* @brief Gets the converted vertices.
* @return The vertices as an array of bytes.
*/
const std::vector<std::vector<std::uint8_t>>& getVertices() const
{
return m_vertices;
}
/**
* @brief Gets the number of converted vertices.
* @return The number of vertices.
*/
std::uint32_t getVertexCount() const
{
if (m_vertices.empty())
return 0;
return static_cast<std::uint32_t>(m_vertices[0].size()/m_vertexFormat[0].stride());
}
private:
void logError(const char* message) const;
struct VertexStream
{
const std::uint8_t* vertexData;
const void* indexData;
VertexFormat vertexFormat;
std::uint32_t vertexCount;
IndexType indexType;
};
struct VertexElementRef
{
std::uint32_t streamIndex;
const VertexElement* element;
Transform transform;
VertexValue minVal;
VertexValue maxVal;
};
std::vector<VertexFormat> m_vertexFormat;
IndexType m_indexType;
PrimitiveType m_primitiveType;
unsigned int m_patchPoints;
std::uint32_t m_maxIndexValue;
ErrorFunction m_errorFunction;
std::vector<VertexStream> m_vertexStreams;
std::vector<std::vector<VertexElementRef>> m_elementMapping;
std::vector<std::vector<std::uint8_t>> m_vertices;
std::vector<std::uint8_t> m_indices;
std::vector<IndexData> m_indexData;
std::uint32_t m_indexCount;
};
} // namespace vfc
| true |
bf4a5c567e5c4b3ebd5a254bd7e5e701f0c3cf7f | C++ | metaflow/contests | /headers/rnd.h | UTF-8 | 1,314 | 3.296875 | 3 | [
"MIT"
] | permissive | #ifndef _RND_H
#define _RND_H
#include <random>
#include <fstream>
#include <iomanip>
#include <chrono>
#include <algorithm>
class Random {
public:
std::default_random_engine source;
Random() {
source.seed(std::chrono::system_clock::now().time_since_epoch().count());
}
// [a, b)
long long next(long long a, long long b) {
return std::uniform_int_distribution<long long>(a, b - 1)(source);
}
double next_double() {
return std::uniform_real_distribution<double>(0, 1)(source);
}
bool next_bool() {
return next(0, 2) == 1;
}
std::string next_string(int length) {
return next_string(
length,
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
}
std::string next_string(int length, std::string an) {
std::string s = "";
for (int i = 0; i < length; i++) {
s += an[next(0, an.size())];
}
return s;
}
// return (size - 1) edges connecting nodes [0, n)
std::vector<std::pair<int, int>> tree(int size) {
std::vector<int> v(size);
iota(v.begin(), v.end(), 0);
shuffle(v.begin(), v.end(), source);
std::vector<int> to(size);
std::vector<std::pair<int, int>> edges;
for (int i = 1; i < size; i++) edges.emplace_back(v[i], v[next(0, i)]);
return edges;
}
};
Random rnd;
#endif // _RND_H
| true |
9a192ea70e780e8f2eec5f6f009ed724e3706a7f | C++ | SeoHyeonMyeong/Practice_Station | /C++ 예제/Sizeof.cpp | UTF-8 | 340 | 3.359375 | 3 | [] | no_license | #include <iostream>
int main(void) {
int a = 10;
int *b = &a;
char c = 'a';
char *d = &c;
std::cout << "a의 크기 : " << sizeof(a) << std::endl;
std::cout << "b의 크기 : " << sizeof(b) << std::endl;
std::cout << "c의 크기 : " << sizeof(c) << std::endl;
std::cout << "d의 크기 : " << sizeof(d) << std::endl;
}
| true |
031da75d9519941dcbd2ccf86e0fc296fc9d6b86 | C++ | LLNL/gidiplus | /MCGIDI/Test/Utilities/MCGIDI_testUtilities.cpp | UTF-8 | 7,898 | 2.515625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
# <<BEGIN-copyright>>
# Copyright 2019, Lawrence Livermore National Security, LLC.
# See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: MIT
# <<END-copyright>>
*/
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <iomanip>
#include "MCGIDI_testUtilities.hpp"
#define PRINT_NAME_WIDTH 20
static unsigned long long state;
static unsigned long long a_factor = 0x27bb2ee687b0b0fd;
static unsigned long long b_addend = 0xb504f32d;
static double stateToDoubleFactor;
/*
=========================================================
*/
long asLong2( char const *a_chars ) {
char *end_ptr;
long value = strtol( a_chars, &end_ptr, 10 );
while( isspace( *end_ptr ) ) ++end_ptr;
std::string msg( "ERROR: " );
if( *end_ptr != 0 ) throw std::runtime_error( msg + a_chars + " is not a valid integer." );
return( value );
}
/*
=========================================================
*/
double asDouble2( char const *a_chars ) {
char *end_ptr;
double value = strtod( a_chars, &end_ptr );
while( isspace( *end_ptr ) ) ++end_ptr;
std::string msg( "ERROR: " );
if( *end_ptr != 0 ) throw std::runtime_error( msg + a_chars + " is not a valid integer." );
return( value );
}
/*
=========================================================
*/
std::string longToString2( char const *format, long value ) {
char Str[256];
sprintf( Str, format, value );
std::string valueAsString( Str );
return( valueAsString );
}
/*
=========================================================
*/
std::string doubleToString2( char const *format, double value ) {
char Str[256];
sprintf( Str, format, value );
std::string valueAsString( Str );
return( valueAsString );
}
/*
=========================================================
*/
void MCGIDI_test_rngSetup( unsigned long long a_seed ) {
state = 0;
--state;
stateToDoubleFactor = 1.0 / state;
state = a_seed;
}
/*
=========================================================
*/
double float64RNG64( void *a_dummy ) {
state = a_factor * state + b_addend;
return( stateToDoubleFactor * state );
}
/*
=========================================================
*/
argvOption2::argvOption2( std::string const &a_name, bool a_needsValue, std::string const &a_descriptor ) :
m_name( a_name ),
m_counter( 0 ),
m_needsValue( a_needsValue ),
m_descriptor( a_descriptor ) {
}
/*
=========================================================
*/
std::string argvOption2::zeroOrOneOption( char **a_argv, std::string const &a_default ) {
std::string msg( "ERROR: " );
if( !m_needsValue ) throw std::runtime_error( msg + m_name + " does not have a value." );
if( m_counter > 1 ) throw std::runtime_error( msg + m_name + " does not allow multiple arguments." );
if( m_counter == 0 ) return( a_default );
return( a_argv[m_indices[0]] );
}
/*
=========================================================
*/
long argvOption2::asLong( char **a_argv, long a_default ) {
if( present( ) ) {
std::string msg( "ERROR: " );
char *end_ptr;
std::string value_string = zeroOrOneOption( a_argv, "" );
a_default = strtol( a_argv[m_indices[0]], &end_ptr, 10 );
while( isspace( *end_ptr ) ) ++end_ptr;
if( *end_ptr != 0 ) throw std::runtime_error( msg + value_string + " is not a valid integer." );
}
return( a_default );
}
/*
=========================================================
*/
double argvOption2::asDouble( char **a_argv, double a_default ) {
if( present( ) ) {
std::string msg( "ERROR: " );
char *end_ptr;
std::string value_string = zeroOrOneOption( a_argv, "" );
a_default = strtod( a_argv[m_indices[0]], &end_ptr );
while( isspace( *end_ptr ) ) ++end_ptr;
if( *end_ptr != 0 ) throw std::runtime_error( msg + value_string + " is not a valid double." );
}
return( a_default );
}
/*
=========================================================
*/
void argvOption2::help( ) {
std::cout << " " << std::left << std::setw( PRINT_NAME_WIDTH ) << m_name;
if( m_needsValue ) {
std::cout << " VALUE "; }
else {
std::cout << " ";
}
std::cout << m_descriptor << std::endl;
}
/*
=========================================================
*/
void argvOption2::print( ) {
std::cout << std::setw( PRINT_NAME_WIDTH ) << m_name;
for( std::vector<int>::iterator iter = m_indices.begin( ); iter != m_indices.end( ); ++iter ) std::cout << " " << *iter;
std::cout << std::endl;
}
/*
=========================================================
*/
argvOptions2::argvOptions2( std::string const &a_codeName, std::string const &a_descriptor ) :
m_codeName( a_codeName ),
m_descriptor( a_descriptor ) {
add( argvOption2( "-h", false, "Show this help message and exit." ) );
}
/*
=========================================================
*/
void argvOptions2::parseArgv( int argc, char **argv ) {
for( int iargc = 1; iargc < argc; ++iargc ) {
std::string arg( argv[iargc] );
if( arg == "-h" ) help( );
if( arg[0] == '-' ) {
int index = 0;
for( ; index < size( ); ++index ) {
argvOption2 &option = m_options[index];
if( option.m_name == arg ) {
++option.m_counter;
if( option.m_needsValue ) {
++iargc;
if( iargc == argc ) {
std::string msg( "ERROR: option '" );
throw std::runtime_error( msg + arg + "' has no value." );
}
option.m_indices.push_back( iargc );
}
break;
}
}
if( index == size( ) ) {
std::string msg( "ERROR: invalid option '" );
throw std::runtime_error( msg + arg + "'." );
} }
else {
m_arguments.push_back( iargc );
}
}
}
/*
=========================================================
*/
argvOption2 *argvOptions2::find( std::string const &a_name ) {
for( std::vector<argvOption2>::iterator iter = m_options.begin( ); iter != m_options.end( ); ++iter ) {
if( iter->m_name == a_name ) return( &(*iter) );
}
return( nullptr );
}
/*
=========================================================
*/
long argvOptions2::asLong( char **argv, int argumentIndex ) {
return( ::asLong2( argv[m_arguments[argumentIndex]] ) );
}
/*
=========================================================
*/
double argvOptions2::asDouble( char **argv, int argumentIndex ) {
return( ::asDouble2( argv[m_arguments[argumentIndex]] ) );
}
/*
=========================================================
*/
void argvOptions2::help( ) {
std::cout << std::endl << "Usage:" << std::endl;
std::cout << " " << m_codeName << std::endl;
if( m_descriptor != "" ) {
std::cout << std::endl << "Description:" << std::endl;
std::cout << " " << m_descriptor << std::endl;
}
if( m_options.size( ) > 0 ) {
std::cout << std::endl << "Options:" << std::endl;
for( std::vector<argvOption2>::iterator iter = m_options.begin( ); iter != m_options.end( ); ++iter ) iter->help( );
}
exit( EXIT_SUCCESS );
}
/*
=========================================================
*/
void argvOptions2::print( ) {
std::cout << "Arugment indices:";
for( std::vector<int>::iterator iter = m_arguments.begin( ); iter != m_arguments.end( ); ++iter ) std::cout << " " << *iter;
std::cout << std::endl;
for( std::vector<argvOption2>::iterator iter = m_options.begin( ); iter != m_options.end( ); ++iter ) iter->print( );
}
| true |
851bcb1796c4e9111377a1ddab2de7ed65b45e34 | C++ | yayahjb/neartree | /DataGen/src/vector_3d.cpp | UTF-8 | 44,802 | 2.53125 | 3 | [] | no_license | #include <cmath>
#include <cfloat>
#include <climits>
#include <iostream>
/* remove the next include if using a local version of rand */
#include <stdlib.h>
#ifdef _MSC_VER
#define USE_LOCAL_HEADERS
#endif
#ifndef USE_LOCAL_HEADERS
#include <vector_3d.h>
#else
#include "vector_3d.h"
#endif
// static const member variable assignments
//const Vector_3 Vector_3::GetXAxis( ) ( 1.0, 0.0, 0.0 );
//const Vector_3 Vector_3::GetYAxis( ) ( 0.0, 1.0, 0.0 );
//const Vector_3 Vector_3::GetZAxis( ) ( 0.0, 0.0, 1.0 );
//const Vector_3 Vector_3::zeroVector( 0.0, 0.0, 0.0 );
// const double Vector_3::MINNORM = 10.0*FLT_MIN;
const double Vector_3::MINNORM = 1.0E-8;
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
void initrn( int& iseed, int& indx, int& jndx, int& kndx, double buffer[56] )
{
jndx = iseed;
for( indx=0; indx<56; ++indx )
{
jndx = (jndx*2349 + 14867)%32767;
buffer[indx] = ::fabs(double(jndx)/32767.0);
}
iseed = -iseed;
if( iseed == 0 ) iseed = -1;
indx = 55;
kndx = 54;
jndx = 31;
}
class Matrix_3x3;
//C**********************************************************************C
// SUBROUTINE RANORI (ISEED,AMAT)
//C
//C derived from
//C real function randf( iseed )
//C if seed .gt. 0 use seed to initialize
//C returns a rotation matrix for a uniformly distributed
//C random rotation in 0-360 degrees about a
//C uniformly distributed random vector
//C
//C RANORI DOES NOT CALL RANVEC TO GET THE RANDOM VECTOR, SO THAT
//C THE USERS HAS THE OPTION OF GENERATING SEPARATE, DIFFERENT
//C STRINGS OF RANDOM ORIENTATIONS AND VECTORS
//C
//
//C the algorithm is derived from one in J.M.Hammersley and D.C.
//C Handscomb, "Monte Carlo Methods," Methuen & Co., London and
//C Wiley & Sons, New York,1964, p47.
//C The method is to generate a random unit quaterion, and
//C then to turn it into the corresponding rotation matrix.
//C Kearsley, Acta Cryst., v. A45, p. 208-210 (1989) solves a
//C related linear least-squares problem. The linearity
//C gives a hint that this method can be used.
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
double randf( int& iseed )
{
// if seed .gt. 0 use seed to initialize
// returns a uniformly distributed random number in (0. < 1.)
static double randomNumberBuffer[56];
static int indx = -1;
static int jndx;
static int kndx;
if( iseed >= 0 || indx < 0 )
{
initrn( iseed, indx, jndx, kndx, randomNumberBuffer );
}
indx = indx%55 + 1;
jndx = jndx%55 + 1;
kndx = kndx%55 + 1;
double dTemp;
randomNumberBuffer[indx] = modf( randomNumberBuffer[jndx]+randomNumberBuffer[kndx], &dTemp );
return( randomNumberBuffer[indx] );
}
Matrix_3x3 RandomOrientation( int& iseed )
{
const int nc = 4; // number of elements in the quaternion
double sum = 0.0;
double v[4];
do
{
sum = 0.0;
for( int i=0; i<nc; ++i )
{
v[i] = 2.0 * randf(iseed) - 1.0;
sum += v[i] * v[i];
if(sum > 1.0) break;
}
} while(sum > 1.0);
sum = ::sqrt( sum );
for( int i=0; i<4; ++i )
{
v[i] /= sum;
}
return( Matrix_3x3(
v[0]*v[0] + v[1]*v[1] - v[2]*v[2] - v[3]*v[3],
2.0*(v[1]*v[2] + v[0]*v[3]),
2.0*(v[1]*v[3] - v[0]*v[2]),
2.0*(v[1]*v[2] - v[0]*v[3]),
v[0]*v[0] + v[2]*v[2] - v[1]*v[1] - v[3]*v[3],
2.0*(v[2]*v[3] + v[0]*v[1]),
2.0*(v[1]*v[3] + v[0]*v[2]),
2.0*(v[2]*v[3] - v[0]*v[1]),
v[0]*v[0] + v[3]*v[3] - v[1]*v[1] - v[2]*v[2] ) );
}
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
Vector_3 randVector( int& iseed )
{
double v[3];
do
{
for( int i=0; i<3; ++i )
{
v[i] = 2.0 * randf(iseed) -1.0;
}
} while( v[0]*v[0]+v[1]*v[1]+v[2]*v[2] > 1.0 ); // reject those in the corners
return( Vector_3( v[0], v[1], v[2] ) );
}
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
double randfg( int& iseed )
{
//C real function randfg( iseed )
//C if seed .gt. 0 use seed to initialize
//C returns a normally distributed random number with unit variance
//C
//C EXACTLY FOLLOWS THE ALGORITHM OF KNUTH, THE ART OF COMPUTER
//C PROGRAMMING, V. 22D. ED., 1981, P. 117-118 (THE POLAR METHOD)
//C EXCEPT THAT LIMITS ARE INCLUDED BY MAKING THE MINIMUM VALUE OF "S"
//C BE EPS
static double randomNumberBuffer[56];
static int indx = -1;
static int jndx;
static int kndx;
static double eps;
double r1 = 1.0;
double r2 = 0.0;
if( iseed >= 0 || indx < 0 )
{
r1 = 1.0;
for( int i=0; i<100; ++i )
{
eps = r1;
r1 = r1/2.0;
if( r1+1.0 == 1.0 ) break;
}
initrn( iseed, indx, jndx, kndx, randomNumberBuffer );
}
double s;
do{
indx = indx%55 + 1;
jndx = jndx%55 + 1;
kndx = kndx%55 + 1;
double dTemp;
randomNumberBuffer[indx] = modf( randomNumberBuffer[jndx]+randomNumberBuffer[kndx], &dTemp );
r1 = 2.0 * randomNumberBuffer[indx] - 1.0;
indx = indx%55 + 1;
jndx = jndx%55 + 1;
kndx = kndx%55 + 1;
randomNumberBuffer[indx] = modf( randomNumberBuffer[jndx]+randomNumberBuffer[kndx], &dTemp );
r2 = 2.0 * randomNumberBuffer[indx] - 1.0;
s = r1*r1 + r2*r2;
if( s >= 1.0 ) continue;
if( ::fabs(s) < eps ) s = ( s >= 0 )? eps : -eps;
} while( s >= 1.0 );
return( r1 * ::sqrt( -2.0 * log10(s)/s ) );
}
//This is a translation of an old fortran library of vector algebra code. It
//was designed to be versatile and easy to use. Surprisingly, even in 2005, it
//is in quite common use in the scientific community.
//
//Conventions:
// vector are internally arrays of 3 doubles
// matrices are internally arrays of 9 doubles, indexed as follows
// 0 1 2
// 3 4 5
// 6 7 8
//
//-----------------------------------------------------------------------------
// Name: Pair()
// Description: returns a matrix that rotates X1 to coincide with Z1
// and put X2 in the plane of Z1,Z2 as close to Z2 as possible
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
Matrix_3x3 Vector_3::Pair( const Vector_3& x1, const Vector_3& x2, const Vector_3& z1, const Vector_3& z2 )
//-------------------------------------------------------------------------------------
{
Matrix_3x3 mTemp( 1.0,0.0,0.0, 0.0,1.0,0.0, 0.0,0.0,1.0 );
const Vector_3 zeroVector = Vector_3::GetZeroVector( );
const double x1Norm = x1.Norm( );
const double z1Norm = z1.Norm( );
if( x1Norm < Vector_3::MINNORM || z1Norm < Vector_3::MINNORM )
{
return( mTemp );
}
else
{
const Vector_3 x1Unit = x1.UnitV( );
const Vector_3 z1Unit = z1.UnitV( );
Vector_3 vx1 = x1.Cross( z1 ); // find the rotation axis that is perpendicular to x1 and z1 so we can place x1 on z1
//if( vx1.SquaredLength( ) < 10.0*DBL_EPSILON *10.0*DBL_EPSILON )
//{
// vx1 = Vector_3::GetXAxis( );
//}
//else
//{
// // vx1 = vx1.UnitV( ); // rescale the rotation axis
//}
//double angle1 = -Vector_3::Torsion( x1,vx1,zeroVector,z1);
const double angleTest = Vector_3::Angle( x1, Vector_3::GetZeroVector( ), z1 );
const Matrix_3x3 bMat = vx1.Rotmat( angleTest );
//}
const Vector_3 vx2 = bMat.MV(x2);
const double angle2 = -Vector_3::Torsion( vx2,z1,zeroVector,z2);
const Matrix_3x3 cMat = z1.Rotmat( angle2 ); // now do a rotation about the already fixed vector
//const double angle3 = -Vector_3::Torsion( vx2.MV( cMat ), z1, Vector_3::GetZeroVector( ), z2 );
//if( angle3 > DBL_EPSILON)
//{
// /* INFO: probably didn't get a good answer */
//}
{
//// check that the point is in the plane
//const Vector_3 vperp = z1.Cross( z2 );
//const double error = (vx2.MV( cMat )).Dot( vperp.UnitV( ) );
//if( error > DBL_EPSILON)
//{
// /* INFO: probably didn't get a good answer */
//}
}
const Matrix_3x3 mResult = cMat*bMat;
//const Vector_3 x1After_3 = mResult.MV( x1 );
//const double distSqBefore1_3 = (x1After_3-z1Unit).SquaredLength( );
//const double distSqBefore2_3 = (x1After_3+z1Unit).SquaredLength( );
//const double thirdDistSqBefore = (distSqBefore1_3<distSqBefore2_3) ? distSqBefore1_3 : distSqBefore2_3;
return( mResult );
}
}
//-----------------------------------------------------------------------------
// Name: HornQRPlane2Plane()
// Description: Returns a quaternion representing the optimal rotation of
// three ordered no-colinear points (v1, v2, v3) around their centroid
// to bring them into best alignment with three ordered no-colinear
// target points (t1, t2, t3) around their centroid.
//
// The algorithm is due to Horn, "Closed-form solution of absolute
// orientation using unit quaternions," Journal of the Optical
// Society of America A, Vol, 4, page 629, April 1987.
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
QR<double> Vector_3::HornQRPlane2Plane( const Vector_3& v1, const Vector_3& v2,const Vector_3& v3,
const Vector_3& t1, const Vector_3& t2, const Vector_3& t3)
{
const Vector_3 vcentroid = (v1+v2+v3)/3.;
const Vector_3 tcentroid = (t1+t2+t3)/3.;
const Vector_3 rv1 = v1-vcentroid;
const Vector_3 rv2 = v2-vcentroid;
const Vector_3 rv3 = v3-vcentroid;
const Vector_3 rt1 = t1-tcentroid;
const Vector_3 rt2 = t2-tcentroid;
const Vector_3 rt3 = t3-tcentroid;
const Vector_3 nv = (rv1.Cross(rv3)).UnitV();
const Vector_3 nt = (rt1.Cross(rt3)).UnitV();
const double ctheta = nv.Dot(nt);
const Vector_3 axis = (nv.Cross(nt)).UnitV();
const double stheta = (nv.Cross(nt)).Norm();
const double angp2p = atan2(stheta,ctheta);
const QR<double> qa = QR<double>(cos(angp2p/2.),sin(angp2p/2.)*axis.v[0],sin(angp2p/2.)*axis.v[1],sin(angp2p/2.)*axis.v[2]);
const Vector_3 qv1 = QR<double>(qa*(QR<double>(rv1))*qa.Conjugate()).ImVector();
const Vector_3 qv2 = QR<double>(qa*(QR<double>(rv2))*qa.Conjugate()).ImVector();
const Vector_3 qv3 = QR<double>(qa*(QR<double>(rv3))*qa.Conjugate()).ImVector();
const double C = qv1.Dot(rt1)+ qv2.Dot(rt2)+ qv3.Dot(rt3);
const double S = (qv1.Cross(rt1)+ qv2.Cross(rt2)+ qv3.Cross(rt3)).Dot(nt);
const double angp = atan2(S,C);
const QR<double> qp = QR<double>(cos(angp/2.),sin(angp/2.)*nt.v[0],sin(angp/2.)*nt.v[1],sin(angp/2.)*nt.v[2]);
return qa*qp;
}
//-----------------------------------------------------------------------------
// Name: GeneralRotation()
// Original Defect: Q-3726 larrya
// Description: For a given rotation angle about the line from v1 to v2,
// GeneralRotation computes the transformation such that for some
// input vector "vIn", an output vector "vOut" can be computed by:
// vOut = m*vIn + vTrans
// where m is the matrix returned in the output pair and vTrans
// is the vector in that pair.
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
std::pair<Matrix_3x3, Vector_3> Vector_3::GeneralRotation(
const double angle,
const Vector_3& v1,
const Vector_3& v2 )
{
const Vector_3 x = v2 - v1;
const Matrix_3x3 m = x.Rotmat( angle );
const Vector_3 y = m.MV( v1 );
const Vector_3 tran = v1 - y;
return( std::make_pair( m, tran ) );
}
//-----------------------------------------------------------------------------
// Name: GeneralRotation()
// Original Defect: Q-3726 larrya
// Description: For a given rotation angle about the line, "L",
// GeneralRotation computes the transformation such that for some
// input vector "vIn", an output vector "vOut" can be computed by:
// vOut = m*vIn + vTrans
// where m is the matrix returned in the output pair and vTrans
// is the vector in that pair.
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
std::pair<Matrix_3x3, Vector_3> Vector_3::GeneralRotation(
const double angle,
const Line_3& L )
{
return( GeneralRotation( angle, L.BasePoint(), L.BasePoint()+L.LineAxis() ) );
}
//-----------------------------------------------------------------------------
// Name: GeneralRotation()
// Original Defect: Q-3726 larrya
// Description: For a given rotation angle about the "this" line
// GeneralRotation computes the transformation such that for some
// input vector "vIn", an output vector "vOut" can be computed by:
// vOut = m*vIn + vTrans
// where m is the matrix returned in the output pair and vTrans
// is the vector in that pair.
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
std::pair<Matrix_3x3, Vector_3> Line_3::GeneralRotation( const double angle )
{
return( Vector_3::GeneralRotation( angle, *this ) );
}
//-----------------------------------------------------------------------------
// Name: Eigen1()
// Description: Computes the eigenvector of the largest eigenvalue of a 3x3 matrix
// and also returns that eigenvalue
//
// The algorithm is that of Andrews and Bernstein, 1976, Acta Cryst, A32, 504-506
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
bool Matrix_3x3::Eigen1( double& eigenvalue1, Vector_3& eigenvector1 ) const
//-------------------------------------------------------------------------------------
{
Matrix_3x3 x( *this );
for( int i=0; i<18; ++i )
{
double trace = x[0] + x[4] + x[8];
if( ::fabs(trace) < Vector_3::MINNORM )
{
trace = 1.0;
}
x = x / trace; // just to keep things in a reasonable range of values
x = x*x;
}
// by this point in the code, the matrix _should_ have been reduced to a matrix with
// a single row (and column) that is non-zero (or at least the others are very small)
// now get the eigenvalue
const Matrix_3x3 b = (*this) * x; // isolate the eigenvector
const Vector_3 v0(b[0],b[1],b[2]);
const Vector_3 v1(b[3],b[4],b[5]);
const Vector_3 v2(b[6],b[7],b[8]);
Vector_3 vResult = v0;
if( v0.Norm( ) < v1.Norm( ) )
{
vResult = v1;
}
if( vResult.Norm( ) < v2.Norm( ) )
{
vResult = v2;
}
eigenvector1 = vResult.UnitV( );
eigenvalue1 = (this->MV(eigenvector1)) .Norm( );
// test for negative eigenvalues
if( eigenvector1.Dot( (*this).MV( eigenvector1 ) )< 0.0 )
{
eigenvector1 = -eigenvector1;
eigenvalue1 = -eigenvalue1;
}
// just for testing
//const Vector_3 ev = eigenvector1.UnitV( );
//const Vector_3 enext = ev.MV( *this );
//if( (ev-enext.UnitV( )).Norm( ) > 2.0*DBL_EPSILON )
//{
// // probably a problem here
// const int i19191 = 19191;
//}
return( true );
}
//-----------------------------------------------------------------------------
// Name: Eigen3()
// Description: Computes the eigenvectors and eigenvalues for a 3x3 matrix
// The vectors are computed sequentially from the largest, which
// is then removed by deflation, etc.
//
//-----------------------------------------------------------------------------
bool Matrix_3x3::Eigen3( std::vector<double>& eigenValues, std::vector<Vector_3>& eigenVectors ) const
{
const double MINEIGENVALUE = 1.0E-16;
Matrix_3x3 m1( *this );
double evalue1;
Vector_3 evector1;
const bool b1 = m1.Eigen1( evalue1, evector1 );
if( ! b1 ) { /* some problem occurred */ };
if( ::fabs(evalue1) < MINEIGENVALUE )
{
// all three eigenvalues are zero - deal with it!
eigenValues.push_back( 0.0 );
eigenValues.push_back( 0.0 );
eigenValues.push_back( 0.0 );
eigenVectors.push_back( Vector_3( 1.0, 0.0, 0.0 ) );
eigenVectors.push_back( Vector_3( 0.0, 1.0, 0.0 ) );
eigenVectors.push_back( Vector_3( 0.0, 0.0, 1.0 ) );
return( false );
}
else
{
eigenValues.push_back( evalue1 );
eigenVectors.push_back( evector1 );
}
Matrix_3x3 m2( m1-evalue1*evector1.MatrixProduct( evector1 ) );
double evalue2;
Vector_3 evector2;
const bool b2 = m2.Eigen1( evalue2, evector2 );
if( ! b2 ) { /* some problem occurred */ };
if( ::fabs(evalue2) < MINEIGENVALUE )
{
// 2nd and 3rd eigenvalues are zero - invent 2 eigenvectors!
eigenValues.push_back( 0.0 );
eigenValues.push_back( 0.0 );
const Vector_3 randomVector( (double)rand( ), (double)rand( ), (double)rand( ) );
const Vector_3 ev2 = eigenVectors[0].Cross( randomVector );
eigenVectors.push_back( Vector_3( ev2 ) );
eigenVectors.push_back( eigenVectors[0].Cross( ev2 ) );
return( false );
}
else
{
eigenValues.push_back( evalue2 );
eigenVectors.push_back(evector2 );
}
Matrix_3x3 m3( m2-evalue2*evector2.MatrixProduct( evector2 ) );
double evalue3;
Vector_3 evector3;
const bool b3 = m3.Eigen1( evalue3, evector3 );
if( ! b3 ) { /* some problem occurred */ };
if( ::fabs(evalue3) < MINEIGENVALUE )
{
// 3rd eigenvalue is zero - calculate the eigenvector from the other two
eigenValues.push_back( 0.0 );
eigenVectors.push_back( eigenVectors[0].Cross( eigenVectors[1] ) );
return( true );
}
else
{
eigenValues.push_back( evalue3 );
eigenVectors.push_back( evector3);
}
return( true );
}
//-----------------------------------------------------------------------------
// Name: Rotmat()
// Description: Rotmat computes the matrix that would rotate an arbitrary vector
// about a specified vector by a specified angle.
//
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
Matrix_3x3 Vector_3::Rotmat( const double angle ) const
//-------------------------------------------------------------------------------------
{/* from Wikipedia http://en.wikipedia.org/wiki/Rotation_matrix
R = \begin{bmatrix}
u_x^2+(1-u_x^2)c & u_x u_y(1-c)-u_zs & u_x u_z(1-c)+u_ys
u_x u_y(1-c)+u_zs & u_y^2+(1-u_y^2)c & u_y u_z(1-c)-u_xs
u_x u_z(1-c)-u_ys & u_y u_z(1-c)+u_xs & u_z^2+(1-u_z^2)c
\end{bmatrix},
where
c = \cos\theta, s = \sin\theta.
*/
const double d = (*this).SquaredLength( );
Vector_3 v;
if ( d != 1.0 )
{
v = (*this) / sqrt( d );
}
else if ( d == 1.0 )
{
v = (*this);
}
else if ( d == 0.0 )
{
v = Vector_3::GetXAxis( );
}
// otherwise it was already a unit vector
const double& ux = v.v[0];
const double& uy = v.v[1];
const double& uz = v.v[2];
const double ux2 = ux*ux;
const double uy2 = uy*uy;
const double uz2 = uz*uz;
const double uxy = ux*uy;
const double uxz = ux*uz;
const double uyz = uy*uz;
const double s = ::sin(angle);
const double c = ::cos(angle);
const Matrix_3x3 mtemp(
ux2+(1.0-ux2)*c, uxy*(1.0-c)-uz*s, uxz*(1.0-c)+uy*s,
uxy*(1.0-c)+uz*s, uy2+(1-uy2)*c, uyz*(1.0-c)-ux*s,
uxz*(1.0-c)-uy*s, uyz*(1.0-c)+ux*s, uz2+(1.0-uz2)*c
);
return (mtemp);
}
//-----------------------------------------------------------------------------
// Name: MV
// Description: multiply a vector by a matrix
//
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
Vector_3 Vector_3::MV( const Matrix_3x3& m ) const
//-------------------------------------------------------------------------------------
{
return (Vector_3(
m.m[0]*v[0]+m.m[1]*v[1]+m.m[2]*v[2],
m.m[3]*v[0]+m.m[4]*v[1]+m.m[5]*v[2],
m.m[6]*v[0]+m.m[7]*v[1]+m.m[8]*v[2] ));
}
//-----------------------------------------------------------------------------
// Name: MatrixProduct()
// Description: return the tensor product of two vectors
//
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
Matrix_3x3 Vector_3::MatrixProduct ( const Vector_3& v_other ) const
//-------------------------------------------------------------------------------------
{
Matrix_3x3 m;
m.m[0] = v[0]*v_other[0];
m.m[1] = v[0]*v_other[1];
m.m[2] = v[0]*v_other[2];
m.m[3] = v[1]*v_other[0];
m.m[4] = v[1]*v_other[1];
m.m[5] = v[1]*v_other[2];
m.m[6] = v[2]*v_other[0];
m.m[7] = v[2]*v_other[1];
m.m[8] = v[2]*v_other[2];
return (m);
}
//-----------------------------------------------------------------------------
// Name: operator*()
// Description: multiply two matrices
//
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
inline Matrix_3x3 Matrix_3x3::operator* ( const Matrix_3x3& o ) const
//-------------------------------------------------------------------------------------
{
return(Matrix_3x3( m[0]*o.m[0] + m[1]*o.m[3] + m[2]*o.m[6],
m[0]*o.m[1] + m[1]*o.m[4] + m[2]*o.m[7],
m[0]*o.m[2] + m[1]*o.m[5] + m[2]*o.m[8],
m[3]*o.m[0] + m[4]*o.m[3] + m[5]*o.m[6],
m[3]*o.m[1] + m[4]*o.m[4] + m[5]*o.m[7],
m[3]*o.m[2] + m[4]*o.m[5] + m[5]*o.m[8],
m[6]*o.m[0] + m[7]*o.m[3] + m[8]*o.m[6],
m[6]*o.m[1] + m[7]*o.m[4] + m[8]*o.m[7],
m[6]*o.m[2] + m[7]*o.m[5] + m[8]*o.m[8] ) );
}
//NON MEMBER FUNCTIONS START HERE
#ifdef __cplusplus
//-----------------------------------------------------------------------------
// Name: operator<<()
// Description: stream a vector to the output stream
//
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
std::ostream& operator<< ( std::ostream& o, const Vector_3& v )
//-------------------------------------------------------------------------------------
{
o<<v.v[0]<<" "<<v.v[1]<<" "<<v.v[2]<<std::endl;
return o;
}
//-----------------------------------------------------------------------------
// Name: operator<<()
// Description: stream a matrix to the output stream
//
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
std::ostream& operator<< ( std::ostream& o, const Matrix_3x3& m )
//-------------------------------------------------------------------------------------
{
o << m.m[0] << ", " << m.m[1] << ", " << m.m[2] << std::endl;
o << m.m[3] << ", " << m.m[4] << ", " << m.m[5] << std::endl;
o << m.m[6] << ", " << m.m[7] << ", " << m.m[8];
return o;
}
#endif
//-----------------------------------------------------------------------------
// Name: operator*()
// Description: multiples a vector by a floating point number
//
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
Vector_3 operator* ( const double& a, const Vector_3& v )
//-------------------------------------------------------------------------------------
{
return ( Vector_3(a*v.v[0], a*v.v[1], a*v.v[2]) );
}
//-----------------------------------------------------------------------------
// Name: operator*()
// Description: multiples a matrix by a floating point number
//
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
Matrix_3x3 operator* ( const double& a, const Matrix_3x3& m )
//-------------------------------------------------------------------------------------
{
return ( Matrix_3x3(
a*m.m[0], a*m.m[1], a*m.m[2],
a*m.m[3], a*m.m[4], a*m.m[5],
a*m.m[6], a*m.m[7], a*m.m[8]
)
);
}
//////////////////////////////////////////////////////////////////////
// Plane_3 Class
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
// Name: Plane_3()
// Description: constructor
//
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
Plane_3::Plane_3( void ) :
m_planeNormal ( 0.0, 0.0, 0.0 ),
m_basePoint ( 0.0, 0.0, 0.0 ),
m_centerOfMass( 0.0, 0.0, 0.0 )
//-------------------------------------------------------------------------------------
{
}
//-----------------------------------------------------------------------------
// Name: Plane_3()
// Description: destructor
//
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
Plane_3::~Plane_3( void )
//-------------------------------------------------------------------------------------
{
}
//-----------------------------------------------------------------------------
// Name: Plane_3()
// Description: constructor
//
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
Plane_3::Plane_3( const Vector_3& direction, const Vector_3& CenterOfMass) :
m_planeNormal ( direction.UnitV( ) ),
m_basePoint ( CenterOfMass.Dot( m_planeNormal ) * m_planeNormal ),
m_centerOfMass( CenterOfMass )
//-------------------------------------------------------------------------------------
{
// center of mass could validly be any point on the plane
}
//-----------------------------------------------------------------------------
// Name: NormalVector()
// Description: returns the vector normal to a determined plane
//
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
Vector_3 Plane_3::NormalVector( void ) const
//-------------------------------------------------------------------------------------
{
return( m_planeNormal );
}
//-----------------------------------------------------------------------------
// Name: BasePoint()
// Description: returns the point in the plane where a normal to the plane from
// the origin will intersect the plane.
//
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
Vector_3 Plane_3::BasePoint( void ) const
//-------------------------------------------------------------------------------------
{
return( m_basePoint );
}
//-----------------------------------------------------------------------------
// Name: Line_3()
// Description: constructor
//
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
Line_3::Line_3( const Vector_3& direction, const Vector_3& CenterOfMass ) :
m_lineAxis( direction.UnitV( ) ),
m_basePoint( CenterOfMass ),
m_centerOfMass( CenterOfMass )
//-------------------------------------------------------------------------------------
{
// Compute the "prep", the perpendicular projector of the line.
const Matrix_3x3 mPrep = UnitMatrix( ) - LineAxis( ).MatrixProduct( LineAxis( ));
if ( direction.SquaredLength( ) == 0.0 )
{
m_lineAxis = Vector_3( 0.0 ,0.0, 0.0 );
m_basePoint = Vector_3( 0.0 ,0.0, 0.0 );
m_centerOfMass = Vector_3( 0.0 ,0.0, 0.0 );
}
else
{
m_basePoint = mPrep.MV( m_basePoint );
}
}
//-----------------------------------------------------------------------------
// Name: LineAxis()
// Description: returns the vector direction of a line
//
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
Vector_3 Line_3::LineAxis( void ) const
//-------------------------------------------------------------------------------------
{
return( m_lineAxis );
}
//-----------------------------------------------------------------------------
// Name: BasePoint()
// Description: returns the point in the line where a normal to the line from
// the origin will intersect the line.
//
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
Vector_3 Line_3::BasePoint( void ) const
//-------------------------------------------------------------------------------------
{
return( m_basePoint );
}
//-----------------------------------------------------------------------------
// Name: Torsion()
// Description: computes the torsion angle formed by 4 points. This is the angle
// between the plane formed by the first 3 and the plane formed by the last 3.
//
double Vector_3::Torsion( const Vector_3& a, const Vector_3& b, const Vector_3& c, const Vector_3& d )
//-------------------------------------------------------------------------------------
{
const Vector_3 zero( 0.0 );
Vector_3 p = a - b;
Vector_3 q = c - b;
Vector_3 x = p.Cross( q );
p = b - c;
q = d - c;
Vector_3 y = p.Cross( q );
double torsionAngle = Vector_3::Angle( x, zero, y );
q = x.Cross(y);
if( p.Dot(q.UnitV( )) > 0.0 ) torsionAngle = -torsionAngle;
return( torsionAngle );
}
//-----------------------------------------------------------------------------
// Name: Angle()
// Description: angle between the ends of three vectors. In many cases, the
// middle vector will be the origin.
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
double Vector_3::Angle( const Vector_3& a, const Vector_3& b, const Vector_3& c )
//-------------------------------------------------------------------------------------
{
const Vector_3 x = a - b;
const Vector_3 y = c - b;
const Vector_3 z = x.Cross(y);
const double xNorm = x.Norm( );
const double yNorm = y.Norm( );
const double zNorm = z.Norm( );
const double dotProduct = x.Dot( y );
double angle;
if (xNorm > Vector_3::MINNORM && yNorm > Vector_3::MINNORM) {
const double cosAngle = dotProduct/(xNorm*yNorm);
const double sinAngle = zNorm/(xNorm*yNorm);
angle = ::atan2( sinAngle, cosAngle );
}
else
{
angle = 0.0;
}
return( angle );
}
double Angle( const Vector_3& v1, const Vector_3& v2 )
{
return Vector_3::Angle( v1, Vector_3::GetZeroVector( ), v2 );
}
//-----------------------------------------------------------------------------
// Name: InertiaTensorForPoint()
// Description: computes the inertia tensor for a SINGLE point. The input also
// includes a weight. Frequently, all the weights are 1.00
//
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
Matrix_3x3 Vector_3::InertiaTensorForPoint( const double weight ) const
//-------------------------------------------------------------------------------------
{
Matrix_3x3 tensor( 0.0,0.0,0.0, 0.0,0.0,0.0, 0.0,0.0,0.0 );
const double am = weight * this->Dot( *this );
tensor.m[0] += am - this->v[0] * this->v[0];
tensor.m[4] += am - this->v[1] * this->v[1];
tensor.m[8] += am - this->v[2] * this->v[2];
tensor.m[1] -= this->v[0] * this->v[1];
tensor.m[3] = tensor.m[1];
tensor.m[2] -= this->v[0] * this->v[2];
tensor.m[6] = tensor.m[2];
tensor.m[5] -= this->v[1] * this->v[2];
tensor.m[7] = tensor.m[5];
return( tensor );
}
//-----------------------------------------------------------------------------
// Name: UNX()
// Description: Compute the rotated component of the X axis
//
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
Matrix_3x3 Matrix_3x3::UNX( void ) const
//-------------------------------------------------------------------------------------
{
const double denominator = ::fabs(m[4]+m[8]);
double numerator = m[7]-m[5];
if ( ::fabs(numerator/denominator) < Vector_3::MINNORM ) numerator = 0.0;
const double angle = ::atan2( numerator, denominator );
return( Vector_3::GetXAxis( ).Rotmat( -angle ) );
}
//-----------------------------------------------------------------------------
// Name: UNY()
// Description: Compute the rotated component of the Y axis
//
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
Matrix_3x3 Matrix_3x3::UNY( void ) const
//-------------------------------------------------------------------------------------
{
const double denominator = ::fabs(m[0]+m[8]);
double numerator = m[6]-m[2];
if ( ::fabs(numerator/denominator) < Vector_3::MINNORM ) numerator = 0.0;
const double angle = ::atan2( numerator, denominator );
return( Vector_3::GetYAxis( ).Rotmat( angle ) );
// IS THIS REALLY RIGHT X and Z are negative
// (probably due to change in position of sub determinant of the row/column)
}
//-----------------------------------------------------------------------------
// Name: UNZ()
// Description: Compute the rotated component of the Z axis
//
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
Matrix_3x3 Matrix_3x3::UNZ( void ) const
//-------------------------------------------------------------------------------------
{
const double denominator = ::fabs(m[0]+m[4]);
double numerator = m[3]-m[1];
if ( ::fabs(numerator/denominator) < Vector_3::MINNORM ) numerator = 0.0;
const double angle = ::atan2( numerator, denominator );
return( Vector_3::GetZAxis( ).Rotmat( -angle ) );
}
//-----------------------------------------------------------------------------
// Name: Line_3()
// Description: constructor
//
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
Line_3::Line_3( void ) :
m_lineAxis ( 0.0 ),
m_basePoint ( 0.0 ),
m_centerOfMass( 0.0 )
//-------------------------------------------------------------------------------------
{
}
//-----------------------------------------------------------------------------
// Name: ~Line_3()
// Description: destructor
//
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
Line_3::~Line_3( void )
//-------------------------------------------------------------------------------------
{
}
//-----------------------------------------------------------------------------
// Name: DistanceFromPlane()
// Description: computes the distance of any point from a plane by subtracting
// the vector to the point from any point in the plane and then projecting onto the
// normal to the plane.
//
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
double Plane_3::DistanceFromPlane( const Vector_3& v ) const
//-------------------------------------------------------------------------------------
{
return( ::fabs((m_basePoint - v).Dot(m_planeNormal)) );
}
//-----------------------------------------------------------------------------
// Name: DistanceFromPlane()
// Description: computes the distance of any point from a plane
//
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
double Vector_3::DistanceFromPlane( const Plane_3& p ) const
//-------------------------------------------------------------------------------------
{
return( p.DistanceFromPlane( *this ) );
}
//-----------------------------------------------------------------------------
// Name: DistanceFromLine()
// Description: computes the distance of any point from a line by subtracting the
// point from any point on the line and then projecting onto a normal to the line.
//
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
double Line_3::DistanceFromLine( const Vector_3& v ) const
//-------------------------------------------------------------------------------------
{
// Compute the "prep", the perpendicular projector of the line.
const Matrix_3x3 mPrep = UnitMatrix( ) - LineAxis( ).MatrixProduct( LineAxis( ));
const Vector_3 vTemp = mPrep.MV( v-m_basePoint ); //
return( vTemp.Norm( ) );
}
//-----------------------------------------------------------------------------
// Name: DistanceFromLine()
// Description: computes the distance of any point from a line
//
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
double Vector_3::DistanceFromLine( const Line_3& vv ) const
//-------------------------------------------------------------------------------------
{
return( vv.DistanceFromLine( *this ) );
}
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
// Name: Cart
// Description: Cart is used to generate a matrix that will convert from coordinates
// in a non-orthogonal coordinate system to an orthogonal basis. This is the solution
// for the common problem in crystallography, where coordinates are often reported in
// coordinates that are measured using the unit cell dimensions. Cart will return
// a matrix that when multiplied by a vector expressed in fractional coordinates will
// generate the corresponding position in an orthonormal system. NOTE: VERY IMPORTANT:
// The coordinates created by that operation may NOT be comparable to those generated
// by some other conversion software. Each system assumes a particular relationship
// between the two system, and they are ALL correct. Basically, the conversion matrix
// can be multiplied by ANY rotation matrix at all, and the result will still generate
// correct orthogonal coordinates, just different ones. The inverse of the matrix that
// Cart generates will convert from orthogonal coordinates back to fractional ONLY IF
// the orginal transformation was made with the same convention that Cart uses.
// The convention used in Cart is that the a-crystallographic axis will be aligned
// parallel to x, the b-axis as close as possible to y, and the c-axis by construction
// of a right handed-coordinate system.
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
Matrix_3x3 Matrix_3x3::Cart ( const double a, const double b, const double c,
const double alpha, const double beta, const double gamma )
//-------------------------------------------------------------------------------------
{
const double degreesPerRad = 180.0 / ( 4.0 * atan(1.0) );
//const double sinAlpha = sin(alpha / degreesPerRad);
//const double sinBeta = sin(beta / degreesPerRad);
const double sinGamma = sin(gamma / degreesPerRad);
const double cosAlpha = cos(alpha / degreesPerRad);
const double cosBeta = cos(beta / degreesPerRad);
const double cosGamma = cos(gamma / degreesPerRad);
const double V = a*b*c*sqrt(1.0
-cosAlpha*cosAlpha-cosBeta*cosBeta-cosGamma*cosGamma +
2.0*cosAlpha*cosBeta*cosGamma );
const Matrix_3x3 amat (
a, b*cosGamma, c*cosBeta,
0.0, b*sinGamma, c*(cosAlpha-cosBeta*cosGamma) / sinGamma,
0.0, 0.0, V/(a*b*sinGamma)
);
return( amat );
}
QR<double> Vector_3::QuaternionFromPair( const Vector_3& v1, const Vector_3& v2 )
{
const Vector_3 axis = v1.Cross( v2 ).UnitV( );
const double angle = Torsion( axis, v1, v2, Vector_3::GetZeroVector( ) );
QR<double> q(
cos( angle/2.0 ),
sin( angle/2.0 ) * axis[0],
sin( angle/2.0 ) * axis[1],
sin( angle/2.0 ) * axis[2]
);
return( q );
}
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
QR<double> randQuaternion( int& iseed )
{
const int nc = 4; // number of elements in the quaternion
double sum = 0.0;
double v[4];
QR<double> q;
do
{
sum = 0.0;
for( int i=0; i<nc; ++i )
{
v[i] = 2.0 * randf(iseed) - 1.0;
sum += v[i] * v[i];
if(sum > 1.0) break;
}
} while(sum > 1.0);
sum = ::sqrt( sum );
for( int i=0; i<4; ++i )
{
v[i] /= sum;
}
q.Set(v[0],v[1],v[2],v[3]);
return q;
}
// return the radius and the center of the circle
std::pair<double,Vector_3> CircleCenterFromThreePoints( const Vector_3& v1, const Vector_3& v2, const Vector_3& v3 )
{
// WARNINGS FROM THE SOURCE WEB PAGE
// * The denominator (mb - ma) is only zero when the lines are parallel
//in which case they must be coincident and thus no circle results.
//* If either line is vertical then the corresponding slope is infinite.
//This can be solved by simply rearranging the order of the points so that vertical lines do not occur.
std::vector<Vector_3> vlist;
vlist.push_back( v1 );
vlist.push_back( v2 );
vlist.push_back( v3 );
const Plane_3 plane = BestPlane( vlist );
int seed = 19192;
Matrix_3x3 m = Vector_3::Pair( plane.NormalVector( ), randVector(seed), Vector_3::GetZAxis( ), Vector_3::GetYAxis( ) );
const Vector_3 rot1 = m.MV( v1 );
const Vector_3 rot2 = m.MV( v2 );
const Vector_3 rot3 = m.MV( v3 );
// from http://local.wasp.uwa.edu.au/~pbourke/geometry/circlefrom3/
const double x1 = rot1[0];
const double x2 = rot2[0];
const double x3 = rot3[0];
const double y1 = rot1[1];
const double y2 = rot2[1];
const double y3 = rot3[1];
if ( ::fabs(x2-x1) == 0.0 || ::fabs(x3-x2) == 0.0 )
{
return( CircleCenterFromThreePoints( v3,v2,v1 ) );
}
const double ma = (y2-y1) / (x2-x1);
const double mb = (y3-y2) / (x3-x2);
if ( ma==mb )
{
return( std::make_pair(DBL_MAX, Vector_3( DBL_MAX )) );
}
const double x = ma*mb*(y1-y3) + mb*(x1+x2) - ma*(x2+x3) / ( 2.0 * (mb-ma ) );
const double y = -(1.0/ma)*(x-(x1+x2)/2.0)+ (y1+y2)/2.0;
const Vector_3 centerInXYPlane = Vector_3( x,y,rot1[2] ); // pick up the z-coordinate of the rotated point
const Vector_3 centerInOriginal = centerInXYPlane.MV( m.Inver( ) );
const double radius = (centerInOriginal-v1).Norm( );
return( std::make_pair( radius, centerInOriginal ) );
}
Line_3 Plane_3::Intersect( const Plane_3& p ) const
{
const Vector_3& n1 = (*this).m_planeNormal;
const Vector_3& n2 = p.m_planeNormal;
const Vector_3& p1 = (*this).m_basePoint;
const Vector_3& p2 = p.m_basePoint;
const Vector_3 vtest = n1.Cross( n2 );
Line_3 result;
if ( vtest.SquaredLength( ) < 0.005*0.005 )
{
result = Line_3( Vector_3(0.0,0.0,0.0), Vector_3(0.0,0.0,0.0 ) );
}
else
{
const double& n11 = n1[0];
const double& n12 = n1[1];
const double& n13 = n1[2];
const double& n21 = n2[0];
const double& n22 = n2[1];
const double& n23 = n2[2];
double x1,x2,x3;
if ( ::fabs(n13*n21 - n11*n23) > Vector_3::MINNORM &&
::fabs(n13*n21 - n11*n23) >= ::fabs(n13*n22 - n12*n23) &&
::fabs(n13*n21 - n11*n23) >= ::fabs(n12*n21 - n11*n22) )
{
x2 = 0.0;
x1 = ( n13*p2.Dot(n2) - n23*p1.Dot(n1)) / (n13*n21 - n11*n23);
x3 = (-n11*p2.Dot(n2) + n21*p1.Dot(n1)) / (n13*n21 - n11*n23);
}
else if ( ::fabs(n13*n22 - n12*n23) > Vector_3::MINNORM &&
::fabs(n13*n22 - n12*n23) >= ::fabs(n12*n21 - n11*n22))
{
x1 = 0.0;
x2 = ( n13*p2.Dot(n2) - n23*p1.Dot(n1)) / (n13*n22 - n12*n23);
x3 = (-n12*p2.Dot(n2) + n22*p1.Dot(n1)) / (n13*n22 - n12*n23);
}
else if ( ::fabs(n12*n21 - n11*n22) > Vector_3::MINNORM )
{
x3 = 0.0;
x1 = ( n12*p2.Dot(n2) - n22*p1.Dot(n1)) / (n12*n21 - n11*n22);
x2 = (-n11*p2.Dot(n2) + n21*p1.Dot(n1)) / (n12*n21 - n11*n22);
}
else
{
// something awful has happened !
x1 = 0.0;
x2 = 0.0;
x3 = 0.0;
}
const Vector_3 pointOnLine( Vector_3( x1,x2,x3 ) );
const Vector_3 vtestUnit = vtest.UnitV( );
const double dot = vtestUnit.Dot( pointOnLine );
Vector_3 v = pointOnLine - dot*vtestUnit;
#ifdef DEBUG
if ( v.Norm( ) > 10000.0 ) {
const int i19191 = 19191;
}
#endif
result = Line_3( vtest.UnitV(), v );
}
return( result );
}
| true |
2ca11ae7599e76d999c79d86232a904a13e22cc9 | C++ | iamjhpark/BOJ | /_2234.cpp | UTF-8 | 3,006 | 2.8125 | 3 | [] | no_license | #include <iostream>
#include <bitset>
#include <vector>
#include <queue>
#include <algorithm>
#include <cstring>
using namespace std;
vector<int> answer;
bool check[50][50];
void BFS(vector<vector<int>> &map, int n, int m) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (check[i][j]) {
queue<pair<int, int>> q;
q.push(make_pair(i, j));
check[i][j] = false;
int count = 1;
while (!q.empty()) {
pair<int, int> current = q.front();
int currentX = current.first;
int currentY = current.second;
q.pop();
int direction = map[currentX][currentY];
bitset<4> bs = bitset<4>(direction);
for (int k = 0; k < 4; k++) {
if (bs[k] == 0) {
int nextX = currentX;
int nextY = currentY;
if (k == 0) {
nextY -= 1;
} else if (k == 1) {
nextX -= 1;
} else if (k == 2) {
nextY += 1;
} else if (k == 3) {
nextX += 1;
}
if (nextX > -1 && nextX < m && nextY > -1 && nextY < n && check[nextX][nextY]) {
count++;
check[nextX][nextY] = false;
q.push(make_pair(nextX, nextY));
}
}
}
}
answer.push_back(count);
}
}
}
}
int main(void) {
int n;
scanf("%d", &n);
int m;
scanf("%d", &m);
memset(check, true, sizeof(check));
vector<vector<int>> map(m, vector<int>(n));
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int el;
scanf("%d", &el);
map[i][j] = el;
}
}
BFS(map, n, m);
long long count = answer.size();
printf("%lld\n", count);
int max = *max_element(answer.begin(), answer.end());
printf("%d\n", max);
answer = vector<int>();
vector<int> walls = { 1, 2, 4, 8 };
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < 4; k++) {
if ((map[i][j] & walls[k]) == walls[k]) {
map[i][j] = map[i][j] & (15 - walls[k]);
memset(check, true, sizeof(check));
BFS(map, n, m);
map[i][j] = map[i][j] | walls[k];
}
}
}
}
int anotherMax = *max_element(answer.begin(), answer.end());
printf("%d\n", anotherMax);
return 0;
}
| true |
444a2d04dcd7ad350f93cdba9a46b5dc19b5c844 | C++ | NicolasMrc/exercices-c2 | /Vector.h | UTF-8 | 455 | 2.515625 | 3 | [] | no_license | //
// Created by Nicolas Mercier on 28/09/2016.
//
#ifndef TP2C_VECTOR_H
#define TP2C_VECTOR_H
/**
* Classe Vetcor
*/
class Vector {
private:
int *t;
int taille;
public:
Vector(int taille);
void afficher();
void saisie();
long operator=(Vector v);
Vector operator+(Vector v);
Vector operator-(Vector v);
Vector operator*(Vector v);
void operator<<(Vector v);
void operator>>(Vector *v);
};
#endif //TP2C_VECTOR_H
| true |
a358a38ded3a8f676931eeee1ce7fbc2d96d3f66 | C++ | to5ta/massive_OpenCL | /exam_excercises/Aufgabe1/Histogram.cpp | UTF-8 | 22,215 | 2.578125 | 3 | [] | no_license | #include "Histogram.h"
#include <cstring>
#include <vector>
#include <assert.h>
#include <cmath>
#include <unistd.h>
#include "../shared/ansi_colors.h"
#include "../shared/clstatushelper.h"
OpenCLMgr *Histogram::OpenCLmgr = nullptr;
Histogram::Histogram(int pixel_per_workitem,
int group_size,
int atomic_add,
int out_of_order){
this->pixels_per_workitem = pixel_per_workitem;
this->group_size = group_size;
this->out_of_order = out_of_order;
if(out_of_order){
printf(ANSI_COLOR_YELLOW);
printf(ANSI_BOLD);
printf("Out-of-Order OpenCL Command Queue!\n");
printf(ANSI_COLOR_RESET);
OpenCLmgr = new OpenCLMgr( CL_QUEUE_PROFILING_ENABLE | CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE );
} else {
OpenCLmgr = new OpenCLMgr( CL_QUEUE_PROFILING_ENABLE );
}
OpenCLmgr->loadFile("../Histogram3.cl");
// OpenCLmgr->setVariable("DEBUG_PRINT", 1);
OpenCLmgr->setVariable("PIXEL_PER_WORKITEM", pixel_per_workitem);
OpenCLmgr->setVariable("GROUP_ATOMIC_ADD", atomic_add);
OpenCLmgr->buildProgram();
const char *kernel_names[] = {"calcStatistic_kernel", "reduceStatistic_kernel"};
OpenCLmgr->createKernels(kernel_names, 2);
}
Histogram::~Histogram(){
delete [] hist;
delete [] rgb_data;
delete [] local_histograms_gpu;
delete [] local_histograms_cpu;
delete OpenCLmgr;
}
void
Histogram::loadFile(char* file_path, int channels){
printf("Loading file: %s\n", file_path);
int w, h, bpp;
unsigned char* rgb;
rgb = stbi_load( file_path, &w, &h, &bpp, 0 );
// rgb is now three bytes per pixel, width*height size. Or nullptr if load failed.
printf("%-25s: %12i\n", "Bytes per Pixel", bpp);
printf("%-25s: %12i\n", "Width", w);
printf("%-25s: %12i\n", "Height", h);
printf("%-25s: %12i\n", "Pixels", w*h);
printf("%-25s: %12i\n", "Bytes per Pixel", bpp);
this->height = h;
this->width = w;
this->bytes_per_pixel = bpp;
if(bpp!=channels){
printf("ERROR: bpp and channels count does not match!");
}
if(rgb_data!=nullptr) {
delete[] rgb_data;
rgb_data = nullptr;
}
if(hist!=nullptr){
delete [] hist;
hist= nullptr;
}
if(hist_cpu!=nullptr){
delete [] hist_cpu;
hist_cpu= nullptr;
}
hist = new cl_uint[256]();
assert(hist!= nullptr);
hist_cpu = new cl_uint[256]();
assert(hist_cpu!= nullptr);
rgb_data = new unsigned char[width*height*channels]();
memcpy(rgb_data, rgb, width*height*channels);
stbi_image_free( rgb );
buffersize = width*height*channels;
datalength = buffersize;
printf("%-25s: %12i\n", "Buffersize (bytes)", buffersize);
pixels_per_group = pixels_per_workitem * group_size;
printf("\n%-25s: %12i\n", "Pixels per Workitem", pixels_per_workitem);
printf("%-25s: %12i\n", "Pixels per Group", pixels_per_group);
printf("%-25s: %12i\n", "Group Size", group_size);
int _gws = ((width*height)+pixels_per_group-1)/pixels_per_group * group_size;
gws[0] = size_t(_gws);
lws[0] = size_t(group_size);
workgroups = gws[0]/lws[0];
printf("\n%-25s: %12i\n", "GLOBAL WORK SIZE",int(gws[0]));
printf("%-25s: %12i\n", "LOCAL WORK SIZE",int(lws[0]));
printf("%-25s: %12i\n", "WORK GROUPS", workgroups);
printf("%-25s: %12i\n", "GWS * Pixels per Group", workgroups*pixels_per_group);
// CL_DEVICE_MAX_WORK_GROUP_SIZE
if(workgroups>1024){
printf(ANSI_BOLD);
printf(ANSI_COLOR_RED);
printf("ERROR: GROUP SIZE < 1024 (HARDWARE MAX)!");
printf(ANSI_COLOR_RESET);
exit(0);
}
local_histograms_gpu = new cl_uint[workgroups*256]();
local_histograms_cpu = new cl_uint[workgroups*256]();
assert(local_histograms_gpu!= nullptr);
assert(local_histograms_cpu!= nullptr);
return;
}
void
Histogram::plotHistogramTable(cl_uint * histo) {
for (int j = 0; j < 256; ++j) {
printf("[%3i]: %12i; ", j, histo[j]);
if ((j + 1) % 10 == 0) {
printf("\n");
}
}
printf("\n\n");
}
void
Histogram::plotHistogram(cl_uint * histogram){
printf(ANSI_BOLD);
if(histogram== nullptr){
printf("histogram == nullptr!");
return;
}
// find max
int max_bin = 0;
for (int l = 0; l < 256; ++l) {
if(histogram[l]>max_bin){
max_bin = histogram[l];
}
}
cl_uint total_count = 0;
printf(" ");
for (int i = 0; i < 255; ++i) {
printf("-");
}
printf("\n");
for (int p = 20; p >= 0; --p) {
printf("%3i% |", p*5);
for (int b = 0; b < 256; ++b) {
float c = (float)(histogram[b]);
if(p==0){
total_count += histogram[b];
}
float s = (float)(max_bin);
float percent = c/s *100.f;
if(percent>(p*5)){
printf("#");
}
else{
printf(" ");
}
}
printf("\n");
}
printf(" ");
for (int k = 0; k < 52; ++k) {
printf("%-5c", '^');
}
printf("\n ");
for (int k = 0; k < 52; ++k) {
printf("%-5i", k*5);
}
printf("\n\n");
printf("Sum Bins : %12i\n", total_count);
printf("Pixels : %12i\n", height*width);
printf(ANSI_COLOR_RESET);
}
void
Histogram::plotImageData(int max_id){
if(max_id!=0){
printf("%3i Elements: ",max_id);
} else {
printf("\n\n");
}
for(int y=0; y<height; y++){
for(int x=0; x<width; x++){
if(max_id>0 && max_id<=width*y+x){
printf("\n");
return;
}
if(max_id<0 && (width*height)-(width*y+x) > abs(max_id) ){
continue;
}
for (int i = 0; i < 3; ++i) {
int val = rgb_data[x*3+y*3*width+i];
if(val>255){
printf(ANSI_COLOR_RED);
printf("%3i", val);
printf(ANSI_COLOR_RESET);
}
else
printf("%3i", val);
if(i<3)
printf("|");
}
printf(" ");
}
if(max_id==0){
printf("\n");
}
}
printf("\n");
}
void
Histogram::calcHistCPU() {
for (int i = 0; i < width*height*3; i+=3) {
float r = (float)(rgb_data[i]);
float g = (float)(rgb_data[i+1]);
float b = (float)(rgb_data[i+2]);
float lum = 0.2126*r + 0.7152*g + 0.0722*b;
hist_cpu[int(lum)]++;
// fake local hists like on gpu, step 1
local_histograms_cpu[int(lum) + ((i/(pixels_per_workitem*group_size*3))*256)]++;
}
}
void
Histogram::plotLocalHistograms(cl_uint * local_histo){
for (int i = 0; i < workgroups; ++i) {
int sum=0;
printf("LOCAL HISTOGRAM: %i\n", i);
for (int j = 0; j < 256; ++j) {
printf("[%3i]: %12i; ",j, local_histo[i*256+j]);
sum += local_histo[i*256+j];
if((j+1)%10==0)
printf("\n");
}
printf("\nSum: %d\n", sum);
}
}
void
Histogram::compareGPUvsCPU(){
for (int i = 0; i < workgroups; ++i) {
int compare_res = memcmp(local_histograms_cpu+(i*256),
local_histograms_gpu+(i*256),
256*sizeof(cl_uint));
// int compare_res = memcmp(local_histograms_cpu, local_histograms_gpu, 256*sizeof(cl_uint));
if(compare_res==0){
printf(ANSI_COLOR_BRIGHTGREEN);
printf(ANSI_BOLD);
printf("Local Histogram %3i OK!\n", i);
printf(ANSI_COLOR_RESET);
} else {
int _diff = 0;
for (int j = 0; j < 256; ++j) {
cl_uint localcpu= local_histograms_cpu[i*256+j];
cl_uint localgpu= local_histograms_gpu[i*256+j];
if(local_histograms_cpu[i*256+j] != local_histograms_gpu[i*256+j]){
printf(ANSI_COLOR_RED);
printf("Local Histogram %3i differs from CPU at %i: ", i, j);
printf("CPU: %i, ", local_histograms_cpu[i*256+j]);
printf("GPU: %i\n", local_histograms_gpu[i*256+j]);
_diff++;
break;
}
}
printf(ANSI_COLOR_RESET);
if(_diff==0)
printf("Local Histogram %3i OK? MEMCMP!=0 but no difference detected!\n", i);
}
}
}
void
Histogram::calcHistGPU(){
cl_int status=0;
if(out_of_order){
calcHistGPUwithEvents();
return;
}
cl_mem rgb_buffer = clCreateBuffer(OpenCLmgr->context,
CL_MEM_READ_ONLY,
buffersize*sizeof(u_char),
nullptr,
nullptr);
status = clEnqueueWriteBuffer(OpenCLmgr->commandQueue,
rgb_buffer,
CL_TRUE,
0,
buffersize*sizeof(u_char),
rgb_data,
0,
nullptr,
nullptr);
check_error(status);
cl_mem all_hist_buffer = clCreateBuffer(OpenCLmgr->context,
CL_MEM_READ_WRITE,
workgroups*256*sizeof(cl_uint),
nullptr,
nullptr);
cl_mem hist_buffer = clCreateBuffer(OpenCLmgr->context,
CL_MEM_READ_WRITE,
256*sizeof(cl_uint),
nullptr,
nullptr);
status = clEnqueueWriteBuffer(OpenCLmgr->commandQueue,
all_hist_buffer,
CL_TRUE,
0,
workgroups*256*sizeof(cl_uint),
local_histograms_gpu,
0,
nullptr,
nullptr);
check_error(status);
status = clSetKernelArg(OpenCLmgr->kernels["calcStatistic_kernel"],
0,
sizeof(cl_mem),
(void *) &rgb_buffer );
check_error(status);
status = clSetKernelArg(OpenCLmgr->kernels["calcStatistic_kernel"],
1,
sizeof(uint),
(void *) &buffersize );
check_error(status);
status = clSetKernelArg(OpenCLmgr->kernels["calcStatistic_kernel"],
2,
sizeof(cl_mem),
(void *) &all_hist_buffer );
check_error(status);
status = clEnqueueNDRangeKernel(OpenCLmgr->commandQueue,
OpenCLmgr->kernels["calcStatistic_kernel"],
1,
nullptr,
gws,
lws,
0,
nullptr,
nullptr);
check_error(status);
status = clEnqueueReadBuffer( OpenCLmgr->commandQueue,
all_hist_buffer,
CL_TRUE,
0,
workgroups*256*sizeof(cl_uint),
local_histograms_gpu,
0,
nullptr,
nullptr);
check_error(status);
// reduce
status = clSetKernelArg(OpenCLmgr->kernels["reduceStatistic_kernel"],
0,
sizeof(cl_mem),
(void *) &all_hist_buffer );
check_error(status);
status = clSetKernelArg(OpenCLmgr->kernels["reduceStatistic_kernel"],
1,
sizeof(int),
(void *) &workgroups );
check_error(status);
status = clSetKernelArg(OpenCLmgr->kernels["reduceStatistic_kernel"],
2,
sizeof(cl_mem),
(void *) &hist_buffer );
check_error(status);
status = clEnqueueNDRangeKernel(OpenCLmgr->commandQueue,
OpenCLmgr->kernels["reduceStatistic_kernel"],
1,
nullptr,
lws,
lws,
0,
nullptr,
nullptr);
check_error(status);
status = clEnqueueReadBuffer( OpenCLmgr->commandQueue,
hist_buffer,
CL_TRUE,
0,
256*sizeof(int),
this->hist,
0,
nullptr,
nullptr);
check_error(status);
clFinish(OpenCLmgr->commandQueue);
clReleaseMemObject(rgb_buffer);
clReleaseMemObject(hist_buffer);
clReleaseMemObject(all_hist_buffer);
}
void
Histogram::calcHistGPUwithEvents(){
cl_int status=0;
cl_mem rgb_buffer = clCreateBuffer(OpenCLmgr->context,
CL_MEM_READ_ONLY,
buffersize*sizeof(u_char),
nullptr,
nullptr);
status = clEnqueueWriteBuffer(OpenCLmgr->commandQueue,
rgb_buffer,
CL_TRUE,
0,
buffersize*sizeof(u_char),
rgb_data,
0,
nullptr,
nullptr);
check_error(status);
cl_mem all_hist_buffer = clCreateBuffer(OpenCLmgr->context,
CL_MEM_READ_WRITE,
workgroups*256*sizeof(cl_uint),
nullptr,
nullptr);
cl_mem hist_buffer = clCreateBuffer(OpenCLmgr->context,
CL_MEM_READ_WRITE,
256*sizeof(cl_uint),
nullptr,
nullptr);
status = clEnqueueWriteBuffer(OpenCLmgr->commandQueue,
all_hist_buffer,
CL_TRUE,
0,
workgroups*256*sizeof(cl_uint),
local_histograms_gpu,
0,
nullptr,
nullptr);
check_error(status);
status = clSetKernelArg(OpenCLmgr->kernels["calcStatistic_kernel"],
0,
sizeof(cl_mem),
(void *) &rgb_buffer );
check_error(status);
status = clSetKernelArg(OpenCLmgr->kernels["calcStatistic_kernel"],
1,
sizeof(uint),
(void *) &buffersize );
check_error(status);
status = clSetKernelArg(OpenCLmgr->kernels["calcStatistic_kernel"],
2,
sizeof(cl_mem),
(void *) &all_hist_buffer );
check_error(status);
// create events
cl_event calcStatisticEvent, reduceStatisticEvent;
status = clEnqueueNDRangeKernel(OpenCLmgr->commandQueue,
OpenCLmgr->kernels["calcStatistic_kernel"],
1,
nullptr,
gws,
lws,
0,
nullptr,
&calcStatisticEvent);
check_error(status);
// rather for debugging
status = clEnqueueReadBuffer( OpenCLmgr->commandQueue,
all_hist_buffer,
CL_TRUE,
0,
workgroups*256*sizeof(cl_uint),
local_histograms_gpu,
1,
&calcStatisticEvent,
nullptr);
check_error(status);
// reduce
status = clSetKernelArg(OpenCLmgr->kernels["reduceStatistic_kernel"],
0,
sizeof(cl_mem),
(void *) &all_hist_buffer );
check_error(status);
status = clSetKernelArg(OpenCLmgr->kernels["reduceStatistic_kernel"],
1,
sizeof(int),
(void *) &workgroups );
check_error(status);
status = clSetKernelArg(OpenCLmgr->kernels["reduceStatistic_kernel"],
2,
sizeof(cl_mem),
(void *) &hist_buffer );
check_error(status);
status = clEnqueueNDRangeKernel(OpenCLmgr->commandQueue,
OpenCLmgr->kernels["reduceStatistic_kernel"],
1,
nullptr,
lws,
lws,
1,
&calcStatisticEvent,
&reduceStatisticEvent);
check_error(status);
status = clEnqueueReadBuffer( OpenCLmgr->commandQueue,
hist_buffer,
CL_TRUE,
0,
256*sizeof(int),
this->hist,
1,
&reduceStatisticEvent,
nullptr);
check_error(status);
clReleaseMemObject(rgb_buffer);
clReleaseMemObject(hist_buffer);
clReleaseMemObject(all_hist_buffer);
// performance measuring
cl_ulong calc_queue_time,
calc_start_time,
calc_end_time,
reduce_queue_time,
reduce_start_time,
reduce_end_time;
size_t return_bytes;
status = clGetEventProfilingInfo(calcStatisticEvent,
CL_PROFILING_COMMAND_QUEUED,
sizeof(cl_ulong),
&calc_queue_time,
&return_bytes);
check_error(status);
status = clGetEventProfilingInfo(calcStatisticEvent,
CL_PROFILING_COMMAND_START,
sizeof(cl_ulong),
&calc_start_time,
&return_bytes);
status = clGetEventProfilingInfo(calcStatisticEvent,
CL_PROFILING_COMMAND_END,
sizeof(cl_ulong),
&calc_end_time,
&return_bytes);
status = clGetEventProfilingInfo(reduceStatisticEvent,
CL_PROFILING_COMMAND_QUEUED,
sizeof(cl_ulong),
&reduce_queue_time,
&return_bytes);
status = clGetEventProfilingInfo(reduceStatisticEvent,
CL_PROFILING_COMMAND_START,
sizeof(cl_ulong),
&reduce_start_time,
&return_bytes);
status = clGetEventProfilingInfo(reduceStatisticEvent,
CL_PROFILING_COMMAND_END,
sizeof(cl_ulong),
&reduce_end_time,
&return_bytes);
printf("\nProfiling 'calcStatistic':\n");
printf(" Queue: %u Ns\n", calc_queue_time);
printf(" Start: %u Ns\n", calc_start_time);
printf(" End : %u Ns\n", calc_end_time);
printf(" Queue Time: %10.3f ms\n", double(calc_start_time-calc_queue_time)/1000000.f);
printf(" Exec Time : %10.3f ms\n", double(calc_end_time-calc_start_time)/1000000.f);
printf("\n IDLE Time : %10.3f ms\n", double(reduce_start_time-calc_end_time)/1000000.f);
printf("\nProfiling 'reduceStatistic':\n");
printf(" Queue: %u Ns\n", reduce_queue_time);
printf(" Start: %u Ns\n", reduce_start_time);
printf(" End : %u Ns\n", reduce_end_time);
printf(" Queue Time: %10.3f ms\n", double(reduce_start_time-calc_queue_time)/1000000.f);
printf(" Exec Time : %10.3f ms\n", double(reduce_end_time-calc_start_time)/1000000.f);
} | true |
d832a73844e2b25f490c3ece6e559b07f4526b03 | C++ | daria-kulikova/linear-congruential-generator | /lcg.cpp | WINDOWS-1251 | 23,794 | 3.09375 | 3 | [] | no_license | #include <algorithm>
#include <iostream>
#include <map>
#include <math.h>
#include <vector>
#include <omp.h>
#include <ctime>
#include "lcg.h"
//
inline long long Generator::LCG::Add(const long long num1, const long long num2) {
return (num1 + num2) % m;
}
//
inline long long Generator::LCG::Subtr(const long long num1, const long long num2) {
return (num1 - num2 + m) % m;
}
//
inline long long Generator::LCG::Mult(const long long num1, const long long num2) {
return (num1 * num2) % m;
}
//
inline long long Generator::LCG::Div(const long long num1, const long long num2) {
return Mult(num1, Pow(num2, m - 2));
}
//
inline long long Generator::LCG::Pow(const long long num, const long long pow) {
if (pow == 0) {
return 1;
}
if (pow & 1) {
return Mult(Pow(num, pow - 1), num);
}
long long result = Pow(num, pow >> 1);
return Mult(result, result);
}
// X eps, [0, 1]
inline double Generator::LCG::GetEps(const long long x) {
return double(x) / m;
}
// from X
inline long long Generator::LCG::GetX(const long long from) {
return Add(Mult(a, from), c);
}
// eps
inline double Generator::LCG::Get() {
x = GetX(x);
return GetEps(x);
}
// "" X k from
long long Generator::LCG::GetXTransition(const long long from, const long long k) {
long long a_to_k_pow = Pow(a, k);
long long b = Subtr(a, 1);
return Add(Mult(a_to_k_pow, from), Div(Mult(Subtr(a_to_k_pow, 1), c), b));
}
// "" eps k
double Generator::LCG::GetTransition(const long long k) {
x = GetXTransition(x, k);
return GetEps(x);
}
// ""
//
bool Generator::LCG::Compare(const long long k) {
double current_x = x;
double sequential_result = 0;
for (long long i = 0; i < k; ++i) {
sequential_result = Get();
}
x = current_x;
double result_by_transition = GetTransition(k);
x = current_x;
std::cout << "k = " << k << std::endl;
std::cout << "Sequential result = " << sequential_result << std::endl;
std::cout << "Result by transition = " << result_by_transition << std::endl;
if (std::fabs(sequential_result - result_by_transition) < 1e-10) {
std::cout << "The values are equal" << std::endl;
std::cout << std::endl;
return true;
}
std::cout << "The values are NOT equal!" << std::endl;
std::cout << std::endl;
return false;
}
double Generator::LCG::GoldsteinApproximation(const long long degrees_of_freedom) {
std::vector<double> a{1.0000886, 0.4713941, 0.0001348028, -0.008553069,
0.00312558, -0.0008426812, 0.00009780499};
std::vector<double> b{-0.2237368, 0.02607083, 0.01128186, -0.01153761,
0.005169654, 0.00253001, -0.001450117};
std::vector<double> c{-0.01513904, -0.008986007, 0.02277679, -0.01323293,
-0.006950356, 0.001060438, 0.001565326};
//
double alpha = 0.90;
double d = 2.0637 * pow(log(1 / (1 - alpha)) - 0.16, 0.4274) - 1.5774;
double x2 = 0;
for (int i = 0; i <= 6; ++i) {
x2 += pow(degrees_of_freedom, -i / 2.0) * pow(d, i) * (a[i] + b[i]
/ degrees_of_freedom + c[i] / (degrees_of_freedom * degrees_of_freedom));
}
x2 = degrees_of_freedom * pow(x2, 3);
return x2;
}
// -
bool Generator::LCG::X2(const std::vector<long long>& culc_v, const std::vector<double>& theor_v,
const long long degrees_of_freedom) {
double x2 = 0;
for (long long i = 0; i < culc_v.size(); ++i) {
if (theor_v[i] == 0) {
continue;
}
double num = culc_v[i] - theor_v[i];
x2 += num * num / theor_v[i];
}
double theoretical_x2 = GoldsteinApproximation(degrees_of_freedom);
std::cout << "Calculated value of X2 = " << x2 << std::endl;
std::cout << "Theoretical value of X2 = " << theoretical_x2 << std::endl;
if (x2 <= theoretical_x2 + 1e-10) {
std::cout << "Test passed" << std::endl << std::endl;
return true;
}
std::cout << "Test failed!" << std::endl << std::endl;
x = x0;
return false;
}
bool Generator::LCG::EquidistributionTest() {
double start = clock();
std::cout << "Equidistribution Test" << std::endl;
x = x0;
int d = 10;
//v[i] - i {y[i]},
// y[i] = eps[i] * d, eps -
// [0, 1]
std::vector<long long> v(d, 0);
for (long long i = 0; i < n; ++i) {
int y = Get() * d;
++v[y];
}
//p[i] - i
std::vector<double> p(d, 0);
for (int i = 0; i < d; ++i) {
p[i] = 1.0 / d;
p[i] *= n;
}
x = x0;
bool is_test_passed = X2(v, p, d - 1);
double finish = clock();
// std::cout << "Sequential runtime = " << (finish - start) / 1000.0
// << std::endl;
// std::cout << std::endl;
return is_test_passed;
}
bool Generator::LCG::EquidistributionTestParallel() {
double start = clock();
std::cout << "Equidistribution Test Parallel" << std::endl;
x = x0;
int d = 10;
// ,
//(= )
const int num_threads = std::min(sqrt(n), 1e5);
//v_threads[i][j] - j
// {y[j]} i-
std::vector<std::vector<long long>> v_threads(num_threads,
std::vector<long long>(d, 0));
//
long long step = n / num_threads;
if (n % num_threads) {
++step;
}
//from[i] - i-
std::vector<long long> from(num_threads, 0);
from[0] = GetX(x0);
++v_threads[0][GetEps(from[0]) * d];
for (int i = 1; i < num_threads; ++i) {
from[i] = GetXTransition(from[i - 1], step);
++v_threads[i][GetEps(from[i]) * d];
}
#pragma omp parallel for num_threads(num_threads)
for (int i = 0; i < num_threads; ++i) {
for (int j = 1; j < step && i * step + j < n; ++j) {
from[i] = GetX(from[i]);
++v_threads[i][GetEps(from[i]) * d];
}
}
//
std::vector<long long> v(d, 0);
for (int i = 0; i < d; ++i) {
for (int j = 0; j < num_threads; ++j) {
v[i] += v_threads[j][i];
}
}
//p[i] - i
std::vector<double> p(d, 0);
for (int i = 0; i < d; ++i) {
p[i] = 1.0 / d;
p[i] *= n;
}
x = x0;
bool is_test_passed = X2(v, p, d - 1);
double finish = clock();
// std::cout << "Parallel runtime = " << (finish - start) / 1000.0 << std::endl;
// std::cout << std::endl;
return is_test_passed;
}
bool Generator::LCG::SerialTest() {
double start = clock();
std::cout << "Serial Test" << std::endl;
x = x0;
int d = 10;
//
int k = 2;
int size = d * d;
long long num_groups = n / k;
//v[i] - i
std::vector<long long> v(size, 0);
for (long long i = 0; i < num_groups; ++i) {
int s = 0;
for (int j = 0; j < k; ++j) {
s = s * d + Get() * d;
}
++v[s];
}
//p[i] - i
std::vector<double> p(size, 0);
for (int i = 0; i < size; ++i) {
p[i] = 1.0 / size;
p[i] *= num_groups;
}
x = x0;
bool is_test_passed = X2(v, p, size - 1);
double finish = clock();
// std::cout << "Sequential runtime = " << (finish - start) / 1000.0
// << std::endl;
// std::cout << std::endl;
return is_test_passed;
}
bool Generator::LCG::SerialTestParallel() {
double start = clock();
std::cout << "Serial Test Parallel" << std::endl;
x = x0;
int d = 10;
//
int k = 2;
int size = d * d;
long long num_groups = n / k;
// ,
//(= )
const int num_threads = std::min(sqrt(num_groups), 1e5);
//v_threads[i][j] - j i-
std::vector<std::vector<long long>> v_threads(num_threads,
std::vector<long long>(size, 0));
//
long long step = num_groups / num_threads;
if (num_groups % num_threads) {
++step;
}
//from[i] - i-
std::vector<long long> from(num_threads, 0);
from[0] = GetX(x0);
for (int i = 1; i < num_threads; ++i) {
from[i] = GetXTransition(from[i - 1], step * k);
}
#pragma omp parallel for num_threads(num_threads)
for (int i = 0; i < num_threads; ++i) {
for (int j = 0; j < step && i * step + j < num_groups; ++j) {
int s = 0;
for (int l = 0; l < k; ++l) {
s = s * d + GetEps(from[i]) * d;
from[i] = GetX(from[i]);
}
++v_threads[i][s];
}
}
//
std::vector<long long> v(size, 0);
for (int i = 0; i < size; ++i) {
for (int j = 0; j < num_threads; ++j) {
v[i] += v_threads[j][i];
}
}
//p[i] - i
std::vector<double> p(size, 0);
for (int i = 0; i < size; ++i) {
p[i] = 1.0 / size;
p[i] *= num_groups;
}
x = x0;
bool is_test_passed = X2(v, p, size - 1);
double finish = clock();
// std::cout << "Parallel runtime = " << (finish - start) / 1000.0 << std::endl;
// std::cout << std::endl;
return is_test_passed;
}
bool Generator::LCG::PokerTest() {
double start = clock();
std::cout << "Poker Test" << std::endl;
x = x0;
int d = 10;
//
int length = 5;
int categories = 7;
long long num_groups = n / length;
//v[i] - i- ,
//0- -
//1- - 1
//2- - 2
//3- - 1
//4- - 1 1
//5- - 1
//6- -
std::vector<long long> v(categories, 0);
for (long long i = 0; i < num_groups; ++i) {
std::map<int, int> y;
for (int j = 0; j < length; ++j) {
y[Get() * d]++;
}
if (y.size() == 5) {
v[0]++;
continue;
}
if (y.size() == 4) {
v[1]++;
continue;
}
if (y.size() == 1) {
v[6]++;
continue;
}
int max_count = 0;
for (auto element : y) {
max_count = std::max(max_count, element.second);
}
if (y.size() == 3) {
if (max_count == 3) {
v[3]++;
continue;
}
v[2]++;
continue;
}
if (max_count == 4) {
v[5]++;
continue;
}
v[4]++;
}
//p[i] - i-
std::vector<double> p{0.30240, 0.50400, 0.10800, 0.07200, 0.00900, 0.00450,
0.00010};
for (int i = 0; i < p.size(); ++i) {
p[i] *= num_groups;
}
x = x0;
bool is_test_passed = X2(v, p, categories - 1);
double finish = clock();
// std::cout << "Sequential runtime = " << (finish - start) / 1000.0
// << std::endl;
// std::cout << std::endl;
return is_test_passed;
}
bool Generator::LCG::PokerTestParallel() {
double start = clock();
std::cout << "Poker Test Parallel" << std::endl;
x = x0;
int d = 10;
int length = 5;
int categories = 7;
int num_groups = n / length;
// ,
//(= )
const int num_threads = std::min(sqrt(num_groups), 1e5);
//v_threads[i][j] - i- j,
//0- -
//1- - 1
//2- - 2
//3- - 1
//4- - 1 1
//5- - 1
//6- -
std::vector<std::vector<long long>> v_threads(num_threads,
std::vector<long long>(categories, 0));
//
long long step = num_groups / num_threads;
if (num_groups % num_threads) {
++step;
}
//from[i] - i-
std::vector<long long> from(num_threads, 0);
from[0] = GetX(x0);
for (int i = 1; i < num_threads; ++i) {
from[i] = GetXTransition(from[i - 1], step * length);
}
#pragma omp parallel for num_threads(num_threads)
for (int i = 0; i < num_threads; ++i) {
for (int j = 0; j < step && i * step + j < num_groups; ++j) {
std::map<int, int> y;
for (int l = 0; l < length; ++l) {
y[GetEps(from[i]) * d]++;
from[i] = GetX(from[i]);
}
if (y.size() == 5) {
v_threads[i][0]++;
continue;
}
if (y.size() == 4) {
v_threads[i][1]++;
continue;
}
if (y.size() == 1) {
v_threads[i][6]++;
continue;
}
int max_count = 0;
for (auto element : y) {
max_count = std::max(max_count, element.second);
}
if (y.size() == 3) {
if (max_count == 3) {
v_threads[i][3]++;
continue;
}
v_threads[i][2]++;
continue;
}
if (max_count == 4) {
v_threads[i][5]++;
continue;
}
v_threads[i][4]++;
}
}
//
std::vector<long long> v(categories, 0);
for (int i = 0; i < categories; ++i) {
for (int j = 0; j < num_threads; ++j) {
v[i] += v_threads[j][i];
}
}
//p[i] - i-
std::vector<double> p{0.30240, 0.50400, 0.10800, 0.07200, 0.00900, 0.00450,
0.00010};
for (int i = 0; i < p.size(); ++i) {
p[i] *= num_groups;
}
x = x0;
bool is_test_passed = X2(v, p, categories - 1);
double finish = clock();
// std::cout << "Parallel runtime = " << (finish - start) / 1000.0 << std::endl;
// std::cout << std::endl;
return is_test_passed;
}
bool Generator::LCG::CouponCollectorsTest() {
double start = clock();
std::cout << "Coupon Collector's Test" << std::endl;
x = x0;
int d = 10;
long long t = 10;
//v[i], 0 <= i < t - 1 - i + 1
//v[t - 1] - >= t
std::vector<long long> v(t, 0);
// ( )
long long num_intervals = 0;
//previous_num -
//length -
long long length = 1;
for (long long i = 1, previous_num = Get() * d; i < n; ++i,
++length) {
int y = Get() * d;
if (y != previous_num) {
++v[std::min(length, t) - 1];
++num_intervals;
length = 0;
previous_num = y;
}
}
++v[std::min(length, t) - 1];
++num_intervals;
// ,
double p1 = 1.0 / d;
//p[i] - i
std::vector<double> p(t, 0);
// p1
double pow = 1;
for (long long i = 1; i <= t; ++i, pow *= p1) {
if (i < t) {
p[i - 1] = pow * (1 - p1);
}
else {
p[i - 1] = pow;
}
p[i - 1] *= num_intervals;
}
x = x0;
bool is_test_passed = X2(v, p, t - 1);
double finish = clock();
// std::cout << "Sequential runtime = " << (finish - start) / 1000.0 << std::endl;
// std::cout << std::endl;
return is_test_passed;
}
bool Generator::LCG::CouponCollectorsTestParallel() {
double start = clock();
std::cout << "Coupon Collector's Test Parallel" << std::endl;
x = x0;
int d = 10;
long long t = 10;
// ,
//(= )
const int num_threads = std::min(sqrt(n), 1e5);
//v_threads[i][j], 0 <= j < t - 1 -
// j + 1 i-
//v_threads[i][t - 1] - >= t i-
std::vector<std::vector<long long>> v_threads(num_threads,
std::vector<long long>(t, 0));
//
long long step = n / num_threads;
if (n % num_threads) {
++step;
}
//from[i] -
std::vector<long long> from(num_threads, 0);
from[0] = GetX(x0);
for (int i = 1; i < num_threads; ++i) {
from[i] = GetXTransition(from[i - 1], step);
}
// , - ,
// -
std::vector<std::pair<int, long long>> first_intervals(num_threads, {-1, 0});
std::vector<std::pair<int, long long>> last_intervals(num_threads, {-1, 0});
#pragma omp parallel for num_threads(num_threads)
for (int i = 0; i < num_threads; ++i) {
first_intervals[i].first = GetEps(from[i]) * d;
int length = 0;
while (int(GetEps(from[i]) * d) == first_intervals[i].first
&& length < step && i * step + length < n) {
from[i] = GetX(from[i]);
++length;
}
first_intervals[i].second = length;
}
// ( )
long long num_intervals = 0;
#pragma omp parallel for reduction(+:num_intervals) num_threads(num_threads)
for (int i = 0; i < num_threads; ++i) {
//previous_num -
//length -
long long previous_num = GetEps(from[i]) * d;
from[i] = GetX(from[i]);
long long length = 1;
for (int j = first_intervals[i].second; j < step - 1 && i * step + j < n;
++j, ++length) {
int y = GetEps(from[i]) * d;
from[i] = GetX(from[i]);
if (y != previous_num) {
++v_threads[i][std::min(length, t) - 1];
++num_intervals;
length = 0;
previous_num = y;
}
}
if (i * step + first_intervals[i].second < n) {
last_intervals[i] = std::make_pair(previous_num, length);
}
}
//
std::vector<long long> v(t, 0);
for (int i = 0; i < t; ++i) {
for (int j = 0; j < num_threads; ++j) {
v[i] += v_threads[j][i];
}
}
if (first_intervals[0].second == step) {
// ,
//
last_intervals[0].first = first_intervals[0].first;
last_intervals[0].second = step;
}
else {
//
++v[std::min(first_intervals[0].second, t) - 1];
++num_intervals;
}
for (int i = 0; i < num_threads - 1; ++i) {
if (last_intervals[i].first == first_intervals[i + 1].first) {
if (first_intervals[i + 1].second == step) {
// i- i+1-,
//i+1 ,
// i+2
last_intervals[i + 1].first = last_intervals[i].first;
last_intervals[i + 1].second = last_intervals[i].second + step;
}
else {
// i- i+1-,
// v 2-
++v[std::min(last_intervals[i].second + first_intervals[i + 1].second
, t) - 1];
++num_intervals;
}
}
else {
// i- i+1-,
// i- v
++v[std::min(last_intervals[i].second, t) - 1];
++num_intervals;
if (first_intervals[i + 1].second == step) {
//i+1 ,
// i+2-
last_intervals[i + 1].first = first_intervals[i + 1].first;
last_intervals[i + 1].second = step;
}
else {
// i+1- v
++v[std::min(first_intervals[i + 1].second, t) - 1];
++num_intervals;
}
}
}
// ,
if (last_intervals[num_threads - 1].second != 0) {
++v[std::min(last_intervals[num_threads - 1].second, t) - 1];
++num_intervals;
}
// ,
double p1 = 1.0 / d;
//p[i] - i
std::vector<double> p(t, 0);
// p1
double pow = 1;
for (long long i = 1; i <= t; ++i, pow *= p1) {
if (i < t) {
p[i - 1] = pow * (1 - p1);
}
else {
p[i - 1] = pow;
}
p[i - 1] *= num_intervals;
}
x = x0;
bool is_test_passed = X2(v, p, t - 1);
double finish = clock();
// std::cout << "Sequential runtime = " << (finish - start) / 1000.0 << std::endl;
// std::cout << std::endl;
return is_test_passed;
}
bool Generator::LCG::Test() {
if (EquidistributionTestParallel() && SerialTestParallel()
&& PokerTestParallel() && CouponCollectorsTestParallel()) {
std::cout << "All tests passed!" << std::endl << std::endl;
return true;
}
return false;
}
void Generator::LCG::ParallelTest() {
EquidistributionTest();
EquidistributionTestParallel();
SerialTest();
SerialTestParallel();
PokerTest();
PokerTestParallel();
CouponCollectorsTest();
CouponCollectorsTestParallel();
}
| true |
e7fd2385e87b78b6780353962a2aa6538cc66eca | C++ | n2westman/raytrace | /template-rt.cpp | UTF-8 | 10,704 | 3.046875 | 3 | [] | no_license | //
// CS 174A Project 3
// Ray Tracing
// Nick Westman
// UID 903996152
#define _CRT_SECURE_NO_WARNINGS
#include "matm.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm> //To get max and min, which are used in clamping pixel values
#include <omp.h> //To speed up the process
using namespace std;
struct Ray
{
vec4 origin;
vec4 dir;
};
struct Sphere
{
string name;
vec4 position;
vec4 color;
vec3 scale;
float Ka;
float Kd;
float Ks;
float Kr;
float n;
// Printing Utility
friend std::ostream& operator << ( std::ostream& os, const Sphere& s ) {
return os << "Name " << s.name << "\nPos " << s.position
<< "\nColor " << s.color << "\nScale " << s.scale
<< "\nK Values " << vec4(s.Ka, s.Kd, s.Ks, s.Kr)
<< "\nN " << s.n;
}
};
struct Light
{
string name;
vec4 position;
vec4 color;
//Printing Utility
friend std::ostream& operator << ( std::ostream& os, const Light& l ) {
return os << "Name " << l.name
<< "\nPosition " << l.position
<< "\nColor " << l.color;
}
};
enum Type
{
NO_INTERSECTION,
SPHERE,
H_SPHERE
};
struct Intersection
{
vec4 position;
Type t;
union {
Light * l;
Sphere * s;
};
};
vector<vec4> g_colors;
Sphere g_spheres[5]; //5 is the max
Light g_lights[5];
int num_spheres;
int num_lights;
vec4 g_back; //Background color
vec4 g_ambient; //Ambient intensity
string g_output;
int g_width;
int g_height;
float g_left;
float g_right;
float g_top;
float g_bottom;
float g_near;
// -------------------------------------------------------------------
// Input file parsing -- Added toVec3 Function
vec4 toVec4(const string& s1, const string& s2, const string& s3)
{
stringstream ss(s1 + " " + s2 + " " + s3);
vec4 result;
ss >> result.x >> result.y >> result.z;
result.w = 1.0f;
return result;
}
vec3 toVec3(const string& s1, const string& s2, const string& s3)
{
stringstream ss(s1 + " " + s2 + " " + s3);
vec3 result;
ss >> result.x >> result.y >> result.z;
return result;
}
float toFloat(const string& s)
{
stringstream ss(s);
float f;
ss >> f;
return f;
}
void parseLine(const vector<string>& vs)
{
if (vs[0] == "RES") {
g_width = (int)toFloat(vs[1]);
g_height = (int)toFloat(vs[2]);
g_colors.resize(g_width * g_height);
} else if (vs[0] == "NEAR") {
g_near = toFloat(vs[1]);
} else if (vs[0] == "LEFT") {
g_left = toFloat(vs[1]);
} else if (vs[0] == "RIGHT") {
g_right = toFloat(vs[1]);
} else if (vs[0] == "BOTTOM") {
g_bottom = toFloat(vs[1]);
} else if (vs[0] == "TOP") {
g_top = toFloat(vs[1]);
} else if (vs[0] == "BACK") {
g_back = toVec4(vs[1], vs[2], vs[3]);
} else if (vs[0] == "AMBIENT") {
g_ambient = toVec4(vs[1], vs[2], vs[3]);
} else if (vs[0] == "OUTPUT") {
g_output = vs[1];
} else if (vs[0] == "SPHERE") {
Sphere * s = &g_spheres[num_spheres++];
s->name = vs[1];
s->position = toVec4(vs[2],vs[3],vs[4]);
s->scale = toVec3(vs[5],vs[6],vs[7]);
s->color = toVec4(vs[8],vs[9],vs[10]);
s->Ka = toFloat(vs[11]);
s->Kd = toFloat(vs[12]);
s->Ks = toFloat(vs[13]);
s->Kr = toFloat(vs[14]);
s->n = toFloat(vs[15]);
} else if (vs[0] == "LIGHT") {
Light * l = &g_lights[num_lights++];
l->name = vs[1];
l->position = toVec4(vs[2],vs[3],vs[4]);
l->color = toVec4(vs[5],vs[6],vs[7]);
}
}
void loadFile(const char* filename)
{
ifstream is(filename);
if (is.fail())
{
cout << "Could not open file " << filename << endl;
exit(1);
}
string s;
vector<string> vs;
while(!is.eof())
{
vs.clear();
getline(is, s);
istringstream iss(s);
while (!iss.eof())
{
string sub;
iss >> sub;
vs.push_back(sub);
}
parseLine(vs);
}
}
// -------------------------------------------------------------------
// Utilities
void setColor(int ix, int iy, const vec4& color)
{
int iy2 = g_height - iy - 1; // Invert iy coordinate.
g_colors[iy2 * g_width + ix] = color;
}
inline
float determinant(float a, float b, float c)
{
return (b * b) - (a * c);
}
void printArgs()
{
cout << "Height is " << g_height << endl;
cout << "Width is " << g_width << endl;
cout << "Near is " << g_near << endl;
cout << "Left is " << g_left << endl;
cout << "Right is " << g_right << endl;
cout << "Top is " << g_top << endl;
cout << "Bottom is " << g_bottom << endl;
for(int i = 0; i < num_spheres; i++)
{
cout << "Sphere " << i << ": " << g_spheres[i] << endl;
}
for(int i = 0; i < num_lights; i++)
{
cout << "Light " << i << ": " << g_lights[i] << endl;
}
cout << "Background color is " << g_back << endl;
cout << "Ambient color is " << g_ambient << endl;
cout << "Output file is " << g_output << endl;
}
// -------------------------------------------------------------------
// Intersection routine
// Returns an intersection object based off of the ray.
Intersection findIntersection(const Ray& ray)
{
float intersect = 1000.0;
float minDist = g_near;
Intersection toRet;
toRet.t = NO_INTERSECTION;
for(int i = 0; i < num_spheres; i++)
{
mat4 undoScale;
InvertMatrix(Scale(g_spheres[i].scale), undoScale);
vec4 originToSphere = g_spheres[i].position - ray.origin;
vec4 S = undoScale * originToSphere;
vec4 C = undoScale * ray.dir;
// Quadratic equation for the solution:
// c*c * t^2 - 2 * dot(s,c) * t + (s*s - 1) = 0
// Just use the quadratic formula for a solution for t!
float a = dot(C,C);
float b = dot(S,C);
float c = dot(S,S) - 1;
if ( determinant(a,b,c) < 0 ) //intersection can't be imaginary!
continue;
float r = sqrtf(determinant(a,b,c))/a;
float t1 = b/a - r;
float t2 = b/a + r;
if(t1 > minDist && t1 < intersect)
{
intersect = t1;
toRet.position = ray.origin + intersect * ray.dir;
if(t2 > minDist) //Both are past near plane
toRet.t = SPHERE;
else
toRet.t = H_SPHERE;
toRet.s = &g_spheres[i];
}
if(t2 > minDist && t2 < intersect)
{
intersect = t2;
toRet.position = ray.origin + intersect * ray.dir;
if(t1 > minDist) //Both are past near plane
toRet.t = SPHERE;
else
toRet.t = H_SPHERE;
toRet.s = &g_spheres[i];
}
}
return toRet;
}
inline
vec4 findNormal(const Intersection& I)
{
vec4 normal = I.position - I.s->position;
mat4 undoScale; //Gradient is just dividing by scale twice - it does a good job.
InvertMatrix(Scale(I.s->scale), undoScale);
normal.w = 0;
return normalize(2*undoScale*undoScale*normal);
}
// -------------------------------------------------------------------
// Ray tracing
vec4 trace(const Ray& ray, int rlevel) //Step holds max level of recur
{
Intersection intersect = findIntersection(ray);
if(intersect.t == NO_INTERSECTION || rlevel >= 5)
return g_back;
// Set Ambient color
vec4 color = intersect.s->color * intersect.s->Ka * g_ambient;
vec4 normal = findNormal(intersect);
vec4 diffuse = vec4(0.0,0.0,0.0,0.0);
vec4 specular = vec4(0.0,0.0,0.0,0.0);
for(int i = 0; i < num_lights; i++)
{
Ray toLight;
toLight.origin = intersect.position;
toLight.dir = normalize(g_lights[i].position - intersect.position);
Intersection lightIntersect = findIntersection(toLight); //Shadow Rays. Code Doesn't actually matter.
if(lightIntersect.t == NO_INTERSECTION)
{
float proj = dot(normal, toLight.dir); //Projection of light ray onto normal
if(proj < 0) //Don't care, doesn't hit light.
continue;
diffuse += proj * g_lights[i].color * intersect.s->color * intersect.s->Kd;
float proj2 = dot(normal, ray.dir); //Projection of ray onto normal
float spec = dot((toLight.dir - ray.dir), (toLight.dir - ray.dir)); //Blinn vector magnitude squared
if (spec > 0.0) //Avoid taking sqrt of negative numbers
{
spec = max(proj-proj2,0.0f)/sqrtf(spec);
specular += powf(spec, intersect.s->n * 3) * g_lights[i].color * intersect.s->Ks;
}
}
}
// Finish Phong Shading
color += diffuse + specular;
if(intersect.t == H_SPHERE) //Hollow Spheres don't have reflections.
return color;
Ray ref;
ref.origin = intersect.position;
ref.dir = normalize(ray.dir - 2.0 * dot(normal, ray.dir) * normal);
vec4 reflection = trace(ref, rlevel+1);
if(reflection != g_back) //Re-wrote the != operator in vecm.h to do what we want it to do! (Tolerance is 0.01. Check vecmh for info)
color += reflection*intersect.s->Kr;
return color;
}
vec4 getDir(int ix, int iy)
{
float x = g_left + (float) ix * (g_right - g_left) / g_width;
float y = g_bottom + (float) iy * (g_top - g_bottom) / g_height;
vec4 dir;
dir = vec4(x, y, -g_near, 0.0f);
return dir;
}
void renderPixel(int ix, int iy)
{
Ray ray;
ray.origin = vec4(0.0f, 0.0f, 0.0f, 1.0f);
ray.dir = getDir(ix, iy);
vec4 color = trace(ray, 0);
setColor(ix, iy, color);
}
void render()
{
int ix; //Open MP directive added to speedup debugging. Why not.
#pragma omp parallel for private(ix)
for (int iy = 0; iy < g_height; iy++)
for (ix = 0; ix < g_width; ix++)
renderPixel(ix, iy);
}
// -------------------------------------------------------------------
// PPM saving
void savePPM(int Width, int Height, char* fname, unsigned char* pixels)
{
FILE *fp;
const int maxVal=255;
printf("Saving image %s: %d x %d\n", fname, Width, Height);
fp = fopen(fname,"wb");
if (!fp) {
printf("Unable to open file '%s'\n", fname);
return;
}
fprintf(fp, "P6\n");
fprintf(fp, "%d %d\n", Width, Height);
fprintf(fp, "%d\n", maxVal);
for(int j = 0; j < Height; j++) {
fwrite(&pixels[j*Width*3], 3, Width, fp);
}
fclose(fp);
}
inline
float clamp(float c)
{
return max(min(c,1.0f),0.0f);
}
void saveFile()
{
// Convert color components from floats to unsigned chars.
unsigned char* buf = new unsigned char[g_width * g_height * 3];
for (int y = 0; y < g_height; y++)
for (int x = 0; x < g_width; x++)
for (int i = 0; i < 3; i++)
buf[y*g_width*3+x*3+i] = (unsigned char)(clamp(((float*)g_colors[y*g_width+x])[i]) * 255.9f);
char * f = new char[g_output.length() + 1];
strcpy(f, g_output.c_str());
savePPM(g_width, g_height, f, buf);
delete[] f;
delete[] buf;
}
// -------------------------------------------------------------------
// Main
int main(int argc, char* argv[])
{
if (argc < 2)
{
cout << "Usage: template-rt <input_file.txt>" << endl;
exit(1);
}
loadFile(argv[1]);
// printArgs();
render();
saveFile();
return 0;
}
| true |
487d72129e1ff5856aa6eef58f4606197779905c | C++ | mr-jaffery-hash/A-Simple-Shell | /SimpleShell.cpp | UTF-8 | 8,106 | 2.640625 | 3 | [] | no_license | #include <unistd.h>
#include <stdio.h> /* printf*/
#include <stdlib.h> /* getenv*/
#include <iostream> /*cout*/
#include <cstring> /*strlen*/
#include <string> /*getline*/
#include <string.h> /*strtok*/
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/shm.h>
#include <bits/stdc++.h>
using namespace std;
int inputCheck, outputCheck;
char* inputfilename;
bool backgroundProcessCheck=false;
char* FindCommand(char* command) {
char* path;
path = getenv("PATH");
int commandlength = strlen(command);
int length = strlen(path);
int index = 0;
int size = 30;
char* shortpath = new char[size];
for (int i = 0; i < length; i++) {
while (path[i] != ':' && path[i] != '\0') {
if (index < size) {
shortpath[index] = path[i];
i++;
index++;
}
else {
int oldsize = size;
size = size + size;
char* newptr = shortpath;
shortpath = new char[size];
for (int i = 0; i < oldsize; i++) {
shortpath[i] = newptr[i];
}
shortpath[index] = path[i];
i++;
index++;
}
}
shortpath[index] = '/';
index++;
for (int j = 0; j < commandlength; j++) {
if (index < size) {
shortpath[index] = command[j];
index++;
}
else {
int oldsize = size;
size = size + size;
char* newptr = shortpath;
shortpath = new char[size];
for (int i = 0; i < oldsize; i++) {
shortpath[i] = newptr[i];
}
shortpath[index] = command[j];
index++;
}
}
shortpath[index] = '\0';
index++;
if (access(shortpath, F_OK) == 0) {
return shortpath;
}
index = 0;
}
return NULL;
}
void tokenize(char**& token, string command, char* str) {
int size = 0;
for (int i = 0; i < command.length(); i++) {
if (command[i] == ' ') {
size++;
}
}
size++;
int s = size;
token = new char* [size + 1];
token[size] = nullptr;
char* temp = new char[100];
size = 0;
int tokenNumber = 0;
for (int i = 0; i < command.length(); i++) {
while (command[i] != ' ' && command[i] != '\0') {
temp[size] = command[i];
size++;
i++;
}
token[tokenNumber] = new char[size + 1];
for (int j = 0; j < size; j++) {
token[tokenNumber][j] = temp[j];
}
token[tokenNumber][size] = '\0';
tokenNumber++;
size = 0;
}
}
void execute(string commandAndParameters) {
int size = 30;
int index = 0;
char* cap = new char[commandAndParameters.length() + 1];
strcpy(cap, commandAndParameters.c_str());
char* command = new char[size];
for (int i = 0; cap[i] != ' ' && cap[i] != '\0'; i++) {
if (index < size) {
command[index] = cap[i];
index++;
}
else {
int oldsize = size;
size = size + size;
char* newptr = command;
command = new char[size];
for (int i = 0; i < oldsize; i++) {
command[i] = newptr[i];
}
command[index] = cap[i];
index++;
}
}
command[index] = '\0';
if (FindCommand(command)) {
char* exec = FindCommand(command);
char** myargs = nullptr;
tokenize(myargs, commandAndParameters, exec);
execv(exec, myargs);
}
else {
cout << "Command Not Found" << endl;
return;
}
}
void parse(char* fullString, char**&seperatedCommands, int (&delPosition)[10], int&noOfDelCount, int& NumberOfPipes, int& NumberOfCommands) {
char* pch;
noOfDelCount = 0;
NumberOfPipes = 0;
NumberOfCommands = 0;
inputCheck=0;
outputCheck=0;
for (int i = 0; i < strlen(fullString); i++) {
if (fullString[i] == '|') {
delPosition[noOfDelCount] = 0;
noOfDelCount++;
NumberOfPipes++;
}
else if (fullString[i] == '<') {
delPosition[noOfDelCount] = 1;
noOfDelCount++;
inputCheck=1;
}
else if (fullString[i] == '>') {
delPosition[noOfDelCount] = 2;
noOfDelCount++;
outputCheck=1;
}
else if (fullString[i] == '&'){
backgroundProcessCheck=true;
}
}
seperatedCommands = new char* [noOfDelCount + 1];
int seperatedCommandsIndex = 0;
#pragma warning(suppress : 4996)
pch = strtok(fullString, "|<>");
while (pch != NULL){
seperatedCommands[seperatedCommandsIndex] = new char[strlen(pch)];
for (int i = 0; i < strlen(pch); i++) {
seperatedCommands[seperatedCommandsIndex][i] = pch[i];
}
seperatedCommandsIndex++;
#pragma warning(suppress : 4996)
pch = strtok(NULL, "|<>");
}
NumberOfCommands=seperatedCommandsIndex;
int delimCheckCount = 0;
//int readorwrite = 0;
if (noOfDelCount == 0) {
int fd=fork();
if(fd==0){
execute(seperatedCommands[0]);
}
else if(fd>0){
wait(NULL);
}
}
}
void doTheThing(char**allCommands, int NumberOfSigns,int NumberOfPipes,int NumberOfCommands){
int signsIndex=0;
if(NumberOfCommands==1){
return;
}
int pipefds[NumberOfPipes*2];
/* parent creates all needed pipes at the start */
for( int i = 0; i < NumberOfPipes; i++ ){
if( pipe(pipefds + i*2) < 0 ){
exit;
}
}
//commandc = 0
char* inputFile;
int command=0;
bool inputTaken=true;
int savestdout = dup(1);
if(inputCheck==1){
inputfilename=new char[strlen(allCommands[1])];
for(int i=0; i<strlen(allCommands[1]); i++){
inputfilename[i]=allCommands[1][i];
}
for(int i=1; i<NumberOfCommands-1;i++){
allCommands[i]=new char[strlen(allCommands[i+1])];
for(int j=0; j<strlen(allCommands[i+1]); j++){
allCommands[i][j]=allCommands[i+1][j];
}
}
NumberOfCommands--;
}
if(outputCheck==1){
NumberOfCommands--;
}
while(command!=NumberOfCommands){
int pid = fork();
if( pid == 0 ){
//if it is first command and we have to take input from the file
if(command==0){
if(inputCheck==1){
int in = open(inputfilename, O_RDONLY);
dup2(in, 0);
close(in);
}
}
//get the input from the previous commands if it is not the first command
if(command!=0){
if( dup2(pipefds[(command-1)*2], 0) < 0 ){
perror and exit;
}
}
//direct the output to the next pipe if it is not the last command
if(command!=NumberOfCommands){
if( dup2(pipefds[command*2+1], 1) < 0 ){
perror and exit;
}
}
//if it is the last command check where to direct the output
if(command==NumberOfCommands-1){
if(dup2(savestdout, 1)<0)
perror and exit;
if(outputCheck==1){
int out = open(allCommands[command+ 1], O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IRGRP | S_IWGRP | S_IWUSR);
dup2(out, 1);
close(out);
}
}
//close all pipes
for( int i = 0; i < 2 * NumberOfCommands; i++ ){
close( pipefds[i] );
}
execute(allCommands[command]);
}
else if( pid < 0 ){
perror and exit;
}
//wait(NULL);
command++;
}
//closing all the pipes in parent
for(int i = 0; i < 2 * NumberOfCommands; i++ ){
close( pipefds[i] );
}
//if '&' was recieved in the command the do the processing in the background
if(backgroundProcessCheck==false)
wait(NULL);
}
void shell_display(){
system("clear");
cout<<"ENTER -1 TO EXIT"<<endl;
cout<<"\n\n\n\n******************"
"***************************************";
cout<<"\n\n\t****SHELL-19L-0910****";
cout<< "\n\n\n1) Executes commands having multiple pipes and filters (program names). \n2) Support for I/O redirection is provided. \n3) If user appends string with '&' then the command executes in the background.";
cout<<"\n\n\n*******************"
"**************************************";
char* username = getenv("USER");
printf("\n\n\nsystem: @%s", username);
cout<<"\n";
sleep(1);
system("clear");
}
void myShell() {
string commandAndParameters;
int NumberOfSigns;
int NumberOfPipes;
int NumberOfCommands;
char**allCommands;
int signs[10];
shell_display();
cout << endl << "L190910_Assignement 2: Enter Command: ";
getline(cin, commandAndParameters);
char* stringToPass = new char[commandAndParameters.length()+1];
for (int i = 0; i < commandAndParameters.length(); i++) {
stringToPass[i] = commandAndParameters[i];
}
stringToPass[commandAndParameters.length()] = '\0';
for(int i=0; i<10; i++){
signs[i]=-1;
}
parse(stringToPass,allCommands,signs,NumberOfSigns, NumberOfPipes, NumberOfCommands);
doTheThing(allCommands, NumberOfSigns, NumberOfPipes, NumberOfCommands);
}
int main() {
//while(true)
myShell();
}
| true |
5d716fa5f4ed0a4b6a10defa4bd4a2a494872385 | C++ | PaulDodd/chull | /src/chull.h | UTF-8 | 38,001 | 2.671875 | 3 | [
"MIT"
] | permissive | #pragma once
#include <memory>
#include <vector>
#include <string>
#include <queue>
#include <set>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <functional>
#include <eigen3/Eigen/Dense>
#include <eigen3/Eigen/Sparse>
#include <eigen3/Eigen/Geometry>
namespace chull{
enum copy_type{shallow, deep};
template<class P>
constexpr P zero() { return P(0.0); }
template<class P>
constexpr P tolerance() { return P(1e-5); } // TODO: set externally?
using Eigen::Dynamic;
template<class P, int D=Dynamic>
using PointRn = Eigen::Matrix<P, D, 1>;
template<class P, int D=Dynamic>
using PlaneRn = Eigen::Hyperplane<P, D>;
template<class P, int D=Dynamic>
using VectorRn = PointRn<P,D>;
template<class IndexIterator>
inline std::vector<int> __make_index_vector(IndexIterator first, IndexIterator last, int N)
{
if(first != last)
return std::vector<int>(first, last);
std::vector<int> v(N);
for(int i = 0; i < N; i ++) v[i] = i;
return v;
}
struct dim{
const unsigned int value;
template<class P, int D1, int D2>
dim(const Eigen::Matrix<P, D1, D2>& m) : value((D1 > 0) ? D1 : m.rows()) { }
template<class P, int D>
dim(const Eigen::Hyperplane<P, D>& p) : value((D > 0) ? D : p.dim()) { }
};
template<class P>
struct support_function // TODO: optimize this by removing expensive vector copy operations!
{
typedef typename Eigen::Matrix<P, Eigen::Dynamic, Eigen::Dynamic > MatrixType;
typedef typename MatrixType::Index IndexType;
support_function(const MatrixType& points) : verts(points), m_Indices(__make_index_vector(0,0, points.rows()))
{
}
template<class VectorType, class IteratorType>
support_function(const std::vector< VectorType > & points, IteratorType first=0, IteratorType last=0)
: m_Indices(__make_index_vector(first, last, points.size()))
{
verts.resize(m_Indices.size(), points[0].rows());
for(IndexType i = 0; i < m_Indices.size(); i++)
verts.row(i) = points[m_Indices[i]];
}
P operator () (const PointRn<P>& v)
{
// h(P, v) = sup { a . v : a in P }
Eigen::VectorXd dots = verts*v;
return dots.maxCoeff();
}
IndexType index(const PointRn<P>& v, bool bMap=true)
{
Eigen::VectorXd dots = verts*v;
P maxv = dots[0];
IndexType maxi = 0;
for(IndexType i=1; i < dots.rows(); i++)
{
if(dots[i] > maxv)
{
maxv = dots[i];
maxi = i;
}
}
return bMap ? m_Indices[maxi] : maxi;
}
PointRn<P> element(const PointRn<P>& v) { return PointRn<P>(verts.row(index(v, false))); }
MatrixType verts;
std::vector<int> m_Indices;
};
template<class P, int D=3> // Here D is the ambient space dimension
struct counter_clockwise
{
counter_clockwise(const PointRn<P,D>& ref, const VectorRn<P,D>& n) : reference(as3D(ref)), normal(as3D(n)), tol(tolerance<P>())
{
static_assert(D == 2 || D == 3 || D == Dynamic, "Counter Clockwise is only defined for dimemsions 2 and 3.");
if(reference.rows() > 3)
throw std::runtime_error("Counter Clockwise is only defined for dimemsions 2 and 3.");
normal.normalize();
}
// returns true if point p1's polar angle is less than p2's polar angle from
// a given a reference point in the plane normal vector.
bool less2(const PointRn<P,3>& a, const PointRn<P,3>& b) const
{
Eigen::Vector3d va, vb, vab;
vab = a-b;
va = a - reference;
vb = b - reference;
if(vab.squaredNorm() < tol)
return false;
return normal.dot(va.cross(vb)) > 0;
}
// Container must have the [] operator overloaded
template<class IndexType, class Container>
bool less(const IndexType& a, const IndexType& b, const Container& pointset) const
{
VectorRn<P,3> va, vb;
va = as3D(pointset[a]) - reference;
vb = as3D(pointset[b]) - reference;
if(a == b)
return false;
else if(va.squaredNorm() < tol)
return true;
else if(vb.squaredNorm() < tol)
return false;
return normal.dot(va.cross(vb)) > 0;
}
template<class IndexType, class Container>
std::function<bool(const IndexType& , const IndexType&) > lessfn(const Container& points) const
{
return [this, points](const IndexType& a, const IndexType& b) {
return this->less(a, b, points);
};
}
// returns true if a->b->c makes a left turn, false otherwise (colinear or right turn)
bool operator()(const PointRn<P,D>& a, const PointRn<P,D>& b, const PointRn<P,D>& c) const
{
// VectorRn<P,3> e1 = {}
// VectorRn<P,3> e2 = {}
VectorRn<P,3> vb = as3D(b);
VectorRn<P,3> va, vc;
va = as3D(a) - vb;
vc = as3D(c) - vb;
// std::cout << "a = \n"<< a << std::endl<< std::endl;
// std::cout << "b = \n"<< b << std::endl<< std::endl;
// std::cout << "c = \n"<< c << std::endl<< std::endl;
//
// std::cout << "va = \n"<< va << std::endl<< std::endl;
// std::cout << "vc = \n"<< vc << std::endl<< std::endl;
// std::cout << "n = \n"<< normal << std::endl<< std::endl;
// std::cout << "vc x va = \n"<< vc.cross(va) << std::endl<< std::endl;
// std::cout << "n * (vc x va) = \n"<< normal.dot(vc.cross(va)) << std::endl<< std::endl;
// std::cout << "e1 x e2 = \n"<< as3D<3>({-1.0, 0.0, 0.0}).cross(as3D<3>({0.0, -1.0, 0.0})) << std::endl<< std::endl;
return normal.dot(vc.cross(va)) > 0;
}
template<int Do>
VectorRn<P,3> as3D(const VectorRn<P,Do> v) const
{
if(v.rows() == 3)
return v;
else if (v.rows() == 2)
return {v[0], v[1], P(0.0)};
else
return {v[0], v[1], v[2]};
}
PointRn<P,3> reference;
VectorRn<P,3> normal;
P tol;
};
template<class P, int D=Dynamic> // Here D is the ambient space dimension
class SubSpace // represents the span of a set of basis vectors.
{
typedef typename Eigen::Matrix<P, Eigen::Dynamic, Eigen::Dynamic > MatrixType;
public:
template<int D2> // ArrayType must have the accessor [] overloaded.
SubSpace(const Eigen::Matrix<P, D, D2>& basis, P threshold = tolerance<P>())
{
from_basis(basis, threshold);
}
template<class ArrayType, int D2> // ArrayType must have the accessor [] overloaded.
SubSpace(const std::vector< VectorRn<P,D2> >& points, const ArrayType& indices, unsigned int N, P threshold = tolerance<P>())
{
int d = points[indices[0]].rows();
m_origin = points[indices[0]];
MatrixType basis(d, int(N)-1);
for(int i = 1; i < N; i++)
{
basis.col(i-1) = points[indices[i]] - m_origin;
}
from_basis(basis, threshold);
}
~SubSpace() {}
bool in(const PointRn<P, D>& p, P threshold = tolerance<P>()) { return fabs(distance(p, true)) < threshold; }
template<int D2>
PointRn<P, D> project(const PointRn<P, D2>& point) const
{
PointRn<P, D> proj, x0;
x0 = point - m_origin;
proj = m_Projection*x0;
return proj + m_origin;
}
template<int D2>
P distance(const PointRn<P, D2>& point, bool squared=true) const
{
PointRn<P, D> proj = project(point);
VectorRn<P,D> dv = point - proj;
P d2 = dv.dot(dv);
return squared ? d2 : sqrt(d2);
}
const size_t& dim() const { return m_dim; }
const MatrixType& basis() const { return m_Basis; }
const MatrixType& projection() const { return m_Projection; }
const PointRn<P, D>& origin() const { return m_origin; }
private:
void from_basis(const MatrixType& basis, P threshold = tolerance<P>())
{
Eigen::FullPivLU< MatrixType > lu(basis.rows(), basis.cols());
lu.setThreshold(threshold);
lu.compute(basis);
m_Basis = lu.image(basis);
if(m_Basis.isZero(threshold))
{
std::cerr << "Basis dimension is zero!" << std::endl;
std::cerr << "input: \n" << basis << std::endl;
std::cerr << "output: \n" << m_Basis << std::endl;
throw std::runtime_error("Could not initialize subspace.");
}
m_dim = m_Basis.cols(); // number of basis vectors.
// now solve for the projection map.
// P = A(A^T A)^{−1} A^T. where A is the basis.
MatrixType bt = m_Basis.transpose();
MatrixType btbinv = (bt*m_Basis).inverse();
m_Projection = m_Basis * btbinv * bt;
}
private:
size_t m_dim;
MatrixType m_Basis;
MatrixType m_Projection;
PointRn<P, D> m_origin;
};
template<class P, int D=Eigen::Dynamic>
class HalfSpace
{
public:
HalfSpace() {}
~HalfSpace() {}
private:
PlaneRn<P, D> m_plane;
};
// may move some of these functions inside the half space class.
template<class P, int D, int N>
inline VectorRn<P,D> get_normal(const Eigen::Matrix<P, D, N>& points)
{
VectorRn<P,D> ret;
Eigen::Matrix<P, Eigen::Dynamic, Eigen::Dynamic> space(points.cols()-1, points.rows());
if(points.cols() == 1)
{
ret = VectorRn<P,D>(points.col(0));
ret.normalize();
return ret;
}
for(int i = 1; i < points.cols(); i++) // TODO: I am not happy about this copy. can we remove?
space.row(i-1) = points.col(i) - points.col(0);
Eigen::FullPivLU< Eigen::Matrix<P, Eigen::Dynamic, Eigen::Dynamic > > lu(space);
Eigen::Matrix<P, Eigen::Dynamic, Eigen::Dynamic> null_space = lu.kernel();
// Check the dimension is one.
if(null_space.cols() != 1)
{
std::cout << "points : " << std::endl;
std::cout << points << std::endl;
std::cout << "kernel : " << std::endl;
std::cout << null_space << std::endl;
throw(std::runtime_error("space is either under or over specified."));
}
ret = null_space;
ret.normalize();
return ret;
}
template< class P, int D, class MatType, class IndexType>
inline void slice(const std::vector< VectorRn<P,D> >& points, const std::vector<IndexType>& indices, MatType& mat)
{
for(size_t i = 0; i < indices.size(); i++)
mat.col(i) = points[indices[i]];
}
template< class P, int D, class IndexType, class MatType >
inline void slicen(const std::vector< VectorRn<P,D> >& points, IndexType indices, size_t n, MatType& mat)
{
assert(mat.cols() == n);
for(size_t i = 0; i < n; i++)
mat.col(i) = points[indices[i]];
}
// face is assumed to be an array of indices of triangular face of a convex body.
// points may contain points inside or outside the body defined by faces.
// faces may include faces that contain vertices that are inside the body.
// TODO: replace this as a constructor for the HalfSpace above?
template<class P, int D, class IndexType>
inline VectorRn<P,D> getOutwardNormal(const std::vector< VectorRn<P,D> >& points, const VectorRn<P,D>& inside_point, const std::vector<IndexType>& face)
{
// const std::vector<unsigned int>& face = faces[faceid];
unsigned int d = dim(inside_point).value;
assert(d <= face.size()); // TODO: throw error?
Eigen::Matrix<P, D, D> facet(d,d);
slicen(points, face, d, facet);
VectorRn<P,D> di = inside_point - points[face[0]];
VectorRn<P,D> normal = get_normal(facet);
P x = normal.dot(di);
if(fabs(d) < tolerance<P>())
throw(std::runtime_error("inner point is in the plane."));
return (x > 0) ? VectorRn<P,D>(-normal) : normal;
}
template<class P, int D = Dynamic>
class ConvexHull
{
const unsigned int invalid_index=-1;
public:
template<class VectorType>
ConvexHull(const std::vector< VectorType >& points)
{
m_points.resize(points.size());
for(int i = 0; i < points.size(); i++){
m_points[i] = points[i]; // copies the points.
// std::cout << m_points[i] <<std::endl;
}
assert(points.size() > 0);
m_dim = dim(m_points[0]).value;
m_ravg = VectorRn<P,Eigen::Dynamic>::Zero(m_dim);
}
template<class MatrixType>
ConvexHull(const MatrixType& points)
{
m_dim = dim(points).value;
m_ravg = VectorRn<P,Eigen::Dynamic>::Zero(m_dim);
m_points.reserve(points.cols());
for(int i = 0; i < points.cols(); i++)
{
m_points.push_back(points.col(i));
}
}
void compute()
{
std::vector<bool> inside(m_points.size(), false); // all points are outside.
std::vector<unsigned int> outside(m_points.size(), invalid_index);
try{
if(m_points.size() < m_dim+1) // problem is not well posed.
return;
// step 1: create a tetrahedron from the first 4 points.
initialize(); // makes the tetrahedron
for(unsigned int i = 0; i < m_points.size(); i++) // O((dim+1)*N) since we have a tetrahedron
{
// step 2: initialize the outside and inside sets
for(unsigned int f = 0; f < m_faces.size() && !inside[i]; f++)
{
if(m_deleted[f])
continue;
if(outside[i] == invalid_index && is_above(i,f))
{
outside[i] = f;
break;
}
}
if(!inside[i] && outside[i] == invalid_index)
{
inside[i] = true;
}
}
unsigned int faceid = 0;
// write_pos_frame(inside);
while(faceid < m_faces.size()) //
{
if(m_deleted[faceid]) // this facet is deleted so we can skip it.
{
faceid++;
continue;
}
P dist = 0.0;
unsigned int _id = invalid_index;
for(unsigned int out = 0; out < outside.size(); out++) // O(N)
{
if(outside[out] == faceid)
{
P sd = signed_distance(out, faceid);
assert(sd > tolerance<P>());
if( sd > dist)
{
dist = sd;
_id = out;
}
}
}
if(_id == invalid_index) // no point found.
{
faceid++;
continue;
}
// step 3: Find the visible set
std::vector< unsigned int > visible;
build_visible_set(_id, faceid, visible);
// step 4: Build the new faces
std::vector< std::vector<unsigned int> > new_faces;
build_horizon_set(visible, new_faces); // boundary of the visible set
assert(visible[0] == faceid);
for(unsigned int dd = 0; dd < visible.size(); dd++)
{
m_deleted[visible[dd]] = true;
}
for(unsigned int i = 0; i < new_faces.size(); i++)
{
new_faces[i].push_back(_id);
std::sort(new_faces[i].begin(), new_faces[i].end());
unsigned int fnew = m_faces.size();
assert(m_normals.size() == m_faces.size());
m_faces.push_back(new_faces[i]);
m_normals.push_back(getOutwardNormal(m_points, m_ravg, m_faces[fnew]));
m_deleted.push_back(false);
build_adjacency_for_face(fnew);
for(unsigned int out = 0; out < outside.size(); out++)
{
for(unsigned int v = 0; v < visible.size() && !inside[out]; v++)
{
if(outside[out] == visible[v])
{
if(is_above(out, fnew))
{
outside[out] = fnew;
}
break;
}
}
}
}
// update the inside set for fun.
for(unsigned int out = 0; out < outside.size(); out++)
{
if(outside[out] != invalid_index && m_deleted[outside[out]])
{
outside[out] = invalid_index;
inside[out] = true;
}
}
inside[_id] = true;
assert(m_deleted.size() == m_faces.size() && m_faces.size() == m_adjacency.size());
faceid++;
// write_pos_frame(inside);
}
#ifndef NDEBUG //TODO: remove in a bit. here for extra debug and its easy to turn off.
for(size_t i = 0; i < m_faces.size(); i++)
{
if(m_deleted[i]) continue;
for(size_t j = i+1; j < m_faces.size(); j++)
{
if(m_deleted[j]) continue;
for(size_t k = 0; k < m_faces[j].size(); k++)
{
if(signed_distance(m_faces[j][k], i) > 0.1) // Note this is a large tolerance but this sort of check is prone to numerical errors
{
std::cout << "ERROR!!! point " << m_faces[j][k] << ": [\n" << m_points[m_faces[j][k]] << "]" << std::endl
<< " is above face " << i << ": [" << m_faces[i][0] << ", " << m_faces[i][1] << ", . . . ]" << std::endl
<< " from the face " << j << ": [" << m_faces[j][0] << ", " << m_faces[j][1] << ", . . . ]" << std::endl
<< " distance is " << signed_distance(m_faces[j][k], i) << ", " << signed_distance(m_faces[j][k], j) << std::endl
<< " inside is " << std::boolalpha << inside[m_faces[j][k]] << std::endl;
throw std::runtime_error("ERROR in ConvexHull::compute() !");
}
}
}
}
#endif
remove_deleted_faces(); // actually remove the deleted faces.
// build_edge_list();
// sortFaces(m_points, m_faces, zero);
}
catch(std::runtime_error e){
write_pos_frame(inside);
throw(e);
}
}
private:
void write_pos_frame(const std::vector<bool>& inside)
{
if(m_dim != 3) // todo, make it work with 2d as well
return;
std::ofstream file("convex_hull.pos", std::ios_base::out | std::ios_base::app);
std::string inside_sphere = "def In \"sphere 0.1 005F5F5F\"";
std::string outside_sphere = "def Out \"sphere 0.1 00FF5F5F\"";
std::string avg_sphere = "def avg \"sphere 0.2 00981C1D\"";
std::stringstream ss, connections;
std::set<unsigned int> verts;
for(size_t f = 0; f < m_faces.size(); f++)
{
if(m_deleted[f]) continue;
verts.insert(m_faces[f].begin(), m_faces[f].end());
for(size_t k = 0; k < 3; k++)
connections << "connection 0.05 005F5FFF "<< m_points[m_faces[f][k]][0] << " "<< m_points[m_faces[f][k]][1] << " "<< m_points[m_faces[f][k]][2] << " "
<< m_points[m_faces[f][(k+1)%3]][0] << " "<< m_points[m_faces[f][(k+1)%3]][1] << " "<< m_points[m_faces[f][(k+1)%3]][2] << std::endl;
}
ss << "def hull \"poly3d " << verts.size() << " ";
for(std::set<unsigned int>::iterator iter = verts.begin(); iter != verts.end(); iter++)
for(int d = 0; d < m_dim; d++)
ss << m_points[*iter][d] << " ";
ss << "505984FF\"";
std::string hull = ss.str();
// file<< "boxMatrix 10 0 0 0 10 0 0 0 10" << std::endl;
file<< inside_sphere << std::endl;
file<< outside_sphere << std::endl;
file<< avg_sphere << std::endl;
// file<< hull << std::endl;
// file << "hull 0 0 0 1 0 0 0" << std::endl;
file << connections.str();
file << "avg ";
for(int d = 0; d < m_dim; d++)
file<< m_ravg[d] << " ";
file << std::endl;
for(size_t i = 0; i < m_points.size(); i++)
{
if(inside[i])
file << "In ";
else
file << "Out ";
for(int d = 0; d < m_dim; d++)
file << m_points[i][d] << " ";
file << std::endl;
}
file << "eof" << std::endl;
}
P signed_distance(const unsigned int& i, const unsigned int& faceid) const
{
VectorRn<P,D> dx = m_points[i] - m_points[m_faces[faceid][0]];
return dx.dot(m_normals[faceid]); // signed distance. either in the plane or outside.
}
bool is_above(const unsigned int& i, const unsigned int& faceid) const { return (signed_distance(i, faceid) > tolerance<P>()); }
template<class ArrayType>
bool is_coplanar(const ArrayType& indices, size_t n)
{
for(size_t i = 1; i < n; i++)
{
if(indices[0] == indices[i])
{
return true;
}
}
SubSpace<P, D> space(m_points, indices, n-1);
P dist = space.distance(m_points[indices[n-1]]);
// std::cout << "is_coplanar: " << dist << " <= " << tolerance<P>() << std::boolalpha << (fabs(dist) <= tolerance<P>()) << std::endl;
// TODO: Note I have seen that this will often times return false for nearly coplanar points!!
// How do we choose a good threshold. (an absolute threshold is not good)
return dist <= tolerance<P>(); //fabs(d) <= zero;
}
void edges_from_face(const unsigned int& faceid, std::vector< std::vector<unsigned int> >& edges)
{
assert(faceid < m_faces.size());
unsigned int N = m_faces[faceid].size();
assert(N == 3);
assert(!m_deleted[faceid]);
for(unsigned int i = 0; i < m_faces[faceid].size(); i++)
{
std::vector<unsigned int> edge;
unsigned int e1 = m_faces[faceid][i], e2 = m_faces[faceid][(i+1) % N];
assert(e1 < m_points.size() && e2 < m_points.size());
edge.push_back(std::min(e1, e2));
edge.push_back(std::max(e1, e2));
edges.push_back(edge);
}
}
unsigned int farthest_point_point(const unsigned int& a, bool greater=false)
{
unsigned int ndx = a;
P maxdsq = 0.0;
for(unsigned int p = greater ? a+1 : 0; p < m_points.size(); p++)
{
VectorRn<P,D> dr = m_points[p] - m_points[a];
P distsq = dr.dot(dr);
if(distsq > maxdsq)
{
ndx = p;
maxdsq = distsq;
}
}
return ndx;
}
/*
unsigned int farthest_point_line(const unsigned int& a, const unsigned int& b)
{
unsigned int ndx = a;
P maxdsq = 0.0, denom = 0.0;
const VectorRn<P,D>& x1 = m_points[a],x2 = m_points[b];
VectorRn<P,D> x3;
x3 = x2-x1;
denom = dot(x3,x3);
if(denom <= zero)
return a;
for(unsigned int p = 0; p < m_points.size(); p++)
{
if( p == a || p == b)
continue;
const VectorRn<P,D>& x0 = m_points[p];
VectorRn<P,D> cr = cross(x3,x1-x0);
P numer = dot(cr,cr), distsq;
distsq = numer/denom;
if(distsq > maxdsq)
{
ndx = p;
maxdsq = distsq;
}
}
return ndx;
}
unsigned int farthest_point_plane(const unsigned int& a, const unsigned int& b, const unsigned int& c)
{
unsigned int ndx = a;
P maxd = 0.0, denom = 0.0;
const VectorRn<P,D>& x1 = m_points[a],x2 = m_points[b], x3 = m_points[c];
VectorRn<P,D> n;
n = cross(x2-x1, x3-x1);
denom = dot(n,n);
if(denom <= zero)
return a;
normalize_inplace(n);
for(unsigned int p = 0; p < m_points.size(); p++)
{
if(p == a || p == b || p == c)
continue;
const VectorRn<P,D>& x0 = m_points[p];
P dist = fabs(dot(n,x0-x1));
if(dist > maxd)
{
ndx = p;
maxd = dist;
}
}
return ndx;
}
*/
template<class ArrayType>
unsigned int farthest_point_subspace(const ArrayType& indices, size_t n)
{
unsigned int ndx = indices[0];
P maxd = 0.0;
SubSpace<P, D> space(m_points, indices, n);
for(unsigned int p = 0; p < m_points.size(); p++)
{
P dist = space.distance(m_points[p]);
if(dist > maxd)
{
ndx = p;
maxd = dist;
}
}
return ndx;
}
void initialize()
{
const unsigned int Nsym = m_dim+1; // number of points in the simplex.
std::vector< unsigned int > ik(Nsym);
for(size_t d = 0; d < Nsym; d++) ik[d] = invalid_index;
m_faces.clear(); m_faces.reserve(100000);
m_deleted.clear(); m_deleted.reserve(100000);
m_adjacency.clear(); m_adjacency.reserve(100000);
if(m_points.size() < Nsym) // TODO: the problem is basically done. but need to set up the data structures and return. not common in our use case so put it off until later.
{
throw(std::runtime_error("Could not initialize ConvexHull: need n+1 points to take the convex hull in nD"));
}
ik[0] = 0; // always use the first point.
bool coplanar = true;
while( coplanar )
{
ik[1] = farthest_point_point(ik[0], true); // will only search for points with a higher index than ik[0].
for(size_t d = 1; d < Nsym-1; d++)
{
if(ik[d] == ik[0])
break;
ik[d+1] = farthest_point_subspace(ik, d+1); // will only search for points with a higher index than ik[0].
}
// ik[2] = farthest_point_line(ik[0], ik[1]);
// ik[3] = farthest_point_plane(ik[0], ik[1], ik[2]);
if(!is_coplanar(ik, Nsym))
{
coplanar = false;
}
else
{
ik[0]++;
for(size_t d = 1; d < Nsym; d++) ik[d] = invalid_index;
if( ik[0] >= m_points.size() ) // tried all of the points and this will not.
{
ik[0] = invalid_index; // exit loop and throw an error.
coplanar = false;
}
}
}
if(std::find(ik.begin(), ik.end(), invalid_index) != ik.end())
{
std::cerr << std::endl << std::endl<< "*************************" << std::endl;
for(size_t i = 0; i < m_points.size(); i++)
{
std::cerr << "point " << i << ": [ \n" << m_points[i] << "]" << std::endl;
}
throw(std::runtime_error("Could not initialize ConvexHull: found only nearly coplanar points"));
}
m_ravg = VectorRn<P,D>::Zero(m_dim);
for(size_t i = 0; i < Nsym; i++)
{
m_ravg += m_points[ik[i]];
}
m_ravg /= P(Nsym);
std::vector<unsigned int> face(m_dim);
assert(m_dim == 3); // I think in any dimension, we must enumerate the C(d+1, d) combinations for each face.
// This shouldn't be hard but I will do it later.
// TODO: is there anywhere else in the code where I assume 3d?
// face 0
face[0] = ik[0]; face[1] = ik[1]; face[2] = ik[2];
std::sort(face.begin(), face.end());
m_faces.push_back(face);
// face 1
face[0] = ik[0]; face[1] = ik[1]; face[2] = ik[3];
std::sort(face.begin(), face.end());
m_faces.push_back(face);
// face 2
face[0] = ik[0]; face[1] = ik[2]; face[2] = ik[3];
std::sort(face.begin(), face.end());
m_faces.push_back(face);
// face 3
face[0] = ik[1]; face[1] = ik[2]; face[2] = ik[3];
std::sort(face.begin(), face.end());
m_faces.push_back(face);
m_deleted.resize(4, false); // we have 4 facets at this point.
build_adjacency_for_face(0);
build_adjacency_for_face(1);
build_adjacency_for_face(2);
build_adjacency_for_face(3);
// std::cout << "initializing normals" << std::endl;
for(int f = 0; f < m_faces.size(); f++){
VectorRn<P, D> n = getOutwardNormal(m_points, m_ravg, m_faces[f]);
// std::cout << "normal "<< f << ": \n" << n << std::endl;
m_normals.push_back(n);
}
// std::cout << "done" << std::endl;
}
void build_adjacency_for_face(const unsigned int& f)
{
assert(m_dim == 3); // This assumes 3d!
if(f >= m_faces.size())
throw std::runtime_error("index out of range!");
if(m_deleted[f]) return; // don't do anything there.
m_adjacency.resize(m_faces.size());
for(unsigned int g = 0; g < m_faces.size(); g++)
{
if(m_deleted[g] || g == f) continue;
// note this is why we need the faces to be sorted here.
std::vector<unsigned int> intersection(3, 0);
assert(m_faces[f].size() == 3 && m_faces[g].size() == 3);
std::vector<unsigned int>::iterator it = std::set_intersection(m_faces[f].begin(), m_faces[f].end(), m_faces[g].begin(), m_faces[g].end(), intersection.begin());
intersection.resize(it-intersection.begin());
if(intersection.size() == 2)
{
m_adjacency[f].insert(g); // always insert both ways
m_adjacency[g].insert(f);
}
}
}
void build_visible_set(const unsigned int& pointid, const unsigned int& faceid, std::vector< unsigned int >& visible)
{
// std::cout << "building visible set point: "<< pointid << " face: " << faceid << std::endl;
assert(m_dim == 3); // This assumes 3d!
visible.clear();
visible.push_back(faceid);
std::queue<unsigned int> worklist;
std::vector<bool> found(m_deleted);
worklist.push(faceid);
found[faceid] = true;
// std::cout << "point id: " << pointid << ", face id: " << faceid << std::endl;
while(!worklist.empty())
{
unsigned int f = worklist.front();
worklist.pop();
// std::cout << "face " << f << ": " << "[ " << m_faces[f][0] << ", " << m_faces[f][1] << ", " << m_faces[f][2] << "] "<< std::endl;
if(m_deleted[f]) continue;
// std::cout << " m_adjacency.size = "<< m_adjacency.size() << " m_adjacency["<<f<<"].size = "<< m_adjacency[f].size() << std::endl;
for(std::set<unsigned int>::iterator i = m_adjacency[f].begin(); i != m_adjacency[f].end(); i++)
{
// std::cout << "found: " << found[*i] << " - neighbor "<< *i << ": " << "[ " << m_faces[*i][0] << ", " << m_faces[*i][1] << ", " << m_faces[*i][2] << "] "<< std::endl;
if(!found[*i]) // face was not found yet and the point is above the face.
{
found[*i] = true;
if( is_above(pointid, *i) )
{
assert(!m_deleted[*i]);
worklist.push(*i);
visible.push_back(*i);
}
}
}
}
}
void build_horizon_set(const std::vector< unsigned int >& visible, std::vector< std::vector<unsigned int> >& horizon)
{
assert(m_dim == 3); // This assumes 3d!
std::vector< std::vector<unsigned int> > edges;
for(unsigned int i = 0; i < visible.size(); i++)
edges_from_face(visible[i], edges); // all visible edges.
std::vector<bool> unique(edges.size(), true);
for(unsigned int i = 0; i < edges.size(); i++)
{
for(unsigned int j = i+1; j < edges.size() && unique[i]; j++)
{
if( (edges[i][0] == edges[j][0] && edges[i][1] == edges[j][1]) ||
(edges[i][1] == edges[j][0] && edges[i][0] == edges[j][1]) )
{
unique[i] = false;
unique[j] = false;
}
}
if(unique[i])
{
horizon.push_back(edges[i]);
}
}
}
// void build_edge_list()
// {
// return;
// std::vector< std::vector<unsigned int> > edges;
// for(unsigned int i = 0; i < m_faces.size(); i++)
// edges_from_face(i, edges); // all edges.
//
// for(unsigned int i = 0; i < edges.size(); i++)
// {
// bool unique = true;
// for(unsigned int j = i+1; j < edges.size(); j++)
// {
// if(edges[i][0] == edges[j][0] && edges[i][1] == edges[j][1])
// {
// unique = false;
// }
// }
// if(unique)
// {
// m_edges.push_back(edges[i]);
// }
// }
// }
void remove_deleted_faces()
{
std::vector< std::vector<unsigned int> >::iterator f;
std::vector< bool >::iterator d;
bool bContinue = true;
while(bContinue)
{
bContinue = false;
d = m_deleted.begin();
f = m_faces.begin();
for(; f != m_faces.end() && d != m_deleted.end(); f++, d++)
{
if(*d)
{
m_faces.erase(f);
m_deleted.erase(d);
bContinue = true;
break;
}
}
}
m_adjacency.clear(); // the id's of the faces are all different so just clear the list.
}
public:
const std::vector< std::vector<unsigned int> >& getFaces() { return m_faces; }
// const std::vector< std::vector<unsigned int> >& getEdges() { return m_edges; }
const std::vector< VectorRn<P,D> >& getPoints() { return m_points; }
void moveData(std::vector< std::vector<unsigned int> >& faces, std::vector< VectorRn<P,D> >& points)
{
// NOTE: *this is not valid after using this method!
faces = std::move(m_faces);
points = std::move(m_points);
}
protected:
size_t m_dim;
VectorRn<P,D> m_ravg;
std::vector< VectorRn<P,D> > m_points;
std::vector< std::vector<unsigned int> > m_faces; // Always have d vertices in a face.
std::vector< VectorRn<P,D> > m_normals;
// std::vector< std::vector<unsigned int> > m_edges; // Always have 2 vertices in an edge.
std::vector< std::set<unsigned int> > m_adjacency; // the face adjacency list.
std::vector<bool> m_deleted;
};
template<class P>
class GrahamScan
{
public:
template<class VectorType>
GrahamScan(const std::vector< VectorType >& points)
{
assert(points.size() > 0);
m_points.resize(points.size());
for(int i = 0; i < points.size(); i++)
{
m_points[i] = points[i]; // copies the points.
}
m_dim = dim(m_points[0]).value;
}
template<class MatrixType>
GrahamScan(const MatrixType& points)
{
m_dim = dim(points).value;
m_points.reserve(points.cols());
for(int i = 0; i < points.cols(); i++)
{
m_points.push_back(points.col(i));
}
}
template<class OutputIterator, class IndexIterator=int>
void compute(OutputIterator hull, IndexIterator first=0, IndexIterator last=0, VectorRn<P, 3> normal = {0,0,1}, P tol=tolerance<P>())
{
std::vector<int> Index(__make_index_vector(first, last, m_points.size()));
size_t N = Index.size();
SubSpace<P> plane(m_points, Index, 3, tol);
if(plane.dim() != 2)
{
std::cerr << "output: \n" << plane.basis() << std::endl;
throw std::runtime_error("Graham Scan is only valid on 2D subspaces");
}
VectorRn<P,3> e1 = plane.basis().col(0);
VectorRn<P,3> e2 = plane.basis().col(1);
e1.normalize();
e2.normalize();
support_function<P> supp(m_points, Index.begin(), Index.end());
normal.normalize();
counter_clockwise<P> ccw(supp.element(e1), normal);
std::function<bool(const int&, const int&)> lessfn = ccw.template lessfn<int, std::vector< VectorRn<P,3> > >(m_points);
std::vector<int> points(Index);
std::sort(points.begin(), points.end(), lessfn);
points.insert(points.begin(), points.back());
int M = 1;
for(int i = 2; i < N+1; i++)
{
while(!ccw(m_points[points[M-1]], m_points[points[M]], m_points[points[i]]) )
{
if( M > 1) M--;
else if(i >= N) break;
else i++;
}
M++;
std::swap(points[M], points[i]);
}
std::copy(points.begin(), points.begin()+M, hull);
}
protected:
size_t m_dim;
std::vector< VectorRn<P,3> > m_points;
};
}
| true |
c3e21d3c5316ba4cf9bb59b2c41ee9e673abe8bb | C++ | wangwangbuaa/leetcode_interview | /剑指offer/剑指offer30_包含min函数的栈.cpp | UTF-8 | 959 | 3.71875 | 4 | [] | no_license | /*
返回一个包含栈中最小元素的栈,实践复杂度是O(1)
*/
#include<iostream>
#include<stack>
#include<vector>
#include<climits>
using namespace std;
class Solution
{
public:
void push(int value)
{
stack1.push(value);
if(stack2.size()<1)
stack2.push(value);
else
{
if(stack2.top()>value)
stack2.push(value);
else
stack2.push(stack2.top());
}
}
void pop()
{
if(stack1.size()<1)
return;
else
{
stack1.pop();
stack2.pop();
}
}
int top()
{
if(stack1.size()<1)
throw "error";
else
return stack1.top();
}
int min()
{
if(stack2.size()<1)
throw "error";
else
return stack2.top();
}
private:
stack<int> stack1;
stack<int> stack2;
};
| true |
de1a5196041c2c87bbb52edd7ed493ffebfc23b6 | C++ | ArtemNikolaev/opp-in-cpp | /ch05/_retref.cpp | UTF-8 | 160 | 2.8125 | 3 | [] | no_license | #include <iostream>
int x;
int& setx();
int main() {
setx() = 92;
std::cout << "x=" << x << std::endl;
return 0;
}
int& setx() {
return x;
} | true |
72abb466fb9324965101c9d576ab6cfb4417c1ac | C++ | alexandraback/datacollection | /solutions_2749486_1/C++/Mathew24/main.cpp | UTF-8 | 1,134 | 2.890625 | 3 | [] | no_license | #include <cstdio>
#include <vector>
#include <algorithm>
#define FOR(a,b) for(int a=0; a<b; a++)
#define ABS(a) ((a)<0 ? (-(a)) : (a))
using namespace std;
vector < char > solution;
int tryN(int n, int x, int y){
solution.resize(0);
while (n>0){
if(ABS(x) > ABS(y)){
if(x>0){
x-=n;
solution.push_back('E');
}else{
x+=n;
solution.push_back('W');
}
}else{
if(y>0){
y-=n;
solution.push_back('N');
}else{
y+=n;
solution.push_back('S');
}
}
n--;
}
return x==0 && y==0;
}
int Len(int n, int x, int y){
return tryN(n, x,y) || tryN(n-2, x,y);
}
void solveCase(){
int x, y;
scanf("%d", &x);
scanf("%d", &y);
int lowB=0;
int upB=1;
while(!Len(upB, x ,y))
upB*=2;
while (upB-lowB>4){
if(Len((upB+lowB)/2, x ,y))
upB=(upB+lowB)/2;
else
lowB=(upB+lowB)/2;
}
int min=10000000;
for(int i = lowB-2; i<upB+2; i++)
if(tryN(i, x, y)){
min=i;
break;
}
FOR(i, solution.size())
printf("%c", solution[solution.size()-i-1]);
}
int main(){
int T;
scanf("%d", &T);
FOR(i,T){
printf("Case #%d: ", i+1);
solveCase();
printf("\n");
}
}
| true |
8654814498208a17f280ebb88d4d968ce80da7b2 | C++ | jacob-hegna/jhcrypto | /src/AES/AES.cpp | UTF-8 | 4,526 | 2.96875 | 3 | [] | no_license | #include "AES.h"
jhc::buffer jhc::AES::encrypt_block(jhc::buffer block, jhc::buffer key, jhc::AES::Mode mode) {
// establish Nr and Nk constants for the AES mode
uint key_length = 0;
uint rounds = 0;
switch(mode) {
case Mode::AES_128: key_length = 4 * 4; rounds = 10; break;
case Mode::AES_192: key_length = 6 * 4; rounds = 12; break;
case Mode::AES_256: key_length = 8 * 4; rounds = 14; break;
}
// ensure our buffers are of the correct size
if(block.size() != 16)
throw jhc::AES::AES_error("jhc::AES::encrypt_block has failed: incorrect block size!");
if(key.size() != key_length)
throw jhc::AES::AES_error("jhc::AES::encrypt_block has failed: incorrect key size!");
// initialize the state
jhc::matrix<uint8_t> state(4, 4);
for(uint i = 0; i < 16; ++i) {
state.set(i / 4, i % 4, block.at(i));
}
// begin the AES cipher
for(uint i = 0; i < rounds - 1; ++i) {
state = jhc::AES::sub_bytes(state);
state = jhc::AES::shift_rows(state);
state = jhc::AES::mix_cols(state);
state = jhc::AES::add_round_key(state);
}
jhc::buffer output;
for(uint i = 0; i < 16; ++i) {
output.push(state.get(i / 4, i % 4));
}
return output;
}
jhc::matrix<uint8_t> jhc::AES::sub_bytes(jhc::matrix<uint8_t> state) {
static const uint8_t S_box_table[] = {
0x063, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
0x0ca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
0x0b7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
0x004, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
0x009, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
0x053, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
0x0d0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
0x051, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
0x0cd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
0x060, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
0x0e0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
0x0e7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
0x0ba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
0x070, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
0x0e1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
0x08c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16
};
jhc::matrix<uint8_t> new_state(4, 4);
for(uint i = 0; i < 4; ++i) {
for(uint j = 0; j < 4; ++j) {
new_state.set(i, j, S_box_table[state.get(i, j)]);
}
}
return new_state;
}
jhc::matrix<uint8_t> jhc::AES::shift_rows(jhc::matrix<uint8_t> state) {
jhc::matrix<uint8_t> new_state(4, 4);
for(uint8_t i = 0; i < 4; ++i) {
for(uint8_t j = 0; j < 4; ++j) {
new_state.set(i, j, state.get(i, (j + i) % 4));
}
}
return new_state;
}
jhc::matrix<uint8_t> jhc::AES::mix_cols(jhc::matrix<uint8_t> state) {
jhc::matrix<uint8_t> new_state(4, 4);
auto m1 = [] (uint8_t v) {
return v;
};
auto m2 = [] (uint8_t v) {
uint8_t r = v << 1;
r ^= (v & 0b10000000) == 0b10000000 ? 0x1b : 0x00;
return r;
};
auto m3 = [m1, m2] (uint8_t v) {
uint8_t r = m2(v);
r ^= m1(v);
return r;
};
for(uint8_t j = 0; j < 4; ++j) {
new_state.set(0, j, m2(state[0][j]) ^ m3(state[1][j]) ^ m1(state[2][j]) ^ m1(state[3][j]));
new_state.set(1, j, m1(state[0][j]) ^ m2(state[1][j]) ^ m3(state[2][j]) ^ m1(state[3][j]));
new_state.set(2, j, m1(state[0][j]) ^ m1(state[1][j]) ^ m2(state[2][j]) ^ m3(state[3][j]));
new_state.set(3, j, m3(state[0][j]) ^ m1(state[1][j]) ^ m1(state[2][j]) ^ m2(state[3][j]));
}
return new_state;
} | true |
ad5c7ac7f09a6cac87a305e25f0046beb3a9a9ed | C++ | mnickrogers/data-structures | /cpp/linked_list/node.hpp | UTF-8 | 1,028 | 3.28125 | 3 | [] | no_license | //
// node.hpp
// linked_list
//
// Created by Nicholas Rogers on 7/23/19.
// Copyright © 2019 Nicholas Rogers. All rights reserved.
//
#ifndef node_hpp
#define node_hpp
#include <iostream>
template <class T>
class Node
{
public:
Node()
{
_previous = _next = nullptr;
}
Node(T data)
{
_previous = _next = nullptr;
_data = data;
}
// ~Node()
// {
// delete _data;
// }
Node<T> * get_next() const
{
return _next;
}
Node<T> * get_previous() const
{
return _previous;
}
void set_next(Node<T> * next)
{
_next = next;
}
void set_previous(Node<T> * previous)
{
_previous = previous;
}
T get_data() const
{
return _data;
}
void set_data(T data)
{
_data = data;
}
private:
Node<T> * _previous;
Node<T> * _next;
T _data;
};
#endif /* node_hpp */
| true |
c4654f51ae0d7c53472266d4cb0e640db0280eb9 | C++ | Plantyplantyplanty/CS3A | /shunting_yard.h | UTF-8 | 927 | 2.703125 | 3 | [] | no_license | #define _CRTDBG_MAP_ALLOC
#ifndef SHUNTING_Y_H
#define SHUNTING_Y_H
//REMOVE INTERNALS, DUPLICATE ALL OF HIS TESTS
#include "Queue.h"
#include "Token.h"
#include "Stack.h"
#include "Number.h"
#include "Operator.h"
#include "RightParen.h"
#include "LeftParen.h"
#include "Variable.h"
#include "Function.h"
class shunting_yard{
public:
shunting_yard(const Queue<Token*>& infix);
//hands infix over to get_postfix() to be converted to postfix notation
Queue<Token*> postfix();
//returns the postfix expression
friend ostream& operator <<(ostream& outs, const shunting_yard& t);
private:
Queue<Token*> _tokens; //an infix notation queue
void get_postfix(Queue<Token*> infix); //LOGICALLY the same thing as const& then making a copy
//creates the postfix queue
void postfix_op(Stack<Token*> &ops, Queue<Token*>& postfix, Token *t);
//deals with the operator case
};
#endif | true |
1d896ddc2ef64d2d18b20066413640b43e51b6d3 | C++ | Joe-Demp/CompetitionCoding | /Deitel&Deitel/Chpt14/Stack.h | UTF-8 | 1,149 | 3.6875 | 4 | [] | no_license | // Stack code taken from fig 14.2 Deitel&Deitel
template<typename T>
class Stack
{
public:
explicit Stack(int = 10);
// destructor - to deal with dynamic memory
~Stack()
{
delete [] stackPtr;
}
bool push(const T &);
bool pop(T &);
bool isEmpty() const
{
return top == -1;
}
bool isFull() const
{
return top == size - 1;
}
private:
int size;
int top;
T *stackPtr;
};
template<typename T>
Stack<T>::Stack(int s)
: size(s > 0 ? s : 10),
top(-1),
stackPtr(new T[size])
{
// empty constructor
}
template<typename T>
bool Stack<T>::push(const T &pushValue)
{
if (!isFull())
{
stackPtr[++top] = pushValue;
return true;
}
return false;
}
template<typename T>
bool Stack<T>::pop(T &popValue)
{
if (!isEmpty())
{
popValue = stackPtr[top--];
return true;
}
return false;
}
// Note each method needs the template<..> heading
// e.g. a test function template
template<typename T>
void testStack(Stack<T> &theStack, T value, T increment, const string stackName)
{
// work....
}
// Notice: compiler infers the type of T from the first argument in list
// i.e. passing a Stack<int> => value, increment : int | true |
099098f3b7aefdf7be10155e0cf1dbccab193740 | C++ | xeon2007/WSProf | /Components/Sourcecode/AIC/MailSender/TestMailSender/TestLocalTempCopyOfFile.cpp | UTF-8 | 5,191 | 2.546875 | 3 | [] | no_license | #include "stdafx.h"
#ifndef _INHIBIT_TESTING_CODE
#include "TestLocalTempCopyOfFile.h"
#include "..\LocalTempCopyOfFile.h"
#include "..\..\..\..\..\Common\Libraries\No MFC\General\General.h"
#include "..\..\..\..\..\Common\Libraries\No MFC\General\FilePath.h"
BEGIN_TEST_SUITE(TestLocalTempCopyOfFile)
ADD_TEST_METHOD(TestIsolatesACopyOfTheFile_ThenDeletesCopyOnDestruction)
ADD_TEST_METHOD(TestResizeOfStringWithOKlength)
ADD_TEST_METHOD(TestResizeOfStringTooLong)
ADD_TEST_METHOD(TestResizeOfEmptyString)
END_TEST_SUITE()
#define TEST_FILE TEST_PATH_MAKE_ABSOLUTE(_T("Test Files\\TestMailSender\\FileForTesting_WithOriginalName.doc"))
bool TestLocalTempCopyOfFile::canRun(std::tstring& sReason)
{
sReason= _T("Why this should not run");
return true;
}
void TestLocalTempCopyOfFile::setUpSuite()
{
::DeleteFile(CGeneral::GetTemporaryFileName().c_str()); // Here to prevent fake detection of a memory leak.
}
void TestLocalTempCopyOfFile::setUp()
{
}
void TestLocalTempCopyOfFile::tearDownSuite()
{
}
void TestLocalTempCopyOfFile::tearDown()
{
}
void TestLocalTempCopyOfFile::TestIsolatesACopyOfTheFile_ThenDeletesCopyOnDestruction()
{
Gen::CFilePath sTempCopy(_T(""));
CStdString sDescriptiveName(_T("NiceDescriptiveName.doc"));
{
LocalTempCopyOfFile localCopy(TEST_FILE, sDescriptiveName);
sTempCopy = localCopy.GetFullPath();
assertMessage(CGeneral::FileExists(sTempCopy.c_str()), _T("This temp copy should be created when the object is instantianted."));
assertMessage(sTempCopy.GetFileName() == sDescriptiveName, _T("The temporary copy should have the descriptive filename, not that of the original file."));
assertMessage(CGeneral::FileExists(TEST_FILE), _T("This file shouldn't be deleted when the copy is made. This is not the Isolator."));
}
int count = 300;
while(CGeneral::FileExists(sTempCopy.c_str()) && --count > 0)
{
::Sleep(100);
}
assertMessage(!CGeneral::FileExists(sTempCopy.c_str()), _T("Should delete the file on destruction."));
assertMessage(CGeneral::FileExists(TEST_FILE), _T("This file shouldn't be deleted when the copy is deleted."));
// TODO: Find out why this fails sometimes on the integration machine (TT/2009/05/13)
//CStdString sContainingTempFolder = sTempCopy.GetDirectory();
//count = 300;
//while(CGeneral::DirectoryExists(sContainingTempFolder.c_str()) && --count > 0)
//{
// ::Sleep(100);
//}
//assertMessage(!CGeneral::DirectoryExists(sContainingTempFolder.c_str()), _T("We should clean up the folder too."));
}
void TestLocalTempCopyOfFile::TestResizeOfStringWithOKlength()
{
LocalTempCopyOfFile sTemp;
CStdString sPath(L"x");
CStdString sTest1(L"1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123.doc"); //257 character string
CStdString sTest2(L"1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123.doc"); //257 character string - should be unchanged
assertTest(sTemp.MakeFileNameShorter(sPath, sTest1).Equals(L"1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123.doc")); //257 character string
assertTest(sTemp.MakeFileNameShorter(sPath, sTest2).GetLength() == 257);
}
void TestLocalTempCopyOfFile::TestResizeOfStringTooLong()
{
LocalTempCopyOfFile sTemp;
CStdString sPath(L"x");
CStdString sTest1(L"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567.doc");
CStdString sTest2(L"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567.doc"); //261 character string - should be shortened by 4
assertTest(sTemp.MakeFileNameShorter(sPath, sTest1).Equals(L"1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123.doc")); //257 character string
assertTest(sTemp.MakeFileNameShorter(sPath, sTest2).GetLength() == 257 );
}
void TestLocalTempCopyOfFile::TestResizeOfEmptyString()
{
LocalTempCopyOfFile sTemp;
CStdString sPath(L"x");
CStdString sTest1(L"");
CStdString sTest2(L"");
assertTest(sTemp.MakeFileNameShorter(sPath, sTest1).Equals(L""));
assertTest(sTemp.MakeFileNameShorter(sPath, sTest2).GetLength() == 0);
}
// {END_IMPL}
#endif // _INHIBIT_TESTING_CODE
| true |
f6da7c7e7bda8b51f1dd44a9b291c0722e6e2613 | C++ | sebrockm/PA_TimeWarp | /Brocken_Physik/Heap.h | UTF-8 | 1,320 | 2.953125 | 3 | [] | no_license | #ifndef _HEAP_H_
#define _HEAP_H_
#include "Array.h"
#include "cuda_macro.h"
#include "types.h"
template <class T, u32 Size>
class Heap{
private:
Array<T, Size> ar;
u32 count;
public:
CUDA_CALLABLE_MEMBER Heap():ar(), count(0){}
CUDA_CALLABLE_MEMBER u32 length() const {
return count;
}
CUDA_CALLABLE_MEMBER bool empty() const {
return count == 0;
}
CUDA_CALLABLE_MEMBER bool full() const {
return count == Size;
}
CUDA_CALLABLE_MEMBER void eraseAll(){
count = 0;
}
CUDA_CALLABLE_MEMBER void insert(const T& t){
u32 id = count++;
ar[id] = t;
while(id > 0){
u32 father = (id-1)/2;
if(ar[id] < ar[father]){
T tmp = ar[id];
ar[id] = ar[father];
ar[father] = tmp;
id = father;
}
else{
break;
}
}
}
CUDA_CALLABLE_MEMBER const T& top() const {
return ar[0];
}
CUDA_CALLABLE_MEMBER T peek(){
T erg = ar[0];
ar[0] = ar[--count];
u32 id = 0;
u32 left = 1;
while(left < count){//solange linker Sohn vorhanden
if(ar[left] < ar[id] || left+1 < count && ar[left+1] < ar[id]){
u32 tausch = left;
if(left+1 < count && ar[left+1] < ar[left]){
tausch++;
}
T tmp = ar[id];
ar[id] = ar[tausch];
ar[tausch] = tmp;
id = tausch;
left = id*2 + 1;
}
else{
break;
}
}
return erg;
}
};
#endif | true |
0a048533a95ca174e59a9bfe4d62c850facafbdf | C++ | Lucas3H/Maratona | /CodCad/CodCad-ContagemdeAlgarismos.cpp | UTF-8 | 390 | 2.671875 | 3 | [] | no_license | #include <iostream>
#define MAXN 100000
using namespace std;
int main(){
int n;
int s[MAXN];
int v[10];
cin >> n;
for (int i = 0; i < n; i++){
cin >> s[i];
while (true){
if(s[i] < 10){
v[s[i]]++;
break;
}
v[s[i]%10]++;
s[i]/=10;
}
}
for(int i=0; i<10 ; i++) cout << i << " - " << v[i] << endl;
return 0;
}
| true |
ba25e7048e2041938cc4f9915c30d3f488ed7878 | C++ | simonrg/data-structures-patterns | /Spike 13 - Composite Pattern/World.h | UTF-8 | 1,508 | 2.828125 | 3 | [] | no_license | #include <map>
#include <vector>
#include "Component.h"
class Location{
private:
MetaComponent info;
CollectionComponent item_ids;
PositionComponent position;
LocationManagerComponent l;
public:
Location(){};
Location(vector<string>);
MetaComponent& Info(){ return info; }
CollectionComponent& Items(){ return item_ids; }
PositionComponent& Position(){ return position; }
LocationManagerComponent& LocationManager(){ return l; }
};
class Item{
private:
MetaComponent info;
CollectionComponent items;
public:
Item(){};
Item(vector<string>);
MetaComponent& Info(){ return info; }
CollectionComponent& Items(){ return items; }
};
class Player{
private:
HealthComponent health;
PositionComponent position;
CollectionComponent items;
bool playing = true;
public:
HealthComponent& Health(){ return health; }
PositionComponent& Position(){ return position; }
CollectionComponent& Items(){ return items; }
//information specific to a player object
bool getPlayState(){ return playing; }
void setPlayState(bool state){ playing = state; }
};
class World{
private:
Player player = Player();
MetaComponent info;
WorldResourcesComponent w;
LocationManagerComponent lm;
public:
MetaComponent& Info(){ return info; }
WorldResourcesComponent& Resources(){ return w; }
LocationManagerComponent& LocationManager(){ return lm; }
//information specific to a world object
void setPlayer(Player player_instance){ player = player_instance; }
Player getPlayer(){ return player; }
}; | true |
11a7ae729a7e1f0b3c2771dbf9ea8394d083ec7c | C++ | amengede/cpp-practice | /team.cpp | UTF-8 | 853 | 3.734375 | 4 | [] | no_license | /*
How many problems to attempt?
A team has 3 members and is given n problems. For each problem, each team member knows whether they can solve it.
The team will only attempt a problem if 2 out of 3 of them can solve it. How many problems can they attempt?
input: standard, no. of problems and the data set where row=problem and column=team member, 0=can't solve, 1=can solve
output: no. of problems the team can attempt
example:
3
1 1 0
1 1 1
1 0 0
2
*/
#include <iostream>
using namespace std;
int main()
{
int n, temp, thisP = 0, problems = 0;
cin >> n;
for (int i = 0;i < n;i++) {
int thisP = 0;
for(int j = 0;j < 3;j++) {
cin >> temp;
thisP += temp;
}
if (thisP >= 2) {
problems++;
}
}
cout << problems;
}
| true |
b780b5f2633d8bc9e51b468dfd04e91a273f2151 | C++ | wlsgur0726/asd | /asd_test/test_objpool.cpp | UTF-8 | 7,465 | 2.875 | 3 | [] | no_license | #include "stdafx.h"
#include "asd/objpool.h"
#include "asd/util.h"
#include "asd/random.h"
#include <thread>
#include <mutex>
#include <atomic>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <unordered_map>
namespace asdtest_objpool
{
std::atomic<int> g_objCount;
std::atomic<int> g_conCount_default;
std::atomic<int> g_conCount_param;
std::atomic<int> g_desCount;
void Init()
{
g_objCount = 0;
g_conCount_default = 0;
g_desCount = 0;
g_conCount_param = 0;
}
struct TestClass
{
char m_data[100];
TestClass() {
++g_objCount;
++g_conCount_default;
}
TestClass(int p1, void* p2) {
++g_objCount;
++g_conCount_param;
}
~TestClass() {
--g_objCount;
++g_desCount;
}
};
const int TestCount = 100;
template<typename ObjPool, int ThreadCount>
void TestObjPool()
{
// 1. AddCount 테스트
Init();
{
const int ObjCount = TestCount;
ObjPool objPool;
EXPECT_EQ(objPool.GetCount(), 0);
EXPECT_EQ(g_objCount, 0);
EXPECT_EQ(g_conCount_default, 0);
objPool.AddCount(ObjCount);
EXPECT_EQ(objPool.GetCount(), ObjCount);
EXPECT_EQ(g_objCount, 0);
EXPECT_EQ(g_conCount_default, 0);
}
// 2. ObjectPool 생성자의 인자 테스트
Init();
{
const int LimitCount = TestCount;
const int InitCount = TestCount + 123; // 사용자가 실수로 많이 넣는 경우
ObjPool objPool(LimitCount, InitCount);
EXPECT_EQ(objPool.GetCount(), LimitCount);
EXPECT_EQ(g_objCount, 0);
EXPECT_EQ(g_conCount_default, 0);
std::vector<TestClass*> objs;
// 2-1. initCount로 풀링되어있는 개수만큼
// 기본생성자로 Alloc을 하면서 풀에 남아있는 객체 수를 검사
const size_t FirstGetCount = objPool.GetCount();
for (size_t i=1; i<=FirstGetCount; ++i) {
objs.emplace_back(objPool.Alloc());
EXPECT_EQ(g_objCount, i);
EXPECT_EQ(g_conCount_default, i);
EXPECT_EQ(g_conCount_param, 0);
EXPECT_EQ(objPool.GetCount(), FirstGetCount - i);
}
// 2-2. 기존에 풀링되어있는 개수를 초과하여 Alloc,
// 더불어 생성하는 객체의 다른 생성자가 동작하는지 여부도 테스트
const size_t SecondGetCount = TestCount;
for (size_t i=1; i<=SecondGetCount; ++i) {
objs.emplace_back(objPool.Alloc(123, &objPool));
EXPECT_EQ(g_objCount, FirstGetCount + i);
EXPECT_EQ(g_conCount_default, FirstGetCount);
EXPECT_EQ(g_conCount_param, i);
EXPECT_EQ(objPool.GetCount(), 0);
}
// 2-3. 생성자 횟수와 풀링된 객체 수 검사
EXPECT_EQ(objPool.GetCount(), 0);
ASSERT_EQ(g_objCount, FirstGetCount + SecondGetCount);
ASSERT_EQ(g_objCount, objs.size());
ASSERT_EQ(g_conCount_default, FirstGetCount);
ASSERT_EQ(g_conCount_param, SecondGetCount);
// 2-4. 모두 반납. LimitCount보다 많이 풀링되어선 안된다.
ASSERT_GT(objs.size(), LimitCount);
const int ObjCount = g_objCount;
for (int i=1; i<=objs.size(); ++i) {
objPool.Free(objs[i-1]);
EXPECT_EQ(g_desCount, i);
EXPECT_EQ(g_objCount, ObjCount - i);
if (i < LimitCount)
EXPECT_EQ(objPool.GetCount(), i);
else
EXPECT_EQ(objPool.GetCount(), LimitCount);
}
EXPECT_EQ(objPool.GetCount(), LimitCount);
EXPECT_EQ(g_desCount, ObjCount);
EXPECT_EQ(g_objCount, 0);
}
// 3. 멀티쓰레드 테스트 (락이 있는 경우만)
Init();
if (ThreadCount > 1)
{
std::thread threads[ThreadCount];
ObjPool objPool;
volatile bool start = false;
for (auto& t : threads) {
t = std::thread([&]()
{
while (start == false);
for (int i=0; i<TestCount; ++i) {
TestClass* objs[TestCount];
// 3-1. 풀에서부터 할당
for (int i=0; i<TestCount; ++i) {
objs[i] = objPool.Alloc();
}
// 3-2. 할당받았던 것들을 풀에 반납
for (int i=0; i<TestCount; ++i) {
objPool.Free(objs[i]);
}
// 3-3. 랜덤하게 Clear나 AddCount등을 호출하여
// Thread Safe 여부를 테스트
switch (asd::Random::Uniform(0, 3)) {
case 0:
objPool.Clear();
break;
case 1:
objPool.AddCount(TestCount/10);
break;
default:
break;
}
}
});
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
start = true;
for (auto& t : threads)
t.join();
const int CheckCount = ThreadCount * TestCount * TestCount;
EXPECT_EQ(g_conCount_default, CheckCount);
EXPECT_EQ(g_desCount, CheckCount);
EXPECT_EQ(g_objCount, 0);
}
}
template<typename ObjPoolShardSet, int ThreadCount>
void ShardSetTest()
{
std::thread threads[ThreadCount];
ObjPoolShardSet shardSet;
// 해시 분포가 고른지 확인하기 위한 맵
struct Count
{
size_t Alloc = 0;
size_t Free = 0;
};
std::unordered_map<size_t, Count> Counter;
std::mutex lock;
volatile bool start = false;
volatile bool run = true;
for (auto& t : threads) {
t = std::thread([&]()
{
std::unordered_map<size_t, Count> t_Counter;
while (start == false);
do {
TestClass* objs[TestCount];
// 3-1. 풀에서부터 할당
for (int i=0; i<TestCount; ++i) {
objs[i] = shardSet.Alloc();
auto shard = *shardSet.template GetHeader<size_t>(objs[i]);
t_Counter[shard].Alloc++;
}
// 3-2. 할당받았던 것들을 풀에 반납
for (int i=0; i<TestCount; ++i) {
auto shard = *shardSet.template GetHeader<size_t>(objs[i]);
t_Counter[shard].Free++;
shardSet.Free(objs[i]);
}
} while (run);
lock.lock();
for (auto it : t_Counter) {
Counter[it.first].Alloc += it.second.Alloc;
Counter[it.first].Free += it.second.Free;
}
lock.unlock();
});
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
start = true;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
run = false;
for (auto& t : threads)
t.join();
Count sum;
for (auto it : Counter) {
auto print = asd::MString::Format(" [{}] ", it.first);
print << it.second.Alloc << " " << it.second.Free;
printf("%s\n", print.c_str());
sum.Alloc += it.second.Alloc;
sum.Free += it.second.Free;
}
auto print = asd::MString::Format(" total : ");
print << sum.Alloc;
printf("%s\n", print.c_str());
EXPECT_EQ(g_objCount, 0);
EXPECT_EQ(sum.Alloc, sum.Free);
}
TEST(ObjectPool, Default)
{
typedef asd::ObjectPool<TestClass> Pool;
TestObjPool<Pool, 1>();
}
TEST(ObjectPool, WithStdMutex)
{
typedef asd::ObjectPool<TestClass, std::mutex> Pool;
TestObjPool<Pool, 4>();
}
TEST(ObjectPool, WithAsdMutex)
{
typedef asd::ObjectPool<TestClass, asd::Mutex> Pool;
TestObjPool<Pool, 4>();
}
TEST(ObjectPool, WithSpinMutex)
{
typedef asd::ObjectPool<TestClass, asd::SpinMutex> Pool;
TestObjPool<Pool, 4>();
}
TEST(ObjectPool, LockFree)
{
typedef asd::ObjectPool2<TestClass> Pool;
TestObjPool<Pool, 4>();
}
TEST(ObjectPool, ShardSet)
{
typedef asd::ObjectPool<TestClass> Pool0;
typedef asd::ObjectPool<TestClass, asd::Mutex> Pool1;
typedef asd::ObjectPool2<TestClass> Pool2;
// compile error
//typedef asd::ObjectPoolShardSet<Pool0> ShardSet0;
//ShardSetTest<ShardSet0, 4>();
typedef asd::ObjectPoolShardSet<Pool1> ShardSet1;
ShardSetTest<ShardSet1, 4>();
typedef asd::ObjectPoolShardSet<Pool2> ShardSet2;
ShardSetTest<ShardSet2, 4>();
}
}
| true |
7d2ae6aacf3bd9ce933eb5e47aafc1fae4c12ab2 | C++ | belazaras/teardrop | /OpenGL/Classes/Components/Camera.cpp | IBM852 | 2,051 | 3.34375 | 3 | [] | no_license | #include "Camera.h"
// Included here to avoid circular dependencies.
#include <GameObject.h>
#include <Input.h>
#include <Transform.h>
vector <Camera*> Camera::instances;
// Camera(float fieldOfView=45.0, float aspectRatio=16/9, float nearClippingPlane=0.1, float farClippingPlane=100)
Camera::Camera(GameObject *go)
{
// Beta, borrar.
this->enabled = true;
// Setting parent GameObject.
this->parent = go;
// Adding instance to static collection.
Camera::instances.push_back(this);
// Getting Transform from parent.
transform = this->parent->getComponent<Transform>();
// Setting up Projection Matrix with default values.
this->fieldOfView = 45.0f;
this->aspectRatio = 16.0f / 9.0f; // Por ah cambiar a valores de la window.
this->nearClippingPlane = 0.1f;
this->farClippingPlane = 1000.0f;
this->setUpProjMatrix();
}
void Camera::setUpProjMatrix()
{
this->projectionMatrix = glm::perspective(
this->fieldOfView, // The horizontal Field of View, in degrees : the amount of "zoom". Think "camera lens". Usually between 90 (extra wide) and 30 (quite zoomed in)
this->aspectRatio, // Aspect Ratio. Depends on the size of your window. Notice that 4/3 == 800/600 == 1280/960, sounds familiar ?
this->nearClippingPlane, // Near clipping plane. Keep as big as possible, or you'll get precision issues.
this->farClippingPlane // Far clipping plane. Keep as little as possible.
);
}
Camera::~Camera()
{
}
// Beta: Retrieves the first active camera at the moment. If none, returns null.
Camera* Camera::current()
{
int i = 0;
bool found = false;
Camera* result = nullptr;
while (i < instances.size() && !found)
{
if (instances[i]->enabled)
{
result = instances[i];
found = true;
}
i++;
}
return result;
}
mat4 Camera::getViewMatrix()
{
//It's returning a copy, right?
return viewMatrix;
}
mat4 Camera::getProjectionMatrix()
{
return projectionMatrix;
}
void Camera::update()
{
viewMatrix = glm::lookAt(transform->getPosition(), transform->getLookAt(), transform->getUp());
} | true |
45fa98ccb868919448b8986c77534b3a30143a37 | C++ | DenislavNedev/SDA | /LinkedList.cpp | UTF-8 | 721 | 3.890625 | 4 | [] | no_license | #include <iostream>
using namespace std;
struct Node {
int value;
Node* next;
};
class List {
public:
List() {
this->head = NULL;
this->tail = NULL;
}
void add(int value)
{
Node* temp = new Node;
temp->value = value;
temp->next = NULL;
if (head == NULL)
{
head = temp;
tail = temp;
temp = NULL;
}
else
{
tail->next = temp;
tail = temp;
}
}
void insertAtPosition(int value,int pos)
{
Node* temp = new Node;
temp->value = value;
Node* previous;
Node* current;
current = head;
for (int i = 1; i < pos; i++)
{
previous = current;
current = current->next;
}
previous->next = temp;
temp->next = current;
}
private:
Node* head;
Node* tail;
};
| true |
21bd9d85b0b0f1ff7a75f2b7d8f58373e99ef043 | C++ | HellicarAndLewis/InMotion | /Basic/src/ofApp.cpp | UTF-8 | 5,424 | 2.96875 | 3 | [
"MIT"
] | permissive | #include "ofApp.h"
/*
moved on to Vertical_Horizontal from this version.
key input:
h = hide/show GUI
f = toggle fullscreen
m = hide mouse
important: include ofxGui addons.
changes:
- random width toggle
- two widths to change sizes of different coloured rectangles
- lock width toggle makes uniform width for both sets of rectangles
- negative speed allows for scrolling in both directions
to do:
- find a smoother method of resetting the x-coordinates once they have reached the edge of the screen
- find a better method of driving the animation than ofGetElapsedTimeMillis()
- experiment with using matrices instead of for loops to draw different sized shapes with different colors
- gradient rectangles
- scroll vertically and horizontally
- change background color?
- try ofxtimeline
*/
//--------------------------------------------------------------
void ofApp::setup(){
gui.setup("panel");
// initiate GUI
gui.add(width1.setup("width 1", 150, 1, 400));
gui.add(width2.setup("width 2", 150, 1, 400));
// width of rectangles. ("name", initial value, min value, max value)
gui.add(speed.setup("speed", 5, -100, 100));
// speed at which rectangles move. ("name", initial value, min value, max value)
gui.add(color1.set("color 1", ofColor(0,0,10), ofColor(0,0), ofColor(255, 255)));
gui.add(color2.set("color 2", ofColor(250, 250, 250), ofColor(0,0), ofColor(255, 255)));
// (starting color, background color for the gui, opacity value (a))
gui.add(sine.setup("sine mode", false));
// initiate sine mode
gui.add(randomwidths.setup("random width", false));
// initiate random width mode
gui.add(lockwidths.setup("lock widths", true));
// start with widths locked at the same value
xloc = - 2 * ofGetWidth();
// start drawing the rectangles from behind the screen
frame = 0;
// counter for drawing rectangles successively
hide = false;
swapIn = new ofFbo();
swapOut = new ofFbo();
}
//--------------------------------------------------------------
void ofApp::update(){
if (sine == true){
randomwidths = false;
lockwidths = false;
int width = ofMap(sin(ofGetElapsedTimef()), -1, 1, 1, ofGetWidth());
width1 = width;
width2 = width;
}
// sinusoidal oscillation in the width. change last two values of ofMap to change the range of oscillation.
if (randomwidths == true){
lockwidths = false;
sine = false;
width1 = ofRandom(500);
width2 = ofRandom(300);
}
// randomize both widths
if (lockwidths == true){
randomwidths = false;
sine = false;
float width = width1;
width2 = width;
}
// lock both widths to the same value. must change width 1 in order to change width 2
if (xloc > 0){
xloc = - 2 * ofGetWidth();
}
// reset starting coordinate for drawing rectangles. really glitchy, find a smoother method
// keeps the for loop going - need to find a better method
xloc = xloc + speed;
// move rectangles by their x-coordinates
}
//--------------------------------------------------------------
void ofApp::draw(){
ofFill();
// set rectangles to fill mode
ofSetColor(color1);
ofDrawRectangle(xloc+width1*i, 0, width1, ofGetHeight());
ofSetColor(color2);
ofDrawRectangle(xloc+width2*i, 0, width2, ofGetHeight());
// draw every other rectangle a different color
// xloc+width*i gives a starting x-coordinate that shifts at a given rate.
// problem: because it starts from just double the screen, it can never be more than that, no matter how many it draws. this is why we shift the xloc periodically.
if (!hide){
gui.draw();
}
// gui must be drawn after the animation so that it is visible on top
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
if (key == 'f')
ofToggleFullscreen();
if (key == 'm')
ofHideCursor();
if (key == 'h')
hide = !hide;
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| true |
b13658bfd1c65671f6d55cbf42547cdeb29ed642 | C++ | Conun/abel | /abel/strings/str_split.cc | UTF-8 | 4,011 | 3.3125 | 3 | [
"BSD-3-Clause"
] | permissive | //
#include <abel/strings/str_split.h>
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <iterator>
#include <limits>
#include <memory>
#include <abel/log/raw_logging.h>
#include <abel/strings/ascii.h>
namespace abel {
namespace {
// This GenericFind() template function encapsulates the finding algorithm
// shared between the by_string and by_any_char delimiters. The FindPolicy
// template parameter allows each delimiter to customize the actual find
// function to use and the length of the found delimiter. For example, the
// Literal delimiter will ultimately use abel::string_view::find(), and the
// AnyOf delimiter will use abel::string_view::find_first_of().
template <typename FindPolicy>
abel::string_view GenericFind(abel::string_view text,
abel::string_view delimiter, size_t pos,
FindPolicy find_policy) {
if (delimiter.empty() && text.length() > 0) {
// Special case for empty std::string delimiters: always return a zero-length
// abel::string_view referring to the item at position 1 past pos.
return abel::string_view(text.data() + pos + 1, 0);
}
size_t found_pos = abel::string_view::npos;
abel::string_view found(text.data() + text.size(),
0); // By default, not found
found_pos = find_policy.Find(text, delimiter, pos);
if (found_pos != abel::string_view::npos) {
found = abel::string_view(text.data() + found_pos,
find_policy.Length(delimiter));
}
return found;
}
// Finds using abel::string_view::find(), therefore the length of the found
// delimiter is delimiter.length().
struct LiteralPolicy {
size_t Find(abel::string_view text, abel::string_view delimiter, size_t pos) {
return text.find(delimiter, pos);
}
size_t Length(abel::string_view delimiter) { return delimiter.length(); }
};
// Finds using abel::string_view::find_first_of(), therefore the length of the
// found delimiter is 1.
struct AnyOfPolicy {
size_t Find(abel::string_view text, abel::string_view delimiter, size_t pos) {
return text.find_first_of(delimiter, pos);
}
size_t Length(abel::string_view /* delimiter */) { return 1; }
};
} // namespace
//
// by_string
//
by_string::by_string(abel::string_view sp) : delimiter_(sp) {}
abel::string_view by_string::Find(abel::string_view text, size_t pos) const {
if (delimiter_.length() == 1) {
// Much faster to call find on a single character than on an
// abel::string_view.
size_t found_pos = text.find(delimiter_[0], pos);
if (found_pos == abel::string_view::npos)
return abel::string_view(text.data() + text.size(), 0);
return text.substr(found_pos, 1);
}
return GenericFind(text, delimiter_, pos, LiteralPolicy());
}
//
// ByChar
//
abel::string_view ByChar::Find(abel::string_view text, size_t pos) const {
size_t found_pos = text.find(c_, pos);
if (found_pos == abel::string_view::npos)
return abel::string_view(text.data() + text.size(), 0);
return text.substr(found_pos, 1);
}
//
// by_any_char
//
by_any_char::by_any_char(abel::string_view sp) : delimiters_(sp) {}
abel::string_view by_any_char::Find(abel::string_view text, size_t pos) const {
return GenericFind(text, delimiters_, pos, AnyOfPolicy());
}
//
// by_length
//
by_length:: by_length(ptrdiff_t length) : length_(length) {
ABEL_RAW_CHECK(length > 0, "");
}
abel::string_view by_length::Find(abel::string_view text,
size_t pos) const {
pos = std::min(pos, text.size()); // truncate `pos`
abel::string_view substr = text.substr(pos);
// If the std::string is shorter than the chunk size we say we
// "can't find the delimiter" so this will be the last chunk.
if (substr.length() <= static_cast<size_t>(length_))
return abel::string_view(text.data() + text.size(), 0);
return abel::string_view(substr.data() + length_, 0);
}
} // namespace abel
| true |
d9450dac67416219e21b6433cf7d964353b1e5c8 | C++ | TasnimZia/UniThings | /CSC101-CPP/CSE-101-master/Arrays.cp | UTF-8 | 891 | 3.328125 | 3 | [] | no_license | #include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
//DECLARATION
int n = 5;
int A[5];
//POPULATE
//srand(time(0));
srand(time(NULL));
int ll = 0, ul = 5;
for (int i = 0;i < n;i++)
{
//cout<<"Enter Number "<<i<<": ";
//cin>>A[i];
A[i] = ll + rand() % (ul - ll + 1);
}
//DISPLAY
cout<<"Array: ";
for (int i = 0;i < n;i++)
cout<<A[i]<<" ";
cout<<endl;
//SUM
int sum = 0;
for (int i = 0;i < n;i++)
sum += A[i];
cout<<"Sum: "<<sum<<endl;
//CUMULATIVE FREQUENCY
for (int i = 1;i < n;i++)
A[i] = A[i] + A[i - 1];
//DISPLAY
cout<<"Cumulative Freq Array: ";
for (int i = 0;i < n;i++)
cout<<A[i]<<" ";
cout<<endl;
return 0;
}
| true |
82e9152e3b2bd79a01fcbb127b9a28c4f3dc0977 | C++ | mon3/CPP_labs | /prog4/macierz.hpp | UTF-8 | 735 | 2.78125 | 3 | [] | no_license | #ifndef _macierz_hpp_
#define _macierz_hpp_
#include <iostream>
typedef std::pair <int, int> RozmiarMacierzy;
typedef std::pair <int, int> Polozenie;
class Macierz
{
public:
Macierz (std::istream &is);
// tworzy macierz na podstawie strumienia
Macierz (int n, int m);
// tworzy pustą (niezainicjowaną) macierz n x m
~Macierz ();
int element (int i, int j) const; // zwraca element macierzy (kopia przez wartość)
int &element (int i, int j); // zwraca ref. (można modyfikować!) do el. macierzy
RozmiarMacierzy rozmiar () const;
// zwraca rozmiar macierzy
private:
mutable int n_;
mutable int m_;
int *mac_ = nullptr;
void init(int n, int m);
friend std::ostream &operator<< (std::ostream &os, const Macierz &m);
};
#endif | true |
2e792fb509ebcad3fa1f69206e5c3c0ff0915e00 | C++ | liamst19/game-frame | /src/drawing/drawing_text.cpp | UTF-8 | 4,819 | 3.015625 | 3 | [
"MIT"
] | permissive | /** drawing_text.cpp
* Object for rendering text to screen.
*/
#include "drawing_text.h"
#include <string>
#include "drawing_element.h"
#include "../medialayer/medialayer_drawing_renderer.h"
namespace Drawing{
/** Constructor
* @text: Text content
* @ font_src, @font_size: Font source and size
* @x, @y: Text position
* @r, @g, @b, @alpha: Text color
*/
TextDrawing::TextDrawing(MediaLayer::Drawing_Renderer* renderer,
std::string text,
std::string font_src, int font_size,
int x, int y,
int r, int g, int b, int alpha):
DrawingElement(renderer, DrawingElement::Color{r, g, b, alpha}),
_text(text),
_font_src(font_src),
_font_size(font_size),
_position(DrawingElement::Position{x, y})
{
_initialize();
}
/** Constructor
* @text: Text content
* @ font_src, @font_size: Font source and size
* @position: Text position
* @color: Text color
*/
TextDrawing::TextDrawing(MediaLayer::Drawing_Renderer* renderer,
std::string text,
std::string font_src, int font_size,
DrawingElement::Position position,
DrawingElement::Color color):
DrawingElement(renderer, color),
_text(text),
_font_src(font_src),
_font_size(font_size),
_position(position)
{
_initialize();
}
/** Destructor
*/
TextDrawing::~TextDrawing()
{}
/** private function: _initialize()
* Initializes text object
*/
void TextDrawing::_initialize()
{
_initialize_texture();
}
/** private function: _initialize_texture
* Initializes texture in renderer
*/
void TextDrawing::_initialize_texture()
{
int index = -1;
index = _drawing_renderer
->initialize_text(_text,
_font_src, _font_size,
_position.x, _position.y,
_color.r, _color.g, _color.b, _color.alpha);
if(index > 0)
{
_texture_index = index;
}
else
{
// Something went wrong, throw exception?
}
}
/** private function: _update_texture
* Updates texture in renderer
*/
void TextDrawing::_update_texture()
{
bool result = false;
result = _drawing_renderer
->update_text(_texture_index,
_text,
_font_src, _font_size,
_color.r, _color.g, _color.b, _color.alpha);
if(!result)
{
// Something went wrong, throw exception?
}
}
/** public function: render()
* Renders text to screen
*/
bool TextDrawing::render()
{
return _drawing_renderer
->render_text(_texture_index,
_position.x, _position.y);
}
/** public function: text()
* Text content
*/
std::string TextDrawing::text()
{
return _text;
}
/** public function: update()
* update text
*/
void TextDrawing::update(std::string text)
{
_text = text;
bool result = false;
_update_texture();
}
/** public function: font_src()
* Location of font file
*/
std::string TextDrawing::font_src()
{
return _font_src;
}
/** public function: set_font
* Sets font file source and font size
* @source_path: Path of font file
* @size: font size
*/
void TextDrawing::set_font(std::string source_path, int size)
{
_font_src = source_path;
set_font_size(size);
}
/** public function: font_size
* Font size
*/
int TextDrawing::font_size()
{
return _font_size;
}
/** public function: set_font_size
* Sets font size
* @font_size: Font size
*/
void TextDrawing::set_font_size(int size)
{
_font_size = size;
}
/** public function: position
* Text position
*/
DrawingElement::Position TextDrawing::position()
{
return _position;
}
/** public function: set_position()
* Sets text position
* @position: Text position
*/
void TextDrawing::set_position(DrawingElement::Position position)
{
_position = position;
}
/** public function: texture_index
* Gets index for referring to cache of textures
* stored in the renderer
*/
int TextDrawing::texture_index()
{
return _texture_index;
}
} // namespace Drawing
| true |
6e6649d8bfb0bcb2021b021e129306edbca03ea0 | C++ | williamwii/ubc_proj | /cs314/a2/a2/pose.cpp | UTF-8 | 1,639 | 3.3125 | 3 | [] | no_license | #include <cstdlib>
#include <fstream>
#include <iostream>
#include <sstream>
#include "pose.hpp"
void readPoseFile(char const *path, std::vector<Pose> &poses) {
// Open the file.
std::ifstream fh;
fh.open(path);
while (fh.good()) {
double x, y, z;
std::vector<double> angles;
// Read a line from the file.
std::string line;
getline(fh, line);
// Skip empty lines, or comments.
if (!line.size() || line[0] == '#') {
continue;
}
// Push the line into a stringstream so we can easily pull out doubles.
std::stringstream ss;
ss << line;
// Read translation coordinates.
ss >> x;
ss >> y;
ss >> z;
// Read angles while there is still stuff to read.
while (ss.good()) {
double a;
ss >> a;
angles.push_back(a);
}
poses.push_back(Pose(x, y, z, angles));
}
}
void writePoseFile(char const *path, Pose const &pose) {
// Try to open the file.
std::ofstream outFile;
outFile.open(path);
if (!outFile.good()) {
std::cerr << "could not open '" << path << "' for writing" << std::endl;
return;
}
// Write position.
outFile << pose.x_ << '\t';
outFile << pose.y_ << '\t';
outFile << pose.z_ << '\t';
// Write angles.
for (unsigned int i = 0; i < pose.angles_.size(); i++) {
outFile << pose.angles_[i] << '\t';
}
// All done!
outFile.close();
}
| true |
1d8e19dda28374cd4fb91682d6cf560e1093feee | C++ | MacgyverLin/FBXPreprocessor | /Vertex.h | UTF-8 | 1,669 | 3.109375 | 3 | [
"MIT"
] | permissive | #ifndef _Vertex_h_
#define _Vertex_h_
#include "Vector2.h"
#include "Vector3.h"
#include "Color.h"
#define NUM_COLORS 1
#define NUM_UVS 8
#define NUM_NORMALS 1
#define NUM_TANGENTS 1
#define NUM_BINORMALS 1
class Vertex
{
public:
Vertex();
Vertex(const Vector3& position, const Color& color, const Vector2& uv, const Vector3& normal, const Vector3& tangent, const Vector3& binormal);
Vertex(const Vector3& position, const Vector3& normal, const Vector2& uv);
Vertex(const Vertex& other);
// assignment
Vertex& operator = (const Vertex& other);
// comparison
int CompareArrays(const Vertex& v) const;
bool operator== (const Vertex& v) const;
bool operator!= (const Vertex& v) const;
bool operator< (const Vertex& v) const;
bool operator<= (const Vertex& v) const;
bool operator> (const Vertex& v) const;
bool operator>= (const Vertex& v) const;
// arithmetic operations
Vertex operator+ (const Vertex& v) const;
Vertex operator- (const Vertex& v) const;
Vertex operator* (const Vertex& v) const;
Vertex operator/ (const Vertex& v) const;
Vertex operator* (float fScalar) const;
Vertex operator/ (float fScalar) const;
Vertex operator- () const;
// arithmetic updates
Vertex& operator+= (const Vertex& v);
Vertex& operator-= (const Vertex& v);
Vertex& operator*= (const Vertex& v);
Vertex& operator*= (float fScalar);
Vertex& operator/= (float fScalar);
void Flip();
friend Vertex Lerp(const Vertex& v0, const Vertex& v1, float t);
Vector3 position;
Color colors[NUM_COLORS];
Vector2 uvs[NUM_UVS];
Vector3 normals[NUM_NORMALS];
Vector3 tangents[NUM_TANGENTS];
Vector3 binormals[NUM_BINORMALS];
};
#endif | true |
12af35f093c0df0a4fb8dbfd5ac9037c2583f014 | C++ | jmborr/code | /cpp/Heavy_atom_code/decapeptide_utils/turn_propensities.cpp | UTF-8 | 1,727 | 2.578125 | 3 | [] | no_license | #include "pdbClasses2.h"
using namespace std;
#include<fstream>
#include<string>
#include<cstring>
/*=================================================================*/
bool test_input(int argc, char ** argv ){
int number_of_arguments = argc -1 ;
if( number_of_arguments != 2 ){
system("clear");
cout << "Usage: ./turn_propensities.x pdbmov out\n";
cout << "pdbmov : movie en PDB format\n" ;
cout << "out : \"angle\" printed to \"out\" file\n";
cout << "\n";
return false ;
}
else return true ;
}
/*=====================================================*/
int main(int argc, char* argv[]){
/*check arguments*/
if( test_input(argc, argv) == false ) { return 1 ; }
/*retrieve input*/
ifstream PDBMOV(argv[1]); /*cout<<"PDBMOV="<<argv[1]<<endl;*/
ofstream OUT(argv[2]);
/*retrieve the five atom numbers*/
PDBatom prev_2,prev_1,curr,next_1,next_2 ;
PDBchain prot;
listPDBatom listCA;
int l;
double r;
char buff[5120],buff2[128];
double angle ; /*string line ; getline(PDBMOV,line);cout<<line<<endl;*/
while( PDBMOV>>prot ){
sprintf(buff,"");
prot.createCAchain(listCA);
listCA.renumberFully(1);
l=listCA.length();
prev_2=listCA.getAtomAtII(1);
prev_1=listCA.getAtomAtII(2);
curr =listCA.getAtomAtII(3);
next_1=listCA.getAtomAtII(4);
for(int i=5;i<=l;i++){
next_2=listCA.getAtomAtII(i);
/*cout<<prev<<endl<<curr<<endl<<next<<endl;*/
r=curr.radius(prev_2,next_2);
/*sprintf(buff2,"%6.2lf",r);*/
sprintf(buff2,"%4d %6.2lf\n",i-2,r);
strncat(buff,buff2,strlen(buff2));
prev_2=prev_1; prev_1=curr; curr=next_1; next_1=next_2;
}
OUT<<buff<<endl;
}
OUT.close();
return 0;
}
| true |
a432e4093a018fd13b12906d3defc63f8099607a | C++ | dima-bmstu/http_downloader | /src/HttpDownloader.cpp | UTF-8 | 3,364 | 2.875 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
#include <sstream>
#include "HttpDownloader.h"
#include "utils.h"
static constexpr char end_of_header[] = "\r\n\r\n";
static constexpr char content_length[] = "Content-Length: ";
HttpDownloader::HttpDownloader(std::unique_ptr<SaverInterface>&& saver,
std::unique_ptr<TcpInterface>&& tcp,
std::shared_ptr<ParserInterface<Url, std::string_view> > parser)
: saver(std::move(saver)), tcp(std::move(tcp)), url_parser(parser) {}
void HttpDownloader::download(std::string_view string_url, std::string_view filename) {
if (filename.empty())
thow_exception("filename is empty");
Url url = url_parser->parse(string_url);
if (url.host.empty())
thow_exception("url is empty");
if (url.protocol != "http")
thow_exception("protocol " + url.protocol + " is not supported");
tcp->connect(url.host, url.port);
std::cout << "Connection established" << std::endl;
tcp->write(make_request(url));
while (!response_header_received)
append_to_header(tcp->read());
saver->open(filename);
uint32_t received_bytes = 0;
if (!file_chunk.empty()) {
saver->save(file_chunk);
received_bytes += file_chunk.size();
}
while(received_bytes < file_size) {
auto data = tcp->read();
saver->save(data);
received_bytes += data.size();
print_progress(received_bytes);
}
saver->close();
std::cout << "\nFile downloaded and saved to file " << filename << std::endl;
}
std::string HttpDownloader::make_request(const Url& url) {
std::stringstream stream;
stream << "GET /" << url.path << (url.parameters.empty() ? "" : "?" + url.parameters) << " HTTP/1.1\r\n"
<< "Host: " << url.host << "\r\n";
if(!url.user.empty()) {
stream << "Authorization: Basic " << base64_encode(url.user + ":" + url.password) << "\r\n";
}
stream << "User-Agent: downloader\r\n\r\n";
return stream.str();
}
constexpr size_t HttpDownloader::string_size(std::string_view str) {
return str.size();
}
void HttpDownloader::append_to_header(std::string_view data) {
response_header.append(data);
size_t header_end_position = response_header.find(end_of_header);
if (header_end_position == response_header.npos)
return;
size_t length_posistion = response_header.find(content_length);
if (length_posistion == response_header.npos)
thow_exception("Cannot find Content-Length in header");
file_size = std::stol(response_header.substr(length_posistion + string_size(content_length),
response_header.find("\r\n", length_posistion)));
if (file_size == 0)
thow_exception("Wrong Content-Length");
response_header_received = true;
file_chunk = response_header.substr(header_end_position + string_size(end_of_header));
}
void HttpDownloader::print_progress(size_t received) {
std::cout << "\rReceived " << std::fixed << std::setprecision(0) << (static_cast<double>(received)/file_size)*100 << "% "
<< "(" << received << " bytes from " << file_size << ")" << std::flush;
}
void HttpDownloader::thow_exception(std::string error) {
throw std::runtime_error("HttpDownloader: " + error);
} | true |
fc87fec0eb270480c624a6a035922580fa6ba652 | C++ | harsh-agarwal/Competitive_programming | /part3/POINT/geometry.h | UTF-8 | 2,430 | 3.171875 | 3 | [] | no_license | #include <stdio.h>
#ifndef GEOMETRY_H_INCLUDED
#define GEOMETRY_H_INCLUDED
class point
{
private:
int x,y;
public:
point(int p=0,int q=0){x=p;
y=q;}
int GetX()const
{
return x;
}
int GetY()const
{
return y;
}
void SetX(const int new_X)
{
x=new_X;
}
void SetY(const int new_Y)
{
y=new_Y;
}
};
class PointArray
{
point *start;
int size;
public:
const int returnsize()
{
return size;
}
point *returnpointer()
{
return start;
}
PointArray()
{
size=0;
start=new point[size];
}
PointArray(const point Points[],const int length)
{
size=length;
start=new point[size];
for(int i=0;i<size;i++)
{
start[i].SetX(Points[i].GetX());
start[i].SetY(Points[i].GetY());
}
}
// PointArray(const PointArray &pv)
//{
// size =pv.returnsize();
//start=pv.returnpointer();
//}
~PointArray()
{
delete start;
}
private:
void resize(int n)
{
point *startNew;
startNew= new point[n];
for(int i=0;i<n;i++)
{
startNew[i]=start[i];
//startNew[i].SetX(start[i].GetX());
//startNew[i].SetY(start[i].GetY());
}
size=n;
//for(int i=0;i<n;i++)
//cout<<startNew[i].GetX();
delete[] start;
start=startNew;
}
public:
void push_back(point &p)
{
resize(size+1);
start[size-1].SetX(p.GetX());
start[size-1].SetY(p.GetY());
}
void insert(const int position,const point &p)
{
resize(size+1);
for(int i=(size-1);i>=(position-1);i--)
{
if(i==position-1)
{
start[i+1]=start[i];
start[i]=p;
}
else
start[i+1]=start[i];
}
}
void removal(const int pos)
{
for(int i=pos;i<size;i++)
start[i-1]=start[i];
resize(size-1);
}
const int getSize() const
{
return size;
}
void clear()
{
delete start;
size=0;
point *start;
start=new point[size];
}
};
#endif // GEOMETRY_H_INCLUDED
| true |
5b883e4827419ca4dfd3ce39ea7fbedfc74c1228 | C++ | dpalchak/estoppel | /estp/base/meta.hh | UTF-8 | 6,129 | 2.734375 | 3 | [
"MIT"
] | permissive | #pragma once
#include "estp/base/types.hh"
#include <cstdint>
#include <iterator>
#include <type_traits>
#include <utility>
namespace estp {
// Metaprogramming functions
// Credit: many of these are borrow from R. Martinho Fernandes
// See his website Flaming Dangerous (rmf.io)
// Saves redundant typename ... ::type
template<typename Meta>
using Invoke = typename Meta::type;
// Use a template function to get the value of a type so that it can be
// specialized if necessary
template<typename T>
constexpr auto GetValue(T const&) {
return T::value;
}
// Provide an alternative form that doesn't require type instantiation
template<typename T>
constexpr auto GetValue() {
return T::value;
}
// Simple identity/alias templates
// These are useful for inhibiting type deduction, since the compiler
// won't deduce dependent types
template <typename T>
struct Type { using type = T; };
template <typename T>
using Identity = Invoke<Type<T>>;
template<typename T>
using Decay = Invoke<::std::decay<T>>;
template<typename...>
using Void = void;
// Lazy bool type, useful for postponing evaluation of a compile-time expression
template<bool B, typename...>
struct LazyBool : public std::integral_constant<bool, B> {};
template<bool B, typename... T>
using Bool = LazyBool<B, T...>;
template<typename... T>
using True = Bool<true, T...>;
template<typename... T>
using False = Bool<false, T...>;
template<typename T>
using Not = Bool<!GetValue<T>()>;
template<typename If, typename Then, typename Else>
using Conditional = Invoke<::std::conditional<If::value,Then,Else> >;
// Meta-logical Or
template<typename... T>
struct Or : public False<T...> {};
template<typename Head, typename... Tail>
struct Or<Head, Tail...> : public Conditional<Head, True<>, Or<Tail...> > {};
// Meta-logical And
template<typename...>
struct And : public True<> {};
template<typename Head, typename... Tail>
struct And<Head, Tail...> : public Conditional<Head, And<Tail...>, False<> > {};
// Standard Library Type Traits as LazyBools
template<typename T>
using IsConst = Bool<::std::is_const<T>::value, T>;
template<typename T>
using IsIntegral = Bool<::std::is_integral<T>::value, T>;
template<typename T>
using IsSigned = Bool<::std::is_signed<T>::value, T>;
template<typename T>
using IsUnsigned = Bool<::std::is_unsigned<T>::value, T>;
template<typename T>
using IsClass = Bool<::std::is_class<T>::value, T>;
template<typename B, typename D>
using IsBaseOf = Bool<::std::is_base_of<B,D>::value, B, D>;
template<typename D, typename B>
using IsDerivedFrom = Bool<IsBaseOf<B,D>::value, D, B>;
template<typename T>
using IsAbstract = Bool<::std::is_abstract<T>::value, T>;
template<typename T>
using IsRvalue = Bool<::std::is_rvalue_reference<T&&>::value, T>;
template<typename T>
using IsLvalue = Bool<::std::is_lvalue_reference<T&>::value, T>;
template<typename T, typename S>
using IsSame = Bool<::std::is_same<T,S>::value, T, S>;
template<typename T, typename S>
using IsConvertible = Bool<::std::is_convertible<T,S>::value, T, S>;
template<typename T, typename = Void<> >
struct HasSize : False<T> {};
template<typename T>
struct HasSize<T, Void< decltype(std::size(std::declval<T>())) > > : True<T> {};
template<typename T, typename = Void<> >
struct HasData : False<T> {};
template<typename T>
struct HasData<T, Void< decltype(std::data(std::declval<T>())) > > : True<T> {};
// Control flow
template<typename If, typename Then=void>
using EnableIf = Invoke<::std::enable_if<If::value,Then> >;
template<typename T, typename C>
using EnableIfSame = EnableIf< IsSame<Decay<T>, Decay<C>> >;
template<typename T, typename C>
using EnableIfDifferent = EnableIf< Not< IsSame<Decay<T>, Decay<C>> > >;
// Traits
// Strips all reference and cv qualifiers from a type
template<typename T>
using Unqualified = Invoke< std::remove_reference< Invoke<::std::remove_cv<T> > > >;
template<typename T>
using AddConst = Invoke< std::add_const<T> >;
template<typename T>
using RemoveConst = Invoke< std::remove_const<T> >;
template<typename T>
using AddPointer = Invoke< ::std::add_pointer<T> >;
template<typename T>
using RemovePointer = Invoke< ::std::remove_pointer<T> >;
template<typename T>
using ElementType = RemovePointer<decltype(std::data(std::declval<T>()))>;
template<typename T>
struct FunctionTraits;
template<typename R, typename... A>
struct FunctionTraits<R(A...)> {
using ReturnType = R;
using ArgTypes = ::std::tuple<A...>;
using Signature = R(A...);
using PointerType = Signature *;
};
template<typename SIG>
using FunctionPointer = typename FunctionTraits<SIG>::PointerType;
template<typename T, typename C=void>
struct MethodTraits;
template<typename R, typename... A, typename C>
struct MethodTraits<R(A...), C> {
using ReturnType = R;
using ArgTypes = ::std::tuple<A...>;
using ClassType = C;
using Signature = R(A...);
using PointerType = Signature C::*;
};
template<typename R, typename... A, typename C>
struct MethodTraits<R(C::*)(A...), void> {
using ReturnType = R;
using ArgTypes = ::std::tuple<A...>;
using ClassType = C;
using Signature = R(A...);
using PointerType = Signature C::*;
};
template<typename R, typename... A, typename C>
struct MethodTraits<R(C::*)(A...) const, void> {
using ReturnType = R;
using ArgTypes = ::std::tuple<A...>;
using ClassType = C const;
using Signature = R(A...);
using PointerType = Signature ClassType::*;
};
template<typename SIG, typename C=void>
using MethodPointer = typename MethodTraits<SIG,C>::PointerType;
// Useful functions for working with Index sequences
template<Index... Is>
using IndexSequence = std::integer_sequence<Index, Is...>;
template<Index N>
using MakeIndexSequence = std::make_integer_sequence<Index, N>;
template<typename... T>
using IndexSequenceFor = MakeIndexSequence<sizeof...(T)>;
template<Index Offset, Index... Is>
constexpr auto AddOffsetToIndexSequence(IndexSequence<Is...>) -> IndexSequence<(Offset+Is)...> {
return {};
}
template <Index Offset, Index N>
using MakeOffsetIndexSequence = decltype(AddOffsetToIndexSequence<Offset>(MakeIndexSequence<N>{}));
} // namespace estp
| true |
d4ede1cf02a631692ab40469af82e257d613ec3a | C++ | usherfu/zoj | /zju.finished/2110.cpp | UTF-8 | 1,423 | 2.96875 | 3 | [] | no_license | #include<iostream>
// DFS + 剪枝,剪枝条件为奇偶性和数量
using namespace std;
enum {
SIZ = 7,
};
int tab[SIZ][SIZ];
int N,M,T;
int tx,ty,sx,sy, occupy;
int readIn(){
if(scanf("%d%d%d",&N,&M,&T) <= 0 || N + M + T ==0)
return 0;
char ch;
occupy = 0;
for(int i=0;i<N;i++){
for(int j=0;j<M;j++){
scanf(" %c", &ch);
tab[i][j] = 0;
switch(ch){
case 'X':
tab[i][j] = 2;
occupy++;
break;
case 'S':
sx = i; sy = j;
break;
case 'D':
tx = i, ty = j;
break;
}
}
}
return 1;
}
int test(int x, int y, int step){
if(step == T){
return (x == tx && y == ty);
}
tab[x][y] = 1;
if(x>0 && tab[x-1][y]==0 && test(x-1,y,step+1))
return 1;
if(x<N-1&&tab[x+1][y]==0 && test(x+1,y,step+1))
return 1;
if(y >0&&tab[x][y-1]==0 && test(x,y-1,step+1))
return 1;
if(y<M-1&&tab[x][y+1]==0&&test(x,y+1,step+1))
return 1;
return tab[x][y] = 0;
}
int fun(){
int step = tx - sx + ty - sy + T;
if(step % 2 == 1 || N*M - occupy <= T)
return 0;
return test(sx, sy, 0);
}
int main(){
const char *ans[2] = {"NO", "YES"};
while(readIn() > 0){
printf("%s\n", ans[fun()]);
}
return 0;
}
| true |
4d8f46a6bfa9ed83e6cd98cb8f3b76943d1b8fde | C++ | blegal/EN224-Test-et-verification | /2_Hardware/Etape_7/c_code/src/main.cpp | UTF-8 | 2,295 | 2.921875 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <paths.h>
#include <termios.h>
#include <sysexits.h>
#include <sys/param.h>
#include <sys/select.h>
#include <sys/time.h>
#include <time.h>
#include <cassert>
#include <iostream>
using namespace std;
void write_int(const int fileID, const int value)
{
int wBytes = write( fileID, &value, sizeof(int) );
assert( wBytes == (sizeof(int)) );
}
int read_int(const int fileID)
{
int value;
int rBytes = read( fileID, &value, sizeof(int) );
assert( rBytes == (sizeof(int)) );
return value;
}
int PGDC_v2(const int A, const int B)
{
int N1 = A;
int N2 = B;
int reste;
do
{
reste = N1 % N2;
N1 = N2;
N2 = reste;
}while(reste != 0);
return N1;
}
int main (int argc, char * argv []){
cout << "(II) Initialisation des composants..." << endl;
int fileDescriptor = -1;
fileDescriptor = open("/dev/ttyUSB1", O_RDWR | O_NOCTTY );
if(fileDescriptor == -1)
{
printf("Impossible d'ouvrir ttyUSB1 !\n");
return -1;
}
struct termios t;
tcgetattr(fileDescriptor, &t); // recupère les attributs
cfmakeraw(&t); // Reset les attributs
t.c_cflag = CREAD | CLOCAL; // turn on READ
t.c_cflag |= CS8;
t.c_cc[VMIN] = 0;
t.c_cc[VTIME] = 255; // 5 sec timeout
cfsetispeed(&t, B921600);
cfsetospeed(&t, B921600);
tcsetattr(fileDescriptor, TCSAFLUSH, &t); // envoie le tout au driver
int A = 32;
int B = 3;
if( argc == 3 )
{
A = atoi( argv[1] );
B = atoi( argv[2] );
}
write_int(fileDescriptor, A);
write_int(fileDescriptor, B);
const int C = read_int(fileDescriptor);
cout << "PGCD(" << A << ", " << B << ") = " << C << endl;
cout << "PGCD(" << A << ", " << B << ") = " << PGDC_v2(A,B) << endl;
for(int a = 1; a < 65535; a += 1)
{
for(int b = 1; b < 65535; b += 1)
{
if( b%256 == 0 ) cout << "PGCD(" << a << ", " << b << ")" << endl;
write_int(fileDescriptor, a);
write_int(fileDescriptor, b);
int hard = read_int(fileDescriptor);
int soft = PGDC_v2(a,b);
if( hard != soft )
cout << endl << b << " PGCD(" << a << ", " << b << ") => " << hard << " == " << soft << endl;
}
}
return 0;
}
| true |
d42a92c79e509751e2e6057641de431c8955e077 | C++ | CYR15000/Arduino-INA3221 | /examples/get_started/get_started.ino | UTF-8 | 1,357 | 2.78125 | 3 | [
"MIT"
] | permissive | #include <Wire.h>
#include <Beastdevices_INA3221.h>
#define SERIAL_SPEED 115200 // serial baud rate
#define PRINT_DEC_POINTS 3 // decimal points to print
// Set I2C address to 0x41 (A0 pin -> VCC)
Beastdevices_INA3221 ina3221(INA3221_ADDR41_VCC);
void setup() {
Serial.begin(SERIAL_SPEED);
while (!Serial) {
delay(1);
}
ina3221.begin();
ina3221.reset();
// Set shunt resistors to 10 mOhm for all channels
ina3221.setShuntRes(10, 10, 10);
}
void loop() {
float current[3];
float voltage[3];
current[0] = ina3221.getCurrent(INA3221_CH1);
voltage[0] = ina3221.getVoltage(INA3221_CH1);
current[1] = ina3221.getCurrent(INA3221_CH2);
voltage[1] = ina3221.getVoltage(INA3221_CH2);
current[2] = ina3221.getCurrent(INA3221_CH3);
voltage[2] = ina3221.getVoltage(INA3221_CH3);
Serial.print("Channel 1: ");
Serial.print(current[0], PRINT_DEC_POINTS);
Serial.print("A, ");
Serial.print(voltage[0], PRINT_DEC_POINTS);
Serial.println("V");
Serial.print("Channel 2: ");
Serial.print(current[1], PRINT_DEC_POINTS);
Serial.print("A, ");
Serial.print(voltage[1], PRINT_DEC_POINTS);
Serial.println("V");
Serial.print("Channel 3: ");
Serial.print(current[2], PRINT_DEC_POINTS);
Serial.print("A, ");
Serial.print(voltage[2], PRINT_DEC_POINTS);
Serial.println("V");
delay(1000);
}
| true |
a6cbc440f2d56dd85f7cdc52bdae0a9251e9ce1a | C++ | AlejandroNegri/POO-Biblioteca | /Biblioteca/VagregarLibro.h | UTF-8 | 602 | 2.625 | 3 | [] | no_license | /**
* @brief Ventana cargar los datos de un nuevo Libro
**/
#ifndef VAGREGARLIBRO_H
#define VAGREGARLIBRO_H
#include "Ventanas.h"
#include "Singleton.h"
class VagregarLibro : public VentanaAgregarLibro {
protected:
/// Guarda el nuevo dato y cierra la ventana (boton "Aceptar");
void ClickAgregarLibroNuevo( wxCommandEvent& event ) ;
/// Cierra la ventana sin agregar el nuevo dato (boton "Cancelar")
void bCancelarAgregarLibro( wxCommandEvent& event ) ;
public:
VagregarLibro(wxWindow *parent=NULL);
~VagregarLibro();
/// Valida los datos ingresados
string ValidarDatos();
};
#endif
| true |
bb78c8dced3e4490cfc7607baebfa7f0f710c08c | C++ | DawidK1/AiRRepo | /Maciek/problem3/main.cpp | UTF-8 | 819 | 3.0625 | 3 | [] | no_license | #include <iostream>
#include "vector.h"
#include "iter.h"
#include "toy.h"
#include "shop.h"
#include "company.h"
#include <fstream>
using namespace std;
int main()
{
ifstream file;
file.open("toys1.txt");
vector<toy> list1;
if(file)
{
string name;
float price;
while(file.eof() != true)
{
file >> name;
file >> price;
toy t(name,price);
list1.add(t);
}
}
file.close();
shop s1("dluga",13,list1);
ifstream file1;
file1.open("toys2.txt");
vector<toy> list2;
if(file1)
{
string name;
float price;
while(file1.eof() != true)
{
file1 >> name;
file1 >> price;
toy t(name,price);
list2.add(t);
}
}
file1.close();
shop s2("krotka",5,list2);
vector<shop> shops;
shops.add(s1);
shops.add(s2);
company firm("Najlepsze zabawki",shops);
cout<< firm << endl;
return 0;
}
| true |
58c9f8c6d3c1f479c4ce45272202b253683078fe | C++ | wjezowski/neuralNetwork | /include/Layer.h | UTF-8 | 633 | 2.515625 | 3 | [] | no_license | //
// Created by Wojtek on 2018-07-10.
//
#ifndef NEURALNETWORK_LAYER_H
#define NEURALNETWORK_LAYER_H
#include "Neuron.h"
#include <vector>
using namespace std;
class Layer {
private:
vector<shared_ptr<Neuron>> neurons;
public:
Layer(vector<shared_ptr<Neuron>> neurons, float biasWeight = std::numeric_limits<float>::quiet_NaN());
Layer(int numberOfNeurons, int numberOfInputs, float biasWeight = std::numeric_limits<float>::quiet_NaN());
void updateErrors();
//getters
vector<shared_ptr<Neuron>>& getNeurons();
string toString();
};
#endif //NEURALNETWORK_LAYER_H
| true |
778dd44b8faf3bc4e225ee32cd6785f5e324fb8f | C++ | souayrioss/Periode-SAS | /semaine 1/Challenges Variable/challenge8.cpp | UTF-8 | 365 | 2.90625 | 3 | [] | no_license | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
int nb1,nb2,nb3,nb4;
double moy,sum;
printf("enter les 4 nombre : \n");
scanf("%d",&nb1);
scanf("%d",&nb2);
scanf("%d",&nb3);
scanf("%d",&nb4);
sum=nb1+nb2+nb3+nb4;
printf("Moyenne est : %.2f \n",sum);
moy=sum/4;
printf("Moyenne est : %.2f",moy);
return 0;
}
| true |
517b8bd75b3d19636c29e8697af1a1ae7c504461 | C++ | JoKeR-VIKING/DS_Algo | /Coding Ninjas/Time And Space Complexity Analysis/arrayIntersection.cpp | UTF-8 | 2,288 | 4 | 4 | [] | no_license | // You have been given two integer arrays/list(ARR1 and ARR2) of size N and M, respectively. You need to print their intersection; An intersection for this problem can be defined when both the arrays/lists contain a particular value or to put it in other words, when there is a common value that exists in both the arrays/lists.
// Note :
// Input arrays/lists can contain duplicate elements.
// The intersection elements printed would be in the order they appear in the first sorted array/list(ARR1).
// Input format :
// The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow.
// The first line of each test case or query contains an integer 'N' representing the size of the first array/list.
// The second line contains 'N' single space separated integers representing the elements of the first the array/list.
// The third line contains an integer 'M' representing the size of the second array/list.
// The fourth line contains 'M' single space separated integers representing the elements of the second array/list.
// Output format :
// For each test case, print the intersection elements in a row, separated by a single space.
// Output for every test case will be printed in a separate line.
// Constraints :
// 1 <= t <= 10^2
// 0 <= N <= 10^6
// 0 <= M <= 10^6
// Time Limit: 1 sec
// Sample Input 1 :
// 2
// 6
// 2 6 8 5 4 3
// 4
// 2 3 4 7
// 2
// 10 10
// 1
// 10
// Sample Output 1 :
// 2 3 4
// 10
// Sample Input 2 :
// 1
// 4
// 2 6 1 2
// 5
// 1 2 3 4 2
// Sample Output 2 :
// 1 2 2
// Explanation for Sample Output 2 :
// Since, both input arrays have two '2's, the intersection of the arrays also have two '2's. The first '2' of first array matches with the first '2' of the second array. Similarly, the second '2' of the first array matches with the second '2' if the second array.
#include<algorithm>
void intersection(int *arr1, int *arr2, int n, int m)
{
sort(arr1, arr1+n);
sort(arr2, arr2+m);
int i = 0, j = 0;
while (i < n && j < m)
{
if (arr1[i] == arr2[j])
{
cout<<arr1[i]<<" ";
i++;
j++;
}
else if (arr1[i] > arr2[j])
j++;
else
i++;
}
}
| true |
82b119e5a99485dca561c2812eb34db7c975aed0 | C++ | alexandraback/datacollection | /solutions_5662291475300352_0/C++/valih10/main.cpp | UTF-8 | 1,192 | 2.53125 | 3 | [] | no_license | #include<iostream>
#include<fstream>
#include<cstdio>
#include<vector>
#include<string>
#include<cstring>
#include<queue>
#include<map>
#include<set>
#include<algorithm>
#include<iomanip>
#include<bitset>
using namespace std;
double d1, d2, d3, d4;
void sol() {
int n;
d1 = d2 = 0;
int a, b, c, cc, vv = 1;
cin >> n;
for(int i = 1; i <= n; ++i) {
cin >> a >> b >> cc;
for(int j = 1; j <= b; ++j) {
c = cc + j - 1;
double aa = 1.0 * (360 - a) * c / 360, bb = aa + c;
if(vv) {
d1 = aa;
d2 = bb;
vv = 0;
}
else {
d3 = aa;
d4 = bb;
}
}
}
if(d2 > d4) {
swap(d4, d2);
swap(d3, d1);
}
if(d2 <= d3)
cout << 1;
else
cout << 0;
}
int main() {
freopen("ttt", "r", stdin);
freopen("tttt", "w", stdout);
int t, a = 0;
cin >> t;
while(t--) {
++a;
cout << "Case #" << a << ": ";
sol();
cout << "\n";
}
return 0;
}
| true |
d78cb3db07c8fb656a5cb9f5a9b95ce495f30c66 | C++ | wujinggrt/PAT | /Basic/1007.cpp | UTF-8 | 987 | 3.5 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <cmath>
using namespace std;
bool is_prime(unsigned n)
{
if (n == 1)
{
return false;
}
if (n == 2)
{
return true;
}
unsigned bound = sqrt(n) + 1;
for (int i = 2; i < bound; ++i)
{
if (n % i == 0)
{
return false;
}
}
return true;
}
int prime_conjecture(unsigned n)
{
if (n <= 3)
{
return 0;
}
vector<int> vec;
vec.reserve(n / 2 + 1);
int count = 0;
for (int i = 1; i <= n; ++i)
{
if (is_prime(i))
{
if (vec.size())
{
if (i - vec.back() == 2)
{
++count;
}
}
vec.push_back(i);
}
}
return count;
}
int main()
{
int n;
cin >> n;
n = prime_conjecture(n);
cout << n;
return 0;
} | true |
1c5397b13768e77896ba0452533a7b8b33a2a5f3 | C++ | himanshu777m/LAB-5.5 | /lab5.5_q3.cpp | UTF-8 | 397 | 3.28125 | 3 | [] | no_license | // Programme to print reverse right triangle star pattern
#include<iostream>
using namespace std;
int main()
{
//declaring variable
int i,j,n;
cout << "Enter number of Row: ";
cin >> n;
//print inverted right triangle star pattern
for(i=0; i<n; i++){
for(j=0; (n-i)>j; j++){
cout << "*"; //printing star
cout << " \n"; //goto next line
}
}
cout << "\n";
return 0;
}
| true |
aa4954774a709be7228737f14ba2f5258982da41 | C++ | Yan-Song/burdakovd | /contests/timus/train/1413.cpp | UTF-8 | 1,694 | 2.65625 | 3 | [] | no_license | #include <iostream>
#include <cstring>
#include <string>
#include <cmath>
#include <stack>
#include <queue>
#include <deque>
#include <vector>
#include <algorithm>
#pragma comment(linker, "/STACK:16777216")
#define mset(block,value) memset(block,value,sizeof(block))
#define fo(i,begin,end) for(int i=begin; i<end; i++)
#define foreach(i,x) for(int i=0; i<x.size(); i++)
#define showv(v) foreach(i,v) cout<<v[i]<<" "; cout<<endl
#define ALL(v) v.begin(), v.end()
using namespace std;
typedef long long i64;
typedef vector<int> VI;
struct Vector
{
int x,y,xq2,yq2;
Vector(): x(0), y(0), xq2(0), yq2(0) {};
Vector(int xx, int yy, int xq, int yq): x(xx), y(yy), xq2(xq), yq2(yq) {};
Vector operator+=(const Vector& v)
{
x+=v.x;
y+=v.y;
xq2+=v.xq2;
yq2+=v.yq2;
return *this;
}
void print() const
{
double xx=double(x)+sqrt(double(0.5))*xq2;
double yy=double(y)+sqrt(double(0.5))*yq2;
printf("%.10lf %.10lf\n", xx, yy);
}
};
Vector solve(const string& code)
{
Vector pos;
Vector mv[10] = { Vector(),
Vector(0,0,-1,-1), Vector(0,-1,0,0), Vector(0,0,1,-1),
Vector(-1,0,0,0), Vector(0,0,0,0), Vector(1,0,0,0),
Vector(0,0,-1,1), Vector(0,1,0,0), Vector(0,0,1,1)
};
foreach(i, code)
{
pos += mv[code[i]-'0'];
if(code[i]=='0') return pos;
}
return pos;
}
int main()
{
/*
обратить внимание, что на string code; cin>>code - получал стабильный TLE
*/
char cs[1200000];
scanf("%s", cs);
string code=string(cs);
solve(code).print();
return 0;
}
| true |
bbacbdaafd280119b1a3540cce2c87ac337a0da0 | C++ | BestU/STM32_for_Arduino_BSP | /stm32/libraries/DHT_Sensor/dht.cpp | UTF-8 | 2,543 | 2.9375 | 3 | [] | no_license | #include "dht.h"
#define TIMEOUT 100000
void DHT::begin(uint8_t pin, uint8_t type)
{
_pin = pin;
_type = type;
}
boolean DHT::read(void)
{
int status;
switch(_type)
{
case DHT11:
status = read11(_pin);
break;
case DHT22:
status = read22(_pin);
break;
default:
status = -1;
break;
}
if (status == 0)
return true;
return false;
}
int DHT::read11(uint8_t pin)
{
// READ VALUES
int rv = read(pin);
if (rv != 0) return rv;
// CONVERT AND STORE
humidity = bits[0]; // bit[1] == 0;
temperature = bits[2]; // bits[3] == 0;
// TEST CHECKSUM
uint8_t sum = bits[0] + bits[2]; // bits[1] && bits[3] both 0
if (bits[4] != sum) return -1;
return 0;
}
int DHT::read22(uint8_t pin)
{
// READ VALUES
int rv = read(pin);
if (rv != 0) return rv;
// CONVERT AND STORE
humidity = word(bits[0], bits[1]) * 0.1;
int sign = 1;
if (bits[2] & 0x80) // negative temperature
{
bits[2] = bits[2] & 0x7F;
sign = -1;
}
temperature = sign * word(bits[2], bits[3]) * 0.1;
// TEST CHECKSUM
uint8_t sum = bits[0] + bits[1] + bits[2] + bits[3];
if (bits[4] != sum) return -1;
return 0;
}
int DHT::read(uint8_t pin)
{
// INIT BUFFERVAR TO RECEIVE DATA
uint8_t cnt = 7;
uint8_t idx = 0;
// EMPTY BUFFER
for (int i=0; i< 5; i++) bits[i] = 0;
// REQUEST SAMPLE
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
delay(20);
digitalWrite(pin, HIGH);
delayMicroseconds(44);
pinMode(pin, INPUT);
// GET ACKNOWLEDGE or TIMEOUT
unsigned int loopCnt = TIMEOUT;
while(digitalRead(pin) == LOW)
if (loopCnt-- == 0) return -2;
loopCnt = TIMEOUT;
while(digitalRead(pin) == HIGH)
if (loopCnt-- == 0) return -2;
// READ THE OUTPUT - 40 BITS => 5 BYTES
for (int i=0; i<40; i++)
{
loopCnt = TIMEOUT;
while(digitalRead(pin) == LOW)
if (loopCnt-- == 0) return -2;
unsigned long t = micros();
loopCnt = TIMEOUT;
while(digitalRead(pin) == HIGH)
if (loopCnt-- == 0) return -2;
if ((micros() - t) > 40) bits[idx] |= (1 << cnt);
if (cnt == 0) // next byte?
{
cnt = 7;
idx++;
}
else cnt--;
}
return 0;
}
| true |
b8c5acba7eb1abc95c00852ab2c33220521302aa | C++ | mjenrungrot/competitive_programming | /UVa Online Judge/v127/12720.cc | UTF-8 | 1,285 | 2.5625 | 3 | [
"MIT"
] | permissive | /*=============================================================================
# Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/
# FileName: 12720.cc
# Description: UVa Online Judge - 12720
=============================================================================*/
#include <bits/stdc++.h>
using namespace std;
int T;
string A;
string S;
const int MOD = 1e9 + 7;
int main() {
scanf("%d", &T);
for (int _i = 1; _i <= T; _i++) {
cin >> A;
int N = A.length();
S = "";
int start_i, start_j;
if (N % 2 == 1) {
S += A[N / 2];
start_i = N / 2 - 1;
start_j = N / 2 + 1;
} else {
start_i = N / 2 - 1;
start_j = N / 2;
}
for (int i = start_i, j = start_j; j <= N; i--, j++) {
if (A[i] > A[j]) {
S += A[i];
S += A[j];
} else {
S += A[j];
S += A[i];
}
}
int ans = 0;
int factor = 1;
for (int i = N - 1; i >= 0; i--) {
ans = (ans + ((S[i] == '1' ? 1 : 0) * factor)) % MOD;
factor = (factor * 2) % MOD;
}
printf("Case #%d: %d\n", _i, ans);
}
return 0;
} | true |
1fe95cca73d3dd1285a444da673777151e7c6b1e | C++ | abagwell/chatProgram | /chatserv.cpp | UTF-8 | 4,739 | 3.125 | 3 | [] | no_license | /*
Name: Andrew Bagwell
Date: 04/30/2016
Assignment: Project1
File: chatserv.cpp
Language: C++
*/
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <signal.h>
//constants
#define BACKLOG 20
#define MESS_LGTH 500
#define SERVER_HDLE "Serv"
//function prototypes
void buildServer(char*);
void doChat(int);
void signalIntHandle(int);
int main(int argc, char *argv[]) {
//command line constraints
if (argc != 2) {
fprintf(stderr,"usage: chatserv [port number]\n");
exit(1);
}
//handle the possibility of signal interruption..
signal(SIGINT, signalIntHandle);
buildServer(argv[1]);
return 0;
}
//------------------chat function--------------------------
//This function handles the actual chatting between client and server
//---------------------------------------------------------
void doChat(int socketPassed) {
char msgRcvd[MESS_LGTH];
char msgSent[MESS_LGTH];
printf("\n");
printf("Beginning new chat session, wait for client message and then respond. Type \\quit to quit chat.\n\n");
while (1) {
//get the message from client
recv(socketPassed, msgRcvd, MESS_LGTH, 0);
//determine if message is a quit message
char *phrase;
if ((phrase = strstr(msgRcvd, "\\quit"))!=NULL) {
printf("Connection closed by user..\n");
return;
}
//display message from client
printf("%s\n", msgRcvd); //changed something here...
//send message to client
char preCatMsg[500]; //this will store the message typed from the console...
std::cout << SERVER_HDLE << "> ";
fgets(preCatMsg, MESS_LGTH, stdin);
char *lastChar;
if ((lastChar=strchr(preCatMsg, '\n')) != NULL)
*lastChar = '\0';
//combine the user entered message with the handle...
sprintf(msgSent, "%s> %s", SERVER_HDLE, preCatMsg); //changed something here
//send that combined message to client...
send(socketPassed, msgSent, MESS_LGTH, 0);
//if server wants to close, it's closed here
if(strcmp(preCatMsg, "\\quit")==0) {
std::cout << "Goodbye.." << std::endl;
return;
}
}
}
//----------------------BUILD SERVER FUNCTION----------------
//This is the main driver function of the program.
//-----------------------------------------------------------
void buildServer(char* portPassed) {
//create structs for storing information about server
struct addrinfo hints;
struct addrinfo* servInfo;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
//check for errors in getaddrinfo function
int errCheck;
if ((errCheck = getaddrinfo(NULL, portPassed, &hints, &servInfo)) != 0) {
fprintf(stderr, "Error -getaddinfo failure: %s\n", gai_strerror(errCheck));
exit(1);
}
//This is where the socket for the server is created...
int serverSocket = socket(servInfo->ai_family, servInfo->ai_socktype, servInfo->ai_protocol);
//check for errors in socket function
if (serverSocket == -1) {
exit(1);
}
//bind the socket with bind function
errCheck = bind(serverSocket, servInfo->ai_addr, servInfo->ai_addrlen);
if (errCheck == -1) {
fprintf(stderr, "Error bind() failure");
exit(1);
}
//begin listening for conections
errCheck = listen(serverSocket, BACKLOG);
//check for errors in the listen() function
if (errCheck == -1) {
fprintf(stderr, "Error listen() failure");
exit(1);
}
std::cout << "Server up and listening on: " << portPassed << std::endl;
//server begins listening and continues to do so until exiting...
while(1) {
printf("\n");
printf("Waiting for connection..\n");
//client socket info is obtained...
struct sockaddr_storage clientAddress;
socklen_t addressSize = sizeof(clientAddress);
int connectionSocket = accept(serverSocket, (struct sockaddr*)&clientAddress, &addressSize);
if (connectionSocket == -1) {
std::cout << "Connection failed.." << std::endl;
exit(1);
}
doChat(connectionSocket); //call this function to do the chat
close(connectionSocket);
}
freeaddrinfo(servInfo);
return;
}
void signalIntHandle(int sigReceived) {
printf("\nConnection lost....signal interrupted.\n");
exit(0);
}
| true |
ccadbb896e987ec0fc3e5235ee0e7cefeca1b096 | C++ | jwbecalm/Head-First-Design-Patterns-CPP | /Factory/include/Sauce.hpp | UTF-8 | 209 | 2.515625 | 3 | [] | no_license | #ifndef SAUCE_HPP
#define SAUCE_HPP
#include <string>
class Sauce
{
public:
Sauce();
virtual ~Sauce();
virtual std::string toString() = 0;
};
#endif // SAUCE_HPP
| true |
18be6748775d21b52438b1529c42d2aaa3b7634a | C++ | bqqbarbhg/cold | /cold/cold/render/blend_state.h | UTF-8 | 1,171 | 3.0625 | 3 | [
"MIT"
] | permissive | #ifndef _COLD_RENDER_BLEND_STATE_H
#define _COLD_RENDER_BLEND_STATE_H
namespace cold {
// Controls how the renderer blends pixels
struct BlendState {
public:
// A blending factor applied to either source or destination
enum Factor {
_NONE,
// 0
ZERO,
// 1
ONE,
// Source color
SRC_COLOR,
// Destination color
DST_COLOR,
// Inverse source color
INV_SRC_COLOR,
// Inverse destination color
INV_DST_COLOR,
// Source alpha
SRC_ALPHA,
// Destination alpha
DST_ALPHA,
// Inverse source alpha
INV_SRC_ALPHA,
// Inverse destination alpha
INV_DST_ALPHA,
};
BlendState();
BlendState(Factor src, Factor dst);
// Applies the blend state to the current render state
void apply() const;
// Returns the source factor
Factor get_source() const { return source; }
// Returns the destination factor
Factor get_destination() const { return destination; }
const static BlendState None;
const static BlendState Additive;
const static BlendState AlphaBlend;
const static BlendState Opaque;
const static BlendState Multiply;
private:
Factor source, destination;
unsigned int hash;
static unsigned int _factor_hash;
};
}
#endif | true |
aa3fb33958aac9eec01d12a2d079354069e53f2c | C++ | rennancl/competitive-programming | /1416.cpp | UTF-8 | 4,077 | 2.8125 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <cmath>
#include <iomanip>
#include <vector>
#include <utility>
#include <string.h>
#include <algorithm>
int ep = 20;
long long unsigned int problem_penalty(std::pair <int, int> p, int EP){
/*
A penalidade de um problema é TP + EP x FA, onde TP é a penalidade de tempo para aquele problema,
EP é a penalidade de erro do competidor e FA é o número de tentativas frustradas de resolver
o problema antes de submeter uma solução certa.
*/
if(p.second == -1) return 0;
//TP + FA X EP
long long unsigned int FA = (p.first);
FA = FA > 0 ? FA : 0;
return p.second + FA * EP;
}
long long unsigned int team_penalty(std::vector< std::pair <int, int> > team, int EP){
long long unsigned int penalty = 0;
for(int i = 0; i < team.size(); i++){
penalty += problem_penalty(team[i], EP);
}
return penalty;
}
bool compare_times(const std::pair<int, std::vector< std::pair <int, int> > > &team1,const std::pair<int, std::vector< std::pair <int, int> > > &team2){
int n1 = 0, n2 = 0;
for(int j = 0; j < team1.second.size(); j++){
if(team1.second[j].second > -1) n1++;
if(team2.second[j].second > -1) n2++;
}
if(n1 == 0 and n2 == 0) return false;
if(n1 == n2) return team_penalty(team1.second, ep) < team_penalty(team2.second, ep);
return n1 > n2;
}
std::vector<std::pair < int, int> > get_board(std::vector< std::pair<int, std::vector< std::pair <int, int> > > > times){
int pos = 1;
std::vector<std::pair < int, int> > score;
long long unsigned int actual = team_penalty(times[0].second, ep);
score.push_back(std::make_pair(times[0].first, pos));
for(int i = 1; i < times.size(); i++){
if(team_penalty(times[i].second, ep) != actual) pos++;
score.push_back(std::make_pair(times[i].first, pos));
actual = team_penalty(times[i].second, ep);
}
return score;
}
int main() {
int t, p;
int retries, tempo;
char Cretries[10], Ctempo[10];
while(1){
ep = 20;
std::vector<std::pair < int, int> > original_score,score;
std::vector< std::pair<int, std::vector< std::pair <int, int> > > > times;
std::vector< std::pair<int, std::vector< std::pair <int, int> > > > times2, original;
scanf(" %d %d", &t, &p);
if(p == 0 and t == 0) break;
for(int i = 0; i < t; i++){
int n = 0;
std::vector< std::pair <int, int> > team;
for(int j = 0; j < p; j++){
scanf(" %99[^/]/%s", Cretries, Ctempo);
retries = atoi(Cretries);
tempo = strcmp(Ctempo, "-") ? atoi(Ctempo) : -1;
team.push_back(std::make_pair(retries, tempo));
}
times.push_back(std::make_pair(i,team));
}
sort(times.begin(), times.end(), compare_times);
original = times;
original_score = get_board(times);
//alterar esse valor altera a resposta!!!
int lower, upper;
for(int i = 1; i < 21; i++){
ep = i;
sort(times.begin(), times.end(), compare_times);
score = get_board(times);
times = original;
if(original_score == score){lower = i; break;}
}
ep = 200000000;
sort(times.begin(), times.end(), compare_times);
score = get_board(times);
times = original;
if(original_score == score){
std::cout << lower << " " << '*' << std::endl;
continue;
}
for(int i = 21; i <= 200000000; i++){
ep = i; upper = i;
sort(times.begin(), times.end(), compare_times);
score = get_board(times);
times = original;
if(original_score != score){upper = i - 1; break;}
}
if(upper < 200000000)
std::cout << lower << " " << upper << std::endl;
else
std::cout << lower << " " << '*' << std::endl;
}
return 0;
} | true |
bbdf4f27606936442a5216c8b3c9c1c845ab478d | C++ | ammarm7/C-Plus-Plus | /Const/Sally.cc | UTF-8 | 278 | 2.625 | 3 | [] | no_license | //Sally.cc
#include "Sally.h"
#include <iostream>
using namespace std;
Sally::Sally(){ //Calling ctor
}
void Sally::printShit(){
cout << "I am the print shit function" << endl;
}
void Sally::printShit2() const{
cout << "I am the constant print shit function" << endl;
}
| true |
4d7630832650a64e5fa451602a4f5e921cc5fe45 | C++ | skyformat99/Camera-Streaming | /Src/Linux/tcpchatclient/main.cpp | UTF-8 | 1,083 | 3.015625 | 3 | [
"MIT"
] | permissive |
#include <iostream>
#include "../netcom/network.h"
using namespace std;
bool g_threadLoop = true;
network::cTCPClient client;
void* PrintRecv(void* arg);
int main(int argc, char **argv)
{
if (argc < 3)
{
cout << "command line <ip> <port>" << endl;
return 0;
}
const string ip = argv[1];
const int port = atoi(argv[2]);
if (!client.Init(ip, port))
{
cout << "connect error!!" << endl;
return false;
}
cout << "connect success .. start loop.." << endl;
pthread_t handle;
g_threadLoop = true;
pthread_create(&handle, NULL, PrintRecv, NULL);
while (1)
{
cout << "send data : ";
char buff[512];
fgets(buff, sizeof(buff), stdin);
client.Send((BYTE*)buff, sizeof(buff));
sleep(1);
}
g_threadLoop = false;
pthread_join(handle, NULL);
return 0;
}
void* PrintRecv(void* arg)
{
char buff[512];
while (g_threadLoop)
{
network::sPacket packet;
if (client.m_recvQueue.Front(packet))
{
memcpy(buff, packet.buffer, packet.actualLen);
client.m_recvQueue.Pop();
cout << "recv data : " << packet.buffer << endl;
}
}
return 0;
}
| true |
38023b5c761b998f4aa97c5a103b011b51fdaa6a | C++ | adzkar/cp-archive | /Hackerrank/ProblemSolving/MiniMaxSum.cpp | UTF-8 | 389 | 2.796875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main() {
int angka[5];
for(int i = 0; i < 5;i++) scanf("%i", &angka[i]);
vector<int> total(5);
for(int i = 0;i < 5;i++) {
for(int j = 0; j < 5;j++) {
if(i != j) total[i] += angka[j];
}
}
sort(total.begin(), total.end());
printf("%i %i\n", total[0], total[4]);
return 0;
} | true |
d9f5eb6479366b77d7025956b11ba4e8b1cb2a20 | C++ | JohnieWalkerCZ/LogicOS | /Release/src/ConvertImgs.cpp | UTF-8 | 3,208 | 2.78125 | 3 | [] | no_license | #include "Logic.hpp"
#include "esp_spiffs.h"
#include "ConvertImgs.hpp"
#include <iostream>
#include <cstdio>
void convertImgPre () {
// Konfigurace datového oddílu
esp_vfs_spiffs_conf_t conf = {
.base_path = "/spiffs",
.partition_label = NULL,
.max_files = 5,
.format_if_mount_failed = true,
};
// Připojení datového oddílu na /spiffs
esp_err_t ret = esp_vfs_spiffs_register(&conf);
if (ret != ESP_OK) {
if (ret == ESP_FAIL) {
printf("Failed to mount or format filesystem\n");
} else if (ret == ESP_ERR_NOT_FOUND) {
printf("Failed to find SPIFFS partition\n");
} else {
printf("Failed to initialize SPIFFS (%d)\n", ret);
}
return;
}
}
void convertImgSnake(int brightness) {
// Otevření souboru
FILE* soubor = fopen("/spiffs/SnakeIcon.data", "r");
if (!soubor) {
printf("Failed to open file: %s\n", strerror(errno));
return;
}
// Načtení dat ze souboru, pixel po pixelu.
uint8_t pixel[3];
for (int i = 0; i < display.width() * display.height(); ++i) {
size_t res = fread(pixel, 1, 3, soubor);
if (res != 3) {
printf("Nepodarilo se precist 3 byty %d\n", res);
break;
}
// Nastavení do displeje
display[i] = Rgb(pixel[0], pixel[1], pixel[2]);
}
// Zavření souboru - nezapomeňte na to!
fclose(soubor);
display.show(brightness);
}
void convertImgFlappyBird (int brightness) {
// Otevření souboru
FILE* soubor = fopen("/spiffs/FlappyBirdLogo.data", "r");
if (!soubor) {
printf("Failed to open file: %s\n", strerror(errno));
return;
}
// Načtení dat ze souboru, pixel po pixelu.
uint8_t pixel[3];
display.clear();
for (int i = 0; i < display.width() * display.height(); ++i) {
size_t res = fread(pixel, 1, 3, soubor);
//printf("%dx%d: %d:%d:%d %d\n", i%10, i/10, pixel[0], pixel[1], pixel[2], res);
if (res != 3) {
printf("Nepodarilo se precist 3 byty %d\n", res);
break;
}
// Nastavení do displeje
display[i] = Rgb(pixel[0], pixel[1], pixel[2]);
}
// Zavření souboru - nezapomeňte na to!
fclose(soubor);
display.show(brightness);
}
void convertImgMineSweeper(int brightness) {
// Otevření souboru
FILE* soubor = fopen("/spiffs/MineSweeperLogo.data", "r");
if (!soubor) {
printf("Failed to open file: %s\n", strerror(errno));
return;
}
// Načtení dat ze souboru, pixel po pixelu.
uint8_t pixel[3];
for (int i = 0; i < display.width() * display.height(); ++i) {
size_t res = fread(pixel, 1, 3, soubor);
if (res != 3) {
printf("Nepodarilo se precist 3 byty %d\n", res);
break;
}
// Nastavení do displeje
display[i] = Rgb(pixel[0], pixel[1], pixel[2]);
}
// Zavření souboru - nezapomeňte na to!
fclose(soubor);
display.show(brightness);
} | true |
9ec3cdb6948ab5a333f8eb6a2fa74c734ad3122b | C++ | system-thoughts/leetcode | /863.二叉树中所有距离为-k-的结点.cpp | UTF-8 | 1,809 | 3.40625 | 3 | [] | no_license | /*
* @lc app=leetcode.cn id=863 lang=cpp
*
* [863] 二叉树中所有距离为 K 的结点
*/
// @lc code=start
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void dfs(TreeNode* from, unordered_map<int, vector<int>>& map, unordered_map<int, int>& visited) {
TreeNode* to = nullptr;
if (from->left != nullptr) {
to = from->left;
visited[from->val] = 0;
visited[to->val] = 0;
map[from->val].push_back(to->val);
map[to->val].push_back(from->val);
dfs(to, map, visited);
}
if (from->right != nullptr) {
to = from->right;
visited[from->val] = 0;
visited[to->val] = 0;
map[from->val].push_back(to->val);
map[to->val].push_back(from->val);
dfs(to, map, visited);
}
}
void travel(unordered_map<int, vector<int>>& map, unordered_map<int, int>& visited, int start, int len, vector<int> &res)
{
if (len == 0) {
res.push_back(start);
return;
}
for (auto v : map[start]) {
if (!visited[v]) {
visited[v] = 1;
travel(map, visited, v, len - 1, res);
}
}
}
vector<int> distanceK(TreeNode* root, TreeNode* target, int K) {
// 将树转换为图
unordered_map<int, vector<int>> map;
unordered_map<int, int> visited;
vector<int> res;
dfs(root, map, visited);
visited[target->val] = 1;
travel(map, visited, target->val, K, res);
return res;
}
};
// @lc code=end
| true |
84bb064ada8f9e3d6c2d7fcc9f0380e33da4236d | C++ | Ahuttunen/Shodan | /22aaa/Backround.cpp | UTF-8 | 1,240 | 2.859375 | 3 | [] | no_license | #include "Backround.h"
#include <iostream>
Backround::Backround()
{
BTexture.loadFromFile("Textures/Background.png");
BSprite.setTexture(BTexture);
BSprite.setPosition(0, -BSprite.getGlobalBounds().height);
BSprite2 = BSprite;
BSprite3 = BSprite;
}
Backround::~Backround(void)
{
}
void Backround::draw(sf::RenderWindow& myWindow)
{
myWindow.draw(BSprite);
if (BSprite.getPosition().y > 0)
{
myWindow.draw(BSprite2);
if (BSprite2.getPosition().y > myWindow.getSize().y)
{
BSprite2.setPosition(0, BSprite.getGlobalBounds().top - BSprite3.getGlobalBounds().height);
}
}
if (BSprite2.getPosition().y > 0)
{
myWindow.draw(BSprite3);
if (BSprite3.getPosition().y > myWindow.getSize().y)
{
BSprite3.setPosition(0, BSprite.getGlobalBounds().top - BSprite.getGlobalBounds().height);
}
}
if (BSprite3.getPosition().y > 0)
{
BSprite.setPosition(0, BSprite3.getGlobalBounds().top - BSprite.getGlobalBounds().height);
}
}
void Backround::Scroll()
{
sf::Time time = sf::seconds(1.f / 60.f);
int speed = 600;
sf::Vector2f scrollDown(0, 0);
scrollDown.y += speed;
BSprite.move(scrollDown * time.asSeconds());
BSprite2.move(scrollDown * time.asSeconds());
BSprite3.move(scrollDown * time.asSeconds());
} | true |
63758d8ae7c32f4211234aec03484a102201c8fc | C++ | bitsai/euler | /cpp/p18.cpp | UTF-8 | 838 | 2.921875 | 3 | [] | no_license | #include "euler.h"
using namespace std;
int main() {
ifstream file( "p18.txt" );
string line;
vector< vector<int> > best_paths;
while( getline( file, line ) ) {
vector<string> cells = tokenize( line, " " );
vector<int> row;
for( int i = 0; i < cells.size(); i++ ) {
int left_ancestor = 0, right_ancestor = 0;
if( best_paths.size() > 0 && i > 0 )
left_ancestor = best_paths.back()[ i - 1 ];
if( best_paths.size() > 0 && best_paths.back().size() > i )
right_ancestor = best_paths.back()[ i ];
int best_path_thru_cell = max( left_ancestor, right_ancestor ) + string_to_number( cells[ i ] );
row.push_back( best_path_thru_cell );
}
best_paths.push_back( row );
}
cout << *max_element( best_paths.back().begin(), best_paths.back().end() ) << endl;
}
| true |
5b3537f8c6dcf7bff09e768aae91c781b6c48799 | C++ | neilkg/clibrary | /vector.h | UTF-8 | 3,941 | 3.765625 | 4 | [] | no_license | #ifndef VECTOR_H
#define VECTOR_H
// NEIL GOLLAPDUI
template <typename T>
class vector {
public:
// constructs an empty container with 0 elements
vector() {
data = new T[10];
elts_capacity = 10;
elts_size = 0;
}
// constructs a container size n with each elements being val
vector(int n, T val) {
data = new T[n];
elts_capacity = n;
elts_size = n;
for (int i = 0; i < n; ++i) {
data[i] = val;
}
}
//range based constructor
template <class Iterator>
vector(Iterator begin, int size) {
data = new T[10];
elts_capacity = 10;
elts_size = 0;
for (int i = 0; i < size; ++i) {
push_back(*begin);
++begin;
}
}
//destructor
~vector() {
delete data;
}
// copy constructor
vector(const vector<T> &other) {
elts_size = other.elts_size;
elts_capacity = other.elts_capacity;
data = new T[elts_capacity];
for (int i = 0; i < elts_size; ++i) {
data[i] = other.data[i];
}
}
// assignment operator
vector & operator= (const vector<T> &rhs) {
if (&rhs != this) {
elts_size = rhs.elts_size;
elts_capacity = rhs.elts_capacity;
delete data;
T* temp = new T[elts_capacity];
data = temp;
for (int i = 0; i < elts_size; ++i) {
data[i] = rhs.data[i];
}
}
return *this;
}
bool empty() {
return elts_size == 0;
}
int size() {
return elts_size;
}
T &front() {
return data[0];
}
T &back() {
return data[elts_size - 1];
}
// amortized O(n)
void push_front(const T &val) {
if (elts_size == elts_capacity) {
grow(elts_capacity * 2);
}
for (int i = elts_size; i > 0; --i) {
data[i] = data[i - 1];
}
data[0] = val;
++elts_size;
}
// amortized O(1)
void push_back(const T &val) {
if (elts_size == elts_capacity) {
grow(elts_capacity * 2);
}
data[elts_size] = val;
++elts_size;
}
// O(n)
void pop_front() {
for (int i = 0; i < elts_size - 1; ++i) {
data[i] = data[i + 1];
}
--elts_size;
}
// O(1)
void pop_back() {
--elts_size;
}
// reserves memory for vector of size n
// invalidates all previous elements
void reserve(int n) {
T* temp = new T[n];
elts_capacity = n;
delete data;
data = temp;
}
// resizes vector of size n with val filling in the rest
void resize(const int n, const T &val) {
T * temp = new T[n];
if (n > elts_size) {
int stop = 0;
for (int i = 0; i < elts_size; ++i) {
temp[i] = data[i];
++stop;
}
for (int i = stop; i < n; ++i) {
temp[i] = val;
}
}
else {
for (int i = 0; i < n; ++i) {
temp[i] = data[i];
}
}
elts_capacity = n;
elts_size = n;
delete data;
data = temp;
}
// REQUIRES: Index is withing the bounds of the scope
T &operator[](int idx) {
return data[idx];
}
T* begin() {
return data;
}
private:
T *data;
int elts_capacity;
int elts_size;
// creates new dyanamic array of size n and copies over previous elements
void grow(int n) {
elts_capacity = n;
T *temp = new T[elts_capacity];
for (int i = 0; i < elts_size; ++i) {
temp[i] = data[i];
}
delete data;
data = temp;
}
};
#endif
| true |
9eeed7ed98571e6b4d1fb41dc6fce8782c86c6b7 | C++ | stanford-ssi/sats-cs | /databases/Tree preprocessing/generatetree.cpp | UTF-8 | 1,415 | 3.171875 | 3 | [] | no_license | #include <databasenode.h>
#include <databaseanswernode.h>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
void generateTree(ifstream file) {
databaseNode* root = new databaseNode();
int currID;
int numNeighbors;
string currLine;
//location
while(getline(file, currLine)) { //loops over each line in csv file
istringstream sStream (currLine);
sStream >> currID;
sStream >> numNeighbors;
int currValue = numNeighbors;
databaseSuperNode* currLevel = root;
for(int currNeighbor = 0; currNeighbor <= numNeighbors; currNeighbor++) { //loops over all details for current star
if(!currLevel->containsChild(currValue)) { //if the current level doesnt have that node add it
if(currNeighbor < numNeighbors) { //add a decision node
databaseSuperNode* decisionNode = new databaseNode();
currLevel->addChild(currValue, decisionNode);
}
else {//add an answer node
databaseSuperNode* answerNode = new databaseAnswerNode(currID);
currLevel->addChild(currValue, answerNode);
}
}
currLevel = currLevel->getChild(currValue); //go to next level in database
sStream >> currValue; //go to next value to enter in to database
}
}
}
| true |
634b9f8d435f8d034a9bca96e2008bc1f12681fd | C++ | eTakazawa/procon-archive | /atcoder.jp/arc022/arc022_3/Main.cpp | UTF-8 | 771 | 2.71875 | 3 | [] | no_license | #include<iostream>
#include<string>
#include<vector>
#include<map>
#include<queue>
#include<cmath>
#include<algorithm>
#include<utility>
#include<functional>
using namespace std;
vector<vector<int> > g;
vector<int> dist;
void dfs(int now,int pre,int d){
dist[now] = d;
for(int i=0;i<g[now].size();i++){
if(g[now][i] == pre)continue;
dfs(g[now][i],now,d+1);
}
return;
}
int main(void){
int N;
cin >> N;
g.resize(N);
dist.resize(N);
for(int i=0;i<N-1;i++){
int a,b;
cin >> a >> b;
a--;b--;
g[a].push_back(b);
g[b].push_back(a);
}
dfs(0,-1,0);
int pos1 = max_element(dist.begin(),dist.end()) - dist.begin();
dfs(pos1,-1,0);
int pos2 = max_element(dist.begin(),dist.end()) - dist.begin();
cout << ++pos1 << " " << ++pos2 << endl;
return 0;
}
| true |
974232da823af85a8bc8dafc57b4572a66ec8f8c | C++ | kevintank/e_wiz | /Ado.cpp | UHC | 15,894 | 2.515625 | 3 | [] | no_license | // Ado.cpp: implementation of the CAdo class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "testdlg.h"
#include "Ado.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
const TCHAR *oleString = _T("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=");
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CAdo::CAdo()
{
CoInitialize(NULL); //COM ʱȭ
m_pCON = NULL;
m_pRS = NULL;
m_pCOM = NULL;
m_IsDBOpen = FALSE;
if(FAILED( m_pCON.CreateInstance(__uuidof(Connection))))
AfxMessageBox(_T("Connection ü "), MB_OK, NULL);
if(FAILED(m_pRS.CreateInstance(__uuidof(Recordset))))
AfxMessageBox(_T("Recordset ü "), MB_OK, NULL);
if(FAILED(m_pCOM.CreateInstance(__uuidof(Command))))
AfxMessageBox(_T("Command ü "), MB_OK, NULL);
}
CAdo::~CAdo()
{
m_pCON.Release();
m_pRS.Release();
m_pCOM.Release();
m_pCON = NULL;
m_pRS = NULL;
m_pCOM = NULL;
m_IsDBOpen = FALSE;
CoUninitialize(); // COM ü
}
/********************************************************************
* ڿ .
* ϸ Ʋ connection ݰ, Ṯڿ .
*
* return : BOOL : TRUE | FALSE
*
* parameter :
* [in] CString Filename : MDB ϸ
********************************************************************/
BOOL CAdo::DB_Init(CString strFilename)
{
if(m_pRS == NULL || m_pCON == NULL)
return FALSE;
if(strFilename.IsEmpty())
return FALSE;
if(FileCmp(strFilename) == TRUE)
return TRUE;
DB_Close();
m_strConnection = oleString + strFilename;
return FALSE;
}
/********************************************************************
* ڵ Ѵ.
* recordset close Ѵ.
*
* return : BOOL : TRUE | FALSE
*
* parameter :
* [in] CString sql : SQL Query SELECT
* [in] CString Filename : MDB ϸ
********************************************************************/
BOOL CAdo::DB_Open(CString sql, CString Filename)
{
HRESULT hr;
VARIANT conn;
if(m_pCON == NULL || m_pRS == NULL)
{
return FALSE;
}
if(Filename.IsEmpty() == FALSE)
{
AfxMessageBox("̸ ");
DB_Connection(Filename);
}
else
{
AfxMessageBox("̸ ֳ");
DB_Connection("");
}
if(m_IsDBConn == FALSE)
{
return FALSE;
}
if(m_IsDBOpen == TRUE)
DB_Close();
try
{
// TRACE(sql);
// TRACE("\n");
VariantInit(&conn);
conn.pdispVal = m_pCON;
conn.vt = VT_DISPATCH;
hr = m_pRS->Open( (LPTSTR)(LPCTSTR)sql, conn,
adOpenForwardOnly, adLockOptimistic, adCmdUnknown); //ڵ ..... ʿ κ
}
catch(_com_error &e)
{
TRACE("\tDescription: %s\n", (LPCTSTR) e.Description());
}
catch(...)
{
TRACE("*** Unhandled Exception ***\n");
}
if(SUCCEEDED(hr))
m_IsDBOpen = TRUE;
sql.TrimLeft();
CString str = sql.Left(7);
if(str.CollateNoCase("SELECT ")) //2 string
{
m_IsDBOpen = FALSE;
}
return SUCCEEDED(hr);
}
/********************************************************************
* DB Ѵ.
* connection Ѵ.
*
* return : BOOL : TRUE | FALSE
*
* parameter :
* [in] CString Filename : MDB ϸ
********************************************************************/
BOOL CAdo::DB_Connection(CString Filename)
{
if(Filename.IsEmpty() && m_strConnection.IsEmpty() )
return FALSE;
if(Filename.IsEmpty() == FALSE)
{
DB_Init(Filename);
}
if(m_pCON == NULL)
return FALSE;
if(m_IsDBConn == TRUE )
return TRUE;
try
{ //connection.Open(ConnectionString, UserID, Password, Options) Ÿ ̽ ϱ.
m_pCON->Open((_bstr_t)m_strConnection,"","", adConnectUnspecified);
m_IsDBConn = TRUE;
AfxMessageBox("Ʈ");
}catch(_com_error &err)
{
m_IsDBConn = FALSE;
AfxMessageBox("Ʋ ");
TRACE("Error : %s : DB CONNECTION FAIL\n", err.Description() );
}
return m_IsDBConn;
}
void CAdo::DB_Search()
{
m_pCOM->ActiveConnection = m_pCON;
m_pCOM->CommandText = "Select * From TB_LINECODE";
try
{
//Execute Ⱦ Ʒó Ӽ ش.
//m_pRS->CursorLocation = adUseClient;
// m_pRS->CursorType = adOpenStatic;
// m_pRS->LockType = adLockOptimistic;
//Ŀ Ÿ Ʒ ش
//recordset.Open( Source, ActiveConnection, CursorType, LockType, Options)
m_pRS->Open("TB_LINECODE", _variant_t((IDispatch *)m_pCON, true),adOpenStatic, adLockOptimistic,adCmdTable);
/////////////////////////////////////////////
// --> m_pRS = m_pCOM->Execute(NULL,NULL,adCmdText);
//
m_pCOM->Execute(NULL,NULL,adCmdText);
}
catch(_com_error &e)
{
COMERRORMSG(e);
//AfxMessageBox("ȸ ʾҽϴ.!!");
return;
}
if(m_pRS->adoEOF)
{
AfxMessageBox("Ÿ !!");
return;
}
_variant_t fldItem01, fldItem02, fldItem03, fldItem04, fldItem05, fldItem06, fldItem07;
CString strLineName01,strLineName02,strLineName03,strLineName04,strLineName05;
long lngIndex01,lngIndex02;
int intFieldCount;
intFieldCount = 1; //ݺ ī
while(!m_pRS->adoEOF)
{
//ʵ忡
fldItem01 = m_pRS->Fields->GetItem("unit")->GetValue();
fldItem02 = m_pRS->Fields->GetItem("unitidx")->GetValue();
fldItem03 = m_pRS->Fields->GetItem("word")->GetValue();
fldItem04 = m_pRS->Fields->GetItem("wordkr")->GetValue();
fldItem05 = m_pRS->Fields->GetItem("exkor")->GetValue();
fldItem06 = m_pRS->Fields->GetItem("exeng")->GetValue();
fldItem07 = m_pRS->Fields->GetItem("exans")->GetValue();
strLineName01 = Convert_Variant_To_String(fldItem03);
strLineName02 = Convert_Variant_To_String(fldItem04);
strLineName03 = Convert_Variant_To_String(fldItem05);
strLineName04 = Convert_Variant_To_String(fldItem06);
strLineName05 = Convert_Variant_To_String(fldItem07);
lngIndex01 = fldItem01;
lngIndex02 = fldItem02;
// AddData(lngIndex01,lngIndex02,strLineName01,strLineName02,strLineName03,strLineName04,strLineName05 );
intFieldCount++;
m_pRS->MoveNext();
}
/*
try{
m_pRS->MoveLast();
}catch(_com_error &e){
COMERRORMSG(e);
return;
}
try{
fldItem01 = m_pRS->Fields->GetItem("unit")->GetValue();
}catch(_com_error &e){
COMERRORMSG(e);
return;
}
lngIndex01 = fldItem01;
strLineName01.Format("This: %ld", lngIndex01);
AfxMessageBox(strLineName01);
*/
m_pRS->Close();
// m_flxDBList.SetRedraw(1);
// m_flxDBList. Refresh();
}
CString CAdo::Convert_Variant_To_String(_variant_t &varString)
{
if (varString.vt == VT_BSTR)
{
_bstr_t bstrString = (_bstr_t)varString;
return (LPTSTR)bstrString;
}
return "";
}
/**********************************************************
* recordset ݱ
* return : BOOL : TRUE : FALSE
*
* parameter : None
***********************************************************/
BOOL CAdo::DB_Close()
{
if(m_IsDBOpen == FALSE)
return TRUE;
m_IsDBOpen = FALSE;
return SUCCEEDED(m_pRS->Close());
}
/**********************************************************
* connection ´.
* return : BOOL : TRUE : FALSE
*
* parameter : None
***********************************************************/
BOOL CAdo::DB_CloseConnection()
{
if(m_pCON == FALSE)
return TRUE;
m_pCON = FALSE;
return SUCCEEDED( m_pCON->Close());
}
//Ÿ ߰ϱ
void CAdo::DB_Insert(long lngIndex01, long lngIndex02,CString strLineName01,
CString strLineName02,CString strLineName03,CString strLineName04,CString strLineName05)
{
CString strQuery;
m_pCOM->ActiveConnection = m_pCON;
strQuery.Format("Insert into TB_LINECODE(unit,unitidx,word,wordkr,exkor,exeng,exans) values(%ld,%ld,'%s','%s','%s','%s','%s')",
lngIndex01,lngIndex02,strLineName01,strLineName02,strLineName03,strLineName04,strLineName05);
m_pCOM->CommandText = (LPTSTR)(_bstr_t)strQuery;
try
{
m_pRS = m_pCOM->Execute(NULL, NULL, adCmdText);
}
catch(_com_error &e)
{
COMERRORMSG(e);
return;
}
//OnButtonSearchdb(); //FlexGrid ʱȭ ϰ, ٽ ´.
//DB_Search();
}
//ϱ
void CAdo::DB_Modify(long lngIndex01, long lngIndex02, CString strLineName01,CString strLineName02,CString strLineName03,CString strLineName04,CString strLineName05, CString strOldLineName)
{
CString strQuery;
//m_pCOM->ActiveConnection = m_pCON;
//{"Update TB_LINECODE SET LINENAME='',INDEX=102323 WHERE LINENAME ='⵿ֱ'"}
strQuery.Format("Update TB_LINECODE SET unit=%ld,unitidx=%ld,word='%s',wordkr='%s',exkor='%s',exeng='%s',exans='%s' WHERE word='%s'",
lngIndex01,lngIndex02,strLineName01,strLineName02,strLineName03,strLineName04,strLineName05,strOldLineName);
m_pCOM->ActiveConnection = m_pCON;
m_pCOM->CommandText = (LPTSTR)(_bstr_t)strQuery;
try
{
m_pRS = m_pCOM->Execute(NULL, NULL, adCmdText);
}
catch(_com_error &e)
{
COMERRORMSG(e);
return;
}
}
//Ÿ ϱ where
void CAdo::DB_Delete(CString strQuery)
{
m_pCOM->ActiveConnection = m_pCON;
m_pCOM->CommandText = (LPTSTR)(_bstr_t)strQuery;
try
{
m_pRS = m_pCOM->Execute(NULL, NULL, adCmdText);
}
catch(_com_error &e)
{
COMERRORMSG(e);
return;
}
//OnButtonSearchdb();
}
void CAdo::COMERRORMSG(_com_error &e)
{
CString sMsg, errMsg;
/////////////////////////////////////////////////////////////////////////
// Com errors.
_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());
errMsg.Format("%08lx : %s\n", e.Error(), e.ErrorMessage());
sMsg += errMsg;
errMsg.Format("Source = %s\n", (LPCSTR) bstrSource);
sMsg += errMsg;
errMsg.Format("Description = %s", (LPCSTR) bstrDescription);
sMsg += errMsg;
AfxMessageBox(sMsg, MB_ICONSTOP);
}
/********************************************************************
* ϸ Ʋ FALSE ȯѴ.
* ( .
* ϸ ΰ Ե Ȯ )
*
* return : BOOL : TRUE | FALSE
*
* parameter :
* [in] CString Filename : MDB ϸ
********************************************************************/
BOOL CAdo::FileCmp(CString Filename)
{
if(m_IsDBConn == FALSE)
return FALSE;
return m_strConnection.CompareNoCase(oleString + Filename);
}
/********************************************************************
* ̻ Ʃ TRUE ȯ Ѵ.
*
* return : BOOL : TRUE | FALSE
*
* parameter : None
********************************************************************/
BOOL CAdo::DB_IsEof()
{
if(!m_IsDBOpen)
return TRUE;
return(BOOL)m_pRS->GetadoEOF();
}
/********************************************************************
* Ʃ Field شϴ Instance ڿ · ´.
*
* return : CString : Value
*
* parameter :
* [in] CString Field : Attribute Name
********************************************************************/
CString CAdo::GetValueString(CString Field)
{
if(!m_IsDBOpen || DB_IsEof())
return "";
_variant_t vt = m_pRS->GetCollect((LPTSTR)(LPCTSTR)Field);
if( vt.vt != VT_NULL)
return (LPCSTR)_bstr_t(vt); // str = (LPCSTR)_bstr_t(vt.bstrVal);
else
return "";
}
/********************************************************************
* Ʃ Field شϴ Instance · ´.
*
* return : int : Value
*
* parameter :
* [in] CString Field : Attribute Name
********************************************************************/
int CAdo::GetValueInt(CString Field)
{
/*
_variant_t vi = m_pRS->Fields->GetItem("unit")->GetValue();
int lngIndex01;
CString str;
lngIndex01 = atoi(GetValueString(Field));
str.Format("this val %d", lngIndex01);
AfxMessageBox(str);
return 0;
*/
return atoi(GetValueString(Field));
}
/********************************************************************
* Ʃ÷ ̵Ѵ.
*
* return : BOOL : TRUE | FALSE
*
* parameter : None
********************************************************************/
BOOL CAdo::DB_MoveNext()
{
if(!m_IsDBOpen)
return FALSE;
return SUCCEEDED(m_pRS->MoveNext());
}
/********************************************************************
* ڵ ̵.
*
* return : BOOL : TRUE | FALSE
*
* parameter : None
********************************************************************/
BOOL CAdo::DB_MoveLast()
{
if(!m_IsDBOpen)
return FALSE;
try{
m_pRS->MoveLast();
}catch(_com_error &e){
COMERRORMSG(e);
return FALSE;
}
return TRUE;
}
/********************************************************************
* DML Ѵ.
* connection Ѵ.
*
* return : BOOL : TRUE | FALSE
*
* parameter :
* [in] CString sql : SQL Query DML
* [in] CString Filename : MDB ϸ
********************************************************************/
BOOL CAdo::DB_Excute(CString sql, CString Filename /*=_T("")*/)
{
if(m_pCON == NULL)
return FALSE;
if(Filename.IsEmpty() == FALSE)
{
DB_Connection(Filename);
}
else
{
DB_Connection("");
}
if(m_IsDBConn == FALSE)
return FALSE;
try
{
TRACE(sql);
TRACE("\n");
m_pCON->Execute((_bstr_t)sql, NULL, adCmdText);
}
catch(_com_error &err)
{
TRACE("Error: %s: DB Execute FAIL\n", err.Description());
return FALSE;
}
return TRUE;
}
/********************************************************************
* connection ´.
*
* return : _ConnectionPtr
*
* parameter : None
* [in] CString Filename : MDB ϸ
********************************************************************/
_ConnectionPtr CAdo::DB_GetConnection()
{
return m_pCON;
}
/********************************************************************
* connection AttachѴ.
* ̹ connection Recordset ݴ´.
*
* return : None
*
* parameter :
* [in] _ConnectionPtr conn : Connection Object
********************************************************************/
void CAdo::DB_AttachConnection(_ConnectionPtr conn)
{
if(m_IsDBOpen == TRUE)
DB_Close();
if(m_IsDBConn == TRUE)
{
DB_CloseConnection();
m_pCON.Release();
}
m_pCON = conn;
m_IsDBConn = TRUE;
}
/********************************************************************
* connection AttachѴ.
* ̹ connection Recordset ݴ´.
*
* return : None
*
* parameter :
* [in] _ConnectionPtr conn : Connection Object
********************************************************************/
void CAdo::DB_DetachConnection()
{
if(m_IsDBConn == FALSE)
return;
m_pCON = NULL;
m_IsDBConn = FALSE;
}
void CAdo::Test()
{
_variant_t fldItem01;
CString strLineName01;
//fldItem01 = m_pRS->Fields->GetItem("MaxNum")->GetValue();
//strLineName01 = Convert_Variant_To_String(fldItem01);
AfxMessageBox(strLineName01);
}
| true |
decfb96d45c8ddc6fa7d6ad2e2a194ac39debb5b | C++ | taoyeh/DataStructure | /最大流FF算法.cpp | GB18030 | 1,461 | 2.796875 | 3 | [] | no_license |
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std;
int map[405][405];
int used[405];
int n,m;
const int INF= 0x3f3f3f3f;
int DFS(int s, int t, int f)
{
if(s==t)
return f;//ҵյˣʱʣµܻõ
int i;
for(i=1;i<=n+m+2;i++)
{
if(map[s][i] >0 && used[i] ==0)//sʼ
{
used[i]=1;
int d=DFS(i, t, min(f, map[s][i]));//û·
if(d>0)
{
map[s][i] -=d;
map[i][s] +=d;
return d;
}
}
}
return 0;
}
int maxflow(int s, int t)
{
int flow=0;
while(true)
{
memset(used, 0, sizeof(used));
int f= DFS(s,t, INF);//st·
if(f == 0)
return flow; //Ҳ˾ͻȥ
flow += f;//ҵһfľ
}
}
void init()
{
memset(map, 0, sizeof(map));
return ;
}
int main()
{
while(scanf("%d %d", &n, &m) != EOF)
{
init();
int num, cap;
int i,j,k;
for(i=1;i<=n;i++)
{
scanf("%d", &num);
for(j=0;j<num;j++)
{
scanf("%d", &k);
map[i+1][k+n+1]=1;
}
}
for(i=1;i<=n;i++) map[1][i+1]=1;
for(i=1;i<=m;i++) map[n+1+i][n+m+2]=1;
int ans=maxflow(1,n+m+2);
printf("%d\n", ans);
}
return 0;
}
| true |
8a83d9fbe7c5d3fed253328a6b6b314b32b31d04 | C++ | DorAm1010/FlySimul | /printCommand.cpp | UTF-8 | 780 | 3 | 3 | [] | no_license | //
// Created by dor on 1/2/20.
//
#include <iostream>
#include "readingData.h"
#include "printCommand.h"
using namespace std;
/**
* Execute print command.
**/
int PrintCommand::execute() {
ReadingData* readingData = ReadingData::getInstance();
string print;
// get to argument of Print function
readingData->incInd(1);
print = readingData->getWordsVector()->at(readingData->getInd());
double expression;
// if argument has quotes its a message to be printed without it
if(print[0] == '"') {
cout << print.substr(1, print.length() - 2) << endl;
} else {
// otherwise it is an expression and needs to be interpreted
expression = evaluate(print);
cout << expression << endl;
}
readingData->incInd(1);
} | true |
6b4e49e481f410ace224127799069bf393708114 | C++ | wenqf11/LeetCode | /C++/438. Find All Anagrams in a String/solution.h | UTF-8 | 831 | 2.71875 | 3 | [
"MIT"
] | permissive | #pragma once
#include <vector>
#include <queue>
#include <string>
#include <climits>
#include <algorithm>
#include <cmath>
#include <unordered_map>
#include <set>
using namespace std;
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
vector<int> res, m(256, 0);
if (s.empty()) return res;
int left = 0, right = 0, cnt = p.size(), n = s.size();
for (char c : p) ++m[c];
while (right < n) {
if (m[s[right]] >= 1) cnt--;
m[s[right]]--;
right ++;
if (cnt == 0) res.push_back(left);
if (right - left == p.size()) {
if (m[s[left]] >= 0) {
cnt++;
}
m[s[left]]++;
left++;
}
}
return res;
}
}; | true |
7aaaf613211157c82b1515ec4e8123593f180643 | C++ | shaimendel/BioTagMonitor | /MeasureGraph/AutoMeasureGraphMin/real_rag.cpp | UTF-8 | 3,252 | 2.5625 | 3 | [] | no_license | #include "real_tag.h"
#include "arch.h"
#include "utils.h"
#include "last_samples.h"
vector* real_pulse_samples;
void real_tag_setup(vector* v) {
real_pulse_samples = v;
}
float voltage_in_pulse = 0;
float current_in_pulse = 0;
float voltage_not_in_pulse = 0;
long num_of_relevant_samples = 0;
unsigned long start_of_period = 0;
unsigned long start_of_period_micros = 0;
bool in_pulse = false;
bool too_long_pulse = false;
int long_pulse_seconds = 0;
unsigned long last_samples_offset = 0;
const long NUM_OF_RELEVANT_SAMPLE_LIMIT = 4;
const int TOO_LONG_PULSE_LIMIT_MS = 30;
void real_tag_loop() {
unsigned long currentMillis = millis();
float current_voltage = getVoltage(BATTERY_VOLTAGE); //Battery Voltage
float current_amper = getVoltage(TAG_LOAD_CURRENT); //Current
if (in_pulse) {
if (current_amper < 0.05){
num_of_relevant_samples++;
}
else
num_of_relevant_samples = 0;
}
else {
last_samples_add(current_voltage, current_amper, micros() - start_of_period_micros);
if (current_amper >= 0.06) {
num_of_relevant_samples++;
}
else {
num_of_relevant_samples = 0;
}
}
if (num_of_relevant_samples >= NUM_OF_RELEVANT_SAMPLE_LIMIT) {
if (in_pulse) {
Serial.print(voltage_in_pulse, 5);
Serial.print(",");
Serial.print(current_in_pulse, 5);
Serial.print(",");
Serial.print(currentMillis - start_of_period);
Serial.print(",");
Serial.print(voltage_not_in_pulse, 5);
Serial.print(",");
vector_serialize(real_pulse_samples);
Serial.println();
voltage_not_in_pulse = 0;
vector_reset(real_pulse_samples);
}
else {
last_samples_offset = last_sample_get_micros_offset();
last_samples_fill_vector(real_pulse_samples);
last_samples_reset();
}
start_of_period = currentMillis;
start_of_period_micros = micros();
in_pulse = !in_pulse;
num_of_relevant_samples = 0;
voltage_in_pulse = 100;
current_in_pulse = 0;
too_long_pulse = false;
long_pulse_seconds = 0;
}
if (in_pulse) {
if (current_voltage < voltage_in_pulse) {
voltage_in_pulse = current_voltage;
}
if (current_amper > current_in_pulse) {
current_in_pulse = current_amper;
}
if (!too_long_pulse) {
addPulseToVector(real_pulse_samples, current_voltage, current_amper, micros() + last_samples_offset - start_of_period_micros);
if (currentMillis - start_of_period > TOO_LONG_PULSE_LIMIT_MS) {
too_long_pulse = true;
long_pulse_seconds = (currentMillis - start_of_period) / 1000;
vector_reset(real_pulse_samples);
}
}
}
else {
if (current_voltage > voltage_not_in_pulse) {
voltage_not_in_pulse = current_voltage;
}
}
if (too_long_pulse && (currentMillis - start_of_period)/1000 > long_pulse_seconds){
Serial.print(voltage_in_pulse, 5);
Serial.print(",");
Serial.print(current_in_pulse, 5);
Serial.print(",");
Serial.print(currentMillis - start_of_period);
Serial.print(",");
Serial.print(voltage_not_in_pulse, 5);
Serial.print(",");
Serial.print("*");
Serial.println();
long_pulse_seconds++;
}
}
| true |
70a97c7eb75e41e35a84705eb06d2ce9c8260e48 | C++ | LeeChungHyun/Programmers_Coding_Practice | /Stack&Queue/queue_printer.cpp | UTF-8 | 1,548 | 3.65625 | 4 | [] | no_license | #include <string>
#include <vector>
#include <queue>
#include <iostream>
using namespace std;
/*priority_queue<T, Container, Compare> : 원하는 자료형 및 클래스 T를 통해 생성. 여기서 Container는 vector와 같은 컨테이너이며 Compare는 비교함수 클래스이다.*/
int solution(vector<int> priorities, int location) {
int answer = 0;
queue<pair<int,int>>q;//일반queue에 다 집어넣는다.
priority_queue<int>q1;//그 후 우선순위 큐 사용해 중요도를 고려해 문서를 인쇄한다.
for(int i=0; i < priorities.size(); i++){
q.push(make_pair(i, priorities[i]));
q1.push(priorities[i]);
}
while(!q.empty()){
int i = q.front().first;
int j = q.front().second;
q.pop();
if(j == q1.top()){//현재 문서의 중요도가 가장 높을때 인쇄한다.
q1.pop();
answer += 1;//우선순위 queue도 pop하고 answer 1증가한다.
if(i == location){//현재 문서가 내가 요청한 문서일때 인쇄 할 필요가 없으므로 break.
break;
}
}
else{
q.push(make_pair(i,j));//그 외이면 현재보다 중요문서가 있으므로 다시 queue에 넣는다.
}
}
return answer;
}
void print(vector<int> priorities, int location){
int t = solution(priorities, location);
cout<< t << endl;
}
int main(){
print({2,1,3,2},2);
print({1,1,9,1,1,1},0);
return 0;
} | true |
88026ccf2b3473ce368135e598df0d918c353484 | C++ | liuce-/My-Solution-of-Leetcode-Problems | /494. Target Sum/源.cpp | UTF-8 | 1,738 | 3.484375 | 3 | [] | no_license | //You are given a list of non - negative integers, a1, a2, ..., an, and a target, S.Now you have 2 symbols + and -.For each integer, you should choose one from + and -as its new symbol.
//
//Find out how many ways to assign symbols to make sum of integers equal to target S.
//
//Example 1:
//Input: nums is[1, 1, 1, 1, 1], S is 3.
// Output : 5
// Explanation :
//
// -1 + 1 + 1 + 1 + 1 = 3
// + 1 - 1 + 1 + 1 + 1 = 3
// + 1 + 1 - 1 + 1 + 1 = 3
// + 1 + 1 + 1 - 1 + 1 = 3
// + 1 + 1 + 1 + 1 - 1 = 3
//
// There are 5 ways to assign symbols to make the sum of nums be target 3.
// Note:
// The length of the given array is positive and will not exceed 20.
// The sum of elements in the given array will not exceed 1000.
// Your output answer is guaranteed to be fitted in a 32 - bit integer.
#include<vector>
#include<algorithm>
#include<iostream>
using namespace std;
class Solution {
vector<vector<int>> result;
int shift = 0;
public:
int helper(vector<int>&nums, int n, int target) {
if (nums.size() <= n) {
return 0;
}
if (n == nums.size() - 1) {
result[n ][target + shift] = 0;
if (target == nums[n])
result[n][target + shift] += 1;
if(target==-nums[n])
result[n][target + shift] += 1;
return result[n][target+shift];
}
if (result[n][target+shift] != -1)
return result[n][target+shift];
return result[n][target+shift] = helper(nums, n + 1, target + nums[n]) + helper(nums, n + 1, target - nums[n]);
}
int findTargetSumWays(vector<int>& nums, int target) {
int size = nums.size();
int sum = 0;
for (int i = 0; i < size; i++) {
sum += nums[i];
}
result.resize(size, vector<int>(2 * sum + 1, -1));
shift = sum - target;
return helper(nums, 0, target);
}
}; | true |
9b123d02131546964318283dd9fc63f46c66818c | C++ | heitoradao/minimos_quadrados | /mmq.cpp | UTF-8 | 1,548 | 3.234375 | 3 | [
"MIT"
] | permissive | #include "mmq.h"
double gi(double x, int i)
{
double resultado = 1;
for (int j = 0; j < i; j++) {
resultado *= x;
}
return resultado;
}
SPonto *PreencheTabela(int *numeroPontos)
{
cout << "Informe o numero de pontos: ";
cin >> (*numeroPontos);
SPonto *tabela = new SPonto[*numeroPontos];
for (int i = 0; i < *numeroPontos; i++) {
cout << "X[" << i << "] = ";
cin >> tabela[i].x;
cout << "Y[" << i << "] = ";
cin >> tabela[i].y;
}
return tabela;
}
double **PreencheMatrizCoeficientes(SPonto *tabelaPontos, int numeroPontos, int grauPolinomio)
{
// Aloca memoria para a matriz.
double **matriz = new double*[grauPolinomio + 1];
for (int linha = 0; linha <= grauPolinomio; linha++) {
matriz[linha] = new double[grauPolinomio + 1];
for (int coluna = 0; coluna <= grauPolinomio; coluna++) {
matriz[linha][coluna] = 0;
for (int i = 0; i < numeroPontos; i++) {
matriz[linha][coluna] += gi(tabelaPontos[i].x, linha) * gi(tabelaPontos[i].x, coluna);
}
}
}
return matriz;
}
double *PreencheVetorTermosIndependentes(SPonto *tabelaPontos, int numeroPontos, int grauPolinomio)
{
double *vetor = new double [grauPolinomio + 1];
for (int linha = 0; linha <= grauPolinomio; linha++) {
vetor[linha] = 0;
for (int i = 0; i < numeroPontos; i++) {
vetor[linha] += (gi(tabelaPontos[i].x, linha) * tabelaPontos[i].y);
}
}
return vetor;
}
| true |
84733597efad67cbbf9a3ad7a522c6c4967aa6f4 | C++ | thebravoman/software_engineering_2015 | /VhodnoNivo/Georgi_Stoilov/Georgi_Stoilov_05.cc | UTF-8 | 936 | 3.296875 | 3 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
int main(){
int x;
float arr[10];
bool isOrder = false;
bool isSorted = false;
cout << "Insert X between 0 and 10" << endl;
cin >> x;
while(x <= 0 || x >= 10){
cout << "Insert X between 0 and 10" << endl;
cin >> x;
}
for(int count = 0; count < 10; count++){
arr[count] = cos(count);
cout << arr[count] << ", ";
}
while(isOrder == false){
int a = 0;
for(int count = 0; count < 10; count++){
if(arr[count] < arr[count+1] ){
float c = arr[count+1];
arr[count+1] = arr[count];
arr[count] = c;
isSorted = false;
}else{
a++;
if(a == 10){
isSorted = true;
}
}
}
if(isSorted == true){
isOrder = true;
arr[5] = 0;
}else {
isOrder = false;
}
}
cout << "" << endl;
cout << "Sorted: " ;
for(int count = 0; count < 11; count++){
cout<< arr[count] << ", ";
}
cout << "" << endl;
return 0;
}
| true |
39a04e02cad74df5bf9a04aeb85eedfce965a717 | C++ | puorc/uNetwork | /src/MessageListener.cpp | UTF-8 | 7,341 | 2.75 | 3 | [] | no_license | #include "MessageListener.h"
void MessageListener::start() {
unlink(unix_sock_path);
int main_sock;
if ((main_sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
throw std::system_error(EBADF, std::system_category(), "Unable to open Unix socket.");
}
struct sockaddr_un addr;
memset(&addr, 0, sizeof(struct sockaddr_un));
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, unix_sock_path, sizeof(addr.sun_path) - 1);
int rc = bind(main_sock, reinterpret_cast<const sockaddr *>(&addr), sizeof(addr.sun_path) - 1);
if (rc == -1) {
throw std::system_error(EBADF, std::system_category(), "Unable to bind to socket.");
}
if ((listen(main_sock, 20)) == -1) {
throw std::system_error(EBADF, std::system_category(), "Unable to listen to socket.");
}
if (chmod(unix_sock_path, S_IRUSR | S_IWUSR | S_IXUSR |
S_IRGRP | S_IWGRP | S_IXGRP |
S_IROTH | S_IWOTH | S_IXOTH) == -1) {
throw std::system_error(EBADF, std::system_category(), "Unable to set permission.");
}
for (;;) {
int fd = accept(main_sock, NULL, NULL);
if (fd == -1) {
throw std::system_error(EBADF, std::system_category(), "Accept error");
}
std::thread t(&MessageListener::process, this, fd);
t.detach();
}
close(main_sock);
}
void MessageListener::process(int fd) {
int rc;
char buf[LEN];
while ((rc = read(fd, buf, LEN)) > 0) {
auto *msg = reinterpret_cast<ipc_msg *>(buf);
switch (msg->type) {
case IPC_SOCKET:
reply(fd, IPC_SOCKET, msg->pid, tcp.socket());
break;
case IPC_CONNECT: {
net_connect(msg, fd);
break;
}
case IPC_READ: {
net_read(msg, fd);
break;
}
case IPC_WRITE: {
net_write(msg, fd);
break;
}
case IPC_FCNTL: {
struct ipc_fcntl *fc = (struct ipc_fcntl *) msg->data;
pid_t pid = msg->pid;
int rc = -1;
switch (fc->cmd) {
case F_GETFL:
rc = O_RDWR;
break;
case F_SETFL:
rc = 0;
break;
default:
rc = -EINVAL;
}
reply(fd, IPC_FCNTL, pid, rc);
break;
}
case IPC_POLL: {
net_poll(msg, fd);
break;
}
case IPC_CLOSE: {
pid_t pid = msg->pid;
auto *payload = (struct ipc_close *) msg->data;
tcp.close(payload->sockfd);
reply(fd, IPC_CLOSE, pid, 0);
break;
}
case IPC_GETPEERNAME:
case IPC_GETSOCKNAME:
getname(fd, msg);
break;
}
}
close(fd);
}
void MessageListener::reply(int fd, int type, pid_t pid, int rc) {
size_t size = sizeof(struct ipc_msg) + sizeof(struct ipc_err);
auto *response = reinterpret_cast<ipc_msg *>(new uint8_t[size]);
response->type = type;
response->pid = pid;
struct ipc_err err;
if (rc < 0) {
err.err = -rc;
err.rc = -1;
} else {
err.err = 0;
err.rc = rc;
}
memcpy(response->data, &err, sizeof(struct ipc_err));
if (send(fd, response, size, MSG_NOSIGNAL) == -1) {
perror("Error on writing IPC write response");
}
}
void MessageListener::getname(int fd, struct ipc_msg *msg) {
pid_t pid = msg->pid;
auto *name = reinterpret_cast<ipc_sockname *>(msg->data);
int rc = 0;
size_t resplen = sizeof(struct ipc_msg) + sizeof(struct ipc_err) + sizeof(struct ipc_sockname);
struct ipc_msg *response = reinterpret_cast<ipc_msg *>(new uint8_t[resplen]);
response->type = msg->type;
response->pid = pid;
struct ipc_sockname *nameres = (struct ipc_sockname *) ((struct ipc_err *) response->data)->data;
rc = tcp.get_name(name->socket, (struct sockaddr *) nameres->sa_data, &nameres->address_len,
msg->type == IPC_GETPEERNAME);
struct ipc_err err;
if (rc < 0) {
err.err = -rc;
err.rc = -1;
} else {
err.err = 0;
err.rc = rc;
}
memcpy(response->data, &err, sizeof(struct ipc_err));
nameres->socket = name->socket;
if (send(fd, response, resplen, MSG_NOSIGNAL) == -1) {
perror("Error on writing IPC getpeername response");
}
}
void MessageListener::net_read(struct ipc_msg *msg, int fd) {
pid_t pid = msg->pid;
auto *payload = reinterpret_cast<struct ipc_read *>(msg->data);
uint8_t rbuf[payload->len];
ssize_t n = tcp.read(payload->sockfd, rbuf, payload->len);
size_t resplen = sizeof(struct ipc_msg) + sizeof(struct ipc_err) +
sizeof(struct ipc_read) + payload->len;
auto *response = reinterpret_cast<ipc_msg *>(new uint8_t[resplen]);
auto *error = reinterpret_cast<ipc_err *>(response->data);
auto *actual = reinterpret_cast<ipc_read *>(error->data);
response->type = IPC_READ;
response->pid = pid;
error->rc = n;
error->err = 0;
actual->sockfd = payload->sockfd;
actual->len = n;
std::copy(rbuf, rbuf + payload->len, actual->buf);
send(fd, response, resplen, MSG_NOSIGNAL);
}
void MessageListener::net_write(struct ipc_msg *msg, int fd) {
auto *data = reinterpret_cast<ipc_write *>(msg->data);
printf("messgae %s\n", data->buf);
ssize_t size = tcp.write(data->sockfd, data->buf, data->len);
reply(fd, IPC_WRITE, msg->pid, size);
}
void MessageListener::net_connect(struct ipc_msg *msg, int fd) {
auto *data = reinterpret_cast<struct ipc_connect *>(msg->data);
tcp.connect(data->sockfd, data->addr.sin_addr.s_addr, ntohs(data->addr.sin_port), [&](int rc) {
reply(fd, IPC_CONNECT, msg->pid, rc);
});
}
void MessageListener::net_poll(struct ipc_msg *msg, int fd) {
struct ipc_poll *data = (struct ipc_poll *) msg->data;
pid_t pid = msg->pid;
int rc = -1;
struct pollfd fds[data->nfds];
for (int i = 0; i < data->nfds; i++) {
fds[i].fd = data->fds[i].fd;
fds[i].events = data->fds[i].events;
fds[i].revents = data->fds[i].revents;
}
rc = tcp.poll(fds, data->nfds, data->timeout);
int resplen = sizeof(struct ipc_msg) + sizeof(struct ipc_err) + sizeof(struct ipc_pollfd) * data->nfds;
struct ipc_msg *response = reinterpret_cast<ipc_msg *>(new uint8_t[resplen]);
response->type = IPC_POLL;
response->pid = pid;
struct ipc_err err;
if (rc < 0) {
err.err = -rc;
err.rc = -1;
} else {
err.err = 0;
err.rc = rc;
}
memcpy(response->data, &err, sizeof(struct ipc_err));
struct ipc_pollfd *polled = (struct ipc_pollfd *) ((struct ipc_err *) response->data)->data;
for (int i = 0; i < data->nfds; i++) {
polled[i].fd = fds[i].fd;
polled[i].events = fds[i].events;
polled[i].revents = fds[i].revents;
}
send(fd, response, resplen, MSG_NOSIGNAL);
}
| true |
bda245fcae65d2287fc09a6d42fdc7cc046092f8 | C++ | Topru333/speed-test | /server/cppsrc/Samples/math.cpp | UTF-8 | 2,102 | 3.1875 | 3 | [] | no_license | #include "math.h"
#include <vector>
#include <stdlib.h>
int Math::Fibonacci(int n){
if (n <= 1) {
return n;
} else {
return Math::Fibonacci(n-1) + Math::Fibonacci(n-2);
}
}
int Math::FibonacciMap(int n){
if (n <= 1) {
return n;
}
std::vector<int> table(n+1);
table[0] = 0;
table[1] = 1;
for (int i = 2; i <= n; i++) {
table[i] = table[i-1] + table[i-2];
}
return table.back();
}
Napi::Number Math::FibonacciWrapped(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
if (info.Length() < 2 || !info[0].IsNumber() || !info[1].IsBoolean()) {
Napi::TypeError::New(env, "Wrong atributes").ThrowAsJavaScriptException();
}
Napi::Number value = info[0].As<Napi::Number>();
Napi::Boolean withmap = info[1].As<Napi::Boolean>();
int result = 0;
if (withmap) {
result = Math::FibonacciMap(value.Int32Value());
} else {
result = Math::Fibonacci(value.Int32Value());
}
return Napi::Number::New(env, result);
}
double Math::Sqrt(double x, double g, double closeto) {
if (abs(x/g - g) < closeto) {
return g;
} else {
return Math::Sqrt(x, ((g + x/g) / 2), closeto);
}
}
Napi::Number Math::SqrtWrapped(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
if (info.Length() < 2 || !info[0].IsNumber() || !info[1].IsNumber() || (info.Length() == 3 && !info[2].IsNumber())) {
Napi::TypeError::New(env, "Wrong atributes").ThrowAsJavaScriptException();
}
Napi::Number x = info[0].As<Napi::Number>();
Napi::Number g = info[1].As<Napi::Number>();
double result = 0;
if (info.Length() == 3) {
Napi::Number closeto = info[2].As<Napi::Number>();
result = Math::Sqrt(x.DoubleValue(), g.DoubleValue(), closeto.DoubleValue());
} else {
result = Math::Sqrt(x.DoubleValue(), g.DoubleValue(), 0.001);
}
return Napi::Number::New(env, result);
}
Napi::Object Math::Init(Napi::Env env, Napi::Object exports) {
exports.Set("Fibonacci", Napi::Function::New(env, Math::FibonacciWrapped));
exports.Set("Sqrt", Napi::Function::New(env, Math::SqrtWrapped));
return exports;
}
| true |
f3cce3c0bee9f1012f71b76abb3a4051433dea18 | C++ | sourcecodebd/Sorting-Algoritm | /Linear Search.cpp | UTF-8 | 493 | 3.578125 | 4 | [] | no_license | #include<iostream>
#define size 5
using namespace std;
int linear_search(int arr[], int e)
{
int i,found=-1;
for(i=0; i<size; i++)
{
if(arr[i]==e)
{
found=i;
break;
}
}
return found;
}
int main()
{
int arr[size];
cout<<"Enter value: "<<endl;
for(int i=0; i<size; i++)
{
cin>>arr[i];
}
int e;
cout<<"Enter the value for searching: "<<endl;
cin>>e;
int r=linear_search(arr,e);
if(r==-1)
{
cout<<"Not found"<<endl;
}
else
{
cout<<"Found at index"<<endl;
}
}
| true |
3f3d59f7382ba74ddb42397b29d2937f7203780d | C++ | NamrathaHV/Computer_Graphics | /17E_3M-Spin_Cube_change_color.cpp | UTF-8 | 2,821 | 3.296875 | 3 | [] | no_license | /* 17E-3M. /*Write a program to spin a cube clockwise, anticlockwise and change color using menu
callback function. */
#include<gl/glut.h>
#include<gl/GLU.h>
#include<math.h>
#include<iostream>
GLfloat d = 0;
int a = 0;
void MyInit()
{
glClearColor(0, 0, 0, 1);
glEnable(GL_DEPTH_TEST);
}
void Spin()
{
d = d + 0.25;
if (d > 360)
d = 0;
glutPostRedisplay();
}
void Face(GLfloat A[], GLfloat B[], GLfloat C[], GLfloat D[])
{
glBegin(GL_POLYGON);
glVertex3fv(A);
glVertex3fv(B);
glVertex3fv(C);
glVertex3fv(D);
glEnd();
}
void Cube(GLfloat V0[], GLfloat V1[], GLfloat V2[], GLfloat V3[], GLfloat V4[], GLfloat V5[], GLfloat V6[], GLfloat V7[])
{
glColor3f(1, 0, 0);
Face(V0, V1, V2, V3); //Front
glColor3f(0, 1, 0);
Face(V4, V5, V6, V7); //Back
glColor3f(0, 0, 1);
Face(V0, V4, V7, V3); //Left
glColor3f(1, 1, 0);
Face(V1, V5, V6, V2); //Right
glColor3f(1, 0, 1);
Face(V2, V3, V7, V6); //Bot
glColor3f(0, 1, 1);
Face(V0, V1, V5, V4); //Top
}
void Draw()
{
GLfloat V[8][3] = {
{-0.5, 0.5, 0.5},
{ 0.5, 0.5, 0.5},
{ 0.5,-0.5, 0.5},
{-0.5,-0.5, 0.5},
{-0.5, 0.5,-0.5},
{ 0.5, 0.5,-0.5},
{ 0.5,-0.5,-0.5},
{-0.5,-0.5,-0.5},
};
GLfloat rV[8][3], r;
int i;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
r = d * 3.14 / 180;
if (a == 1)
{
for (i = 0; i < 8; i++)
{
rV[i][0] = V[i][0];
rV[i][1] = V[i][1] * cos(r) - V[i][2] * sin(r);
rV[i][2] = V[i][1] * sin(r) + V[i][2] * cos(r);
}
}
if (a == 2)
{
for (i = 0; i < 8; i++)
{
rV[i][0] = V[i][2] * sin(r) + V[i][0] * cos(r);
rV[i][1] = V[i][1];
rV[i][2] = V[i][2] * cos(r) - V[i][0] * sin(r);
}
}
if (a == 3)
{
for (i = 0; i < 8; i++)
{
rV[i][0] = V[i][0] * cos(r) - V[i][1] * sin(r);
rV[i][1] = V[i][0] * sin(r) + V[i][1] * cos(r);
rV[i][2] = V[i][2];
}
}
Cube(rV[0], rV[1], rV[2], rV[3], rV[4], rV[5], rV[6], rV[7]);
glutSwapBuffers();
}
int main(int argc, char* argv[])
{
printf("Enter the Axis of Rotation [ 1->Xaxis | 2->Yaxis | 3->Zaxis ]: ");
scanf_s("%d", &a);
glutInit(&argc, argv);
glutInitWindowSize(600, 600);
glutInitWindowPosition(50, 150);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("Cube Spin with Matrices");
MyInit();
glutDisplayFunc(Draw);
glutIdleFunc(Spin);
glutMainLoop();
return 0;
} | true |
04a2117cf6ceb6920f77b55d2717db6be9b1f06b | C++ | suyinlong/leetcode | /393-UTF-8.Validation.cpp | UTF-8 | 1,113 | 2.984375 | 3 | [] | no_license | class Solution {
private:
bool validHelper(vector<int> &data, int p) {
if (p >= data.size())
return false;
if (((data[p] >> 6) & 3) == 2)
return true;
return false;
}
public:
bool validUtf8(vector<int>& data) {
if (data.size() == 0)
return true;
int p = 0;
while (p < data.size()) {
if (((data[p] >> 7) & 1) == 0)
p++;
else if (((data[p] >> 5) & 7) == 6) {
if (!validHelper(data, p+1))
return false;
p += 2;
}
else if (((data[p] >> 4) & 15) == 14) {
if (!validHelper(data, p+1) || !validHelper(data,p+2))
return false;
p += 3;
}
else if (((data[p] >> 3) & 31) == 30) {
if (!validHelper(data,p+1) || !validHelper(data,p+2) || !validHelper(data,p+3))
return false;
p += 4;
}
else
return false;
}
return true;
}
}; | true |
954b71aec9cfd9036a9e4e065c14fe8980559531 | C++ | nawZeroX239/competitive-programming | /UVAOJ/UVAOJ12150.cpp | UTF-8 | 818 | 2.625 | 3 | [] | no_license | #include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
#include <unordered_set>
using namespace std;
int main() {
int n;
int cars[1001];
long sum = 0;
int c, s;
bool b;
unordered_set<int> uset;
while (scanf("%d", &n) && n > 0) {
sum = 0;
b = true;
for (int i = 1; i <= n; i++) {
scanf("%d%d", &c, &s);
//printf(" i+s:%d ", i + s);
sum += s;
if (!b)
continue;
if (i+s<1 || i+s>n || (i + s > 0 && i + s < n+1
&& uset.find(i + s) != uset.end())) {
b = false;
} else {
uset.insert(i + s);
cars[i + s] = c;
}
}
//printf(" sum:%d ", sum);
if (sum != 0 || !b) {
printf("%d\n", -1);
} else {
printf("%d", cars[1]);
for (int i = 2; i < n + 1; i++)
printf(" %d", cars[i]);
printf("\n");
}
uset.clear();
}
return 0;
}
| true |
c4ae88bf4710c922e3e6b161d3b4df9d6ec31c75 | C++ | minaminao/competitive-programming | /cpp/library/library/NumberTheory.cpp | SHIFT_JIS | 7,090 | 3.1875 | 3 | [] | no_license | #include "ModInt.cpp"
/*
vZʂ𗎂Ƃ
gcd(x%y,y) == gcd(x,y)
y̐ƂAgcd(x%y,y) ̒lŏꍇ
̌ N<=10^9 ̂Ƃ X1344
f̌ N<=10^9 ̂Ƃ X9
*/
//߂ \[g
vector<int> divisor(int x) {
vector<int> ret;
int i;
for (i = 1; i*i < x; i++) {
if (x%i)continue;
ret.emplace_back(i);
ret.emplace_back(x / i);
}
if (i*i == x)ret.emplace_back(i);
return ret;
}
//ő
int gcd(int x, int y) { return y ? gcd(y, x%y) : x; }
//ŏ{
int lcm(int x, int y) { return x*y / gcd(x, y); }
//ő
int gcd(const vector<int> &v) {
int ret = v[0];
for (int i = 1; i < v.size(); i++)
ret = gcd(ret, v[i]);
return ret;
}
//ŏ{
int lcm(const vector<int> &v) {
int ret = v[0];
for (int i = 1; i < v.size(); i++)
ret = lcm(ret, v[i]);
return ret;
}
//g[Nbȟݏ@
//ax+by=gcd(a,b) x, y ߂
//http://mathtrain.jp/euclid (ꎟsւ̉p)
long long extgcd(long long a, long long b, long long &x, long long &y) {
long long g = a; x = 1; y = 0;
if (b != 0) {
g = extgcd(b, a % b, y, x);
y -= (a / b) * x;
}
return g;
}
const double EPS = 1e-8;
//mod(double)
double modulo(double x, double mod) {
x -= floor(x / mod)*mod;
if (x<EPS || x + EPS>mod)x = 0;
return x;
}
//ŏ](c/c++͐Βlŏ])
int modulo(int x, int mod) {
return (x%mod < 0) ? x%mod + abs(mod) : x%mod;
}
//ݏ JԂ@
//I[o[t[\Ί|Zmodmul()g
long long modpow(long long base, long long exponent, long long mod) {
long long res = 1;
while (exponent > 0) {
if (exponent & 1)res = res * base % mod;
base = base * base % mod;
exponent >>= 1;
}
return res;
}
//(a*b)%mod
long long modmul(long long a, long long b, long long mod) {
long long x = 0, y = a % mod;
while (b > 0) {
if (b & 1)x = x + y % mod;
y = y * 2 % mod;
b >>= 1;
}
return x % mod;
}
//fiMiller-Rabin primality testj2^24x
//miller_rabin_primality_test(n, 5)
bool miller_rabin_primality_test(long long x, int iteration) {
if (x < 2)return false;
if (x != 2 && x % 2 == 0)return false;
long long s = x - 1;
while (s % 2 == 0)s /= 2;
for (int i = 0; i < iteration; i++) {
long long a = rand() % (x - 1) + 1, temp = s;
long long mod = modpow(a, temp, x);
while (temp != x - 1 && mod != 1 && mod != x - 1) {
mod = modmul(mod, mod, x);
temp *= 2;
}
if (mod != x - 1 && temp % 2 == 0)return false;
}
return true;
}
//t
//xy%m=1, y<m ƂȂy߂
long long modinv(long long x, long long m) {
long long s, t;
extgcd(x, m, s, t);
return (s + m) % m;
}
//f
bool is_prime(int x) {
if (x <= 1)return false;
else if (x == 2)return true;
if (x % 2 == 0)return false;
for (int i = 3; i*i <= x; i += 2)
if (x%i == 0)return false;
return true;
}
//1͍ł͂Ȃ
//1+f+
// GgXelX
//nȉ̐f肵is_prime[]Ɋi[
void eratos(int n, bool is_prime[]) {
fill(is_prime, is_prime + n + 1, true);
is_prime[0] = is_prime[1] = false;
for (int i = 2; i*i <= n; i++)
if (is_prime[i]) {
int j = i + i;
while (j <= n) {
is_prime[j] = false;
j += i;
}
}
}
//GgXelX
vector<char> eratos(int n) {
vector<char> is_prime(n + 1, true);
is_prime[0] = is_prime[1] = false;
for (int i = 2; i*i <= n; i++)
if (is_prime[i]) {
int j = i + i;
while (j <= n) {
is_prime[j] = false;
j += i;
}
}
return is_prime;
}
//߂l: nȉ̑f
vector<int> get_primes(int n) {
vector<char> is_prime = eratos(n);
vector<int> primes;
for (int i = 0; i < n + 1; i++)
if (is_prime[i])
primes.emplace_back(i);
return primes;
}
//f
vector<int> prime_factorization(int x) {
vector<int> primes = get_primes(sqrt(x)); //xȉ̑fɂĒׂΗǂ
vector<int> factors;
for (auto &p : primes) {
while (x%p == 0) {
x /= p;
factors.emplace_back(p);
}
}
if (x != 1)factors.emplace_back(x);
return factors;
}
//IC[̃ӊiEuler's totient functionj
//nƌ݂ɑfȐ[1,n]̌
//http://mathtrain.jp/phi
int eulerTotient(int n) {
int ret = n;
for (int x = 2; x*x <= n; x++) {
if (n%x)continue;
ret -= ret / x;
while (n%x == 0)
n /= x;
}
if (n != 1)
ret -= ret / n;
return ret;
}
//nCrzpXJ̎Op`琶
//double Ȃ 10^308 炢܂OK
using Num = double;
vector<vector<Num>> nCr;
void compute_nCr(int n) {
vector<Num> a(1, 1), b(2, 1);
nCr = { a,b };
for (int i = 3; i <= n + 1; i++) {
swap(a, b);
b.resize(i);
b[0] = 1; b[i - 1] = 1;
for (int j = 1; j < i - 1; j++)
b[j] = a[j - 1] + a[j];
nCr.emplace_back(b);
}
}
//m
//iiڂ̘a͕K1.0
void compute_nCr_probability(int n) {
vector<Num> a(1, 1.0), b(2, 1.0 / 2.0);
nCr = { a,b };
for (int i = 3; i <= n + 1; i++) {
swap(a, b);
b.resize(i);
b.front() = a.front() / 2.0; b.back() = a.back() / 2.0;
for (int j = 1; j < i - 1; j++)
b[j] = a[j - 1] / 2.0 + a[j] / 2.0;
nCr.emplace_back(b);
}
}
//ni@
struct Radix {
string s;
int a[128];
Radix(string s = "0123456789ABCDEF") :s(s) {
for (int i = 0; i < s.size(); i++)
a[s[i]] = i;
}
//10i(long long) -> ni(string)
string format(long long x, int n, int len = 1) {
if (!x)return string(len, s[0]);
string ret;
for (; x || len > 0; x /= n, len--)
ret += s[x%n];
reverse(ret.begin(), ret.end());
return ret;
}
using It = string::iterator;
//mi(string) -> ni(string)
string format(It l, It r, int m, int n, int len = 1) {
return format(format(l, r, m), n, len);
}
//mi(string) -> 10i(long long)
long long format(It l, It r, int m) {
long long x = a[*l];
for (l++; l != r; l++)
x = x * m + a[*l];
return x;
}
};
/*
1) 𐔒lƂĈ 27i@ Radix r(" abcdefghijklmnopqrstuvwxyz");
http://judge.u-aizu.ac.jp/onlinejudge/creview.jsp?rid=2231361&cid=RitsCamp17Day1
2) http://arc009.contest.atcoder.jp/submissions/1177495
*/
//L <= x <= R x ̌
int number_in_range(const vector<int> &v, int L, int R) {
return upper_bound(v.begin(), v.end(), R) - lower_bound(v.begin(), v.end(), L);
}
// v ̕ו
mint number_of_arrangement(vector<int> v) {
int n = v.size();
assert(fact.size() >= n);
mint ret = fact[n];
unordered_map<int, int> cnt;
for (auto &e : v)cnt[e]++;
sort(v.begin(), v.end());
v.erase(unique(v.begin(), v.end()), v.end());
for (auto &e : v)ret /= fact[cnt[e]];
return ret;
}
//tB{ib`
vector<int> fibonacci(int n) {
vector<int> v(n);
v[0] = v[1] = 1;
rep(i, 0, n - 2)
v[i + 2] += v[i + 1] + v[i];
return v;
}
vector<int> compute_pow(int b, int e) {
vector<int> ret(e);
ret[0] = 1;
rep(i, 0, e - 1)ret[i + 1] = ret[i] * b;
return ret;
} | true |
c79024559d36d90b37fd5204df6c232333b1b4f9 | C++ | vladimir-kirillovskiy/misc | /C++/projects/hspg-glade/main.cpp | UTF-8 | 1,080 | 2.703125 | 3 | [] | no_license | #include <gtkmm/application.h>
#include <gtkmm/builder.h>
#include <glibmm/markup.h>
#include <glibmm/fileutils.h>
#include <iostream>
#include "gui.h"
int main (int argc, char **argv)
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
//Load the Glade file and instiate its widgets:
Glib::RefPtr<Gtk::Builder> refBuilder = Gtk::Builder::create();
try
{
refBuilder->add_from_file("hspggui.glade");
}
catch(const Glib::FileError& ex)
{
std::cerr << "FileError: " << ex.what() << std::endl;
return 1;
}
catch(const Glib::MarkupError& ex)
{
std::cerr << "MarkupError: " << ex.what() << std::endl;
return 1;
}
catch(const Gtk::BuilderError& ex)
{
std::cerr << "BuilderError: " << ex.what() << std::endl;
return 1;
}
//Get the GtkBuilder-instantiated dialog::
Gui* pWindow = 0;
refBuilder->get_widget_derived("window1", pWindow);
if(pWindow)
{
pWindow->set_title("HS Password Generator");
//Start:
app->run(*pWindow);
}
delete pWindow;
return 0;
} | true |
8b9ee611be3f051159fb93384aa87bc876085ef1 | C++ | ChrisLundquist/cs250 | /math/Matrix4.cpp | UTF-8 | 4,592 | 3.46875 | 3 | [] | no_license | #include "Matrix4.h"
Matrix4::Matrix4(void) {
Zero();
}
// Copy constructor, copies every entry from the other matrix.
Matrix4::Matrix4(const Matrix4& rhs) {
for( unsigned i = 0; i < 4 * 4; i++)
v[i] = rhs.v[i];
}
// Non-default constructor, self-explanatory
Matrix4::Matrix4(f32 mm00, f32 mm01, f32 mm02, f32 mm03,
f32 mm10, f32 mm11, f32 mm12, f32 mm13,
f32 mm20, f32 mm21, f32 mm22, f32 mm23,
f32 mm30, f32 mm31, f32 mm32, f32 mm33) {
m[0][0] = mm00;
m[0][1] = mm01;
m[0][2] = mm02;
m[0][3] = mm03;
m[1][0] = mm10;
m[1][1] = mm11;
m[1][2] = mm12;
m[1][3] = mm13;
m[2][0] = mm20;
m[2][1] = mm21;
m[2][2] = mm22;
m[2][3] = mm23;
m[3][0] = mm30;
m[3][1] = mm31;
m[3][2] = mm32;
m[3][3] = mm33;
}
// Assignment operator, does not need to handle self-assignment
Matrix4& Matrix4::operator=(const Matrix4& rhs) {
for( unsigned i = 0; i < 4 * 4; i++)
v[i] = rhs.v[i];
return *this;
}
// Multiplying a Matrix4 with a Vector4 or a Point4
Vector4 Matrix4::operator*(const Vector4& rhs) const {
Vector4 tmp = Vector4(0,0,0,0);
for( unsigned i = 0; i < 4; i++)
for( unsigned j = 0; j < 4; j++)
tmp.v[i] += rhs.v[j] * m[i][j];
return tmp;
}
Point4 Matrix4::operator*(const Point4& rhs) const {
Point4 tmp = Point4(0,0,0,0);
for( unsigned i = 0; i < 4; i++)
for( unsigned j = 0; j < 4; j++)
tmp.v[i] += rhs.v[j] * m[i][j];
return tmp;
}
// Basic Matrix arithmetic operations
Matrix4 Matrix4::operator+(const Matrix4& rhs) const {
Matrix4 tmp = Matrix4();
for(unsigned i = 0; i < 4 * 4; i++)
tmp.v[i] = v[i] + rhs.v[i];
return tmp;
}
Matrix4 Matrix4::operator-(const Matrix4& rhs) const {
Matrix4 tmp = Matrix4();
for(unsigned i = 0; i < 4 * 4; i++)
tmp.v[i] = v[i] - rhs.v[i];
return tmp;
}
Matrix4 Matrix4::operator*(const Matrix4& rhs) const {
Matrix4 tmp = Matrix4();
for (unsigned i = 0; i < 4; i++)
for (unsigned j = 0; j < 4; j++)
for (unsigned k = 0; k < 4; k++)
tmp.m[i][j] += m[i][k] * rhs.m[k][j];
return tmp;
}
// Similar to the three above except they modify
// the original
Matrix4& Matrix4::operator+=(const Matrix4& rhs) {
for(unsigned i = 0; i < 4 * 4; i++)
v[i] += rhs.v[i];
return *this;
}
Matrix4& Matrix4::operator-=(const Matrix4& rhs) {
for(unsigned i = 0; i < 4 * 4; i++)
v[i] -= rhs.v[i];
return *this;
}
Matrix4& Matrix4::operator*=(const Matrix4& rhs) {
*this = *this * rhs;
return *this;
}
// Scale/Divide the entire matrix by a float
Matrix4 Matrix4::operator*(const f32 rhs) const {
Matrix4 tmp = Matrix4();
for(unsigned i = 0; i < 4 * 4; i++)
tmp.v[i] = v[i] * rhs;
return tmp;
}
Matrix4 Matrix4::operator/(const f32 rhs) const {
Matrix4 tmp = Matrix4();
for(unsigned i = 0; i < 4 * 4; i++)
tmp.v[i] = v[i] / rhs;
return tmp;
}
// Same as previous
Matrix4& Matrix4::operator*=(const f32 rhs) {
for(unsigned i = 0; i < 4 * 4; i++)
v[i] *= rhs;
return *this;
}
Matrix4& Matrix4::operator/=(const f32 rhs) {
for(unsigned i = 0; i < 4 * 4; i++)
v[i] /= rhs;
return *this;
}
// Comparison Matrix4::operators which should use an epsilon defined in
// Utilities.h to see if the value is within a certain range
// in which case we say they are equivalent.
bool Matrix4::operator==(const Matrix4& rhs) const {
for( unsigned i = 0; i < 4 * 4; i++)
if( fabs(v[i] - rhs.v[i]) > EPSILON)
return false;
return true;
}
bool Matrix4::operator!=(const Matrix4& rhs) const {
return !(*this == rhs);
}
// Zeroes out the entire matrix
void Matrix4::Zero(void) {
for( unsigned i = 0; i < 4 * 4; i++)
v[i] = 0;
}
// Builds the identity matrix
void Matrix4::Identity(void) {
for( unsigned i = 0; i < 4; i++)
for( unsigned j = 0; j < 4; j++)
m[i][j] = i == j;
}
void Matrix4::Print(void) const {
printf("--------------------------\n");
printf("%5.3f %5.3f %5.3f %5.3f\n", m00, m01, m02, m03 );
printf("%5.3f %5.3f %5.3f %5.3f\n", m10, m11, m12, m13 );
printf("%5.3f %5.3f %5.3f %5.3f\n", m20, m21, m22, m23 );
printf("%5.3f %5.3f %5.3f %5.3f\n", m30, m31, m32, m33 );
printf("--------------------------\n");
}
| true |
b542b96ed4f9210f5b24f50a75b6e6d6c757c412 | C++ | erwinbonsma/BusyBeaverFinder | /BusyBeaverFinder/SweepTransitionGroup.h | UTF-8 | 13,462 | 2.671875 | 3 | [
"MIT"
] | permissive | //
// SweepTransitionGroup.h
// BusyBeaverFinder
//
// Created by Erwin on 13/11/2020.
// Copyright © 2020 Erwin. All rights reserved.
//
#ifndef SweepTransitionGroup_h
#define SweepTransitionGroup_h
#include "LoopAnalysis.h"
#include "Utils.h"
#include "RunSummary.h"
class Data;
class ExecutionState;
#include <map>
#include <set>
/* Different types of behaviour at one end of the sweep. These are determined during analysis and
* require different checks to proof that the program is indeed hanging.
*/
enum class SweepEndType : int {
UNKNOWN = 0,
// TODO: Rename to MONOTONOUS_GROWTH
/* The sequence is growing each sweep. Each iteration it adds one (or more) non-exit values
* to the sweep body.
*/
STEADY_GROWTH = 1,
// TODO: Rename to NONUNIFORM_GROWTH
/* The sequence is growing, but not each sweep. This end value of the sequence can take two
* (or more) different exit values. For at least one value, the sweep will change it into
* another exit value. For at least one other value, the sweep will change it in a non-exit
* value (i.e. it will extend the sweep body).
*/
IRREGULAR_GROWTH,
/* The sweep ends at a fixed position, with a constant value.
*
* Note: Value changes during a transition are ignored. Only the final value matters.
*/
FIXED_POINT_CONSTANT_VALUE,
/* The sweep ends at a fixed position, which can take multiple but a fixed number of values.
*/
FIXED_POINT_MULTIPLE_VALUES,
/* The sweep ends at a fixed position with an increasing value.
*/
FIXED_POINT_INCREASING_VALUE,
/* The sweep ends at a fixed position with a decreasing value.
*/
FIXED_POINT_DECREASING_VALUE,
/* The sweep ends in an "appendix" sequence. This appendix consists of two (or more)
* different exit values. These values can change each sweep, impacting where the sweep ends
* the next time. The appendix grows over time but this is aperiodic. Some kind of binary
* counting is realized, and the size of appendix grows logarithmitically. The side of the
* appendix that is attached to the body of the sweep has a fixed position.
*/
FIXED_APERIODIC_APPENDIX,
/* The sweep end type is unsupported (or to complex to be recognized by the current logic).
*/
UNSUPPORTED
};
std::ostream &operator<<(std::ostream &os, SweepEndType sweepEndType);
enum class SweepValueChangeType : int {
// The sweep loop does not change values
NO_CHANGE,
// Each value is changed by the same amount
UNIFORM_CHANGE,
// There are multiple changes, of different amounts, but all with the same sign
MULTIPLE_ALIGNED_CHANGES,
// There are multiple changes, of different amounts, and with different signs
MULTIPLE_OPPOSING_CHANGES,
};
class SweepLoopAnalysis : public LoopAnalysis {
friend std::ostream &operator<<(std::ostream&, const SweepLoopAnalysis&);
const RunBlock* _loopRunBlock;
SweepValueChangeType _sweepValueChangeType;
// Representative sweep value change:
// - NO_CHANGE: Value is zero
// - UNIFORM_CHANGE: All values in the sequence are changed by this amount
// - MULTIPLE_ALIGNED_CHANGES: This is one of the changes. Other changes have the same sign
// - MULTIPLE_OPPOSING_CHANGES: This is one of the changes (but its value is not useful for
// further analysis)
int _sweepValueChange;
std::set<int> _sweepValueChanges;
// Map from exit value to the instruction in the loop that can cause this exit. Only anytime
// exits are considered. Nevertheless, there may be more than one possible exit for a given
// value. This is the case when the loop moves more than one cell each iteration, i.e.
// abs(dataPointerDelta()) > 1.
std::multimap<int, int> _exitMap;
bool _requiresFixedInput;
int _requiredInput;
public:
const RunBlock* loopRunBlock() const { return _loopRunBlock; }
const bool movesRightwards() const { return dataPointerDelta() > 0; }
SweepValueChangeType sweepValueChangeType() const { return _sweepValueChangeType; }
int sweepValueChange() const { return _sweepValueChange; }
auto sweepValueChanges() const { return makeProxyIterator(_sweepValueChanges); }
bool isExitValue(int value) const;
int numberOfExitsForValue(int value) const;
void collectInsweepDeltasAfterExit(int exitInstruction, DataDeltas &dataDeltas) const;
// Returns iterator over exit values
auto exitValues() const { return makeKeyIterator(_exitMap); }
bool canSweepChangeValueTowardsZero(int value) const;
bool requiresFixedInput() const { return _requiresFixedInput; }
bool analyzeSweepLoop(const RunBlock* runBlock, const ExecutionState& execution);
};
std::ostream &operator<<(std::ostream &os, const SweepLoopAnalysis& sta);
class SweepTransitionAnalysis : public SequenceAnalysis {
public:
// The indexes are run block indices. The end index is exclusive.
bool analyzeSweepTransition(int startIndex, int endIndex, const ExecutionState& execution);
bool transitionEquals(int startIndex, int endIndex, const ExecutionState& execution) const;
void dump() const;
};
std::ostream &operator<<(std::ostream &os, const SweepTransitionAnalysis& sta);
struct SweepTransition {
const SweepTransitionAnalysis *transition;
int nextLoopStartIndex;
mutable int numOccurences;
SweepTransition() : transition(nullptr), nextLoopStartIndex(0), numOccurences(0) {}
SweepTransition(const SweepTransitionAnalysis *sta, int nextLoopStartIndex)
: transition(sta), nextLoopStartIndex(nextLoopStartIndex), numOccurences(1) {}
};
class SweepTransitionGroup;
class SweepEndTypeAnalysis {
protected:
const SweepTransitionGroup& _group;
int deltaAfterExit(const LoopExit& loopExit, const SweepTransition& trans) const;
void addInsweepDeltasAfterTransition(SweepTransition st, DataDeltas &dataDeltas) const;
void addInSweepDeltasForExit(std::set<int> &deltas, int exitInstruction) const;
// Determines all in-sweep deltas that can occur as part of a loop exit and adds them to the
// given set. This method considers the following changes:
// 1. Changes by the incoming loop. Due to the exit, these deltas can differ from the steady
// state deltas applied during the sweep.
// 2. Changes by the subsequent transition(s). These are applied on top of the deltas of the
// incoming loop.
// 3. Bootstrap only changes by the outgoing loop.
void collectExitRelatedInsweepDeltas(std::set<int> &deltas) const;
void collectSweepDeltas(std::set<int> &deltas) const;
bool valueCanBeChangedToExitByDeltas(int value, std::set<int> &deltas) const;
public:
SweepEndTypeAnalysis(const SweepTransitionGroup& group) : _group(group) {}
virtual SweepEndType determineSweepEndType() = 0;
};
class SweepEndTypeAnalysisZeroExits : SweepEndTypeAnalysis {
// Counts transitions where an exit value remains unchanged, or changes into another exit.
int _exitToExit;
// Counts transitions where an exit value is converted to a value that can never be converted
// into an exit. It considers sweep changes as well as any in-sweep deltas by transitions.
int _exitToSweepBody;
// Counts transitions where an exit value is converted to a value that is not an exit, but might
// be changed into one later. It might also be changed to a definite sweep body value, or always
// remain in limbo.
int _exitToLimbo;
int _limboToExitBySweep;
int _limboToExitByLoopExit;
int _limboToSweepBody;
bool _exitValueChanges;
bool analyseExits();
SweepEndType classifySweepEndType();
public:
SweepEndTypeAnalysisZeroExits(const SweepTransitionGroup& group)
: SweepEndTypeAnalysis(group) {};
SweepEndType determineSweepEndType() override;
};
class SweepEndTypeAnalysisNonZeroExits : SweepEndTypeAnalysis {
public:
SweepEndTypeAnalysisNonZeroExits(const SweepTransitionGroup& group)
: SweepEndTypeAnalysis(group) {};
SweepEndType determineSweepEndType() override;
};
class SweepTransitionGroup {
friend std::ostream &operator<<(std::ostream&, const SweepTransitionGroup&);
friend SweepEndTypeAnalysis;
friend SweepEndTypeAnalysisZeroExits;
friend SweepEndTypeAnalysisNonZeroExits;
// The loop that start this (group of) transition(s).
const SweepLoopAnalysis *_incomingLoop;
const SweepLoopAnalysis *_outgoingLoop;
// The mid-sweep transition of the outgoing sweep, if any.
const SweepTransitionAnalysis *_midSweepTransition;
// Map from a given loop exit to the transition(s) that follows it.
//
// Note: Most exits are followed by either no or one transition. However, it is possible that
// there is more than one, which can happen if the transition depends on nearby data values.
std::multimap<int, SweepTransition> _transitionMap;
SweepEndTypeAnalysisZeroExits _zeroExitEndTypeAnalysis;
SweepEndTypeAnalysisNonZeroExits _nonZeroExitEndTypeAnalysis;
SweepEndType _sweepEndType;
bool _locatedAtRight;
// Combined change made both by incoming and outgoing loop
SweepValueChangeType _sweepValueChangeType;
int _sweepValueChange;
DataDeltas _outsideDeltas;
// The direction of changes inside the sweep made by the transitions. It is only set when the
// sweep loops themselves do not make any combined change (as otherwise the latter is leading).
int _insideSweepTransitionDeltaSign;
bool determineCombinedSweepValueChange();
protected:
// The deltas of the sweep end-point after each sweep. Positive deltas means that the sequence
// grows. The sum of all deltas can only be zero (fixed point) or positive (growing sequence).
// However, individual deltas can be negative.
std::vector<int> _sweepExitDeltas;
// Indicates if the hang is locked into a periodic behavior at the meta-run level. Not only
// should the sequence of meta run-blocks be periodic, also the length of the run-block loops
// that do not have a fixed length (i.e. the sweep loops) should increase with a fixed number
// of iterations each period. When this is the case, the checks on the changes made by the
// loops and transition sequences associated with this transition group can be a bit more
// lenient.
virtual bool hangIsMetaPeriodic() { return false; }
void setEndType(SweepEndType endType) {
assert(!didDetermineEndType());
_sweepEndType = endType;
}
int numberOfExitsForValue(int value) const;
int numberOfTransitionsForExitValue(int value) const;
virtual bool determineZeroExitSweepEndType();
virtual bool determineNonZeroExitSweepEndType();
virtual bool determineSweepEndType();
virtual bool onlyZeroesAhead(DataPointer dp, const Data& data) const;
public:
SweepTransitionGroup();
void addExitDelta(int delta) { _sweepExitDeltas.push_back(delta); }
bool locatedAtRight() const { return _locatedAtRight; }
SweepEndType endType() const { return _sweepEndType; }
bool didDetermineEndType() { return (_sweepEndType != SweepEndType::UNKNOWN &&
_sweepEndType != SweepEndType::UNSUPPORTED); }
const DataDeltas& outsideDeltas() const { return _outsideDeltas; }
int insideSweepTransitionDeltaSign() const { return _insideSweepTransitionDeltaSign; }
bool isSweepGrowing() const;
bool isSweepGrowthConstant() const;
const SweepLoopAnalysis* incomingLoop() const { return _incomingLoop; }
const SweepLoopAnalysis* outgoingLoop() const { return _outgoingLoop; }
void setIncomingLoop(const SweepLoopAnalysis* loop) { _incomingLoop = loop; }
void setOutgoingLoop(const SweepLoopAnalysis* loop) { _outgoingLoop = loop; }
const SweepTransitionAnalysis* midSweepTransition() const { return _midSweepTransition; }
void setMidSweepTransition(const SweepTransitionAnalysis* sta) { _midSweepTransition = sta; }
// The combined change to the sequence made by both the sweep-loops
SweepValueChangeType combinedSweepValueChangeType() const { return _sweepValueChangeType; }
int combinedSweepValueChange() const { return _sweepValueChange; }
bool canSweepChangeValueTowardsZero(int value) const;
bool hasTransitionForExit(int exitIndex) const {
return _transitionMap.find(exitIndex) != _transitionMap.end();
}
const SweepTransition* addTransitionForExit(int exitIndex, SweepTransition st) {
return &(_transitionMap.insert({exitIndex, st})->second);
}
const SweepTransition* findTransitionMatching(int exitInstruction,
int transitionStartIndex,
int transitionEndIndex,
const ExecutionState& execution) const;
bool hasUniqueTransitions() const;
virtual void clear();
bool analyzeSweeps();
bool analyzeGroup();
bool allOutsideDeltasMoveAwayFromZero(DataPointer dp, const Data& data) const;
Trilian proofHang(DataPointer dp, const Data& data);
std::ostream& dumpExitDeltas(std::ostream &os) const;
virtual std::ostream& dump(std::ostream &os) const;
};
std::ostream &operator<<(std::ostream &os, const SweepTransitionGroup &group);
#endif /* SweepTransitionGroup_h */
| true |
031d4885339c7bd18c06116448d0acfaf34feae7 | C++ | Pankajadhana97-bit/COMPETITIVE_CODING | /Mirzapur_Election.cpp | UTF-8 | 1,991 | 2.8125 | 3 | [] | no_license | #include<bits/stdc++.h>
/*
Pankaj Adhana
Panjab university;
*/
/* Defined values---------------------------------------------------- */
#define fast_io ios_base::sync_with_stdio(false);cin.tie(NULL)
#define cases int t=1;cin>>t; while(t--) { solve();} return 0
#define ll int64_t
/*--------------------------------------------------------------------*/
using namespace std;
int findMaxGCD(int arr[], int n)
{
// Calculating MAX in array
int high = 0;
for (int i = 0; i < n; i++)
high = max(high, arr[i]);
// Maintaining count array
int count[high + 1] = {0};
for (int i = 0; i < n; i++)
count[arr[i]]++;
// Variable to store the
// multiples of a number
int counter = 0;
// Iterating from MAX to 1
// GCD is always between
// MAX and 1. The first
// GCD found will be the
// highest as we are
// decrementing the potential
// GCD
for (int i = high; i >= 1; i--)
{
int j = i;
counter = 0;
// Iterating from current
// potential GCD
// till it is less than
// MAX
while (j <= high)
{
// A multiple found
if(count[j] >=2)
return j;
else if (count[j] == 1)
counter++;
// Incrementing potential
// GCD by itself
// To check i, 2i, 3i....
j += i;
// 2 multiples found,
// max GCD found
if (counter == 2)
return i;
}
}
}
void solve()
{
int n,d;
cin>>n>>d;
int arr[n];
for(int i=0;i<n;i++)cin>>arr[i];
while(d--)
{
int num;
cin>>num;
if(num==1)
{
int x,y;
cin>>x>>y;
arr[x]=y;
}
if(num==2)
{
cout<<findMaxGCD(arr, n)<<endl;
}
}
}
int main()
{
fast_io;
cases;
} | true |
84b489d7c81642ee98d8b0ebb526f13353a44cfa | C++ | DarkCaster/ArduinoOTP | /Firmware/OTPManagerFirmware/eeprom_profile_manager.h | UTF-8 | 1,418 | 2.6875 | 3 | [
"MIT"
] | permissive | #ifndef EEPROM_PROFILE_MANAGER_H
#define EEPROM_PROFILE_MANAGER_H
#include <Arduino.h>
#include "profile_manager.h"
#include "cipher.h"
class EEPROMProfileManager final : public ProfileManager
{
private:
const uint8_t * const key;
const uint8_t * const tweak;
const size_t keySz;
const size_t tweakSz;
const int baseAddr;
const int addrLimit;
const uint16_t profileHdrSz;
const uint16_t profileFullSz;
Cipher &cipher;
EEPROMProfileManager(const int baseAddr, const int maxLen, Cipher &cipher, const uint8_t * const key, const uint8_t * const tweak, const size_t KSZ, const size_t TSZ);
public:
template<size_t KSZ, size_t TSZ> EEPROMProfileManager(const int baseAddr, const int maxLen, Cipher &cipher, const uint8_t (&enc_key)[KSZ], uint8_t const (&enc_tweak)[TSZ]) :
EEPROMProfileManager(baseAddr,maxLen,cipher, enc_key, enc_tweak, KSZ, TSZ) { }
template<size_t KSZ, size_t TSZ> EEPROMProfileManager(const int baseAddr, const int maxLen, Cipher &&, const uint8_t (&&)[KSZ], uint8_t const (&&)[TSZ]) = delete;
uint16_t GetProfilesCount() final;
uint16_t GetProfileDataSize() final;
Profile ReadProfileHeader(uint16_t index) final;
bool ReadProfileData(uint16_t index, uint8_t * const data) final;
bool WriteProfile(uint16_t index, const Profile &profile, const uint8_t * const data) final;
bool WriteProfileData(uint16_t index, const uint8_t * const data) final;
};
#endif
| true |
8694f184af93dffd87321046fbe01511016fdf10 | C++ | cross4yu/code4leetcode | /p19_remove_nth_node_from_end_of_list.cpp | UTF-8 | 793 | 3.359375 | 3 | [] | no_license | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n)
{
int k = n;
ListNode prehead(-1);
prehead.next = head;
ListNode* pNode = &prehead;
while (k > 0)
{
pNode = pNode->next;
--k;
if (pNode == NULL) return NULL;
}
ListNode *runNode = &prehead;
while (pNode->next != NULL)
{
runNode = runNode->next;
pNode = pNode->next;
}
ListNode* temp = runNode->next;
runNode->next = temp->next;
delete temp;
reutrn prehead.next;
}
};
| true |
8d377a83e520adfbb5445443b5a1610088e8e017 | C++ | motsuSiRO/Deseld | /GameSource/SceneManager.cpp | SHIFT_JIS | 872 | 2.65625 | 3 | [] | no_license | #include "Scene.h"
void SceneManager::Update(float elapsedTime)
{
current_scene->Update(elapsedTime);
}
void SceneManager::Render()
{
current_scene->Render();
}
void SceneManager::ChangeScene(Scene* new_scene)
{
//currentScene.reset(new_scene);
//currentScene->Initialize();
previous_scene.reset(current_scene.release());
current_scene.reset(new_scene);
// 2dȂ悤ɂB
if (!current_scene->initialized)
{
current_scene->Initialize();
current_scene->initialized = true;
}
}
//void SceneManager::ChangeScene(Scene* new_scene, int load_list)
//{
// previous_scene.reset(current_scene.release());
//
// current_scene.reset(new_scene, load_list);
// // 2dȂ悤ɂB
// if (!current_scene->initialized)
// {
// current_scene->Initialize();
// current_scene->initialized = true;
// }
//
//}
| true |
a5bc9171eb1253ee5f239d7a701438ccc67e046d | C++ | seemantaggarwal/CODEFORALL | /ALGOS in C++/TREES/largestbstinbt.cpp | UTF-8 | 3,944 | 3.4375 | 3 | [] | no_license | #include <iostream>
using namespace std;
class node
{
public:
int data;
node *left;
node *right;
node(int d)
{
data=d;
right=NULL;
left=NULL;
}
};
node *buildtree()
{
int data;
cin>>data;
if(data==-1)
{
return NULL;
}
node *root = new node(data);
root->left=buildtree();
root->right=buildtree();
return root;
}
int largestBSTUtil(node* node, int *min_ref, int *max_ref,
int *max_size_ref, bool *is_bst_ref);
/* Returns size of the largest BST
subtree in a Binary Tree
(efficient version). */
int largestBST(node* node)
{
// Set the initial values for
// calling largestBSTUtil()
int min = INT_MAX; // For minimum value in right subtree
int max = INT_MIN; // For maximum value in left subtree
int max_size = 0; // For size of the largest BST
bool is_bst = 0;
largestBSTUtil(node, &min, &max,
&max_size, &is_bst);
return max_size;
}
/* largestBSTUtil() updates *max_size_ref
for the size of the largest BST subtree.
Also, if the tree rooted with node is
non-empty and a BST, then returns size
of the tree. Otherwise returns 0.*/
int largestBSTUtil(node* node, int *min_ref, int *max_ref,
int *max_size_ref, bool *is_bst_ref)
{
/* Base Case */
if (node == NULL)
{
*is_bst_ref = 1; // An empty tree is BST
return 0; // Size of the BST is 0
}
int min = INT_MAX;
/* A flag variable for left subtree property
i.e., max(root->left) < root->data */
bool left_flag = false;
/* A flag variable for right subtree property
i.e., min(root->right) > root->data */
bool right_flag = false;
int ls, rs; // To store sizes of left and right subtrees
/* Following tasks are done by
recursive call for left subtree
a) Get the maximum value in left
subtree (Stored in *max_ref)
b) Check whether Left Subtree is
BST or not (Stored in *is_bst_ref)
c) Get the size of maximum size BST
in left subtree (updates *max_size) */
*max_ref = INT_MIN;
ls = largestBSTUtil(node->left, min_ref, max_ref,
max_size_ref, is_bst_ref);
if (*is_bst_ref == 1 && node->data > *max_ref)
left_flag = true;
/* Before updating *min_ref, store the min
value in left subtree. So that we have the
correct minimum value for this subtree */
min = *min_ref;
/* The following recursive call
does similar (similar to left subtree)
task for right subtree */
*min_ref = INT_MAX;
rs = largestBSTUtil(node->right, min_ref,
max_ref, max_size_ref, is_bst_ref);
if (*is_bst_ref == 1 && node->data < *min_ref)
right_flag = true;
// Update min and max values for
// the parent recursive calls
if (min < *min_ref)
*min_ref = min;
if (node->data < *min_ref) // For leaf nodes
*min_ref = node->data;
if (node->data > *max_ref)
*max_ref = node->data;
/* If both left and right subtrees are BST.
And left and right subtree properties hold
for this node, then this tree is BST.
So return the size of this tree */
if(left_flag && right_flag)
{
if (ls + rs + 1 > *max_size_ref)
*max_size_ref = ls + rs + 1;
return ls + rs + 1;
}
else
{
// Since this subtree is not BST,
// set is_bst flag for parent calls
*is_bst_ref = 0;
return 0;
}
}
int main(int argc, char const *argv[])
{
/* code */
node *root=buildtree();
return 0;
}
| true |
52757585beded717be0e085927520c384e697a2f | C++ | Aman-Arcanion9/CP-for-interview-preparation | /GFG - Swap every two bits in bytes.cpp | UTF-8 | 571 | 2.609375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin>>t;
while(t--){
int n;
cin>>n;
vector<int> bits;
while(n>0){
bits.push_back(n%2);
n = n/2;
}
int sz = bits.size();
if(sz%2)
bits.push_back(0);
for(int i=0 ; i<bits.size()-1 ; i+=2)
swap(bits[i],bits[i+1]);
int ans = 0;
for(int i=0 ; i<bits.size() ; i++){
if(bits[i])
ans += pow(2,i);
}
cout<<ans<<"\n";
}
}
| true |
4b4c39283fec3d0707eba60c92ac31afdd77cf5e | C++ | mandalsudipti/competitive_programming | /HackerRank/Sherlock and Subarray.cpp | UTF-8 | 1,684 | 2.84375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
#define SIZE 2*200003
struct node
{
int maximum , freq ;
node(){}
node (int a , int b)
{
maximum=a;
freq=b;
}
};
node tree[SIZE];
int arr[100000];
node merge(node &lc , node &rc)
{
node tmp;
if(lc.maximum==rc.maximum)
{
tmp.maximum=lc.maximum;
tmp.freq=lc.freq + rc.freq;
}
else if (lc.maximum>rc.maximum)
{
tmp.maximum=lc.maximum;
tmp.freq=lc.freq;
}
else
{
tmp.maximum=rc.maximum;
tmp.freq=rc.freq;
}
return tmp;
}
void build_tree(int idx , int left , int right)
{
if(left==right)
{
tree[idx]=node(arr[left],1);
//cout<<"leaf node->"<<idx<<endl;
return;
}
int mid = (left+right)/2;
build_tree(2*idx,left,mid);
build_tree(2*idx+1,mid+1,right);
tree[idx]=merge(tree[2*idx],tree[2*idx+1]);
}
node query(int idx , int left , int right , int q_left , int q_right)
{
if(right<q_left || left>q_right|| right<left)
{
return node(-1,-1);
}
if(q_left<=left && q_right>=right)
{
return tree[idx];
}
int mid =(left+right)/2;
node l_ans = query(2*idx,left,mid,q_left,q_right);
node r_ans =query(2*idx+1,mid+1,right,q_left,q_right);
return merge(l_ans,r_ans);
}
int main()
{
int n,m,i;
cin>>n>>m;
for(i=1;i<=n;i++)
cin>>arr[i];
build_tree(1,1,n);
//for(i=1;i<=15;i++)
//cout<<i<<"-> "<<tree[i].maximum<<" "<<tree[i].freq<<endl;
while(m--)
{
int l,r;
cin>>l>>r;
node ans = query(1,1,n,l,r);
cout<<ans.freq<<endl;
}
return 0;
}
| true |
58b602a8650760885c06ef72688ea1aae071d54f | C++ | mssalvatore/EN605.417.FA | /roulette/analytics.cpp | UTF-8 | 1,651 | 3.515625 | 4 | [] | no_license | #include "analytics.h"
#include <iostream>
template <class T>
void printArray(T * data, size_t size)
{
for (int i = 0; i < size; i++)
{
std::cout<<data[i] << " ";
}
std::cout<<std::endl;
}
template <class T>
double calculateMean(T * data, size_t size)
{
double total = 0;
for (int i = 0; i < size; i++)
{
total += (((double)data[i]) / size);
}
return total;
}
template <class T>
T calculateMax(T * data, size_t size)
{
T max = INT_MIN;
for (int i = 0; i < size; i++)
{
if (data[i] > max)
{
max = data[i];
}
}
return max;
}
template <class T>
T calculateMin(T * data, size_t size)
{
T min = INT_MAX;
for (int i = 0; i < size; i++)
{
if (data[i] < min)
{
min = data[i];
}
}
return min;
}
void runAnalytics(int * purse, int * maxPurse, int * minPurse, int64_t * integral, size_t size)
{
std::cout<<"Avg Purse: " << calculateMean(purse, size) << std::endl;
std::cout<<"Max Purse: " << calculateMax(purse, size) << std::endl;
std::cout<<"Min Purse: " << calculateMin(purse, size) << std::endl;
std::cout<<std::endl;
std::cout<<"Max Max Purse: " << calculateMax(maxPurse, size) <<std::endl;
std::cout<<"Min Min Purse: " << calculateMin(minPurse, size) <<std::endl;
std::cout<<std::endl;
std::cout<<"Avg Integral: " << calculateMean(integral, size) << std::endl;
std::cout<<"Max Integral: " << calculateMax(integral, size) << std::endl;
std::cout<<"Min Integral: " << calculateMin(integral, size) << std::endl;
std::cout<<std::endl;
}
| true |
5552594ebcdb4e27c8516a82abc133e45f8a21e5 | C++ | TheTastyGravy/AIProject | /Project/AI-Game/Swarmer.cpp | UTF-8 | 1,600 | 2.921875 | 3 | [
"MIT"
] | permissive | #include "Swarmer.h"
#include "Leader.h"
#include "raylib.h"
#include "FormationStateBehav.h"
Swarmer::Swarmer(const Vector2& position, const std::shared_ptr<Behaviour> flockingState, const int health) :
Agent(position, 200.0f),
importance(0.0f),
leader(nullptr),
health(health),
maxHealth(health),
flocking(flockingState)
{
addTag(Tag::Swarmer);
}
Swarmer::~Swarmer()
{
}
void Swarmer::draw()
{
// Draw swarmers as black dots that hollow on taking damage
DrawRing(position, 2.0f*(1.0f - (float)health/maxHealth), 2.5f, 0, 360, 0, BLACK);
}
void Swarmer::enterFlocking(const float& importance, Leader* leader)
{
// Update importance and leader, and join its swarm
this->importance = importance;
this->leader = leader;
leader->joinSwarm(this);
// Remove any current behaviours and set current to flocking
behaviours.clear();
addBehaviour(flocking);
}
void Swarmer::enterFormation(const float& importance, Agent* leaderObj, const Vector2& offset)
{
// A swarmer cant enter formation unless it has a ref to a leader
if (leader == nullptr)
return;
// Update importacne
this->importance = importance;
// Remove any current behaviours
behaviours.clear();
// Add a new formation state to be the current behaviour
addBehaviour(std::make_shared<FormationStateBehav>(leaderObj, offset));
}
void Swarmer::dealDamage(const int damage)
{
health -= damage;
// If health is at 0, kill the swarmer
if (health <= 0)
{
// If this has a leader, remove this from it's swarm
if (leader != nullptr)
leader->leaveSwarm(this);
// Delete this swarmer
delete this;
}
} | true |
e52c5e51ce4ee741c33d259332c0d034ffc37105 | C++ | mhigg/3DAirHockey | /AirHockey/Classes/Obj/BallAfter.cpp | SHIFT_JIS | 2,122 | 2.5625 | 3 | [] | no_license | #include "BallAfter.h"
USING_NS_CC;
BallAfter::BallAfter() : _invTime(10)
{
Init();
}
BallAfter::BallAfter(const cocos2d::Vec3 & lPos) : _invTime(10)
{
_localPos = lPos;
Init();
}
BallAfter::~BallAfter()
{
}
void BallAfter::Update(const cocos2d::Vec3 & lPos)
{
if ((_cnt / _invTime) % 2)
{
/// 3W̍XV
for (int i = _images.size() - 2; i >= 0; --i)
{
_points[i + 1] = _points[i];
}
_cnt = 0;
_points[0] = lPos;
/// XVWgāAc̈ʒuƃTCYXV
for (int i = 0; i < _images.size(); ++i)
{
///// ʒû߂ɁAʃTCY̔ZĂ
_images[i]->setPosition(lpPointWithDepth.SetWorldPosition(_points[i]) - cocos2d::Vec2(1024 / 2, 576 / 2));
_images[i]->setScale(lpPointWithDepth.GetScale(_points[i].z));
}
}
// Ԃ̍XV
++_cnt;
}
void BallAfter::ResetPosition()
{
float rate;
_localPos = { 0,0,0 };
for (int i = 0; i < _images.size(); ++i)
{
/// 摜TCY̔{vZĂ
rate = (float)(_images.size() - i) / (_images.size());
/// 摜x̐ݒ
_images[i]->setOpacity(75 * rate);
_points[i] = _localPos;
/// W̐ݒ
setPosition(lpPointWithDepth.SetWorldPosition(_localPos));
/// 摜XP[̐ݒ
setScale(lpPointWithDepth.GetScale(_localPos.z));
}
}
void BallAfter::Init()
{
// vZ摜̔{ۑ
float rate;
for (int i = 0; i < _images.size(); ++i)
{
/// 摜TCY̔{vZĂ
rate = (float)(_images.size() - i) / (_images.size());
/// 摜̎擾
_images[i] = Sprite::create("image/ball/afterImage.png");
/// 摜TCY̐ݒ
_images[i]->setContentSize(_images[i]->getContentSize());
/// 摜x̐ݒ
_images[i]->setOpacity(75 * rate);
/// W̐ݒ
setPosition(lpPointWithDepth.SetWorldPosition(_localPos));
/// 摜XP[̐ݒ
setScale(lpPointWithDepth.GetScale(_localPos.z));
this->addChild(_images[i]);
}
}
void BallAfter::update(float dt)
{
}
| true |
f2486cdb904c80265cb6b5a0a8f4e5d9b6f4e0be | C++ | nikhita-n/CP | /Practice/Sliding_window_minimum_2D_array.cpp | UTF-8 | 350 | 2.828125 | 3 | [] | no_license | /* A 2D array with NxN dimensions given a window of WxW dimension, find the minimum in all possible windows"
Optimized soln by me - O((N-W+1)*N*W)
Check this for O(N) soln
https://jimmy-shen.medium.com/2d-sliding-window-min-max-problem-e24b0c707a62
Sliding window in general
https://people.cs.uct.ac.za/~ksmith/articles/sliding_window_minimum.html
| true |
8169e857bdf98a49cf7bcff5a576540881347a46 | C++ | StonecutterX/DataStructureAndAlgorithm | /LeetCode/P892_surface_of_3d_shape.cc | UTF-8 | 1,363 | 3.1875 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int surfaceArea(vector<vector<int>>& grid) {
if (0 == grid.size()) {
return 0;
}
int row = static_cast<int>(grid.size());
int col = static_cast<int>(grid[0].size());
int cnt = 0;
// 定义四个方向
vector<int> dr{0, 1, 0, -1};
vector<int> dc{1, 0, -1, 0};
// 做减法
for (int r = 0; r < row; ++r)
for (int c = 0; c < col; ++c) {
int value = grid[r][c];
if (value != 0) {
cnt += (value * 6 - 2 * (value - 1));
}
int neighbour_min = 0;
for (int k = 0; k < 4; ++k) {
int nr = r + dr[k];
int nc = c + dc[k];
if (0 <= nr && nr < row && 0 <= nc && nc < col) {
neighbour_min = std::min(value, grid[nr][nc]);
cnt -= neighbour_min;
}
}
}
return cnt;
}
};
int main(int argc, char* argv[]) {
// vector<vector<int>> grid{{2}};
vector<vector<int>> grid{{1, 2}, {3, 4}};
Solution sln;
auto res = sln.surfaceArea(grid);
std::cout << "res = " << res << std::endl;
return 0;
} | true |
6a99de23d7453139915c2a57ae600e68c8e71e6c | C++ | Neverous/codeforces | /176/a.cpp | UTF-8 | 655 | 3.1875 | 3 | [] | no_license | /* 2013
* Maciej Szeptuch
* II UWr
*/
#include <cstdio>
char row[4][8];
int white, black;
int main(void)
{
for(int h = 0; h < 4; ++ h)
scanf("%s", row[h]);
for(int h = 0; h < 3; ++ h)
for(int w = 0; w < 3; ++ w)
{
white = black = 0;
for(int i = 0; i < 2; ++ i)
for(int j = 0; j < 2; ++ j)
if(row[h + i][w + j] == '#')
++ black;
else
++ white;
if(white != 2)
{
puts("YES");
return 0;
}
}
puts("NO");
return 0;
}
| true |
d73230b0c764541601884cbbd70dd02f4f8fc774 | C++ | kopecdav/CircleCi | /_libs_/libraries/RGB_matrix.cpp | UTF-8 | 5,595 | 2.65625 | 3 | [] | no_license | #include "RGB_matrix.h"
DigitalOut* RGB_matrix::CLK;
BusOut* RGB_matrix::ABCD; // Row address.
DigitalOut* RGB_matrix::LAT; // Data latch - active low (pulse up after data load)
DigitalOut* RGB_matrix::OE; // Output enable - active low (hold high during data load, bring low after LAT pulse)
DigitalOut* RGB_matrix::R1; // RED Serial in for upper half
DigitalOut* RGB_matrix::R2; // RED Serial in for lower half
DigitalOut* RGB_matrix::G1; // GREEN Serial in for upper half
DigitalOut* RGB_matrix::G2; // GREEN Serial in for lower half
DigitalOut* RGB_matrix::B1; // BLUE Serial in for upper half
DigitalOut* RGB_matrix::B2; // BLUE Serial in for lower half
Ticker* RGB_matrix::painter = NULL;
uint16_t RGB_matrix::row_cnt;
uint16_t RGB_matrix::gm[128][6]; // Buffer with 64*number_of_linesx6 bytes. Graphics memory if you like.
char RGB_matrix::_background;
char RGB_matrix::_color;
/**
* Inicializuje knihovnu RGB_matrix a fyzické piny desky. Zároveň zapne ticker, který sekvenčně vykresluje řádky displeje
*
*/
void RGB_matrix::Init(PinName Pin_R1, PinName Pin_R2,PinName Pin_G1 ,PinName Pin_G2, PinName Pin_B1,PinName Pin_B2,
PinName Pin_CLK,PinName Pin_LAT, PinName Pin_OE, PinName Pin_A,PinName Pin_B,PinName Pin_C,PinName Pin_D) {
R1 = new DigitalOut(Pin_R1);
R2 = new DigitalOut(Pin_R2);
G1 = new DigitalOut(Pin_G1);
G2 = new DigitalOut(Pin_G2);
B1 = new DigitalOut(Pin_B1);
B2 = new DigitalOut(Pin_B2);
CLK = new DigitalOut(Pin_CLK);
LAT = new DigitalOut(Pin_LAT);
ABCD = new BusOut(Pin_A,Pin_B,Pin_C,Pin_D);
OE = new DigitalOut(Pin_OE);
//attach ticker
painter = new Ticker();
painter->attach(&paint, 0.001);
row_cnt = 0;
_color = RED;
_background = 0;
}
void RGB_matrix::detach_ticker(){
//painter.attach(&paint, 1000);
if(painter != NULL){
delete(painter);
painter = NULL;
}
//painter.detach();
}
void RGB_matrix::attach_ticker(){
/*
if(&painter){
painter.attach(&paint, 0.001);
}
*/
if(painter == NULL){
painter = new Ticker();
painter->attach(&paint, 0.001);
}
}
void RGB_matrix::set_background(char color){
_background = color;
}
void RGB_matrix::set_color(char color){
_color = color;
}
void RGB_matrix::set_pixel(uint16_t x ,uint16_t y, uint16_t c){
// Handle graphix memory, so calling this method wont change
// Display boundries
if ((x > 127) || (y > 31)){
return;
}
uint16_t r0,g0,b0;
r0=(c & 4) >>2; // Extract red bit from color
g0=(c & 2) >>1; // Extract green bit from color
b0=(c & 1); // Extract blue bit from color
// Handle second half of display
if (y > 15){
gm[x][3] = (gm[x][3] & ~(1<<(15-(y-16))));
gm[x][4] = (gm[x][4] & ~(1<<(15-(y-16))));
gm[x][5] = (gm[x][5] & ~(1<<(15-(y-16))));
gm[x][3] = (gm[x][3] | (r0<<(15-(y-16))));
gm[x][4] = (gm[x][4] | (g0<<(15-(y-16))));
gm[x][5] = (gm[x][5] | (b0<<(15-(y-16))));
}else{
gm[x][0] = (gm[x][0] & ~(1<<(15-y)));
gm[x][1] = (gm[x][1] & ~(1<<(15-y)));
gm[x][2] = (gm[x][2] & ~(1<<(15-y)));
gm[x][0] = (gm[x][0] | (r0<<(15-y)));
gm[x][1] = (gm[x][1] | (g0<<(15-y)));
gm[x][2] = (gm[x][2] | (b0<<(15-y)));
}
}
void RGB_matrix::paint()
{
// Write graphics memory to display
*OE = 1; // Disable output
write_row(row_cnt);
*OE = 0; // Enable output
row_cnt++;
if (row_cnt > 15){
row_cnt = 0;
}
}
void RGB_matrix::paint_all()
{
// Write graphics memory to display
for(uint16_t i=0; i<16; i++){
*OE = 1; // Disable output
write_row(i);
*OE = 0; // Enable output
wait_us(40);
}
*OE=1;
}
char RGB_matrix::put_char(int x,int y, char c){
// Define character library offsets
int offset = 3;
int width_offset = 1;
int width = (int) HD44780_6x8[offset + width_offset + (7*(c - 0x20))];
char col;
for (int i = 0; i <= width; i++){
// Chose a character in libray
col = HD44780_6x8[(offset + width_offset + (7*(c - 0x20))) + i + 1];
// Set pixels
for (int j = 0; j < 8; j++){
if((col & 1<<j) > 0){
set_pixel(x+i,y + j,_color);
}else{
set_pixel(x+i,y + j,_background);
}
}
}
return width+1;
}
void RGB_matrix::put_line(char* str, int line_number){
int len = std::strlen(str);
int char_offset = 0;
for(int i = 0; i < len; i++){
char_offset += put_char(char_offset,(line_number-1)*8,str[i]);
}
}
void RGB_matrix::put_row(char* str,uint16_t mins, int line_number){
for(int i = 0; i<128; i++){
for(int j = 0; j<8; j++)
set_pixel(i,j+(line_number-1)*8,NONE);
}
int len = std::strlen(str);
int char_offset = 0;
//set_color(WHITE);
for(int i = 0; i < len; i++){
char_offset += put_char(char_offset,(line_number-1)*8,str[i]);
}
char_offset=128-6;
char buffer[50];
len = sprintf(buffer,"%dmin",mins);
int i=0;
//set_color(PINK);
while(i<len){
i++;
char_offset -= put_char(char_offset,(line_number-1)*8,buffer[len-i]);
}
}
void RGB_matrix::write_row(uint16_t Row)
{
// Write specified row (and row+8) to display. Valid input: 0 to 15.
*ABCD=15-Row; // Set row address
for(int col=0; col<128; col++) {
*R1 = gm[col][0] & (1<<Row); // Red bit, upper half
*G1 = gm[col][1] & (1<<Row); // Green bit, upper half
*B1 = gm[col][2] & (1<<Row); // Blue bit, upper half
*R2 = gm[col][3] & (1<<Row); // Red bit, lower half
*G2 = gm[col][4] & (1<<Row); // Green bit, lower half
*B2 = gm[col][5] & (1<<Row); // Blue bit, lower half
*CLK = 1; // Clock with CLK pin
*CLK = 0;
}
*LAT = 1; // Latch entire row to output
*LAT = 0;
}
| true |