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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
02bf41a01870787d9a3e22b7d719fe07e14ee55e | C++ | amauryESGI/4A_COLMANT_LOQUET_BATTLE_IA | /BattleIA_V2/BattleIA_V2/BattleIA_V2/Util.hpp | UTF-8 | 240 | 2.71875 | 3 | [] | no_license | #ifndef __UTIL_HPP__
#define __UTIL_HPP__
#include <algorithm>
class Util
{
public:
static float width;
static float heigth;
static float clip(float n, float limit)
{
return std::max(0.f, std::min(n, limit));
}
};
#endif | true |
5660cefa29d5acab85ffc62a160d63ca58159fc4 | C++ | vvvictorlee/eossmartcontractssafeframeworks | /contractscxx/crowdsale/distribution/PostDeliveryCrowdsale.hpp | UTF-8 | 1,188 | 2.796875 | 3 | [] | no_license | //
#include "../validation/TimedCrowdsale.hpp"
#include "../../token/ERC20/ERC20.hpp"
#include "../../math/SafeMath.hpp"
/**
* @title PostDeliveryCrowdsale
* @dev Crowdsale that locks tokens from withdrawal until it ends.
*/
class PostDeliveryCrowdsale : TimedCrowdsale {
// using SafeMath for uint256_t;
// mapping(account_name => uint256_t) public balances;
struct balance
{
account_name name;
uint64_t balance;
uint64_t primary_key() const { return name; }
};
typedef eosio::multi_index<N(balances), balance> balances;
/**
* @dev Withdraw tokens only after crowdsale ends.
*/
void withdrawTokens() {
eosio_assert(hasClosed());
uint256_t amount = balances[_self];
eosio_assert(amount > 0);
balances[_self] = 0;
_deliverTokens(_self, amount);
}
/**
* @dev Overrides parent by storing balances instead of issuing tokens right away.
* @param _beneficiary Token purchaser
* @param _tokenAmount Amount of tokens purchased
*/
void _processPurchase(
account_name _beneficiary,
uint256_t _tokenAmount
)
// internal
{
balances[_beneficiary] = balances[_beneficiary].add(_tokenAmount);
}
}
| true |
545a07bd9f06dca924125a08ee3996aae123b85c | C++ | trevinwong/space_pearates | /src/DataLoaders/player_data_loader.cpp | UTF-8 | 1,052 | 2.53125 | 3 | [] | no_license | #include "player_data_loader.hpp"
PlayerData PlayerDataLoader::playerData;
void PlayerDataLoader::loadPlayerData()
{
std::ifstream ifs(player_path("player_data.txt"));
checkValidFilename(ifs, player_path("player_data.txt"));
float sizeX, sizeY;
float maxVelocityX, maxVelocityY;
float maxAccelX, maxAccelY;
float health;
int maxJumps;
float jumpVelocity;
fillVariable(ifs, sizeX, "sizeX");
fillVariable(ifs, sizeY, "sizeY");
moveToNextLine(ifs);
fillVariable(ifs, maxVelocityX, "maxVelocityX");
fillVariable(ifs, maxVelocityY, "maxVelocityY");
moveToNextLine(ifs);
fillVariable(ifs, maxAccelX, "maxAccelX");
fillVariable(ifs, maxAccelY, "maxAccelY");
moveToNextLine(ifs);
fillVariable(ifs, health, "health");
moveToNextLine(ifs);
fillVariable(ifs, maxJumps, "maxJumps");
moveToNextLine(ifs);
fillVariable(ifs, jumpVelocity, "jumpVelocity");
ifs.close();
playerData = PlayerData(vec2(sizeX, sizeY), vec2(maxVelocityX, maxVelocityY), vec2(maxAccelX, maxAccelY), health, maxJumps, jumpVelocity);
}
| true |
c86c0f083fd2cf9842a486dcb2beeefa8683e761 | C++ | pkufahl/sample | /SimpleString.cpp | UTF-8 | 4,760 | 3.375 | 3 | [] | no_license | //
// Created by Peter Kufahl on 8/21/15.
//
#include "SimpleString.h"
#include <algorithm>
std::pair<char *, char *> SimpleString::allocate_and_copy(const char *first, const char *last) {
auto str = _alloc.allocate(last - first);
return { str, std::uninitialized_copy(first, last, str) };
}
void SimpleString::range_initializer(const char *first, const char *last) {
auto newStr = allocate_and_copy(first, last);
_first_element = newStr.first;
_first_free = _capacity = newStr.second;
_last_element = _first_free - 1;
}
SimpleString::SimpleString(const char *str) {
// main ctor
char *c = const_cast<char*>(str);
while (*c)
++c;
range_initializer(str, ++c);
}
SimpleString::SimpleString(const SimpleString &rhs) {
// copy ctor
// range_initializer(rhs._elements, rhs._end);
range_initializer(rhs._first_element, rhs._first_free);
std::cout << "copy constructor" << std::endl;
}
void SimpleString::free() {
// std::cout << "free() called ... ";
if (_first_element)
{
// std::cout << *_first_element << " ... ";
std::for_each(_first_element, _first_free, [this](char &c){ _alloc.destroy(&c); });
_alloc.deallocate(_first_element, _capacity - _first_element);
}
// std::cout << "successful" << std::endl;
}
SimpleString &SimpleString::operator=(const SimpleString &rhs) {
// copy assignment
auto newstr = allocate_and_copy(rhs._first_element, rhs._first_free);
free();
_first_element = newstr.first;
_first_free = _capacity = newstr.second;
_last_element = _first_free - 1;
std::cout << "copy assignment" << std::endl;
return *this;
}
SimpleString::SimpleString(SimpleString &&str) noexcept
: _first_element(str._first_element),
_last_element(str._last_element),
_first_free(str._first_free),
_capacity(str._capacity)
{
// move ctor
str._first_element = str._last_element = str._first_free = str._capacity = nullptr;
std::cout << "move constructor" << std::endl;
}
SimpleString &SimpleString::operator=(SimpleString &&rhs) noexcept
{
// move assignment
if (this != &rhs)
{
free();
_first_element = rhs._first_element;
_last_element = rhs._last_element;
_first_free = rhs._first_free;
_capacity = rhs._capacity;
rhs._first_element = rhs._last_element = rhs._first_free = rhs._capacity = nullptr;
}
std::cout << "move assignment" << std::endl;
return *this;
}
std::ostream& operator<<(std::ostream& output, const SimpleString& str)
{
output << str.c_string();
return output;
}
void SimpleString::push_back(const char tidbit) {
check_and_allocate();
*_last_element = tidbit;
_last_element = _first_free;
_alloc.construct(_first_free++, '\0');
}
void SimpleString::allocate_and_move(size_t newCap) {
auto newData = _alloc.allocate(newCap);
auto dest = newData;
auto elem = _first_element;
for (size_t i=0; i != size()+1; ++i)
_alloc.construct(dest++, std::move(*elem++));
free();
_first_element = newData;
_last_element = dest - 1;
_first_free = dest;
_capacity = _first_element + newCap;
}
void SimpleString::reallocate() {
auto newCapacity = size() ? 2 * (size()+1) : 2;
allocate_and_move(newCapacity);
}
std::istream &operator>>(std::istream &input, SimpleString &str) {
for (char tidbit; (tidbit = input.get()) != '\n'; )
str.push_back(tidbit);
return input;
}
bool operator==(const SimpleString& lhs, const SimpleString& rhs)
{
return ((lhs.size() == rhs.size()) &&
std::equal(lhs.begin(), lhs.end(), rhs.begin()));
}
bool operator!=(const SimpleString& lhs, const SimpleString& rhs)
{
return !(lhs == rhs);
}
void SimpleString::resize(size_t count) {
// little resize()
resize(count, ' ');
}
void SimpleString::resize(size_t count, char tidbit) {
// big resize()
if (count > size()) // grow to fit
{
if (count > capacity()) reserve(count * 2);
for (size_t i = size(); i != count; ++i)
{
*_last_element++ = tidbit;
_alloc.construct(_first_free++, '\0');
}
}
else if (count < size()) // shrink to fit, procrustean style
{
while (_last_element != _first_element + count)
{
--_last_element;
_alloc.destroy(--_first_free);
}
*_last_element = '\0';
}
}
void SimpleString::reserve(size_t sz) {
// used by the resize() method
// wrapper function for allocate_and_move
if (sz <= capacity()) return;
allocate_and_move(sz);
}
bool operator<(const SimpleString &lhs, const SimpleString &rhs) {
return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());
}
bool operator>(const SimpleString &lhs, const SimpleString &rhs) {
return rhs < lhs;
}
bool operator<=(const SimpleString &lhs, const SimpleString &rhs) {
return !(rhs < lhs);
}
bool operator>=(const SimpleString &lhs, const SimpleString &rhs) {
return !(lhs < rhs);
}
| true |
3cb8d0c20853bbf8b862fc07dfb153ac421a04fa | C++ | ceosss/coding | /LeetCode/Array/3Sum.cpp | UTF-8 | 1,318 | 3.0625 | 3 | [] | no_license | class Solution
{
public:
vector<vector<int> > threeSum(vector<int> &nums)
{
// TC - o(n^2)
// SC - o(1)
vector<vector<int> > res;
int n = nums.size();
sort(nums.begin(), nums.end());
for (int i = 0; i < n; i++)
{
if (i > 0 && nums[i] == nums[i - 1])
{
continue;
}
int a = -nums[i];
int start = i + 1;
int end = n - 1;
while (start < end)
{
if (nums[start] + nums[end] > a)
{
end--;
}
else if (nums[start] + nums[end] < a)
{
start++;
}
else
{
vector<int> cur;
int b = nums[start];
int c = nums[end];
cur.push_back(nums[i]);
cur.push_back(b);
cur.push_back(c);
res.push_back(cur);
while (start < end && nums[start] == b)
start++;
while (start < end && nums[end] == c)
end--;
}
}
}
return res;
}
}; | true |
dd1fd73253160b167c1bb273c71b39ec9bdafd38 | C++ | jennydvr/NeuralNet | /NeuralNet/SuperFang.cpp | UTF-8 | 610 | 2.625 | 3 | [] | no_license | //
// SuperFang.cpp
// Neuralmon_Mac
//
// Created by Jenny Valdez on 30/03/13.
// Copyright (c) 2013 Universidad Simon Bolivar. All rights reserved.
//
#include "SuperFang.h"
SuperFang::SuperFang() : Move(10)
{
name = "SuperFang";
}
void SuperFang::effect(Pet *me, Pet *foe)
{
// Chequea cuantos pp quedan
if (pp <= 0)
return;
// Disminuye los pp
--pp;
// 90% de chance de funcionar
if (rand() % 100 >= 90)
return;
// Quita la mitad de la vida
int damage = foe->getHP() / 2;
if (damage == 0)
damage = 1;
foe->setHP(-damage);
}
| true |
4abc2cfed578e14b74c850ae84444419c5fe176d | C++ | Sindisil/ray-tracer-challenge-cpp | /tests/test_transformations.cpp | UTF-8 | 1,504 | 2.84375 | 3 | [
"MIT"
] | permissive | #include "transformations.h"
#include "doctest.h"
#include "matrix.h"
#include "primitives.h"
using raytrace::identity_matrix;
using raytrace::Matrix4;
using raytrace::Point;
using raytrace::Vector3;
TEST_CASE("A transformation matrix for the default orientation") {
auto from = Point{0.0f, 0.0f, 0.0f};
auto to = Point{0.0f, 0.0f, -1.0f};
auto up = Vector3{0.0f, 1.0f, 0.0f};
auto t = view_transform(from, to, up);
REQUIRE(t == identity_matrix());
}
TEST_CASE("A view transformation matrix looking in toward +z") {
auto from = Point{0.0f, 0.0f, 0.0f};
auto to = Point{0.0f, 0.0f, 1.0f};
auto up = Vector3{0.0f, 1.0f, 0.0f};
auto t = view_transform(from, to, up);
REQUIRE(t == identity_matrix().scaled(-1.0f, 1.0f, -1.0f));
}
TEST_CASE("The view transformation moves the world") {
auto from = Point{0.0f, 0.0f, 8.0f};
auto to = Point{0.0f, 0.0f, 0.0f};
auto up = Vector3{0.0f, 1.0f, 0.0f};
auto t = view_transform(from, to, up);
REQUIRE(t == identity_matrix().translated(0.0f, 0.0f, -8.0f));
}
TEST_CASE("An arbitrary view transformation") {
auto from = Point{1.0f, 3.0f, 2.0f};
auto to = Point{4.0f, -2.0f, 8.0f};
auto up = Vector3{1.0f, 1.0f, 0.0f};
auto t = view_transform(from, to, up);
REQUIRE(t == Matrix4{{-0.50709f, 0.50709f, 0.67612f, -2.36643f},
{0.76772f, 0.60609f, 0.12122f, -2.82843f},
{-0.35857f, 0.59761f, -0.71714f, 0.00000f},
{0.00000f, 0.00000f, 0.00000f, 1.00000f}});
} | true |
4ea39522bb30876aa45aeb7a96835e6494e2f158 | C++ | SamridhG/Queue | /queue implement with stack in opps.cpp | UTF-8 | 1,444 | 3.484375 | 3 | [] | no_license | #include<iostream>
using namespace std;
class node{
public:
int data;
node *next;
node(int data)
{
this->data=data;
this->next=NULL;
}
};
class stack{
private:
node *head;
public:
stack()
{
head=NULL;
}
void push(int data)
{
if(head==NULL)
{
head=new node(data);
}
else
{
node *temp=head;
head=new node(data);
head->next=temp;
}
}
int top()
{
return head->data;
}
void pop()
{
node *temp=head;
head=head->next;
delete (temp);
}
bool empty()
{
if(head==NULL)
{
return true;
}
else
{
return false;
}
}
};
class queue{
private:
stack s1,s2;
public:
void enqueue(int data)
{
s1.push(data);
}
int dequeue()
{
if(s1.empty())
{
cout<<"empty";
}
else
{
while(!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
int D=s2.top();
s2.pop();
while(!s2.empty())
{
s1.push(s2.top());
s2.pop();
}
return D;
}
}
};
int main()
{
queue Q;
Q.enqueue(3);
Q.enqueue(4);
Q.enqueue(7);
Q.enqueue(2);
Q.enqueue(5);
Q.enqueue(9);
cout<<Q.dequeue()<<" ";
cout<<Q.dequeue()<<" ";
cout<<Q.dequeue()<<" ";
cout<<Q.dequeue()<<" ";
cout<<Q.dequeue()<<" ";
cout<<Q.dequeue()<<" ";
cout<<Q.dequeue()<<" ";
}
| true |
3e9c70f7608d09e1fa2cc64e5d9fbe6c3473b0e9 | C++ | 81120/trival-s-exp-interpreter | /Block.cpp | UTF-8 | 632 | 2.75 | 3 | [
"MIT"
] | permissive | #include "./Block.hpp"
#include <string>
std::string toy_lang::Block::to_string() {
if (block_type_ == BlockType::Symbol) {
return ":" + raw_val_;
}
if (block_type_ == BlockType::Number) {
return raw_val_;
}
if (block_type_ == BlockType::String) {
return "\"" + raw_val_ + "\"";
}
if (block_type_ == BlockType::Lambda) {
return "<Lmabda>";
}
if (block_type_ == BlockType::Proc) {
return "<Proc>";
}
if (block_type_ == BlockType::List) {
std::string res = "(";
for (auto b : args_) {
res += b.to_string() + " ";
}
res += ")";
return res;
}
return raw_val_;
}
| true |
67696990fc62112a40b943fa5a413c394f1b0ef2 | C++ | richiMarchi/Follow-The-Light | /follow_the_light/AnalogLed.cpp | UTF-8 | 199 | 2.703125 | 3 | [] | no_license | #include "AnalogLed.h"
#include "Arduino.h"
AnalogLed::AnalogLed(int pin){
this->pin = pin;
pinMode(pin,OUTPUT);
}
void AnalogLed::setIntensity(int intensity){
analogWrite(pin,intensity);
}
| true |
44547a1b1cd6ed330200888d5328ba165a3b576f | C++ | SanctuaryComponents/layer_management | /LayerManagerBase/include/GraphicalSurface.h | UTF-8 | 7,091 | 2.59375 | 3 | [
"BSD-3-Clause",
"Zlib",
"MIT",
"Apache-2.0"
] | permissive | /***************************************************************************
*
* Copyright 2010,2011 BMW Car IT GmbH
*
*
* 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 _GRAPHICALSURFACE_H_
#define _GRAPHICALSURFACE_H_
#include "GraphicalObject.h"
#include "OrientationType.h"
#include "Rectangle.h"
#include "Vector2.h"
/**
* Abstract Type representing a graphical surface.
*/
class GraphicalSurface : public GraphicalObject
{
public:
GraphicalSurface(ObjectType type, int creatorPid);
GraphicalSurface(int externalId, ObjectType type, int creatorPid);
virtual ~GraphicalSurface() {}
/**
* @brief Set Orientation value
* @param[in] newOrientation the new value. Multiples of 90 degrees. (0->0°, 1->90°, 2->180°,3->279°)
* @return TRUE if the new orientation value is not equal to the current orientation value
* FALSE if they are equal
*/
bool setOrientation(OrientationType newOrientation);
OrientationType getOrientation() const;
/**
* @brief Set Source Viewport (only use portion of source graphics)
* @param[in] newSource Rectangle defining position and size within surface (clip from the left)
* @return TRUE if the new source rectangle is not equal to the current source rectangle
* FALSE if they are equal
*/
bool setSourceRegion(const Rectangle& newSource);
const Rectangle& getSourceRegion() const;
/**
* Set Destination Viewport (Scale output)
* @param[in] newDestination Rectangle defining destination position and size
* @return TRUE if the new destination rectangle is not equal to the current destination rectangle
* FALSE if they are equal
*/
bool setDestinationRegion(const Rectangle& newDestination);
bool setPosition(const unsigned int& x, const unsigned int& y);
Vector2 getPosition();
bool setDimension(const unsigned int& width, const unsigned int& height);
const Rectangle& getDestinationRegion() const;
Vector2 getDimension();
/**
* @brief Indicate if a x,y position is inside the destination region.
* Attention: Graphical Surface rotation is not yet supported.
* @param x_DestCoordinateSyst x position in the destination coordinate system
* @param y_DestCoordinateSyst y position in the destination coordinate system
* @return TRUE if the position is inside the destination region
*/
bool isInside(unsigned int x_DestCoordinateSyst, unsigned int y_DestCoordinateSyst) const;
/**
* @brief Transform a x,y position from destination coordinate system to
* source coordinate system. Attention, to get valid result the x,y
* positions given in parameter must be located within the destination
* region of the GraphicalSurface
*
* @param[in] x x position in the destination coordinate system
* @param[out] x x position in the source coordinate system
* @param[in] y y position in the destination coordinate system
* @param[out] y y position in the source coordinate system
* @param check If TRUE, a test will be done to make sure the x,y positions
* given in parameter are located within the destination region.
*
* @return TRUE if the coordinates have been translated
* FALSE if an error occured, exp: The position is not in the destination region
*/
bool DestToSourceCoordinates(int *x, int *y, bool check) const;
int OriginalSourceWidth;
int OriginalSourceHeight;
bool m_surfaceResized;
bool m_resizesync;
private:
OrientationType m_orientation; // Rotation of the graphical content
Rectangle m_sourceViewport;
Rectangle m_destinationViewport;
};
inline GraphicalSurface::GraphicalSurface(ObjectType type, int creatorPid)
: GraphicalObject(type, 1.0, false, creatorPid)
, OriginalSourceWidth(0)
, OriginalSourceHeight(0)
, m_surfaceResized(false)
, m_resizesync(false)
, m_orientation(Zero)
, m_sourceViewport(0, 0, 0, 0)
, m_destinationViewport(0, 0, 0, 0)
{
}
inline GraphicalSurface::GraphicalSurface(int externalId, ObjectType type, int creatorPid)
: GraphicalObject(externalId, type, 1.0, false, creatorPid)
, OriginalSourceWidth(0)
, OriginalSourceHeight(0)
, m_surfaceResized(false)
, m_resizesync(false)
, m_orientation(Zero)
, m_sourceViewport(0, 0, 0, 0)
, m_destinationViewport(0, 0, 0, 0)
{
}
inline bool GraphicalSurface::setOrientation(OrientationType newOrientation)
{
if (m_orientation != newOrientation)
{
m_orientation = newOrientation;
renderPropertyChanged = true;
return true;
}
return false;
}
inline OrientationType GraphicalSurface::getOrientation() const
{
return m_orientation;
}
inline bool GraphicalSurface::setSourceRegion(const Rectangle& newSource)
{
if (!(m_sourceViewport == newSource))
{
m_sourceViewport = newSource;
renderPropertyChanged = true;
return true;
}
return false;
}
inline const Rectangle& GraphicalSurface::getSourceRegion() const
{
return m_sourceViewport;
}
inline bool GraphicalSurface::setDestinationRegion(const Rectangle& newDestination)
{
if (!(m_destinationViewport == newDestination))
{
m_destinationViewport = newDestination;
renderPropertyChanged = true;
return true;
}
return false;
}
inline bool GraphicalSurface::setPosition(const unsigned int& x, const unsigned int& y)
{
if (m_destinationViewport.x != x || m_destinationViewport.y != y)
{
m_destinationViewport.x = x;
m_destinationViewport.y = y;
renderPropertyChanged = true;
return true;
}
return false;
}
inline Vector2 GraphicalSurface::getPosition()
{
return Vector2(m_destinationViewport.x, m_destinationViewport.y);
}
inline bool GraphicalSurface::setDimension(const unsigned int& width, const unsigned int& height)
{
if (m_destinationViewport.width != width || m_destinationViewport.height != height)
{
m_destinationViewport.width = width;
m_destinationViewport.height = height;
renderPropertyChanged = true;
return true;
}
return false;
}
inline const Rectangle& GraphicalSurface::getDestinationRegion() const
{
return m_destinationViewport;
}
inline Vector2 GraphicalSurface::getDimension()
{
return Vector2(m_destinationViewport.width, m_destinationViewport.height);
}
#endif /* _GRAPHICALSURFACE_H_ */
| true |
a14b93a6047a66d1aa508d059100526d27e0c983 | C++ | ENSTABretagneRobotics/ardupilot2ros | /ardupilot2ros/src/iboolean.h | UTF-8 | 1,549 | 2.75 | 3 | [] | no_license | // Simple interval library from Luc JAULIN, with minor modifications from Fabrice LE BARS and Jeremy NICOLA.
#ifndef IBOOLEAN_H
#define IBOOLEAN_H
// IBOOLEAN is an interval Boolean. Used for a trivalued logic
// if x=[0,0]=ifalse : certainly false
// if x=[0,1]=iperhaps: don't know
// if x=[1,1]=itrue : certainly true
// Otherwise x=iempty
#ifdef _MSC_VER
// Enable additional features in math.h.
#ifndef _USE_MATH_DEFINES
#define _USE_MATH_DEFINES
#endif // !_USE_MATH_DEFINES
#endif // _MSC_VER
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cfloat>
enum IBOOLEAN {itrue, ifalse, iperhaps, iempty};
class iboolean
{
public:
IBOOLEAN value;
public:
iboolean();
iboolean(bool);
iboolean(IBOOLEAN);
iboolean(const iboolean&);
friend iboolean operator&&(iboolean, iboolean);
friend iboolean operator||(iboolean, iboolean);
friend iboolean operator!(iboolean);
friend bool operator==(iboolean, iboolean);
friend bool operator!=(iboolean, iboolean);
friend iboolean Not(iboolean x);
friend iboolean Inter(iboolean, iboolean);
friend iboolean Union(iboolean, iboolean);
friend iboolean And(iboolean,iboolean);
friend iboolean Or(iboolean,iboolean);
friend iboolean leq(iboolean x, iboolean y);
friend iboolean geq(iboolean x, iboolean y);
friend iboolean Restrict(iboolean x, iboolean y); // return x and !y
friend iboolean Xor(iboolean x, iboolean y);
friend std::ostream& operator<<(std::ostream& os, const iboolean&);
};
#endif // !IBOOLEAN_H
| true |
928dd68301067bc287315291097627882ab86481 | C++ | BlueSpells/MapGen | /Common/PendingList.h | UTF-8 | 3,295 | 2.953125 | 3 | [] | no_license | #pragma once
#include <map>
#include "TimeStamp.h"
#include "LogEvent.h"
#include "Common/CriticalSection.h"
template<typename PendingItem>
class CPendingList
{
public:
CPendingList(): m_CurrentRequestId(0), m_LastGeneratedId(0)
{
}
void ClearAll()
{
CCriticalSectionLocker Locker(m_PendingMapLock);
m_CurrentRequestId = 0;
m_LastGeneratedId = 0;
m_Pending.clear();
}
bool AddRequest(const PendingItem& Item, const CTimePeriod& ItemTimeout, int& AllocatedRequestId)
{
CCriticalSectionLocker Locker(m_PendingMapLock);
AllocatedRequestId = ++m_LastGeneratedId;
PendingRequest Request = {Item, CTimeStamp::Now(), ItemTimeout};
PendingMap::value_type Value(AllocatedRequestId, Request);
std::pair<PendingIterator, bool> Result = m_Pending.insert(Value);
if (!Result.second)
{
LogEvent(LE_ERROR, "CPendingList::AddRequest: error insert (%d)", AllocatedRequestId);
return false;
}
return true;
}
// Return false if no such request
bool FindRequest(int RequestId, PendingItem& Item, bool RemoveRequest = true, bool UpdateRequestTime = false)
{
CCriticalSectionLocker Locker(m_PendingMapLock);
PendingIterator Iter = m_Pending.find(RequestId);
if (Iter == m_Pending.end())
{
LogEvent(LE_ERROR, "CPendingList::FindRequest: (%d) not found", RequestId);
return false;
}
PendingRequest& Request = Iter->second;
Item = Request.Item;
if(RemoveRequest)
m_Pending.erase(Iter);
else if(UpdateRequestTime)
Request.RequestTime = CTimeStamp::Now();
return true;
}
// Return false if no such request
bool RemoveRequest(int RequestId)
{
PendingItem Item;
return FindRequest(RequestId, Item);
}
// These are used to walk over list and retrieve outdated requests
void StartOutdated()
{
CCriticalSectionLocker Locker(m_PendingMapLock);
m_CurrentRequestId = 0;
}
bool NextOutdatedRequest(
int& RequestId,
PendingItem& Item)
{
CCriticalSectionLocker Locker(m_PendingMapLock);
PendingIterator End = m_Pending.end();
CTimeStamp CurrentTime = CTimeStamp::Now();
for (;; ++m_CurrentRequestId)
{
PendingIterator Iter = m_Pending.lower_bound(m_CurrentRequestId);
if (Iter == End)
break;
PendingRequest& Request = Iter->second;
if (CurrentTime - Request.RequestTime > Request.RequestTimeout)
{
RequestId = Iter->first;
return FindRequest(RequestId, Item);
}
}
return false; // Not found
}
private:
struct PendingRequest
{
PendingItem Item;
CTimeStamp RequestTime;
CTimePeriod RequestTimeout;
};
typedef std::map<int/*RequestId*/, PendingRequest> PendingMap;
typedef typename PendingMap::iterator PendingIterator;
PendingMap m_Pending;
int m_CurrentRequestId; // Used to iterate over all requests
int m_LastGeneratedId;
CCriticalSection m_PendingMapLock;
};
| true |
7603401a42b7f8fdcda9d71904a3d7dbd29615f9 | C++ | Zillit/ARC | /src/test.cpp | UTF-8 | 254 | 2.59375 | 3 | [] | no_license | #include "test.h"
#include <iostream>
using namespace std;
class Test;
Test::Test()
{
number_of_calls_=0;
}
int Test::test()
{
number_of_calls_++;
cout << "Number of test calls: " << number_of_calls_ << endl;
return number_of_calls_;
}
| true |
710ddb51cc6ba9f5f0c8d6ae50ef5c5dc6609eb0 | C++ | Hanray-Zhong/Computer-Science | /hust C语言学习/第七章/strstr.cpp | UTF-8 | 560 | 3.296875 | 3 | [] | no_license | #include <stdio.h>
int strlen(char []);
int strstr(char [],char []);
int main(void)
{
char cs[20],ct[20];
scanf("%s",cs);
scanf("%s",ct);
printf("%d",strstr(cs,ct));
return 0;
}
/*************strstr()************/
int strstr(char cs[],char ct[])
{
int j=0,k;
for(;cs[j]!='\0';j++)
if(cs[j]==ct[0])
{
k=1;
while(cs[j+k]==ct[k]&&ct[k]!='\0')
k++;
if(k==strlen(ct))
return j;
}
return -1;
}
/***************strlen()****************/
int strlen(char s[])
{
int j=0;
while(s[j]!='\0') j++;
return j;
}
| true |
1911b7b0c2742953811844a29d1627ef69b8f193 | C++ | AguaClara/sensor_dev | /code/MIA/turbidity_sensor5.ino | UTF-8 | 3,203 | 3.0625 | 3 | [] | no_license | /*
* THIS CODE IS FOR AGUACLARA SENSOR_DEV
* This code's function is to take the input voltage from the turbidity sensor
* and translate it into a numerical value for turbidity
*/
//global variables
int ledPin = 13; //declaration for LED
int button = 11; //digital input of the pushbutton
int offset = 0; //set the offset as zero for now
int turb_input = A0; //input in A0 from sensor
int flag = 0; //if flag is 1, start loop
float turbidity = 0.0; //turbidity
int threshold = 2500; //threshold turbidity for sludge blanket
//setup
void setup() {
Serial.begin(9600); //Baud rate: 9600
pinMode(ledPin, OUTPUT); //This is to set up the LED
pinMode(turb_input, INPUT); //This is to set up the turbidity input from sensor
pinMode(button, INPUT); //This is to set up the input from pushbutton
//CALIBRATION
//set up so that the difference between the clear water turbidity
//and the usual 0 turbidity value and set this as the constant offset
//as Hannah pointed out, this will also take care of the temp difference
//(this will be used in the conversion)
Serial.println('\n');
Serial.println("Please calibrate the sensor by pressing the button"); //clear water calibration
//PUSHBUTTON
//set it up with a push button
if (digitalRead(button)==LOW){
//don't remember if pushbutton high or low when pressed
flag = 0;
}
else if(digitalRead(button) == HIGH){
//whole thing could possibly be moved into loop()
offset = analogRead(turb_input);
Serial.println('\n');
Serial.print("this is the offset value:"); //but then get rid of flag=0
Serial.println(offset);
delay(500);
flag = 1;
}
}
void loop() {
// if (flag == 1){
int sensorValue = analogRead(turb_input);// read the input on A0:
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float voltage = sensorValue * (5.0 / 1024.0);
Serial.println("____________________________________");
Serial.print("this is the reading from the analog:");
Serial.println(sensorValue); // print out the value you read:
Serial.print("this is the voltage reading:");
Serial.println(voltage); // print out the value you read:
// Convert voltage to turbidity
// relation from page is -1120.4x^2 +5742.3x-4352.9
// only supports voltages of 2.5-4.2 for the relation
if (voltage > 2.5 && voltage < 4.2){
//this relation needs to be fixed as well
//this fixes the problem with the negative numbers
turbidity = (voltage*voltage*(-1120.4))+(voltage*5742.3)-4352.9-(offset);
}
else if (voltage < 2.5){
turbidity = 3000;
}
else if (voltage > 4.2){
turbidity = 0;
}
Serial.print("this is the turbidity reading:");
Serial.println(turbidity); // print out the value you read:
delay(500);
//threshold value to compare to light up LED
if (turbidity > threshold){
digitalWrite(ledPin, HIGH);
Serial.println("YOU ARE NOW IN THE SLUDGE BLANKET");
// }
//later add breadboard stuff with display
}
}
| true |
1c67f38994e45d5014e0b7ca80bc2feca92a501e | C++ | adiM3344/ex3 | /DefineVarCommand.cpp | UTF-8 | 1,340 | 3.046875 | 3 | [] | no_license |
#include "DefineVarCommand.h"
/**
* defines a variable according to the data provided and adds it to the symbol table
* @return the number of indexes to move in the commands map
*/
int DefineVarCommand::execute() {
Singleton* singleton = Singleton::getInstance();
// gets the data the belongs to this variable
vector<string> vars_fields = this->vars[this->place];
this->place = this->place+1;
// if "sim" is defined
if (vars_fields[1] != "") {
Variable* var = singleton->getXMLMap()->at(vars_fields[1]);
if (vars_fields[3] == "->") {
var->setDirection(true);
}
singleton->getSymbolTable()->insert({vars_fields[0], var});
return 5;
}
else {
Interpreter i;
double val = i.interpret(vars_fields[2])->calculate();
Variable *var = new Variable(vars_fields[0], val);
singleton->getSymbolTable()->insert({vars_fields[0], var});
return 4;
}
}
/**
* adds the data of a new variable
* @param n the name
* @param s the sim path
* @param v the value
* @param d the direction
*/
void DefineVarCommand::addVar(string n, string s, string v, string d) {
vector<string> fields;
fields.push_back(n);
fields.push_back(s);
fields.push_back(v);
fields.push_back(d);
this->vars.push_back(fields);
} | true |
400f687490dea31a2ac2f64fb8158970a8eb613d | C++ | tinglai/Algorithm-Practice | /LeetCode/Unique Binary Search Trees II/main.cpp | UTF-8 | 2,413 | 3.6875 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct TreeNode{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL){}
};
class Solution{
public:
vector<TreeNode *> generateTrees(int n){
vector<TreeNode*> result;
if(n <= 0){
result.push_back(NULL);
return result;
}
help(n, result, n);
return result;
}
void help(int n, vector<TreeNode*>& trees, int top){
//generate BST's s.t the size of the tree is n
//with largest number among the tree to be top
//store the root of those trees in vector trees
if(n == 0){
return;
}
else{
for(int i = top - n + 1; i <= top; i++){
//i denotes the val of root of the tree
vector<TreeNode*> leftSubtree;
vector<TreeNode*> rightSubtree;
help(i - top + n - 1, leftSubtree, i - 1);
help(top - i, rightSubtree, top);
if(leftSubtree.empty() && rightSubtree.empty()){
TreeNode* root = new TreeNode(i);
trees.push_back(root);
}
if(leftSubtree.empty()){
for(unsigned p = 0; p < rightSubtree.size(); p++){
TreeNode* root = new TreeNode(i);
root->right = rightSubtree[p];
trees.push_back(root);
}
}
else if(rightSubtree.empty()){
for(unsigned p = 0; p < leftSubtree.size(); p++){
TreeNode* root = new TreeNode(i);
root->left = leftSubtree[p];
trees.push_back(root);
}
}
else{
for(unsigned j = 0; j < leftSubtree.size(); j++){
for(unsigned p = 0; p < rightSubtree.size(); p++){
TreeNode* root = new TreeNode(i);
root->left = leftSubtree[j];
root->right = rightSubtree[p];
trees.push_back(root);
}
}
}
}
}
}
};
void byLevelPrint(TreeNode* root){
if(root == NULL) return;
queue<TreeNode*> que;
que.push(root);
while(!que.empty()){
int size = (int)que.size();
for(int i = 0; i < size; i++){
TreeNode* temp = que.front();
cout << temp->val << " ";
if(temp->left) que.push(temp->left);
if(temp->right) que.push(temp->right);
que.pop();
}
cout << endl;
}
}
int main(){
int n;
cout << "n = "; cin >> n;
Solution soln;
vector<TreeNode*> result = soln.generateTrees(n);
cout << "result.size() = " << result.size() << endl;
for(unsigned int i = 0; i < result.size(); i++){
TreeNode* temp = result[i];
cout << "********" << endl;
byLevelPrint(temp);
cout << endl;
}
}
| true |
9d45ddb1b677356f14e937ca632a1987148875d1 | C++ | matvey1997/MetProgHomeworks | /metProghome1.cpp | UTF-8 | 1,476 | 3.125 | 3 | [] | no_license | #include<tuple>
#include<vector>
#include<string>
#include<iostream>
#include<cstdio>
using namespace std;
template<int N>
class tupleReader {
public:
template<class T1, class ... otherClasses>
static tuple<T1, otherClasses ...> readTuple(tuple<T1, otherClasses ...> *temp) {
T1 a;
cin >> a;
tuple<otherClasses ...> new_temp;
return (tuple_cat(make_tuple(a), tupleReader<N - 1>::readTuple(&new_temp)));
}
};
template<>
class tupleReader<1> {
public:
template<class T1>
static tuple<T1> readTuple(tuple<T1> *temp) {
T1 a;
cin >> a;
return make_tuple(a);
}
};
template<class T1, class ... otherClasses>
vector<tuple<T1, otherClasses ...> > readCSV(char* filename) {
freopen(filename, "r", stdin);
vector<tuple<T1, otherClasses...> > ans;
tuple<otherClasses ...> temp;
while (1) {
T1 a;
if (!(cin >> a))
break;
ans.push_back(tuple_cat(make_tuple(a), tupleReader<tuple_size<tuple<T1, otherClasses ... > >::value- 1>::readTuple(&temp)));
}
return ans;
}
/*
tempalte<class T1>
vector<tuple<T1> > readCSV(char* filename) {
freopen(filename, "r", stdin);
vector<tuple<T1> > ans;
T1 a;
while (cin >> a) {
ans.push_back(make_tuple<T1>(a));
}
return ans;
}*/
int main() {
auto v = readCSV<double, string, int, string> ("input.txt");
cout << v.size() << endl;
cout << std::get<1>(v[2]);
return 0;
}
| true |
f731a3aa84b0de20b3de605cdec8b6769772eae4 | C++ | stormbreaker07/CodingQuestions | /problem set 3/codeforcesdivision_2_11.cpp | UTF-8 | 633 | 2.765625 | 3 | [] | no_license | #include <bits/stdc++.h>
#include<iostream>
#include<string>
#include<deque>
using namespace std;
int main()
{deque<char> d;
int n;
cin>>n;
string s;
cin>>s;
d.push_back(s[0]);
if(s.length()%2!=0)
{for(int i=1;i<s.length();i++)
{if(i%2!=0)
{d.push_front(s[i]);}
else
{d.push_back(s[i]);}
}
}
else
{for(int i=1;i<s.length()-1;i++)
{if(i%2==0)
{d.push_front(s[i]);}
else
{d.push_back(s[i]);}
}
d.push_back(s[s.length()-1]);
}
deque<char>::iterator it;
for(it=d.begin();it!=d.end();it++)
{cout<<*it;}
return 0;
}
| true |
0aa60e1da3f8d7a4382670e41468ce66fedcef6e | C++ | byJunKim/GIS | /libstreetmap/src/m4.cpp | UTF-8 | 19,095 | 2.640625 | 3 | [] | no_license | #include <thread>
#include <queue>
#include <unordered_map>
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include "map_list.h"
#include "m3.h"
#include "m2.h"
#include "m4.h"
//// generates path from start point using greedy algo
//Seg_array path_gen(const IntersectionIndex intersect_id_start,
// const std::unordered_multimap<IntersectionIndex, IntersectionIndex>& pd_pair,
// const std::unordered_map<IntersectionIndex, bool>& legal_points,
// const std::vector<unsigned>& depots,
// const double turn_penalty);
//
//double calculate_points_distance_helper(IntersectionIndex i, IntersectionIndex j);
//
//
//double calculate_path_distance_helper(const I_array path) ;
//
//
//Seg_array double_insertion2(const std::vector<DeliveryInfo>& deliveries,
// const std::vector<unsigned>& depots,
// const float turn_penalty, const float alpha);
//
////void rand_path_gen(const std::unordered_multimap<IntersectionIndex, IntersectionIndex>& pd_pair,
//// const I_array& legal,
//// const std::vector<unsigned>& depots,
//// std::pair<I_array, double>& score);
////
////
////double calculate_intersection_score(const I_array& path);
////
////
////Seg_array i_array_to_path(const I_array& intersection_path, const double turn_penalty);
//
//
////Seg_array traveling_courier(const std::vector<DeliveryInfo>& deliveries,
//// const std::vector<unsigned>& depots,
//// const float turn_penalty) {
////
//// // path to return
////// Seg_array path;
////// std::vector<Seg_array> delivery_paths;
////
//// // use to check for corresponding dropoff point after pickup
//// std::unordered_multimap<IntersectionIndex, IntersectionIndex> pickup_dropoff;
////
//// // store legal_points
//// std::unordered_map<IntersectionIndex, bool> legal_points;
////
////
//// // initializing first points
//// for (DeliveryInfo i : deliveries) {
//// pickup_dropoff.insert(std::make_pair(i.pickUp, i.dropOff));
//// legal_points.insert(std::make_pair(i.pickUp, true));
//// }
////
////
//// // keep track of best path
//// Seg_array best_path;
//// double min_distance = INF;
////
////
//// for (IntersectionIndex i : depots) {
//// // call path_gen here for each depot
//// Seg_array current_path = path_gen(i, pickup_dropoff, legal_points, depots, turn_penalty);
////
//// if (current_path.size() == 0) {
//// continue;
//// }
////
//// double current_distance = compute_path_travel_time(current_path, turn_penalty);
////
//// if (current_distance < min_distance) {
//// best_path = current_path;
//// }
//// }
////
//// return best_path;
////}
//
///*
//// should take in a start point, legal points, and pickup-dropoff pairs to develop greedy path
//Seg_array path_gen(const IntersectionIndex intersect_id_start,
// const std::unordered_multimap<IntersectionIndex, IntersectionIndex>& pd_pair,
// const std::unordered_map<IntersectionIndex, bool>& legal_points,
// const std::vector<unsigned>& depots,
// const double turn_penalty) {
//
// std::unordered_map<IntersectionIndex, bool> legal = legal_points;
//
// Seg_array path;
//
// IntersectionIndex current_point = intersect_id_start;
// IntersectionIndex next_point;
//
// if (legal.find(intersect_id_start) != legal.end()) {
// for (auto it = pd_pair.equal_range(intersect_id_start).first; it != pd_pair.equal_range(intersect_id_start).second; ++it) {
// legal.insert(std::make_pair(it->second, true));
// }
// }
//
// else if (intersection_dijkstra(intersect_id_start, legal, turn_penalty, next_point).size() == 0) {
// return Seg_array();
// }
//
// while (legal.size() != 0) {
// Seg_array current_subpath = intersection_dijkstra(current_point, legal, turn_penalty, next_point);
//
// legal.erase(next_point);
//
// for (auto it = pd_pair.equal_range(next_point).first; it != pd_pair.equal_range(next_point).second; ++it) {
// legal.insert(std::make_pair(it->second, true));
// }
//
// current_point = next_point;
// path.insert(std::end(path), std::begin(current_subpath), std::end(current_subpath));
// }
//
// Seg_array last_path = intersection_dijkstra(current_point, depots, turn_penalty, current_point);
//
// path.insert(std::end(path), std::begin(last_path), std::end(last_path));
// return path;
//}
//
// helper dijkstra to find shortest path from intersection to a set of points
// also returns intersect_id_end (input as reference)
Seg_array intersection_dijkstra(const unsigned intersect_id_start,
std::unordered_map<IntersectionIndex, bool>& endpoints,
const double turn_penalty,
IntersectionIndex& intersect_id_end) {
// containing uninitialized nodes with time = inf
std::vector<I_node> graph(getNumberOfIntersections());
// setup temp variables: visited checker and heap
std::vector<bool> visited(getNumberOfIntersections(), false);
std::priority_queue<I_node, std::vector<I_node>, compare_I_node> minheap;
// initial distance = 0 and start node is visited
visited[intersect_id_start] = true;
bool found = false;
// update graph for starting intersection
graph[intersect_id_start].id = intersect_id_start;
I_node current_node = graph[intersect_id_start];
current_node.travel_time = 0;
// initial loading from starting intersection
for (unsigned i = 0; i < mapData->graph[current_node.id].adjacent.size(); ++i) {
// setting up initial distances for intersections adjacent to starting point
IntersectionIndex current_id = mapData->graph[current_node.id].adjacent[i];
graph[current_id].id = current_id;
double distance = find_street_segment_travel_time(mapData->graph[current_node.id].segments[i]);
// check if less than existing distances (either INF or already set)
if (distance < graph[mapData->graph[current_node.id].adjacent[i]].travel_time) {
graph[current_id].travel_time = distance;
graph[current_id].prev = mapData->graph[current_node.id].segments[i];
minheap.push(graph[current_id]);
}
}
// check whether heap is empty or we found the destination
while (!minheap.empty() && !found) {
while (visited[current_node.id]) {
if (!minheap.empty()) {
current_node = minheap.top();
minheap.pop();
}
else {
continue;
}
}
// check if any intersection is found - if true, then it is the closest destination
if (endpoints.find(current_node.id) != endpoints.end()) {
found = true;
continue;
}
// mark the current node as visited
visited[current_node.id] = true;
for (unsigned i = 0; i < mapData->graph[current_node.id].adjacent.size(); ++i) {
// setting up initial distances for intersections adjacent to starting point
if (!visited[mapData->graph[current_node.id].adjacent[i]]) {
IntersectionIndex current_id = mapData->graph[current_node.id].adjacent[i];
graph[current_id].id = current_id;
double distance = find_street_segment_travel_time(mapData->graph[current_node.id].segments[i]) + current_node.travel_time;
// check for turns
if (getStreetSegmentInfo(mapData->graph[current_node.id].segments[i]).streetID != getStreetSegmentInfo(current_node.prev).streetID) {
distance += turn_penalty;
}
// check if less than existing distances (either INF or already set)
if (distance < graph[current_id].travel_time) {
graph[current_id].travel_time = distance;
graph[current_id].prev = mapData->graph[current_node.id].segments[i];
minheap.push(graph[current_id]);
}
}
}
}
// loop backwards if found
if (found) {
intersect_id_end = current_node.id;
return path_find(graph, current_node, intersect_id_start);
}
// else return empty array
return Seg_array();
}
// same function which takes in vector instead of multimap
Seg_array intersection_dijkstra(const unsigned intersect_id_start,
I_array endpoints,
const double turn_penalty,
IntersectionIndex& intersect_id_end) {
// initializing potential destinations and hash table for checking
std::unordered_map<IntersectionIndex, bool> intersections_check;
// closest intersections into hash table
for (IntersectionIndex i : endpoints) {
intersections_check.insert(std::make_pair(i, true));
}
// containing uninitialized nodes with time = inf
std::vector<I_node> graph(getNumberOfIntersections());
// setup temp variables: visited checker and heap
std::vector<bool> visited(getNumberOfIntersections(), false);
std::priority_queue<I_node, std::vector<I_node>, compare_I_node> minheap;
// initial distance = 0 and start node is visited
visited[intersect_id_start] = true;
bool found = false;
// update graph for starting intersection
graph[intersect_id_start].id = intersect_id_start;
I_node current_node = graph[intersect_id_start];
current_node.travel_time = 0;
// initial loading from starting intersection
for (unsigned i = 0; i < mapData->graph[current_node.id].adjacent.size(); ++i) {
// setting up initial distances for intersections adjacent to starting point
IntersectionIndex current_id = mapData->graph[current_node.id].adjacent[i];
graph[current_id].id = current_id;
double distance = find_street_segment_travel_time(mapData->graph[current_node.id].segments[i]);
// check if less than existing distances (either INF or already set)
if (distance < graph[mapData->graph[current_node.id].adjacent[i]].travel_time) {
graph[current_id].travel_time = distance;
graph[current_id].prev = mapData->graph[current_node.id].segments[i];
minheap.push(graph[current_id]);
}
}
// check whether heap is empty or we found the destination
while (!minheap.empty() && !found) {
while (visited[current_node.id]) {
if (!minheap.empty()) {
current_node = minheap.top();
minheap.pop();
}
else {
continue;
}
}
// check if any intersection is found - if true, then it is the closest destination
if (intersections_check.find(current_node.id) != intersections_check.end()) {
found = true;
continue;
}
// mark the current node as visited
visited[current_node.id] = true;
for (unsigned i = 0; i < mapData->graph[current_node.id].adjacent.size(); ++i) {
// setting up initial distances for intersections adjacent to starting point
if (!visited[mapData->graph[current_node.id].adjacent[i]]) {
IntersectionIndex current_id = mapData->graph[current_node.id].adjacent[i];
graph[current_id].id = current_id;
double distance = find_street_segment_travel_time(mapData->graph[current_node.id].segments[i]) + current_node.travel_time;
// check for turns
if (getStreetSegmentInfo(mapData->graph[current_node.id].segments[i]).streetID != getStreetSegmentInfo(current_node.prev).streetID) {
distance += turn_penalty;
}
// check if less than existing distances (either INF or already set)
if (distance < graph[current_id].travel_time) {
graph[current_id].travel_time = distance;
graph[current_id].prev = mapData->graph[current_node.id].segments[i];
minheap.push(graph[current_id]);
}
}
}
}
// loop backwards if found
if (found) {
intersect_id_end = current_node.id;
return path_find(graph, current_node, intersect_id_start);
}
// else return empty array
return Seg_array();
}
//*/
//
//Seg_array traveling_courier(const std::vector<DeliveryInfo>& deliveries,
// const std::vector<unsigned>& depots,
// const float turn_penalty) {
//
// float alpha = 1.0;
//
// return double_insertion2(deliveries, depots, turn_penalty, alpha);
//}
//
//Seg_array double_insertion2(const std::vector<DeliveryInfo>& deliveries,
// const std::vector<unsigned>& depots,
// const float turn_penalty, const float alpha){
//
// // intersection-ordered path (path to plug into a*)
// I_array path;
//
// //step 0: initialization
// IntersectionIndex largest_pickup;
// IntersectionIndex largest_dropoff;
// double largest_cost = INF;
// for (auto i : deliveries) {
// double current_cost = compute_path_travel_time(find_path_between_intersections(i.pickUp, i.dropOff, turn_penalty), turn_penalty);
//
// if (current_cost < largest_cost) {
// largest_cost = current_cost;
// largest_pickup = i.pickUp;
// largest_dropoff = i.dropOff;
// }
// }
//
//
//
//
// //add the first pair of pickup and dropoff to the path to start with
// path.push_back(largest_pickup);
// path.push_back(largest_dropoff);
//
// unsigned i, j;
//
// //going through all the deliveries
// for(unsigned x = 0; x < deliveries.size(); x++){
//
// //get each pair of delivery and pickup
// i = deliveries[x].pickUp;
// j = deliveries[x].dropOff;
//
// if (i == largest_pickup) {
// continue;
// }
//
// //find their combined minimum weighted insertion cost
// //find the corresponding position in the current subtour H
//
// //(k,l) & (s,t) are two consecutive vertices
//
//
// double min_cost1 = INF;
// double min_cost2 = INF;
//
// unsigned position1, position2i, position2j;
//
// //1st case: i & j are inserted btw k and l
// for(unsigned k = 0; k + 1 < path.size(); k++){
// unsigned l = k + 1;
//
// double new_cost = 0;
//
// //calculate min_cost1 based on the formula
// //min{alphi * cost(k,i) + cost(i,j) + (2-alpha) * cost(j,l) - cost(k,l)}
// new_cost = alpha * calculate_points_distance_helper(path[k], i);
// new_cost += calculate_points_distance_helper(i, j);
// new_cost += (2 - alpha) * (calculate_points_distance_helper(j, path[l]));
// new_cost -= calculate_points_distance_helper(path[k], path[l]);
//
// if(new_cost < min_cost1){
// min_cost1 = new_cost;
// position1 = k;
// }
// }
//
//
// //2nd case: i is inserted btw k and l
// // j is inserted btw s and t
// for(unsigned k = 0; k + 1 < path.size(); k++){
// unsigned l = k + 1;
//
// for(unsigned s = l + 1; s + 1 < path.size(); s++){
// unsigned t = s + 1;
//
// double new_cost = 0;
//
// //calculate min_cost2 based on the formula
// //min{alpha * (cost(k,i) + cost(i,l) - cost(k,l))
// // + (2 - alpha) * (cost(s,j) + cost(j, t) - cost(s,t)}
//
// new_cost = alpha * (calculate_points_distance_helper(path[k], i)
// + calculate_points_distance_helper(i, path[l])
// - calculate_points_distance_helper(path[k], path[l]));
// new_cost += (2 - alpha) * (calculate_points_distance_helper(path[s], j)
// + calculate_points_distance_helper(j, path[t])
// - calculate_points_distance_helper(path[s], path[t]));
//
// if(new_cost < min_cost2){
// min_cost2 = new_cost;
// position2i = k;
// position2j = s;
// }
// }
// }
//
// //take the min{min_cost1, min_cost2}
//
// //if its better to insert this pair together
// if(min_cost1 <= min_cost2){
// path.insert(path.begin() + position1 + 1, i);
// path.insert(path.begin() + position1 + 2, j);
// }
// else if(min_cost1 > min_cost2){
// path.insert(path.begin() + position2i + 1, i);
// path.insert(path.begin() + position2j + 1, j);
// }
//
// }
//
// //find the lowest cost depots to connect to first and last point
//
// //start and end with any depot first, will change later
// path.insert(path.begin(), depots[0]);
// path.insert(path.end(), depots[0]);
//
// Seg_array seg_path;
//
// //plug into m3 a*
// for(unsigned x = 0; x + 1 < path.size(); x ++){
// Seg_array temp = find_path_between_intersections(path[x], path[x+1], turn_penalty);
// seg_path.insert(seg_path.end(), temp.begin(), temp.end());
// }
//
// return seg_path;
//
//}
//
//double calculate_path_distance_helper(const I_array path) {
// double distance = 0;
//
// //for loop going through all the points in the path and calculating the total distance in the array
// for (unsigned i = 0; i + 1 < path.size(); i++) {
// distance += calculate_points_distance_helper(path[i], path[i + 1]);
// }
//
// return distance;
//}
//
//double calculate_points_distance_helper(IntersectionIndex i, IntersectionIndex j) {
// LatLon start, end;
//
// start = getIntersectionPosition(i);
// end = getIntersectionPosition(j);
//
// if (i == j) {
// return 0;
// }
//
// return find_distance_between_two_points(start, end);
//}
| true |
6d927a1301414c25ca6c05a482f375f2e2ba746e | C++ | royyjzhang/leetcode_cpp | /189_RotateArray.cpp | UTF-8 | 844 | 3.015625 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<queue>
#include<stdlib.h>
#include<string>
#include<algorithm>
#include<map>
#include<math.h>
using namespace std;
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int len = nums.size();
if (len == 0)
return;
int maxindex = k % len, j, value, tmp, next;
for (int i = 0; i < maxindex; i++) {
j = i;
value = nums[j];
do {
next = (j + k) % len;
tmp = nums[next];
nums[next] = value;
value = tmp;
if ((next < maxindex) && (next != i))
maxindex = next;
j = next;
} while (j != i);
}
}
};
int main() {
vector<int> nums = { 1, 2, 3, 4, 5, 6, 7, 8 };
int k = 3;
Solution v;
v.rotate(nums,k);
for (int i = 0; i < nums.size(); i++)
cout << nums[i] << " ";
system("PAUSE");
return 0;
} | true |
43ef523eb55d92bc66f656500f9766ed3a3fc74b | C++ | Luiz6ustav0/competitiveProgramming | /codeforces/632A.cpp | UTF-8 | 731 | 2.75 | 3 | [] | no_license | #include <bits/stdc++.h>
#define _ \
ios_base::sync_with_stdio(0); \
cin.tie(0);
int main() {
int numberOfTests = 0;
int lines = 0, columns = 0;
std::cin >> numberOfTests;
char black = 'B', white = 'W';
for (int i = 0; i < numberOfTests; ++i) {
std::cin >> lines >> columns;
for (int inside_i = 0; inside_i < lines - 1; ++inside_i) {
for (int inside_j = 0; inside_j < columns; inside_j++) {
std::cout << black;
}
std::cout << std::endl;
}
for (int lastLine = 0; lastLine < columns - 1; lastLine++) {
std::cout << black;
}
std::cout << white << std::endl;
}
}
| true |
3d4807bea8bb59fd25343a41435954c6ae124ad6 | C++ | eshamidi/2010_CS | /carRental/car rental.cpp | UTF-8 | 465 | 2.84375 | 3 | [] | no_license | //Car Rental 9/8
#include <iostream.h>
#include <apstring.h>
main()
{
apstring make, model;
//Make and Model
cout<< "Enter in the model and make of your car.\n"
<<"Make:";
cin>> make;
cout<< "Model:";
cin>> model;
//License Plate Code
char c1,c2,c3;
long num1;
cout<< "Enter in the license plate of your car.\n";
cin>> c1,c2,c3, num1;
//Run Output
cout<<make<<endl;
cout<<model;
cout<< long (c1+c2+c3);
return 0;
}
//incomplete -5 | true |
befb7c156d9f66052b8114a2ec90fdaab905a98e | C++ | runngezhang/sword_offer | /sword_offer/cpp/36_两个链表的第一个公共结点.cpp | UTF-8 | 2,691 | 3.65625 | 4 | [] | no_license | #include <iostream>
#include <map>
#include <stdio.h>
#include <sys/time.h>
#include "ListNode.h"
#include "my_vector.h"
/*
typedef struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
} ListNode;
*/
class Solution {
public:
// 1. hash方式
// 时间复杂度O(n + m),空间复杂度O(n)
ListNode* FindFirstCommonNode(ListNode* h1, ListNode* h2) {
if (h1 == nullptr || h2 == nullptr) {
return nullptr;
}
std::map<ListNode*, int> map;
while (h1) {
map[h1] = h1->val;
h1 = h1->next;
}
while (h2) {
if (map.count(h2) == 1) {
return h2;
}
h2 = h2->next;
}
return nullptr;
}
// 2. 循环法,高效的迭代方式
// 时间复杂度O(n + m),空间复杂度O(1)
ListNode* FindFirstCommonNode2(ListNode* h1, ListNode* h2) {
ListNode* t1 = h1;
ListNode* t2 = h2;
while (t1 != t2) {
t1 = (t1 == nullptr ? h2 : t1->next);
t2 = (t2 == nullptr ? h1 : t2->next);
}
return t1;
}
// 测试函数
// 输入两个vec,分别构建链表,将vec2链接到vec1的中点位置
void test(std::vector<int>& data1, std::vector<int>& data2) {
struct timeval start, end;
ListNode* result = nullptr;
// 构建链表
ListNode* head1 = ListNode_creatFromVec(data1);
ListNode* head2 = ListNode_creatFromVec(data2);
ListNode* tail2 = ListNode_getLastNode(head2);
tail2->next = ListNode_getMiddleNode(head1);
printf("=====\n");
for (auto & func : this->func_vec_) {
gettimeofday(&start, nullptr);
result = (this->*func)(head1, head2);
gettimeofday(&end, nullptr);
printf("result: %d, times(us): %ld\n", result->val, end.tv_usec - start.tv_usec);
}
// 注意释放head2之前需要处理尾部的野指针
tail2->next = nullptr;
ListNode_clear(head1);
ListNode_clear(head2);
}
private:
typedef ListNode* (Solution::*func_ptr)(ListNode*, ListNode*);
std::vector<func_ptr> func_vec_ = {&Solution::FindFirstCommonNode,
&Solution::FindFirstCommonNode2};
};
int main(int argc, char* argv[])
{
std::vector<int> data1 = {1, 2, 4, 8, 2, 9, 6};
std::vector<int> data2 = {4, 6, 9};
std::vector<int> data3 = vector_CreatRandom(1, 1000, 1000);
std::vector<int> data4 = vector_CreatRange(1, 100);
Solution s;
s.test(data1, data2);
s.test(data3, data4);
return 0;
} | true |
11782725650475bc53360ea6a043d9a6feab2a6d | C++ | wzAdmin/Graph | /WoodHome/UIFrame/EffectFactory.cpp | UTF-8 | 929 | 2.53125 | 3 | [] | no_license | #include "EffectFactory.h"
#include "Trace.h"
#include "EffectFadeto.h"
CEffectFactory::CEffectFactory(void)
{
Register(Effect_FadeTo, CEffectFadeto::Create);
}
CEffectFactory::~CEffectFactory(void)
{
}
bool CEffectFactory::Register( EffectType effect , CreateFunc func )
{
CreaterIt it = mCreaterMap.find(effect);
if(mCreaterMap.end() != it)
{
DebugTrace(Trace_Warning,"CEffectFactory::Register fail %d is exsited\n",effect);
return false;
}
else
{
mCreaterMap.insert(CreaterPair(effect, func));
return true;
}
}
CSceneEffect* CEffectFactory::CreateEffect( EffectType effect , IEffectListner* listner , int interval , int Frames ,CGraphics* pGraphic )
{
CreaterIt it = mCreaterMap.find(effect);
if(mCreaterMap.end() != it)
{
return (*it->second)(listner,interval,Frames,pGraphic);
}
else
{
DebugTrace(Trace_Error,"CEffectFactory::CreateEffect fail %d is not exsited\n",effect);
return NULL;
}
}
| true |
cb63118649368b51e91ac337bc72ab1c1ed54806 | C++ | alaminbhuyan/CPP-Programming | /OPARETOR/Tarnary operator/Untitled1.cpp | UTF-8 | 172 | 2.890625 | 3 | [] | no_license | #include<iostream>
#include<string>
using namespace std;
int main()
{
int num = 18;
string result = (num<20) ? "Good morning" : "Good evening";
cout<<result;
}
| true |
888731621528bf1307bce3ed16b409c0b2d66c1a | C++ | sikotidis/SmartGridMarket | /SmartGridMarket/Producer.h | UTF-8 | 1,517 | 2.890625 | 3 | [] | no_license | #pragma once
#ifndef PRODUCER_H
#define PRODUCER_H
#include <thread>
#include "Bank.h"
#include "Energy.h"
class Producer : public Bank{ // Producer inherits from Bank
private:
std::thread producer_thread;
int type;
int id; // Producer id
int credits; // Credits a producer has
int time;
float Producer::getEnergyAmmount();
float Producer::getEnergyPrice();
float getEnergyTotalCost(int energy_ammount);
std::string period_of_day();
public:
void startThread();
struct time_date{
int hour, minute, second;
};
struct energy_node{
int energy_ammount;
int energy_cost;
};
struct producer_energy_profile{
int id;
bool expired;
energy_node ammount_price;
//time_date time_produced;
};
static int producers_counter;
static int producer_counter_list;
std::vector<producer_energy_profile> producer_buffer;
void Producer::send_energy(int consumer_id, int producer_id);
Producer(); // Default Constructor
Producer(int credits, int type); // Constructor
~Producer(); // Destructor
int getId();
int getCredits();
int getType();
void printCredits();
void setEnergyProductionCost();
int getDayAvailable(int timeYear);
int getTimeAvailableFrom(int timeMinut);
int getTimeAvailableUntil(int timeAvailableFrom);
bool nowOrLater();
float getProducedEnergy();
void startProducer(int timeMinut, int timeYear);
//friend void broker_agent(Producer &broker); // broker_agent function can use methods of Produce class
};
#endif | true |
e5ca3bb5a9176a57b3725363f87ff91778f31ffe | C++ | NeymarL/LeetCode | /1007-1013/#24 Swap Nodes in Pairs.cpp | UTF-8 | 1,191 | 3.859375 | 4 | [] | no_license | /**
* #24 Swap Nodes in Pairs
* https://leetcode.com/problems/swap-nodes-in-pairs/
*
* Given a linked list, swap every two adjacent nodes and return its head.
*
* Example:
*
* Given 1->2->3->4, you should return the list as 2->1->4->3.
*
* Note:
* Your algorithm should use only constant extra space.
* You may not modify the values in the list's nodes, only nodes itself may be changed.
*/
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* swapPairs(ListNode* head)
{
if (!head) {
return NULL;
}
ListNode *pre = NULL, *p = head, *q = head->next, *next = NULL;
while (p) {
q = p->next;
if (q) {
next = q->next;
if (pre) {
pre->next = q;
} else {
head = q;
}
p->next = next;
q->next = p;
} else {
break;
}
pre = p;
p = next;
}
return head;
}
};
| true |
c06e31cbe1ea77f2c512f31c3688c79bedf1e7e7 | C++ | HimanshuGunjal10/CPP-Programs | /LeetCode/Tag-Hash/1078. Occurrences After BigramNOTOPTIMIZED.cpp | UTF-8 | 1,141 | 3.484375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <unordered_map>
using namespace std;
{
stringstream ss(text);
string prev2,prev1,curr;
vector<string> res;
while(ss >> curr)
{
if(prev2 == first && prev1== second)
res.push_back(curr);
prev2 = prev1;
prev1 = curr;
}
return res;
}
/*
vector<string> findOcurrences(string text, string first, string second)
{
stringstream ss(text);
string temp;
vector<string> vec_str;
while(ss >> temp)
vec_str.push_back(temp);
//why do ++it and then go reverse
//just check on the 3rd word and keep saing the prev words
//also no need to push into a vector! just work on temp
vector<string> res;
for(vector<string>::iterator it=vec_str.begin();it!=vec_str.end()-1;it++)
{
if(*it == first)
{
if(*(++it) == second)
{
if( ++it !=vec_str.end())
{
res.push_back(*it);
}
--it;
}
--it;
}
}
return res;
}
*/
int main()
{
string text = "hello there how are you";
vector<string> res = findOcurrences(text,"are","me");
for(string i : res)
cout << i << " ";
cout << endl;
cout << endl << "La Fin!!";
}
| true |
1255bf1b0ef3377fc810a098df2c85187f770e2d | C++ | shubhendra/HyperMarketInventory | /Jobs.cpp | UTF-8 | 4,867 | 3.03125 | 3 | [] | no_license | #include "Jobs.h"
Jobs::Jobs(){}
Jobs::Jobs(string _code)
{
code=_code;
}
string Jobs::getjobcode()
{
return code;
}
bool Jobs::readjobDetails(ifstream *readFile)
{
if( code == "ADD")
{
job_add(readFile);
return true;
}
else if(code == "DELETE")
{
job_delete(readFile);
return true;
}
else if(code == "RESTOCK")
{
job_restock(readFile);
return true;
}
else if(code == "DISPOSE")
{
job_dipose(readFile);
return true;
}
else if(code == "SALE")
{
job_sale(readFile);
return true;
}
else
return false;
}
void Jobs::job_add(ifstream* readFile){
string DUMMY;
getline(*readFile,product_name);
getline(*readFile,product_category);
*readFile >> product_barcode;
getline(*readFile,DUMMY);
*readFile >> product_price;
getline(*readFile,DUMMY);
getline(*readFile, product_manufacturer);
*readFile >> product_stock;
getline(*readFile,DUMMY);
}
void Jobs::job_delete(ifstream* readFile){
getline(*readFile, product_barcode);
}
void Jobs::job_restock(ifstream* readFile){
string DUMMY;
*readFile >> product_barcode;
getline(*readFile,DUMMY);
*readFile >> product_stock;
getline(*readFile,DUMMY);
}
void Jobs::job_dipose(ifstream* readFile){
string DUMMY;
*readFile >> product_barcode;
getline(*readFile,DUMMY);
getline(*readFile, cur_date);
}
void Jobs::job_sale(ifstream* readFile){
string DUMMY;
*readFile >> product_barcode;
getline(*readFile,DUMMY);
*readFile >> product_sales;
getline(*readFile,DUMMY);
}
bool Jobs::job_exec(ListBase<Product>* List)
{
if( code == "ADD")
return exec_add(List);
else if(code == "DELETE")
return exec_delete(List);
else if(code == "RESTOCK")
return exec_restock(List);
else if(code == "DISPOSE")
return exec_dipose(List);
else if(code == "SALE")
return exec_sale(List);
else
return false;
}
bool Jobs::exec_add(ListBase<Product>* List)
{
AddProduct Batch_add;
Search Search_Barcode;
ListBase<Product>* Result= new ListDA<Product>();
Search_Barcode.ByBarcode(List, product_barcode, Result);
if(!Result->isEmpty())
{
//cout<<"Barcode already exist!"<<endl;
delete Result;
return false;
}
else
{ delete Result;
return Batch_add.addProduct(List, product_name, product_category, product_barcode, product_manufacturer, product_price, product_stock, 0);
}
}
bool Jobs::exec_delete(ListBase<Product>* List)
{
//string product_barcode;
DeleteProduct Batch_delete;
Search Search_Barcode;
ListBase<Product>* Result= new ListDA<Product>();
// Search_Barcode.ByBarcode(List, product_barcode, Result);
//cout<<List->getLength();
if(!Search_Barcode.ByBarcode(List, product_barcode, Result))
{
//cout<<"Barcode does not exist!"<<endl;
delete Result;
return false;
}
else
{
bool success= Batch_delete.delete_function(List, Result->retrieveItem(0));
delete Result;
return success;
}
}
bool Jobs::exec_restock(ListBase<Product>* List)
{
Restock Batch_restock;
Search Search_Barcode;
ListBase<Product>* Result= new ListDA<Product>();
//Search_Barcode.ByBarcode(List, product_barcode, Result);
if(!Search_Barcode.ByBarcode(List, product_barcode, Result))
{
//cout<<"Barcode does not exist!"<<endl;
delete Result;
return false;
}
else
{
bool success= Batch_restock.restock_function(Result, 0 , product_stock);
delete Result;
return success;
}
return true;
}
bool Jobs::exec_dipose(ListBase<Product>* List)
{
CheckExpiry Batch_checkexpiry;
Search Search_Barcode;
ListBase<Product>* Result= new ListDA<Product>();
//Search_Barcode.ByBarcode(List, product_barcode, Result);
if(!Search_Barcode.ByBarcode(List, product_barcode, Result))
{
//cout<<"Barcode does not exist!"<<endl;
delete Result;
return false;
}
else
{
int result;
result=Batch_checkexpiry.check_manual(Result,0,cur_date);
switch (result)
{
case 1:
//cout<<"Product not yet expired."<<endl;
delete Result;
return true;
break;
case 0:
{
//cout<<"Product expired."<<endl;
Restock Batch_restock;
bool success= Batch_restock.restock_function(Result, 0 , -Result->retrieveItem(0)->get_stock());
delete Result;
return success;
break;
}
case -1:
//cout<<"Not a perishable product"<<endl;
delete Result;
return false;
break;
default:
delete Result;
return false;
}
}
}
bool Jobs::exec_sale(ListBase<Product>* List)
{
Sales Batch_sales;
Search Search_Barcode;
ListBase<Product>* Result= new ListDA<Product>();
//Search_Barcode.ByBarcode(List, product_barcode, Result);
if(!Search_Barcode.ByBarcode(List, product_barcode, Result))
{
//cout<<"Barcode does not exist!"<<endl;
delete Result;
return false;
}
else
{
bool success= Batch_sales.sale_function(Result,0,product_sales);
delete Result;
return success;
}
}
string Jobs::retrieveErrorMsgs()
{
string status;
status=product_barcode+" "+code+" ";
return status;
} | true |
75899a5d2b2cd50270b5c6a51bfee3dce61732ad | C++ | chenmin1116/my_data_struct | /stack_and_queue/DoubleQueue_To_Stack.h | GB18030 | 1,841 | 4.3125 | 4 | [] | no_license | //ʹʵһջ
//ջȽУȽȳ
#pragma once
#include<iostream>
#include<queue>
using namespace std;
template<class T>
class Stack
{
private:
queue<T> queue1;
queue<T> queue2;
public:
void Push(const T& node)
{
if(queue1.empty() == true && queue2.empty() == true)//оΪʱ,ݵʱѡqueue1
{
queue1.push(node);
}
else
{
if(queue1.empty() == true && queue2.empty() == false)//queue1Ϊգqueue2Ϊգ
{
queue2.push(node);
}
if(queue1.empty() == false && queue2.empty() == true)
{
queue1.push(node);
}
}
}
void Pop()
{
//queue1queue2Ϊʱ
if(queue1.empty() == true && queue2.empty() == true)
{cout<<"ջΪգд˲"<<endl;return;}
//queue1Ϊʱ:queue2еβqueue1Уҽqueue2еǰn-1pop();
//һpopɳջ
if(queue1.empty() == true && queue2.empty() == false)
{
while(queue2.size()-1 > 0)
{
queue1.push(queue2.front());
queue2.pop();
}
queue2.pop();
return;
}
if(queue1.empty() == false && queue2.empty() == true)
{
while(queue1.size()-1 > 0)
{
queue2.push(queue1.front());
queue1.pop();
}
queue1.pop();
return;
}
}
};
void DoubleQueue_To_Stack()
{
Stack<int> stack1;
stack1.Push(1); //ڿջв
stack1.Push(2);//ڷǿջв
stack1.Push(3);
stack1.Push(4);//1 2 3 4ڿջIJ
stack1.Pop();//1 2 3//ڷǿջгջ
stack1.Pop();//1 2
stack1.Pop();//1
stack1.Pop();//ڿջջֱջΪգ
stack1.Pop();//ڿջгջ
} | true |
7b77ca66fed2bbf7087842229ae01b53d999fc37 | C++ | boschglobal/iceoryx | /iceoryx_hoofs/include/iceoryx_hoofs/internal/relocatable_pointer/relative_pointer.hpp | UTF-8 | 4,574 | 2.515625 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-generic-export-compliance",
"BSD-3-Clause",
"EPL-2.0",
"MIT"
] | permissive | // Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// 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.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_HOOFS_RELOCATABLE_POINTER_RELATIVE_POINTER_HPP
#define IOX_HOOFS_RELOCATABLE_POINTER_RELATIVE_POINTER_HPP
#include "base_relative_pointer.hpp"
#include <cstdint>
#include <iostream>
#include <limits>
namespace iox
{
namespace rp
{
/// @brief typed version so we can use operator->
template <typename T>
class RelativePointer : public BaseRelativePointer
{
public:
/// @brief constructs a RelativePointer pointing to the same pointee as ptr in a segment identified by id
/// @param[in] ptr the pointer whose pointee shall be the same for this
/// @param[in] id is the unique id of the segment
RelativePointer(ptr_t ptr, id_t id) noexcept;
/// @brief constructs a RelativePointer from a given offset and segment id
/// @param[in] offset is the offset
/// @param[in] id is the unique id of the segment
RelativePointer(offset_t offset, id_t id) noexcept;
/// @brief constructs a RelativePointer pointing to the same pointee as ptr
/// @param[in] ptr the pointer whose pointee shall be the same for this
RelativePointer(ptr_t ptr = nullptr) noexcept;
/// @brief creates a RelativePointer from a BaseRelativePointer
/// @param[in] other is the BaseRelativePointer
RelativePointer(const BaseRelativePointer& other) noexcept;
/// @brief assign this to point to the same pointee as the BaseRelativePointer other
/// @param[in] other the pointer whose pointee shall be the same for this
/// @return reference to self
RelativePointer& operator=(const BaseRelativePointer& other) noexcept;
/// @brief assigns the RelativePointer to point to the same pointee as ptr
/// @param[in] ptr the pointer whose pointee shall be the same for this
/// @return reference to self
RelativePointer& operator=(ptr_t ptr) noexcept;
/// @brief dereferencing operator which returns a reference to the underlying object
/// @tparam U a template parameter to enable the dereferencing operator only for non-void T
/// @return a reference to the underlying object
template <typename U = T>
typename std::enable_if<!std::is_void<U>::value, U&>::type operator*() noexcept;
/// @brief access to the underlying object
/// @return a pointer to the underlying object
T* operator->() noexcept;
/// @brief dereferencing operator which returns a const reference to the underlying object
/// @tparam U a template parameter to enable the dereferencing operator only for non-void T
/// @return a const reference to the underlying object
template <typename U = T>
typename std::enable_if<!std::is_void<U>::value, const U&>::type operator*() const noexcept;
/// @brief read-only access to the underlying object
/// @return a const pointer to the underlying object
T* operator->() const noexcept;
/// @brief access the underlying object
/// @return a pointer to the underlying object
T* get() const noexcept;
/// @brief converts the RelativePointer to a pointer of the type of the underlying object
/// @return a pointer of type T pointing to the underlying object
operator T*() const noexcept;
/// @brief checks if this and ptr point to the same pointee
/// @param[in] ptr is the pointer whose pointee is compared with this' pointee
/// @return true if the pointees are equal, otherwise false
bool operator==(T* const ptr) const noexcept;
/// @brief checks if this and ptr point not to the same pointee
/// @param[in] ptr is the pointer whose pointee is compared with this' pointee
/// @return true if the pointees are not equal, otherwise false
bool operator!=(T* const ptr) const noexcept;
};
} // namespace rp
} // namespace iox
#include "iceoryx_hoofs/internal/relocatable_pointer/relative_pointer.inl"
#endif // IOX_HOOFS_RELOCATABLE_POINTER_RELATIVE_POINTER_HPP
| true |
5741265362ca1e10f907f571cc15a9d13b99502d | C++ | avmal0-Cor/xr2-dsgn | /xr2-dsgn/sources/xray/maya_animation/sources/sisl/s1940.cpp | UTF-8 | 18,421 | 2.796875 | 3 | [] | no_license | #include "pch.h"
#define S1940
#include "sislP.h"
#if defined(SISLNEEDPROTOTYPES)
void
s1940(SISLCurve *oldcurve, sisl_double eps[], int startfix, int endfix, int iopen,
int itmax, SISLCurve **newcurve, sisl_double maxerr[],
int *stat)
#else
void
s1940(oldcurve, eps, startfix, endfix, iopen, itmax, newcurve,
maxerr, stat)
SISLCurve *oldcurve;
sisl_double eps[];
int startfix;
int endfix;
int iopen;
int itmax;
SISLCurve **newcurve;
sisl_double maxerr[];
int *stat;
#endif
/*
*********************************************************************
*
*********************************************************************
*
* Purpose: To remove as many knots as possible from the spline curve
* "oldcurve" without perturbing the curve more than a given
* tolerance. The tolerance is given by "eps" and the
* approximation by "newcurve".
*
*
* Input:
* oldcurve - pointer to the original spline curve.
*
* eps - sisl_double array giving the desired absolute accuracy
* of the final approximation as compared to oldcurve.
* If oldcurve is a spline curve in a space of
* dimension dim, then eps must have length dim.
* Note that it is not relative, but absolute accuracy
* that is being used. This means that the difference
* in component i at any parameter value, between
* the given curve and the approximation, is to be
* less than eps[i]. Note that in such comparisons
* the same parametrization is used for both curves.
*
* startfix - the number of derivatives to be kept fixed at
* the beginning of the knot interval.
* The (0 - (startfix-1)) derivatives will be kept fixed.
* If startfix <0, this routine will set it to 0.
* If startfix< the order of the curve, this routine
* will set it to the order.
*
* endfix - the number of derivatives to be kept fixed at
* the end of the knot interval.
* The (0 - (endfix-1)) derivatives will be kept fixed.
* If endfix <0, this routine will set it to 0.
* If endfix< the order of the curve, this routine
* will set it to the order.
*
* iopen - Open/closed parameter.
* = 1 : Produce open curve.
* = 0 : Produce closed, non-periodic curve if possible.
* = -1 : Produce closed, periodic curve if possible.
*
* itmax - maximum number of iterations. The routine will
* follow an iterative procedure trying to remove
* more and more knots. The process will almost always
* stop after less than 10 iterations and it will often
* stop after less than 5 iterations. A suitable
* value for itmax is therefore usually in the region
* 3-10.
*
*
*
*
* Output:
* newcurve - the spline approximation on the reduced
* knot vector.
* maxerr - sisl_double array containing an upper bound for the
* pointwise error in each of the components of the
* spline approximation. The two curves oldcurve and
* newcurve are compared at the same parameter value,
* i.e., if oldcurve is f and newcurve is g, then
* |f(t)-g(t)| <= eps
* in each of the components.
*
* stat - status message
* > 0 : warning
* = 0 : ok
* < 0 : error
*
*
*
*
* Method:
* The method is described in two papers listed as references below.
* First, the knots of the input spline, s, are ranked according to their
* relative importance in the representation of s (s1353). Using this
* information, knots are removed from s and an approximation g is computed
* on the reduced knot vector (s1950) with the error guaranteed to be
* less than the tolerance in all components. In order to remove more knots,
* the knots of g are ranked, and then knots are removed from g, resulting
* in a spline h with even fewer knots. The knot vector of h is then
* clearly a subsequence of the knot vector of s and s is approximated
* on this knot vector (s1943). If the error is less than the tolerance
* then h is accepted as the new best approximation and stored in g.
* If the error is greater than the tolerance, knots are removed directly
* from s based on the ranking of g resulting in a new g. In either case a
* new best approximation g is obtained, and we can continue the iteration.
* The iterations stop when no more knots can be removed or all the interior
* knots have been removed. (The names s, g, and h are not used in the
* code.)
*
* NB! The iopen parameter will be satisfyed only if the original curve
* provides the possibility for it. For instance if the original curve
* is open, and a closed curve is expected, this will in general not be
* possible.
*
*
* References:
* 1. A Data-Reduction Strategy for Splines with Applications to the
* Approximation of Functions and data, IMA J. of Num. Anal. 8 (1988),
* pp. 185-208.
*
* 2. Knot Removal for Parametric B-spline Curves and Surfaces,
* CAGD 4 (1987), pp. 217-230.
*
*
* Calls: s1353, s1712, s1950, s1943, s6err
*
* Written by: Knut Moerken, University of Oslo, November 1992, based
* on an earlier Fortran version by the same author.
* CHANGED BY: Paal Fugelli, SINTEF, 1994-07. Initialized pointers (to SISL_NULL)
* in 'ranking' to avoid potential memory leak when exiting through 'out'.
* Removed several other memory leaks.
* CHANGED BY: Per OEyvind Hvidsten, SINTEF, 1994-11. Added a freeCurve
* call before overwriting the *newarray pointer (thus removing a
* memory leak.
* Changed by : Vibeke Skytt, SINTEF Oslo, 94-12. Introduced periodicity.
*
*********************************************************************
*/
{
char ready, big; /* Boolean variables used for computing
the stopping criteria. */
int k = oldcurve->ik; /* Unwrapped version of the given curve. */
int dim = oldcurve->idim;
sisl_double *d = oldcurve->ecoef;
int itcount=0; /* Iteration counter. */
int n1 = oldcurve->in; /* n1 and n2 are used for storing the number
coefficients in consecutive spline
approximations. The situation n1=n2
signifies that no more knots can be
removed. */
int n2;
int i, mini, maxi, indx; /* Various auxiliary integer variables. */
int kncont = 0; /* Number of continuity requirements over
the seem of a closed curve. */
sisl_double *local_err = SISL_NULL; /* Variables used for storing local error
estimates. */
sisl_double *l2err = SISL_NULL;
sisl_double *lepsco = SISL_NULL;
sisl_double *temp_err = SISL_NULL;
SISLCurve *tempcurve = SISL_NULL; /* Variables that are used for storing
temporary curves. */
SISLCurve *helpcurve = SISL_NULL;
rank_info ranking; /* Variable used for holding ranking
information (from s1353). */
int lstat=0; /* Local status variable. */
int pos=0; /* Parameter to s6err. */
SISLCurve *qc_kreg = SISL_NULL; /* Non-periodic version of the input curve. */
SISLCurve *qcpart = SISL_NULL; /* Curve representing a Bezier segment. */
/* Initialize ranking ptrs in case of early exit through 'out' (PFU 05/07-94) */
ranking.prio = SISL_NULL;
ranking.groups = SISL_NULL;
/* Initialize maxerr to zero. */
for (i=0; i<dim; i++) maxerr[i] = DZERO;
/* Only interior knots may be removed so if n1==k we can stop
straight away. */
if (n1 == k)
{
*newcurve = newCurve(n1, k, oldcurve->et, oldcurve->ecoef,
oldcurve->ikind, oldcurve->idim, 1);
if (*newcurve == SISL_NULL) goto err101;
*stat = 0;
goto out;
}
/* Make sure that the input curve is non-periodic. */
if (oldcurve->cuopen == SISL_CRV_PERIODIC)
{
/* First count continuity at the seem. */
for (i=oldcurve->ik-1; i>0; i--)
if (DNEQUAL(oldcurve->et[i-1], oldcurve->et[i])) break;
kncont = i;
make_cv_kreg(oldcurve, &qc_kreg, &lstat);
if (lstat < 0) goto error;
}
else
{
qc_kreg = newCurve(oldcurve->in, oldcurve->ik, oldcurve->et,
oldcurve->ecoef, oldcurve->ikind, oldcurve->idim, 1);
if (qc_kreg == SISL_NULL) goto err101;
}
/* Ensure closed output curve if the input curve is closed. */
if (oldcurve->cuopen == SISL_CRV_CLOSED)
kncont = 1;
/* Allocate space for some local arrays. */
temp_err = newarray(dim, sisl_double);
if (temp_err == SISL_NULL) goto err101;
lepsco = newarray(dim, sisl_double);
if (lepsco == SISL_NULL) goto err101;
local_err = newarray(dim, sisl_double);
if (local_err == SISL_NULL) goto err101;
l2err = newarray(dim, sisl_double);
if (l2err == SISL_NULL) goto err101;
/* ranking is of type rank_info which is a struct described in s1353. */
ranking.prio = newarray(n1, int);
if (ranking.prio == SISL_NULL) goto err101;
ranking.groups = newarray(n1, int);
if (ranking.groups == SISL_NULL) goto err101;
/* lespco is needed in s1950. In component i we first store the l1-norm
of the component i of the B-spline coefficients of oldcurve. */
for (i=0; i<dim; i++) lepsco[i] = fabs(d[i]);
indx = 0;
for (i=1; i<n1*dim; i++)
{
lepsco[indx++] += fabs(d[i]);
if (indx == dim) indx = 0;
}
/* We can now compute the final value of lepsco which will be used for
checking if two numbers are almost equal. */
for (i=0; i<dim; i++)
lepsco[i] = MIN(lepsco[i]*REL_COMP_RES/n1, eps[i]);
/* This is where the knot removal process starts. */
/* mini and maxi are lower and upper bounds on how many knots that can
be removed. */
mini = 0;
maxi = n1 - k + 1;
/* Start by ranking the knots of oldcurve. First make a help curve where
the first Bezier segment of the original curve is repeated at the
end of the curve. */
/* Pick first segment of original curve. */
s1712(qc_kreg, qc_kreg->et[k-1], qc_kreg->et[k], &qcpart, &lstat);
if (lstat < 0) goto error;
/* Adjust qc_kreg in order to store the extra Bezier segment. */
if ((qc_kreg->ecoef = increasearray(qc_kreg->ecoef, (n1+k)*dim, sisl_double))
== SISL_NULL) goto err101;
if ((qc_kreg->et = increasearray(qc_kreg->et, n1+k+k, sisl_double)) == SISL_NULL)
goto err101;
memcopy(qc_kreg->ecoef+n1*dim, qcpart->ecoef, k*dim, sisl_double);
for (i=0; i<k; i++)
qc_kreg->et[n1+k+i] = qc_kreg->et[n1+i] + qcpart->et[k+i] - qcpart->et[i];
qc_kreg->in += k;
/* Remove memory occupied by the curve describing the Bezier segment. */
if (qcpart != SISL_NULL) freeCurve(qcpart);
qcpart = SISL_NULL;
/* Perform ranking. */
s1353(qc_kreg, eps, &ranking, &lstat);
if (lstat < 0) goto error;
/* Based on the computed ranking, we remove as close to maxi knots
from oldcurve as possible, but such that we can always compute an
approximation to oldcurve on the reduced knot vector, with error less
than eps. newcurve will be created with icopy==1. */
/* First reset the size of qc_kreg. This routine operates on the
original (non-periodic) input curve. */
qc_kreg ->in -= k;
s1950(qc_kreg, qc_kreg, &ranking, eps, lepsco, startfix, endfix, &kncont,
mini, maxi, newcurve, maxerr, &lstat);
if (lstat < 0) goto error;
/* The spline stored in newcurve is now an approximation to oldcurve
with error less than eps. We will now iterate and try to remove knots
from newcurve. The integers n1 and n2 will be the number of knots in
the two most recent approximations. */
n2 = (*newcurve)->in;
/* Start the iterations. We have already done one iteration and we have
not had any problems with the error getting too big. */
itcount = 1;
big = 0;
/* If n1=n2 we are unable to remove any knots, and if n2=k there are
no interior knots left so we can stop. Likewise if itmax was 1. */
ready = (n1 == n2) || (n2 == k) || (itcount == itmax);
while (!ready)
{
/* We start by ranking the knots of newcurve which is the approximation
with the fewest knots that we have found so far. */
/* Pick first segment of newcurve curve. */
s1712(*newcurve, (*newcurve)->et[k-1], (*newcurve)->et[k],
&qcpart, &lstat);
if (lstat < 0) goto error;
/* Adjust *newcurve in order to store the extra Bezier segment. */
if (((*newcurve)->ecoef = increasearray((*newcurve)->ecoef, (n2+k)*dim, sisl_double))
== SISL_NULL) goto err101;
if (((*newcurve)->et = increasearray((*newcurve)->et, n2+k+k, sisl_double)) == SISL_NULL)
goto err101;
memcopy((*newcurve)->ecoef+n2*dim, qcpart->ecoef, k*dim, sisl_double);
for (i=0; i<k; i++)
(*newcurve)->et[n2+k+i] = (*newcurve)->et[n2+i] + qcpart->et[k+i] - qcpart->et[i];
(*newcurve)->in += k;
/* Remove memory occupied by the curve describing the Bezier segment. */
if (qcpart != SISL_NULL) freeCurve(qcpart);
qcpart = SISL_NULL;
/* Ranking. */
s1353(*newcurve, eps, &ranking, &lstat);
if (lstat < 0) goto error;
/* Reset size of *newcurve. */
(*newcurve)->in -= k;
if (!big)
{
/* If we have not had any problems with the error in approximation
becoming too big we take the risk of removing as many knots as
we can from newcurve and in this way determining an even shorter
knot vector.
First we iterate in s1950 to see how many knots we can remove
and store the approximation to newcurve in helpcurve (will be
created with icopy==1). */
mini = 0; maxi = (*newcurve)->in - k + 1;
s1950(*newcurve, *newcurve, &ranking, eps, lepsco, startfix,
endfix, &kncont, mini, maxi, &helpcurve, temp_err, &lstat);
if (lstat < 0) goto error;
/* Now, we have no guarantee that helpcurve is closer to oldcurve
than the tolerance so we compute a new approximation to oldcurve
on the knot vector of helpcurve and store this in tempcurve (with
icopy==1).
Must make sure that local_err is free'ed if allocated from last
iteration. */
s1943(qc_kreg, helpcurve->et, k, helpcurve->in,
startfix, endfix, kncont, &tempcurve,
local_err, l2err, &lstat);
if (lstat < 0) goto error;
/* Don't need helpcurve anymore. */
freeCurve(helpcurve);
helpcurve = SISL_NULL;
/* We must now check if the new tempcurve is within the tolerance. */
i = 0;
while (!big && i<dim)
{
big = local_err[i] > eps[i];
i++;
}
}
else
/* If we have had problems with the error becoming greater than the
tolerance, we simply store newcurve in tempcurve and proceed. */
tempcurve = *newcurve;
if (big)
{
/* If at some stage we have had problems with the error becoming
larger than the tolerance, we do not get involved in the risky
approach of removing knots from newcurve. Instead we throw away
tempcurve and remove knots directly from oldcurve, but remember
that the only knots left to remove are the knots of newcurve for
which we use the ranking computed above. The result is stored
in helpcurve and later transferred to newcurve. */
mini= 0; maxi = tempcurve->in - k + 1;
s1950(qc_kreg, *newcurve, &ranking, eps, lepsco, startfix,
endfix, &kncont, mini, maxi, &helpcurve, maxerr, &lstat);
if (lstat < 0) goto error;
if (*newcurve != SISL_NULL && *newcurve != tempcurve)
{
freeCurve(*newcurve);
*newcurve = SISL_NULL;
}
if (tempcurve != SISL_NULL)
{
freeCurve(tempcurve);
tempcurve = SISL_NULL;
}
*newcurve = helpcurve;
helpcurve = SISL_NULL;
}
else
{
/* Since we now know that the difference between oldcurve and tempcurve
is within the tolerance, we just have to store the error in maxerr,
throw away the old newcurve, and store tempcurve in newcurve. */
for (i=0; i<dim; i++) maxerr[i] = local_err[i];
if (*newcurve != SISL_NULL) freeCurve(*newcurve);
*newcurve = tempcurve;
tempcurve = SISL_NULL;
}
/* Now we must check if it is time to stop. */
n1 = n2;
n2 = (*newcurve)->in;
++itcount;
ready = (n1 == n2) || (n2 == k) || (itcount == itmax);
}
/* Set periodicity flag. */
if (iopen == SISL_CRV_PERIODIC && kncont > 0)
{
/* Make the curve periodic. */
s1941(*newcurve, MIN(k-2,kncont-1), &lstat);
if (lstat < 0) goto error;
}
else if (kncont > 0)
(*newcurve)->cuopen = SISL_CRV_CLOSED;
/* Success */
*stat = 0;
goto out;
/* Error in allocation of memory. */
err101:
*stat = -101;
s6err("s1940", *stat, pos);
goto out;
/* Error in lower level routine. */
error:
*stat = lstat;
s6err("s1940", *stat, pos);
goto out;
/* Clear up and free memory before exit. */
out:
if (temp_err != SISL_NULL) freearray(temp_err);
if (local_err != SISL_NULL) freearray(local_err);
if (l2err != SISL_NULL) freearray(l2err);
if (lepsco != SISL_NULL) freearray(lepsco);
if (ranking.prio != SISL_NULL) freearray(ranking.prio);
if (ranking.groups != SISL_NULL) freearray(ranking.groups);
if (qc_kreg != SISL_NULL) freeCurve(qc_kreg);
if (qcpart != SISL_NULL) freeCurve(qcpart);
if (helpcurve != SISL_NULL && helpcurve != (*newcurve)) freeCurve(helpcurve);
if (tempcurve != SISL_NULL && tempcurve != (*newcurve)) freeCurve(tempcurve);
return;
}
| true |
57cb46abdac6ebdc284fc0724eeb6d0a0cca6efb | C++ | bryanmlyr/School-Projects | /cpp_pool/cpp_d08/ex01/DroidMemory.cpp | UTF-8 | 1,077 | 3.078125 | 3 | [] | no_license | /*
** EPITECH PROJECT, 2018
** piscine
** File description:
** ex01
*/
#include "DroidMemory.hpp"
#include <iostream>
DroidMemory::DroidMemory()
{
Exp = 0;
FingerPrint = random();
}
size_t DroidMemory::getFingerPrint()
{
return FingerPrint;
}
size_t DroidMemory::getExp()
{
return Exp;
}
void DroidMemory::setFingerPrint(size_t t)
{
FingerPrint = t;
}
void DroidMemory::setExp(size_t t)
{
FingerPrint = t;
}
void DroidMemory::operator<<(const DroidMemory &mem)
{
FingerPrint ^= mem.FingerPrint;
Exp += mem.Exp;
}
void DroidMemory::operator>>(DroidMemory &mem)
{
mem.FingerPrint ^= FingerPrint;
mem.Exp += Exp;
}
void DroidMemory::operator+=(size_t add)
{
Exp += add;
FingerPrint ^= Exp;
}
void DroidMemory::operator+(const DroidMemory mem)
{
FingerPrint ^= mem.FingerPrint;
Exp += mem.Exp;
}
DroidMemory DroidMemory::operator+(size_t add)
{
Exp += add;
FingerPrint ^= Exp;
return *this;
}
std::ostream &operator<<(std::ostream &s, DroidMemory mem)
{
s << "Droid Memory '" << mem.getFingerPrint() << "', " << mem.getExp() << std::endl;
return s;
} | true |
372c61d8c7228cca26a86386b7a3ab4bff8b6228 | C++ | lockskywalker/EquivalanceRelationManager | /testequiv.cpp | UTF-8 | 1,388 | 3.46875 | 3 | [] | no_license | // CSCI 2530
// Assignment: 3
// Author: Nigel Smith
// File: testequiv.cpp
// Tab stops: 4
// **Say what this program does here. (replace this comment)**
#include <cstdio>
#include <iostream>
#include "equiv.h"
using namespace std;
int main(int argc, char** argv)
{
int n = 7;
int * R = newER(n);
showER(R, n);
///R = {1} {2} {3} {4} {5} {6} {7}
merge(R, 1,5);
showER(R, n);
///R = {1, 5} {2} {3} {4} {6} {7}
merge(R, 2, 7);
showER(R, n);
///R = {1, 5} {2, 7} {3} {4} {6}
///equivalent(R, 1,5) yields true
///equivalent(R, 1,7) yields false
cout << "equivalent(R, 1,5) : " << equivalent(R, 1, 5) << endl;
cout << "equivalent(R, 1,7) : " << equivalent(R, 1, 7) << endl;
merge(R, 5, 7);
showER(R, n);
///R = {1, 2, 5, 7} {3} {4} {6}
///equivalent(R, 2,5) yields true
///equivalent(R, 2,3) yields false
cout << "equivalent(R, 2,5) : " << equivalent(R, 2, 5) << endl;
cout << "equivalent(R, 2,3) : " << equivalent(R, 2, 3) << endl;
merge(R, 2, 3);
showER(R, n);
///R = {1, 2, 3, 5, 7} {4} {6}
///equivalent(R, 3,7) yields true
///equivalent(R, 4,7) yields false
cout << "equivalent(R, 3,7) : " << equivalent(R, 3, 7) << endl;
cout << "equivalent(R, 4,7) : " << equivalent(R, 4, 7) << endl;
merge(R, 2, 3);
showER(R, n);
///R = {1, 2, 3, 5, 7} {4} {6}
destroyER(R);
}
| true |
ca0a7d0b41dd0daec8811f27573b0a51de0b1032 | C++ | jenyu7/CS11-cpp | /lab1/units.h | UTF-8 | 353 | 3.21875 | 3 | [] | no_license | #include <string>
/* Immutable class that holds a value and its units */
class UValue {
// value of the object
double value;
// units of the value
std::string units;
public:
UValue();
UValue(double value, std::string units);
double get_value();
std::string get_units();
};
UValue convert_to(UValue input, std::string to_units);
| true |
29b9e56d9e84fabb8f15a2b03ed76ff13b5337e3 | C++ | led-sudare/sudare_package | /lib/converter.h | UTF-8 | 905 | 2.640625 | 3 | [] | no_license | #pragma once
#include "polar.h"
#include "rectangular.h"
namespace sudare {
class converter {
public:
virtual ~converter() {}
virtual void operator()(rectangular const& rect, polar& polar) const = 0;
};
/** 直交座標から極座標へ変換する。補間はバイリニア。 */
class bilinear_converter : public converter {
std::vector<double> m_sin;
std::vector<double> m_cos;
void mod_sincos(polar const& po);
public:
~bilinear_converter() {}
void operator()(rectangular const& rect, polar& po) const;
};
/** 直交座標から極座標へ変換する。補間はニアレストネイバー。 */
class nearest_neighbor_converter : public converter {
std::vector<double> m_sin;
std::vector<double> m_cos;
void mod_sincos(polar const& po);
public:
~nearest_neighbor_converter() {}
void operator()(rectangular const& rect, polar& po) const;
};
} // namespace sudare
| true |
c1cbbbbb95face24c2ecd9a4d617fa835a638118 | C++ | wangcy6/weekly | /KM/03code/book/Thinking-In-C-resource-master/C08/c0823.cpp | UTF-8 | 846 | 3.984375 | 4 | [
"Apache-2.0"
] | permissive | /*
*本题主要考查const对象和const成员函数之间的调用
*const对象只能调用const成员函数,这样才能保证
*成员函数不会修改const对象,编译器也会阻止你这
*么做.
*非const对象则任何成员函数都能够调用,因为成员
*函数无需保证任何事情,只需要它能够被正确调用即可.
*/
class ConstFunc {
int i;
public:
ConstFunc(int ii);
int noneConstFunc();
int constFunc() const;
};
ConstFunc::ConstFunc(int ii)
:i(ii)
{}
//非const成员函数
int
ConstFunc::noneConstFunc()
{
return ++i;
}
//const成员函数
int
ConstFunc::constFunc() const
{
return i;
}
int
main(void)
{
const ConstFunc cc(11);
ConstFunc nc(12);
//非const对象调用非const成员函数
nc.noneConstFunc();
//const对象调用const成员函数
cc.constFunc();
return 0;
}
| true |
4d815d30b2d43d2a7937cef13cededbbf598c34c | C++ | yular/CC--InterviewProblem | /LeetCode/leetcode_binary-tree-maximum-path-sum.cpp | UTF-8 | 695 | 3.34375 | 3 | [] | no_license | /*
*
* Tag: Tree DP
* Time: O(n)
* Space: O(n)
*/
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxPathSum(TreeNode *root) {
res = INT_MIN;
dfs(root);
return res;
}
private:
int res;
int dfs(TreeNode *root){
if(root == NULL) return 0;
int l = dfs(root->left), r = dfs(root->right);
int sum = root->val;
if(l > 0) sum += l;
if(r > 0) sum += r;
res = max(res, sum);
return max(l, r) > 0?max(l, r) + root->val:root->val;
}
};
| true |
53b1821ac5b9385445b46226639c904ce2c558ca | C++ | mengweimw/My-Plan | /2022/Learn/Class/4.1 封装/01.封装的意义_学生系统.cpp | UTF-8 | 479 | 3.40625 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
class Student
{
public:
string name; //!< 姓名
string id; //!< 学号
void setStudent(string in_name, string in_id)
{
name = in_name;
id = in_id;
}
void showStudent()
{
cout << "name: " << name << " id: " << id << endl;
}
};
int main()
{
Student stu;
stu.setStudent("mengwei", "1881120011");
stu.showStudent();
return 0;
} | true |
e2aff750818edf0141f90ab1910e0f4d6e96cbe8 | C++ | Cryrivers/SPA | /SPA/Utility.cpp | UTF-8 | 964 | 2.53125 | 3 | [] | no_license | #include "stdafx.h"
#include "Utility.h"
#include "CFGNode.h"
#include "PKBController.h"
int indexOf(vector<int> list, int val)
{
for (int i = 0; i < list.size(); i++) {
if (list.at(i) == val) {
return(i);
}
}
return(-1);
}
int indexOf(vector<CFGNode*> list, CFGNode* val)
{
for (int i = 0; i < list.size(); i++) {
if (list.at(i) == val) {
return(i);
}
}
return(-1);
}
int indexOf(vector<ASTNode*> list, ASTNode* val){
for (int i = 0; i < list.size(); i++) {
if (list.at(i) == val) {
return(i);
}
}
return(-1);
}
StmtType getTypeOfStmt(STMT st){
vector<statement>* program = PKBController::createInstance()->getPreprocessedProgram();
for (int i = 0; i < program->size(); i++)
{
if (program->at(i).stmtNumber == st)
{
StmtType t = program->at(i).type;
if(t == STMT_ASSIGNMENT ||
t == STMT_CALL ||
t == STMT_IF ||
t == STMT_WHILE)
{
return program->at(i).type;
}
}
}
return STMT_NONE;
}
| true |
c414a96008aa19e9fedc8c19e860046364b3c77b | C++ | terminator-128/BUAA-compilers2020 | /cxylex.cpp | UTF-8 | 4,939 | 3.046875 | 3 | [
"MIT"
] | permissive | #include<stdio.h>
#include<stdlib.h>
#include<string>
#include<vector>
#include<iostream>
#include<fstream>
using namespace std;
enum lexType
{
UNKOWNSY,// 0
BEGINSY,// 1
ENDSY,// 2
FORSY,// 3
IFSY,// 4
THENSY,// 5
ELSESY,// 6
IDENTSY,// 7
INTSY,// 8
COLONSY,// 9
PLUSSY,// 10
STARSY,// 11
COMMASY,// 12
LPARSY,// 13
RPARSY,// 14
ASSIGNSY,// 15
};
lexType symbol;
fstream infile; // 当前文件流,参数路径读入的文件内容
vector<char> token; // 字符数组,用于存放单词的字符串
string identity;
char current; // 单个字符,存放当前读入的字符
int num; // 整形数字,存放当前读入整形数值
void clearToken() // 清空单词字符数组
{
token.clear();
return;
}
bool getChar() // 向前读进一个字符
{
if (infile.get(current)){
infile.flush();
return true;
}
return false;
}
void retract() // 向后退回上个字符
{
infile.putback(current);
return;
}
void identify()
{
identity.assign(token.begin(),token.end());
return;
}
lexType reserver() // 查找保留字, 返回值为0, 则代表token中的字符串是一个标识符; 否则为保留字编码, 返回当前保留字的类编码
{
identify();
if(!identity.compare("BEGIN")) return BEGINSY;
else if (!identity.compare("END")) return ENDSY;
else if (!identity.compare("FOR")) return FORSY;
else if (!identity.compare("IF")) return IFSY;
else if (!identity.compare("THEN")) return THENSY;
else if (!identity.compare("ELSE")) return ELSESY;
else return IDENTSY;
}
void catToken() // 每次电泳把当前char中读进的字符与当前token字符数组的字符串连接
{
token.push_back(current);
return;
}
int transNum() // 将token中的字符串转换成整数数值,返回这个数值
{
string token_str;
return stoi(token_str.assign(token.begin(),token.end()));
}
void error() // 出错处理函数
{
// perror("好像发生了什么错误\n");
return;
}
bool isSpace()
{
return current==' '? true : false;
}
bool isNewline()
{
return current=='\r'||current=='\n'? true : false;
}
bool isTab()
{
return current=='\t'? true : false;
}
bool isLetter()
{
if (current>='A'&& current<='Z')
return true;
else if (current >= 'a' && current<='z')
return true;
else
return false;
}
bool isDigit()
{
return (current>='0'&¤t<='9')? true : false;
}
bool isColon()
{
return current==':'? true : false;
}
bool isPlus()
{
return current=='+'? true : false;
}
bool isStar()
{
return current=='*'? true : false;
}
bool isComma()
{
return current==','? true : false;
}
bool isLpar()
{
return current=='('? true : false;
}
bool isRpar()
{
return current==')'? true : false;
}
bool isEqu()
{
return current=='='? true : false;
}
int getsysm()
{
// 清空标识符
clearToken();
do{
if(!getChar())
break;
}
while(isSpace()||isNewline()||isTab());
// cout << current;
if(isLetter()) // 判断是否为标识符
{
while(isLetter() || isDigit()){
catToken();
if(!getChar())
break;
}
if(!infile.eof())
retract();
// string token_str;
// cout <<token_str.assign(token.begin(),token.end());
symbol = reserver();
}
else if(isDigit()) // 判断是否为常数(整数)
{
while(isDigit()){
catToken();
if(!getChar())
break;
}
if(!infile.eof())
retract();
num = transNum();
symbol = INTSY;
}
else if (isColon())
{
getChar();
if (isEqu())
{
symbol = ASSIGNSY;
}
else{
retract();
symbol = COLONSY;
}
}
else if (isPlus()) { symbol = PLUSSY;} // 判断 +
else if (isStar()) { symbol = STARSY;} // 判断 *
else if (isComma()) { symbol = COMMASY;} // 判断 ,
else if (isLpar()) { symbol = LPARSY;} // 判断 (
else if (isRpar()) { symbol = RPARSY;} // 判断 )
else{
error();
symbol = UNKOWNSY;
return UNKOWNSY;
}
return symbol;
}
int main(int argc, char const *argv[])
{
// 目前只会有一个路径名, 即 argc = 1
// 打开文件
infile.open(argv[1], ios::in);
// 定位到 infile 第一个字节
infile.seekg(0,ios::beg);
// if(infile.fail())
// cout << "fail to read the file \""<<argv[1]<<"\" by the given location." << endl;
// else
// cout << "open file \""<<argv[1]<<"\" successfully"<<endl;
while(!infile.eof()&&getsysm()){
switch(symbol){
case 1: cout<<"Begin\n";break;
case 2: cout<<"End\n";break;
case 3: cout<<"For\n";break;
case 4: cout<<"If\n";break;
case 5: cout<<"Then\n";break;
case 6: cout<<"Else\n";break;
case 7: cout<<"Ident("<<identity<<")\n";break;
case 8: cout<<"Int("<<num<<")\n";break;
case 9: cout<<"Colon\n";break;
case 10: cout<<"Plus\n";break;
case 11: cout<<"Star\n";break;
case 12: cout<<"Comma\n";break;
case 13: cout<<"LParenthesis\n";break;
case 14: cout<<"RParenthesis\n";break;
case 15: cout<<"Assign\n";break;
}
}
if(!infile.eof()){
cout<<"Unknown\n";
}
infile.close();
return 0;
}
| true |
655d0d8a190677905af5a270099d2f267e73376f | C++ | RobertasJan/hello-github | /main.cpp | UTF-8 | 234 | 2.796875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
int main()
{
std::ofstream output ("HelloTxt.txt");
for (int i=0; i<1000; i++) {
output << "Hello GitHub!" << '\n';
}
output << std::flush;
return 0;
}
| true |
4c3bfb3e110facf4daf40b1ac7931730ebb68a8e | C++ | TeachMeHow/TSP-genetic-algorithm | /PEA_3/MeasurementEngine.cpp | UTF-8 | 894 | 3.03125 | 3 | [] | no_license | #include "MeasurementEngine.h"
MeasurementEngine::MeasurementEngine()
{
}
MeasurementEngine::~MeasurementEngine()
{
}
void MeasurementEngine::poll(std::chrono::milliseconds elapsed_time, int gen_cnt, int mut_cnt, int best_val)
{
data.emplace_back(elapsed_time, gen_cnt, mut_cnt, best_val);
}
void MeasurementEngine::print_to_csv_file(const char * filename)
{
std::ofstream file;
file.open(filename, std::ios::trunc | std::ios::out);
file << "filename,Best solution,Generations,Mutations,Elapsed Time\n";
file << filename << ',' << data.back().get_value() << ','
<< data.back().get_gen_cnt() << ',' << data.back().get_mut_cnt() << ','
<< data.back().get_elapsed_time_ms();
file << "\nData\n";
file << "Elapsed time (ms),Generation,Mutations,Best solution";
for (MeasurementDataPoint data_point : data)
{
file << data_point.to_string();
file << '\n';
}
file.close();
} | true |
a7c2b352323a24023bdeeecb196f794f68dba2c3 | C++ | syrilzhang/CSU-Projects | /CS253/P2/fRead.h | UTF-8 | 478 | 2.625 | 3 | [] | no_license | /* Name: Luke Burford
* Date: 09/08/17
* Email: lburford@rams.colostate.edu
*/
#ifndef FREAD_H_INCLUDE
#define FREAD_H_INCLUDE
#include <string>
using namespace std;
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
using std::cerr;
#include <fstream>
using std::ifstream;
using std::ws;
// fRead, reads files and tests if file type being read is valid
class fRead {
public:
// read will return -1 if error, 0 if success
int read(char* in);
};
#endif //FREAD_H_INCLUDE
| true |
f934b16b881fb7e4c87398e4ef1a629039c9b3b1 | C++ | Klarksonnek/FIT | /IPK_2/common.h | UTF-8 | 2,262 | 2.625 | 3 | [] | no_license | /**
* Projekt: IPK - projekt 2: Prenos souboru
* Modul: common.cpp
* Autor: Klara Necasova
* Email: xnecas24@stud.fit.vutbr.cz
* Datum: duben 2016
*/
#ifndef COMMON_H
#define COMMON_H
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <cerrno>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <regex.h>
#include <unistd.h>
#include <signal.h>
#include <cstring>
// velikost bufferu
#define BUFFER_SIZE 1024
using namespace std;
/**
* Chybove kody.
*/
enum ecodes
{
EOK,
EPARAMS,
EHOST,
ESOCKET,
ESOCKET_CLS,
ECONNECT,
ESEND,
EOPEN,
EBIND,
ELISTEN,
ERCV,
EUPLOAD,
EDOWNLOAD,
EPORT,
EHOST_NAME,
EACCEPT,
END
};
/**
* Chybova hlaseni odpovidajici chybovym kodum.
*/
extern const char *ERRMSG[];
/**
* Vytiskne chybove hlaseni.
* @param errCode Chybovy kod.
*/
void printError(int errCode);
/**
* Prijima data (binarni data).
* @param socketNum Socket pro komunikaci.
* @param fileName Jmeno souboru.
* @param fileSize Velikost souboru.
* @return Vraci EOK nebo prislusny chybovy kod.
*/
int receiveData(int socketNum,string fileName, int fileSize);
/**
* Prijima zpravy protokolu.
* @param socketNum Socket pro komunikaci.
* @param data Ukazatel na zapsana data.
* @return Vraci EOK nebo prislusny chybovy kod.
*/
int receiveProtocolData(int socketNum,string* data);
/**
* Overi existenci souboru a jeho rezim.
* @param name Jmeno souboru.
* @param mode Rezim souboru.
* @param size Velikost souboru.
* @return Vraci 0 - soubor neexistuje, 1 - jinak
*/
bool fileExists(const string& name,const char* mode, int* size);
/**
* Prevadi cisto typu integer na retezec (typ string).
* @param integer Cislo typu integer, ktere se bude prevadet.
* @return Vraci retezec obsahujici prevedene cislo.
*/
string intToString(int integer);
/**
* Zajistuje odeslani binarnich dat.
* @param commSocket Socket pro komunikaci.
* @param fileName Jmeno souboru.
* @param fileSize Velikost souboru.
* @return Vraci EOK nebo prislusny chybovy kod.
*/
int sendData(int commSocket, string fileName, int fileSize);
#endif
| true |
d9ff7a21f3fae328e572517f8b090a46a7f09099 | C++ | mrdrivingduck/leet-code | /Offer63.BestTimeToBuyAndSellStock.cpp | UTF-8 | 1,981 | 3.734375 | 4 | [
"MIT"
] | permissive | /**
* @author Mr Dk.
* @version 2021/03/04
*/
/*
You are given an array prices where prices[i] is the price of a given
stock on the ith day.
You want to maximize your profit by choosing a single day to buy one
stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If
you cannot achieve any profit, return 0.
Example 1:
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation:
Buy on day 2 (price = 1) and sell on day 5 (price = 6),
profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed
because you must buy before you sell.
Example 2:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation:
In this case, no transactions are done and the max profit = 0.
Constraints:
1 <= prices.length <= 105
0 <= prices[i] <= 104
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
/*
在每个位置上,记录到目前为止遇到的最低股票价格。
*/
#include <cassert>
#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::vector;
class Solution {
public:
int maxProfit(vector<int>& prices) {
int max = 0;
for (size_t i = 1; i < prices.size(); i++) {
if (prices[i] > prices[i - 1]) {
max = std::max(max, prices[i] - prices[i - 1]);
}
prices[i] = std::min(prices[i], prices[i - 1]);
}
return max;
}
};
int main()
{
Solution s;
vector<int> prices;
prices = { 7,1,5,3,6,4 };
assert(5 == s.maxProfit(prices));
prices = { 7,6,4,3,1 };
assert(0 == s.maxProfit(prices));
return 0;
}
| true |
007514d1481c124abbc1222ae2425dd4fd7254da | C++ | goldDaniel/Plug-N-Play | /Src/Game/Systems/PlayerWeaponSystem.h | UTF-8 | 1,994 | 2.8125 | 3 | [
"MIT"
] | permissive | #ifndef PLAYER_WEAPON_SYSTEM_H
#define PLAYER_WEAPON_SYSTEM_H
#include <Core.h>
#include "Graphics/Texture.h"
class PlayerWeaponSystem : public System
{
public:
PlayerWeaponSystem(ECSController * const ECS) : System::System(ECS) {}
void Update(float dt)
{
for(const auto& entity : entities)
{
const auto& trans = ECS->GetComponent<Transform>(entity);
const auto& input = ECS->GetComponent<PlayerInput>(entity);
auto& weapon = ECS->GetComponent<Weapon>(entity);
if(weapon.cooldown_timer > 0)
{
weapon.cooldown_timer -= dt;
}
if (input.key_shoot && weapon.cooldown_timer <= 0)
{
weapon.cooldown_timer = weapon.cooldown;
auto texture = Texture::CreateTexture("Assets/Textures/Bullet.png");
float ratio = (float)texture->height / (float)texture->width;
float scaleX = 1 / 2.f;
float scaleY = ratio / 2.f;
float spacing = 0.5f;
for (float i = -spacing; i <= spacing; i += spacing)
{
Entity bullet = ECS->CreateEntity();
glm::vec2 pos = trans.position + glm::vec2(i / 2.f, trans.scale.y / 2.f + scaleY / 2.f);
Transform t{ pos, glm::vec2(scaleX, scaleY), glm::pi<float>() / 2 };
ECS->AddComponent<Transform>(bullet, t);
ECS->AddComponent<Bullet>(bullet, Bullet());
Velocity v{ glm::vec2(0, 24) };
ECS->AddComponent<Velocity>(bullet, v);
Collider collider{ Collider::Bullet, Collider::Enemy, 0.1f };
ECS->AddComponent(bullet, collider);
Renderable r{ glm::vec4(1.f,1.f,1.f,1.f), texture };
ECS->AddComponent<Renderable>(bullet, r);
}
}
}
}
};
#endif | true |
ab8e669b8519dbb5d6528479d092ab4add23db7e | C++ | cha63506/archive-45 | /U/old/graphics/grid.h | UTF-8 | 6,728 | 3.40625 | 3 | [] | no_license | #include <fstream>
/*+
* class grid
*
*//*#########################################################################*/
class grid
{
private:
int pen_i, pen_j;
color **pos;
void construct()
{
array = new (color *) [rows*cols];
pen_i=0;
pen_j=0;
pos=array;
}
public:
color **array;
color *default_c;
int rows, cols;
/** constructors, loading and saving *//*===================================*/
grid(color *default_c0, int rows0, int cols0)
{
default_c = default_c0;
rows = rows0;
cols = cols0;
construct();
}
grid(grid *g, frame *f)
{
default_c = g->default_c;
rows = 1+f->imax-f->imin;
cols = 1+f->jmax-f->jmin;
construct();
color **cp = g->array + ((f->imin * cols) + f->jmin), **cp2 = array;
for (int i=0; i<rows; i++) {
for (int j=0; j<cols; j++) {
*cp2 = *cp;
cp++;
cp2++;
}
cp += (g->cols - cols);
}
}
grid(char *filename)
{
ifstream in(filename);
in >> rows;
in >> cols;
char *s = new char[7];
s += 6;
*s = '\0';
s -= 6;
in >> s;
default_c = new color(s);
construct();
color **cp = array;
color *c;
for (int i=0; i<rows*cols; i++) {
in >> s;
c = new color(s); // Note: wasty. In future, re-use colors.
if (c->equals(default_c)) {
delete(c);
*cp = default_c;
} else
*cp = c;
cp++;
}
in.close();
}
~grid()
{
delete array;
}
/**
* write(ofstream out, int indent()
*
* Write an ASCII-encoded grid to a stream for storage.
*/
write(ofstream out)
{
out << "\tgrid " << id() << " {\n";
out << '\t';
write_formatted_name(out);
out << "\n";
out << rows << ' ' << cols << ' ' << default_c->id() << '\n';
color **cp = array;
for (int i=0; i<rows; i++) {
out << "\t\t";
for (int j=0; j<rows; j++) {
out << (*c)->id();
if (j<rows-1)
out << '\t';
else
out << '\n';
cp++;
}
}
out << "\t}\n";
}
/** interactions between grids *//*=========================================*/
/* Note: assumes same array dimensions */
void copy(grid *ref)
{
color **cp = array, **cp2 = ref->array;
for (int i=0; i<rows*cols; i++) {
*cp = *cp2;
cp++;
cp2++;
}
}
/**
* void embed(grid *ref, int i_corner, int j_corner)
*
* Overwrite the contents of one grid with those of another
* starting at the specified upper left corner.
*
* Note: current grid dimensions must be large enough to hold the target pattern.
*/
void embed(grid *ref, int i_corner, int j_corner)
{
if ((ref->rows > rows)||(ref->cols > cols))
return;
else {
color **cp = ref->array;
for (int i=0; i<ref->rows; i++) {
for (int j=0; j<ref->cols; j++) {
array[((i_corner+i)*cols)+j_corner+j] = *cp;
cp++;
}
}
}
}
/**
* void embed_center(grid *ref)
*
* Overwrite the center of one grid with another
*/
void embed_center(grid *ref)
{
embed(ref, (rows-ref->rows)/2, (cols-ref->cols)/2);
}
/** transformations (the interesting stuff) *//*============================*/
/* Note: all of these transformations assume that the reference grid has
the same dimensions and default color as "this" grid */
// relative vs. eigen-transformations
void flatten(grid *ref, color *dest_c)
{
color **cp = array, **cp2 = ref->array;
for (int i=0; i<rows*cols; i++) {
if (!default_c->equals(*cp2))
*cp = dest_c;
cp++;
cp2++;
}
}
void flex(grid *ref, color *dest_c0, color *source_c0)
{
flatten(source_c0);
dest_c = dest_c0;
source_c = source_c0;
color **cp = ref->array;
int i, j;
for (i=0; i<rows*cols; i++) {
if (source_c->equals(*cp))
break;
cp++;
}
if (i<rows*cols) {
j = i%cols;
i = i/cols;
imin = i; imax = i; jmin = j; jmax = j;
recursive_set(i, j);
cout << "imin = " << imin << endl;
cout << "imax = " << imax << endl;
cout << "jmin = " << jmin << endl;
cout << "jmax = " << jmax << endl;
}
}
/**
* conway()
*
* A dead cell with exactly 3 live neighbours becomes alive (or is "born").
* A live cell with 2 or 3 live neighbours stays alive
*
* {Atari}
*/
void conway(grid *ref, color *fore_c)
{
color **cp = array, **cp2 = stunt_double;
int neighbors;
bool live;
for (int i=0; i<rows; i++) {
for (int j=0; j<cols; j++) {
neighbors = 0;
if (!default_c->equals(wrap(i-1,j-1))) //### ...
neighbors++;
if (!default_c->equals(wrap(i-1,j+1))) //### ...
neighbors++;
if (!default_c->equals(wrap(i+1,j-1))) //### ...
neighbors++;
if (!default_c->equals(wrap(i+1,j+1))) //### ...
neighbors++;
if (!default_c->equals(wrap(i-1,j))) //### ...
neighbors++;
if (!default_c->equals(wrap(i+1,j)))
neighbors++;
if (!default_c->equals(wrap(i,j-1)))
neighbors++;
if (!default_c->equals(wrap(i,j+1)))
neighbors++;
if (!default_c->equals(*cp)) {
live = (neighbors > 1 && neighbors < 4);
fore_c = *cp;
} else
live = (neighbors == 3);
if (live)
*cp2 = fore_c;
else
*cp2 = default_c;
cp++;
cp2++;
}
}
color **temp = array;
array = stunt_double;
stunt_double = temp;
}
/** miscellaneous *//*======================================================*/
/* find boundaries */
frame *crop()
{
frame *f = new frame();
register int i, j;
int max_index = rows*cols-1;
color **cp = array, **cp2;
for (i=0; i<=max_index; i++) {
if (default_c != (*cp))
break;
cp++;
}
f->imin = i/cols;
cp = array + max_index;
for (i=0; i<=max_index; i++) {
if (default_c != (*cp))
break;
cp--;
}
f->imax = rows - (i/cols) - 1;
cp = array;
for (j=0; j<cols; j++) {
cp2 = cp;
for (i=0; i<rows; i++) {
if (default_c != (*cp2)) {
f->jmax = j;
break;
}
cp2 += cols;
}
cp++;
}
cp = array + max_index;
for (j=cols-1; j>=0; j--) {
cp2 = cp;
for (i=rows-1; i>=0; i--) {
if (default_c != (*cp2)) {
f->jmin = j;
break;
}
cp2 -= cols;
}
cp--;
}
return f;
}
}; /*- end class grid ........................................................*/
| true |
6f3019de6fef03849d9d5961f701c56b7fc5d0d7 | C++ | gjmistkawi/file-transfer-system | /ftserver.cpp | UTF-8 | 12,353 | 3 | 3 | [] | no_license | /*
George Mistkawi
ftserver.cpp
Description:
Server opens and waits for a client to connect and send a command. Once a
command is recieved the server will either send the current working directory
or the contents of a specified file. Once the transaction is complete, the
connection is closed and the server continues to listen for more connections
until a SIGINT is sent.
CS 372 - 400
Last Modified 11/21/2018
*/
/*
big credit for my c++ side goes to Eduonix Learning Soluctions on Youtube.
I used the Socket Programing Tutorial in C For Beginners | Part 1 | Eduonix
To help me figure out how to make connections in this language, the video is
here:
https://www.youtube.com/watch?v=LtXEMwSG5-8&list=PLZ4ODEExSiRdIsfgA_AnmmO36BJsD_XEv&index=2&t=2161s
*/
#include <iostream>
#include <string>
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <cstdlib>
#include <sstream>
#include <vector>
#include <iterator>
#include <dirent.h>
#include <fstream>
#include <fcntl.h>
//#include<errno.h>
#define MAXSIZE 1024
using namespace std;
vector<string> recieveCommand(int commandConnection); //get command from client
int clientToServer(int sock, struct sockaddr_in *serverAddress, struct sockaddr_in *clientAddress); //listen on local socket for client
int serverToClient(int clientPort, struct sockaddr_in *clientAddress); //connet to open socket on the client
void getAddress(int portNum, struct sockaddr_in *address); //get desired address object, stored by reference
int openSocket(); //opens any available socket and passes back
void checkInput(int argc, char **argv); //check for valid user input
int listenSocket(struct sockaddr_in *serverAddress); //opens a valid socket to listen for client
void sendDirectory(int dataConnection); //sends the contents of cwd to client
void sendFile(int dataConnection, string fileName); //sends file based on client request
bool fileExists(string fileName); //checks whether or not a file exists
int sendMessage(int connection, string message); //sends messages to client
//=============================================================================================
//================================= MAIN =====================================
//=============================================================================================
int main(int argc, char **argv) {
checkInput(argc, argv);
cout << "Server open on " << argv[1] << endl;
int dataConnection, commandConnection;
int serverPort = atoi(argv[1]);
//create address from user specified port number
struct sockaddr_in serverAddress;
getAddress(serverPort, &serverAddress);
int sock = listenSocket(&serverAddress);
//loop until SIGINT from an admin
while(true) {
//connect to client and get client address
struct sockaddr_in clientAddress;
if((commandConnection = clientToServer(sock, &serverAddress, &clientAddress)) == -1) {
cout << "connection failed: " << commandConnection << endl;
continue;
}
//get command from client
vector<string> command = recieveCommand(commandConnection);
if(command.size() == 0) {
close(commandConnection);
continue;
}
//connect to open socket on client for data transfer
if((dataConnection = serverToClient(atoi((command[2]).c_str()), &clientAddress)) == -1) {
continue;
}
//list command
if(command[0] == "-l") {
cout << "List directory requested on port " << command[2] << "." << endl;
cout << "Sending directory contents to " << command[1] << ":" << command[2] << "." << endl;
sendDirectory(dataConnection);
}
//get file command
else if(command[0] == "-g") {
string fileName = command[3];
if(fileExists(fileName)) {
sendFile(dataConnection, fileName);
}
else {
cout << "File not found. Sending error message to " << command[1] << ":" << command[2] << "." << endl;
int i = sendMessage(dataConnection, "ERROR: FILE NOT FOUND");
}
}
close(commandConnection);
close(dataConnection);
}
}
//=============================================================================================
//================================= FUNCTIONS ====================================
//=============================================================================================
//fileExists: Checks current working directory for a file with given name
//arguments: fileName(name of the file searched for)
//return values: returns true if file exists, otherwise false
bool fileExists(string fileName) {
//found how to check if a file exists here
//https://stackoverflow.com/questions/12774207/fastest-way-to-check-if-a-file-exist-using-standard-c-c11-c
ifstream f(fileName.c_str());
return f.good();
}
//sendFile: Sends the file to client in pieces until complete
//arguments: dataConnection(open connection to the client)
// fileName(name of the client specified file)
//return values: none
void sendFile(int dataConnection, string fileName) {
//help with file sending from this article
//https://stackoverflow.com/questions/11952898/c-send-and-receive-file
char buff[MAXSIZE];
memset(buff, 0, sizeof(buff)); //clear the buffer
int file = open(fileName.c_str(), O_RDONLY); //open the file
while(true) { //get size of the file
int byteSize = read(file, buff, sizeof(buff)-1);
if(byteSize == 0) {
break;
}
void* temp = buff; //void pointer to save what content hasn't been sent
while(byteSize > 0) {
int bytesWritten = sendMessage(dataConnection, buff); //send partially to client
if(bytesWritten < 0) {
cout << "Error sending message" << endl;
return;
}
byteSize -= bytesWritten; //how many bytes are left
temp = (char*)temp + bytesWritten; //move our place holder to whats left
}
memset(buff, 0, sizeof(buff)); //reset the buffer to grab more info
}
}
//sendDirectory: reads the contents of current directory and sends file names them to client
//arguments: dataConnection(open connection to the client)
//return values: none
void sendDirectory(int dataConnection) {
//help with grabbing contents from a directory goes to this article
//http://www.martinbroadhurst.com/list-the-files-in-a-directory-in-c.html
vector<string> contents;
string dirName = ".";
DIR* dirp = opendir(dirName.c_str());
struct dirent * dp;
while ((dp = readdir(dirp)) != NULL) {
contents.push_back(dp->d_name);
}
closedir(dirp);
string message = "";
for(int i = 0; i < contents.size(); i++) {
message += contents[i] + " ";
}
int x = sendMessage(dataConnection, message);
}
//listenSocket: Opens the listening socket with the serveraddress
//arguments: serverAddress(address specified by server and user input)
//return values: returns an open socket
int listenSocket(struct sockaddr_in *serverAddress) {
int sock = openSocket();
//bind socket to specified address and port number
bind(sock, (struct sockaddr *) serverAddress, sizeof(*serverAddress));
//wait for client side
listen(sock,5);
return sock;
}
//recieveCommand: recieves and parses command message from client
//arguments: commandConnection(open connection to client)
//return values: returns a vector of the command message
vector<string> recieveCommand(int commandConnection) {
int numBytes;
char message[MAXSIZE];
vector<string> command;
//get message from client
if((numBytes = recv(commandConnection, &message, MAXSIZE-1, 0)) == -1) {
cout << "Error recieving message from client" << endl;
cout << "Closing connection to client" << endl;
return command;
}
message[numBytes] = '\0';
//help with breaking down the command goes to this post
//https://gist.github.com/conrjac/5387376
string temp = message;
istringstream iss(temp);
string token;
while(getline(iss,token,' ')) {
command.push_back(token);
}
cout << "Connection from " << command[1] << "." << endl;
return command;
}
//clientToServer: Opens socket on server and waits for client to connect
//arguments: serverAddress(address specified by server and user input)
// clientAddress(pass by reference to grab client address from accept)
//return values: returns open connection from client to server
int clientToServer(int sock, struct sockaddr_in *serverAddress, struct sockaddr_in *clientAddress) {
//https://www.geeksforgeeks.org/accept-system-call/
//help with accepting client address goes to this article
unsigned int clientLength = sizeof(clientAddress);
int connection = accept(sock, (struct sockaddr *) clientAddress, &clientLength);
return connection;
}
//serverToClient: Opens a second connection for data transfer
//arguments: clientSocket(port number sent from client side)
// clientAddress(pointer to address object recieved by accept statement)
//return values: returns an open connection from server to client
int serverToClient(int clientPort, struct sockaddr_in *clientAddress) {
int sock = openSocket();
clientAddress->sin_port = htons(clientPort);
if(connect(sock, (struct sockaddr *) clientAddress, sizeof(*clientAddress)) == -1) {
cout << "Error establishing connection Q to client" << endl;
return -1;
}
return sock;
}
//getAddress: Gets address for connection to be established
//arguments: portNum(desired port number)
// address(pointer to a socket address struct, passed by reference)
//return values: none
void getAddress(int portNum, struct sockaddr_in *address) {
address->sin_family = AF_INET;
address->sin_port = htons(portNum);
address->sin_addr.s_addr = INADDR_ANY;
}
//openSocket: Opens an available socket for communication
//arguments: none
//return values: returns an open socket, or exits if unable to open a socket
int openSocket() {
int sock;
if((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
cout << "Error creating socket." << endl;
exit(1);
}
return sock;
}
//checkInput: Checks the users command line arguments to check if program is being called correctly
//arguments: argc(the number of command line arguments)
// argv(the command line as an array of character arrays)
//return values: exits program if invalid input, otherwise none
void checkInput(int argc, char **argv) {
//making sure the function is called with proper number of arguments
if(argc != 2)
{
cout << "Usage: ftserver <port#>" << endl;
exit(1);
}
//making sure a valid int was entered for a port number
int portNum = atoi(argv[1]);
if(portNum == 0)
{
cout << "Please input a valid interger port number" << endl;
exit(1);
}
}
//sendMessage: Sends user message to already established connection
//arguments: username(handle to prepend to each message) connection(open socket connection)
//return values: returns -1 if message send failed, and the size of the message sent otherwise
int sendMessage(int connection, string message) {
int size = strlen(message.c_str());
size = send(connection, message.c_str(), size, 0);
if(size == -1) {
cout << "Error sending message to client" << endl;
cout << "Closing connection to client" << endl;
return -1;
}
return size;
}
| true |
c1a33893ccfb90da9df8ceb48a6992e1cf164cd5 | C++ | francoisludewig/SolidMechanics | /GeometricalSolid/Include/Disk.h | UTF-8 | 1,236 | 2.828125 | 3 | [] | no_license | #pragma once
#include "Shape.h"
#include <Matrix.h>
namespace GeometricalSolid{
class Disk: public Shape{
public:
RetDiskangle(const double radius, const double thickness, const double density):radius(raidus), thickness(thickness), density(density) {
this->init();
}
double Density() const { return this->density; }
double Volume() const { return this->volume; }
double Radius() const { return this->radius; }
double Thickness const { return this-> thickness; }
private:
void init() {
this->nature = Shape::Nature::Container;
this->form = Shape::Form::Disk;
this->volume = this->radius*this->radius*M_PI*this->thickness;
this->mass = this->volume*this->density;
this->inertia.Element(0, 0, this->mass*(this->radius*this->radius/4. + this->thickness*this->thickness/12.));
this->inertia.Element(1, 1, this->mass*(this->radius*this->radius/4. + this->thickness*this->thickness/12.));
this->inertia.Element(2, 2, this->mass/2*(this->radius*this->radius));
this->invertedInertia = inertia.MatrixInverse();
}
double radius{1};
double thickness{1};
double density{2500};
double volume{M_PI};
double mass{2500*M_PI};
GeometricalSpaceObjects::Matrix<double> inertia;
};
}
| true |
4923bc9241d81fb7933626aed46cd00dd0b6b4a2 | C++ | lruiz5/testrepo | /challenges/1NthSmallest/1NthSmallest/main.cpp | UTF-8 | 1,227 | 4.03125 | 4 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int findNthSmallest(vector<int> numbers, int n)
{
if (numbers.empty())//check for emtptyness
{
return 0;
}
else if (n > numbers.size())
{
cout << n << " is out of vector range." << endl;
return n;
}
//set minimum = first element in vector
//set next = numbers[0 + 1]
int minimum, next, current;
minimum = next = current = numbers[0];
for (auto number : numbers)
{
if (number < minimum)//if current number is less than current minimum
{
minimum = number;//set the new minimum
}
}
//find the nth smallest number in vector
if (n == 1) return minimum;
for (int i = 0; i < (n - 1); i++)
{
for (auto number : numbers)
{
if (number > minimum && number <= next)
{
next = number;
}
}
minimum = next;
next = numbers[0];
}
return minimum;
}
int main()
{
vector<int> numbers{ 1, 3, 2, 5, 9, 8, 6 };
int out_of_range = findNthSmallest(numbers, 8);
int result2 = findNthSmallest(numbers, 0);
int result3 = findNthSmallest(numbers, 3);
int result4 = findNthSmallest(numbers, 4);
cout << "Return n for out of range: " << out_of_range << endl;
cout << result2;
cout << result3;
cout << result4;
return 0;
} | true |
dba22e8a92aa42d30a15512d3990f11daa80d147 | C++ | chris-blackburn/plotscript | /threaded_interpreter.cpp | UTF-8 | 2,630 | 3.359375 | 3 | [] | no_license | #include "threaded_interpreter.hpp"
ThreadedInterpreter::ThreadedInterpreter(InputQueue* iq, OutputQueue* oq): m_iq(iq), m_oq(oq) {
start();
}
// evaluate a stream directly
ThreadedInterpreter::ThreadedInterpreter(OutputQueue* oq, std::istream& stream): m_oq(oq) {
if (!m_thread.joinable()) {
m_thread = std::thread([this, &stream](){
Interpreter interp;
loadStartupFile(interp);
// pop in case there was an error with the startup file
OutputMessage msg;
m_oq->try_pop(msg);
evalStream(interp, stream);
});
}
}
// Be sure to stop and join the thread when falling out of scope
ThreadedInterpreter::~ThreadedInterpreter() {
stop();
}
void ThreadedInterpreter::start() {
active = true;
if (!m_thread.joinable()) {
// Move a new thread into the class' thread
m_thread = std::thread(&ThreadedInterpreter::run, this);
}
}
void ThreadedInterpreter::stop() {
active = false;
if (m_thread.joinable()) {
m_thread.join();
}
}
void ThreadedInterpreter::reset() {
stop();
start();
}
bool ThreadedInterpreter::isActive() const {
return active;
}
void ThreadedInterpreter::error(const std::string& e) {
m_oq->push(OutputMessage(ErrorType, e));
}
void ThreadedInterpreter::evalStream(Interpreter& interp, std::istream& stream) {
if (!interp.parseStream(stream)) {
error("Invalid Expression. Could not parse.");
} else {
// try to evaluate the expression, push the result to the output queue
try {
Expression exp = interp.evaluate();
m_oq->push(OutputMessage(ExpressionType, exp));
} catch(const SemanticError& ex) {
error(std::string(ex.what()));
}
}
}
void ThreadedInterpreter::run() {
Interpreter interp;
loadStartupFile(interp);
while (active) {
// Grab input messages as they populate the queue. If not message is returned, then continue
// iterating
InputMessage msg;
if (m_iq->try_pop(msg)) {
// Attempt to parse the input stream
std::istringstream stream(msg);
evalStream(interp, stream);
}
}
}
void ThreadedInterpreter::loadStartupFile(Interpreter& interp) {
std::ifstream ifs(STARTUP_FILE);
if (!ifs) {
error("Could not open startup file for reading.");
} else {
// Just load the expressions from the startup file into the interpreter. We don't need to do
// anything with them
if (!interp.parseStream(ifs)) {
error("Invalid Program in startup file. Could not parse.");
} else {
try {
interp.evaluate();
} catch (const SemanticError& ex) {
error(std::string(ex.what()) + " [startup]");
}
}
}
startupLoaded = true;
}
bool ThreadedInterpreter::isStartupLoaded() const {
return startupLoaded;
}
| true |
0861ad82cd32c39f8c334346a8a5fe56048ccdc0 | C++ | ivanliu1989/Helping-Santas-Helpers | /C++ code/exp1/Driver.cpp | UTF-8 | 1,049 | 2.640625 | 3 | [] | no_license | /**
* My version of the Naive Solution from
* https://github.com/noahvanhoucke/HelpingSantasHelpers
*
* Written by Rick Bischoff
* but I claim no license or copyright.
* https://github.com/rdbisch/Santa2014
**/
#include "Score.h"
#include "Naive.h"
#include <iostream>
#include <iomanip>
#include <string.h>
using namespace std;
int main(int argc, char** argv) {
init_startTime();
if ( argc < 3 ) {
usage_message:
cerr << "Usage:\n\ta.out (--score) [n] [toys]\n\n"
<< "\t--score\tIf present will score the submission on stdin. If not will produce naive solution.\n"
<< "\t[n]\tinteger number of elves\n"
<< "\t[toys]\tPath to list of toys.\n";
std::exit(1);
}
if ( strcmp(argv[1], "--score") == 0 ) {
if (argc < 4) goto usage_message;
int n = atoi(argv[2]);
string toys = string(argv[3]);
cout << std::setprecision(15) << score( n, toys ) << endl;
} else {
NaiveSolution e( atoi(argv[1]), string(argv[2]) );
}
return 0;
}
| true |
d198a5a0d346aff59142b30e6a59124688ea13ec | C++ | khjoony/CPP_lesson | /CPP_lesson/CPP_lesson/struct_string_bookLibraryManagement.cpp | UTF-8 | 8,390 | 3.234375 | 3 | [
"Apache-2.0"
] | permissive | // Book Library Management
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
enum BOOKMAX {BOOK = 1000, NAME = 25, DESCRIPTION = 500 };
enum MENU {MENU_EXIT, MENU_CREATE, MENU_READ, MENU_UPDATE, MENU_SEARCH, MENU_DELETE };
enum ITEM { ITEM_PRICE = 1, ITEM_RENTAL };
struct _Book {
long lID;
char strName[NAME];
char strAuthor[NAME];
char strPubli[NAME];
char strNation[NAME];
char strDescript[DESCRIPTION];
int iPrice;
int bRental;
};
void PrintAll(int iBookCnt, _Book _book[]);
void Print(int iExistID, _Book _book[]);
long Search(char strNameUpdate[],long iSelectID, int iBookCount, _Book _book[]);
void Update(long iSelectedID, _Book _book[]);
void Delete(int iExistID, int& iBookCount, _Book _book[]);
int main()
{
_Book _book[BOOK] = {};
int iBookCount = 0;
int iBookID = 1;
while (true)
{
cout << "0: EXIT" << endl;
cout << "1: CREATE" << endl;
cout << "2: READ" << endl;
cout << "3: UPDATE" << endl;
cout << "4: SEARCH" << endl;
cout << "5: DELETE" << endl;
cout << "Select number of menu : ";
int iMenu;
cin >> iMenu;
if (cin.fail())
{
cin.clear();
cin.ignore(INT_MAX, '\n');
system("cls");
cout << "It's wrong !! Try again.\n";
continue;
}
if (iMenu == MENU_EXIT)
{
break;
}
cin.ignore(INT_MAX, '\n');
long iSelectID = 0, iExistID = 0;
switch (iMenu)
{
case MENU_CREATE:
system("cls");
cout << "================ Create a student info ================" << endl;
if (iBookCount == BOOK)
{
cout << "Can't add a book any more.";
break;
}
cout << "Book Name : "; cin.getline( _book[iBookCount].strName, NAME-1);
_book[iBookCount].lID = iBookID;
//cin.ignore(NAME, '\n');
cout << "Author : "; cin.getline(_book[iBookCount].strAuthor, NAME-1);
cout << "Dedcription : "; cin.getline(_book[iBookCount].strDescript, DESCRIPTION);
//cin.ignore(DESCRIPTION, '\n');
cout << "Publisher : "; cin.getline(_book[iBookCount].strPubli, NAME-1);
//cin.ignore(NAME, '\n');
cout << "Nation : "; cin.getline(_book[iBookCount].strNation, NAME-1);
//cin.ignore(NAME, '\n');
cout << "Price :"; cin >> _book[iBookCount].iPrice;
while (true)
{
cout << "IsRental [1: yes, 0: no] :"; cin >> _book[iBookCount].bRental;
if (_book[iBookCount].bRental == 1 || _book[iBookCount].bRental == 0)
{
break;
}
else {
cout << "It's wrong number !" << endl;
continue;
}
}
cout.setf(ios::left);
++iBookID;
++iBookCount;
break;
case MENU_READ:
system("cls");
PrintAll(iBookCount, _book);
break;
case MENU_UPDATE:
system("cls");
char strNameUpdate[NAME];
while (true)
{
system("cls");
cout << "================ Update a student info ================" << endl;
cout << "Book Name : "; cin.getline(strNameUpdate, NAME-1);
cout << "ID : "; cin >> iSelectID;
if (cin.fail())
{
cin.clear();
cin.ignore(INT_MAX, '\n');
continue;
}
iExistID = Search(strNameUpdate, iSelectID, iBookCount, _book);
Update(iExistID, _book);
cout << "Do you keep updating? [y: Continue, n: Exit] : ";
char cYorN;
cin >> cYorN;
switch (cYorN)
{
case 'y':
case 'Y':
continue;
case 'n':
case 'N':
break;
}
break;
}
break;
case MENU_SEARCH:
system("cls");
char strNameSearch[NAME];
while (true)
{
system("cls");
cout << "================ Searching a student info ================" << endl;
cout << "BookName : "; cin >> strNameSearch;
cout << "ID : "; cin >> iSelectID;
if (cin.fail())
{
cin.clear();
cin.ignore(INT_MAX, '\n');
cout << "It's wrong ! Try again !\n";
continue;
}
iExistID = Search(strNameSearch, iSelectID, iBookCount, _book);
Print(iExistID, _book);
cout << endl << "Do you looking for ohter book's info again? " << endl;
cout << "[Y | y] : Researching" << endl;
cout << "[N | n] : Exit" << endl;
char cYorN;
cout << "Input : "; cin >> cYorN;
switch (cYorN)
{
case 'Y':
case 'y':
continue;
case 'N':
case 'n':
break;
}
break;
}
break;
case MENU_DELETE:
system("cls");
char strNameDelete[NAME];
while (true)
{
system("cls");
cout << "================ Update a student info ================" << endl;
cout << "FirstName : "; cin >> strNameDelete;
cout << "ID : "; cin >> iSelectID;
if (cin.fail())
{
cin.clear();
cin.ignore(INT_MAX, '\n');
continue;
}
iExistID = Search(strNameDelete, iSelectID, iBookCount, _book);
if (iExistID == 0)
{
char cYorN;
cout << "It is not exist book.\n";
cout << "Y : Continue, N : Exit : ";
cin >> cYorN;
switch (cYorN)
{
case 'Y':
case 'y':
continue;
case 'N':
case 'n':
break;
}
}
else {
Delete(iExistID, iBookCount, _book);
}
break;
}
break;
default:
cout << "It's wrong number. Try again~";
break;
}
system("pause");
system("cls");
}
return 0;
}
void PrintAll(int iBookCnt, _Book _book[])
{
for (int i = 0; i < iBookCnt; ++i)
{
cout << "================ Readding a student info [" << i + 1 << "] ================" << endl;
cout << setw(25) << "Name" << ": " << _book[i].strName << endl;
cout << setw(25) << "BookID" << ": " << _book[i].lID << endl;
cout << setw(25) << "Author" << ": " << _book[i].strAuthor << endl;
cout << setw(25) << "Description" << ": " << _book[i].strDescript << endl;
cout << setw(25) << "Publisher" << ": " << _book[i].strPubli << endl;
cout << setw(25) << "Nation" << ": " << _book[i].strNation << endl;
cout << setw(25) << "Rental Price" << ": " << _book[i].iPrice << endl;
if (_book[i].bRental == 1)
{
cout << setw(25) << "Rental status" << ": " << "On loan" << endl;
}
else if (_book[i].bRental == 0)
{
cout << setw(25) << "Loan status" << ": " << "Rentable" << endl;
}
}
}
void Print(int iExistID, _Book _book[])
{
int iNum = iExistID - 1;
cout << "================ Readding a student info [" << iNum + 1 << "] ================" << endl;
cout << setw(25) << "Name" << ": " << _book[iNum].strName << endl;
cout << setw(25) << "BookID" << ": " << _book[iNum].lID << endl;
cout << setw(25) << "Author" << ": " << _book[iNum].strAuthor << endl;
cout << setw(25) << "Description" << ": " << _book[iNum].strDescript << endl;
cout << setw(25) << "Publisher" << ": " << _book[iNum].strPubli << endl;
cout << setw(25) << "Nation" << ": " << _book[iNum].strNation << endl;
cout << setw(25) << "Rental Price" << ": " << _book[iNum].iPrice << endl;
if (_book[iNum].bRental == 1)
{
cout << setw(25) << "Rental status" << ": " << " On loan" << endl;
}
else if (_book[iNum].bRental == 0)
{
cout << setw(25) << "Loan status" << ": " << " Rentable" << endl;
}
}
long Search(char strNameUpdate[], long iSelectID, int iBookCount, _Book _book[])
{
long lSelectedID;
int isExist = 0;
for (int i = 0; i < iBookCount; ++i)
{
if (strcmp(strNameUpdate, _book[i].strName) == 0 && iSelectID == _book[i].lID)
{
lSelectedID = _book[i].lID;
isExist = 1;
}
}
if (isExist == 1)
return lSelectedID;
else if (isExist == 0)
return 0;
}
void Update(long iSelectedID, _Book _book[])
{
while (true)
{
system("cls");
int iItem = NULL;
cout << "1: Price" << endl;
cout << "2: IsRental" << endl;
cout << "Select a item to update :"; cin >> iItem;
switch (iItem)
{
case ITEM_PRICE:
cout << "New Price :"; cin >> _book[iSelectedID - 1].iPrice;
cout << endl << "Changed Price : " << _book[iSelectedID - 1].iPrice << endl;
break;
case ITEM_RENTAL:
cout << "IsRental ? [1: yes, 0: no] :"; cin >> _book[iSelectedID - 1].bRental;
cout << endl << "Changed IsRental : " << _book[iSelectedID - 1].bRental << endl;
break;
default:
break;
}
cout << "Do you keep updating other item? [y: Continue, n: Exit item] ";
char cYorN;
cin >> cYorN;
switch (cYorN)
{
case 'y':
case 'Y':
continue;
case 'n':
case 'N':
break;
}
break;
}
}
void Delete(int iExistID, int& iBookCount, _Book _book[])
{
cout << "Deleted " << _book[iExistID].strName << "'s data. \n";
for (int i = iExistID; i < iBookCount; ++i)
{
_book[i] = _book[i + 1];
}
--iBookCount;
}
| true |
3819f5136c611b2018f8b577b7e4dab1795f80fa | C++ | LucasEBSkora/jogo-tecnicas | /Managers/GraphicsManager.hpp | UTF-8 | 1,305 | 2.640625 | 3 | [] | no_license | #ifndef GRAPHICSMANAGER_HPP
#define GRAPHICSMANAGER_HPP
#include <utility> // std::pair
#include <map>
#include <string>
#include <SFML/Graphics.hpp>
#include "../Utils/GeometricVector.hpp"
namespace DIM {
namespace Managers {
class GraphicsManager {
private:
std::map<std::string, sf::Texture*> assets;
sf::RenderWindow* window;
sf::View view;
Utils::VectorF camera_pos;
Utils::VectorF camera_size;
sf::Font font;
const bool outOfSight(Utils::VectorF at, Utils::VectorF size) const;
public:
GraphicsManager();
~GraphicsManager();
const bool loadAsset(const std::string& path);
void draw(const std::string& id, Utils::VectorF at) const;
void drawRect(Utils::VectorF at, Utils::VectorF size, int r, int g, int b) const;
void drawTextCentered(const std::string& text, Utils::VectorF at, unsigned size) const;
void centerCamera(Utils::VectorF at);
sf::Window* getWindow() const;
void display() const;
void clear(int r, int g, int b) const;
const Utils::VectorF getViewSize() const;
const Utils::VectorF getMousePos() const;
const Utils::VectorF getMousePosInView() const;
const Utils::VectorF getSizeOfAsset(const std::string& id) const;
};
}
}
#endif | true |
1455a128389b6f912ab2d7445622116c98e905b3 | C++ | TTashev/Cpp-Programming | /JudgeAssingment2/ClosestTowns/main.cpp | UTF-8 | 2,347 | 2.9375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include "Vector2D.h"
using namespace std;
int main()
{
int NumberOfTowns;
cin >> NumberOfTowns;
vector<string> Towns;
vector<double> TownCoordinatesX;
vector<double> TownCoordinatesY;
cin.ignore();
string input;
for(int i = 0; i < NumberOfTowns; i++)
{
getline(cin, input);
int firstWhiteSpaceIndex = input.find(' ');
string City = input.substr(0,firstWhiteSpaceIndex);
int coordinateCount = 0;
double x, y;
x = y = 0;
coordinateCount = -1;
stringstream Coordinates(input);
string word;
while(Coordinates >> word)
{
istringstream num(word);
if(coordinateCount < 1)
{
num >> x;
}
else
{
num >> y;
}
coordinateCount++;
}
Towns.push_back(City);
TownCoordinatesX.push_back(x);
TownCoordinatesY.push_back(y);
}
double DistanceOfClosestTowns = (double)INT_MAX;
double CurrentDistanceOfClosestTowns = (double)INT_MAX;
vector<string> ClosestTowns;
for(int t = 0; t < Towns.size(); t++)
{
string CurrTown = Towns[t];
for(int c = t + 1; c < Towns.size(); c++)
{
string SecondCurrTown = Towns[c];
CurrentDistanceOfClosestTowns = sqrt(((TownCoordinatesX[c] - TownCoordinatesX[t]) * (TownCoordinatesX[c] - TownCoordinatesX[t])) + ((TownCoordinatesY[c] - TownCoordinatesY[t]) * (TownCoordinatesY[c] - TownCoordinatesY[t])));
if(CurrentDistanceOfClosestTowns < DistanceOfClosestTowns)
{
DistanceOfClosestTowns = CurrentDistanceOfClosestTowns;
if(ClosestTowns.empty())
{
ClosestTowns.push_back(Towns[t] + "-" + Towns[c]);
}
else
{
ClosestTowns.pop_back();
ClosestTowns.push_back(Towns[t] + "-" + Towns[c]);
}
}
}
}
for(int a = 0; a < ClosestTowns.size(); a++)
{
cout << ClosestTowns[a] << endl;
}
return 0;
}
| true |
08e33bbbb961d06f0111ed8274edaff50e92909c | C++ | kshashwat/Cpp-Basics | /Completed USACO Problems/crosswords.cc | UTF-8 | 1,607 | 3.03125 | 3 | [] | no_license | /*
ID: kshashw1
PROG: crosswords
LANG: C++11
*/
#include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include <math.h>
#include <utility>
using namespace std;
int main() {
ifstream fin ("crosswords.in");
ofstream fout ("crosswords.out");
long long N;
long long M;
string input_str;
fin >> N >> M;
vector<string> table;
for (long long i = 0; i < N; i++) {
input_str.clear();
fin >> input_str;
table.push_back(input_str);
}
vector<long long> x;
vector<long long> y;
long long num_clues = 0;
for (long long i = 0; i < N; i++) {
for (long long j = 0; j < M; j++) {
if (j == 0 && table[i][0] == '.' && table[i][1] == '.' && table[i][2] == '.') {
x.push_back(i+1);
y.push_back(j+1);
num_clues++;
}
else if (j > 0 && j <= M-3 && table[i][j-1] == '#' && table[i][j] == '.' && table[i][j+1] == '.' && table[i][j+2] == '.') {
x.push_back(i+1);
y.push_back(j+1);
num_clues++;
}
else if (i == 0 && table[0][j] == '.' && table[1][j] == '.' && table[2][j] == '.') {
x.push_back(i+1);
y.push_back(j+1);
num_clues++;
}
else if (i > 0 && i <= N-3 && table[i-1][j] == '#' && table[i][j] == '.' && table[i+1][j] == '.' && table[i+2][j] == '.') {
x.push_back(i+1);
y.push_back(j+1);
num_clues++;
}
}
}
if (num_clues == 0) {
fout << 0 << endl;
return 0;
}
fout << num_clues << endl;
for (long long i = 0; i < num_clues; i++) {
fout << x[i] << " " << y[i] << endl;
}
return 0;
}
| true |
6b149cb84069288d7f3e688d67edd58e08196d9d | C++ | binzume/cppfl | /include/encode.h | UTF-8 | 5,832 | 2.703125 | 3 | [] | no_license | #ifndef _ENCODE_H
#define _ENCODE_H
#include <string>
namespace Encode{
#ifdef _WIN32
#include <windows.h>
typedef int ENCODE;
static const ENCODE AUTO=0; // NOT SUPPORT
static const ENCODE SJIS=932;
static const ENCODE UTF8=CP_UTF8;
static const ENCODE EUCJP=51932; // NOT SUPPORT
static std::string encode(const std::string &src,const ENCODE &from, const ENCODE &to)
{
int len = MultiByteToWideChar(from,0,src.c_str(),src.length(),NULL,0);
wchar_t *buf1 = new wchar_t[len];
len = MultiByteToWideChar(from,0,src.c_str(),src.length(),buf1,len);
int len2=WideCharToMultiByte(to,0,buf1,len,NULL,0,NULL,NULL);
char *buf2 = new char[len2+1];
len=WideCharToMultiByte(to,0,buf1,len,buf2,len2,NULL,NULL);
buf2[len2]=0;
std::string s=buf2;
delete [] buf1;
delete [] buf2;
return s;
}
// iconv
#else
#include <iconv.h>
typedef const char* ENCODE;
static const ENCODE AUTO=NULL;
static const ENCODE SJIS="SHIFT_JIS";
static const ENCODE UTF8="UTF-8";
static const ENCODE EUCJP="EUC-jp";
static std::string encode(const std::string &src,const ENCODE &to, const ENCODE &from)
{
std::string s;
const char *lps = src.c_str();
size_t len = src.length();
char dst[256];
char *dst2 = dst;
size_t size = (size_t)sizeof(dst);
iconv_t c = iconv_open(from,to);
do {
if (iconv(c,const_cast<char**>(&lps),&len ,&dst2 ,&size) <0 ) return s; // error
s.append(dst,sizeof(dst)-size);
dst2=dst;
size = (size_t)sizeof(dst);
} while(len);
iconv_close(c);
return s;
}
#endif
class IStringIterator{
public:
virtual int shift() = 0;
virtual bool eof() = 0;
};
template<typename T>
class StringIteratorProxy : public IStringIterator{
T sf;
public:
StringIteratorProxy(const T &s):sf(s){}
StringIteratorProxy(const typename T::iterator &begin, const typename T::iterator &end):sf(begin,end){}
int shift(){return sf.shift();}
bool eof(){return sf.eof();}
int operator *(){
typename T::iterator tmp = sf.it;
return sf.shift(tmp);
}
bool operator !=(const typename T::iterator &s) {
return sf.it!=s;
}
StringIteratorProxy& operator ++() {
sf.shift();
return *this;
}
StringIteratorProxy operator ++(int) {
StringIteratorProxy tmp=*this;
sf.shift();
return tmp;
}
};
template<typename T>
class EmptyStringIterator{
T it,end;
public:
EmptyStringIterator(T begin_,T end_):it(begin_),end(end_) {};
int shift(T &it){int a=*it;++it; return a;}
bool eof(){return it==end;}
int shift(){
return shift(it);
}
};
template<typename T>
class StringIterator_SJIS{
friend class StringIteratorProxy< StringIterator_SJIS >;
T it,end;
inline bool isFirstByte(unsigned char c) {
return ((unsigned char)((c^0x20)-0xA1)<=0x3B);
}
public:
typedef T iterator;
StringIterator_SJIS(T begin_,T end_):it(begin_),end(end_) {};
int shift(T &it){
if (it==end) return -1;
int c = (unsigned char)*it;
++it;
if (it==end) return c;
if( isFirstByte(c) ) {
c = (unsigned char)(*it) | c<<8;
++it;
}
//char j1 = (s0<<1) - (s0 <= 0x9f ? 0xe0:0x160) - (s1 < 0x9f ? 1:0);
//char j2 = s1 - 0x1f - (s1 >= 0x7f ? 1:0) - (s1 >= 0x9f ? 0x5e:0);
//c = ((j1&0x7f)<<7) | (j2&0x7f);
return c;
}
int shift(){
return shift(it);
}
bool eof(){return it==end;}
};
template<typename T>
class StringIterator_UTF8{
friend class StringIteratorProxy< StringIterator_UTF8<T> >;
T it,end;
public:
typedef T iterator;
StringIterator_UTF8(const T &begin_,const T &end_):it(begin_),end(end_) {};
int shift(T &it){
if (it==end) return -1;
int code,bits,i=0;
code = *it; ++it;
int c=code;
i++;
bits=6;
if (c&0x80) {
while(c&0x40) {
code=(code<<6)|(*it&0x3f);
bits+=5;
++it;
++i;
c<<=1;
}
}
if (bits==6) bits++;
code &= (1<<bits)-1;
return code;
}
int shift(){
return shift(it);
}
bool eof(){return it==end;}
};
template<typename T>
class StringIterator_EUC{
friend class StringIteratorProxy< StringIterator_EUC >;
T it,end;
public:
typedef T iterator;
StringIterator_EUC(const T &begin_,const T &end_):it(begin_),end(end_) {};
int shift(T &it){
int c = (unsigned char)*it;
if( c&0x80 )
c = (unsigned char)*(++it) | c<<8;
it++;
return c&0x7f7f;
}
int shift(){
return shift(it);
}
bool eof(){return it==end;}
};
template<typename T>
class StringIterator_JIS{
friend class StringIteratorProxy< StringIterator_JIS >;
T it,end;
int jismode;
public:
typedef T iterator;
StringIterator_JIS(const T &begin_,const T &end_):it(begin_),end(end_) {};
int shift(T &it){
if (*it==0x1b) { // KI/KO
if (*++it=='$' && *++it=='B') {jismode=1;++it;}
if (*++it=='(' && *++it=='B') {jismode=0;++it;}
}
int c = (unsigned char)*it;
if( jismode )
c = (unsigned char)*(++it) | c<<8;
return c;
}
int shift(){
return shift(it);
}
bool eof(){return it==end;}
};
typedef StringIteratorProxy< StringIterator_SJIS< std::string::iterator > > SJIS_IteratorS;
typedef StringIteratorProxy< StringIterator_SJIS< char const* > > SJIS_IteratorC;
typedef StringIteratorProxy< StringIterator_UTF8< std::string::iterator > > UTF8_IteratorS;
typedef StringIteratorProxy< StringIterator_UTF8< char const* > > UTF8_IteratorC;
template<typename T>
std::string& stringEncode_SJIS(std::string &s,T begin,T end)
{
s.clear();
for(;begin!=end;++begin) {
if (*begin>0xff)
s.push_back(*begin>>8);
s.push_back(*begin);
}
return s;
}
template<typename T>
std::string& stringEncode_UTF8(std::string &s,T begin,T end)
{
s.clear();
for(;begin!=end;++begin) {
short wc = *begin;
if (wc<=0x7f) {s.push_back((char)wc); continue; }
unsigned char m = 0x1f;
unsigned char m2=0x7f;
int i=0;
do {
i++;
m>>=1;
m2>>=1;
}while (m && m < (wc>>6*i));
int t=i+1;
s.push_back((char)(wc>>6*i) | ~m2);
do {
i--;
s.push_back((char)(wc>>6*i)&0x3f | 0x80);
} while(i);
}
return s;
}
}
#endif
| true |
42348fc1e9b291e5e38089da0e68a4a10f138826 | C++ | erekc/cartesian-data-generator | /src/test/test.cpp | UTF-8 | 1,466 | 3.203125 | 3 | [] | no_license | #include "../../headers/test/nndatatest.h"
#include "../../headers/test/nntrainingdatatest.h"
void acceptNNTrainingDataByValue(NNTrainingDataTest data){
std::cout << "Accepted NNTrainingData by value" << std::endl;
// data destructs
}
void test1(){
NNTrainingDataTest data1 = NNTrainingDataTest(50, 2, 3); // Constructor
NNTrainingDataTest data2 = NNTrainingDataTest(100, 2, 3); // Constructor
data1 = data2; // Copy Assignment
NNTrainingDataTest data3(data1); // Copy Constructor
NNTrainingDataTest data4(std::move(data2)); //Move Constructor
data4 = std::move(data3); // Move Assignment
// Everything destructs (4 objects total)
}
void test2(){
NNTrainingDataTest data1 = NNTrainingDataTest(50, 2, 3); // Constructor
NNTrainingDataTest data2 = NNTrainingDataTest(100, 2, 3); // Constructor
NNTrainingDataTest data3(data1); // Copy Constructor
{
NNTrainingDataTest data4(std::move(data2)); // Move Constructor (invalidates data2)
{
NNTrainingDataTest data5 = NNTrainingDataTest(75, 2, 3);
data5 = data4; // Copy Assignment
data5 = std::move(data3); // Move Assignment (invalidates data3)
// data5 destructs
}
// data4 destructs
}
acceptNNTrainingDataByValue(data1); // Copy constructor and Destructor called inside function
// data1, data2, and data3 destructs
}
int main(){
test1();
test2();
return 0;
}
| true |
f7e3dbb4eddc1475cfa4cb2cefcf1d38c9d67e4e | C++ | MokraneAc/TicTacToe_cpp | /tictactoe++/Logic.cpp | UTF-8 | 4,612 | 3.109375 | 3 | [] | no_license | #include "Logic.h"
bool Logic::isMovesLeft(char board[3][3])
{
for (int i = 0; i<3; i++)
for (int j = 0; j<3; j++)
if (board[i][j]=='_')
return true;
return false;
}
int Logic::game_over(sf::RenderWindow &window ,char board[3][3]){
string path2;
char result = evaluate(board,player,opponent);
if (result == +10){
path2 ="Xwin.png";
Game::drawgrid(window,"red.png");
if (Winner(board) == 1){
Game::winner_drawc(window,path2,35,195,355,95);
}
if (Winner(board) == 2){
Game::winner_drawc(window,path2,35,195,355,255);
}
if (Winner(board) == 3){
Game::winner_drawc(window,path2,35,195,355,412);
}
if (Winner(board) == 4){
Game::winner_drawl(window,path2,95,255,412,35);
}
if (Winner(board) == 5){
Game::winner_drawl(window,path2,95,255,412,195);
}
if (Winner(board) == 6){
Game::winner_drawl(window,path2,95,255,412,355);}
if (Winner(board) == 7){
Game::winner_drawD(window,path2);}
if (Winner(board) == 8){
Game::winner_drawAD(window,path2);}
}
if (result == -10){
path2 ="Owin.png";
Game::drawgrid(window,"green.png");
if (Winner(board) == 1){
Game::winner_drawc(window,path2,35,195,355,95);
}
if (Winner(board) == 2){
Game::winner_drawc(window,path2,35,195,355,255);
}
if (Winner(board) == 3){
Game::winner_drawc(window,path2,35,195,355,412);
}
if (Winner(board) == 4){
Game::winner_drawl(window,path2,95,255,412,35);
}
if (Winner(board) == 5){
Game::winner_drawl(window,path2,95,255,412,195);
}
if (Winner(board) == 6){
Game::winner_drawl(window,path2,95,255,412,355);}
if (Winner(board) == 7){
Game::winner_drawD(window,path2);}
if (Winner(board) == 8){
Game::winner_drawAD(window,path2);}
}
}
int Logic::Winner(char matrix[3][3])
{
if(matrix[0][0] == 'x' && matrix[0][1] == 'x' && matrix[0][2] == 'x')
return 1;
if(matrix[1][0] == 'x' && matrix[1][1] == 'x' && matrix[1][2] == 'x')
return 2;
if(matrix[2][0] == 'x' && matrix[2][1] == 'x' && matrix[2][2] == 'x')
return 3;
if(matrix[0][0] == 'x' && matrix[1][0] == 'x' && matrix[2][0] == 'x')
return 4;
if(matrix[0][1] == 'x' && matrix[1][1] == 'x' && matrix[2][1] == 'x')
return 5;
if(matrix[0][2] == 'x' && matrix[1][2] == 'x' && matrix[2][2] == 'x')
return 6;
if(matrix[0][0] == 'x' && matrix[1][1] == 'x' && matrix[2][2] == 'x')
return 7;
if(matrix[0][2] == 'x' && matrix[1][1] == 'x' && matrix[2][0] == 'x')
return 8;
if(matrix[0][0] == 'o' && matrix[0][1] == 'o' && matrix[0][2] == 'o')
return 1;
if(matrix[1][0] == 'o' && matrix[1][1] == 'o' && matrix[1][2] == 'o')
return 2;
if(matrix[2][0] == 'o' && matrix[2][1] == 'o' && matrix[2][2] == 'o')
return 3;
if(matrix[0][0] == 'o' && matrix[1][0] == 'o' && matrix[2][0] == 'o')
return 4;
if(matrix[0][1] == 'o' && matrix[1][1] == 'o' && matrix[2][1] == 'o')
return 5;
if(matrix[0][2] == 'o' && matrix[1][2] == 'o' && matrix[2][2] == 'o')
return 6;
if(matrix[0][0] == 'o' && matrix[1][1] == 'o' && matrix[2][2] == 'o')
return 7;
if(matrix[0][2] == 'o' && matrix[1][1] == 'o' && matrix[2][0] == 'o')
return 8;
return '/';
}
int Logic::evaluate(char b[3][3] , char player ,char opponent)
{
for (int row = 0; row<3; row++)
{
if (b[row][0]==b[row][1] &&
b[row][1]==b[row][2])
{
if (b[row][0]==player)
return +10;
else if (b[row][0]==opponent)
return -10;
}
}
for (int col = 0; col<3; col++)
{
if (b[0][col]==b[1][col] &&
b[1][col]==b[2][col])
{
if (b[0][col]==player)
return +10;
else if (b[0][col]==opponent)
return -10;
}
}
// Checking for Diagonals for X or O victory.
if (b[0][0]==b[1][1] && b[1][1]==b[2][2])
{
if (b[0][0]==player)
return +10;
else if (b[0][0]==opponent)
return -10;
}
if (b[0][2]==b[1][1] && b[1][1]==b[2][0])
{
if (b[0][2]==player)
return +10;
else if (b[0][2]==opponent)
return -10;
}
return 0;
}
bool Logic::retry(sf::RenderWindow &window,char board[3][3]){
if (Logic::isMovesLeft(board) == false){
Game::check_end(window ,"background.png");
return true;
}
if ( Logic::evaluate(board,player,opponent)== +10){
Game::check_end(window ,"red.png");
return true;
}
if ( Logic::evaluate(board,player,opponent)== -10){
Game::check_end(window ,"green.png");
return true;
}
}
void Logic::init(char board[3][3]){
for (int i = 0;i<3;i++){
for (int j = 0;j<3;j++){
board[i][j] = '_';
}
}
}
Logic::Logic()
{
//ctor
}
Logic::~Logic()
{
//dtor
}
| true |
bd56ff531f2c1b4b399a08941060b63d7c8f3e14 | C++ | KeinR/APPC_term_project | /src/nocopylazy.h | UTF-8 | 519 | 2.796875 | 3 | [] | no_license | #ifndef NOCOPYLAZY_H_INCLUDED
#define NOCOPYLAZY_H_INCLUDED
// Extended if the reason for no copy or move constructors/operators
// is because it's not worth the time and effort due to them
// not being used, rather than any technical reason.
class nocopylazy {
public:
nocopylazy();
virtual ~nocopylazy() = 0;
nocopylazy(nocopylazy&&) = delete;
nocopylazy(const nocopylazy&) = delete;
nocopylazy &operator=(nocopylazy&&) = delete;
nocopylazy &operator=(const nocopylazy&) = delete;
};
#endif
| true |
bcad01fa220f16d7274a362d9ffda27308e44379 | C++ | tamyiuchau/competitve_programming_pratice | /poj/3253-fence_repair(not_tested).cpp | UTF-8 | 765 | 3.125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <set>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
vector<int> fence;
int search(const vector<int>::iterator begin,const vector<int>::iterator end) {
if (end - begin == 1)return 0;
if (end-begin==2)return accumulate(begin, end, 0);
int sum = accumulate(begin, end,0);
vector<int>::iterator middle = upper_bound(begin, end, sum / (end - begin));
if (*middle - *(middle - 1) > *(middle + 1) - *middle)middle++;
return sum + search(begin, middle) + search(middle, end);
}
int main() {
int count;
cin >> count;
for (int i = 0; i < count; i++) {
int _tmp;
cin >> _tmp;
fence.push_back(_tmp);
}
sort(fence.begin(), fence.end());
cout << search(fence.begin(), fence.end());
return 0;
}
| true |
6e1db727619eacfbe0f51ce90a469b769bd6b4a0 | C++ | FeiZhao0531/PlayLeetCode | /LinkedList/0445-Add-Two-Numbers-II/main-20ms.cpp | GB18030 | 2,144 | 3.421875 | 3 | [
"MIT"
] | permissive | /// https://leetcode.com/problems/add-two-numbers-ii/
/// Author : Fei
/// Time : Jun-4-2019
#include <iostream>
#include "../SingleLinkedList.h"
#include "../SingleLinkedList.cpp"
#include <vector>
using namespace std;
class Solution {
public:
// 1.ת002ͬ
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
return reverseList( addTwoNumbersReverse( reverseList( l1), reverseList( l2)));
}
private:
ListNode* reverseList( ListNode* head) {
ListNode* pre = NULL;
ListNode* curr = head;
while( curr) {
ListNode* aft = curr->next;
curr->next = pre;
pre = curr;
curr = aft;
}
return pre;
}
ListNode* addTwoNumbersReverse( ListNode* l1, ListNode* l2) {
ListNode* sumHead = new ListNode(0);
ListNode* curr = sumHead;
int carry = 0;
while( l1 || l2 || carry) {
int sum = carry;
if( l1) {
sum += l1->val;
l1 = l1->next;
}
if( l2) {
sum += l2->val;
l2 = l2->next;
}
carry = sum / 10;
ListNode* sumNode = new ListNode( sum % 10);
curr->next = sumNode;
curr = curr->next;
}
ListNode* res = sumHead->next;
delete sumHead;
sumHead = NULL;
return res;
}
};
int main()
{
int arr1[] = {7,2,4,3};
int arr2[] = {5,6,4};
// int arr1[] = {0};
// int arr2[] = {0};
int n1 = sizeof(arr1)/sizeof(arr1[0]);
int n2 = sizeof(arr2)/sizeof(arr2[0]);
SingleLinkedList mysinglelinkedlist;
ListNode* l1 = mysinglelinkedlist.createSingleLinkedList(arr1, n1);
ListNode* l2 = mysinglelinkedlist.createSingleLinkedList(arr2, n2);
mysinglelinkedlist.printSingleLinkedList(l1);
mysinglelinkedlist.printSingleLinkedList(l2);
ListNode* head = Solution().addTwoNumbers2(l1,l2);
mysinglelinkedlist.printSingleLinkedList(head);
mysinglelinkedlist.deleteSingleLinkedList(head);
//system("pause");
return 0;
}
| true |
e5cbc24b7c0ba423ea89496d20aa81108ee798c5 | C++ | ImAbdollahzadeh/GenericLinkedList_HashTable | /GenericLinkedList.h | UTF-8 | 2,046 | 2.765625 | 3 | [
"MIT"
] | permissive | #pragme once
#ifndef GENERICLISTLIST_H_
#define GENERICLISTLIST_H_
template<typename T> struct Node
{
Node<T>* nextPointer;
Node<T>* backPointer;
T Value;
};
template<typename T, typename U> struct SameType
{
static constexpr bool result = false;
};
template<typename T> struct SameType<T, T>
{
static constexpr bool result = true;
};
struct ID
{
enum class _ID
{
INT ,
FLOAT ,
CHAR ,
DOUBLE ,
BOOL ,
STRING ,
INT_VECTOR ,
ANY_THING_ELSE,
};
static int EnumToInt(const _ID& enumerationIDs);
};
template<typename T> class List
{
private:
static int index;
Node<T>* beginnerNode;
Node<T>* firstDanglingNode;
Node<T>* currentNode;
void EmptyNode();
const char* TypeID() const;
public:
explicit List<T>();
void assign(const T&);
void printList() const;
void freeResource();
template<int Size>
void assignMore_decimalTypes_(T value, ...);
template<typename U, U first, U... args>
void assignMore_intergralTypes_();
};
template<typename T> int List<T>::index = 1;
template<typename T, T first, T...args> struct _AssignMore_
{
void internallyFunction(List<T>*);
};
template<typename T, T last> struct _AssignMore_<T, last>
{
void internallyFunction(List<T>*);
};
template<typename T, typename...U> struct TypeGeneratorOfListHead
{
typedef T Head;
};
template<typename T> struct TypeGeneratorOfListHead<T>
{
typedef T Head;
};
template<typename T, typename...U> struct HashTable
{
HashTable(const T&, const U&...);
template<typename V, typename...W>
void generate(const typename TypeGeneratorOfListHead<V, W...>::Head&, const W&...);
template<typename V, typename...W>
void generate(const typename TypeGeneratorOfListHead<V, W...>::Head&);
template<typename AsListType>
void printIt(const AsListType* const);
};
#endif
| true |
9ecf1ca6e23f47c61708f226598b81796b01609d | C++ | shadowcomer/CatLing | /Source/Task.h | UTF-8 | 2,153 | 3.15625 | 3 | [] | no_license | /*
This file contains the Task abstract class and specific
implementations of it.
A Task is a piece of code to be executed, accompanied by its
execution parameters.
This allows for deferred execution of a Task.
Tasks are scheduled for execution inside a TaskManager's queue.
*/
#ifndef TASK_H
#define TASK_H
#include <BWAPI.h>
class Task
{
public:
/*
Execution function to be implemented by each specific task separately.
*/
virtual void execute() = 0;
private:
};
class TGather : public Task
{
public:
/*
Task.
Sends 'unit' to gather 'target'.
shouldQueue - If true, this action is queued after any other
already executing actions on the client side of Starcraft's process.
*/
TGather(BWAPI::Unit unit, BWAPI::Unit target, bool shouldQueue);
void execute();
const BWAPI::Unit unit;
const BWAPI::Unit target;
const bool queueCommand;
private:
};
class TTrain : public Task
{
public:
/*
Task.
Trains 'unit' from 'builder'.
*/
TTrain(BWAPI::Unit builder, BWAPI::UnitType unit);
void execute();
const BWAPI::Unit builder;
const BWAPI::UnitType unit;
private:
};
class TBuild : public Task
{
public:
/*
Task.
Sends 'builder' to build 'building' at 'location'.
*/
TBuild(BWAPI::Unit builder, BWAPI::UnitType building, BWAPI::TilePosition location);
void execute();
const BWAPI::Unit builder;
const BWAPI::UnitType building;
const BWAPI::TilePosition location;
private:
/*
Verifies whether the given 'builder' is a valid builder for the 'building'.
*/
bool verifyBuildCapability();
};
class TAttack : public Task
{
public:
/*
Task.
Sends unit 'origin' to attack 'target'.
shouldQueue - If true, this action is queued after any other
already executing actions on the client side of Starcraft's process.
*/
TAttack(BWAPI::Unit origin, BWAPI::PositionOrUnit target, bool shouldQueue);
void execute();
const BWAPI::Unit origin;
const BWAPI::PositionOrUnit target;
const bool queueCommand;
private:
};
#endif | true |
a300dfaffc847f19556c814b7b3bf7354efb8126 | C++ | devedu-AI/Back_to_Basics | /Arrays/matrix_search.cpp | UTF-8 | 671 | 3.421875 | 3 | [] | no_license | //Optimized Search
#include<iostream>
using namespace std;
int main()
{
int n, m;
cin>>n>>m;
int arr[n][m];
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
cin>>arr[i][j];
}
}
int target;
cin>>target;
bool flag = false;
int r = 0, c = m-1;
//array search
while(r <= c){
if(arr[r][c] == target){
flag = true;
}
if(arr[r][c] < target){
c--;
}
else{
r++;
}
}
if(flag){
cout<<"Element found";
}
else{
cout<<"Not Found";
}
return 0;
} | true |
8dbfd1c6b42f8d376c2519964c67ed1c1f6ff335 | C++ | zeffrin/Zesmi | /ZesmiCore/initialize.cpp | UTF-8 | 1,569 | 2.5625 | 3 | [] | no_license |
#include "initialize.hpp"
Initialize* Initialize::_instance = NULL;
Initialize::Initialize()
{
}
Initialize* Initialize::getInstance()
{
if(_instance)
return _instance;
return ((_instance = new Initialize()));
}
bool Initialize::doInitialization()
{
#ifdef TARGET_OS_MAC
#error "TODO initialize for osx"
#elif defined __linux__
return init_linux();
#elif defined _WIN32 || defined _WIN64
return init_win();
#else
#error "unknown platform"
#endif
}
Initialize::~Initialize()
{
#ifdef TARGET_OS_MAC
#error "TODO initialize for osx"
#elif defined __linux__
cleanup_linux();
#elif defined _WIN32 || defined _WIN64
cleanup_win();
#else
#error "unknown platform"
#endif
}
// -----------------
#ifdef TARGET_OS_MAC
#error "TODO implement init_macosx()"
#elif defined __linux__
bool Initialize::init_linux()
{
#error "init_linux not implemented"
}
bool Initialize::cleanup_linux()
{
#error "cleanup_linux not implemented"
}
#elif defined _WIN32 || defined _WIN64
bool Initialize::init_win()
{
WSADATA wsaData;
int iResult;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
// TODO: replace with logger
//printf("WSAStartup failed: %d\n", iResult);
return false;
}
return true;
}
bool Initialize::cleanup_win()
{
int iResult;
iResult = WSACleanup();
if(iResult != 0) {
// TODO: log failure with logger
return false;
}
return true;
}
#else
#error "unknown platform"
#endif
| true |
e9ee77ef3f1c62f478d3f195a48747f5373350ba | C++ | priety33/hashmaps | /Counting Elements.cpp | UTF-8 | 1,077 | 3.46875 | 3 | [] | no_license | class Solution {
public:
int countElements(vector<int>& arr) {
unordered_map<int,int> m;
for(int i=0;i<arr.size();i++) m[arr[i]]++;
int count=0;
for(int i=0; i<arr.size(); i++)
{
if(m.find(arr[i]+1)!=m.end())
{
count++;
m[arr[i]]--;
}
}
return count;
}
};
Given an integer array arr, count element x such that x + 1 is also in arr.
If there're duplicates in arr, count them seperately.
Example 1:
Input: arr = [1,2,3]
Output: 2
Explanation: 1 and 2 are counted cause 2 and 3 are in arr.
Example 2:
Input: arr = [1,1,3,3,5,5,7,7]
Output: 0
Explanation: No numbers are counted, cause there's no 2, 4, 6, or 8 in arr.
Example 3:
Input: arr = [1,3,2,3,5,0]
Output: 3
Explanation: 0, 1 and 2 are counted cause 1, 2 and 3 are in arr.
Example 4:
Input: arr = [1,1,2,2]
Output: 2
Explanation: Two 1s are counted cause 2 is in arr.
Example 5: (imp)
Input: arr = [2,2,3,3,3,4,4,4]
Output: 5
Example 6: (imp)
Input: arr = [1,1,2]
Output: 2
| true |
0f6cac8ad14f3ef2da45eef2de8153073a6ab28c | C++ | prudentboy/leetcode | /Solutions/999.available-captures-for-rook.cpp | UTF-8 | 1,562 | 2.921875 | 3 | [] | no_license | /*
* @lc app=leetcode id=999 lang=cpp
*
* [999] Available Captures for Rook
*/
class Solution {
public:
int numRookCaptures(vector<vector<char>>& board) {
int ans(0);
int i(0), j(0), x(0), y(0);
for (x = 0; x < board.size(); ++x)
{
for (y = 0; y < board[0].size(); ++y)
{
if (board[x][y] == 'R')
{
i = x;
j = y;
break;
}
}
}
//cout << i << ' ' << j << endl;
int tmp(0);
for (tmp = 1; i - tmp >= 0; ++tmp)
{
if (board[i - tmp][j] == 'B') break;
if (board[i - tmp][j] == 'p')
{
++ans;
break;
}
}
for (tmp = 1; i + tmp < board.size(); ++tmp)
{
if (board[i + tmp][j] == 'B') break;
if (board[i + tmp][j] == 'p')
{
++ans;
break;
}
}
for (tmp = 1; j - tmp >= 0; ++tmp)
{
if (board[i][j - tmp] == 'B') break;
if (board[i][j - tmp] == 'p')
{
++ans;
break;
}
}
for (tmp = 1; j + tmp < board[0].size(); ++tmp)
{
if (board[i][j + tmp] == 'B') break;
if (board[i][j + tmp] == 'p')
{
++ans;
break;
}
}
return ans;
}
};
| true |
ff232f3fa5cbf88d1672e3db75b122308ff90497 | C++ | Alvarez-Rivera-Jorge-Adrian/Repo1B | /A_B_C_EN_C.cpp | UTF-8 | 543 | 3.09375 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <cmath>
int main (){
float a, b, c, res, ress, resss;
printf("VALOR DE A: ");
scanf("%f", &a);
printf("VALOR DE B: ");
scanf("%f",&b);
res=a+b;
printf("\nLA SUMA DE A+B: %f: ",res);
ress=res*res*res;
printf("\nLA SUMA DE A+B ELEVADO AL CUBO: %f ", ress);
printf("\n\nVALOR DE C: ");
scanf("%f", &c);
if(c!=0){
resss=ress/c;
printf("\nEL RESULTADO DE LA OPERACION A+B ELEVADO AL CUBO ENTRE C ES: %f", resss);
}
else{
printf("ERROR DIVISION: ");
}
return 0;
}
| true |
6b9ad24a0124f8ba7d344af63501c9e8b0df1a77 | C++ | dirmich/MonkSWF | /src/tags/RemoveObject.h | UTF-8 | 979 | 2.5625 | 3 | [] | no_license | /*
* RemoveObject.h
* MonkSWF
*
* Created by Micah Pearlman on 5/7/09.
* Copyright 2009 MP Engineering. All rights reserved.
*
*/
#ifndef __RemoveObject_h__
#define __RemoveObject_h__
#include "mkTag.h"
#include <iostream>
using namespace std;
namespace MonkSWF {
class RemoveObjectTag : public IRemoveObjectTag {
public:
RemoveObjectTag( TagHeader& h )
: IRemoveObjectTag( h )
{}
virtual ~RemoveObjectTag() {
}
virtual bool read( Reader* reader ) {
if( code() == REMOVEOBJECT )
_character_id = reader->get<uint16_t>();
_depth = reader->get<uint16_t>();
return true;
}
virtual void print() {
if( code() == REMOVEOBJECT )
cout << "REMOVEOBJECT id = " << _character_id << " depth = " << _depth << endl;
else
cout << "REMOVEOBJECT2 depth = " << _depth << endl;
}
static ITag* create( TagHeader* header ) {
return (ITag*)(new RemoveObjectTag( *header ));
}
};
}
#endif // __RemoveObject_h__ | true |
cbc960da2c8655051098ff3a8e612b8abffe3ca6 | C++ | SpyrosLahanas/Alpha-Vantage-API-CPP | /sources/Instrument.cpp | UTF-8 | 4,087 | 3.015625 | 3 | [] | no_license | #include "Instrument.hpp"
void DayInfo::print()
{
std::cout << "Open: " << open << std::endl;
std::cout << "High: " << high << std::endl;
std::cout << "Low: " << low << std::endl;
std::cout << "Close: " << close << std::endl;
std::cout << "Adjusted Close: " << adjclose << std::endl;
std::cout << "Volume: " << volume << std::endl;
std::cout << "Divident: " << divident << std::endl;
std::cout << "Split coefficient: " << split_coefficient << std::endl;
}
DayInfo::DayInfo() : open(), high(), low(), close(), adjclose(), volume(),
divident(), split_coefficient() {}
DayInfo::DayInfo(double open, double high, double low, double close,
double adjclose, double volume, double divident, double
split_coefficient) : open(std::move(open)), high(std::move(high)),
low(std::move(low)), close(std::move(close)), adjclose(std::move(adjclose)),
volume(std::move(volume)), divident(std::move(divident)),
split_coefficient(split_coefficient) {}
DayInfo::DayInfo(const DayInfo& other)
{
open = other.open;
high = other.high;
low = other.low;
close = other.close;
adjclose = other.adjclose;
volume = other.volume;
divident = other.divident;
split_coefficient = other.split_coefficient;
}
DayInfo& DayInfo::operator=(const DayInfo& other)
{
open = other.open;
high = other.high;
low = other.low;
close = other.close;
adjclose = other.adjclose;
volume = other.volume;
divident = other.divident;
split_coefficient = other.split_coefficient;
return *this;
}
std::size_t DateHash::operator()(boost::gregorian::date const& date) const noexcept
{
return std::hash<int>{}(date.julian_day());
}
const char* DayInfoNotFound::what()
{
return "DayInfoNotFound: Lookup operation failed";
}
PriceHistory::PriceHistory() : _data(), ticker() {}
PriceHistory::PriceHistory(std::string ticker) : _data()
,ticker(std::move(ticker)) {}
PriceHistory::PriceHistory(const PriceHistory& other) : ticker(other.ticker),
_data(other._data) {}
PriceHistory::PriceHistory(PriceHistory&& other) :
ticker(std::move(other.ticker)),
_data(std::move(other._data)) {}
PriceHistory& PriceHistory::operator=(const PriceHistory& other)
{
ticker = other.ticker;
_data = other._data;
return *this;
}
std::string PriceHistory::get_ticker() const
{
return std::string(ticker);
}
void PriceHistory::set_ticker(std::string nticker)
{
ticker = nticker;
}
void PriceHistory::insert_dayinfo(boost::gregorian::date date, DayInfo info)
{
_data.emplace(std::pair<boost::gregorian::date, DayInfo>(
boost::gregorian::date(std::move(date)),
DayInfo(std::move(info))));
}
void PriceHistory::insert_dayinfo(boost::gregorian::date date, double open,
double high, double low, double close, double adjclose,
double volume, double divident, double split_coefficient)
{
_data.emplace(std::pair<boost::gregorian::date, DayInfo>(
boost::gregorian::date(std::move(date)),
DayInfo(std::move(open), std::move(high), std::move(low),
std::move(close), std::move(adjclose), std::move(volume),
std::move(divident), std::move(split_coefficient))));
}
DayInfo& PriceHistory::get_dayinfo(boost::gregorian::date& date)
{
std::unordered_map<boost::gregorian::date, DayInfo, DateHash>::iterator
found = _data.find(date);
if(found != _data.end()) return found->second;
else throw DayInfoNotFound();
}
std::unordered_map<boost::gregorian::date, DayInfo, DateHash>::iterator
PriceHistory::begin()
{
return _data.begin();
}
std::unordered_map<boost::gregorian::date, DayInfo, DateHash>::const_iterator
PriceHistory::cbegin() const
{
return _data.cbegin();
}
std::unordered_map<boost::gregorian::date, DayInfo, DateHash>::iterator
PriceHistory::end()
{
return _data.end();
}
std::unordered_map<boost::gregorian::date, DayInfo, DateHash>::const_iterator
PriceHistory::cend() const
{
return _data.cend();
}
| true |
26e4a9b790cac88615d3451ef046f304910d81b2 | C++ | Jackpon/Data-Structures | /school_acm/cpp/排队打水问题.cpp | UTF-8 | 1,061 | 3.609375 | 4 | [] | no_license | /*
1120: 排队打水问题
题目描述
算法提高 排队打水问题
时间限制:1.0s 内存限制:256.0MB
问题描述
有n个人排队到r个水龙头去打水,他们装满水桶的时间t1、t2………..tn为整数且各不相等,应如何安排他们的打水顺序才能使他们总共花费的时间最少?
输入格式
第一行n,r (n< =500,r< =75)
第二行为n个人打水所用的时间Ti (Ti< =100);
输出格式
最少的花费时间
样例输入
3 2
1 2 3
样例输出
7
*/
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
//装满时间最少的最先排,总时间sum等于a[i]+d(等待时间)
int main()
{
int n,r;
while(cin>>n>>r){
int a[n];//n个人的装水时间
int d[r];//等待时间
int sum=0;//总共时间
for (int i = 0; i < n; ++i)
{
cin>>a[i];
}
sort(a,a+n);
memset(d,0,sizeof(d));
for (int i = 0; i < n; ++i)
{
sort(d,d+r);
sum += d[0]+a[i];
d[0]+=a[i];
}
cout<<sum<<endl;
}
return 0;
}
| true |
50d8abc4f4cad5e297e7cafcd17a691e8bce6143 | C++ | mworley2/UVa | /uva00278.cpp | UTF-8 | 523 | 2.75 | 3 | [] | no_license | #include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
using namespace std;
int main() {
int cases;
scanf("%d", &cases);
for(int i=0; i<cases; i++) {
char piece;
int rows, cols;
scanf("\n%c %d %d", &piece, &rows, &cols);
switch(piece) {
case 'r':
printf("%d\n",min(rows, cols));
break;
case 'k':
printf("%d\n",(rows * cols + 1)/2);
break;
case 'Q':
printf("%d\n",min(rows, cols));
break;
case 'K':
printf("%d\n",((rows + 1)/2)*((cols+1)/2));
break;
}
}
}
| true |
60b4fc0e8c4c3517f63f5cf2a6e49be46199520b | C++ | gunzigun/CodingInterviews | /面试题66/面试题66/面试题66.cpp | UTF-8 | 739 | 3.9375 | 4 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
void multiply(const vector<int>& array1, vector<int>& array2)
{
int length1 = array1.size();
int length2 = array2.size();
if (length1 == length2 && length2 > 1)
{
array2[0] = 1;
for (int i = 1; i < length1; ++i)
{
array2[i] = array2[i - 1] * array1[i - 1];
}
int Temp = 1;
for (int i = length1 - 2; i >= 0; --i)
{
Temp *= array1[i + 1];
array2[i] *= Temp;
}
}
}
void main()
{
int array[] = { 1, 2, 3, 4, 5, 6, 7 };
int length = sizeof(array) / sizeof(int);
vector<int> array1(array, array + length);
vector<int> array2(length);
multiply(array1,array2);
for (int i = 0; i < length; ++i)
{
cout << array2[i] << " ";
}
cout << endl;
} | true |
8cc0b25162b75a671c71884ebfcc78cad7d26370 | C++ | rolandbernard/task-planner | /optimizer/src/permutation-genetic-algorithm.h | UTF-8 | 2,492 | 2.734375 | 3 | [
"MIT"
] | permissive | #ifndef PERMUTATION_GENETIC_ALGORITHM_H
#define PERMUTATION_GENETIC_ALGORITHM_H
#include <vector>
#include <algorithm>
#include <array>
#include <random>
#include <map>
#include <cstdlib>
#include <climits>
#include <thread>
#include "genetic-algorithm.h"
#include "util.h"
class PermutationGeneticAlgorithm : public GeneticAlgorithm<std::vector<int>> {
protected:
int chromosome_lenght;
public:
static void default_init_function(std::vector<int>& chrom) {
iota(chrom.begin(), chrom.end(), 0);
std::shuffle(chrom.begin(), chrom.end(), generator);
}
public:
PermutationGeneticAlgorithm(
GeneticAlgorithm<std::vector<int>>::FittnessFunction F,
void* user_data,
GeneticAlgorithm<std::vector<int>>::CrossoverFunction X,
GeneticAlgorithm<std::vector<int>>::MutationFunction M,
GeneticAlgorithm<std::vector<int>>::SamplingFunction S,
int population_size = 200,
int surviver_count = 1,
int mutation_count = 1,
double mutation_rate = 0.5,
double crossover_rate = 0.95
) : GeneticAlgorithm<std::vector<int>>(F, user_data, X, M, S, population_size, surviver_count, mutation_count, mutation_rate, crossover_rate) {
}
template<typename C = decltype(default_init_function)>
void initialize(int chromosome_lenght, C init_function = default_init_function, int init_size = 10000) {
std::vector<std::vector<int>> init_population(init_size, std::vector<int>(chromosome_lenght));
std::vector<double> init_population_fittness(init_size);
for(int i = 0; i < init_size; i++) {
init_function(init_population[i]);
init_population_fittness[i] = F(init_population[i], user_data);
}
std::vector<int> sorted(init_size);
std::iota(sorted.begin(), sorted.end(), 0);
std::nth_element(sorted.begin(), sorted.begin() + population_size, sorted.end(), [&init_population_fittness](int a, int b) {
return init_population_fittness[a] > init_population_fittness[b];
});
for(int i = 0; i < population_size+1; i++) {
population_a[i].swap(init_population[sorted[i]]);
}
this->chromosome_lenght = chromosome_lenght;
best_solution.resize(chromosome_lenght);
iota(best_solution.begin(), best_solution.end(), 0);
best_result = 0;
for(auto& chrom : population_b) {
chrom.resize(chromosome_lenght);
}
}
};
#endif
| true |
4e60873ad115a55f8860d89ad28724bf3f90f34e | C++ | demadewe/first-repo | /Node.cpp | UTF-8 | 193 | 2.890625 | 3 | [] | no_license | class Node {
private:
Item item;
Node *next;
public:
Node(Item a)
{ item = a; next=NULL }
Node* getNext() {return next; }
void setNext(Node *n) { next = n; }
Item getItem() { return Item; }
};
| true |
5be0b28a4d7a039d5be6a6ad54a384384b5acfb4 | C++ | anmsg98/CG_OPGL | /CG_OPENGL_term/debug.h | UTF-8 | 797 | 2.65625 | 3 | [] | no_license | /*
made by sunkue.
*/
#pragma once
#include<time.h>
#include<crtdbg.h>
#include<assert.h>
namespace timer {
clock_t d_start{ 0 };
void start() {
d_start = clock();
}
void start_mes(const char message[] = "timer start :") {
std::cout << message << '\n';
d_start = clock();
}
clock_t end() {
return clock() - d_start;
}
void end_mes() {
std::cout <<"timer end : "<< timer::end() << " ms\n";
}
}
namespace assert {
void false_exit(bool b) {
assert(b);
}
}
namespace memory {
/* this works on debug mode. use debug output */
//debug show out put {addr}
void check_now() {
_CrtDumpMemoryLeaks();
}
void check_exit() {
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
}
void set_stop_point(const long addr) {
_CrtSetBreakAlloc(addr);
}
} | true |
27be3693a151c5f97d204c3fbc2f34e54cff8128 | C++ | NinoRataDeCMasMas/HashTrie | /HashCollection/HashCollection.h | UTF-8 | 2,210 | 3.09375 | 3 | [] | no_license | /**
* @author Giovanny Alfonso Chávez Ceniceros (310831)
* Julieta Navarro Rivera (311012)
* Sebastián De la Riva Rivera (301608)
* Christopher Ochoa Gutierrez (310853)
*
* @file HashCollection.h
* @date Nov 25, 2018
* @version 1.0
* @brief Colección de algoritmos generadores de diversos valores hash
* a partir de un arreglo proporcionado
*/
#ifndef HASHTRIE_HASHCOLLECTION_H
#define HASHTRIE_HASHCOLLECTION_H
class HashCollection {
static HashCollection* instance;
HashCollection() = default;
public:
/**
* @brief generar una copia de la instancia de HashCollection
* @return
*/
static HashCollection* create()
{
if(instance == nullptr)
instance = new HashCollection;
return instance;
}
/**
* @brief Variante recursiva del checksum
* @param T* r, arreglo al que hay que determinar un valor hash
* @param int n, la longitud del arreglo
* @return T , valor hash calculado mediante la suma de los valores ASCII
*/
template<typename T> T checksum(T* r, unsigned long n)
{
return n == 0 ? r[n] : checksum(r, n - 1) + r[n];
}
/**
* @brief Variante recursiva del checksum staircase
* @param T* r, arreglo al que hay que determinar un valor hash
* @param int n, la longitud del arreglo
* @return T , valor hash calculado mediante la suma de los valores ASCII multiplicado por su posicion
*/
template<typename T> T staircase(T* r, unsigned long n)
{
return n == 0 ? r[n] : staircase(r, n - 1) + r[n]*(n + 1);
}
/**
* @brief Variante recursiva del algoritmo djb2
* @param T* r, arreglo al que hay que determinar un valor hash
* @param int n, la longitud del arreglo
* @param unsigned long hash, valor requerido para el funciona_
* miento del algoritmo djb2
* @return T , valor hash calculado
*/
template<typename T> unsigned long djb2(T* r, unsigned long n, unsigned long hash = 5381)
{
return n == 0 ? r[n] : djb2(r, n - 1, hash << 5) + r[n] + hash;
}
};
HashCollection* HashCollection::instance = nullptr;
#endif //HASHTRIE_HASHCOLLECTION_H
| true |
bd324f1dcc87735c80df485eba8161a9d7500941 | C++ | WeAreChampion/notes | /c/learn/CharOperate.cpp | IBM852 | 1,164 | 3.671875 | 4 | [
"Apache-2.0"
] | permissive | #include<iostream>
using namespace std;
//delete the ' ' from the string where start and ending
string trim(string str)
{
string newStr = "";
int start;
for(int i = 0; i < str.size(); i++) {
if(str[i] != ' ') {
start = i;
break;
}
}
int end;
for(int i = str.size() - 1; i >= 0; i--) {
if(str[i] != ' ') {
end = i;
break;
}
}
for(int i = start; i <= end; i++) {
newStr += str[i];
}
return newStr;
}
void TestTrim()
{
string s = " aa av b ";
string news = trim(s);
cout<<news.size()<<endl<<news<<endl;
}
string string1 = "SaU|bV";
//the char is lower like 'a','b'...'z'
bool isLower(char ch)
{
if(ch >= 'a' && ch <= 'z') {
return true;
}
return false;
}
//the char is Uper like 'A','B'...'Z'
bool isUper(char ch)
{
if(ch >= 'A' && ch <= 'Z') {
return true;
}
return false;
}
void TestChar()
{
char ch;
cout<<"Please type a word: ";
while(cin>>ch) {
if(isUper(ch)) {
cout<<ch<<" is upper!"<<endl;
}
else if(isLower(ch)) {
cout<<ch<<" is lower!"<<endl;
}
else {
cout<<ch<<" is not word!"<<endl;
}
getchar();
cout<<"Please type a word: ";
}
}
int main()
{
TestChar();
return 0;
} | true |
5251eefd372d83de926fddadf00fb4ad3c471713 | C++ | BullDog481/Data_Structures | /Data_Struct/Data_Struct/Stack_Array.h | UTF-8 | 921 | 3.59375 | 4 | [
"MIT"
] | permissive | #pragma once
#define MAX_SIZE 101
int A[MAX_SIZE];
int top = -1;
//Last in First Out Collection (LIFO)
//a list with the restriction that insertion and deletion can
//be performed from only one end, called the top
/*Operations:
* Push(x) -> void
* Pop() -> elem
* Top() -> elem
* IsEmpty() -> boolean
* These are all O(1)
*/
//Used for Function Calls/Recursion, implement undo operation in a text editor
//Can Determine Balanced Parentheses in a Source code using a stack for a compiler.
void Push(int x) {
if (top == MAX_SIZE - 1) {
std::cout << "Error: stack overflow\n";
return;
}
A[++top] = x;
}
void Pop() {
if (top == -1) {
std::cout << "Error: No element to pop\n";
return;
}
top--;
}
int Top() {
return A[top];
}
void Print() {
int i;
std::cout << "Stack: ";
for (i = 0; i <= top; i++) {
std::cout << " " << A[i];
}
std::cout << std::endl;
} | true |
fb4028338c0614c0e1b370b013b70c0aafd221e9 | C++ | tfilla1/Universe | /Universe/ShaderUtils.cpp | UTF-8 | 2,779 | 2.71875 | 3 | [] | no_license | // ShaderUtils.cpp
// Universe
//
// Created by Aquilla Sherrock on 11/18/14.
// Copyright (c) 2014 Aquilla Sherrock. All rights reserved.
#include "ShaderUtils.h"
GLuint ShaderUtils::createShaderFromFile(const GLchar* path, GLenum shaderType) {
GLuint shaderID = glCreateShader(shaderType);
// Open input stream from ShaderProgram
std::ifstream fin;
fin.open(path);
if (!fin.is_open()) {
fin.close();
std::cout << "file not found: " << path << std::endl;
return 0;
}
// Read shader program into string
std::string source((std::istreambuf_iterator<GLchar>(fin)), std::istreambuf_iterator<GLchar>());
fin.close();
// Cast source to C string
const GLchar* shaderSource = source.c_str();
#ifdef _DEBUG
std::cout << "Source Open: " << path << std::endl;
std::cout << shaderSource << std::endl << std::endl;
#endif
// Set and compile source code
glShaderSource(shaderID, 1, &shaderSource, NULL);
glCompileShader(shaderID);
// Get status of source compilation
GLint compileStatus;
glGetShaderiv(shaderID, GL_COMPILE_STATUS, &compileStatus);
#ifdef _DEBUG
std::cout << "Source Compile Status: " << path << std::endl;
std::cout << compileStatus << std::endl << std::endl;
#endif
if (compileStatus != GL_TRUE) {
std::cout << "Shader failed to compile: " << path << std::endl;
GLint infoLogLength;
glGetShaderiv(shaderID, GL_INFO_LOG_LENGTH, &infoLogLength);
GLchar* infoLog = new GLchar[infoLogLength + 1];
glGetShaderInfoLog(shaderID, infoLogLength, NULL, infoLog);
std::cout << infoLog << std::endl;
delete infoLog;
return 0;
}
return shaderID;
}
GLuint ShaderUtils::createProgramFromShaders(const GLuint vertexShader, const GLuint fragmentShader) {
GLint shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
// Bind fragment data location
glBindFragDataLocation(shaderProgram, 0, "fragData");
glLinkProgram(shaderProgram);
GLint linkStatus;
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &linkStatus);
if (linkStatus != GL_TRUE) {
std::cout << "Program link failed!" << std::endl;
GLint infoLogLength;
glGetProgramiv(shaderProgram, GL_INFO_LOG_LENGTH, &infoLogLength);
GLchar* infoLog = new GLchar[infoLogLength + 1];
glGetProgramInfoLog(shaderProgram, infoLogLength, NULL, infoLog);
std::cout << infoLog << std::endl;
delete infoLog;
return 0;
}
return shaderProgram;
} | true |
e2ac333ff0d183c60c385461979d8bbebed2ace3 | C++ | uabti/coolfluid3 | /cf3/mesh/Reconstructions.hpp | UTF-8 | 12,803 | 2.5625 | 3 | [] | no_license | // Copyright (C) 2010-2011 von Karman Institute for Fluid Dynamics, Belgium
//
// This software is distributed under the terms of the
// GNU Lesser General Public License version 3 (LGPLv3).
// See doc/lgpl.txt and doc/gpl.txt for the license text.
#ifndef cf3_mesh_Reconstructions_hpp
#define cf3_mesh_Reconstructions_hpp
////////////////////////////////////////////////////////////////////////////////
#include "common/BoostArray.hpp"
#include "math/MatrixTypes.hpp"
#include "mesh/ShapeFunction.hpp"
////////////////////////////////////////////////////////////////////////////////
namespace cf3 {
namespace mesh {
////////////////////////////////////////////////////////////////////////////////
/// Base class to help reconstruction of element values to any given coordinate
/// value_in_coord = sum ( N(i) * value_in_node(i) )
/// Derived classes have to implement the actual computation of the
/// values "N(i)". Optimization is allowed by storing an internal vector
/// m_pts, holding the indices of only the non-zero N(i)'s.
/// @author Willem Deconinck
struct ReconstructBase
{
/// Reconstruct values from matrix with values in row-vectors to vector.
/// The location of the vector must have been previously setup using
/// build_coefficients()
/// @param [in] from matrix with values in row-vectors
/// @param [out] to vector
/// @note to is marked as const, but constness is casted away inside,
/// according to Eigen documentation http://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html
template <typename matrix_type, typename vector_type>
void operator()(const matrix_type& from, const vector_type& to) const
{
equal(from,to);
}
/// Reconstruct values from matrix with values in row-vectors to a vector.
/// The location of the vector must have been previously setup using
/// build_coefficients()
/// @param [in] from matrix with values in row-vectors
/// @param [out] to vector
/// @note to is marked as const, but constness is casted away inside,
/// according to Eigen documentation http://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html
template <typename matrix_type, typename vector_type>
void equal(const matrix_type& from, const vector_type& to) const
{
// cf3_assert(used_points().size()>0);
set_zero(to);
add(from,to);
}
/// Set the given vector to zero
/// @note vec is marked as const, but constness is casted away inside,
/// according to Eigen documentation http://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html
template <typename vector_type>
static void set_zero(const vector_type& vec)
{
for (Uint var=0; var<vec.size(); ++var)
const_cast<vector_type&>(vec)[var] = 0;
}
/// Reconstruct values from matrix with values in row-vectors to a vector.
/// The location of the vector must have been previously setup using
/// build_coefficients()
/// The vector is not initialized to zero, hence the reconstructed values
/// will be summed on top of the existing vector values
/// @param [in] from matrix with values in row-vectors
/// @param [out] to vector
/// @note to is marked as const, but constness is casted away inside,
/// according to Eigen documentation http://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html
template <typename matrix_type, typename vector_type>
void add(const matrix_type& from, const vector_type& to) const
{
// cf3_assert(used_points().size()>0);
boost_foreach(const Uint pt, m_pts)
contribute_plus(from,to,pt);
}
/// Reconstruct values from matrix with values in row-vectors to a vector.
/// The location of the vector must have been previously setup using
/// build_coefficients()
/// The vector is not initialized to zero, hence the reconstructed values
/// will be subtracted from the existing vector values
/// @param [in] from matrix with values in row-vectors
/// @param [out] to vector
/// @note to is marked as const, but constness is casted away inside,
/// according to Eigen documentation http://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html
template <typename matrix_type, typename vector_type>
void subtract(const matrix_type& from, const vector_type& to) const
{
// cf3_assert(used_points().size()>0);
boost_foreach(const Uint pt, m_pts)
contribute_minus(from,to,pt);
}
/// Add to a vector "to", the contribution of a given point "pt"
/// coming from a matrix "from"
/// @param [in] from matrix with values in row-vectors
/// @param [in] pt point of which the contribution is added
/// @param [out] to vector
/// @note to is marked as const, but constness is casted away inside,
/// according to Eigen documentation http://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html
template <typename matrix_type, typename vector_type>
void contribute_plus(const matrix_type& from, const vector_type& to,const Uint pt) const
{
for (Uint var=0; var<nb_vars(from); ++var)
const_cast<vector_type&>(to)[var] += m_N[pt] * access(from,pt,var);
}
/// Subtract from a vector "to", the contribution of a given point "pt"
/// coming from a matrix "from"
/// @param [in] from matrix with values in row-vectors
/// @param [in] pt point of which the contribution is added
/// @param [out] to vector
/// @note to is marked as const, but constness is casted away inside,
/// according to Eigen documentation http://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html
template <typename matrix_type, typename vector_type>
void contribute_minus(const matrix_type& from, const vector_type& to,const Uint pt) const
{
for (Uint var=0; var<nb_vars(from); ++var)
const_cast<vector_type&>(to)[var] -= m_N[pt] * access(from,pt,var);
}
/// Get the reconstruction coefficient of a given point
const Real& coeff(const Uint pt) const
{
return m_N[pt];
}
/// Get a vector of points of which the reconstruction coefficient is not zero
const std::vector<Uint>& used_points() const
{
return m_pts;
}
protected: // functions
// Adaptor functions to support both RealMatrix, multi_array, multi_array_view
// as function arguments in this class
template <typename matrix_type>
static Uint nb_vars(const matrix_type& m) { return m[0].size(); }
static Uint nb_vars(const RealMatrix& m) { return m.cols(); }
static Uint nb_vars(const boost::multi_array<Real, 2>& m) { return m.shape()[1]; }
static Uint nb_vars(const boost::detail::multi_array::multi_array_view<Real, 2>& m) { return m.shape()[1]; }
template <typename matrix_type>
static const Real& access(const matrix_type& m, Uint i, Uint j) { return m[i][j]; }
static const Real& access(const RealMatrix& m, Uint i, Uint j) { return m(i,j); }
protected:
Handle<mesh::ShapeFunction const> m_sf;
RealVector m_coord;
RealRowVector m_N;
std::vector<Uint> m_pts;
};
////////////////////////////////////////////////////////////////////////////////
/// Reconstruction helper, implementing a function to calculate
/// values N(i) for a given coordinate, and optimizing by storing
/// indices i of non-zero N(i)'s.
///
/// Use:
/// ReconstructPoint reconstruct;
/// reconstruct.build_coefficients(coord,shape_function);
/// reconstruct( matrix_of_node_values , vector_of_values_in_coord );
/// @author Willem Deconinck
struct ReconstructPoint : ReconstructBase
{
/// Build coefficients for reconstruction in a given coordinate
template <typename vector_type>
void build_coefficients(const vector_type& coord, const Handle<mesh::ShapeFunction const>& sf)
{
m_coord = coord;
m_pts.clear();
m_N.resize(sf->nb_nodes());
sf->compute_value(coord,m_N);
// Save indexes of non-zero values to speed up reconstruction
for (Uint pt=0; pt<m_N.size(); ++pt)
{
if (std::abs(m_N[pt])>math::Consts::eps())
{
m_pts.push_back(pt);
}
}
}
};
////////////////////////////////////////////////////////////////////////////////
/// Reconstruction helper for the derivative in a given direction in a given coordinate.
/// Use:
/// DerivativeReconstructPoint reconstruct_derivative;
/// reconstruct_derivative.build_coefficients(orientation,coord,shape_function);
/// reconstruct_derivative( matrix_of_node_values , vector_of_derivatives_in_coord );
/// @author Willem Deconinck
struct DerivativeReconstructPoint : ReconstructBase
{
/// Build coefficients for reconstruction in a given coordinate
template <typename vector_type>
void build_coefficients(const Uint derivative, const vector_type& coord, const Handle<mesh::ShapeFunction const>& sf)
{
m_derivative = derivative;
m_coord = coord;
RealMatrix grad_sf(sf->dimensionality(),sf->nb_nodes());
sf->compute_gradient(coord,grad_sf);
m_N = grad_sf.row(derivative);
// std::cout << "grad_sf = \n" << sf->gradient(coord) << std::endl;
// Save indexes of non-zero values to speed up reconstruction
m_pts.clear();
for (Uint pt=0; pt<m_N.size(); ++pt)
{
if (std::abs(m_N[pt])>math::Consts::eps())
{
m_pts.push_back(pt);
}
}
// cf3_assert(used_points().size()>0);
}
Uint derivative() const
{
return m_derivative;
}
private:
Uint m_derivative;
};
////////////////////////////////////////////////////////////////////////////////
/// Reconstruction helper that reconstructs values matching one shape function
/// to values matching another shape function.
/// This is good to interpolate between different spaces.
/// Use:
/// Reconstruct reconstruct;
/// reconstruct.build_coefficients( from_shape_function, to_shape_function);
/// reconstruct( matrix_of_from_values , matrix_of_to_values );
/// @author Willem Deconinck
struct Reconstruct
{
/// Build the coefficients for the reconstruction for every point of to_sf
void build_coefficients(const Handle<mesh::ShapeFunction const>& from_sf,
const Handle<mesh::ShapeFunction const>& to_sf)
{
m_from_sf=from_sf;
m_to_sf=to_sf;
m_reconstruct.resize(to_sf->nb_nodes());
for (Uint pt=0; pt<to_sf->nb_nodes(); ++pt)
{
m_reconstruct[pt].build_coefficients(to_sf->local_coordinates().row(pt),from_sf);
}
}
/// Access to individual reconstructor for one point
const ReconstructPoint& operator[](const Uint pt) const
{
return m_reconstruct[pt];
}
/// Reconstruct values from matrix with values in row-vectors to matrix with values in row-vectors
template <typename matrix_type_from, typename matrix_type_to>
void operator()(const matrix_type_from& from, matrix_type_to& to) const
{
cf3_assert(m_reconstruct.size()==to.size());
for (Uint pt=0; pt<m_reconstruct.size(); ++pt)
m_reconstruct[pt](from,to[pt]);
}
/// Reconstruct values from matrix with values in row-vectors to matrix with values in row-vectors
template <typename matrix_type_from>
void operator()(const matrix_type_from& from, RealMatrix& to) const
{
cf3_assert(m_reconstruct.size()==to.rows());
for (Uint pt=0; pt<m_reconstruct.size(); ++pt)
m_reconstruct[pt](from,to.row(pt));
}
private:
Handle<mesh::ShapeFunction const> m_from_sf;
Handle<mesh::ShapeFunction const> m_to_sf;
std::vector<ReconstructPoint> m_reconstruct;
};
////////////////////////////////////////////////////////////////////////////////
/// @author Willem Deconinck
struct GradientReconstruct : ReconstructBase
{
/// Build the coefficients for the reconstruction for every point of to_sf
void build_coefficients(const Handle<mesh::ShapeFunction const>& from_sf,
const Handle<mesh::ShapeFunction const>& to_sf)
{
m_from_sf=from_sf;
m_to_sf=to_sf;
m_derivativereconstruct.resize(from_sf->dimensionality());
for (Uint d=0; d<m_derivativereconstruct.size(); ++d)
{
m_derivativereconstruct[d].resize(to_sf->nb_nodes());
for (Uint pt=0; pt<to_sf->nb_nodes(); ++pt)
{
m_derivativereconstruct[d][pt].build_coefficients(d,to_sf->local_coordinates().row(pt),from_sf);
}
}
}
/// Access to individual reconstructor for one derivative
const std::vector<DerivativeReconstructPoint>& operator[](const Uint d) const
{
cf3_assert(d<m_derivativereconstruct.size());
return m_derivativereconstruct[d];
}
private:
Handle<mesh::ShapeFunction const> m_from_sf;
Handle<mesh::ShapeFunction const> m_to_sf;
std::vector< std::vector<DerivativeReconstructPoint> > m_derivativereconstruct;
Uint m_dim;
};
////////////////////////////////////////////////////////////////////////////////
} // mesh
} // cf3
////////////////////////////////////////////////////////////////////////////////
#endif // cf3_mesh_Reconstructions_hpp
| true |
8147b20dea6162a171932caef9708edd9853b738 | C++ | davmac909/MaciasDavid_CSC5_41202 | /Class/Monthly_Payment/main.cpp | UTF-8 | 1,516 | 3.109375 | 3 | [] | no_license | /*
* File: main.cpp
* Author: David Macias
* Purpose: Check out IDE
* Created on January 4, 2016, 10:18 AM
*/
//System Libraries
#include <iostream>
using namespace std;
//User Libraries
//Global Constants
//Function Prototypes
//Execution Begins Here
int main(int argc, char** argv) {
//Declare and Initialize variables
float amtNeed, inRate, mntDur, facVal, intrst, mntPay;
char again;
//Input data
cout <<"This is a program to calculate the face value of a loan depending on" <<endl;
cout <<"amount needed, interest rate, and duration of the loan." <<endl;
cout <<"Press enter after every response" <<endl;
cout <<endl;
do {
cout <<"What is the amount needed in dollars? " <<endl;
cin >> amtNeed;
cout <<endl;
cout <<"What is the interest rate? " <<endl;
cin >> inRate;
cout <<endl;
cout <<"What is the duration of the loan? " <<endl;
cin >> mntDur;
//Calculate or map inputs to outputs
inRate /= 100.00f;
facVal = amtNeed/(1-inRate*(mntDur/12));
mntPay = facVal/mntDur;
//Output results
cout <<"The required face value of the loan when $" <<amtNeed <<" is needed is $" <<facVal <<"." <<endl;
cout <<"Your Monthly installments will be $" <<mntPay <<" per month for " <<mntDur <<" months." <<endl;
//Exit stage right
cout <<"Calculate again? (y/n)" <<endl;
cin >>again;
}
while ((again == 'y')||(again == 'Y'));
cout <<"Good-Bye" <<endl;
return 0;
}
| true |
a0b254036ab6096ba23e9f578f7ebeec2d8f0ab1 | C++ | nasa/EMTG | /emtg/src/Utilities/maneuver_spec_line.cpp | UTF-8 | 1,191 | 2.578125 | 3 | [] | no_license | //Jacob Englander 6/22/2018
//a box to put maneuver spec items in
#include "maneuver_spec_line.h"
namespace EMTG
{
void maneuver_spec_line::append_maneuver_spec_item(const std::string& frame,
const doubleType& epoch,
const math::Matrix<doubleType>& ControlVector,
const doubleType& StartMass,
const doubleType& FinalMass,
const doubleType& ThrustMagnitude,
const doubleType& MassFlowRate,
const doubleType& ManeuverDuration,
const doubleType& EnforcedDutyCycle)
{
this->ManeuverItems.push_back(maneuver_spec_item(frame,
epoch,
ControlVector,
StartMass,
FinalMass,
ThrustMagnitude,
MassFlowRate,
ManeuverDuration,
EnforcedDutyCycle));
}//end append_maneuver_spec_item()
void maneuver_spec_line::write(std::ofstream& outputfile)
{
outputfile << this->eventID;
outputfile << ", " << this->ManeuverItems.size();
for (maneuver_spec_item thisItem : this->ManeuverItems)
thisItem.write(outputfile);
outputfile << std::endl;
}//end write()
}//close namespace EMTG | true |
f4bd49b8abe3e27688076ea249044f455ef8b33c | C++ | baoxuezhao/solution_set | /string/patternMatching2.cpp | UTF-8 | 1,742 | 3.09375 | 3 | [] | no_license | //source: http://www.careercup.com/question?id=19587667
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
bool isMatch(char *str, char *pat)
{
int m = strlen(pat);
int n = strlen(str);
bool dp[m+1][n+1];
memset(dp, false, sizeof(dp));
dp[0][0] = true;
for(int j=1; j<=n; j++)
dp[0][j] = false;
for(int i=1; i<=m; i++)
dp[i][0] = (i>1 && pat[i-1] == '*' && dp[i-2][0]);
for(int i=1; i<=m; i++)
{
for(int j=1; j<=n; j++)
{
dp[i][j] = dp[i][j] || (dp[i-1][j-1] && str[j-1] == pat[i-1]);
dp[i][j] = dp[i][j] || (i>=2 && dp[i][j-1] && str[j-1] == pat[i-2] && (pat[i-1] == '*' || pat[i-1] == '+' ));
dp[i][j] = dp[i][j] || (i>=2 && dp[i-2][j] && pat[i-1] == '*');
dp[i][j] = dp[i][j] || (i>=2 && dp[i-2][j-1] && pat[i-1] == '+' && (pat[i-2] == str[j-1]));
}
}
return dp[m][n];
}
int main()
{
cout << isMatch("aaab", "a*b") << endl;
cout << isMatch("b", "a*b") << endl;
cout << isMatch("ab", "a*b") << endl;
cout << isMatch("aab", "a*b") << endl;
cout << isMatch("aaab", "a*b") << endl;
cout << isMatch("aaab", "a*b") << endl;
cout << isMatch("ab", "a+aabc") << endl;
cout << isMatch("aabc", "a+aabc") << endl;
cout << isMatch("aaabc", "a+aabc") << endl;
cout << isMatch("aaaabc", "a+aabc") << endl;
cout << isMatch("aab aab", "aa*b*ab+") << endl;
cout << isMatch("aab", "aa*b*ab+") << endl;
cout << isMatch("aabab", "aa*b*ab+") << endl;
cout << isMatch("aaaabbab", "aa*b*ab+") << endl;
cout << isMatch("a", "a+a*b*") << endl;
cout << isMatch("ab", "a+a*b*") << endl;
cout << isMatch("aab", "a+a*b*") << endl;
cout << isMatch("aaabb", "a+a*b*") << endl;
cout << isMatch("aaaabba", "aa*b*ab+") << endl;
cout << isMatch("bbb", "a+a*b*") << endl;
return 0;
}
| true |
2626acca5d7b72e44af5331ba452c57dc9f6c4c4 | C++ | navi-cs467/cubeRunner | /SOURCE/printMenu.cpp | UTF-8 | 2,832 | 2.71875 | 3 | [] | no_license | /***************************************************
** Program name: printMenu.cpp
** CS467 Capstone - 2D Runner - "Cube Runner"
** Team: NAVI
** Date: 4/23/2019
** Description: Source file for printMenu function.
****************************************************/
#include "../HEADER/printMenu.hpp"
//Prints a menu (using ncurses library) and returns (pointer to)
//subwindow object containing printed window. Menu items are
//designated in the menuItems parameter. Starting row and column
//is given by default according to the size of the graphic above
//(MM_GRAPHIC_WIDTH x MM_GRAPHIC_HEIGHT), but these values can
//be overridden by specifying the default parameters altStartingCol
//and altStartingRow.
WINDOW *printMenu(vector<string> menuItems, int seedColor,
int lineColors[], int menuLength, int menuWidth,
int altStartingCol, int altStartingRow) {
int startingCol, startingRow;
//Setup subscreen for menu
if(!altStartingCol) startingCol = (COLS - MM_GRAPHIC_WIDTH)/2 +
(MM_GRAPHIC_WIDTH - MM_WIDTH)/2 + 1;
else startingCol = altStartingCol;
if(!altStartingRow) startingRow = ((LINES - MM_GRAPHIC_HEIGHT)/4) +
MM_GRAPHIC_HEIGHT + 5 + 1; //By default starts 5 rows below cube graphic, + 1 due to outer border
else startingRow = altStartingRow;
WINDOW *subscrnMenu = newwin(menuLength + 2, menuWidth, startingRow, startingCol);
wattron(subscrnMenu, COLOR_PAIR(WHITE_BLACK));
if(seedColor != -1) {
box(subscrnMenu, '|', '_');
wborder(subscrnMenu, '|', '|', '-', '-', '*', '*', '*', '*');
}
wrefresh(subscrnMenu);
//Makes sure nothing erroneous is printed next time cmdoutlinesGraphics
//is used.
for(vector<string>::iterator it = cmdoutlines.begin();
it < cmdoutlines.end(); it++)
*it = "";
cmdoutlines.clear();
//Print and store menu line items and line colors...
int i = 1;
wattron(subscrnMenu, A_BOLD);
for(vector<string>::iterator it = menuItems.begin();
it != menuItems.end(); it++, i++) {
if(seedColor == BLUE_BLACK) seedColor++; //No blue, too hard to see against black
if(lineColors && seedColor != -1) lineColors[i - 1] = seedColor;
if(seedColor != -1) wattron(subscrnMenu, COLOR_PAIR(seedColor));
else wattron(subscrnMenu, COLOR_PAIR(WHITE_BLACK));
if(seedColor != -1)
mvwprintw(subscrnMenu, i, (menuWidth - it->length())/2, it->c_str()); //Centered for menu 1 and 2
//mvwprintw(subscrnMenu, i, 6, it->c_str()); //Slightly off-centered when not highlighted
else
mvwprintw(subscrnMenu, i, 0, it->c_str()); //left - justified for menu 3
cmdoutlines.push_back(*it); //Stores current menu items in cmdoutlines
wrefresh(subscrnMenu);
if(seedColor != -1) seedColor++;
if(seedColor == 7) seedColor = 1;
}
return subscrnMenu;
} | true |
c8a74eba560e2a604c443e4c60833cd8f178f41d | C++ | sam12321/Wiley_Training_Programs | /dataStructs/sortAlgo/sortPrac.cpp | UTF-8 | 859 | 3.203125 | 3 | [] | no_license | #include<iostream>
using namespace std;
void quick_sort(int *a,int low,int high)
{
int pivot=a[low];
int i=low;
int j=low+1;
if(low>=high) return;
while(j<high)
{
if(a[j]<pivot)
{
i++;
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
j++;
}
int t=a[i];
a[i]=pivot;
a[low]=t;
quick_sort(a,low,i-1);
quick_sort(a,i+1,high);
}
int main()
{
int a[5]={5,2,7,8,1};
//int a[10]={12,5,7,32,45,90,9,19,78,3};
int n=5;
int low=0;
int high=5;
#if 0
Bubble
for (int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
Insertion
for(int i=0;i<n;i++)
{
int temp=a[i];
int j=i-1;
while(j>=0 && temp<a[j])
{
int t=a[j+1];
a[j+1]=a[j];
a[j]=t;
j--;
}
a[j+1]=temp;
}
#endif
quick_sort(a,low,high);
for(int i=0;i<n;i++)
cout<<a[i]<<endl;
return 0;
}
| true |
11bb83bc922a79b828df5e4ba5100061ffb5ab1a | C++ | guithin/BOJ | /13460/Main.cpp | UTF-8 | 1,624 | 2.609375 | 3 | [] | no_license | #include<stdio.h>
#include<vector>
#include<stdlib.h>
using namespace std;
struct pos {
int x, y;
pos() {}
pos(int q, int w) {
x = q; y = w;
}
};
int n, m;
char inp[15][15];
int dx[4] = { 0, 1, 0, -1 };
int dy[4] = { -1, 0, 1, 0 };
int ans = 10000000;
pos O;
void back(pos r, pos b, int cnt, int j) {
if (cnt > 10)
return;
for (int i = 0; i < 4; i++) {
if (i == j)continue;
int rx = r.x, ry = r.y, bx = b.x, by = b.y;
bool flag = true;
bool holeR = false, holeB = false;
while (flag) {
bool rmove = holeR ? false : inp[rx + dx[i]][ry + dy[i]] == '.' && !(rx + dx[i] == bx && ry + dy[i] == by);
if (rmove) {
rx += dx[i];
ry += dy[i];
if (rx == O.x&&ry == O.y) {
rx = ry = -1;
holeR = true;
}
}
bool bmove = holeB ? false : inp[bx + dx[i]][by + dy[i]] == '.' && !(bx + dx[i] == rx && by + dy[i] == ry);
if (bmove) {
bx += dx[i];
by += dy[i];
if (bx == O.x && by == O.y) {
rx = ry = -1;
holeB = true;
}
}
flag = rmove || bmove;
}
if (holeB) {
continue;
}
else if (holeR) {
if (ans > cnt)ans = cnt;
continue;
}
back(pos(rx, ry), pos(bx, by), cnt + 1, i);
}
}
int main() {
scanf("%d %d", &n, &m);
pos sr, sb;
for (int i = 1; i <= n; i++) {
scanf("%s", inp[i] + 1);
for (int j = 1; j <= m; j++) {
if (inp[i][j] == 'R') {
sr = pos(i, j);
inp[i][j] = '.';
}
else if (inp[i][j] == 'B') {
sb = pos(i, j);
inp[i][j] = '.';
}
else if (inp[i][j] == 'O') {
O = pos(i, j);
inp[i][j] = '.';
}
}
}
back(sr, sb, 1, -1);
printf("%d\n", ans > 10 ? -1 : ans);
return 0;
} | true |
79172fc901750510d64de900e5090f942e16c239 | C++ | gyuseon/Cplusplus | /Chapter2_01/Chapter2_01/Chapter2_02.cpp | UHC | 7,134 | 2.75 | 3 | [] | no_license | #include ".h"
//void print(int temp[5][5])
//{
// for (int i = 0; i < 5; i++)
// {
// for (int j = 0; j < 5; j++)
// cout << setw(3)<<temp[i][j];
// cout << endl;
// }
// cout << endl;
//}
//
//
//
//void main()
//{
// int k,cnt, tab[5][5];
// while (1)
// {
// cout << "The four type of matrix <1> <2> <3> <4>" << endl;
// cout << "α Ͻ÷ 0 " << endl;
// k = _getch(); //<conio.h>
// if (k == '0') {
// cout << "α " << endl;
// break;
// }
// switch (k)
// {
// case'1':
// cnt = 0; // ʱȭ 0 Ҽְ
// for (int i = 0; i < 5; i++)
// {
// for (int j = 0; j < 5; j++)
// tab[i][j] = ++cnt; //++ ̸ 1ϰ
// }
// print(tab);
// break;
//
// case '2':
// cnt = 0;
// for (int j = 4; j >= 0; j--)
// {
// for (int i = 0; i < 5; i++)
// tab[i][j] = ++cnt;
// }
// print(tab);
// break;
//
// case '3':
// cnt = 0;
// for (int i = 4; i >= 0; i--)
// {
// for (int j = 0; j < 5; j++)
// tab[i][j] = ++cnt;
// }
// print(tab);
// break;
// case '4':
// cnt = 0;
// for (int j = 0; j<5; j++)
// {
// for (int i = 4; i>=0; i--)
// tab[i][j] = ++cnt;
// }
// print(tab);
// break;
// }
//}
//
//}
//void print(int temp[5][5])
//{
// for (int i = 0; i < 5; i++)
// {
// for (int j = 0; j < 5; j++)
// cout << setw(3) << temp[i][j];
// cout << endl;
// }
// cout << endl;
//}
//
//
//void main()
//{
// int cnt=0, tab[5][5];
//
// for (int i = 0; i < 5; i++)
// {
// if (i % 2 == 0) {
// for (int j = 0; j < 5; j++)
// tab[i][j] = ++cnt;
// }
// else {
// for (int j = 4; j >= 0; j--)
// tab[i][j] = ++cnt;
// }
// }
// print(tab);
//
//}
//int k, cnt, tab[100][100];
//
//void print()
//{
// for (int i = 0; i < k; i++)
// {
// for (int j = 0; j < k; j++)
// cout << setw(3)<<tab[i][j];
// cout << endl;
// }
// cout << endl;
//}
//
//
//
//void main()
//{
//
// while (1)
// {
//
// cout << "ڸ Է ϼ" << endl;
// cin >> k;
//
// if (k == '0') {
//
// break;
// }
// cout << endl;
//
// cnt = 0; // ʱȭ 0 Ҽְ
// for (int i = 0; i < k; i++)
// {
// if (i % 2 == 0) {
// for (int j = 0; j < k; j++)
// tab[i][j] = ++cnt;
// }
// else {
// for (int j = k-1; j >= 0; j--)
// tab[i][j] = ++cnt;
// }
// }
// print();
// break;
//
//
// }
//
//}
//
// 1. ( ϳϳ տ ū ڿ)
//int i, j, temp;
//int tab[5] = { 9,5,10,3,2 };
//
//void print()
//{
// for (i = 0; i < 5; i++)
// cout << setw(5) << tab[i];
// cout << endl;
//}
//void main()
//{
// for (i = 0; i < 5 - 1; i++)
// {
// for (j = i + 1; j < 5; j++)
// {
// if (tab[i] >= tab[j])
// {
// temp = tab[i];
// tab[i] = tab[j];
// tab[j] = temp;
// }
// }
// }
// print();
//}
//1-1 Է°
//int i, j, temp,cnt;
//int tab[5];
//
//void print()
//{
// for (i = 0; i < 5; i++)
// cout << setw(5) << tab[i];
// cout << endl;
//}
//void main()
//{
//cout << "ڸ Էϼ : " << endl;
//for (i = 0; i < 5; i++)
// cin >> tab[i];
//
// for (i = 0; i < 5 - 1; i++)
// {
// for (j = i + 1; j < 5; j++)
// {
//
// if (tab[i] >= tab[j])
// {
// temp = tab[i];
// tab[i] = tab[j];
// tab[j] = temp;
// }
// }
// }
// print();
//}
//2. (ڿ )
//int i, j, temp;
//int tab[5];
//
//void print()
//{
// for (i = 0; i < 5; i++)
// cout << setw(5) << tab[i];
// cout << endl;
//}
//void main()
//{
// cout << "ڸ Էϼ : " << endl;
// for (i = 0; i < 5; i++)
// cin >> tab[i];
//δ ̷
//for (int i = 5; i > 0; i--) {
// for (int j = 0; j < i-1; j++) {
// if (tab[j] > tab[j + 1]) {
// // ٲ
// temp = tab[j];
// tab[j] = tab[j+1];
// tab[j+1] = temp;
// }
// }
//}
//
// for (i = 0; i < 5 - 1; i++)
// {
// for (j = 0; j < 5-1-i; j++)
// {
// if (tab[j] >= tab[j+1])
// {
// temp = tab[j];
// tab[j] = tab[j+1];
// tab[j+1] = temp;
// }
// }
// }
//
// print();
//}
//
//int i, j, temp;
//int tab[] = { 1,8,10,4,5 };
//
//void print()
//{
// for (i = 0; i < 5; i++)
// cout << setw(5) << tab[i];
// cout << endl;
//}
//void main()
//{
// for (i = 1; i < 5;i++) //2° Ľ key
// {
// temp = tab[i];
// j = i - 1; //key ٷ տ
// while (j >= 0 && tab[j] > temp)
// {
// tab[j + 1] = tab[j];
// j--;
// tab[j + 1] = temp;
// }
// }
// print();
//}
//void main()
//{
// int E[5] = { 95,75,80,100,50 };
// int i;
// int j, key;
// for (i = 1; i < 5; i++)
// {
// //Ű ġ ι ؾ ù° ۵
// key = E[i];
// for (j = i - 1; j >= 0; j--)
// {
// if (E[j] < key)
// break;
// E[j + 1] = E[j];
// }
// E[j + 1] = key;
// }
// for (i = 0; i < 5; i++)
// cout << setw(5) << E[i];
// cout << endl;
// }
//BS FUNCTION
//int BS(int E[], int L, int H, int K)
//{
// int M;
// for (;;) // true ѷ while(1)
// {
// if (L > H) // Ͱ 1Ǵ 2
// {
// return -99;
// }
// M = (L + H) / 2;
// if (E[M] > K)
// {
// H = M - 1;
// continue;
// }
// else
// if (E[M] < K)
// {
// H = M + 1;
// continue;
// }
// else
// return M + 1;// 0 ؼ 1
// }
//}
//
//void main()
//{
// int L, H, K;
// int E[] = { 11,15,20,22,35,38,39,42,43,45,100 };
// cout << "ã :" << 20 << "";
// cout<< BS(E, 0, 10, 20); //0 10 Ű20 迭E
// cout << " ֽϴ,";
//}
void print(int tab[], int n)
{
for (int i = 0; i < n; i++) {
cout << setw(5) << tab[i];
}
cout << endl;
}
int BS(int E[], int L, int H, int k) {
int M;
while (L <= H) { // , L>H Ǹ -99
M = (L + H) / 2;
if (E[M] > k) {
H = M - 1;
}
else if (E[M] < k) {
L = M + 1;
}
else if (E[M] == k) {
return M + 1;
}
}
return -99;
}
void jung(int tab[], int n) {
int key, j;
for (int i = 1; i < n; i++) { // 2° . key
key = tab[i]; // temp= tab[1]
j = i - 1; //key ٷ տ
while (j >= 0 && tab[j] > key) {
tab[j + 1] = tab[j]; // j = 0̸ tab[1] tab[0] ־
j--; // j = -1;
tab[j + 1] = key; // tab[0] temp=key=tab[1] ־.
}
}
}
void main() {
int tab[50];
int num, i = 0;
int index;
cout << "ڸ Էϼ ( 0)" << endl;
while (1) {
cin >> num;
if (num == 0)
break;
tab[i] = num;
i++;
}
print(tab, i);
//
jung(tab, i);
cout << " " << endl;
print(tab, i);
// ̺ ˻
cout << "ã ϴ Էϼ : ";
cin >> num;
index = BS(tab, 0, i, num);
if (index == -99) cout << "ã ϴ ڰ " << endl;
else cout << "ã ϴ " << num << " " << index << " ° ִ" << endl;
} | true |
0d3aeca3c40eaa793fda81fc81bfd4f47f7e7a99 | C++ | wrapdavid/c-_Primer_book- | /src/Main16.cpp | UTF-8 | 213 | 2.9375 | 3 | [] | no_license | #include<iostream>
int main() {
std::string str;
std::string resault;
while(std::cin >> str)
{
for (char c : str)
{
if (!ispunct(c)) {
resault += c;
}
}
}
std::cout << resault << std::endl;
} | true |
21c4ff2ddeff99a943abd63a37d95dc1e2c72b54 | C++ | AlienCowEatCake/tet_mesh_gen | /src/geometry.h | UTF-8 | 1,352 | 3.046875 | 3 | [] | no_license | #ifndef GEOMETRY_H
#define GEOMETRY_H
#include <cstdlib>
// Класс точка с номером
class point
{
public:
double x, y, z;
size_t num;
point(double x = 0, double y = 0, double z = 0, size_t num = 0 )
{
this->x = x;
this->y = y;
this->z = z;
this->num = num;
}
};
/*
* /|\3
* / | \
* / | \
* / | \
* /- -| - -\
* 0\_ | _/2
* \_ | _/
* \/1
*/
// Структура для описания узлов тетраэдра
struct tetrahedron
{
size_t nodes[4];
};
/*
* /\2
* / \
* 4/----\5
* / \ / \
* 0/___\/___\1
* 3
*/
// Структура для описания узлов треугольника
struct triangle
{
size_t nodes[3];
};
/* _____________
* /|6 /|7 ^ z
* /____________/ | | ^ y
* |4| |5| | /
* | | | | |/----> x
* | | | |
* | | | |
* | |__________|_|
* | /2 | /3
* |/___________|/
* 0 1
*/
/* Список соседей:
* 0 - слева
* 1 - справа
* 2 - спереди
* 3 - сзади
* 4 - снизу
* 5 - сверху
*/
// Класс куб с флагом соседства
class cube
{
public:
size_t nodes[8];
bool neighbor[6];
};
#endif // GEOMETRY_H
| true |
6afc1bdab439de0a956f61b91692e6ac9b25a2c4 | C++ | limoiie/audittools | /src/core/common/str.cpp | UTF-8 | 2,642 | 2.84375 | 3 | [] | no_license | #include <common/str.h>
#include <Windows.h>
#define CP_GB2312 936
#define CP_GB18030 54936
namespace str {
UINT codepage(ansi_encoding_e const encoding) {
switch (encoding) {
case ACP:
return CP_ACP;
case UTF8:
return CP_UTF8;
case UTF7:
return CP_UTF7;
case GBK:
return CP_GB2312;
}
return CP_ACP;
}
Result<std::wstring, bool> ansi_to_unicode(std::string const& ansi_string,
ansi_encoding_e const encoding) {
auto result = make_result(std::wstring(), false);
result.error = !ansi_to_unicode(ansi_string, encoding, result.value);
return result;
}
Result<std::string, bool> unicode_to_ansi(std::wstring const& unicode_string,
ansi_encoding_e const encoding) {
auto result = make_result(std::string(), false);
result.error = !unicode_to_ansi(unicode_string, encoding, result.value);
return result;
}
bool ansi_to_unicode(std::string const& ansi_string,
ansi_encoding_e const encoding,
std::wstring& unicode_string) {
// get windows code page and make sure that is valid
auto const code_page = codepage(encoding);
if (FALSE == IsValidCodePage(code_page)) return false;
// check how much wchars we need to store the result
auto dw_min_size = MultiByteToWideChar(code_page, 0, ansi_string.c_str(),
ansi_string.size(), nullptr, 0);
if (0 == dw_min_size) return false;
// allocate wstring and convert
unicode_string.assign(dw_min_size, '\0');
dw_min_size = MultiByteToWideChar(
code_page, 0, ansi_string.c_str(), ansi_string.size(),
const_cast<LPWCH>(unicode_string.c_str()), dw_min_size);
return 0 != dw_min_size;
}
bool unicode_to_ansi(std::wstring const& unicode_string,
ansi_encoding_e const encoding, std::string& ansi_string) {
// get windows code page and make sure that is valid
auto const code_page = codepage(encoding);
if (FALSE == IsValidCodePage(code_page)) return false;
// check how much chars we need to store the result
auto dw_min_size =
WideCharToMultiByte(code_page, 0, unicode_string.c_str(),
unicode_string.size(), nullptr, 0, nullptr, nullptr);
if (0 == dw_min_size) return false;
// allocate wstring and convert
ansi_string.assign(dw_min_size, '\0');
dw_min_size = WideCharToMultiByte(
code_page, 0, unicode_string.c_str(), unicode_string.size(),
const_cast<LPCH>(ansi_string.c_str()), dw_min_size, nullptr, nullptr);
return 0 != dw_min_size;
}
} // namespace str
| true |
017265c5b57111f19410edf86c6ef1da96194ee3 | C++ | burntham/varsity.CSC3022H.assignment4 | /cmdline_parser.h | UTF-8 | 1,974 | 2.640625 | 3 | [] | no_license | /*
* cmdline_parser.h
*
* Created on: 22 Feb 2012
* Author: simon
*/
#ifndef CMDLINE_PARSER_H_
#define CMDLINE_PARSER_H_
#include <iostream>
#include <list>
#include <string>
#include <boost/program_options.hpp>
//---------------------------------------------------------------------------//
class cmdline_parser
{
public:
//-----------------------------------------------------------------------//
// Constructor
cmdline_parser(void);
// Member function that parses command line options
bool process_cmdline(int argc, char * argv[]);
// Return the input PGM filename
std::string get_input_filename(void) const;
// Return the lightening output PGM filename
std::string get_lighten_filename(void) const;
//M Return the darkening output PGM filename
std::string get_output_filename(void) const;
bool get_encoding(void) const;
bool get_decoding(void) const;
char get_cypher(void) const;
int get_ckey(void) const;
std::string get_vkey(void) const;
int32_t get_xkey(void) const;
bool should_group(void) const;
bool should_pack(void) const;
void print_errors(std::ostream & out) const;
bool should_print_help(void) const;
// Output help to the specified output stream
void print_help(std::ostream & out) const;
private:
//-----------------------------------------------------------------------//
// Member variables
boost::program_options::variables_map vm;
boost::program_options::options_description od;
std::list<std::string> errors;
//-----------------------------------------------------------------------//
// Static string variables
static const std::string INPUTFILE;
//My static string variables.
static const std::string OUTPUTFILE;
static const std::string XKEY;
static const std::string VKEY;
static const std::string CKEY;
static const std::string GROUPING;
static const std::string PACKING;
static const std::string ENCODING;
static const std::string DECODING;
};
#endif /* CMDLINE_PARSER_H_ */
| true |
4088ef4a4a75340b7a884cf12e608bb491be4d6e | C++ | simmito/micmac-archeos | /src/uti_image/CPP_Ann.cpp | UTF-8 | 2,091 | 2.734375 | 3 | [] | no_license | #include <iomanip>
#include "AnnSearcher.h"
using namespace std;
inline bool ann_read_sift_file( const string &i_filename, vector<SiftPoint> &array )
{
if ( !read_siftPoint_list( i_filename, array ) ){
cerr << "ERROR: Ann: unable to read file " << i_filename << endl;
return false;
}
return true;
}
int Ann_main( int argc, char **argv )
{
if ( argc<3 ){
cerr << "ERROR: ANN search needs two arguments: the names of the two files listing SIFT points to match" << endl;
return EXIT_FAILURE;
}
string output_name;
if ( argc==4 )
output_name = argv[3];
else
{
// construct output name from input names
// if in0 = dir0/name0.ext0 and in1 = dir1/name1.ext1
// with ext0 and ext1 the shortest extensions of in0 and in1
// then out = dir0/name0.-.name1.result
string name0 = argv[1],
name1 = argv[2];
name0 = name0.substr( 0, name0.find_last_of( "." ) );
size_t pos0 = name1.find_last_of( "/\\" ),
pos1 = name1.find_last_of( "." );
if ( pos0==string::npos ) pos0=0;
else if ( pos1==string::npos ) pos1=name1.length();
else if ( pos0==name1.length()-1 ){
cerr << "Ann: ERROR: invalid filename " << name1 << endl;
return EXIT_FAILURE;
}
else pos0++;
name1 = name1.substr( pos0, pos1-pos0 );
output_name = name0+".-."+name1+".result";
}
list<V2I> matchedCoupleIndices;
vector<SiftPoint> array0, array1;
if ( !ann_read_sift_file( argv[1], array0 ) ) return EXIT_FAILURE;
if ( !ann_read_sift_file( argv[2], array1 ) ) return EXIT_FAILURE;
match_lebris( array0, array1, matchedCoupleIndices );
if ( matchedCoupleIndices.size()!=0 )
{
unfoldMatchingCouples( array0, array1, matchedCoupleIndices );
neighbourFilter( array0, array1, matchedCoupleIndices );
if ( matchedCoupleIndices.size()!=0 )
{
unfoldMatchingCouples( array0, array1, matchedCoupleIndices );
neighbourFilter( array0, array1, matchedCoupleIndices );
}
}
write_matches_ascii( output_name, array0, array1, matchedCoupleIndices );
cout << matchedCoupleIndices.size() << " matches" << endl;
return EXIT_SUCCESS;
}
| true |
108b490edc903f09634fc1049a7a7941d4997d7c | C++ | vbugaevskii/msu.supercomputers.course | /parallel-hw2-03/parallel-no/main.cpp | UTF-8 | 10,863 | 2.828125 | 3 | [] | no_license | #include <memory>
#include <cmath>
#include <iostream>
#include <fstream>
#include <chrono>
int N = 128, K = 5;
double hx, hy, hz, tau;
int dx, dy, dz;
const int LAYERS = 3;
class Timer {
public:
Timer() : t_delta(0) {}
virtual void start() = 0;
virtual void pause() = 0;
virtual double delta() = 0;
virtual void reset() = 0;
virtual ~Timer() = default;
protected:
double t_delta;
};
class ChronoTimer : public Timer {
public:
ChronoTimer() : t_start(std::chrono::high_resolution_clock::now()), is_paused(true) {}
void start() override {
is_paused = false;
t_start = std::chrono::high_resolution_clock::now();
}
void pause() override {
if (!is_paused) {
auto end = std::chrono::high_resolution_clock::now();
double delta = std::chrono::duration_cast<std::chrono::microseconds>(end - t_start).count();
t_delta += delta / 1e6;
}
is_paused = true;
}
double delta() override {
double delta = 0;
if (!is_paused) {
auto end = std::chrono::high_resolution_clock::now();
delta = std::chrono::duration_cast<std::chrono::microseconds>(end - t_start).count();
delta /= 1e6;
}
return t_delta + delta;
}
void reset() override {
t_delta = 0;
start();
}
private:
std::chrono::high_resolution_clock::time_point t_start;
bool is_paused;
};
class TimerScopePauseCallback {
public:
explicit TimerScopePauseCallback(Timer& a_timer) : timer(a_timer) {
timer.pause();
}
~TimerScopePauseCallback() {
timer.start();
}
private:
Timer& timer;
};
class TimerScopeUnpauseCallback {
public:
explicit TimerScopeUnpauseCallback(Timer& a_timer) : timer(a_timer) {
timer.start();
}
~TimerScopeUnpauseCallback() {
timer.pause();
}
private:
Timer& timer;
};
struct TimersArray {
ChronoTimer total;
ChronoTimer init;
ChronoTimer free;
ChronoTimer copy;
} timers;
inline double x(int i) { return i * hx; }
inline double y(int j) { return j * hy; }
inline double z(int k) { return k * hz; }
inline double phi_func(double x, double y, double z) {
return sin(3 * x) * cos(2 * y) * sin(z);
}
inline double u_func(double x, double y, double z, double t) {
return cos(sqrt(14) * t) * phi_func(x, y, z);
}
inline double f_func(double x, double y, double z, double t) {
return 0;
}
/*
inline double phi_func(double x, double y, double z) {
return sin(3 * x) * cos(2 * y) * sin(z);
}
inline double u_func(double x, double y, double z, double t) {
return ( 1 + pow(t, 3.0) ) * phi_func(x, y, z);
}
inline double f_func(double x, double y, double z, double t) {
return ( 6 * t + 14 * ( 1 + pow(t, 3.0) ) ) * phi_func(x, y, z);
}
*/
inline int index(int i, int j, int k) {
return i + j * dx + k * dx * dy;
}
inline double laplace(const double data[], int i, int j, int k) {
double val = 0;
int p_prev, p_curr = index(i, j, k), p_next;
p_prev = index(i-1, j, k);
p_next = index(i+1, j, k);
val += (data[p_prev] - 2 * data[p_curr] + data[p_next]) / hx / hx;
p_prev = index(i, j-1, k);
p_next = index(i, j+1, k);
val += (data[p_prev] - 2 * data[p_curr] + data[p_next]) / hy / hy;
p_prev = index(i, j, k-1);
p_next = index(i, j, k+1);
val += (data[p_prev] - 2 * data[p_curr] + data[p_next]) / hz / hz;
return val;
}
struct EstimateError {
double mse;
double max;
EstimateError() : mse(0), max(0) {}
};
void estimate_error(EstimateError* p_error, const double *data, int t) {
double mse = 0;
double max = 0;
for (int p = 0; p < dx * dy * dz; p++) {
int i = p % dx;
int j = (p / dx) % dy;
int k = (p / dx / dy) % dz;
if (i == dx - 1 || j == dy - 1 || k == dz - 1)
continue;
double u_true = u_func(x(i), y(j), z(k), t * tau);
double u_pred = data[p];
mse += pow(u_true - u_pred, 2);
double u_abs = fabs(u_true - u_pred);
if (u_abs > max)
max = u_abs;
}
p_error->max = max;
p_error->mse = mse;
}
int main(int argc, char **argv)
{
timers.total.start();
timers.init.start();
N = (argc > 1) ? std::atoi(argv[1]) : 128;
K = (argc > 2) ? std::atoi(argv[2]) : 20;
const bool is_compute = (argc > 4) ? std::atoi(argv[4]) : 1;
hx = hy = hz = 16 * M_PI / (N - 1);
tau = 0.004;
const int i_min = 0, j_min = 0, k_min = 0;
dx = dy = dz = N + 1;
// размерность декартовой решетки
int ndim = 3;
char border_conditions[ndim];
border_conditions[0] = 1;
border_conditions[1] = 2;
border_conditions[2] = 1;
// подсчет ошибки
EstimateError error_cumm, error_curr;
double* u_data[LAYERS];
for (int p = 0; p < LAYERS; p++)
u_data[p] = new double[dx * dy * dz];
timers.init.pause();
// засекаем время
ChronoTimer timer;
timer.start();
// заполняем для t = t0
for (int p = 0; p < dx * dy * dz; p++) {
int i = p % dx;
int j = (p / dx) % dy;
int k = (p / dx / dy) % dz;
u_data[0][p] = phi_func(x(i_min + i), y(j_min + j), z(k_min + k));
}
if (is_compute) {
TimerScopePauseCallback callback(timer);
estimate_error(&error_curr, u_data[0], 0);
error_curr.mse /= pow(N, 3);
error_cumm.mse += error_curr.mse;
if (error_curr.max > error_cumm.max)
error_cumm.max = error_curr.max;
}
printf("[iter %03d]", 0);
if (is_compute)
printf(" RMSE = %.6f; MAX = %.6f;", sqrt(error_curr.mse), error_curr.max);
printf(" Time = %.6f sec.\n", timer.delta());
// заполняем для остальных t
for (int n = 1; n < K; n++) {
for (int p = 0; p < dx * dy * dz; p++) {
int i = p % dx;
int j = (p / dx) % dy;
int k = (p / dx / dy) % dz;
// пропускаем обменные области
if (i == dx - 1)
continue;
if (j == dy - 1)
continue;
if (k == dz - 1)
continue;
// пропускаем граничные области
if (i == 0 || (border_conditions[0] != 2) && i == dx - 2)
continue;
if (j == 0 || (border_conditions[1] != 2) && j == dy - 2)
continue;
if (k == 0 || (border_conditions[2] != 2) && k == dz - 2)
continue;
if (n == 1) {
// заполняем для t = t1;
double f_value = f_func(x(i_min + i), y(j_min + j), z(k_min + k), 0);
u_data[n][p] = u_data[n - 1][p] + 0.5 * tau * tau * (laplace(u_data[n - 1], i, j, k) + f_value);
} else {
// заполняем для всех остальных t;
double f_value = f_func(x(i_min + i), y(j_min + j), z(k_min + k), (n - 1) * tau);
u_data[n % LAYERS][p] = 2 * u_data[(n - 1) % LAYERS][p] - u_data[(n - 2) % LAYERS][p] \
+ tau * tau * (laplace(u_data[(n - 1) % LAYERS], i, j, k) + f_value);
}
}
{
TimerScopeUnpauseCallback cb(timers.copy);
if (border_conditions[0] == 1) {
for (int k = 0; k < dz; k++) {
for (int j = 0; j < dy; j++) {
u_data[n % LAYERS][index(0, j, k)] = 0;
u_data[n % LAYERS][index(dx - 2, j, k)] = 0;
}
}
} else if (border_conditions[0] == 2) {
for (int k = 0; k < dz; k++) {
for (int j = 0; j < dy; j++) {
u_data[n % LAYERS][index(0, j, k)] = u_data[n % LAYERS][index(dx - 2, j, k)];
u_data[n % LAYERS][index(dx - 1, j, k)] = u_data[n % LAYERS][index(1, j, k)];
}
}
}
if (border_conditions[1] == 1) {
for (int k = 0; k < dz; k++) {
for (int i = 0; i < dx; i++) {
u_data[n % LAYERS][index(i, 0, k)] = 0;
u_data[n % LAYERS][index(i, dy - 2, k)] = 0;
}
}
} else if (border_conditions[1] == 2) {
for (int k = 0; k < dz; k++) {
for (int i = 0; i < dx; i++) {
u_data[n % LAYERS][index(i, 0, k)] = u_data[n % LAYERS][index(i, dy - 2, k)];
u_data[n % LAYERS][index(i, dy - 1, k)] = u_data[n % LAYERS][index(i, 1, k)];
}
}
}
if (border_conditions[2] == 1) {
for (int j = 0; j < dy; j++) {
for (int i = 0; i < dx; i++) {
u_data[n % LAYERS][index(i, j, 0)] = 0;
u_data[n % LAYERS][index(i, j, dz - 2)] = 0;
}
}
} else if (border_conditions[2] == 2) {
for (int j = 0; j < dy; j++) {
for (int i = 0; i < dx; i++) {
u_data[n % LAYERS][index(i, j, 0)] = u_data[n % LAYERS][index(i, j, dz - 2)];
u_data[n % LAYERS][index(i, j, dz - 1)] = u_data[n % LAYERS][index(i, j, 1)];
}
}
}
}
if (is_compute) {
TimerScopePauseCallback callback(timer);
estimate_error(&error_curr, u_data[n % LAYERS], n);
error_curr.mse /= pow(N, 3);
error_cumm.mse += error_curr.mse;
if (error_curr.max > error_cumm.max)
error_cumm.max = error_curr.max;
}
printf("[iter %03d]", n);
if (is_compute)
printf(" RMSE = %.6f; MAX = %.6f;", sqrt(error_curr.mse), error_curr.max);
printf(" Time = %.6f sec.\n", timer.delta());
}
timer.pause();
if (is_compute)
printf("Final RMSE = %.6f; MAX = %.6f\n", sqrt(error_cumm.mse / K), error_cumm.max);
printf("Task elapsed in: %.6f sec.\n", timer.delta());
timers.free.start();
for (int p = 0; p < LAYERS; p++)
delete u_data[p];
timers.free.pause();
timers.total.pause();
printf("\n");
printf("Time total: %.6f\n", timers.total.delta());
printf("Time init: %.6f\n", timers.init.delta());
printf("Time logic: %.6f\n", timer.delta());
printf("Time sendrecv: NaN\n");
printf("Time copy: %.6f\n", timers.copy.delta());
printf("Time free: %.6f\n", timers.free.delta());
return 0;
}
| true |
e852e6bb4d137dc0279e1af61219c2bdab957105 | C++ | ElephantT/TelegramBot_cpp | /bot/telegram/client.h | UTF-8 | 2,571 | 2.890625 | 3 | [] | no_license | // #pragma once
#include <stdexcept>
#include <optional>
#include <string>
#include <variant>
#include <vector>
#include <queue>
#include <memory>
struct TelegramAPIError;
class AbstractCPPClass {
public:
virtual ~AbstractCPPClass() = default;
};
class NewMessage : public AbstractCPPClass {
public:
NewMessage(int64_t chat_id, int64_t message_id, std::string text,
std::vector<std::string> commands);
bool AreCommandsInText();
std::vector<std::string>& Commands();
std::string GetText();
int64_t GetChatId();
void SetCommandsChecker(bool are_there_commands);
int64_t GetMessageId();
private:
int64_t chat_id_;
int64_t message_id_;
std::string text_;
std::vector<std::string> commands_;
bool are_there_commands_;
};
// если мы хотим, чтобы наш API работал ещё с какими-то командами, запросами или ещё чем,
// то нужно создать классы с++ и отнаследовать их к JsonToCPP
// дальше работаем со smart-ptr от них
class ClientTelegramBotAPI {
public:
ClientTelegramBotAPI(const std::string& token, const std::string& uri);
~ClientTelegramBotAPI() = default;
bool GetMe();
std::vector<std::shared_ptr<AbstractCPPClass>> GetUpdates(int timeout = 0);
void SendMessage(int64_t chat_id, std::string response, int64_t message_id = -1);
// отправляет ответ бота на один из полученных апдейтов из getUpdate
// используем шаблон, смотрим что там может быть, делаем по нему Json и отправляем на сервер
private:
const std::string token_;
const std::string uri_;
int64_t offset_;
std::string offset_file_name_;
std::vector<std::shared_ptr<AbstractCPPClass>> FormCppStructFromJson(std::istream& response_body);
// делает с++ структуру из json, берём один объект из getUpdates
void SetOffset();
// изменить offset в файле
void GetOffset();
// получить offset из файла
};
struct TelegramAPIError : public std::runtime_error {
TelegramAPIError(int error_code, const std::string& details)
: std::runtime_error("api error: code=" + std::to_string(error_code) +
" details=" + details),
http_code(error_code),
details(details) {
}
int http_code;
std::string details;
};
| true |
e64a7c4e7d109ef70f4a6bee0ca154044faeb0c5 | C++ | abrdej/pigeon-war | /src/turn_based/move.h | UTF-8 | 1,043 | 2.90625 | 3 | [] | no_license | #pragma once
#include <turn_based/move_ability.h>
#include <turn_based/turn_system.h>
/**
* @brief Standard ability to move the entity.
*/
class move final : public move_ability, turn_callback_helper {
public:
enum class types { path, straight };
explicit move(std::int32_t range, types type = types::path);
void refresh_range() override { used_ = false; }
bool has_range() const override { return !used_; }
void remove_range() override { used_ = true; }
void set_slow_down(std::int32_t value) override { range_ = value; }
void remove_slow_down() override { range_ = base_range_; }
bool usable() const override { return has_range(); }
void skip_collisions(bool value) { skip_collisions_ = value; }
private:
void prepare(index_t for_index) override;
void do_move(index_t index_to);
private:
static constexpr auto name = "move";
std::int32_t range_;
const std::int32_t base_range_;
bool used_{false};
bool skip_collisions_{false};
types movement_type_;
};
| true |