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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
128471fb0febdb46f0e130d7fbbd25a4f0f2ccae | C++ | pastorsa/dec | /dec_world_state/include/dec_world_state/world_state_impl.h | UTF-8 | 1,986 | 2.59375 | 3 | [] | no_license | /*
* world_state_impl.h
*
* Created on: Jan 14, 2013
* Author: kalakris
*/
#ifndef WORLD_STATE_IMPL_H_
#define WORLD_STATE_IMPL_H_
#include <ros/ros.h>
#include <boost/function.hpp>
#include <dec_world_state/ObjectState.h>
#include <dec_msgs/Objects.h>
#include <tf/transform_datatypes.h>
#include <map>
namespace dec_utilities
{
template<class T> class SingletonFactory;
}
namespace dec_world_state
{
class WorldStateImpl
{
friend class dec_utilities::SingletonFactory<WorldStateImpl>;
public:
WorldStateImpl();
virtual ~WorldStateImpl();
/**
* Get the latest state of an object. Returns false if object doesn't exist.
*/
bool getObject(const std::string& name, dec_msgs::Object& object, const bool verbose = false);
bool getObjectPose(const std::string& name, tf::Pose& pose, const bool verbose = false);
void addObjects(const std::vector<dec_msgs::Object>& objects);
void addObjects(const dec_msgs::Objects& objects);
void addObject(const dec_msgs::Object& object);
void addObject(const std::string& name, const tf::Pose& pose);
void removeObjects(const dec_msgs::Objects& objects);
void removeObject(const dec_msgs::Object& object);
void removeObject(const std::string& name);
void removeAllObjects();
void getObjects(std::vector<dec_msgs::Object>& objects);
void addCallback(boost::function<void (const ObjectState& state)> callback);
int getNumSubscribers();
private:
ros::NodeHandle node_handle_;
ros::Subscriber object_sub_;
ros::Publisher object_pub_;
void objectCallbackEvent(const ros::MessageEvent<ObjectState const>& object_state_event);
void objectCallback(const ObjectState& object_state);
void publishObject(const dec_msgs::Object& object, int operation);
typedef std::map<std::string, dec_msgs::Object> ObjectMap;
ObjectMap object_map_;
std::vector<boost::function<void (const ObjectState& state)> > callbacks_;
};
} /* namespace dec_world_state */
#endif /* WORLD_STATE_IMPL_H_ */
| true |
617845e77a588ccf23350d81c0593d6e3f9133eb | C++ | RobJenks/rj-engine | /RJ/DynamicTerrainDefinition.h | UTF-8 | 3,298 | 2.890625 | 3 | [] | no_license | #pragma once
#include <string>
#include <unordered_map>
#include "CompilerSettings.h"
#include "ErrorCodes.h"
#include "DynamicTerrainState.h"
#include "DynamicTerrainInteractionType.h"
class DynamicTerrain;
class DynamicTerrainDefinition
{
public:
// Default constructor
DynamicTerrainDefinition(void);
// Unique string code of the dynamic terrain definition
CMPINLINE std::string GetCode(void) const { return m_code; }
CMPINLINE void SetCode(const std::string & code) { m_code = code; }
// Create a new dynamic terrain object based upon this definition
DynamicTerrain * Create(void) const;
// Prototype terrain object used for instantiation
CMPINLINE const DynamicTerrain * GetPrototype(void) const { return m_prototype; }
CMPINLINE void SetPrototype(DynamicTerrain *prototype) { m_prototype = prototype; }
// Assign a new state definition to this terrain
Result AssignStateDefinition(const DynamicTerrainState & state_definition);
// Default state for the terrain object (if applicable)
CMPINLINE std::string GetDefaultState(void) const { return m_default_state; }
CMPINLINE void SetDefaultState(const std::string & default_state) { m_default_state = default_state; }
// Return details for the given state, or NULL if no such state is defined. Pointer is valid only
// at the current time and should not be retained for future use
const DynamicTerrainState * GetStateDefinition(const std::string & state) const;
// Add a default state transition that can be applied by the object
void AddDefaultStateTransition(const std::string & state, const std::string next_state);
// Return the default state transition for an object of this type, given the specified current state. Returns
// an empty string if no transition is defined (the empty string is not a valid code for a state definition)
std::string GetDefaultStateTransition(const std::string & current_state) const;
// The type of player interaction that is permitted by this object type
CMPINLINE DynamicTerrainInteractionType GetPermittedInteractionType(void) const { return m_permitted_interaction_type; }
CMPINLINE void SetPermittedInteractionType(DynamicTerrainInteractionType interaction_type) { m_permitted_interaction_type = interaction_type; }
// Explicit shutdown method is not required for definition objects; all deallocation is performed in the destructor
CMPINLINE void Shutdown(void) { }
// Default destructor
~DynamicTerrainDefinition(void);
protected:
// Unique string code of the dynamic terrain definition
std::string m_code;
// Prototype terrain object used for instantiation
DynamicTerrain * m_prototype;
// Set of states that the dynamic terrain object can be in, with associated changes to the terrain object itself
std::unordered_map<std::string, DynamicTerrainState> m_states;
// Default state associated with the terrain (if applicable)
std::string m_default_state;
// Set of default state transitions that can be applied by the object
std::unordered_map<std::string, std::string> m_default_state_transitions;
// The type of player interaction that is permitted by this object type
DynamicTerrainInteractionType m_permitted_interaction_type;
}; | true |
37488f5236dacd0dc2658b8f063ed449fdc913fa | C++ | mooncollin/C_plus_plus-Helpful-Libraries | /tests/geometry/triangle.ixx | UTF-8 | 2,899 | 3.09375 | 3 | [] | no_license | export module cmoon.tests.geometry.triangle;
import cmoon.test;
import cmoon.geometry;
namespace cmoon::test::geometry
{
export
class triangle_construction_test : public cmoon::test::test_case
{
public:
triangle_construction_test()
: cmoon::test::test_case{"triangle_construction_test"} {}
void operator()() override
{
constexpr cmoon::geometry::triangle<int> t{1, 2, 3};
static_assert(t.side<1>() == 1);
static_assert(t.side<2>() == 2);
static_assert(t.side<3>() == 3);
static_assert(!cmoon::geometry::valid_triangle(t));
cmoon::test::assert_equal(t.side<1>(), 1);
cmoon::test::assert_equal(t.side<2>(), 2);
cmoon::test::assert_equal(t.side<3>(), 3);
cmoon::test::assert_false(cmoon::geometry::valid_triangle(t));
constexpr cmoon::geometry::triangle<int> t2{8, 6, 7};
static_assert(cmoon::geometry::valid_triangle(t2));
cmoon::test::assert_true(cmoon::geometry::valid_triangle(t2));
cmoon::test::assert_almost_equal(cmoon::geometry::get_angle<1>(t2).degrees(), 75.5224, 0.0001);
cmoon::test::assert_almost_equal(cmoon::geometry::get_angle<2>(t2).degrees(), 46.5674, 0.0001);
cmoon::test::assert_almost_equal(cmoon::geometry::get_angle<3>(t2).degrees(), 57.9100, 0.0001);
cmoon::test::assert_almost_equal(cmoon::geometry::get_exterior_angle<1>(t2).degrees(), 104.4776, 0.001);
cmoon::test::assert_almost_equal(cmoon::geometry::get_exterior_angle<2>(t2).degrees(), 133.4326, 0.001);
cmoon::test::assert_almost_equal(cmoon::geometry::get_exterior_angle<3>(t2).degrees(), 122.0900, 0.001);
const auto angles = cmoon::geometry::get_angles(t2);
const auto ex_angles = cmoon::geometry::get_exterior_angles(t2);
cmoon::test::assert_almost_equal(std::get<0>(angles).degrees(), 75.5224, 0.0001);
cmoon::test::assert_almost_equal(std::get<1>(angles).degrees(), 46.5674, 0.0001);
cmoon::test::assert_almost_equal(std::get<2>(angles).degrees(), 57.9100, 0.0001);
cmoon::test::assert_almost_equal(std::get<0>(ex_angles).degrees(), 104.4776, 0.001);
cmoon::test::assert_almost_equal(std::get<1>(ex_angles).degrees(), 133.4326, 0.001);
cmoon::test::assert_almost_equal(std::get<2>(ex_angles).degrees(), 122.0900, 0.001);
static_assert(cmoon::geometry::perimeter(t2) == 21);
cmoon::test::assert_equal(cmoon::geometry::perimeter(t2), 21);
static_assert(cmoon::geometry::semi_perimeter(t) == 3);
cmoon::test::assert_equal(cmoon::geometry::semi_perimeter(t), 3);
}
};
export
class triangle_perimeter_test : public cmoon::test::test_case
{
public:
triangle_perimeter_test()
: cmoon::test::test_case{"triangle_perimeter_test"} {}
void operator()() override
{
constexpr cmoon::geometry::triangle<int> t{8, 6, 7};
static_assert(cmoon::geometry::perimeter(t) == 21);
cmoon::test::assert_equal(cmoon::geometry::perimeter(t), 21);
}
};
} | true |
8ef1afad2784b76cf0f903eaad31f2e478bc2048 | C++ | AaronCFreytag/SessionZero | /SessionZero/SessionZero/Window.cpp | UTF-8 | 1,479 | 2.734375 | 3 | [] | no_license | #include "Window.h"
#include "ErrorFormatter.h"
#include <stdexcept>
namespace SessionZero {
bool Window::windowClassSet = false;
Window::Window(HINSTANCE instance, const std::wstring title, int width, int height, int windowDisplayState) noexcept {
if (!windowClassSet) {
setupWindowClass(instance);
}
handle = CreateWindowEx(
0,
L"DefaultWindow",
static_cast<const LPCWSTR>(title.c_str()),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
width,
height,
NULL,
NULL,
instance,
NULL
);
if (handle == NULL) {
throw std::runtime_error(
ErrorFormatter::formatWindowsError("Window Creation", GetLastError())
);
}
ShowWindow(handle, windowDisplayState);
}
void Window::setupWindowClass(HINSTANCE instance) {
wchar_t exePath[MAX_PATH];
GetModuleFileName(NULL, exePath, MAX_PATH);
HICON icon = ExtractIcon(instance, exePath, 0);
WNDCLASS windowClass = {
.lpfnWndProc = WindowProc,
.hInstance = instance,
.hIcon = icon,
.lpszClassName = L"DefaultWindow"
};
if (!RegisterClass(&windowClass)) {
throw std::runtime_error(
ErrorFormatter::formatWindowsError("Window Class Registration", GetLastError())
);
}
windowClassSet = true;
}
LRESULT CALLBACK Window::WindowProc(HWND window, UINT uMsg, WPARAM wParam, LPARAM lParam) noexcept {
switch (uMsg)
{
case WM_DESTROY: {
PostQuitMessage(0);
break;
}
}
return DefWindowProc(window, uMsg, wParam, lParam);
}
} | true |
ed7b5e46c6d764775d2334fa8abcb9c98e0ffed2 | C++ | SergioPerea99/Computer-Graphics-and-Visualization | /IGV2021-GR3-PereadelaCasa-Sergio-PR5/PINBALL_codigo_fuente/igvColor.cpp | UTF-8 | 1,123 | 3.09375 | 3 | [] | no_license | #include "igvColor.h"
// Constructures
igvColor::igvColor () {
}
igvColor::~igvColor () {
}
igvColor::igvColor (const double r, const double g, const double b) {
color[R] = r;
color[G] = g;
color[B] = b;
}
igvColor::igvColor (const double r, const double g, const double b, const double a) {
color[R] = r;
color[G] = g;
color[B] = b;
color[A] = a;
}
igvColor::igvColor (const igvColor& p) { //de copia
color[R] = p.color[R];
color[G] = p.color[G];
color[B] = p.color[B];
color[A] = p.color[A];
}
// Metodos publicos
// Operadores de acceso a miembros
double& igvColor::operator[] ( const unsigned char idx ) {
return color[idx];
}
double igvColor::operator[] (const unsigned char idx) const {
return color[idx];
}
void igvColor::aplicar (void) {
glColor4dv(color);
}
float* igvColor::cloneToFloatArray() const
{
float* res = new float[4]{ (float)color[0], (float)color[1], (float)color[2], (float)color[3] };
return res;
}
void igvColor::set(const double r, const double g, const double b)
{
color[R] = r;
color[G] = g;
color[B] = b;
} | true |
b7583d37759c75e79d908271f8c0441e229588a5 | C++ | nganhkhoa/LIBRPO | /src/SignUp/SignUp.cpp | UTF-8 | 4,672 | 2.984375 | 3 | [] | no_license | /*
* @CreateTime: Jun 18, 2017 10:04 PM
* @Author: luibo
* @Contact: ng.akhoa@yahoo.com.vn
* @Last Modified By: luibo
* @Last Modified Time: Jun 18, 2017 10:04 PM
* @Description: Đăng ký người dùng mới
*/
#include <SignUp/SignUp.h>
#include <Data/ReadDataJSON.h>
using namespace std;
using json = nlohmann::json;
bool UserExist(string& NewCreation_username) {
json& userdata = UserDataJSON;
json signup = readSignUp();
unsigned int num_user = userdata.at("UserList").size();
unsigned int num_user_signup = signup.at("SignUp").size();
for (unsigned int index = 0; index < num_user; index++) {
string username = userdata.at("UserList")[index].at("Username");
if (NewCreation_username == username) return true;
}
for (unsigned int index = 0; index < num_user_signup; index++) {
string username = signup.at("SignUp")[index].at("Username");
if (NewCreation_username == username) return true;
}
return false;
}
bool ValidateNew(NewUser& NewCreation) {
if (NewCreation.UserLastName == "") return false;
if (NewCreation.UserFirstName == "") return false;
if (NewCreation.IDNumber == "") return false;
return true;
}
void ExpandSignUp(NewUser& NewCreation) {
return;
}
bool NewCommonUser(NewUser& NewCreation) {
cout << "Sau day la mau dang ki, ban hay dien vao" << endl;
cout << "Neu ban khong muon dang nhap nua, hay bo trong" << endl;
cout << "De bat dau, ban hay cho chung toi biet ban la ai?" << endl;
cout << "Ho: ";
getline(cin, NewCreation.UserLastName);
cout << "Ten: ";
getline(cin, NewCreation.UserFirstName);
cout << "CMDN: ";
getline(cin, NewCreation.IDNumber);
cout << "_________________________________________________" << endl;
cout << "Gioi tinh: " << endl;
cout << " 1. Nam" << endl;
cout << " 2. Nu" << endl;
cout << " 3. Trong" << endl;
int Choice = ChoiceInput(3);
switch (Choice) {
case 1: NewCreation.Gender = "Male"; break;
case 2: NewCreation.Gender = "Female"; break;
case 3: NewCreation.Gender = ""; break;
}
cin.ignore();
cout << "Ten dang nhap cua ban: ";
getline(cin, NewCreation.Username);
while (UserExist(NewCreation.Username)) {
cout << "Ten dang nhap ton tai" << endl;
cout << "Xin moi ban chon lai ten dang nhap khac" << endl;
cout << "De thoat, ban hay de trong" << endl;
cout << "Ten dang nhap moi: ";
getline(cin, NewCreation.Username);
if (NewCreation.Username == "") return false;
}
if (!ValidateNew(NewCreation)) {
cout << "Mau khong hop le, moi ban thu lai" << endl;
//...
return false;
}
return true;
}
bool SignUpUser(NewUser& NewCreation) {
if (!NewCommonUser(NewCreation)) return false;
cout << "Phan dang nhap da ket thuc," << endl;
cout << "Tuy nhien ban co the tiep tuc dien thong tin khong bat buoc"
<< endl;
cout << "De tiep tuc dien thong tin khong bat buoc, ban nhap 1" << endl;
cout << "De dang ky nhanh, ban nhap 2" << endl;
cout << "Lua chon: ";
int Choice = ChoiceInput(2);
if (Choice == 1) ExpandSignUp(NewCreation);
NewCreation.Password = RandomPassword();
NewCreation.UserID = GenerateUserID();
AccountCreation(NewCreation);
return true;
}
void ShowInfoAndBilling(NewUser& NewCreation) {
clearscreen();
cout << "Thong tin tai khoan moi duoc tao" << endl;
cout << "Ho va ten nguoi dung:\n\t ";
cout << NewCreation.UserFirstName << " " << NewCreation.UserLastName
<< endl;
cout << "CMND: " << NewCreation.IDNumber << endl;
cout << "Ten dang nhap: " << NewCreation.Username << endl;
cout << "Mat khau dang nhap: " << NewCreation.Password << endl << endl;
cout << "Ban hay ghi lai thong tin de khi duoc thong bao" << endl;
cout << "(qua email) ban co the bat dau su dung he thong" << endl;
cout << "LIBPRO cua chung toi" << endl;
cout << "Chuc ban mot ngay tot lanh" << endl;
pausescreen();
return;
}
void SignUp() {
clearscreen();
cout << "Ban muon tao tai khoan moi?(y/n) ";
string Answer = "";
getline(cin, Answer);
if (Answer != "y") return;
NewUser NewCreation;
while (true) {
if (!SignUpUser(NewCreation)) return;
ShowInfoAndBilling(NewCreation);
cout << "Ban chac chan voi yeu cau nay?" << endl;
cout << "1.\tChac chan, hay gui yeu cau" << endl;
cout << "2.\tToi thay co thong tin sai, huy" << endl;
cout << "3.\tThoat" << endl;
cout << "Lua chon cua ban: ";
unsigned int Choice = (unsigned int) ChoiceInput(3);
if (Choice == 3) return;
if (Choice == 2) {
cin.ignore();
continue;
}
else
break;
}
if (!add_success(NewCreation)) {
cout << "Rat tiec, loi da xay ra" << endl;
cout << "Ban vui long thu lai sau" << endl;
pausescreen();
return;
}
// pausescreen();
return;
} | true |
fc6ac9b34009cba75f3720dc203f999fbd533254 | C++ | BrunoCamargo-100/estrutura-dados | /01_revisao/aula01/ex21.cpp | UTF-8 | 259 | 3.109375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int contador = 0;
while(contador < 10) {
contador++;
cout << "\nContador = "
<< contador;
}
cout << "\n\nValor final: Contador = "
<< contador;
return 0;
}
| true |
69cefeed46a3971a3e7b88780321489f7080415f | C++ | chavanrc/axion | /problem/include/balancing_scale.hpp | UTF-8 | 988 | 2.9375 | 3 | [] | no_license | #pragma once
#include <variant>
#include <string>
#include <fstream>
namespace balancing_scale {
struct Node {
std::variant<size_t, std::string> value_;
size_t node_weight_{0};
size_t left_delta_{0};
size_t right_delta_{0};
Node *left_{nullptr};
Node *right_{nullptr};
explicit Node(std::variant<size_t, std::string> value);
[[nodiscard]] size_t Get() const;
[[nodiscard]] std::string GetName() const;
};
struct Tree {
Node *root_{nullptr};
std::string out_file_name_{"System.out"};
std::ofstream writer_;
~Tree() {
Clean(root_);
if(writer_) {
writer_.close();
}
}
explicit Tree(const std::string &in_file_name);
Node *GetNode(size_t weight, std::string_view name);
size_t Balance(Node *root);
void PrintPreorder(Node *root);
void Clean(Node *root);
};
} | true |
e076a0a13689b1e3ce779b54369656b97487cafb | C++ | PhillipVoyle/WhiteBlackCat | /src/wbcparse/production.cpp | UTF-8 | 3,497 | 2.953125 | 3 | [
"MIT"
] | permissive | #include "production.h"
class CToken:public IToken
{
std::string m_identifier;
unsigned m_id;
public:
CToken(const std::string& identifier):
m_identifier(identifier),
m_id(0)
{
}
const std::string& GetName()
{
return m_identifier;
}
void SetID(unsigned id)
{
m_id = id;
}
unsigned GetID(void)
{
return m_id;
}
};
std::shared_ptr<IToken> IToken::Create(const std::string& identifier)
{
return std::make_shared<CToken>(identifier);
}
class CTokenList:public ITokenList
{
std::shared_ptr<IToken> m_token;
std::shared_ptr<ITokenList> m_tokenList;
bool m_isTerminal;
public:
CTokenList(std::shared_ptr<IToken>& token, std::shared_ptr<ITokenList>& tokenList):
m_token(token),
m_tokenList(tokenList),
m_isTerminal(true)
{
}
std::shared_ptr<IToken> GetToken()
{
return m_token;
}
std::shared_ptr<ITokenList> GetTokenList()
{
return m_tokenList;
}
void SetIsTerminal(bool isTerminal)
{
m_isTerminal = isTerminal;
}
bool GetIsTerminal(void)
{
return m_isTerminal;
}
};
std::shared_ptr<ITokenList> ITokenList::Create(std::shared_ptr<IToken>& token, std::shared_ptr<ITokenList>& tokenList)
{
return std::make_shared<CTokenList>(token, tokenList);
}
class CProduction:public IProduction
{
std::shared_ptr<IToken> m_left;
std::shared_ptr<ITokenList> m_right;
std::string m_response;
unsigned m_id;
int m_precedence;
Associativity m_associativity;
int m_orderID;
public:
CProduction(std::shared_ptr<IToken>& left, std::shared_ptr<ITokenList>& right, const std::string& response):
m_left(left),
m_right(right),
m_response(response)
{
m_precedence = 0;
m_associativity = asNone;
m_orderID = -1;
}
std::shared_ptr<IToken> GetLeft()
{
return m_left;
}
std::shared_ptr<ITokenList> GetRight()
{
return m_right;
}
const std::string& GetResponse()
{
return m_response;
}
void SetID(unsigned id)
{
m_id = id;
}
unsigned GetID()
{
return m_id;
}
void SetPrecedence(int precedence)
{
m_precedence = precedence;
}
int GetPrecedence()
{
return m_precedence;
}
void SetAssociativity(Associativity associativity)
{
m_associativity = associativity;
}
Associativity GetAssociativity()
{
return m_associativity;
}
void SetOrderID(int id)
{
m_orderID = id;
}
int GetOrderID()
{
return m_orderID;
}
};
std::shared_ptr<IProduction> IProduction::Create(std::shared_ptr<IToken> left, std::shared_ptr<ITokenList> right, const std::string& response)
{
return std::make_shared<CProduction>(left, right, response);
}
class CProductions:public IProductions
{
std::shared_ptr<IProduction> m_production;
std::shared_ptr<IProductions> m_productions;
public:
CProductions(std::shared_ptr<IProduction> &production, std::shared_ptr<IProductions>& productions):
m_production(production),
m_productions(productions)
{
}
std::shared_ptr<IProduction> GetProduction()
{
return m_production;
}
std::shared_ptr<IProductions> GetProductions()
{
return m_productions;
}
void SetProductions(std::shared_ptr<IProductions> productions)
{
m_productions = productions;
}
};
std::shared_ptr<IProductions> IProductions::Create(std::shared_ptr<IProduction> &production, std::shared_ptr<IProductions>& productions)
{
return std::make_shared<CProductions>(production, productions);
} | true |
73489a79a3debe193662d8fdf23050e455f217d8 | C++ | e-sushi/P3DPGE | /P3DPGE/src/components/Light.h | UTF-8 | 503 | 2.625 | 3 | [
"MIT",
"LicenseRef-scancode-public-domain",
"Unlicense"
] | permissive | #pragma once
#include "Component.h"
#include "../math/Vector3.h"
struct Light : public Component {
Vector3 position;
Vector3 direction; //TODO change this to Quat
float strength;
//Geometry* shape;
//OpenGL's tutorial used int but we may want to experiment
//with using float later on
std::vector<int> depthTexture;
Light(const Vector3& position, const Vector3& direction, float strength = 1.f) {
this->position = position;
this->direction = direction;
this->strength = strength;
}
}; | true |
073cc7afdc99fa26dd4e382175cc7e038a92e83b | C++ | buzzon/FirstOpenGL | /ray_traicing/sphere.cpp | WINDOWS-1251 | 889 | 2.984375 | 3 | [] | no_license | #include "sphere.h"
// length ( origin direction) ?
bool sphere::intersect(const vec3f& origin, const vec3f norm_direction, float& length) const
{
//// origin direction
//vec3f ray = norm_direction - origin;
vec3f L = position - origin;
float tca = L * norm_direction;
float d2 = L * L - tca * tca;
if (d2 > radius * radius) return false;
float thc = sqrtf(radius * radius - d2);
length = tca - thc;
float t1 = tca + thc;
if (length < 0) length = t1;
if (length < 0) return false;
return true;
}
Material sphere::get_material() const
{
return material;
}
vec3f sphere::get_normal(vec3f hit) const
{
return (hit - position).normalize();
}
| true |
cf88b636b9c407981e0888c6937993924e3ec40e | C++ | theazgra/CudaCourse | /project/src/image.cpp | UTF-8 | 870 | 3.015625 | 3 | [
"MIT"
] | permissive | #include <image.h>
Image::Image(const char *filename, ImageType type)
{
this->type = type;
FreeImage_Initialise();
FREE_IMAGE_FORMAT fileFormat = FreeImage_GetFileType(filename);
_data = FreeImage_Load(fileFormat, filename);
_channels = channels_per_image_type(type);
_width = FreeImage_GetWidth(_data);
_height = FreeImage_GetHeight(_data);
_pitch = FreeImage_GetPitch(_data);
}
Image::~Image()
{
FreeImage_Unload(_data);
FreeImage_DeInitialise();
}
int Image::width() const
{
return _width;
}
int Image::height() const
{
return _height;
}
size_t Image::pitch() const
{
return _pitch;
}
int Image::channel_count() const
{
return _channels;
}
ImageType Image::image_type() const
{
return type;
}
unsigned char *Image::data() const
{
BYTE *dataPtr = FreeImage_GetBits(_data);
return dataPtr;
} | true |
b6c9ae4afe7ff5dbbadb05f4325d019cba68399a | C++ | haoyuanz13/Codings | /arrayIssue/longestIncrease.cpp | UTF-8 | 1,804 | 3.375 | 3 | [] | no_license | #include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
typedef vector<vector<int>> matrix;
// increase subsequence in array, no need to be continuous (DP)
int longestLength(vector<int> nums) {
if (nums.empty() || nums.size() < 1)
return 0;
if (nums.size() == 1)
return 1;
int len = nums.size();
vector<int> dp (len, 1);
int max_len = 1;
for (int i = 0; i < len; i ++) {
int cur = nums[i];
// traverse all previous longest length
for (int j = 0; j < i; j ++) {
if (cur > nums[j] && dp[i] < dp[j] + 1) {
dp[i] = dp[j] + 1;
max_len = (max_len < dp[i])? dp[i] : max_len;
}
}
}
return max_len;
}
// longest consecutive sequence, the array is out of order
// leetcode 128
int longestConsecutive(vector<int>& nums) {
if (nums.empty() || nums.size() < 2)
return nums.size();
// the key is element in the array, value is their consecutive length
unordered_map<int, int> numMap;
for (int i = 0; i < nums.size(); i ++)
numMap[nums[i]] = 1;
int maxlen = 0;
for (int i = 0; i < nums.size(); i ++) {
if (!(numMap.count(nums[i]) > 0))
continue;
int curlen = 1;
int temp1 = nums[i] + 1;
int temp2 = nums[i] - 1;
// traverse larger value side
while (numMap.count(temp1) > 0) {
curlen += 1;
numMap.erase(temp1); // remove element to speed up searching
temp1 ++;
}
while (numMap.count(temp2) > 0) {
curlen += 1;
numMap.erase(temp2);
temp2 --;
}
// remove the center one
numMap.erase(nums[i]);
maxlen = (maxlen < curlen)? curlen : maxlen;
}
return maxlen;
}
int main(int agrc, char** argv) {
vector<int> nums {100, 4, 200, 1, 3, 2};
cout << longestConsecutive(nums) << endl;
return 0;
}
| true |
ea384ea96ccb87d52b3af9dee8b5ab51cc51a1c7 | C++ | rafaeldoria/Exercicios_Algoritmo1 | /roteiro_5/Exercicio4_lista4.cpp | ISO-8859-1 | 602 | 3.25 | 3 | [] | no_license | /*
Programador : Rafael Dria
Data: 23/05/2013
Descrio: Lista 4 Exerccio 4
*/
#include<iostream>
#include<math.h>
using namespace std;
int main()
{ int vet[10],number,aux;
for (int i=0;i<10;i++)
{ cout<<"Digite um valor: ";
cin>>number;
vet[i]=number;
}
for (int i=0;i<10;i++)
for (int j=i+1;j<10;j++)
{ if(vet[i]>vet[j])
{ aux=vet[i];
vet[i]=vet[j];
vet[j]=aux;}
}
cout<<"Em ordem crescente: ";
for (int i=0;i<10;i++)
{cout<<vet[i]<<", ";}
cout<<"\n";
system("pause");
}
| true |
b22167295b480c03300e3156a842077045c742f4 | C++ | kanekyo1234/AtCoder_solve | /ABC/49/A.cpp | UTF-8 | 252 | 2.765625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main() {
char b;
cin >>b;
//cout <<a << c;
if (b=='a' || b=='e' || b=='i' || b== 'o' || b== 'u'){
cout << "vowel";
}else{
cout << "consonant";
}
return 0;
} | true |
3af5594c2d6c94eadf20d97586405aa13cb5540f | C++ | vespa-engine/vespa | /vespalib/src/vespa/vespalib/hwaccelrated/generic.cpp | UTF-8 | 5,045 | 2.609375 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "generic.h"
#include "private_helpers.hpp"
#include <cblas.h>
namespace vespalib::hwaccelrated {
namespace {
template <typename ACCUM, typename T, size_t UNROLL>
ACCUM
multiplyAdd(const T * a, const T * b, size_t sz) noexcept
{
ACCUM partial[UNROLL];
for (size_t i(0); i < UNROLL; i++) {
partial[i] = 0;
}
size_t i(0);
for (; i + UNROLL <= sz; i+= UNROLL) {
for (size_t j(0); j < UNROLL; j++) {
partial[j] += a[i+j] * b[i+j];
}
}
for (;i < sz; i++) {
partial[i%UNROLL] += a[i] * b[i];
}
ACCUM sum(0);
for (size_t j(0); j < UNROLL; j++) {
sum += partial[j];
}
return sum;
}
template <typename T, size_t UNROLL>
double
squaredEuclideanDistanceT(const T * a, const T * b, size_t sz) noexcept
{
T partial[UNROLL];
for (size_t i(0); i < UNROLL; i++) {
partial[i] = 0;
}
size_t i(0);
for (; i + UNROLL <= sz; i += UNROLL) {
for (size_t j(0); j < UNROLL; j++) {
T d = a[i+j] - b[i+j];
partial[j] += d * d;
}
}
for (;i < sz; i++) {
T d = a[i] - b[i];
partial[i%UNROLL] += d * d;
}
double sum(0);
for (size_t j(0); j < UNROLL; j++) {
sum += partial[j];
}
return sum;
}
template<size_t UNROLL, typename Operation>
void
bitOperation(Operation operation, void * aOrg, const void * bOrg, size_t bytes) noexcept {
const size_t sz(bytes/sizeof(uint64_t));
{
auto a(static_cast<uint64_t *>(aOrg));
auto b(static_cast<const uint64_t *>(bOrg));
size_t i(0);
for (; i + UNROLL <= sz; i += UNROLL) {
for (size_t j(0); j < UNROLL; j++) {
a[i + j] = operation(a[i + j], b[i + j]);
}
}
for (; i < sz; i++) {
a[i] = operation(a[i], b[i]);
}
}
auto a(static_cast<uint8_t *>(aOrg));
auto b(static_cast<const uint8_t *>(bOrg));
for (size_t i(sz*sizeof(uint64_t)); i < bytes; i++) {
a[i] = operation(a[i], b[i]);
}
}
}
float
GenericAccelrator::dotProduct(const float * a, const float * b, size_t sz) const noexcept
{
return cblas_sdot(sz, a, 1, b, 1);
}
double
GenericAccelrator::dotProduct(const double * a, const double * b, size_t sz) const noexcept
{
return cblas_ddot(sz, a, 1, b, 1);
}
int64_t
GenericAccelrator::dotProduct(const int8_t * a, const int8_t * b, size_t sz) const noexcept
{
return multiplyAdd<int64_t, int8_t, 8>(a, b, sz);
}
int64_t
GenericAccelrator::dotProduct(const int16_t * a, const int16_t * b, size_t sz) const noexcept
{
return multiplyAdd<int64_t, int16_t, 8>(a, b, sz);
}
int64_t
GenericAccelrator::dotProduct(const int32_t * a, const int32_t * b, size_t sz) const noexcept
{
return multiplyAdd<int64_t, int32_t, 8>(a, b, sz);
}
long long
GenericAccelrator::dotProduct(const int64_t * a, const int64_t * b, size_t sz) const noexcept
{
return multiplyAdd<long long, int64_t, 8>(a, b, sz);
}
void
GenericAccelrator::orBit(void * aOrg, const void * bOrg, size_t bytes) const noexcept
{
bitOperation<8>([](uint64_t a, uint64_t b) { return a | b; }, aOrg, bOrg, bytes);
}
void
GenericAccelrator::andBit(void * aOrg, const void * bOrg, size_t bytes) const noexcept
{
bitOperation<8>([](uint64_t a, uint64_t b) { return a & b; }, aOrg, bOrg, bytes);
}
void
GenericAccelrator::andNotBit(void * aOrg, const void * bOrg, size_t bytes) const noexcept
{
bitOperation<8>([](uint64_t a, uint64_t b) { return a & ~b; }, aOrg, bOrg, bytes);
}
void
GenericAccelrator::notBit(void * aOrg, size_t bytes) const noexcept
{
auto a(static_cast<uint64_t *>(aOrg));
const size_t sz(bytes/sizeof(uint64_t));
for (size_t i(0); i < sz; i++) {
a[i] = ~a[i];
}
auto ac(static_cast<uint8_t *>(aOrg));
for (size_t i(sz*sizeof(uint64_t)); i < bytes; i++) {
ac[i] = ~ac[i];
}
}
size_t
GenericAccelrator::populationCount(const uint64_t *a, size_t sz) const noexcept {
return helper::populationCount(a, sz);
}
double
GenericAccelrator::squaredEuclideanDistance(const int8_t * a, const int8_t * b, size_t sz) const noexcept {
return helper::squaredEuclideanDistance(a, b, sz);
}
double
GenericAccelrator::squaredEuclideanDistance(const float * a, const float * b, size_t sz) const noexcept {
return squaredEuclideanDistanceT<float, 2>(a, b, sz);
}
double
GenericAccelrator::squaredEuclideanDistance(const double * a, const double * b, size_t sz) const noexcept {
return squaredEuclideanDistanceT<double, 2>(a, b, sz);
}
void
GenericAccelrator::and64(size_t offset, const std::vector<std::pair<const void *, bool>> &src, void *dest) const noexcept {
helper::andChunks<16, 4>(offset, src, dest);
}
void
GenericAccelrator::or64(size_t offset, const std::vector<std::pair<const void *, bool>> &src, void *dest) const noexcept {
helper::orChunks<16,4>(offset, src, dest);
}
}
| true |
1e89b220a529008c4bec3237e931229e1533c37f | C++ | PeterZs/AnIntroductionToRayTracing | /header/superhyperboloid.h | UTF-8 | 1,260 | 2.828125 | 3 | [] | no_license | #ifndef SUPERHYPERBOLOID_H
#define SUPERHYPERBOLOID_H
#include "hitable.h"
#include "material.h"
#include "log.h"
class superhyperboloid : public hitable
{
public:
superhyperboloid() {}
superhyperboloid(vec3 cen, float a1, float a2, float a3, float e1, float e2, float s1, float s2, float hy, int in, float tol, material *m) :
center(cen), intercept_x(a1), intercept_y(a2), intercept_z(a3), p_e1(e1), p_e2(e2),
sign1(s1), sign2(s2), half_y(hy), initial_number(in), tolerance(tol), ma(m) {}
/*
f(x,y,z)=( (x/a1)^(2/e2) + s2*(z/a3)^(2/e2) )^(e2/e1) + s1*(y/a2)^(2/e1) -1 = 0
in: initial number
tol: tolerance
s1,s2: 1, 1: superellipsoid
s1,s2:-1, 1: superhyperboloids of one sheet
s1,s2:-1,-1: superhyperboloids of two sheets
hy: half height of the surface in y-direction
NOTE: there are something wrong with two sheets situation.
*/
virtual bool hit(const ray& r, float tmin, float tmax, hit_record& rec) const;
vec3 center;
float intercept_x, intercept_y, intercept_z;
float p_e1, p_e2;
float sign1, sign2;
float half_y;
int initial_number;
float tolerance;
material *ma;
};
#endif // SUPERHYPERBOLOID_H
| true |
214496ad8d4d26cabc9317ab7f63c89065639667 | C++ | angelhunt/acm | /nowcoder/求解方程.cpp | UTF-8 | 7,469 | 2.984375 | 3 | [] | no_license | #include <cstdio>
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int x=0,n=0,xr=0,nr=0; int flag =0;
void Adds(string a,char op)
{
if(flag==0) // 等式左边
{
if(a[a.size()-1]=='x') // 处理的该项为x的系数
{
if(a=="x")
x += (op=='+'?1:-1);
else
{
a.erase(a.size()-1,a.size()); int temp = stoi(a);
x +=(op=='+'?temp:-temp);
}
}
else //处理的为常数项
{
int temp = stoi(a);
n +=(op=='+'?temp:-temp);
}
}
else // 处理的为等式右边
{
if(a[a.size()-1]=='x') //
{
if(a=="x")
xr += (op=='+'?1:-1);
else
{
a.erase(a.size()-1,a.size()); int temp = stoi(a);
xr +=(op=='+'?temp:-temp);
}
}
else
{
int temp = stoi(a);
nr +=(op=='+'?temp:-temp);
}
}
}
int main()
{
string str;getline(cin,str);int i=0;
char c = '+';if(str[0]=='-') {c='-'; i++;} // 判断第一项的正负号//若第一项为-x;i++
for(;i<str.size();i++)
{
string temp;
while(i<str.size() && str[i]!='-' && str[i]!='+' && str[i]!='=') // 获取每一项
{
temp +=str[i];i++;
}
Adds(temp,c);
if(str[i]=='=') // 处理等式右边置flag1,并且判断等式右边第一项的正负号
{ flag =1;
if(str[i+1]=='-') {c='-';i++;}//若等式后第一项为-x;i++
else c='+';
}
else c=str[i]; //改变符号
}
x = x-xr;nr = nr-n;
if(x==0 && nr!=0) // 无解
printf("-1");
else if(x==0 && nr==0)//无穷多解
printf("-1");
else // 假设解都为正整数
printf("%d",nr/x);
// printf("%d %d %d %d",x,n,xr,nr);
}
#include <bits/stdc++.h>
using namespace std;
string str, str_l, str_r;
struct node
{
// a表示x前面的系数,b表示常数系数
double a, b;
};
// 判断优先级的大小
int priority(char c)
{
if (c == '*' || c == '/')
return 2;
if (c == '+' || c == '-')
return 1;
return 0;
}
void calc(stack <char> &op, stack <node> &num)
{
node bb = num.top();
num.pop();
node aa = num.top();
num.pop();
node temp_node;
switch (op.top())
{
case '+':
temp_node.a = aa.a + bb.a;
temp_node.b = aa.b + bb.b;
num.push(temp_node);
break;
case '-':
temp_node.a = aa.a - bb.a;
temp_node.b = aa.b - bb.b;
num.push(temp_node);
break;
case '*':
// 处理一元一次方程,不考虑二次项
temp_node.a = aa.a * bb.b + aa.b * bb.a;
temp_node.b = aa.b * bb.b;
num.push(temp_node);
break;
case '/':
temp_node.a = aa.a / bb.b;
temp_node.b = aa.b / bb.b;
num.push(temp_node);
break;
}
op.pop();
}
int main()
{
while (1)
{
cin >>str;
// 得到str_l, str_r
for (int i = 0; i < str.size(); ++ i)
{
if (str[i] == '=')
{
str_l = str.substr(0, i);
str_r = str.substr(i + 1, str.size());
}
}
// 定义符号栈、数字栈
stack <node> num_l;
stack <node> num_r;
stack <char> op_l;
stack <char> op_r;
// 定义左右两边串的长度
int len_l = str_l.size();
int len_r = str_r.size();
// 遍历左边的字符串
for (int i = 0; i < len_l; ++ i)
{
if (isdigit(str_l[i]))
{
node temp_node;
double temp = atof(&str_l[i]);
while (isdigit(str_l[i]) || str_l[i] == '.')
++ i;
if (str_l[i] == 'x')
{
temp_node.a = temp;
temp_node.b = 0;
num_l.push(temp_node);
}
else
{
temp_node.a = 0;
temp_node.b = temp;
num_l.push(temp_node);
-- i;
}
}
else if (str_l[i] == 'x')
{
node temp_node;
temp_node.a = 1;
temp_node.b = 0;
num_l.push(temp_node);
}
else if (str_l[i] == '(')
{
op_l.push(str_l[i]);
}
else if (str_l[i] == ')')
{
while (op_l.top() != '(')
calc(op_l, num_l);
op_l.pop();
}
else if (op_l.empty())
{
op_l.push(str_l[i]);
}
else if (priority(op_l.top()) < priority(str_l[i]))
{
op_l.push(str_l[i]);
}
else if (priority(op_l.top()) >= priority(str_l[i]))
{
while (!op_l.empty() && priority(op_l.top()) >= priority(str_l[i]))
calc(op_l, num_l);
op_l.push(str_l[i]);
}
}
// 遍历右边的字符串
for (int i = 0; i < len_r; ++ i)
{
if (isdigit(str_r[i]))
{
node temp_node;
double temp = atof(&str_r[i]);
while (isdigit(str_r[i]) || str_r[i] == '.')
++ i;
if (str_r[i] == 'x')
{
temp_node.a = temp;
temp_node.b = 0;
num_r.push(temp_node);
}
else
{
temp_node.a = 0;
temp_node.b = temp;
num_r.push(temp_node);
-- i;
}
}
else if (str_r[i] == 'x')
{
node temp_node;
temp_node.a = 1;
temp_node.b = 0;
num_r.push(temp_node);
}
else if (str_r[i] == '(')
{
op_r.push(str_r[i]);
}
else if (str_r[i] == ')')
{
while (op_r.top() != '(')
calc(op_r, num_r);
op_r.pop();
}
else if (op_r.empty())
{
op_r.push(str_r[i]);
}
else if (priority(op_r.top()) < priority(str_r[i]))
{
op_r.push(str_r[i]);
}
else if (priority(op_r.top()) >= priority(str_r[i]))
{
while (!op_r.empty() && priority(op_r.top()) >= priority(str_r[i]))
calc(op_r, num_r);
op_r.push(str_r[i]);
}
}
while (!op_l.empty())
calc(op_l, num_l);
while (!op_r.empty())
calc(op_r, num_r);
double x1 = num_l.top().a, y1 = num_l.top().b;
double x2 = num_r.top().a, y2 = num_r.top().b;
// cout <<x1 <<" " <<y1 <<" " <<x2 <<" " <<y2 <<endl;
if(x1 - x2 == 0.0)
cout << "-1";
else
printf("%.2lf\n", (y2 - y1) / (x1 - x2));
}
return 0;
} | true |
57ad2d6e701001764ce66891e3aa58860dfb0168 | C++ | Sumon-Ict/UVA-Problem-Solution | /UVA and URI Problem solution/uva12577.cpp | UTF-8 | 556 | 2.90625 | 3 | [] | no_license | #include<iostream>
#include<stdio.h>
#include<cstring>
using namespace std;
int main()
{
char str[10];
char str1[]="*";
char str2[]="Hajj";
char str3[]="Umrah";
int i=1;
while(1)
{
cin>>str;
if(strcmp(str,str1)==0)
break;
if(strcmp(str,str2)==0)
{
printf("Case %d: Hajj-e-Akbar\n",i);
i++;
}
if(strcmp(str,str3)==0)
{
printf("Case %d: Hajj-e-Asghar\n",i);
i++;
}
}
}
| true |
71f5a37f67c3a9b821402ca1bb3740f239268678 | C++ | Thuy2612/C-_OOP | /Thi/Mtime/Mtime.cpp | UTF-8 | 578 | 3.609375 | 4 | [] | no_license | #include "Mtime.h"
Mtime::Mtime()
{
hours=0;
minutes=0;
seconds=0;
}
Mtime::Mtime(int hours, int minutes, int seconds )
{
this->hours=hours;
this->minutes=minutes;
this->seconds=seconds;
}
void Mtime::show()
{
if(seconds>=60)
{
minutes+=minutes/60;
seconds=seconds%60;
}
if(minutes>=60)
{
hours+=hours/60;
minutes=minutes%60;
}
cout<<hours<<":"<<minutes<<":"<<seconds<<endl;
}
Mtime Mtime :: operator+(Mtime time)
{
Mtime mtime;
mtime.seconds=time.seconds+seconds;
mtime.minutes=time.minutes+minutes;
mtime.hours=time.hours+hours;
return mtime;
}
| true |
8fa990cf7b8f24d8544e8268746b25f4fceb02b6 | C++ | jyao6429/11872A-team-code | /pros-2020-2021/include/indexer.h | UTF-8 | 531 | 2.546875 | 3 | [] | no_license | #ifndef INDEXER_H
#define INDEXER_H
namespace indexer
{
/**
* Moves indexer with target voltage while insuring safety with a mutex
*
* @param indexerVolt - desired voltage for the indexer motor
*/
void moveVoltageSafe(int indexerVolt);
/**
* Moves indexer with target voltage
*
* @param indexerVolt - desired voltage for the indexer motor
*/
void moveVoltage(int indexerVolt);
/**
* Fucntion for indexer control during driver
*/
void opcontrol();
}
#endif | true |
c7086614defbc967858eda5b8b62548809282d6b | C++ | Nikhil12321/codes | /stringendingwith$.cpp | UTF-8 | 883 | 2.890625 | 3 | [] | no_license | #include<iostream>
#include<string.h>
#include<unordered_map>
using namespace std;
int main(){
string s;
getline(std::cin, s);
unordered_map<string, int> m;
char *str;
const char *brk = " $";
int i;
str = new char[s.size()];
for(i = 0;i<s.size();i++)
str[i] = s[i];
char *p;
p = strtok(str,brk);
while(p!=0){
//cout<<"p is "<<p<<endl;
string ss(p);
//cout<<"ss is "<<ss<<endl;
if(m.find(ss) != m.end()){
m.at(ss)++;
}
else
{
pair<string, int> pr(ss, 1);
m.insert(pr);
}
cout<<"p is "<<p<<endl;
p = strtok(0, brk);
}
unordered_map<string, int>::iterator it = m.begin();
while(it != m.end()){
cout<<it->first<< " "<<it->second<<endl;
it++;
}
return 0;
} | true |
7588b413ebc1d073f97b560d2691afde4a2593d7 | C++ | sunnyisgalaxy/moabs | /src/mcomp/lib/stan/math/prim/scal/fun/log1m_exp.hpp | UTF-8 | 1,462 | 3.3125 | 3 | [] | no_license | #ifndef STAN__MATH__PRIM__SCAL__FUN__LOG1M_EXP_HPP
#define STAN__MATH__PRIM__SCAL__FUN__LOG1M_EXP_HPP
#include <boost/math/tools/promotion.hpp>
#include <stdexcept>
#include <boost/throw_exception.hpp>
#include <boost/math/special_functions/expm1.hpp>
#include <stan/math/prim/scal/fun/log1m.hpp>
namespace stan {
namespace math {
/**
* Calculates the log of 1 minus the exponential of the specified
* value without overflow log1m_exp(x) = log(1-exp(x)).
*
* This function is only defined for x<0
*
*
\f[
\mbox{log1m\_exp}(x) =
\begin{cases}
\ln(1-\exp(x)) & \mbox{if } x < 0 \\
\textrm{NaN} & \mbox{if } x \geq 0\\[6pt]
\textrm{NaN} & \mbox{if } x = \textrm{NaN}
\end{cases}
\f]
\f[
\frac{\partial\,\mbox{asinh}(x)}{\partial x} =
\begin{cases}
-\frac{\exp(x)}{1-\exp(x)} & \mbox{if } x < 0 \\
\textrm{NaN} & \mbox{if } x \geq 0\\[6pt]
\textrm{NaN} & \mbox{if } x = \textrm{NaN}
\end{cases}
\f]
*/
template <typename T>
inline typename boost::math::tools::promote_args<T>::type
log1m_exp(const T a) {
if (a >= 0)
return std::numeric_limits<double>::quiet_NaN();
else if (a > -0.693147)
return std::log(-boost::math::expm1(a)); //0.693147 is approximatelly equal to log(2)
else
return log1m(std::exp(a));
}
}
}
#endif
| true |
c10d49d1aa5be5c17b889d8a7e9ad5a82c964674 | C++ | paulobruno/UFC-DigitalImageProcessing | /mains/colorMain.cpp | UTF-8 | 1,595 | 2.640625 | 3 | [] | no_license | #include <string>
#include <opencv2/opencv.hpp>
#include <vector>
#include "../libs/coloring.h"
int main(int argc, const char** argv)
{
if (2 > argc)
{
std::cout << "Error: incorrect number of args.\n"
<< "Usage: " << argv[0] << " <image>\n";
return -1;
}
std::string filename(argv[1]);
cv::Mat img = cv::imread(filename, cv::IMREAD_COLOR);
if (img.empty())
{
std::cerr << "Error: Cannot read " << filename << "\n";
return -1;
}
cv::imshow(filename, img); // Imagem original
cv::Mat cmyImg;
rgbToCmy(img, cmyImg); // teste
cv::imshow("rgbCmy", cmyImg);
cv::Mat rgbImg;
cmyToRgb(cmyImg, rgbImg);
cv::imshow("cmyRgb", rgbImg);
cv::Mat hsiImg;
rgbToHsi(img, hsiImg);
cv::imshow("rgbHsi", hsiImg);
cv::Mat rgbFromHsiImg;
hsiToRgb(hsiImg, rgbFromHsiImg); // FL: peguei a matriz em hsi para devolver os valores em rgb
cv::imshow("hsiRgb", rgbFromHsiImg);
cv::Mat cmyFromHsiImg;
hsiToCmy(img, cmyFromHsiImg);
cv::imshow("hsiCmy", cmyFromHsiImg);
cv::Mat hsiFromCmyImg;
cmyToHsi(img, hsiFromCmyImg);
cv::imshow("cmyHsi", hsiFromCmyImg);
cv::Mat sepiaImg;
sepiaFilter(img, sepiaImg);
cv::imshow("Sepia", sepiaImg);
cv::Mat chromaImg = cv::imread("../assets/chroma_key.jpg", cv::IMREAD_COLOR);
cv::Mat keyedMat;
cv::Vec3b key = {25, 175, 55};
cv::Vec3b pEpsilon = {25, 80, 25};
chromaKeying(chromaImg, keyedMat, key, pEpsilon);
cv::imshow("Chroma Key", keyedMat);
cv::waitKey();
return 0;
}
| true |
cb77d72a8458ab0ca0b9391ba2332db7f7aa2082 | C++ | miguelangelo78/QEPU_HardwareSimulator | /misc/utils/utils.cpp | UTF-8 | 1,821 | 3.03125 | 3 | [] | no_license | #include "../../stdafx.h"
#include "utils.h"
char * Utils::long2binstr(int num, int strlength){
char*str = new char[strlength + 1];
if (!str) return NULL;
str[strlength] = 0;
// type punning because signed shift is implementation-defined
unsigned u = *(unsigned *) #
for (; strlength--; u >>= 1)
str[strlength] = u & 1 ? '1' : '0';
return str;
}
char* Utils::char2str(char c){
char*str = (char*) malloc(sizeof(char));
sprintf(str, "%d", c);
return str;
}
int* Utils::str2intarr(char* c){
int c_length = 0;
for (int i = 0; true; i++) if (c[i] == 0xFF && c[i - 1] == 0xFF && c[i - 2] == 0xFF && c[i - 3] == 0xFF && c[i - 4] == 0xFF) break; else c_length++; c_length -= 4;
int *intarr = (int*) malloc(sizeof(int) *(c_length + 5));
for (int i = 0; i<c_length; i++) intarr[i] = (int) c[i];
for (int i = c_length; i<c_length + 5; i++) intarr[i] = 0xFF;
return intarr;
}
int Utils::countdigits(int dec){
int counter = 0;
while (dec != 0){
dec /= 10;
++counter;
}
return counter;
}
char* Utils::int2str(int dec){
char str[10];
sprintf(str, "%d", dec);
return str;
}
int Utils::dec2hex(int dec){
char str[100];
sprintf(str, "%x", dec);
return (int) strtol(str, NULL, 16);
}
int Utils::concint(int n1, int n2){
char str1[10], str2[10];
sprintf(str1, "%d", n1);
sprintf(str2, "%d", n2);
strcat(str1, str2);
return atoi(str1);
}
void Utils::delay(int ms){
while (ms--) Sleep(1);
}
float Utils::custom_pow(float base, int exp){
float result = 1; for (int i = 0; i<exp; i++) result *= base;
return result;
}
int * Utils::arrint_shiftright(int * arr, int newelem, int array_length){
int * new_array = (int*) malloc(sizeof(int) *array_length);
int new_array_index = 0;
new_array[0] = newelem;
for (int i = 0; i<array_length; i++) new_array[++new_array_index] = arr[i];
return new_array;
} | true |
6d9ee090f1a86f0f7d8457a1c32a1484acb3a9f8 | C++ | skolakoda/ucimo-cpp | /45-pokazivaci/pokazivaci2.cpp | UTF-8 | 307 | 3.15625 | 3 | [] | no_license | #include <iostream>
int main(){
int broj = 3;
int *pokazivac;
std::cout << "Prazan pokazivac pokazuje na memorijsku adresu " << pokazivac << ".\n";
pokazivac = &broj;
std::cout << "Pokazivac sada pokazuje na " << pokazivac << ", memorijsku adresu varijable broj.\n";
return 0;
}
| true |
3b55bbc817670143a0cf2084517607c7226f084c | C++ | ConnectNitish/CompetitiveProgramming | /CodeFiles/Array_Others/interviewbit-count-pairs-in-array-whose-sum-is-divisible-by-the-given-number-hash/main.cpp | UTF-8 | 2,758 | 2.890625 | 3 | [] | no_license | /******************************************************************************
Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.
https://www.interviewbit.com/problems/count-pairs-in-array-whose-sum-is-divisible-by-the-given-number/
*******************************************************************************/
#include <stdio.h>
#include<iostream>
#include<vector>
using namespace std;
int mod = 1000000007;
class Solution
{
public :
int solve(vector<int> &A, int B);
};
int Solution::solve(vector<int> &A, int B)
{
int size = B/2;
bool odd = ((B&1)==0) ? false : true;
//unordered_map<int,vector<int>> m;
long long int cm[B];
for(int i=0;i<B;i++)
cm[i]=0;
//memset(cm,0,sizeof(cm));
for(int i=0;i<A.size();i++)
{
int mod1 = (A[i]%B);
//m[mod1].push_back(A[i]);
cm[mod1]++;
//cm[mod1] = cm[mod1]%mod;
}
long long int count=0;
/*
for(auto a:m)
{
int index = a.first;
if(index==0 && a.second.size()>0)
{
int n = a.second.size();
count += ((n%mod * (n-1)%mod)%mod/2)%mod;
}
else if(B-index == index)
{
int n = a.second.size();
count += ((n%mod * (n-1)%mod)%mod/2)%mod;
}
else if(m[B-index].size()>0 && a.second.size()>0)
{
count += (a.second.size()%mod * m[B-index].size()%mod)%mod;
m[B-index].clear();
}
a.second.clear();
}
*/
// if(count%2==1)
// return (count/2)+1;
bool TLE = false;
if(cm[0]>0)
{
if(TLE)
count = (count + (((long long)( cm[0] * (cm[0]-1) ) % mod) / 2)%mod)%mod;
else
count += ((cm[0] * (cm[0]-1))/2);
}
for(int i=1;i<=(B/2) && i!=(B-i);i++)
{
if(TLE)
count = (count + (((long long)( cm[i] * (cm[B-i]) ) % mod))%mod)%mod;
else
count += ((cm[i] * (cm[B-i])));
}
if(B%2==0)
{
if(TLE)
count = (count + (((long long)( cm[B/2] * (cm[B/2]-1) ) % mod) / 2)%mod)%mod;
else
count += ((cm[B/2] * (cm[B/2]-1))/2);
}
return (count%mod);
}
int main()
{
int V;
cin >> V;
int i=0;
vector<int> ID;
while(i<V)
{
int value;
cin >> value;
ID.push_back(value);
i++;
}
int B;
cin >> B;
Solution s;
cout << s.solve(ID,B) << endl;
return 0;
}
| true |
22cce9542deb4e08a0ca5c90d088852547ebe148 | C++ | Romchirik/OS | /5lab/main.cpp | UTF-8 | 2,155 | 2.8125 | 3 | [] | no_license | #include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#define _FILE_OFFSET_BITS 64
#define LINE_BUF_SIZE 32
int main(int argc, char** argv)
{
if (argc < 2) {
perror("No text file given, please restart with one\n");
return 0;
}
int file_desc = 0;
if ((file_desc = open(argv[1], O_RDONLY)) == -1) {
perror("File cannot be open, try again\n");
return 0;
}
int lines_count = 0;
off_t lines_shifts[BUFSIZ];
int lines_lengths[BUFSIZ];
char c_char = 0;
int cur_line_length = 0;
//making matrixes of lengths and shifts
while (read(file_desc, &c_char, 1)) {
if (c_char == '\n') {
lines_lengths[lines_count] = ++cur_line_length;
lines_shifts[++lines_count] = lseek(file_desc, 0, SEEK_CUR);
cur_line_length = 0;
} else {
cur_line_length++;
}
}
//printing the right line
char line_buffer[LINE_BUF_SIZE];
if (line_buffer == NULL) {
return 0;
}
int line_buffer_size = LINE_BUF_SIZE;
int line_number = 0;
int scanf_return = 0;
// use select for input
while (1) {
if (scanf_return = scanf("%d", &line_number) != 1) {
while (fgetc(stdin) != '\n')
continue;
perror("Input error! Please enter only digits!\n");
continue;
}
if (line_number == 0) {
break;
}
if (line_number > lines_count || line_number < 0) {
perror("Wrong line number!\n");
continue;
}
line_number--;
lseek(file_desc, lines_shifts[line_number], SEEK_SET);
for (int i = 0; i < lines_lengths[line_number] / LINE_BUF_SIZE; i++) {
read(file_desc, line_buffer, LINE_BUF_SIZE);
write(STDOUT_FILENO, line_buffer, LINE_BUF_SIZE);
}
read(file_desc, line_buffer, lines_lengths[line_number] % LINE_BUF_SIZE);
write(STDOUT_FILENO, line_buffer, lines_lengths[line_number] % LINE_BUF_SIZE);
}
close(file_desc);
return 0;
}
| true |
b20bf84e840a224e89bd2cbc73392ecad0fa88cf | C++ | excalibur44/homework | /C++/week11/A.cpp | UTF-8 | 1,864 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
class base
{
public:
base(string one, char two, int three)
{
myname = one; leixing = two; dengji = three;
if(two == 'N')
{
blood = dengji*5;
shanghai = dengji*5;
fangyu = dengji*5;
}
else if(two == 'A')
{
blood = dengji*5;
shanghai = dengji*10;
fangyu = dengji*5;
}
else if(two == 'D')
{
blood = dengji*5;
shanghai = dengji*5;
fangyu = dengji*10;
}
else if(two == 'H')
{
blood = dengji*50;
shanghai = dengji*5;
fangyu = dengji*5;
}
}
void bianshen(char two);
void print()
{
cout << myname << "--"
<< leixing << "--"
<< dengji << "--"
<< blood << "--"
<< shanghai << "--"
<< fangyu << endl;
}
char getleixing(){ return leixing; }
private:
string myname;
int blood;
int shanghai;
int fangyu;
char leixing;
int dengji;
};
void base::bianshen(char two)
{
if(two == 'N')
{
leixing = two;
blood = dengji*5;
shanghai = dengji*5;
fangyu = dengji*5;
}
else if(two == 'A')
{
leixing = two;
blood = dengji*5;
shanghai = dengji*10;
fangyu = dengji*5;
}
else if(two == 'D')
{
leixing = two;
blood = dengji*5;
shanghai = dengji*5;
fangyu = dengji*10;
}
else if(two == 'H')
{
leixing = two;
blood = dengji*50;
shanghai = dengji*5;
fangyu = dengji*5;
}
}
bool trans(base *p, char leixing2)
{
if(p->getleixing() != leixing2)
{
p->bianshen(leixing2);
return true;
}
else
return false;
}
int main()
{
int t; cin >> t; int n = 0;
for(int i = 0; i < t; i++)
{
string myname; char leixing1, leixing2; int dengji;
std::cin >> myname >> leixing1 >> dengji >> leixing2;
base jiqiren(myname, leixing1, dengji);
bool b = trans(&jiqiren, leixing2);
if(b == true) n++;
jiqiren.print();
}
cout << "The number of robot transform is " << n << endl;
return 0;
}
| true |
646ff5ffe1dd4f30d74cb80d8f540d4bdc7dcc7c | C++ | dreamerconglin/2017-Spring-CPE-593 | /HW1b Compute binomials using memoization/HW1b/main.cpp | UTF-8 | 1,178 | 3.140625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <time.h>
using namespace std;
int ch(int n ,int r, vector <vector <int> > &value){
if(value[n][r] != -1){
return value[n][r]; // Use memoization
}
else{
value[n][r] = ch(n - 1 ,r , value) + ch(n - 1 ,r - 1, value); // Recursion
}
return value[n][r]; // Return the value
}
int cal_ch(int n, int r,vector <vector <int> > &val){
for(int i = 0; i <= r; i++){
val[0][i] = 1; // choose(0,i)=1
val[i][i] = 1; // choose(i,i)=1
}
for(int i = 0; i <= n; i++)
val[i][0] = 1; // choose(i,0)=1
return ch(n ,r , val);
}
int main(){
srand((int)time(NULL)); //利用时间函数time(),产生每次不同的随机数种子
int n[100000000],r[100000000],ans[100000000];
for(int i=0; i<100000000;i++){
n[i]=rand()%52+1;
r[i]=rand()%n[i]+1;//rand()%50用于产生0-49之间的随机数
}
vector <vector <int> > val(53,vector<int>(53,-1));
cal_ch(52,52,val);
for(int i=0; i<100000000;i++){
ans[i]=val[n[i]][r[i]];
}
return 0;
}
| true |
676a79119018500dafcf5e8f92b3bbf15026e20b | C++ | ajitesh22/Coding-Problems | /cousins-in-binary-tree.cpp | UTF-8 | 1,202 | 3.5625 | 4 | [] | no_license | //https://leetcode.com/problems/cousins-in-binary-tree/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode *xparent = NULL , *yparent = NULL;
int xdepth = -1 , ydepth = -2 ;
void solve(TreeNode* root , int x , int y , int currDepth , TreeNode* parent){
if(!root)return ;
if(root->val == x){
xparent = parent ;
xdepth = currDepth;
}
if(root->val == y){
yparent = parent;
ydepth = currDepth;
}
else{
solve(root->left , x , y , currDepth + 1, root);
solve(root->right , x , y , currDepth + 1 , root);
}
}
bool isCousins(TreeNode* root, int x, int y) {
solve(root , x ,y , 0, root);
return xparent!=yparent && xdepth == ydepth;
}
};
| true |
0271329ebe88d3e57894d920b4a9d4d2cdd6a1ea | C++ | adameat/arduflow | /Serial.h | UTF-8 | 4,211 | 2.71875 | 3 | [] | no_license | #pragma once
#include <HardwareSerial.h>
#include <SoftwareSerial.h>
namespace AW {
template <HardwareSerial& Port, long Baud>
class THardwareSerial {
public:
void Begin() {
Port.begin(Baud);
}
int AvailableForRead() const {
return Port.available();
}
int AvailableForWrite() const {
return Port.availableForWrite();
}
int Write(const char* buffer, int length) {
return Port.write(buffer, length);
}
int Read(char* buffer, int length) {
return Port.readBytes(buffer, length);
}
};
template <int RxPin, int TxPin, long Baud>
class TSoftwareSerial {
protected:
SoftwareSerial Port;
public:
TSoftwareSerial()
: Port(RxPin, TxPin)
{}
void Begin() {
Port.begin(Baud);
}
int AvailableForRead() const {
return const_cast<SoftwareSerial&>(Port).available();
}
int AvailableForWrite() const {
return 32;
}
int Write(const char* buffer, int length) {
return Port.write(buffer, length);
}
int Read(char* buffer, int length) {
return Port.readBytes(buffer, length);
}
};
struct TEventSerialData : TBasicEvent<TEventSerialData> {
constexpr static TEventID EventID = 2; // TODO
String Data;
TEventSerialData(String data)
: Data(data) {}
};
template <typename SerialType>
class TSerialActor : public TActor {
static constexpr unsigned int MaxBufferSize = 256;
public:
TSerialActor(TActor* owner)
: Owner(owner)
, EOL("\n")
{}
protected:
SerialType Port;
TActor* Owner;
String Buffer;
StringBuf EOL;
void OnEvent(TEventPtr event, const TActorContext& context) override {
switch (event->EventID) {
case TEventBootstrap::EventID:
return OnBootstrap(static_cast<TEventBootstrap*>(event.Release()), context);
case TEventSerialData::EventID:
return OnSerialData(static_cast<TEventSerialData*>(event.Release()), context);
case TEventReceive::EventID:
return OnReceive(static_cast<TEventReceive*>(event.Release()), context);
}
}
void OnBootstrap(TUniquePtr<TEventBootstrap>, const TActorContext& context) {
Port.Begin();
context.Send(this, this, new TEventReceive);
}
void OnSerialData(TUniquePtr<TEventSerialData> event, const TActorContext& context) {
int availableForWrite = Port.AvailableForWrite();
int len = event->Data.length();
int size = len > availableForWrite ? availableForWrite : len;
if (size > 0) {
Port.Write(event->Data.begin(), size);
if (size < len) {
event->Data.erase(0, size);
context.ResendImmediate(this, event.Release());
} else {
// TODO: could block
Port.Write(EOL.data(), EOL.size());
}
} else {
context.ResendImmediate(this, event.Release());
}
}
void OnReceive(TUniquePtr<TEventReceive> event, const TActorContext& context) {
auto size = min((unsigned int)Port.AvailableForRead(), MaxBufferSize - Buffer.size());
if (size > 0) {
//::Serial.println(size);
int strStart = 0;
auto bufferPos = Buffer.size();
Buffer.reserve(Buffer.size() + size);
size = Port.Read(Buffer.data() + Buffer.size(), size);
Buffer.resize(Buffer.size() + size);
while (bufferPos < Buffer.size()) {
if (Buffer[bufferPos] == '\n') {
int strSize = bufferPos;
while (strSize > 0 && Buffer[strSize - 1] == '\r') {
--strSize;
}
//::Serial.println(Buffer.substr(strStart, strSize - strStart).data());
context.Send(this, Owner, new TEventSerialData(Buffer.substr(strStart, strSize - strStart)));
strStart = bufferPos + 1;
}
++bufferPos;
}
Buffer = Buffer.substr(strStart, bufferPos - strStart);
}
context.Resend(this, event.Release());
}
};
}
| true |
0cad933b30b36c06717c7c28f6c58299099c8bff | C++ | andrewzhernov/concurrency | /BlockingQueue/solutions/solution.h | UTF-8 | 1,458 | 3.4375 | 3 | [] | no_license | #include <iostream>
#include <condition_variable>
#include <queue>
#include <mutex>
#include <stdexcept>
template <class T, class Container = std::deque<T>>
class BlockingQueue {
public:
explicit BlockingQueue(const size_t capacity)
: blocked_{false}
, capacity_{capacity} {
}
void Put(T&& item) {
if (blocked_) {
throw std::exception();
}
std::unique_lock<std::mutex> lock(mtx_);
if (data_queue_.size() == capacity_) {
write_cond_.wait(lock, [&] {
return data_queue_.size() < capacity_ || blocked_;
});
if (blocked_) {
throw std::exception();
}
}
data_queue_.push_back(std::move(item));
read_cond_.notify_one();
}
bool Get(T& result) {
if (blocked_) {
return false;
}
std::unique_lock<std::mutex> lock(mtx_);
if (data_queue_.empty()) {
read_cond_.wait(lock, [&] {
return !data_queue_.empty() || blocked_;
});
if (blocked_) {
return false;
}
}
result = std::move(data_queue_.front());
data_queue_.pop_front();
write_cond_.notify_one();
return true;
}
void Shutdown() {
std::lock_guard<std::mutex> lock(mtx_);
blocked_ = true;
read_cond_.notify_all();
write_cond_.notify_all();
}
private:
size_t capacity_;
bool blocked_;
std::mutex mtx_;
Container data_queue_;
std::condition_variable read_cond_;
std::condition_variable write_cond_;
};
| true |
10a0fb171402cf1fc0888edb4b5efb356cd567d7 | C++ | searleser97/DistribuitedSystems | /Proyectos/alan/worms/point.cpp | UTF-8 | 713 | 3.71875 | 4 | [] | no_license | #include "point.h"
#include <cmath>
Point::Point(): x(0), y(0) {}
Point::Point(double x, double y): x(x), y(y) {}
double Point::getX() {
return x;
}
double Point::getY() {
return y;
}
Point Point::operator+(const Point & p) const {
return Point(x + p.x, y + p.y);
}
Point Point::operator-(const Point & p) const {
return Point(x - p.x, y - p.y);
}
Point Point::operator*(const double & k) const {
return Point(x * k, y * k);
}
Point Point::operator/(const double & k) const {
return Point(x / k, y / k);
}
double Point::length() const {
return sqrt(x*x + y*y);
}
Point Point::rotate(const double & theta) const {
return Point(x * cos(theta) - y * sin(theta), x * sin(theta) + y * cos(theta));
}
| true |
a7881162978d8609b0a1664da6fec64bb808b5c1 | C++ | Vidyadhar-Mudkavi/gitApplications | /Calendar/zzBak/CalendarTemplates/calRataDie.h | UTF-8 | 3,299 | 2.59375 | 3 | [
"MIT"
] | permissive | #ifndef _CALRATADIE_
#define _CALRATADIE_
/**
*File: calRataDie.h
*Description:
this file declares class calRataDie
*Version: 1.2 "@(#) calRataDie. header. ver. 1.2. Premalatha, Vidyadhar Mudkavi, CTFD, NAL."
*Dependencies:
*Authors: Premalatha, Vidyadhar Mudkavi, CTFD, NAL.
*Date:
*/
// system includes
#include <iostream>
// standard template
// local includes
#include "calFn.h"
#include "calBase.h"
#include "calNames.h"
// function prototypes
// forward declarations
template <typename T>
class tCalGregorian;
template <typename T>
class tCalJulianDayNumber;
template <typename T>
class tCalJulian;
template <typename T>
class tCalIso;
template <typename T>
class tCalOldHinduSolar;
template <typename T>
class tCalOldHinduLunar;
// begin class declaration
template <typename T>
class tCalRataDie : public tCalBase<T>
{
friend class tCalFn<T>;
friend class tCalGregorian<T>;
friend inline std::ostream& operator<<(std::ostream& os, const tCalRataDie<T>& rd);
public:
// constructors
tCalRataDie(); // default
tCalRataDie(long int date);
tCalRataDie(const tCalRataDie& rata_die);
// assignment operator
tCalRataDie& operator=(const tCalRataDie& rata_die);
inline tCalRataDie& operator=(long int fixed_date);
// destructor
~tCalRataDie();
// other functionality
tCalGregorian<T> Gregorian() const;
tCalJulian<T> Julian() const;
tCalIso<T> Iso() const;
tCalOldHinduSolar<T> OldHinduSolar() const;
tCalOldHinduLunar<T> OldHinduLunar() const;
tCalJulianDayNumber<T> JulianDayNumber() const;
long int GregorianYear() const;
inline std::string DayOfWeek() const;
inline tCalRataDie<T> operator-(long int decrement) const;
protected:
long int operator()() const { return pv_date; }
private:
long int pv_date;
static calGregorianWeekDay pv_weekDay;
// static char* pv_weekDay[7];
};
// include any inline code here
template <typename T>
inline std::string tCalRataDie<T>::DayOfWeek() const
{
long int lindex = tCalFn<T>::Mod(pv_date, 7);
int index = static_cast<int>( tCalFn<T>::Mod(pv_date, 7) );
return pv_weekDay[ index ];
}
template <typename T>
inline tCalRataDie<T>& tCalRataDie<T>::operator=(long int fixed_date)
{
pv_date = fixed_date; return *this;
}
template <typename T>
inline tCalRataDie<T> tCalRataDie<T>::operator-(long int decrement) const
{
return tCalRataDie(pv_date-decrement);
}
template <typename T>
inline std::ostream& operator<<(std::ostream& os, const tCalRataDie<T>& rd)
{
os << rd.pv_date; return os;
}
#include "calRataDie.cpp"
/**
declare any typedef statements here (e.g.: typedef aVortex areVortices;)
*/
// here are the alternate names
// typedef template <typename T> tCalRataDie<T> tCalFixed<T>;
// template <typename T> typedef tCalRataDie tCalRD<T>;
//
// \\^//
// o(!_!)o
// __m__ o __m__
//
#endif // _CALRATADIE_
| true |
68b8df636cbe61eaca270c7ad645534c4b98d197 | C++ | Shawan-Das/C-_Code | /DoubleLinkList.cpp | UTF-8 | 2,467 | 3.53125 | 4 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
///Double Link List
///Create Node
struct Node
{
int data;
Node* next; Node* previous;
};
Node* head=NULL; Node* indicator=NULL;
///Node Insertion
void insertFirst(int value){
Node* singleNode = new Node;
singleNode->data = value;
singleNode->next = NULL;
singleNode->previous = NULL;
if(head != NULL){
singleNode->next= head;
head->previous=singleNode;
} head = singleNode;
}
void insertLast(int value){
Node* singleNode = new Node;
singleNode->data = value;
singleNode->next = NULL;
singleNode->previous = NULL;
Node* temp = head;
while(temp->next!=NULL) temp = temp->next;
singleNode->previous = temp;
temp->next = singleNode;
}
void insertMid(int position, int value){
Node* singleNode = new Node;
Node* temp =head;
for(int i=1; i<position-1;i++) temp=temp->next;
indicator = temp->next;
singleNode->data = value;
singleNode->next = indicator;
singleNode->previous = temp;
temp->next = singleNode;
indicator->previous= singleNode;
}
///Delete Node
void deleteFirst(){
head = head->next;
head->previous=NULL;
}
void deleteLast(){
Node* temp = head; int position =1;
while(temp->next->next!=NULL){
temp = temp->next;
position++;}
//temp->previous=temp;
temp->next=NULL;
}
void deleteMid(int position){
Node* temp =head;
for(int i=1;i<position-1;i++) temp = temp->next;
indicator=(temp->next)->next;
temp->next= indicator;
indicator->previous=temp;
}
/// Print Node
void printList(){
Node* temp = head;
while(temp != NULL){
printf("%d ",temp->data);
temp = temp->next;
} printf("\n");
}
/// Print in Reverse
void printListReverse(){
Node* temp = head;
while(temp->next != NULL)
temp = temp->next;
while(temp != NULL){
printf("%d ",temp->data);
temp = temp->previous;
}
printf("\n");
}
int main()
{
insertFirst(10);
insertLast(20);
insertLast(30);
insertLast(40);
printList();
insertMid(3,25);
insertMid(5,35);
printList();
deleteFirst();
printList();
deleteMid(4);
printList();
//deleteLast();
//printList();
// deleteLast();
printListReverse();
return 0;
}
| true |
3b6c670c18da05698fed3099170ccd3e73ecd49a | C++ | arvind-murty/CS135 | /assignment4/Murty_Arvind_DA04__s3.cpp | UTF-8 | 4,541 | 3.21875 | 3 | [] | no_license | // Header Files
#include "formatted_cmdline_io_v11.h"
#include <cmath>
using namespace std;
// Global Constant Definitions
// Global Function Prototypes
// Prints the title
// Inputs: none
// Outputs: none
void printTitle();
// Gets a coordinate
// Inputs: lowerCoor, higherCoor
// Outputs: coordinate
double getCoordinate(lowerCoor, higherCoor);
// Prints a divider line
// Inputs: none
// Outputs: none
void printDividerLine();
// Prints the top of the information table
// Inputs: none
// Outputs: none
void printTableTop();
// Prints one line of data
// Inputs: testNum, x1, y1, x2, y2, midpoint_x, midpoint_y, distance, slope
// Outputs: none
void printOneDataLine(int testNum, double x1, double y1, double x2, double y2, double midpoint_x, double midpoint_y, double distance, double slope);
// Calculates distance between two points
// Inputs: x1, y1, x2, y2
// Outputs: distance
double calcDistance(double x1, double y1, double x2, double y2);
// Calculates the midpoint of two coordinates
// Inputs: coor1, coor2
// Ouputs: midpointCoor
double calcMidpoint(double coor1, double coor2);
// Calculates the slope of a line using two points
// Inputs: x1, y1, x2, y2
// Outputs: slope
double calcSlope(double x1, double y1, double x2, double y2);
// Main Program Defintion
int main()
{
// initialize program
// initialize variables
// show title, with underline
// function: printTitle
// output a divider space
// function: printEndLines
// print divider line
// function: printDividerLine
// output a divider space
// function: printEndLines
// input Data
// get first data set
// acquire first test number from user
// function: promptForInt
// output a divider space
// function: printEndLines
// get first point from user
// acquire x value
// function: getCoordinate
// acquire y value
// function: getCoordinate
// output a divider space
// function: printEndLines
// get second point from user
// acquire x value
// function: getCoordinate
// acquire y value
// function: getCoordinate
// output a divider space
// function: printEndLines
// print divider line
// function: printDividerLine
// output a divider space
// function: printEndLines
// get second data set
// acquire second test number from user
// function: promptForInt
// output a divider space
// function: printEndLines
// get first point from user
// acquire x value
// function: getCoordinate
// acquire y value
// function: getCoordinate
// output a divider space
// function: printEndLines
// get second point from user
// acquire x value
// function: getCoordinate
// acquire y value
// function: getCoordinate
// output a divider space
// function: printEndLines
// calculate midpoints
// calculate midpoint one
// function: calcMidCoor
// function: calcMidCoor
// calculate midpoint two
// function: calcMidCoor
// function: calcMidCoor
// calculate distances
// calculate distance one
// function: calcDistance
// calculate distance two
// function: calcDistance
// calculate slopes
// calculate slope one
// function: calcSlope
// calculate slope two
// function: calcSlope
// output Data
// print table top
// function: printTableTop
// print first data set
// print first line of data
// function: printOneDataLine
// print second data set
// print second line of data
// function: printOneDataLine
// end program
// return zero
return 0;
}
// Supporting function implementations
| true |
a0f92670a705a817d4210228f6c806d33c432877 | C++ | jjpulidos/Competitive-Programming | /UVa/Competitive Programming 3/Introduction/Getting Started The Easy Problems/Medium/10424 - Love Calculator/main.cpp | UTF-8 | 1,030 | 3.03125 | 3 | [] | no_license | /**
* 10424 - Love Calculator
* Created by Juan Pulido on 6/07/2018
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int INF = (int)1e9;
int sumita(string str) {
int sum = 0, i = 0;
for(i = 0; i < str.size(); i++) {
char ch = str[i];
if((ch>64 &&ch<91)||(ch>96&&ch<123)){
ch =tolower(ch);
sum += ch - 'a' + 1;
}
}
return sum;
}
int numeroListo(int num){
if(num<10) return num;
return (numeroListo(int(floor(num/10)) + num%10));
}
int main() {
string p1;
while(getline(cin,p1)){
string p2;
getline(cin,p2);
double numerito1 = numeroListo(sumita(p1));
double numerito2 = numeroListo(sumita(p2));
if (numerito2/numerito1*100<=100){
printf("%0.2f %%\n",numerito2/numerito1*100);
}else if(numerito1/numerito2*100<=100){
printf("%0.2f %%\n",numerito1/numerito2*100);
}else{
printf("%0.2f %%\n",100.0);
}
}
return 0;
} | true |
cfe3d6ddf4b1134567b8dca1c73b3217c9d8edf7 | C++ | Noobaseem/Competitive-Programing | /spoj_problems/21_absys.cpp | UTF-8 | 1,482 | 2.6875 | 3 | [] | no_license | /*
* @author: Aseem Rastogi
* alumini: National Institute of Technology, Hamirpur
* Batch of 2014
* mail_id: aseem.rastogi1992@gmail.com
*/
#include <iostream>
#include <vector>
#include <queue>
#include <cctype>
#include <cstring>
#include <iomanip>
#include <cstdio>
#include <algorithm>
using namespace std;
/*My utility functions*/
#define pb push_back
#define pf push_front
#define sz size
/*My personalised flavour of some c++ constructs*/
#define for0(i, n) for(int i = 0; i < n; i++)
#define fora(i, a, n) for(int i = a; i < n; i++)
/*Some important programing terms*/
#define MOD 1000000007
using namespace std;
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
int stringtoint(string& s)
{
int ten=1;
int b=0;
int i;
for(i=s.size()-1;i>=0;i--)
{
b += (s[i]-'0')*ten;
ten=ten*10;
}
return b;
}
bool ifnumber(string& s)
{
bool check = true;
for(int i = 0; i < (int)s.size(); i++)
if(s[i]<'0' || s[i]>'9')
return false;
return true;
}
int main()
{
int n1,n2,n3,t;
string s1,s2,s3;
cin>>t;
char ch;
while(t--){
cin>>s1>>ch>>s2>>ch>>s3;
if(ifnumber(s1) == false){
n2=stringtoint(s2);
n3=stringtoint(s3);
n1=n3-n2;
cout<<n1<<" + "<<n2<<" = "<<n3<<endl;
}else if (ifnumber(s2)==false){
n1=stringtoint(s1);
n3=stringtoint(s3);
n2=n3-n1;
cout<<n1<<" + "<<n2<<" = "<<n3<<endl;
}else{
n1=stringtoint(s1);
n2=stringtoint(s2);
n3=n1+n2;
cout<<n1<<" + "<<n2<<" = "<<n3<<endl;
}
}
return 0;
}
| true |
0bd10e485f17a0a66fda2150a3b4ad66e5db12b2 | C++ | El-Duder1no/geometry | /src/structFill.cpp | UTF-8 | 740 | 3.046875 | 3 | [] | no_license | #include "structFill.h"
bool structFill(Circle& a, std::string text)
{
std::string x, y, r, figure;
float xF, yF, rF;
const char* temp;
enter(text, figure, x, y, r);
if (figure != "circle") {
return false;
}
temp = x.c_str();
if (isdigit(temp[0]) || temp[0] == '-') {
xF = stof(x);
a.x = xF;
} else {
return false;
}
temp = y.c_str();
if (isdigit(temp[0]) || temp[0] == '-') {
yF = stof(y);
a.y = yF;
} else {
return false;
}
temp = r.c_str();
if (isdigit(temp[0])) {
rF = stof(r);
if (rF < 0)
return false;
a.r = rF;
} else {
return false;
}
return true;
} | true |
0828a88aa19e3f92908aa8df1666a2f3d65c45ad | C++ | lukeomalley/cpp-algorithms | /src/TwoSumSorted.cpp | UTF-8 | 1,203 | 3.921875 | 4 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
/**
* Given a 1-indexed array of integers numbers that is already sorted in
* non-decreasing order, find two numbers such that they add up to a specific
* target number. Let these two numbers be numbers[index1] and numbers[index2]
* where 1 <= index1 < index2 <= numbers.length.
*
* Return the indices of the two numbers, index1 and index2, added by one as an
* integer array [index1, index2] of length 2.
*
* The tests are generated such that there is exactly one solution. You may not
* use the same element twice.
*
* Your solution must use only constant extra space.
*/
class Solution {
public:
vector<int> twoSum(vector<int> nums, int target) {
int lp = 0;
int rp = nums.size() - 1;
while (lp < rp) {
int sum = nums[lp] + nums[rp];
if (sum == target) {
break;
}
if (sum > target) {
rp--;
} else {
lp++;
}
}
return {lp + 1, rp + 1};
}
};
int main() {
Solution sol;
vector<int> nums = {1, 3, 4, 5, 7, 10, 11};
vector<int> result = sol.twoSum(nums, 9);
std::cout << "Result: " << result[0] << ", " << result[1] << std::endl;
} | true |
58f14db34077ef002c863236a479888b946fcbc4 | C++ | lcls-daq/pdsapp | /config/Table.hh | UTF-8 | 2,131 | 2.765625 | 3 | [] | no_license | #ifndef Pds_ConfigDb_Table_hh
#define Pds_ConfigDb_Table_hh
#include <list>
using std::list;
#include <string>
using std::string;
#include <iostream>
using std::istream;
namespace Pds_ConfigDb {
class FileEntry {
public:
FileEntry();
FileEntry(istream&); // load from a file
FileEntry(const string& name, const string& entry);
public:
string name () const;
const string& entry() const { return _entry; }
public:
bool operator==(const FileEntry&) const;
bool operator< (const FileEntry&) const;
void read(istream&);
private:
string _name;
string _entry;
};
class TableEntry {
public:
TableEntry();
TableEntry(const string& name);
TableEntry(const string& name, const string& key,
const FileEntry& entry);
TableEntry(const string& name, const string& key,
const list<FileEntry>& entries);
public:
const string& name() const { return _name; }
const string& key () const { return _key; }
const list<FileEntry>& entries() const { return _entries; }
bool operator==(const TableEntry&) const;
public:
void set_entry(const FileEntry& entry);
void remove (const FileEntry& entry);
public:
void update (unsigned);
bool updated () const;
private:
string _name;
string _key;
list<FileEntry> _entries;
mutable bool _changed;
};
class Table {
public:
Table();
public:
const std::list<TableEntry>& entries() const { return _entries; }
std::list<TableEntry>& entries() { return _entries; }
std::list<string> get_top_names() const;
const TableEntry* get_top_entry(const string&) const;
// void write(const string&) const;
void set_top_entry(const TableEntry&);
void new_top_entry(const string&);
void remove_top_entry(const TableEntry&);
void copy_top_entry(const string&,const string&);
void set_entry(const string&, const FileEntry&);
void clear_entry(const string&, const FileEntry&);
void dump(const string&) const;
private:
list<TableEntry> _entries;
public:
unsigned _next_key;
};
};
#endif
| true |
021b74e932b1ebafaa5e5f3e05a27d109ec05deb | C++ | cfriedt/leetcode | /zigzag-conversion-test.cpp | UTF-8 | 1,238 | 2.859375 | 3 | [
"MIT"
] | permissive | /*
* Copyright (c) 2018 Christopher Friedt
*
* SPDX-License-Identifier: MIT
*/
#include <array>
using namespace std;
#include <gtest/gtest.h>
#include "zigzag-conversion.cpp"
TEST(ZigZagConversion, Test__PAYPALISHIRING__3) {
// string convert(string s, int numRows)
int numRows = 3;
string s("PAYPALISHIRING");
string expected_string("PAHNAPLSIIGYIR");
string actual_string = Solution().convert(s, numRows);
EXPECT_EQ(actual_string, expected_string);
}
TEST(ZigZagConversion, Test__A__3) {
// string convert(string s, int numRows)
int numRows = 3;
string s("A");
string expected_string("A");
string actual_string = Solution().convert(s, numRows);
EXPECT_EQ(actual_string, expected_string);
}
TEST(ZigZagConversion, Test__AB__4) {
// string convert(string s, int numRows)
int numRows = 4;
string s("AB");
string expected_string("AB");
string actual_string = Solution().convert(s, numRows);
EXPECT_EQ(actual_string, expected_string);
}
TEST(ZigZagConversion, Test__ABAB__2) {
// string convert(string s, int numRows)
int numRows = 2;
string s("ABAB");
string expected_string("AABB");
string actual_string = Solution().convert(s, numRows);
EXPECT_EQ(actual_string, expected_string);
}
| true |
ba93413394e4df407c2187b45d4506739dd0634e | C++ | mei-rune/jingxian-project | /jingxian-network/src/jingxian/exception.h | GB18030 | 9,946 | 2.59375 | 3 | [] | no_license |
#ifndef _MY_Exception_H_
#define _MY_Exception_H_
#include "jingxian/config.h"
#if !defined (JINGXIAN_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* JINGXIAN_LACKS_PRAGMA_ONCE */
// Include files
#include <stdexcept>
#include "jingxian/string/os_string.h"
#include "jingxian/lastError.h"
#include "jingxian/utilities/StackTracer.h"
_jingxian_begin
#ifndef _RAISE
#define _RAISE(x) throw (x)
#endif
class Exception : public std::runtime_error
{
public:
virtual ~Exception() throw()
{
}
const char* getFile() const
{
if (!fSrcFile)
return "";
return fSrcFile;
}
size_t getLine() const
{
return fSrcLine;
}
void setPosition(const char* const file
, size_t line)
{
fSrcFile = file;
fSrcLine = line;
}
Exception()
: std::runtime_error("<δ֪쳣>")
, fSrcFile(0)
, fSrcLine(0)
{
initStackTrace(3);
}
Exception(const tstring& message)
: std::runtime_error(toNarrowString(message))
, fSrcFile(0)
, fSrcLine(0)
{
initStackTrace(3);
}
Exception(const char* const srcFile
, size_t srcLine
, const tstring& message)
: std::runtime_error(toNarrowString(message))
, fSrcFile(srcFile)
, fSrcLine(srcLine)
{
initStackTrace(3);
}
Exception(const char* const srcFile
, size_t srcLine
, const tstring& message
, const Exception& e)
: std::runtime_error(toNarrowString(message) + "," + e.what())
, fSrcFile(srcFile)
, fSrcLine(srcLine)
{
initStackTrace(3);
}
template< typename E >
void Raise(E& e)
{
throw e;
}
void dump(tostream& target) const
{
target << _T("[ file:")
<< toTstring(getFile())
<< _T(" line:")
<< (int) getLine()
<< _T(" ] ")
<< std::endl
<< _stack;
}
virtual Exception* clone()
{
return new Exception(*this);
}
virtual void rethrow()
{
Raise(*this);
}
virtual void print(tostream& target) const
{
target << _T("Exception: ")
<< what();
dump(target);
}
#if !_HAS_EXCEPTIONS
protected:
virtual void _Doraise() const
{ // perform class-specific exception handling
_RAISE(*this);
}
#endif /* _HAS_EXCEPTIONS */
protected :
Exception(const Exception& ex)
: std::runtime_error(ex)
, fSrcFile(ex.fSrcFile)
, fSrcLine(ex.fSrcLine)
, _stack(ex._stack)
{
}
void initStackTrace(int skipFrames)
{
StackTracer stackWalker(StackTracer::RetrieveLine);
stackWalker.ShowCallstack(skipFrames);
_stack = toTstring(stackWalker.GetCallStack());
}
const char* fSrcFile;
size_t fSrcLine;
tstring _stack;
};
inline tostream& operator<<(tostream& target, const Exception& err)
{
err.print(target);
return target;
}
#define MakeException(theType , msg ) \
class theType : public Exception \
{ \
public: \
\
theType(const char* const srcFile \
, size_t srcLine \
, const tstring & m \
, const Exception& e \
) : \
Exception(srcFile, srcLine, msg + m ,e ) \
{ \
\
} \
theType(const char* const srcFile \
, size_t srcLine \
, const tstring & m \
) : \
Exception(srcFile, srcLine, msg + m ) \
{ \
\
} \
theType(const char* const srcFile \
, size_t srcLine \
) : \
Exception(srcFile, srcLine, msg ) \
{ \
\
} \
theType( ) : \
Exception( msg ) \
{ \
\
} \
theType( const tstring & m ) : \
Exception( msg + m ) \
{ \
\
} \
\
virtual ~theType() throw() {} \
virtual Exception* clone() \
{ \
return new theType( *this ); \
} \
virtual void rethrow() \
{ \
Raise( *this ); \
} \
virtual void print(tostream& target) const \
{ \
target << MAKE_STRING( theType ) \
<< what(); \
dump( target ); \
} \
};
//
#define IllegalArgumentError _T("Ч")
#define ArgumentNullError _T("Ϊ")
#define RuntimeError _T("ʱ")
#define OutOfRangeError _T("Χ")
#define LockError _T("")
#define CtrlCHandlerError _T("Ctrl+C")
#define NetError _T("")
#define InvalidPointerError _T("Чָ")
#define LengthError _T("Ч")
#define EOFError _T("Ѿβ")
#define PluginError _T("")
#define URLError _T("URL")
#define CastError _T("תʧ")
#define NullError _T("ָ")
#define NotFindError _T("ûҵ")
#define _ExistError _T("Ѿ")
#define SystemError _T("ϵͳ")
#define TimeSyntaxError _T("ʱʽ")
#define NotImplementedError _T("ûʵ")
//
#define ERR_BAD_BUF -2
#define ERR_BAD_BUF_LEN -1
#define ERR_SYS -200 //
#define ERR_ARG -201
#define ERR_LEN -202
#define ERR_POINT -203
#define ERR_UNKOWN -204
#define ERR_MAXMSGLEN -205
#define ERR_HEADERLENGTH -206
#define ERR_HEADERTYPE -207
#define ERR_MEMORY -208
#define ERR_PARAMETER -400
#define ERR_OBJECT_NOEXIST -501 //
#define ERR_INTERNAL -502 // ڲ
#define ERR_UNKNOWN_COMMAND -503 // ʶ
#define ERR_AUTH -504 // ûȨ
#define ERR_TYPE -505 // ʹһĿ¼
#define ERR_SEEKFILE -506 // ƶļλó
#define ERR_READFILE -507 // ƶļλó
#define ERR_LENGTH -508 // ڴ̫С
// 쳣
MakeException(NullException , NullError);
MakeException(RuntimeException , RuntimeError);
MakeException(IllegalArgumentException, IllegalArgumentError);
MakeException(ArgumentNullException, ArgumentNullError);
MakeException(OutOfRangeException, OutOfRangeError);
MakeException(InvalidPointerException, InvalidPointerError);
MakeException(LengthException, LengthError);
MakeException(CastException, CastError);
MakeException(EOFException , EOFError);
MakeException(URLException, URLError);
MakeException(NotFindException, NotFindError);
MakeException(SystemException, SystemError);
MakeException(LockException , LockError);
MakeException(TimeSyntaxException , TimeSyntaxError);
MakeException(NotImplementedException, NotImplementedError);
// 쳣
#define ThrowException( type ) throw type(__FILE__, __LINE__ )
#define ThrowException1( type ,m1 ) throw type(__FILE__, __LINE__ , m1 )
#define ThrowException2( type ,m1 ,m2 ) throw type(__FILE__, __LINE__ , m1, m2 )
#define ThrowException3( type ,m1 ,m2 ,m3 ) throw type(__FILE__, __LINE__ , m1, m2, m3 )
#define ThrowException4( type ,m1 ,m2 ,m3 ,m4) throw type(__FILE__, __LINE__ , m1, m2, m3, m4)
_jingxian_end
#endif //_MY_Exception_H_
| true |
4d75bce23ff9cd71e29a95737909f0b229b0447c | C++ | kevinqi34/HackerRank | /Algorithms/Strings/Palindrome_Index.cpp | UTF-8 | 1,329 | 3.640625 | 4 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
// Checks if a string is a palindrome
bool palindrome(string s) {
bool checker = true;
int length = s.size() / 2;
for (int i = 0; i < length; i++) {
if (s[i] != s[s.size() - 1 - i]) {
checker = false;
break;
}
}
return checker;
}
int palindromeIndex(string s){
if (palindrome(s)) {
// Already Palindrome
return -1;
} else {
int index = 0;
// Check starting from the ends
int left_index = 0;
int right_index = s.size() - 1;
while (left_index < right_index) {
if (s[right_index] != s[left_index]) {
int mid = right_index - left_index;
string check = s.substr(left_index, mid);
if (palindrome(check)) {
index = right_index;
} else {
index = left_index;
}
break;
}
// Increment
left_index++;
right_index--;
} // While
return index;
}
}
int main() {
int q;
cin >> q;
for(int a0 = 0; a0 < q; a0++){
string s;
cin >> s;
int result = palindromeIndex(s);
cout << result << endl;
}
return 0;
}
| true |
549716e06dc35df6392cd90a364df14c7ddd723f | C++ | MilovanTomasevic/cpp-tutorial | /src/04_exercises__task_15/Zadatak15Cas4/Vreme.hpp | UTF-8 | 1,643 | 3.03125 | 3 | [
"MIT"
] | permissive | //
// Vreme.hpp
// Zadatak15Cas4
//
// Created by Milovan Tomasevic on 18/03/2017.
// Copyright © 2017 Milovan Tomasevic. All rights reserved.
//
#ifndef ZAGLAVLJE_HPP_INCLUDED
#define ZAGLAVLJE_HPP_INCLUDED
#include <iostream>
#include <cmath>
using namespace std;
class Vreme{
private:
int sekunde;
public:
// prazan konstruktor
Vreme();
//konstruktor sa parametirma: sekunde
Vreme(int);
//konstruktor sa parametrima: sekunde, minuti
Vreme(int, int);
//konstruktor sa parametrima: sekunde, minuti, Vremei
Vreme(int, int, int);
// konstruktor kopije
Vreme(const Vreme&);
//dodela kao konstruktor kopije a vraca to sto mu se da
Vreme& operator=(const Vreme&);
Vreme& operator+=(const Vreme&);
Vreme& operator-=(const Vreme&);
// ima pravo pristupa private poljima klase koja je friend (nije clanica klase) pogledati cpp ne pristupa sa Vreme::
friend Vreme operator+(const Vreme&, const Vreme&);
friend Vreme operator-(const Vreme&, const Vreme&);
const Vreme& operator++();
const Vreme operator++(int);
const Vreme& operator--();
const Vreme operator--(int);
friend bool operator==(const Vreme&, const Vreme&);
friend bool operator!=(const Vreme&, const Vreme&);
friend bool operator<(const Vreme&, const Vreme&);
friend bool operator<=(const Vreme&, const Vreme&);
friend bool operator>(const Vreme&, const Vreme&);
friend bool operator>=(const Vreme&, const Vreme&);
friend ostream& operator<<(ostream&, const Vreme&);
friend istream& operator>>(istream&, Vreme&);
};
#endif // ZAGLAVLJE_HPP_INCLUDED
| true |
c92e1493ee445add0b8eacd0581b5e5bf5431e34 | C++ | YangKai-NEU/algorithms | /TheLastRemainingNumberInTheCircle.cpp | UTF-8 | 534 | 3.15625 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int LastRemaining_Solution(int n, int m)
{
vector<int> s;
if(n==0){
return -1;
}
for(int i=0;i<n;i++){
s.push_back(i);
}
int pos=0;
while(s.size()!=1){
pos+=(m-1);
pos%=s.size();
s.erase(s.begin()+pos);
}
return s[0];
}
};
int main(int argc, char *argv[])
{
Solution solution;
cout<<solution.LastRemaining_Solution(5,3)<<endl;
return 0;
}
| true |
2ce9f535c30eb8b6fc28bf97df9fad46ffb379c8 | C++ | hollyhudson/furbies | /brain/brain.ino | UTF-8 | 4,486 | 2.78125 | 3 | [] | no_license | /*
Furby Brain
*/
#define SOUND_IN 21
#define TILT 20
#define UPSIDE_DN 19
#define MOTOR_FOR 18 // 4 // PWM
#define MOTOR_REV 17 // 5 // PWM
#define XCAM_HOME 0
#define GEAR_ROT 1
#define XBACK 2
#define TUMMY 3
int desired_position = 0;
int position;
long last_millis;
// EARS
int ears[] = {
0,
50,
22,
12,
84,
90,
45,
};
const int num_ears = sizeof(ears) / sizeof(*ears);
void ears_function()
{
for (int i = 0; i < num_ears; i++){
long start_time = millis();
desired_position = ears[i];
while (millis() - start_time < 150)
{
updateMotor();
if (position == desired_position) break;
}
}
}
// EYES
int eyes[] = {
120,
15,
22,
3,
};
const int num_eyes = sizeof(eyes) / sizeof(*eyes);
void eyes_function()
{
for (int i = 0; i < num_eyes; i++){
long start_time = millis();
desired_position = eyes[i];
while (millis() - start_time < 150)
{
updateMotor();
if (position == desired_position) break;
}
}
}
// NOSE
int nose[] = {
36,
39,
20,
2,
150,
132,
93,
68,
77,
};
const int num_nose = sizeof(nose) / sizeof(*nose);
void nose_function()
{
for (int i = 0; i < num_nose; i++){
long start_time = millis();
desired_position = nose[i];
while (millis() - start_time < 150)
{
updateMotor();
if (position == desired_position) break;
}
}
}
// TOES
int toes[] = {
72,
43,
80,
61,
};
const int num_toes = sizeof(toes) / sizeof(*toes);
void toes_function()
{
Serial.println("toes");
for (int i = 0; i < num_toes; i++){
long start_time = millis();
desired_position = toes[i];
while (millis() - start_time < 150)
{
updateMotor();
if (position == desired_position) break;
}
}
}
void motor(int dir)
{
if(dir == 0)
{
digitalWrite(MOTOR_REV, LOW);
digitalWrite(MOTOR_FOR, LOW);
} else
if (dir > 0)
{
digitalWrite(MOTOR_REV, LOW);
digitalWrite(MOTOR_FOR, HIGH);
//analogWrite(MOTOR_FOR, dir);
} else {
digitalWrite(MOTOR_FOR, LOW);
digitalWrite(MOTOR_REV, HIGH);
//analogWrite(MOTOR_REV, dir);
}
}
void setup() {
pinMode( MOTOR_FOR, OUTPUT );
pinMode( MOTOR_REV, OUTPUT );
pinMode( SOUND_IN, INPUT );
pinMode( TILT, INPUT_PULLUP );
pinMode( UPSIDE_DN, INPUT_PULLUP );
pinMode( GEAR_ROT, INPUT_PULLUP );
pinMode( TUMMY, INPUT_PULLUP );
pinMode( XCAM_HOME, INPUT_PULLUP );
pinMode( XBACK, INPUT_PULLUP );
// find the home position
Serial.println("Finding home in setup");
const long start_time = millis();
motor(+150);
while(digitalRead(XCAM_HOME))
{
if (millis() - start_time > 5000)
break;
}
motor(0);
position = 0;
delay(5000);
}
int last_position_max;
bool last_rotation;
bool last_home_sensor;
int step = 0;
int positions[] = {
10,
20,
30,
40,
50,
60,
70,
80,
90,
100,
110,
120,
130,
50,
10,
50,
90,
130,
90,
50,
};
void loop()
{
// The fastest it can run is 80, faster is just small twitches
if (random(20000) == 0) {
int choice = random(4);
Serial.print("random what ");
Serial.println(choice);
switch(choice){
case 0: ears_function(); break;
case 1: eyes_function(); break;
case 2: nose_function(); break;
case 3: toes_function(); break;
default:
break;
}
// go back to home
Serial.println("Finding home");
const long start_time = millis();
motor(+150);
while(digitalRead(XCAM_HOME))
{
if (millis() - start_time > 5000)
break;
}
motor(0);
position = 0;
}
}
void updateMotor()
{
//int sounds = analogRead(SOUND_IN); // returns int (0 to 1023)
//Serial.println(sounds - 960);
bool home_sensor = digitalRead(XCAM_HOME) == LOW;
bool rotation_step = digitalRead(GEAR_ROT) == LOW;
int rotation_delta = 0;
if (rotation_step)
{
// if the last read of the sensor was low,
// then this is a real step.
if (!last_rotation)
rotation_delta = 1;
}
last_rotation = rotation_step;
if (home_sensor)
{
if (!last_home_sensor)
{
last_position_max = position;
position = 0;
}
}
last_home_sensor = home_sensor;
Serial.print(rotation_step); Serial.print(' ');
Serial.print(home_sensor); Serial.print(' ');
if (desired_position == position) {
motor(0);
}
int delta = desired_position - position;
if (desired_position > position) {
motor(+150);
position += rotation_delta;
}
if (desired_position < position) {
motor(-150);
position -= rotation_delta;
}
Serial.print(position); Serial.print(' ');
Serial.print(last_position_max); Serial.print(' ');
Serial.println();
}
| true |
4b723f3b6c457c1f742eb229c544d51922b6f3ee | C++ | franco-ruggeri/polito-system-programming-api | /lab3/ReducerInput.h | UTF-8 | 3,244 | 2.953125 | 3 | [] | no_license | //
// Created by fruggeri on 7/2/20.
//
#pragma once
#include <vector>
#include <memory>
#include "Serializable.h"
template<typename K, typename V, typename A>
class ReducerInput: public Serializable<ReducerInput<K,V,A>> {
K key;
V value;
A acc;
public:
ReducerInput() {}
ReducerInput(K key, V value, A acc): key(key), value(value), acc(acc) {}
K getKey() const { return key; }
V getValue() const { return value; }
A getAcc() const { return acc; }
pt::ptree buildPTree() const {
pt::ptree pt;
pt.put("key", key);
pt.put("value", value);
pt.put("acc", acc);
return pt;
}
void loadPTree(const pt::ptree& pt) {
key = pt.get<K>("key");
value = pt.get<V>("value");
acc = pt.get<A>("acc");
}
std::vector<char> serializeBinary() const {
std::vector<char> tmp, serialized_obj;
std::size_t total_size = 3*sizeof(std::size_t) + key.size() + sizeof(value) + sizeof(acc);
serialized_obj = serialize_binary_size(total_size); // total size
tmp = serialize_binary_attribute(key); // key
std::copy(std::move_iterator(tmp.begin()), std::move_iterator(tmp.end()), std::back_inserter(serialized_obj));
tmp = serialize_binary_attribute(value); // value
std::copy(std::move_iterator(tmp.begin()), std::move_iterator(tmp.end()), std::back_inserter(serialized_obj));
tmp = serialize_binary_attribute(acc); // acc
std::copy(std::move_iterator(tmp.begin()), std::move_iterator(tmp.end()), std::back_inserter(serialized_obj));
return serialized_obj;
}
void deserializeBinary(std::shared_ptr<char[]> serialized_obj) {
deserializeBinary(serialized_obj.get());
}
void deserializeBinary(const char *serialized_obj) {
serialized_obj += sizeof(std::size_t); // skip total size
std::pair<K,std::size_t> key_res = deserialize_binary_attribute<K>(serialized_obj);
key = key_res.first;
serialized_obj += key_res.second;
std::pair<V,std::size_t> value_res = deserialize_binary_attribute<V>(serialized_obj);
value = value_res.first;
serialized_obj += value_res.second;
acc = deserialize_binary_attribute<A>(serialized_obj).first;
}
};
template<>
std::vector<char> ReducerInput<std::string,std::string,std::string>::serializeBinary() const {
std::vector<char> tmp, serialized_obj;
std::size_t total_size = 3*sizeof(std::size_t) + key.size() + value.size() + acc.size();
serialized_obj = serialize_binary_size(total_size); // total size
tmp = serialize_binary_attribute(key); // key
std::copy(std::move_iterator(tmp.begin()), std::move_iterator(tmp.end()), std::back_inserter(serialized_obj));
tmp = serialize_binary_attribute(value); // value
std::copy(std::move_iterator(tmp.begin()), std::move_iterator(tmp.end()), std::back_inserter(serialized_obj));
tmp = serialize_binary_attribute(acc); // acc
std::copy(std::move_iterator(tmp.begin()), std::move_iterator(tmp.end()), std::back_inserter(serialized_obj));
return serialized_obj;
}
| true |
14f98436e91523f3e9ce4a3dd6035398560dc5c4 | C++ | mateoreynoso/HW03 | /HW03-EX01/readInt.cpp | UTF-8 | 862 | 3.453125 | 3 | [] | no_license | #include "readInt.h"
#include <iostream>
#include <stdexcept>
#include <limits>
using namespace std;
int read_int(const string &prompt, int low, int high)
{
// First checks the arguments
if (low >= high)
{
throw invalid_argument("The smallest acceptable number cannot be higher that the largest acceptable integer.");
}
// Next asks the user for the input
int input;
bool inputState = false;
std::cout << prompt;
cin >> input;
if (cin.fail())
{
std::cout << "Invalid input. \n";
cin.clear();
cin.ignore(numeric_limits<int>::max(), '\n');
cin >> input;
}
// Now checks the input is between the parameters
bool correct = true;
do
{
if (input < low || high < input)
{
std::cout << "The input is out of range.\n";
std::cout << prompt;
std::cin >> input;
}
else
correct = false;
} while (correct);
return input;
} | true |
1e2e584cbe5290e0bef63c314c5ecbcee5113bbe | C++ | shining-yang/BOP | /misc/lambda01.cpp | UTF-8 | 489 | 3.234375 | 3 | [] | no_license | //
#include <iostream>
void print(int a)
{
std::cout << "Value: " << a << std::endl;
}
void foo()
{
int val = 1;
//auto const_val_lambda = [=]() { val = 2; };
//const_val_lambda();
print(val);
auto mutable_val_lambda = [=]() mutable { val = 3; };
mutable_val_lambda();
print(val);
auto const_ref_lambda = [&] { val = 4; };
const_ref_lambda();
print(val);
auto const_param_lambda = [&](int v) { v = 5; };
const_param_lambda(val);
print(val);
}
int main()
{
foo();
}
| true |
b6c8fee7371f43f780097135deedccdab2102e55 | C++ | dheerajkhatri/bajinga | /leetcode/stackbyQueue.cpp | UTF-8 | 1,393 | 3.796875 | 4 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
class Stack {
public:
// Push element x onto stack.
queue<int>q1,q2;
void push(int x) {
q1.push(x);
}
// Removes the element on top of the stack.
void pop() {
int temp;
while(q1.size()!=1){
temp = q1.front();
q2.push(temp);
q1.pop();
}
q1.pop();
swap(q1,q2);
}
// Get the top element.
int top() {
int temp;
while(!q1.empty()){
temp = q1.front();
q2.push(temp);
q1.pop();
}
swap(q1,q2);
return temp;
}
// Return whether the stack is empty.
bool empty() {
if(q1.empty() && q2.empty())return true;
return false;
}
void print(){
cout<<"q1 :"; prints(q1);
cout<<"q2 :"; prints(q2);
}
void prints(queue<int>q){
queue<int>temp = q;
while(!temp.empty()){
cout<<temp.front()<<" ";
temp.pop();
}
cout<<endl;
}
};
int main(){
Stack s;
s.push(2);s.push(5);s.push(3);s.push(4);s.push(7);
s.print();
cout<<s.top()<<endl;
s.pop();
cout<<s.top()<<endl;
s.pop();
s.push(12);
s.print();
cout<<s.top()<<endl;
s.pop();s.pop();s.pop();
cout<<s.top()<<endl;
s.pop();
cout<<s.empty()<<endl;
return 0;
} | true |
3bf114126e32269231207776826df13ecd1aa192 | C++ | iworeushankaonce/ContestProgramming | /UvA Online Judge/uva12279-Emoogle_Balance.cpp | UTF-8 | 685 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <cctype>
using namespace std;
int main()
{
int cases = 0;
int n;
for(int cas = 0; ; ++cas)
{
cin >> n;
if (n == 0) break;
int c1 = 0;
int c2 = 0;
for(int i = 0; i < n; ++i)
{
int b;
cin >> b;
if (b == 0)
{
++c2;
}
else
{
++c1;
}
}
cout << "Case " << (cas + 1) << ": " << (c1 - c2) << endl;
}
return 0;
}
// g++ -std=c++11 uva12279-Emoogle_Balance.cpp
/*
5
3 4 0 0 1
4
2 0 0 0
7
1 2 3 4 5 0 0
0
Sample Output
Case 1: 1
Case 2: -2
Case 3: 3
*/ | true |
a942c88885ee6aa1e7e5798fa82aac7bf82961ef | C++ | hungvv2808/khmt1_k12_learn_ktlt | /bth1/1.1.cpp | UTF-8 | 448 | 3.171875 | 3 | [] | no_license | #include <iostream>
#include "math.h"
using namespace std;
int main(){
int a, b;
cout << "a = "; cin >> a;
cout << "b = "; cin >> b;
cout << "Tong hai so la: " << a+b << endl;
cout << "Hieu hai so la: " << a-b << endl;
cout << "Tich hai so la: " << a*b << endl;
cout << "Thuong hai so la: " << (float)a/b << endl;
cout << "Dong du hai so la: " << a%b << endl;
return 0;
}
| true |
a8eb868068daa6cf91bc44b3bd2254b9915d6e2f | C++ | cfigueroa36/CS111_Lab | /L10Q1_dice.cpp | UTF-8 | 350 | 3.453125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <cstdlib>
using namespace std;
int main(){
int dice, sum=0;
cout<<"How many dice would you like to roll"<<endl;
cin>>dice;
for(int i=0; i<dice; i++){
int x=rand()%10;
while(!(x>=1 && x<=6)) x=rand()%10;
cout<<x<<" ";
sum+=x;
}
cout<<"\nThe sum of these numbers is "<<sum<<endl;
return 0;
}
| true |
4c73b5bc4e12ee240868b72cce7468ad491bffd9 | C++ | nvdnkpr/bob-1 | /include/bob/trainer/SVMTrainer.h | UTF-8 | 4,634 | 2.5625 | 3 | [
"BSD-2-Clause"
] | permissive | /**
* @file bob/trainer/SVMTrainer.h
* @date Sat Dec 17 14:41:56 2011 +0100
* @author Andre Anjos <andre.anjos@idiap.ch>
*
* @brief C++ bindings to libsvm (training bits)
*
* Copyright (C) 2011-2013 Idiap Research Institute, Martigny, Switzerland
*/
#ifndef BOB_TRAINER_SVMTRAINER_H
#define BOB_TRAINER_SVMTRAINER_H
#include <vector>
#include <bob/machine/SVM.h>
namespace bob { namespace trainer {
/**
* @ingroup TRAINER
* @{
*/
/**
* This class emulates the behavior of the command line utility called
* svm-train, from libsvm. These bindings do not support:
*
* * Precomputed Kernels
* * Regression Problems
* * Different weights for every label (-wi option in svm-train)
*
* Fell free to implement those and remove these remarks.
*/
class SVMTrainer {
public: //api
/**
* Builds a new trainer setting the default parameters as defined in the
* command line application svm-train.
*/
SVMTrainer(
bob::machine::SupportVector::svm_t svm_type=bob::machine::SupportVector::C_SVC,
bob::machine::SupportVector::kernel_t kernel_type=bob::machine::SupportVector::RBF,
int degree=3, //for poly
double gamma=0., //for poly/rbf/sigmoid
double coef0=0., //for poly/sigmoid
double cache_size=100, //in MB
double eps=1.e-3, //stopping criteria epsilon
double C=1., //for C_SVC, EPSILON_SVR and NU_SVR
double nu=0.5, //for NU_SVC, ONE_CLASS and NU_SVR
double p=0.1, //for EPSILON_SVR, this is the "epsilon" value there
bool shrinking=true, //use the shrinking heuristics
bool probability=false //do probability estimates
);
/** TODO: Support for weight cost in multi-class classification? **/
/**
* Destructor virtualisation
*/
virtual ~SVMTrainer();
/**
* Trains a new machine for multi-class classification. If the number of
* classes in data is 2, then the assigned labels will be -1 and +1. If
* the number of classes is greater than 2, labels are picked starting
* from 1 (i.e., 1, 2, 3, 4, etc.). If what you want is regression, the
* size of the input data array should be 1.
*/
boost::shared_ptr<bob::machine::SupportVector> train
(const std::vector<blitz::Array<double,2> >& data) const;
/**
* This version accepts scaling parameters that will be applied
* column-wise to the input data.
*/
boost::shared_ptr<bob::machine::SupportVector> train
(const std::vector<blitz::Array<double,2> >& data,
const blitz::Array<double,1>& input_subtract,
const blitz::Array<double,1>& input_division) const;
/**
* Getters and setters for all parameters
*/
bob::machine::SupportVector::svm_t getSvmType() const { return (bob::machine::SupportVector::svm_t)m_param.svm_type; }
void setSvmType(bob::machine::SupportVector::svm_t v) { m_param.svm_type = v; }
bob::machine::SupportVector::kernel_t getKernelType() const { return (bob::machine::SupportVector::kernel_t)m_param.kernel_type; }
void setKernelType(bob::machine::SupportVector::kernel_t v) { m_param.kernel_type = v; }
int getDegree() const { return m_param.degree; }
void setDegree(int v) { m_param.degree = v; }
double getGamma() const { return m_param.gamma; }
void setGamma(double v) { m_param.gamma = v; }
double getCoef0() const { return m_param.coef0; }
void setCoef0(double v) { m_param.coef0 = v; }
double getCacheSizeInMB() const { return m_param.cache_size; }
void setCacheSizeInMb(double v) { m_param.cache_size = v; }
double getStopEpsilon() const { return m_param.eps; }
void setStopEpsilon(double v) { m_param.eps = v; }
double getCost() const { return m_param.C; }
void setCost(double v) { m_param.C = v; }
double getNu() const { return m_param.nu; }
void setNu(double v) { m_param.nu = v; }
double getLossEpsilonSVR() const { return m_param.p; }
void setLossEpsilonSVR(double v) { m_param.p = v; }
bool getUseShrinking() const { return m_param.shrinking; }
void setUseShrinking(bool v) { m_param.shrinking = v; }
bool getProbabilityEstimates() const
{ return m_param.probability; }
void setProbabilityEstimates(bool v)
{ m_param.probability = v; }
private: //representation
svm_parameter m_param; ///< training parametrization for libsvm
};
/**
* @}
*/
}}
#endif /* BOB_TRAINER_SVMTRAINER_H */
| true |
cba460bdb3d20281b3d610ad9d342b23c7f83264 | C++ | IngwiePhoenix/stlplus3 | /tags/stlplus-03-01/tests/inf_test/inf_test.cpp | UTF-8 | 5,799 | 2.578125 | 3 | [] | no_license | #include "inf.hpp"
#include "timer.hpp"
#include "build.hpp"
#include "file_system.hpp"
#include "persistent_inf.hpp"
#include "persistent_shortcuts.hpp"
#include "strings.hpp"
#define DATA "inf_test.tmp"
#define MASTER "inf_test.dump"
#ifdef WIN32
typedef __int64 bigint;
#else
typedef long long bigint;
#endif
#define SAMPLES 100
static std::string hex_image (bigint value)
{
char str[1000];
sprintf(str, "%llx", value);
return std::string(str);
}
static bool compare (bigint left, const stlplus::inf& right)
{
char left_str[1000];
sprintf(left_str, "%lld", left);
std::string left_image = left_str;
std::string right_image = right.to_string();
if (left_image != right_image)
{
std::cerr << "failed comparing integer " << left_image << " with inf " << right << std::endl;
return false;
}
return true;
}
static bool report(int a, int b, char* op)
{
std::cerr << "operator " << op << " failed with a = " << a << ", b = " << b << std::endl;
return false;
}
static bool test (int a, int b)
{
//std::cerr << "testing [" << a << "," << b << "]" << std::endl;
bool okay = true;
if (!compare((bigint(a) + bigint(b)), (stlplus::inf(a) + stlplus::inf(b))))
okay &= report(a, b, "+");
if (!compare((bigint(a) - bigint(b)), (stlplus::inf(a) - stlplus::inf(b))))
okay &= report(a, b, "-");
if (!compare((bigint(a) * bigint(b)), (stlplus::inf(a) * stlplus::inf(b))))
okay &= report(a, b, "*");
if (b != 0)
{
if (!compare((bigint(a) / bigint(b)), (stlplus::inf(a) / stlplus::inf(b))))
okay &= report(a, b, "/");
if (!compare((bigint(a) % bigint(b)), (stlplus::inf(a) % stlplus::inf(b))))
okay &= report(a, b, "%");
}
if (!compare((bigint(a) | bigint(b)), (stlplus::inf(a) | stlplus::inf(b))))
okay &= report(a, b, "|");
if (!compare((bigint(a) & bigint(b)), (stlplus::inf(a) & stlplus::inf(b))))
okay &= report(a, b, "&");
if (!compare((bigint(a) ^ bigint(b)), (stlplus::inf(a) ^ stlplus::inf(b))))
okay &= report(a, b, "^");
for (unsigned shift = 1; shift < 16; shift*=2)
{
if (!compare((bigint(a) << shift), (stlplus::inf(a) << shift)))
okay &= report(a, shift, "<<");
if (!compare((bigint(a) >> shift), (stlplus::inf(a) >> shift)))
okay &= report(a, shift, ">>");
}
for (unsigned high = 1; high < 16; high*=2)
{
for (unsigned low = 0; low < high+1; low++)
{
stlplus::inf inf_a(a);
if (high < inf_a.size())
{
// discard the lsbs by simply shifting right
bigint bigint_slice = bigint(a) >> low;
// mask the msbs and sign extend the result
int length = int(high)-int(low)+1;
if (bigint_slice & (bigint(1) << (length-1)))
bigint_slice |= ((~bigint(0)) >> length) << length;
else
bigint_slice &= ~(((~bigint(0)) >> length) << length);
stlplus::inf slice = inf_a.slice(low,high);
if (!compare(bigint_slice, slice))
{
std::cerr << "slice failed with hex integer = " << hex_image(bigint(a)) << ", high = " << high << ", low = " << low << std::endl;
std::cerr << " inf slice = " << slice.image_debug() << ", integer slice = " << hex_image(bigint_slice) << std::endl;
okay &= false;
}
}
}
}
return okay;
}
int main (int argc, char* argv[])
{
bool okay = true;
stlplus::timer cpu_time;
std::cerr << "build: " << stlplus::build() << std::endl;
try
{
srand(time(0));
signed long samples = (argc > 2) ? ((argc-1)/2) : argc == 2 ? atol(argv[1]) : SAMPLES;
std::cerr << "testing " << samples << " samples" << std::endl;
float cpu = cpu_time.cpu();
for (signed long i = 1; i <= samples; i++)
{
int a = (argc > 2) ? atol(argv[i*2-1]) : rand();
int b = (argc > 2) ? atol(argv[i*2]) : rand();
std::cerr << "#" << i << " a = " << a << " b = " << b << std::endl;
okay &= test(a, b);
okay &= test(-a, b);
okay &= test(a, -b);
okay &= test(-a, -b);
if (cpu_time.cpu() > (cpu + 5.0))
{
cpu = cpu + 5.0;
std::cerr << cpu_time << ": tested " << i << " samples" << std::endl;
}
}
std::cerr << cpu_time << " total for " << samples << " samples" << std::endl;
stlplus::inf googol(1);
for (unsigned j = 0; j < 100; j++)
googol *= stlplus::inf(10);
std::cerr << "a googol is:" << std::endl;
for (unsigned radix = 2; radix <= 36; radix++)
std::cerr << "base " << radix << " = " << stlplus::inf_to_string(googol,radix) << std::endl;
// test the persistence
std::cerr << "dumping" << std::endl;
stlplus::dump_to_file(googol, DATA, stlplus::dump_inf, 0);
stlplus::inf googol2;
std::cerr << "restoring" << std::endl;
stlplus::restore_from_file(DATA, googol2, stlplus::restore_inf, 0);
if (googol != googol2)
{
std::cerr << "restored value " << googol2 << " is not the same" << std::endl;
okay = false;
}
// compare with the master dump if present
if (!stlplus::file_exists(MASTER))
stlplus::file_copy(DATA,MASTER);
else
{
std::cerr << "restoring master" << std::endl;
stlplus::inf googol3;
stlplus::restore_from_file(MASTER,googol3,stlplus::restore_inf,0);
if (googol != googol3)
{
std::cerr << "restored value " << googol3 << " is not the same" << std::endl;
okay = false;
}
}
}
catch (std::exception& e)
{
std::cerr << "caught std::exception " << e.what() << std::endl;
okay &= false;
}
catch (...)
{
std::cerr << "caught unknown exception " << std::endl;
okay &= false;
}
std::cerr << cpu_time << " total for program" << std::endl;
std::cerr << "test " << (okay ? "succeeded" : "FAILED") << std::endl;
return okay ? 0 : 1;
}
| true |
6212f1dbd167d3bcb023655cd1f97dbbe705da16 | C++ | jamesbertel/CS-311 | /CS311Progs/HWPrograms/forEC2/shortestmain.cpp | UTF-8 | 822 | 3.015625 | 3 | [] | no_license | // CS311 Yoshii - Shortest Path Extra Credit - Use as is - DO NOT CHANGE
//---------------------------------------------------------------------
#include <iostream>
using namespace std;
#include "dgraph2.h"
int main()
{
dgraph T;
T.filltable();
T.makeTree(0); // 0th entry is now in Tree
T.displayTable();
char a; // user input for stopping the loop
while (!T.allTree()) // Until all are in Tree
{
T.makeTree(T.findSmallest());
T.displayTable();
cout << "cont?"; cin >> a;
}
// the shortest path from the 0's vertex to all others
// have been determined.
cout << "Enter a goal vertex or Q: ";
cin >> a;
while (a != 'Q')
{ T.displayPath(a); // display the shortest path
cout << "Enter a goal vertex or Q: ";
cin >> a;
}
}// end of main
| true |
9294eebcfe297affbc4786824ee7f2957caf3f44 | C++ | frankfanslc/XamlCpp | /ui_controls/src/gtk3/entry.cpp | UTF-8 | 1,822 | 2.59375 | 3 | [
"MIT"
] | permissive | #include <shared/atomic_guard.hpp>
#include <shared/entry.hpp>
using namespace std;
xaml_result xaml_entry_internal::draw(xaml_rectangle const& region) noexcept
{
if (!m_handle)
{
m_handle = gtk_entry_new();
g_signal_connect(G_OBJECT(m_handle), "changed", G_CALLBACK(xaml_entry_internal::on_changed), this);
XAML_RETURN_IF_FAILED(draw_visible());
XAML_RETURN_IF_FAILED(draw_text());
XAML_RETURN_IF_FAILED(draw_alignment());
}
return set_rect(region);
}
xaml_result xaml_entry_internal::draw_text() noexcept
{
char const* data = nullptr;
if (m_text)
{
XAML_RETURN_IF_FAILED(m_text->get_data(&data));
}
gtk_entry_set_text(GTK_ENTRY(m_handle), data);
return XAML_S_OK;
}
xaml_result xaml_entry_internal::draw_alignment() noexcept
{
gfloat align;
switch (m_text_halignment)
{
case xaml_halignment_center:
align = 0.5;
break;
case xaml_halignment_right:
align = 1.0;
break;
default:
align = 0;
break;
}
gtk_entry_set_alignment(GTK_ENTRY(m_handle), align);
return XAML_S_OK;
}
void xaml_entry_internal::on_changed(GtkWidget*, xaml_entry_internal* self) noexcept
{
xaml_atomic_guard guard{ self->m_text_changing };
guard.test_and_set();
gchar const* data = gtk_entry_get_text(GTK_ENTRY(self->m_handle));
xaml_ptr<xaml_string> text;
XAML_ASSERT_SUCCEEDED(xaml_string_new(data, &text));
XAML_ASSERT_SUCCEEDED(self->set_text(text));
XAML_ASSERT_SUCCEEDED(self->parent_redraw());
}
xaml_result xaml_entry_internal::size_to_fit() noexcept
{
int32_t length;
XAML_RETURN_IF_FAILED(m_text->get_length(&length));
gtk_entry_set_width_chars(GTK_ENTRY(m_handle), length);
return xaml_control_internal::size_to_fit();
}
| true |
4c1266053deddba37246163f5a6b19036517ad15 | C++ | leilanihc112/CSCE-121_TAMU | /Labs-121/Lab11/lab11.cpp | UTF-8 | 1,244 | 3.4375 | 3 | [] | no_license | #include "std_lib_facilities_4.h"
void fill_vector(istream& ist, vector<int>& v, char terminator)
// read integers from ist into v until we reach eof() or terminator
{
for (int i; ist>>i; ) v.push_back(i);
if (ist.eof()) return; // fine: we found the end of file
if (ist.bad()) error("ist is bad"); // stream corrupted; let's get out of here!
if (ist.fail()) { // clean up the mess as best we can and report the problem
ist.clear(); // clear stream state,
// so that we can look for terminator
char c;
ist>>c; // read a character, hopefully terminator
if (c != terminator) { // unexpected character
ist.unget(); // put that character back
ist.clear(ios_base::failbit); // set the state to fail()
}
}
}
int main()
{
try
{
cin.exceptions(cin.exceptions()|ios_base::badbit);
vector<int> v;
fill_vector(cin, v, '*'); // end with '*'
int v_add = 0; // start with 0
for (unsigned int i = 0; i < v.size(); ++i) // add elements of vector v together
{
v_add = v_add + v[i];
}
cout << v_add; // output sum
}
catch (exception& e) {
cerr << "error: " << e.what() << '\n';
}
catch (...) {
cerr << "Oops: unknown exception!\n";
}
}
| true |
6077f580cf862d80922c48c6a6694b2dcd6ab72b | C++ | sang8052/cpro | /图书馆/源代码/lib/图书馆管理系统/登录窗口.cpp | GB18030 | 10,119 | 2.515625 | 3 | [
"MIT",
"BSD-3-Clause"
] | permissive | // ¼.cpp : ʵļ
//
#include "stdafx.h"
#include "ͼݹϵͳ.h"
#include "¼.h"
// ¼ Ի
¼::¼(CWnd* pParent /*=NULL*/)
: CDialog(¼::IDD, pParent)
, Username(_T(""))
, Password(_T(""))
, strVERSION(_T(""))
{
m_hIcon = AfxGetApp()->LoadIcon(IDI_ICON1);
}
void ¼::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Text(pDX, IDC_EDIT_USERNAME, Username);
DDX_Text(pDX, IDC_EDIT_PASSWORD, Password);
DDX_Text(pDX, IDC_STATIC_VER, strVERSION);
}
BEGIN_MESSAGE_MAP(¼, CDialog)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
//}}AFX_MSG_MAP
ON_BN_CLICKED(IDC_BUTTON_CANCEL, &¼::OnBnClickedButtonCancel)
ON_BN_CLICKED(IDC_BUTTON_LOGIN, &¼::OnBnClickedButtonLogin)
END_MESSAGE_MAP()
// C¼ Ϣ
BOOL ¼::OnInitDialog()
{
CDialog::OnInitDialog();
// ...˵ӵϵͳ˵С
// IDM_ABOUTBOX ϵͳΧڡ
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
pSysMenu->EnableMenuItem(SC_CLOSE, MF_GRAYED);
}
// ô˶ԻͼꡣӦó¼ڲǶԻʱܽԶ
// ִд˲
SetIcon(m_hIcon, TRUE); // ôͼ
SetIcon(m_hIcon, FALSE); // Сͼ
// TODO: ڴӶijʼ
Getready(); //ִԶʼ
return TRUE;
}
// ԻСťҪĴ
// Ƹͼꡣʹĵ/ͼģ͵ MFC Ӧó
// ⽫ɿԶɡ
void ¼::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // ڻƵ豸
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// ʹͼڹо
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// ͼ
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
//û϶Сʱϵͳô˺ȡù
//ʾ
HCURSOR ¼::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
//ػسϢ
BOOL ¼::PreTranslateMessage(MSG* pMsg)
{
if(pMsg->message==WM_KEYDOWN && pMsg->wParam==VK_ESCAPE) return TRUE;
if(pMsg->message==WM_KEYDOWN && pMsg->wParam==VK_RETURN) return enterlogin();
else
return CDialog::PreTranslateMessage(pMsg);
}
// ¼ Ϣ
void ¼::OnBnClickedButtonCancel()//ȡťϢ
{
// TODO: ڴӿؼ֪ͨ
exit(0);
}
// ݿӵĺ
void ¼::SQL_connect(void)
{
conn= mysql_init((MYSQL*) 0);//ʼmysqlṹ
if(!mysql_real_connect(conn,$MYSQLSERVER,$MYSQLUSER,$MYSQLPASS,$MYSQLDATA,3306,NULL,0)) //mysqlṹݿַݿûݿ룬ݿ˿ںţmysqlãһ㲻ģ
{MessageBox("ݿʧܣ");exit(0);}//ݿʧ˳
else{ mysql_query(conn, "set names gbk"); }//MYSQLصıΪgbkĿʹõĶַݡ
}
//¼ťĺ
void ¼::OnBnClickedButtonLogin()
{
// TODO: ڴӿؼ֪ͨ
int result=0;
// ȡǰipַ;
ifstream IPfile("LibTempIp.txt");
string str,strtmp;
while ( getline(IPfile,strtmp) )
{
str+=strtmp;
}
string::size_type posEnd1 = str.find("[");
string::size_type posEnd2 = str.find("]");
str = str.substr(posEnd1+1,posEnd2-posEnd1-1);
CString ip,ipprint;
ip=str.c_str();
//õǰʱ
CString strDateTime,Tday,Thour,Tmin,Tsec,Tyear,Tmo,strlimittime;
CTime time;
time=CTime::GetCurrentTime();
//ȡǰʱ
Tyear=time.Format("%Y");
Tmo=time.Format("%m");
Tday=time.Format("%d");int iTday= atoi(Tday);
Thour=time.Format("%H");int iThour= atoi(Thour);
Tmin=time.Format("%M");
Tsec=time.Format("%S");
if(iThour+2>=24){iThour=iThour-22;iTday=iTday+1;}
else{iThour=iThour+2;}
Tday.Format("%d",iTday);if(iThour<10){Thour.Format("0%d",iThour);}else{Thour.Format("%d",iThour);}
strlimittime.Format("%s-%s-%s %s:%s:%s",Tyear,Tmo,Tday,Thour,Tmin,Tsec);
strDateTime=time.Format(_T("%Y-%m-%d %H:%M:%S"));
//ûMD5
//עMD5ܵĺֻӢĺ֡
MD5 md5;
USES_CONVERSION;
CString Oldpass;
UpdateData(true);//editлĿǰ
Oldpass=Password;
md5.update(Password.GetBuffer()); //Ϊupdateֻstringͣʹgetbuffer()תCStringΪstring
Password.ReleaseBuffer();
Password=md5.toString().c_str(); //toString()üַc_str();תCString
Password.MakeUpper();//Ѽַ֮ȫд
SQL.Format("select * from user where username='%s' and password='%s'",Username,Password);
SQLtosql();
mysql_query(conn,sql);
res=mysql_store_result(conn);
if(mysql_num_rows(res)==0)
{
MessageBox("û");
SQL.Format("insert loginlog (ip,time,user,pass,state) value('%s','%s','%s','%s','ʧ')",ip,strDateTime,Username,Oldpass);
}
else{
if(mysql_num_rows(res)==1)
{
SQL.Format("UPDATE user SET lastlogintime='%s', lastloginip='%s' where username= '%s'",strDateTime,ip,Username);
SQLtosql();
mysql_query(conn,sql);
MessageBox("¼ɹ");
OnOK();
theApp.Username=Username;
theApp.Logintime=strDateTime;
theApp.LimitTime=strlimittime;
SQL.Format("insert loginlog (ip,time,user,pass,state) value('%s','%s','%s','','ɹ')",ip,strDateTime,Username);
}
if(mysql_num_rows(res)!=1)
{
MessageBox("˻Ч");
SQL.Format("insert loginlog (ip,time,user,pass,state) value('%s','%s','%s','%s','ʧ')",ip,strDateTime,Username,Oldpass);
}
}
SQLtosql();
mysql_query(conn,sql);
}
// CString SQL ת char* sql
void ¼::SQLtosql(void)
{
sql=SQL.GetBuffer(); //GCstr תstrȥ
SQL.ReleaseBuffer(); //ͷŻ
}
// Զʼ
void ¼::Getready(void)
{
MessageBox("ϵͳڳʼҪӣԺ");
//ݿ
SQL_connect();
//ݿйϵͳ״̬
SQL.Format("select * from sys where setname='sysonoff'");
SQLtosql();
mysql_query(conn,sql);res=mysql_store_result(conn);row = mysql_fetch_row(res);
CString sysoff;sysoff.Format("off");
if(row[2]==sysoff){SQL.Format("select * from sys where setname='sysoffres'");
SQLtosql();mysql_query(conn,sql);
res=mysql_store_result(conn);row = mysql_fetch_row(res);
CString echotext;
echotext.Format("%sʳʱ",row[2]);
MessageBox(echotext);
if($DEBUG=="false"){exit(0);}
}
//óĿǰİ汾
char cPath[200];
DWORD dwHandle,InfoSize;
::GetModuleFileName(NULL,cPath,sizeof(cPath)); //Ȼð汾ϢԴij
InfoSize = GetFileVersionInfoSize(cPath,&dwHandle); //汾ϢԴ뻺
char *InfoBuf = new char[InfoSize];
GetFileVersionInfo(cPath,0,InfoSize,InfoBuf); //ļʹõĴҳļ汾
unsigned int cbTranslate = 0;
struct LANGANDCODEPAGE {WORD wLanguage; WORD wCodePage; } *lpTranslate;
VerQueryValue(InfoBuf, TEXT("\\VarFileInfo\\Translation"),(LPVOID*)&lpTranslate,&cbTranslate);
for(unsigned int i=0; i < (cbTranslate/sizeof(struct LANGANDCODEPAGE)); i++ )
{char SubBlock[200];wsprintf( SubBlock,TEXT("\\StringFileInfo\\%04x%04x\\FileVersion"),lpTranslate[i].wLanguage,lpTranslate[i].wCodePage);
void *lpBuffer=NULL;unsigned int dwBytes=0;VerQueryValue(InfoBuf,SubBlock,&lpBuffer,&dwBytes);
CString strTemp=( char *)lpBuffer;strVERSION=strTemp;UpdateData(false);}
delete InfoBuf;
//ݿǷǰ汾ʹ
SQL.Format("select * from sys where setvalue='%s'",strVERSION);
SQLtosql();
mysql_query(conn,sql);
res=mysql_store_result(conn);
if(mysql_num_rows(res)==0)
{
SQL.Format("select * from sys where setname='urltodown'");
SQLtosql();
mysql_query(conn,sql);
res=mysql_store_result(conn);
row = mysql_fetch_row(res);
CString echotext;
echotext.Format("ǰİ汾ͣѾֹ֧ͣ֡\t%s ȡ°汾",row[2]);
MessageBox(echotext);
if($DEBUG=="false"){exit(0);}
}
//ñipַ
if($DEBUG=="false"){Getip();}
MessageBox("ʼɹ");
}
// ñipַ
void ¼::Getip(void)
{
char buffer[]="LibTempIp.txt";//óʱipļĿ¼
if(PathFileExists("LibTempIp.txt")){DeleteFile("LibTempIp.txt ");}//黺ļǷڣڼɾ
char* Tempfile=buffer;
//γԻipַ
URLDownloadToFile(0,"http://ip.szhcloud.top/index.php","LibTempIp.txt",0,NULL);
if(PathFileExists(Tempfile)){}else{MessageBox("ʼipַʧܣԡ");
URLDownloadToFile(0,"http://ip.szhcloud.top/index.php","LibTempIp.txt",0,NULL);
if(PathFileExists(Tempfile)){}else {MessageBox("ʼipַʧܣԡ");
URLDownloadToFile(0,"http://ip.szhcloud.top/index.php","LibTempIp.txt",0,NULL);
if(PathFileExists(Tempfile)){}else{MessageBox("ʼipַʧ!");exit(0);}}}
}
bool ¼::enterlogin(void)
{
OnBnClickedButtonLogin();
return TRUE;
}
| true |
42b6e22eef241699933c45f1a98d93d6492b1ad8 | C++ | colistro123/Deer_Hunter04_GameSpy_Patches | /SH2Proxy/GLHook.cpp | UTF-8 | 1,359 | 2.765625 | 3 | [] | no_license | #include "stdafx.h""
#include "GLHook.h"
#include <stdio.h> // Header File For Standard Input/Output
//this will hook a process and all of it`s modules (loaded DLLs)
//by writting to kernel`s area
/* This Code will create a process-wide hook by writing to the kernel's *
* Parameters Are: *
* Dll - Name of the Dll that contains the API *
* FuncName - Name of the API you want to hook *
* Function - Name of the function the API gets redirected to *
* backup - Array of bytes the original code will be read to */
DWORD HookGeneralFunction(const char *Dll, const char *FuncName, void *Function, unsigned char *backup)
{
DWORD addr = (DWORD)GetProcAddress(GetModuleHandle(Dll), FuncName); // Get the address of the API
BYTE jmp[6] = { 0xe9, //jmp
0x00, 0x00, 0x00, 0x00, //address
0xc3 }; //retn
ReadProcessMemory(GetCurrentProcess(), (void*)addr, backup, 6, 0); // Read the first 6 Bytes of the API and save them
DWORD calc = ((DWORD)Function - addr - 5); // Calculate the jump
memcpy(&jmp[1], &calc, 4); //build the jmp
WriteProcessMemory(GetCurrentProcess(), (void*)addr, jmp, 6, 0); //Overwrite the first 6 Bytes of the API with a jump to our function
return addr; //Return the address of the API(so we can restore the original code if needed
} | true |
74b5395f3a2ce54585c4ae9b62dd7750186ae782 | C++ | ShankarBirTamang/Learning_Cplusplus | /ch3_OperatorOverloading/QuestionsNSolution/Q4.cpp | UTF-8 | 1,686 | 4.34375 | 4 | [] | no_license | //Example of overloading < , > and = operator
#include<iostream>
#include<math.h>
using namespace std;
class complex{
private:
int real;
int img;
public:
void getComplex(){
cout<<"Enter real part: ";
cin>>real;
cout<<"Enter Imaginary part: ";
cin>>img;
}
void display(){
if (img<0)
cout<<"\n("<<real<<" -j "<<(-1)*img<<")"<<endl;
else
cout<<"\n("<<real<<" +j "<<img<<")"<<endl;
}
//overloading < operator
float operator <(complex c){
float mag1 = sqrt(real*real+img*img);
float mag2 = sqrt(c.real*c.real+c.img*c.img);
return (mag1<mag2)?true:false;
}
//overloading > operator
float operator >(complex c){
float mag1 = sqrt(real*real+img*img);
float mag2 = sqrt(c.real*c.real+c.img*c.img);
return (mag1>mag2)?true:false;
}
//overloading = operator
float operator =(complex c){
float mag1 = sqrt(real*real+img*img);
float mag2 = sqrt(c.real*c.real+c.img*c.img);
return (mag1==mag2)?true:false;
}
};
int main(){
complex c1,c2;
c1.getComplex();
c2.getComplex();
cout<<"First Complex number: ";
c1.display();
cout<<"Second Complex number: ";
c2.display();
//Testing < , > and = operator
if (c1<c2)
cout<<"First complex number is smaller."<<endl;
else if(c1>c2)
cout<<"First complex number is greater."<<endl;
else if(c1=c2)
cout<<"Both complex number are equal."<<endl;
return 0;
} | true |
c21c6155d889f368d4904ccc465c1fb992373455 | C++ | jsrdzhk/algo_snippet | /jz_offer/bt_path_sum.cxx | UTF-8 | 952 | 3.015625 | 3 | [
"MIT"
] | permissive | /*
* @title: todo
* @author: Rodney Cheung
* @date: 2021-06-20 12:22:10
* @last_author: Rodney Cheung
* @last_edit_time: 2021-06-20 12:44:16
*/
#include "precompiled_headers.h"
class Solution
{
private:
std::vector<std::vector<int>> res;
int t;
std::vector<int> cur;
public:
std::vector<std::vector<int>> pathSum(TreeNode *root, int target)
{
t = target;
pathSumImpl(root, 0);
return res;
}
void pathSumImpl(TreeNode *root, int curSum)
{
if (!root)
{
return;
}
int v = root->val;
cur.push_back(v);
curSum += v;
if (!root->left && !root->right)
{
if (curSum == t)
{
res.push_back(cur);
}
}
else
{
pathSumImpl(root->left, curSum);
pathSumImpl(root->right, curSum);
}
cur.pop_back();
curSum -= v;
}
}; | true |
340bf55d3b9376ee77c97ab6b1453d35283e8eed | C++ | Vothongminh/CODE-055 | /CODE-055.ino | UTF-8 | 1,424 | 2.734375 | 3 | [] | no_license | //VTM https://www.youtube.com/c/VTMVlogVoThongMinh
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 20, 4);
#include "MQ135.h" //gọi thư viện MQ135
#include "DHT.h" //gọi thư viện DHT11
#define PIN_MQ135 A2
MQ135 mq135_sensor = MQ135(PIN_MQ135);
const int DHTPIN = 2; //Đọc dữ liệu từ DHT11 ở chân 2 trên mạch Arduino
const int DHTTYPE = DHT11; //Khai báo loại cảm biến, có 2 loại là DHT11 và DHT22
DHT dht(DHTPIN, DHTTYPE);
///////////////////////////////////////
void setup() {
Serial.begin(9600);
dht.begin(); // Khởi động cảm biến
lcd.init();
lcd.backlight();
lcd.setCursor(4, 0);
lcd.print("SMART GARDEN");
}
////////////////////////////////////////
void loop() {
float humidity = dht.readHumidity(); //Đọc độ ẩm
float temperature = dht.readTemperature(); //Đọc nhiệt độ
float ppm = mq135_sensor.getPPM();
lcd.setCursor(0, 1);
lcd.print("Nhiet do:");
lcd.setCursor(11, 1);
lcd.print(temperature);
lcd.setCursor(15, 1);
lcd.print("(C)");
lcd.setCursor(0, 2);
lcd.print("Do am:");
lcd.setCursor(11, 2);
lcd.print(humidity);
lcd.setCursor(15, 2);
lcd.print("(%)");
lcd.setCursor(0, 3);
lcd.print("Khong khi:");
lcd.setCursor(11, 3);
lcd.print(ppm);
lcd.setCursor(15, 3);
lcd.print("(ppm)");
delay(500);
}
| true |
6f4c7546b8deaa202e9cbbac03613e3d21689435 | C++ | asomeJay/algorithm | /Acm_icpc/C,C++/boj1007.cpp | WINDOWS-1252 | 1,387 | 2.796875 | 3 | [] | no_license | /* Ī */
#include <iostream>
#include <vector>
#include <stack>
#include <tgmath.h>
#include <algorithm>
#include <cstring>
#define N_DOT 21
#define ll long double
using namespace std;
pair<int, int>dot[N_DOT];
ll Ans = 9876543210, n_of_vector;
void init();
void combination();
int main(void) {
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
cout << fixed; cout.precision(12);
int i, j, t_case;
cin >> t_case;
for (i = 1; i <= t_case; i++) {
init();
cin >> n_of_vector;
for (j = 0; j < n_of_vector; j++) {
int a, b;
cin >> a >> b;
dot[j] = { a,b };
}
combination();
cout << Ans << '\n';
}
return 0;
}
void init() {
Ans = 9876543210;
}
void combination() {
vector<int> ind;
int sel_vector = n_of_vector / 2;
for (int i = 0; i < sel_vector ; i++)
ind.push_back(1);
for (int i = 0; i < sel_vector; i++)
ind.push_back(0);
sort(ind.begin(), ind.end());
do {
ll sel_x = 0, sel_y = 0;
ll unsel_x = 0, unsel_y = 0;
for (int i = 0; i < n_of_vector; i++) {
if (ind[i] == 1) {
sel_x += dot[i].first;
sel_y += dot[i].second;
}
else {
unsel_x += dot[i].first;
unsel_y += dot[i].second;
}
}
ll x = (unsel_x - sel_x) * (unsel_x - sel_x);
ll y = (unsel_y - sel_y) * (unsel_y - sel_y);
Ans = min(Ans, sqrt((x + y)));
} while (next_permutation(ind.begin(), ind.end()));
} | true |
c6f0ee4000e615e871330916c2ea2d902b585189 | C++ | Thrash92/Ultrasonic | /Ultrasonic.cpp | UTF-8 | 585 | 2.703125 | 3 | [] | no_license | #include "Ultrasonic.h"
Ultrasonic::Ultrasonic(uint8_t trig, uint8_t echo) : m_trig(trig), m_echo(echo)
{
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
}
ulong Ultrasonic::distance(Unit u, ulong timeout)
{
digitalWrite(m_trig, LOW);
delayMicroseconds(2);
digitalWrite(m_trig, HIGH);
delayMicroseconds(10);
digitalWrite(m_trig, LOW);
ulong dist = pulseIn(m_echo, HIGH, timeout);
if ( u == MM )
return dist / 5.8;
else
if ( u == CM )
return dist / 58;
else
if ( u == IN )
return dist / 148;
return dist;
}
| true |
b608910079eca916b0a80e0e3ba8f5847ab6769d | C++ | AndreSci/Cpp | /lesson_125/prefix_02.cpp | UTF-8 | 2,078 | 3.265625 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <set>
#include <map>
using namespace std;
bool cmp_up(const string& prefix, const string& word)
{
int p = static_cast<int>(prefix.size());
string w1;
//if (p <= static_cast<int>(word.size()))
for (int i(0); i < p; i++)
{
w1 += word[i];
}
return w1 > prefix;
}
bool cmp_low(const string& word, const string& prefix)
{
int p = static_cast<int>(prefix.size());
string w1;
//if(p <= static_cast<int>(word.size()))
for (int i(0); i < p; i++)
{
w1 += word[i];
}
return w1 < prefix;
}
string t_words(const string& word, const string& prefix)
{
int p = static_cast<int>(prefix.size());
string w1;
//if (p <= static_cast<int>(word.size()))
for (int i(0); i < p; i++)
{
w1 += word[i];
}
if (w1 == prefix)
return word;
else
return "";
}
template <typename RandomIt>
pair<RandomIt, RandomIt> FindStartsWith(RandomIt range_begin, RandomIt range_end, const string& prefix)
{
string s;
auto one = lower_bound(range_begin, range_end, prefix, cmp_low);
if (one != range_end)
{
s = t_words(*one, prefix);
}
if (s.empty())
{
auto one_end = lower_bound(range_begin, range_end, prefix, cmp_low);
return { one_end, one_end };
}
auto two = upper_bound(one, range_end, prefix, cmp_up);
return { one , two };
}
int main()
{
const vector<string> sorted_strings = { "moscow", "motovilikha", "murmansk" };
const auto mo_result =
FindStartsWith(begin(sorted_strings), end(sorted_strings), "mo");
for (auto it = mo_result.first; it != mo_result.second; ++it) {
cout << *it << " ";
}
cout << endl;
const auto mt_result =
FindStartsWith(begin(sorted_strings), end(sorted_strings), "mt");
cout << (mt_result.first - begin(sorted_strings)) << " " <<
(mt_result.second - begin(sorted_strings)) << endl;
const auto na_result =
FindStartsWith(begin(sorted_strings), end(sorted_strings), "na");
cout << (na_result.first - begin(sorted_strings)) << " " <<
(na_result.second - begin(sorted_strings)) << endl;
system("pause");
return 0;
}
| true |
dc7bcee4d28d0359fd605c6cde1c2c2e5844080b | C++ | FarshidNooshi/Data-Structures-and-Algorithms-CE-course | /Final Project-Routing with Graph Algorithms/Implementations/Reader.cpp | UTF-8 | 876 | 2.765625 | 3 | [
"MIT"
] | permissive | #include <bits/stdc++.h>
#include "Headers/Reader.h"
using namespace std;
void Reader::ReadMap() {
cin >> numberOfPoints >> numberOfEdges;
for (int i = 0, id; i < numberOfPoints; i++) {
double x, y;
cin >> id >> x >> y;
points.push_back({ id, x, y });
}
for (int i = 0, idSource, idTarget; i < numberOfEdges; i++) {
cin >> idSource >> idTarget;
edgeIds.push_back({ idSource, idTarget });
}
}
void Reader::ReadQueries() {
double tme;
int src, dst;
vector<Query> vec;
cout << "enter number of queries:\n";
/*while (cin >> tme >> src >> dst) {
vec.push_back({ tme, src, dst });
}*/
{
int temp; cin >> temp;
while (temp--) {
cin >> tme >> src >> dst;
vec.push_back({ tme, src, dst });
}
}
sort(vec.begin(), vec.end(), [](Query& left, Query& right) {
return left.tme < right.tme;
});
for (auto& item : vec)
queries.push(item);
} | true |
18e05e438e353459187f048e7986430f45545d2d | C++ | Sawy7/alg2projekt2_nem0215 | /alg2projekt2_nem0215/BTree.h | UTF-8 | 1,130 | 2.5625 | 3 | [] | no_license | #pragma once
#include "TreePage.h"
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
class BTree
{
public:
BTree(int o);
void Insert(int value);
void PrintTree();
int CountKeys();
void FindKey(int value);
void Remove(int value, bool onlyRebalance);
void PTIMP();
int GetTreeHeight();
void InsertInteractive();
~BTree();
private:
/// Rad stromu - maximalni pocet klicu v jakekoliv strance je dvojnasobek zvoleneho radu (vychazim z definice z ALG2 materialu)
int order;
int minKeys;
int maxKeys;
/// Koren stromu (stranka)
TreePage* root;
/// Celkovy pocet klicu stromu - k aktualizaci NEDOCHAZI automaticky, ale pouze pri spusteni metody CountKeys()
int keyCount;
void PrintTree(TreePage* tp, string prefix);
int CountKeys(TreePage* tp);
TreePage* FindKey(int value, TreePage* tp);
TreePage* FindParentPage(int value, TreePage* p, TreePage* r);
int FindFirstGreater(int value, TreePage* tp);
int GetTreeHeight(TreePage* tp, int height);
bool PTIMP(int level, TreePage* tp);
int CharsOnLevel(int level, TreePage* tp);
TreePage* IsSplitNecessary(int value, TreePage* tp);
};
| true |
481d9bb35b2565c588a0b3493c023d3a4e306e8c | C++ | darqwski/DrvalEngine | /Model/Leadings.cpp | UTF-8 | 1,434 | 2.78125 | 3 | [] | no_license | //
// Created by General Automatic on 2019-07-16.
//
#include "Leadings.h"
#include "../Utilities/SuperUtilities.h"
#include "Plan.h"
const Instructors &Leadings::getInstructor() const {
return instructor;
}
void Leadings::setInstructor(const Instructors &instructor) {
Leadings::instructor = instructor;
}
SubjectType Leadings::getType() const {
return type;
}
void Leadings::setType(SubjectType type) {
Leadings::type = type;
}
void Leadings::setType(string type) {
Leadings::type = getSubjectType(type);
}
const Subjects &Leadings::getSubject() const {
return subject;
}
Leadings::Leadings() {
}
Leadings::Leadings(const Instructors &instructor, SubjectType type, const Subjects &subject) {
setInstructor(instructor);
setType(type);
setSubject(subject);
}
void Leadings::setSubject(const Subjects &subject) {
Leadings::subject = subject;
}
Leadings::Leadings(string basicString) {
vector<string> items = split(basicString,";");
this->instructorId=(items.at(0));
this->subjectId=(items.at(1));
this->setType(items.at(2));
}
const string &Leadings::getSubjectId() const {
return subjectId;
}
void Leadings::setSubjectId(const string &subjectId) {
Leadings::subjectId = subjectId;
}
const string &Leadings::getInstructorId() const {
return instructorId;
}
void Leadings::setInstructorId(const string &instructorId) {
Leadings::instructorId = instructorId;
}
| true |
b4f5c01b0758921d7e4896fa77fb3252e4593065 | C++ | lijiaxin-dut/leetcode | /leetcode_train/Solution_676.cpp | GB18030 | 1,290 | 3.421875 | 3 | [] | no_license | #include<unordered_map>
#include<unordered_set>
#include<vector>
using namespace std;
//ֵеĵʵĹھ
//ĵʣھӣ˵һ
//ֻһھӣҪǰǷб
class MagicDictionary {
public:
unordered_set<string>words;
unordered_map<string, int>count;
/** Initialize your data structure here. */
MagicDictionary() {
}
vector<string>generakuzed_neighbors(string &word) {
vector<string>ans;
for (int i = 0; i < word.size(); ++i) {
char letter = word[i];
word[i] = '*';
ans.push_back(word);
word[i] = letter;
}
return ans;
}
void buildDict(vector<string> dictionary) {
for (auto word : dictionary) {
words.insert(word);
for (auto nei : generakuzed_neighbors(word)) {
count[nei]++;
}
}
}
bool search(string searchWord) {
for (auto nei : generakuzed_neighbors(searchWord)) {
int c = count[nei];
if (c > 1 || (c == 1 && words.find(searchWord) == words.end()))
return true;
}
return false;
}
};
/**
* Your MagicDictionary object will be instantiated and called as such:
* MagicDictionary* obj = new MagicDictionary();
* obj->buildDict(dictionary);
* bool param_2 = obj->search(searchWord);
*/
| true |
4a8a60e3987b8fcb01a76087ab330062f1c0f200 | C++ | NothinRandom/PCA9685 | /PCA9685.cpp | UTF-8 | 1,457 | 2.625 | 3 | [] | no_license | #include <PCA9685.h>
#include <Wire.h>
PCA9685::PCA9685(uint8_t address)
{
_address = BASE_ADDRESS | address;
}
void PCA9685::begin()
{
Wire.begin();
}
void PCA9685::init()
{
reset();
}
void PCA9685::reset()
{
write8(MODE1, 0x00);
}
void PCA9685::setFREQ(float freq)
{
float prescaleval = 25000000;
prescaleval /= 4096;
prescaleval /= freq;
prescaleval -= 1;
uint8_t prescale = floor(prescaleval + 0.5);
uint8_t oldmode = read8(MODE1);
uint8_t newmode = (oldmode & 0x7F) | 0x10; // sleep
write8(MODE1, newmode); // go to sleep
write8(PRESCALE, prescale); // set the prescaler
write8(MODE1, oldmode);
delay(5);
write8(MODE1, oldmode | 0xA1);
}
void PCA9685::setDC(uint8_t num, uint16_t on, uint16_t off)
{
Wire.beginTransmission(_address);
Wire.write(LED0_ON_L + (num << 2));
Wire.write(on);
Wire.write(on >> 8);
Wire.write(off);
Wire.write(off >> 8);
Wire.endTransmission();
}
//either all on or off, using pin OE
void PCA9685::all(boolean state)
{
for(byte i = 0; i < 16; i++)
{
if(state) //write all high
setDC(i, 0, 4095);
else //write all low
setDC(i, 0, 0);
}
}
uint8_t PCA9685::read8(uint8_t addr)
{
Wire.beginTransmission(_address);
Wire.write(addr);
Wire.endTransmission();
Wire.requestFrom((uint8_t)_address, (uint8_t)1);
return Wire.read();
}
void PCA9685::write8(uint8_t addr, uint8_t d)
{
Wire.beginTransmission(_address);
Wire.write(addr);
Wire.write(d);
Wire.endTransmission();
}
| true |
e9d0a029f787fb7b4cc7df77de6888984145ab1f | C++ | smurakami/AmarikkoSound | /src/ofApp.cpp | UTF-8 | 4,787 | 2.546875 | 3 | [] | no_license | #include "ofApp.h"
#include "ofxCv.h"
template <typename T>
static cv::Mat toCv(ofPixels_<T>& pix)
{
int depth;
switch(pix.getBytesPerChannel())
{
case 4: depth = CV_32F; break;
case 2: depth = CV_16U; break;
case 1: default: depth = CV_8U; break;
}
return cv::Mat(pix.getHeight(), pix.getWidth(), CV_MAKETYPE(depth, pix.getNumChannels()), pix.getData(), 0);
}
//--------------------------------------------------------------
void ofApp::setup(){
// -----------------------------------
// 画像関連のセットアップ
//
// フレームレートの設定
ofSetFrameRate(30);
// カメラの初期化。ウインドウサイズにあわせる。
grabber.setup(ofGetWidth(), ofGetHeight(), OF_PIXELS_BGRA);
// 昭和の書き方だと...
// setupGrabber(grabber, ofGetWidth(), ofGetHeight(), OF_PIXELS_BGRA);
// -----------------------------------
// 音関連のセットアップ
//
sequencer.setup();
}
//--------------------------------------------------------------
void ofApp::update(){
// カメラから画像を取り込み
grabber.update();
if (!grabber.isFrameNew()) {
// 画像が更新されていなかったら無視する
return;
}
// カメラ画像を取得
cv::Mat image = toCv(grabber.getPixels());
// output = image;
// return;
// グレースケールに変換
cv::Mat gray;
cv::cvtColor(image, gray, CV_BGRA2GRAY);
// output = gray; return;
// 輪郭抽出のために二値化
cv::Mat thresh;
cv::threshold(gray, thresh, 127, 255, 0);
// output = thresh; return;
// 輪郭抽出
// cv::Point p;
// p.x = 100;
// p.y = 200;
// cv::Point -> 位置を記録するデータ、オブジェクト、構造体、クラス
// vector -> たくさんの情報を並べて記録する「配列」(貸し金庫)
vector<cv::Vec4i> hierarchy; // 抽出した輪郭の相互関連の情報が入る入れ物(つかわない)
cv::findContours(thresh, contours, hierarchy, cv::RETR_TREE, cv::CHAIN_APPROX_SIMPLE);
// 階層構造を考慮しつつ密に記録
// 一番精密に抽出
// return cv::Mat(pix.getHeight(), pix.getWidth(), CV_MAKETYPE(depth, pix.getNumChannels()), pix.getData(), 0);
canvas = cv::Mat(image.size(), CV_MAKETYPE(image.depth(), image.channels()), cv::Scalar(0, 0, 0));
const float full_area = ofGetHeight() * ofGetWidth();
for (vector<cv::Point> contour : contours ) {
float area = cv::contourArea(contour);
float hue = 255 * area / full_area;
ofColor color = ofColor::fromHsb(hue, 255, 255);
vector<vector<cv::Point>> pts = {contour};
cv::fillPoly(canvas, pts, cv::Scalar(color.r, color.g, color.b));
}
output = canvas;
sequencer.update(canvas);
return;
}
//--------------------------------------------------------------
void ofApp::draw(){
ofSetColor(255, 255, 255, 255);
cv::drawContours(output, contours, -1, {0, 255, 0});
// 画像認識結果の表示
ofImage img; // キャンバス
ofxCv::toOf(output, img); // キャンバスにデータをいれる
img.update(); // 一回アップデート
img.draw(0, 0); // 描画
sequencer.draw();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
// sound.setSpeed(2.0 * y / (float)ofGetHeight());
// sound.play();
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| true |
c0df1d08ef0a2e7cee713acb7c9bcafa3725db62 | C++ | bobodaye/myWorkSpace | /DesignPatterns/singleton/singleton.cpp | UTF-8 | 1,567 | 2.78125 | 3 | [] | no_license | /*************************************************************************
> File Name: singleton.cpp
> Author: BoLiu
> Mail:
> Created Time: Fri 29 Sep 2017 05:50:36 PM CST
************************************************************************/
#include <iostream>
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include "singleton.h"
using namespace std;
#define THREAD_NUM 4
pthread_t tid[THREAD_NUM];
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void thread_wait();
void* worker(void*);
void err_quit(int err, const char* s);
Singleton* Singleton::CreateInstance()
{
if(NULL == instance)
{
pthread_mutex_lock(&lock);
if(NULL == instance)
instance = new Singleton;
pthread_mutex_unlock(&lock);
}
return instance;
}
int main()
{
int err;
for(int i = 0; i < THREAD_NUM; ++i)
{
err = pthread_create(&tid[i], NULL, worker, NULL);
if(0 != err)
err_quit(err, "thread create error");
}
thread_wait();
cout << "main thread finish\n";
return 0;
}
void* worker(void* /*arg*/)
{
Singleton* instance = NULL;
instance = Singleton::CreateInstance();
printf("%0x\n", (unsigned int)instance);
pthread_exit(NULL);
}
void thread_wait()
{
int err;
for(int i = 0; i < THREAD_NUM; ++i)
{
err = pthread_join(tid[i], NULL);
if(0 != err)
err_quit(err, "thread join error");
}
}
void err_quit(int err, const char* s)
{
fprintf(stderr, "%s %s\n", s, strerror(err));
exit(1);
}
| true |
29e1d3897a0868ed37840b93a8051cf3efbe4e3a | C++ | magicnat/bridge-distribute | /test/dist-server-test.cc | UTF-8 | 2,537 | 2.890625 | 3 | [
"Unlicense"
] | permissive | #include "dist-server-test.h"
#include <sys/socket.h>
#include <chrono>
int cs1[2];
int cs2[2];
int cs3[2];
void DistributionServerTest::DoStart() {
socketpair (AF_UNIX, SOCK_DGRAM, 0, cs1);
socketpair (AF_UNIX, SOCK_DGRAM, 0, cs2);
socketpair (AF_UNIX, SOCK_DGRAM, 0, cs3);
HandleConnect(cs1[1]);
HandleConnect(cs2[1]);
HandleConnect(cs3[1]);
}
void DistributionServerTest::DoStop() { }
int main () {
// server init
DistributionServerTest test;
std::thread server_thread(&DistributionServerTest::Start, &test);
printf("[INFO] main: started, wait 1s for server to be ready.\n");
std::this_thread::sleep_for (std::chrono::seconds(1));
// handshake
handshake_msg_t hs;
hs.id = 114;
write(cs1[0], &hs, sizeof(handshake_msg_t));
write(cs2[0], &hs, sizeof(handshake_msg_t));
write(cs3[0], &hs, sizeof(handshake_msg_t));
server_thread.join();
// publish from cs1
payload_t payload;
printf("[INFO] main: client0: writing payload = test, len = 4.\n");
memcpy(payload.payload, "test", 4);
payload.payload_len = 4;
ssize_t len = write(cs1[0], &payload, 6);
printf("[INFO] main: client0: wrote %li bytes.\n", len);
// cs2: read
printf("[INFO] main: client1: reading payload...\n");
payload_t payload_read;
len = read(cs2[0], &payload_read, sizeof(payload_t));
printf("[INFO] main: client1: read %li bytes, payload length = %d btyes.\n", len, payload_read.payload_len);
if (payload_read.payload_len + 2 != len) {
printf("[WARN] main: client1: error, payload length should be %li bytes.\n", len - 2);
} else {
char content[payload_read.payload_len];
memcpy(&content, payload_read.payload, payload_read.payload_len);
printf("[INFO] main: client1: payload content: '%s'\n", content);
}
// cs3: read
printf("[INFO] main: client2: reading payload...\n");
payload_t payload_read_2;
len = read(cs3[0], &payload_read_2, sizeof(payload_t));
printf("[INFO] main: client2: read %li bytes, payload length = %d btyes.\n", len, payload_read_2.payload_len);
if (payload_read_2.payload_len + 2 != len) {
printf("[WARN] main: client2: error, payload length should be %li bytes.\n", len - 2);
} else {
char content[payload_read_2.payload_len];
memcpy(&content, payload_read_2.payload, payload_read_2.payload_len);
printf("[INFO] main: client2: payload content: '%s'\n", content);
}
// stop
test.Stop();
return 0;
} | true |
05df8a08ad55d1b3f9ea66498690bcd364e75e7b | C++ | GuillaumeNed33/RunnerPOO | /Runner_Nedelec_Marcilloux/AnimatedGraphicElement.cpp | UTF-8 | 2,198 | 2.953125 | 3 | [] | no_license | #include "AnimatedGraphicElement.h"
//===========================================================================================================================
// Description : Constructeur de AnimatedGraphicElement
// Auteur : Guillaume Nedelec
// Date : 8/04/16
// Interêt : permet de creer des AnimatedGraphicELement à partir d'un vecteur de lecture, d'une texture et de quatre entiers
//===========================================================================================================================
AnimatedGraphicElement::AnimatedGraphicElement(const std::vector<sf::IntRect> &clipRects, sf::Texture &image, int x, int y, int w, int h) :
GraphicElement{image,x,y,w,h}, _clip_rects{clipRects}
{}
//====================================================
// Description : Destructeur de AnimatedGraphicElement
// Auteur : Guillaume Nedelec
// Date : 8/04/16
// Interêt : permet de detruire l'objet
//====================================================
AnimatedGraphicElement::~AnimatedGraphicElement() {}
//==============================================================================================================
// Description : Action de Dessin
// Auteur : Guillaume Nedelec
// Date : 8/04/16
// Interêt : permet de dessiner sur une fenêtre, un élément graphique qui changera en fonction du temps (horloge)
//===============================================================================================================
void AnimatedGraphicElement::draw(sf::RenderWindow *window)
{
setTextureRect(_clip_rects[_current_clip_rect%_clip_rects.size()]);
window->draw(*this);
sf::Time time = _clockFrame.getElapsedTime();
if(time.asSeconds() > 0.1)
{
_current_clip_rect++;
_clockFrame.restart();
}
}
//==================================================================================
// Description : Mutateur de vecteur de lecture
// Auteur : Nicolas Marcilloux
// Date : 24/05/16
// Interêt : permet d'appliquer un vecteur de lecture sur un élément graphique animé
//==================================================================================
void AnimatedGraphicElement::setVectRect(std::vector<sf::IntRect> c)
{
_clip_rects = c;
}
| true |
9cd378ca9f480551e918f03f1090ca4053ad0d17 | C++ | hieple19/bee-project | /Engine/BusyBeeEngine/runhistory.h | UTF-8 | 648 | 2.640625 | 3 | [] | no_license | #ifndef RUNHISTORY_H
#define RUNHISTORY_H
#include <iostream>
#include <string>
#include "../../DBee/dbtool.h"
#include "../../DBee/dbtable.h"
#include "../../DBee/dbtablerun.h"
#include "run.h"
class DBTableRun;
class RunHistory
{
public:
RunHistory();
void add_prev_run(Run* run);
void add_new_run(Run* run);
void print();
Run* get_run(unsigned index);
int get_nb_runs(){return run_list->size();}
void load_run_history();
void save_run(Run* run);
private:
std::vector<Run*> *run_list;
void set_up();
DBTool* dbTool;
DBTableRun* table_run;
};
#endif // RUNHISTORY_H
| true |
66892fd8e1639b8dc1636490aa7cdc21a0673768 | C++ | bmartin5263/Cursen | /Cursen/Cursor/ArrowMap.h | UTF-8 | 1,209 | 2.859375 | 3 | [] | no_license | //
// Created by Brandon Martin on 3/12/19.
//
#ifndef CURSEN_ARROWMAP_H
#define CURSEN_ARROWMAP_H
class VisualComponent;
namespace cursen {
struct ArrowMap {
ArrowMap() {
this->left = nullptr;
this->up = nullptr;
this->down = nullptr;
this->right = nullptr;
}
ArrowMap(const ArrowMap& other) {
//TerminalManager::Beep();
this->left = other.left;
this->down = other.down;
this->right = other.right;
this->up = other.up;
}
ArrowMap& operator = (const ArrowMap& other) {
this->left = other.left;
this->down = other.down;
this->right = other.right;
this->up = other.up;
return *this;
}
ArrowMap(VisualComponent* left, VisualComponent* up, VisualComponent* right, VisualComponent* down) {
this->left = left;
this->up = up;
this->down = down;
this->right = right;
}
VisualComponent* left;
VisualComponent* up;
VisualComponent* right;
VisualComponent* down;
};
}
#endif //CURSEN_ARROWMAP_H
| true |
ed88766f1b10695a18864b2ffbc7bc600a908963 | C++ | bingeun/BG_DX | /BG_KGCA/Max02_BG/bgTemplateMap.h | UTF-8 | 3,511 | 2.796875 | 3 | [] | no_license | #pragma once
#include "bgStdMax.h"
using namespace std;
template<class Child>
class bgTemplateMap
{
public:
typedef map<int, Child*> TemplateMap;
typedef typename TemplateMap::iterator TemplateMapIter;
public:
TemplateMap m_TMap;
TemplateMapIter m_TMapIter;
int m_iCurIndex;
public:
bgTemplateMap();
~bgTemplateMap();
public:
bool Init();
bool Release();
public:
int Add(Child*);
int Add(const TCHAR* pFileName);
Child* GetPtr(DWORD index);
Child* GetPtr(const TCHAR* szName);
int GetID(Child*);
int GetID(const TCHAR* szName);
int Count();
};
template<class Child>
bgTemplateMap<Child>::bgTemplateMap()
{
m_iCurIndex = 0;
m_TMap.clear();
}
template<class Child>
bgTemplateMap<Child>::~bgTemplateMap()
{
Release();
}
template<class Child>
bool bgTemplateMap<Child>::Init()
{
m_iCurIndex = 0;
m_TMap.clear();
return true;
}
template<class Child>
bool bgTemplateMap<Child>::Release()
{
for (TemplateMapIter Iter = m_TMap.begin(); Iter != m_TMap.end(); Iter++)
{
Child *pPoint = (Child *)(*Iter).second;
if (pPoint)
pPoint->Release();
else
return false;
delete pPoint;
}
m_TMap.clear();
m_iCurIndex = 0;
return true;
}
template<class Child>
int bgTemplateMap<Child>::Add(Child* pChild)
{
if (pChild == NULL)
{
return 0;
}
for (TemplateMapIter Iter = m_TMap.begin(); Iter != m_TMap.end(); Iter++)
{
Child *pPoint = (Child *)(*Iter).second;
if (pPoint == pChild)
{
return 0;
}
}
m_TMap.insert(make_pair(m_iCurIndex++, pChild));
return m_iCurIndex - 1;
}
template<class Child>
int bgTemplateMap<Child>::Add(const TCHAR* pFileName)
{
if (pFileName)
{
TCHAR szFileName[256];
TCHAR Drive[MAX_PATH];
TCHAR Dir[MAX_PATH];
TCHAR FName[MAX_PATH];
TCHAR Ext[MAX_PATH];
_tsplitpath_s(pFileName, Drive, Dir, FName, Ext);
Ext[4] = 0;
_stprintf_s(szFileName, _T("%s%s"), FName, Ext);
for (TemplateMapIter Iter = m_TMap.begin(); Iter != m_TMap.end(); Iter++)
{
Child *pPoint = (Child *)(*Iter).second;
if (!_tcsicmp(pPoint->m_szName.c_str(), szFileName))
{
return (*Iter).first;
}
}
}
Child *pPoint = NULL;
SAFE_NEW(pPoint, Child);
pPoint->Add(m_iCurIndex, pFileName);
m_TMap.insert(make_pair(m_iCurIndex++, pPoint));
return m_iCurIndex - 1;
}
template<class Child>
Child *bgTemplateMap<Child>::GetPtr(DWORD dwIndex)
{
TemplateMapIter Iter = m_TMap.find(dwIndex);
if (Iter == m_TMap.end()) return NULL;
Child *pPoint = (*Iter).second;
return pPoint;
}
template<class Child>
Child* bgTemplateMap<Child>::GetPtr(const TCHAR* szName)
{
for (TemplateMapIter Iter = m_TMap.begin(); Iter != m_TMap.end(); Iter++)
{
Child *pPoint = (Child *)(*Iter).second;
if (!_tcsicmp(pPoint->m_szName.c_str(), szName))
{
return pPoint;
}
}
return NULL;
}
template<class Child>
int bgTemplateMap<Child>::GetID(Child* pChild)
{
int iIndex = -1;
for (TemplateMapIter Iter = m_TMap.begin(); Iter != m_TMap.end(); Iter++)
{
Child *pPoint = (Child *)(*Iter).second;
if (pChild == pPoint)
{
iIndex = (*Iter).first;
break;
}
}
return dwIndex;
}
template<class Child>
int bgTemplateMap<Child>::GetID(const TCHAR* szName)
{
int iIndex = -1;
for (TemplateMapIter Iter = m_TMap.begin(); Iter != m_TMap.end(); Iter++)
{
Child *pPoint = (Child *)(*Iter).second;
if (!_tcsicmp(pPoint->m_szName.c_str(), szName))
{
iIndex = (*Iter).first;
break;
}
}
return iIndex;
}
template<class Child>
int bgTemplateMap<Child>::Count()
{
return (int)m_TMap.size();
}
| true |
ff8bfca1c32e730218fdacdee9ad6f1f248f8c82 | C++ | rastamarco/ComputacaoGrafica | /projetoDois/projFinal/Bird/Head.cpp | UTF-8 | 360 | 2.59375 | 3 | [] | no_license | #include <GL/glut.h>
#include <GL/glu.h>
#include <GL/gl.h>
#include "Pecker.cpp"
class Head
{
public:
Head(float size);
void Draw();
protected:
Pecker b;
float size;
};
Head::Head(float size)
: size(size), b(size/2)
{}
void Head::Draw()
{
glRotatef(-90,0.0,0.0,1.0);
glPushMatrix();
//Cabeca
glutSolidSphere(0.75*size,50,50);
glPopMatrix();
}; | true |
3a284162ed4db6ce189d65e899ab96ed4e8d11c0 | C++ | mfkiwl/ZH | /Matrix.h | GB18030 | 743 | 2.5625 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
class AFX_EXT_CLASS CMatrix //
{
public:
CMatrix(void);
CMatrix(const CMatrix &); //ƹ캯
CMatrix(int i,int j); //ʼС
//CMatrix(const vector<vector<double>> &); //캯
~CMatrix(void);
//
public:
vector<vector<double>> Data;
int acr;
int ver; //
//
public:
void operator=(const CMatrix &);
CMatrix operator+(const CMatrix &);
CMatrix operator+(const double);
CMatrix operator-(const CMatrix &);
CMatrix operator-(const double);
vector<double>& operator[](const int);
CMatrix operator*(const CMatrix &);
CMatrix T(); //ת
CMatrix Inver(); //
};
| true |
b16fa6729afa3bb37659eb47c85209e3e50dcfa2 | C++ | ttyang/sandbox | /sandbox/synchro/boost/synchro/condition_backdoor.hpp | UTF-8 | 2,119 | 2.640625 | 3 | [] | no_license | //////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Vicente J. Botet Escriba 2008-2009. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/synchro for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_SYNCHRO_CONDITION_BACKDOOR__HPP
#define BOOST_SYNCHRO_CONDITION_BACKDOOR__HPP
#include <boost/synchro/lockable_concepts.hpp>
#include <boost/thread/condition.hpp>
#include <boost/synchro/thread/mutex.hpp>
#include <boost/synchro/condition_safe.hpp>
namespace boost { namespace synchro {
template <
class Condition
>
struct condition_backdoor {
condition_backdoor(condition_safe<Condition>&cnd): that_(cnd) {}
template <typename Locker, typename Predicate>
void wait_when(Locker& lock, Predicate pred){
that_.wait_when(lock, pred);
}
template <typename Locker>
void wait(Locker& lock) {
that_.wait(lock);
}
template <typename Locker>
void wait_until(Locker& lock, boost::system_time const& abs_time) {
that_.wait_until(lock, abs_time);
}
template<typename Locker, typename duration_type>
void wait_for(Locker& lock, duration_type const& rel_time) {
that_.wait_for(lock, rel_time);
}
template<typename Locker, typename predicate_type>
void wait_when_until(Locker& lock, predicate_type pred, boost::system_time const& abs_time) {
that_.wait_when_until(lock, pred, abs_time);
}
template<typename Locker, typename predicate_type, typename duration_type>
void wait_when_for(Locker& lock, predicate_type pred, duration_type const& abs_time) {
that_.wait_when_for(lock, pred, abs_time);
}
template <typename Locker>
void notify_one(Locker& lock) {
that_.notify_one(lock);
}
template <typename Locker>
void notify_all(Locker& lock) {
that_.notify_all(lock);
}
private:
condition_safe<Condition>& that_;
};
}
}
#endif
| true |
28d8c738bc2f813001f6e84d818f4a20ee023162 | C++ | osukarusan/particlephysics | /particlesystem/include/SpringForce.h | UTF-8 | 978 | 2.96875 | 3 | [] | no_license | #ifndef _SPRING_FORCE_
#define _SPRING_FORCE_
#include "Force.h"
class SpringForce : public Force
{
public:
SpringForce(void);
virtual ~SpringForce(void);
virtual void apply();
void setEquilibriumPoint(const Vec3d& eqPoint);
void setSpringCoefficient(double ks);
void setDampingCoefficient(double kd);
Vec3d getEquilibriumPoint() const;
double getSpringCoefficient() const;
double getDampingCoefficient() const;
private:
Vec3d m_equilibrium;
double m_ks, m_kd;
};
inline void SpringForce::setEquilibriumPoint(const Vec3d& eqPoint) {
m_equilibrium = eqPoint;
}
inline void SpringForce::setSpringCoefficient(double ks) {
m_ks = ks;
}
inline void SpringForce::setDampingCoefficient(double kd) {
m_kd = kd;
}
inline Vec3d SpringForce::getEquilibriumPoint() const {
return m_equilibrium;
}
inline double SpringForce::getSpringCoefficient() const {
return m_ks;
}
inline double SpringForce::getDampingCoefficient() const {
return m_kd;
}
#endif | true |
a0e4eec1673416f4285a6f62513562cc3220c130 | C++ | LuigiAndMario/AlgoLab | /week6/london/london 1.cpp | UTF-8 | 3,203 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
// BGL include
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/push_relabel_max_flow.hpp>
// Graph Type with nested interior edge properties for flow algorithms
typedef boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS> traits;
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, boost::no_property,
boost::property<boost::edge_capacity_t, long,
boost::property<boost::edge_residual_capacity_t, long,
boost::property<boost::edge_reverse_t, traits::edge_descriptor>>>> graph;
typedef traits::vertex_descriptor vertex_desc;
typedef traits::edge_descriptor edge_desc;
using namespace std;
class edge_adder {
graph &G;
public:
explicit edge_adder(graph &G) : G(G) {}
void add_edge(int from, int to, long capacity) {
auto c_map = boost::get(boost::edge_capacity, G);
auto r_map = boost::get(boost::edge_reverse, G);
const auto e = boost::add_edge(from, to, G).first;
const auto rev_e = boost::add_edge(to, from, G).first;
c_map[e] = capacity;
c_map[rev_e] = 0; // reverse edge has no capacity!
r_map[e] = rev_e;
r_map[rev_e] = e;
}
};
void testcase() {
int h; cin >> h; // height
int w; cin >> w; // width
const int OFFSET = (int)'A';
const int ALPHABET_SIZE = (int)'Z' - OFFSET + 1; // Yes, I could have just written 26, I know...
string note_str; cin >> note_str;
vector<int> note;
for (char &c: note_str) {
note.push_back((int)c - OFFSET);
}
vector<vector<int> > front(h, vector<int>(w));
for (int i = 0 ; i < h ; i++) {
for (int j = 0 ; j < w ; j++) {
char c; cin >> c;
front[i][j] = ((int)c - OFFSET);
}
}
vector<vector<int> > back(h, vector<int>(w));
for (int i = 0 ; i < h ; i++) {
for (int j = 0 ; j < w ; j++) {
char c; cin >> c;
// front[i][j] corresponds to back[i][w - 1 - j]
back[i][w - 1 - j] = ((int)c - OFFSET);
}
}
graph G(ALPHABET_SIZE);
edge_adder adder(G);
const vertex_desc v_source = boost::add_vertex(G);
const vertex_desc v_target = boost::add_vertex(G);
// Adding all the edges of the daily telegraph
for (int i = 0 ; i < h ; i++) {
for (int j = 0 ; j < w ; j++) {
int side1 = front[i][j];
int side2 = back[i][j]; // We already adjusted the indices when parsing the back side of the daily telegraph
adder.add_edge(v_source, side1, 1); // We assume side1 is chosen,
adder.add_edge(side1, side2, 1); // but we stay ready to reverse that decision
}
}
// Adding all edges of the note
for (int i = 0 ; i < note.size() ; i++) {
adder.add_edge(note[i], v_target, 1);
}
long flow = boost::push_relabel_max_flow(G, v_source, v_target);
cout << (flow == note.size() ? "Yes" : "No") << endl;
}
int main() {
int t; cin >> t;
while (t--) {
testcase();
}
return 0;
}
| true |
257a087712ea810385c34f13d90c2f46ed474d2b | C++ | yaohaiyan/Base-Algorithms | /dataStructure/MinPriorityQueue.cpp | UTF-8 | 1,145 | 3.328125 | 3 | [] | no_license | #include "stdafx.h"
#include "MinPriorityQueue.h"
#include <iostream>
MinPriorityQueue::MinPriorityQueue()
{
this->type = MIN_HEAP;
}
MinPriorityQueue::~MinPriorityQueue()
{
}
Element MinPriorityQueue::minimum()
{
return this->queue.at(0); // 可能会越界
}
Element MinPriorityQueue::extractMin()
{
return extractM();
}
void MinPriorityQueue::decreaseKey(int targetIndex, int handle)
{
if (this->queue.at(targetIndex).handle < handle)
{
std::cout << "句柄大于要增加权重的元素的句柄" << std::endl;
return;
}
this->queue.at(targetIndex).handle = handle;
int node = targetIndex;
while (node > 0)
{
int parentIndex = getParentIndex(node);
if (this->queue.at(node).handle > this->queue.at(parentIndex).handle)
{
break;
}
Element larger = this->queue.at(node);
this->queue.at(node) = this->queue.at(parentIndex);
this->queue.at(parentIndex) = larger;
node = parentIndex;
}
}
void MinPriorityQueue::insert(Element element)
{
Element larger;
larger.handle = INT_MAX;
larger.data = element.data;
this->queue.push_back(larger);
decreaseKey(this->queue.size() - 1, element.handle);
}
| true |
83068e8d0978ae26f3b4ad0b4244dc5e4b4c8639 | C++ | jvanns/oodles | /utility/TreeBase.hpp | UTF-8 | 501 | 2.65625 | 3 | [] | no_license | #ifndef OODLES_TREEBASE_HPP
#define OODLES_TREEBASE_HPP
// oodles
#include "NodeBase.hpp"
namespace oodles {
/*
* Bare-bones base class for any Tree type.
* It must remain non-templated and defines
* only necessary, common place methods and
* attributes.
*/
class TreeBase
{
public:
TreeBase();
virtual ~TreeBase();
/*
* Ensure this is a pure virtual (abstract) class
*/
virtual const NodeBase& root() const = 0;
};
} // oodles
#endif
| true |
401169d1ed85c20c15bccef4fcb399f00cd85bc0 | C++ | VysotskiVadim/algorithms_learning | /binary_heap/src/BinaryHeap.hpp | UTF-8 | 6,316 | 3.546875 | 4 | [
"MIT"
] | permissive | #pragma once
#include <memory>
#include "GenericComparer.hpp"
#include <cstring>
#include <sstream>
namespace al {
template <typename T>
class BinaryHeap {
public:
BinaryHeap(
std::unique_ptr< Comparer<T> > comparer,
T *initialHeap,
int size,
int capacity
);
BinaryHeap(std::unique_ptr< Comparer<T> > comparer)
: BinaryHeap(comparer, new T[10], 0, 10) { }
BinaryHeap(T *initialHeap, int size, int capacity)
: BinaryHeap(std::unique_ptr< Comparer<T> >(new GenericComparer<T>), initialHeap, size, capacity) { }
BinaryHeap()
:BinaryHeap(std::unique_ptr< Comparer<T> >(new GenericComparer<T>), new T[10], 0, 10) { }
~BinaryHeap();
int getSize();
int getCapacity();
void insertItem(T item);
bool removeItemFromTop(T &item);
T* getInnerHeap();
T getItem(int index);
void setItem(int index, T item);
private:
int const Threashold = 2;
int _capacity;
int _size;
std::unique_ptr< Comparer<T> > _comparer;
T *_heap;
void exchangeItems(int index1, int index2);
void swim(int index);
bool isTopNode(int index);
int getParentIndex(int index);
bool isMore(int index1, int index2);
bool isLess(int index1, int index2);
void increaseHeapCapacity();
void sink(int index);
bool getMaxChild(int index, int &childIndex);
bool needToDecreaseHeapCapacity();
void decreaseHeapCapacity();
};
template <typename T>
BinaryHeap<T>::BinaryHeap(std::unique_ptr< Comparer<T> > comparer, T *initialHeap, int size, int capacity) :
_heap(initialHeap),
_capacity(capacity),
_size(size),
_comparer(std::move(comparer))
{ }
template <typename T>
BinaryHeap<T>::~BinaryHeap() {
delete [] _heap;
}
template <typename T>
int BinaryHeap<T>::getSize() {
return _size;
}
template <typename T>
int BinaryHeap<T>::getCapacity() {
return _capacity;
}
template <typename T>
T* BinaryHeap<T>::getInnerHeap() {
return _heap;
}
template <typename T>
T BinaryHeap<T>::getItem(int index) {
if (index < 1 || index > _size) {
std::stringstream errorMessage;
errorMessage << "BinaryHeap.getItem: given index is " << index;
throw std::out_of_range(errorMessage.str());
}
return _heap[index - 1];
}
template <typename T>
void BinaryHeap<T>::setItem(int index, T item) {
if (index < 1 || index > _capacity) {
std::stringstream errorMessage;
errorMessage << "BinaryHeap.setItem: given index is " << index;
throw std::out_of_range(errorMessage.str());
}
_heap[index - 1] = item;
}
template <typename T>
void BinaryHeap<T>::exchangeItems(int index1, int index2) {
T firstItem = getItem(index1);
setItem(index1, getItem(index2));
setItem(index2, firstItem);
}
template <typename T>
bool BinaryHeap<T>::isTopNode(int index) {
return index == 1;
}
template <typename T>
bool BinaryHeap<T>::getMaxChild(int index, int &childIndex) {
int firstChildIndex = index * 2;
if (firstChildIndex > getSize()) {
return false;
}
int secondChildIndex = firstChildIndex + 1;
if (secondChildIndex > getSize()) {
childIndex = firstChildIndex;
}
else if (isMore(firstChildIndex, secondChildIndex)) {
childIndex = firstChildIndex;
}
else {
childIndex = secondChildIndex;
}
return true;
}
template <typename T>
int BinaryHeap<T>::getParentIndex(int index) {
int parent = index / 2;
return parent;
}
template <typename T>
bool BinaryHeap<T>::isMore(int index1, int index2) {
return _comparer->compare(getItem(index1), getItem(index2)) > 0;
}
template <typename T>
bool BinaryHeap<T>::isLess(int index1, int index2) {
return _comparer->compare(getItem(index1), getItem(index2)) < 0;
}
template <typename T>
void BinaryHeap<T>::increaseHeapCapacity() {
int newCapacity = getCapacity() * Threashold;
T* newHeap = new T[newCapacity];
std::memcpy(newHeap, _heap, sizeof(T) * getCapacity());
delete [] _heap;
_heap = newHeap;
_capacity = newCapacity;
}
template <typename T>
bool BinaryHeap<T>::needToDecreaseHeapCapacity() {
return getSize() * 4 <= getCapacity();
}
template <typename T>
void BinaryHeap<T>::decreaseHeapCapacity() {
int newCapacity = getCapacity() / 2;
T* newHeap = new T[newCapacity];
std::memcpy(newHeap, _heap, sizeof(T) * getSize());
delete [] _heap;
_heap = newHeap;
_capacity = newCapacity;
}
template <typename T>
void BinaryHeap<T>::swim(int index) {
while (!isTopNode(index) && isMore(index, getParentIndex(index))) {
int parentIndex = getParentIndex(index);
exchangeItems(index, parentIndex);
index = parentIndex;
}
}
template <typename T>
void BinaryHeap<T>::sink(int index) {
int maxChildIndex = -1;
while(getMaxChild(index, maxChildIndex) && !isMore(index, maxChildIndex)){
exchangeItems(index, maxChildIndex);
index = maxChildIndex;
}
}
template <typename T>
void BinaryHeap<T>::insertItem(T item) {
int nextElementPosition = getSize() + 1;
if (nextElementPosition > getCapacity()) {
increaseHeapCapacity();
}
setItem(nextElementPosition, item);
_size++;
swim(nextElementPosition);
}
template <typename T>
bool BinaryHeap<T>::removeItemFromTop(T &item) {
if (getSize() < 1) {
return false;
}
item = getItem(1);
setItem(1, getItem(_size));
_size--;
sink(1);
if (needToDecreaseHeapCapacity()) {
decreaseHeapCapacity();
}
return true;
}
} | true |
73a84dd958cfb0fd6714b8bca9114354731fa3ed | C++ | verioussmith/Arduino-Introductory-Lessons | /LESSON_3-Ardino-For-Loops-And-LED-Circuit/LESSON_3-Ardino-For-Loops-And-LED-Circuit.ino | UTF-8 | 1,012 | 3.203125 | 3 | [] | no_license | int redLEDPin=9; // Declaring red Led Pin as an int and set to 9
int yellowLEDPin=10; // Declaring yellow Led Pin as an int and set it to 10
int redOnTime=100; // This is the red on time
int redOffTime=900; // This is the red off time
int yellowOnTime=10; // This is the yellow on time
int yellowOffTime=500; // This is the yellow off time
int numRedBlink=5; // Number of times to blink the red led
int numYellowBlink=10;
void setup() {
pinMode(redLEDPin, OUTPUT);
pinMode(yellowLEDPin, OUTPUT);
}
void loop() {
for (int j=1; j<=numRedBlink; j=j+1) {
digitalWrite(redLEDPin, HIGH); // Turen the red LED on
delay(redOnTime); // Wait
digitalWrite(redLEDPin, LOW); // Turn the red LED off
delay(redOffTime); // Wait
}
for (int j=1; j<=numYellowBlink; j=j+1) {
digitalWrite(yellowLEDPin, HIGH); // Turen the yellow LED on
delay(yellowOnTime); // Wait
digitalWrite(yellowLEDPin, LOW); // Turn the yellow LED off
delay(yellowOffTime); // Wait
}
}
| true |
5aed94c48257c7613c0c0768d19fff300e512111 | C++ | youridv1/huiswerk | /week2/2_5.cpp | UTF-8 | 293 | 3 | 3 | [] | no_license | #include <iostream>
#include "functions.hpp"
#include <vector>
using namespace std;
int teller(const vector<int> & numbers, const int & x){
int teller = 0;
for(unsigned int i=0; i<numbers.size(); i++){
if(numbers[i] == x){
teller++;
}
}return teller;
} | true |
3555b20eedf3ab1ef9f332b1c1c7e99b9cd50e15 | C++ | gmeisinger/hackrpg | /src/global.cpp | UTF-8 | 936 | 2.796875 | 3 | [] | no_license |
#include "include/global.h"
int screen_w = SCREEN_WIDTH;
int screen_h = SCREEN_HEIGHT;
int tile_s = TILE_SIZE;
Player *player;
//loads image at specified path as a texture
//fname = relative path to image
SDL_Texture* utils::loadTexture(SDL_Renderer* renderer, std::string fname) {
//the final texture
SDL_Texture* newTexture = nullptr;
//load the image
SDL_Surface* startSurf = IMG_Load(fname.c_str());
if (startSurf == nullptr) {
std::cout << "Unable to load image " << fname << "! SDL Error: " << SDL_GetError() << std::endl;
return nullptr;
}
//color key
SDL_SetColorKey(startSurf, SDL_FALSE, SDL_MapRGB(startSurf->format, 0, 0xFF, 0xFF));
//create texture from image
newTexture = SDL_CreateTextureFromSurface(renderer, startSurf);
if (newTexture == nullptr) {
std::cout << "Unable to create texture!" << std::endl;
}
//free original surface
SDL_FreeSurface(startSurf);
return newTexture;
} | true |
9aa8a2826941b67c9207b43582e55d8e64ccb6aa | C++ | mayankamencherla/cracking-the-coding-interview-solutions | /sorting-and-searching/common-sorting-algorithms.cpp | UTF-8 | 2,730 | 3.9375 | 4 | [
"MIT"
] | permissive | /**
* Some common sorting algorithms
*/
#include <vector>
#include <iostream>
using namespace std;
vector<int> selectionSort(vector<int> v, int index)
{
if (index >= v.size()) return v;
int minIndex = index;
int minValue = v[minIndex];
for (int i=index; i<v.size(); i++)
{
if (v[i] < minValue)
{
minValue = v[i];
minIndex = i;
}
}
swap(v[index], v[minIndex]);
return selectionSort(v, index+1);
}
int computePivot(vector<int>& v, int start, int end)
{
// Random index between [start, end] chosen as pivot
int random = start + rand() % (end - start + 1);
swap(v[start], v[random]);
int l = start+1;
int value = v[start];
for (int i=start+1; i<=end; i++)
{
if (v[i] <= value)
{
swap(v[i], v[l]);
l++;
}
}
swap(v[start], v[l-1]);
return l-1;
}
void quickSort(vector<int>& v, int start, int end)
{
if (start > end) return;
int pivot = computePivot(v, start, end);
quickSort(v, start, pivot-1);
quickSort(v, pivot+1, end);
}
vector<int> quickSort(vector<int>& v)
{
vector<int> res = v;
quickSort(res, 0, v.size()-1);
return res;
}
void merge(vector<int>& v, int start, int mid, int end)
{
// Merge v[start ... mid] and v[mid+1 ... end]
int numElems = (end - start + 1);
vector<int> res(numElems, 0);
int ind1 = start; int ind2 = mid+1;
for (int i=0; i<numElems; i++)
{
if (ind2 > end || (ind2 <= end && ind1 <= mid && v[ind1] <= v[ind2]))
{
res[i] = v[ind1];
ind1++;
}
else
{
res[i] = v[ind2];
ind2++;
}
}
for (int i=start; i<=end; i++) v[i] = res[i-start];
}
void mergeSort(vector<int>& v, int start, int end)
{
if (start >= end) return;
int mid = (start + end) / 2;
mergeSort(v, start, mid);
mergeSort(v, mid+1, end);
merge(v, start, mid, end);
}
vector<int> mergeSort(vector<int>& v)
{
vector<int> res = v;
mergeSort(res, 0, v.size()-1);
return res;
}
void printArray(vector<int>& v, string message)
{
printf("%s\n", message.c_str());
for (int elem : v) cout << elem << " ";
cout << endl;
}
int main()
{
vector<int> v = {10, 7, 4, 5, 1, 2, 8, 9, 3, 6};
printArray(v, "Pre selection sort");
vector<int> v1 = selectionSort(v, 0);
printArray(v1, "Using selection sort");
cout << endl;
printArray(v, "Pre quick sort");
v1 = quickSort(v);
printArray(v1, "quick sort");
cout << endl;
printArray(v, "Pre merge sort");
v1 = mergeSort(v);
printArray(v1, "merge sort");
} | true |
7e6ae3b2ef8a91842654d46aa31607189b7cd78e | C++ | raulMrello/RoboticPlant | /src/Shifter/Shifter.h | ISO-8859-1 | 3,280 | 2.578125 | 3 | [] | no_license | /*
Copyright (c) 2017 @raulMrello
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@file Shifter.h
@purpose Serial to parallel shift register controller
@version v1.0
@date Jun 2017
@author @raulMrello
*/
#ifndef __SHIFTER_H
#define __SHIFTER_H
#include "mbed.h"
#include "Logger.h"
/**
* @author raulMrello
* @see API
*
* <b>Shifter</b> Clase que paraleliza datos seria, controlando una serie de registros dedesplazamiento
* conectados en cascada, para conseguir un nmero de salidas N en paralelo y sincronizadas.
*/
class Shifter {
public:
/** Shifter()
*
* Constructor.
* Configura los gpio necesarios para controlar el registro de desplazamiento
* @param gpio_oe Salida para controla el registro de salida a los pines fsicos /OE
* @param gpio_srclr Salida para controlar el reset del registro de desplazamiento /SRCLR
* @param gpio_rclk Salida de reloj del registro de desplazamiento RCLK _/\_
* @param gpio_srclk Salida de reloj del registro de acumulacin SRCLK _/\_
* @param gpio_ser Salida para inyectar datos serie
* @param logger Objeto logger
*/
Shifter(PinName gpio_oe, PinName gpio_srclr, PinName gpio_rclk, PinName gpio_srclk, PinName gpio_ser, Logger* logger);
/** write()
*
* Paraleliza un stream de datos serie, de tamao "count"
* @param data Stream de datos para actualizar las salidas del registro a un valor deseado.
* @param count Nmero de bits del registro a controlar
*/
void write(uint8_t* data, uint8_t count);
/** simulate()
*
* Simula un envo de datos. til para realizar pruebas funcionales sin enviar movimientos a los motores y poder verificar
* rangos mximos sin que sufra la estructura si hay algn error de implementacin.
* @param data Stream de datos para actualizar las salidas del registro a un valor deseado.
* @param count Nmero de bits del registro a controlar
*/
void simulate(uint8_t* data, uint8_t count){}
protected:
DigitalOut* _out_oe;
DigitalOut* _out_srclr;
DigitalOut* _out_rclk;
DigitalOut* _out_srclk;
DigitalOut* _out_ser;
Logger* _logger;
private:
};
#endif
| true |
fa054557e0c0f3dd13e71b831598239faad433e1 | C++ | elancha98/PracticaPro2 | /program.cc | UTF-8 | 2,565 | 3.1875 | 3 | [] | no_license | //
// Created by ernesto on 23/04/17.
//
/**
* @mainpage Reads commands from the console and executes them.
* It reads a Specie, a initial population and then performs operations over
* that population. Operations like adding a new Organism, reproduce two members
* or print the genotype of an Organism.
* @brief Reads commands from the console and executes them
*/
#include <iostream>
#include "Specie.hh"
using namespace std;
int main() {
// SETUP |
Specie specie = Specie::read();
string name, n1, n2, n3;
// MAIN LOOP
while (cin >> name and name != "acabar") {
if (name == "anadir_individuo") {
cin >> n1;
cout << name << " " << n1 << endl;
Organism o = specie.read_organism();
bool b = specie.add_organism(n1, o);
if (b == false)
cout << " error" << endl;
} else if (name == "reproduccion_sexual") {
cin >> n1 >> n2 >> n3;
cout << name << " " << n1 << " " << n2 << " " << n3 << endl;
try {
if (not specie.reproduce(n1, n2, n3))
cout << " no es posible reproduccion" << endl;
} catch (invalid_argument& e) {
cout << " error" << endl;
}
} else if (name == "escribir_arbol_genealogico") {
cin >> n1;
cout << name << " " << n1;
try {
specie.write_genealogical_tree(n1);
} catch (invalid_argument& e) { cout << endl << " error" << endl; }
} else if (name == "completar_arbol_genealogico") {
cin >> n1;
cout << name << " " << n1 << endl;
pair<queue<string>, bool> s = specie.check_genealogical_tree(n1);
if (s.second) {
cout << " ";
while (!s.first.empty()) {
cout << s.first.front();
s.first.pop();
}
cout << endl;
} else
cout << " no es arbol parcial" << endl;
} else if (name == "escribir_poblacion") {
cout << name << endl;
specie.write();
} else if (name == "escribir_genotipo") {
cin >> n1;
cout << name << " " << n1 << endl;
try {
specie.get(n1).write_genotype();
} catch (invalid_argument& e) { cout << " error" << endl; }
} else {
throw invalid_argument(" Invalid command");
}
}
cout << name << endl;
}
| true |
df0273b6417d2fc10f23749982e6f5d5c300577f | C++ | julioCoutinho/URI | /2510.cpp | UTF-8 | 279 | 2.78125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int t;
cin >>t;
while(t-->0)
{
string nome;
cin >> nome;
if(nome == "batmain")
cout << 'N' << endl;
else
cout << 'Y' << endl;
}
return 0;
}
| true |
a5b62ebee8ecc3712ed68978c83f1511ec3e62dc | C++ | Chainsawkitten/UltimateGolf19XX | /src/Editor/GUI/HorizontalLayout.cpp | UTF-8 | 1,026 | 2.78125 | 3 | [
"MIT"
] | permissive | #include "HorizontalLayout.hpp"
#include <Core/Resources.hpp>
namespace GUI {
HorizontalLayout::HorizontalLayout(Widget* parent) : Container(parent) {
rectangle = Resources().CreateRectangle();
nextPosition = glm::vec2(0.f, 0.f);
}
HorizontalLayout::~HorizontalLayout() {
Resources().FreeRectangle();
}
void HorizontalLayout::Render(const glm::vec2& screenSize) {
// Set color.
glm::vec3 color(0.06666666666f, 0.06274509803f, 0.08235294117f);
rectangle->Render(Position(), size, color, screenSize);
RenderWidgets(screenSize);
}
void HorizontalLayout::AddWidget(Widget* widget) {
Container::AddWidget(widget);
widget->SetPosition(Position() + nextPosition);
nextPosition.x += widget->Size().x;
}
glm::vec2 HorizontalLayout::Size() const {
return this->size;
}
void HorizontalLayout::SetSize(const glm::vec2& size) {
this->size = size;
}
}
| true |
10b298faae91567adb00c993c623a9a80c5f702a | C++ | singhsiddharth10/LuvBabbar450 | /dsanalgo/NegativeAndPositive.cpp | UTF-8 | 386 | 3 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
void negativeAndPositive(int arr[], int n){
int j=0;
for(int i = 0; i < n; i++){
if(arr[i] < 0){
if(i != j){
swap(arr[i], arr[j]);
}
j++;
}
}
}
int main(){
int n;
cin>>n;
int arr[n];
for(int i = 0; i < n; ++i)cin>>arr[i];
negativeAndPositive(arr,n);
for(int i = 0; i < n; ++i)cout<<arr[i]<<" ";
return 0;
}
| true |
0d76e915278e241c6453b3c60d137e86e22156aa | C++ | mdub555/OS-Project-3 | /src/simulation.cpp | UTF-8 | 11,471 | 3.125 | 3 | [] | no_license | #include "simulation.h"
#include "types/event.h"
#include <cassert>
#include <fstream>
#include <iostream>
using namespace std;
void Simulation::run(const string& filename) {
read_file(filename);
// While their are still events to process, invoke the corresponding methods
// to handle them.
while (!events.empty()) {
const Event* event = events.top();
events.pop();
// Invoke the appropriate method on the scheduler for the given event type.
switch (event->type) {
case Event::THREAD_ARRIVED:
handle_thread_arrived(event);
break;
case Event::THREAD_DISPATCH_COMPLETED:
handle_thread_dispatch_completed(event);
break;
case Event::PROCESS_DISPATCH_COMPLETED:
handle_process_dispatch_completed(event);
break;
case Event::CPU_BURST_COMPLETED:
handle_cpu_burst_completed(event);
break;
case Event::IO_BURST_COMPLETED:
handle_io_burst_completed(event);
break;
case Event::THREAD_COMPLETED:
handle_thread_completed(event);
break;
case Event::THREAD_PREEMPTED:
handle_thread_preempted(event);
break;
case Event::DISPATCHER_INVOKED:
handle_dispatcher_invoked(event);
break;
}
// change some of the stats in SystemStats
stats.total_time = event->time;
// print out for verbose output
// output on a non-null event that changed state
if (event->thread) {
if (event->thread->current_state != event->thread->previous_state) {
logger.print_state_transition(event,
event->thread->previous_state,
event->thread->current_state);
}
}
// Free the event's memory.
delete event;
}
for (pair<int, Process*> entry : processes) {
logger.print_process_details(entry.second);
}
logger.print_statistics(calculate_statistics());
}
//==============================================================================
// Event-handling methods
//==============================================================================
void Simulation::handle_thread_arrived(const Event* event) {
// this is probably handled correctly (done in class)
assert(event->thread->current_state == Thread::State::NEW);
// set the thread state to ready
event->thread->set_state(Thread::State::READY, event->time);
assert(event->thread->current_state == Thread::State::READY);
// add the thread to the queue
scheduler->enqueue(event, event->thread);
// create a new event to put on the queue
invoke_dispatcher(event->time);
}
void Simulation::handle_thread_dispatch_completed(const Event* event) {
assert(event->thread->current_state == Thread::State::READY);
// set the thread running
event->thread->set_state(Thread::State::RUNNING, event->time);
// update the previously running thread
prev_thread = active_thread;
active_thread = event->thread;
// create a new event based on the time slice and thread length
assert(event->thread->bursts.front()->type == Burst::Type::CPU);
size_t burst_length = event->thread->bursts.front()->length;
// make a copy of the scheduling decision since the old one will be deleted
SchedulingDecision* dec = new SchedulingDecision();
dec->thread = event->scheduling_decision->thread;
dec->time_slice = event->scheduling_decision->time_slice;
dec->explanation = event->scheduling_decision->explanation;
size_t time_slice = dec->time_slice;
if (time_slice < burst_length) { // thread gets preempted
Event* e = new Event(Event::Type::THREAD_PREEMPTED,
event->time + time_slice,
event->thread,
dec);
add_event(e);
stats.service_time += time_slice;
} else {
Event* e = new Event(Event::Type::CPU_BURST_COMPLETED,
event->time + burst_length,
event->thread);
add_event(e);
stats.service_time += burst_length;
}
}
void Simulation::handle_process_dispatch_completed(const Event* event) {
// a process dispatch does the same thing as a thread dispatch, so we call
// that function here. This function is still used in order for the
// output to work correctly.
handle_thread_dispatch_completed(event);
}
void Simulation::handle_cpu_burst_completed(const Event* event) {
// pop burst from queue
assert(event->thread->bursts.front()->type == Burst::Type::CPU);
event->thread->bursts.pop();
// unset current_thread
prev_thread = active_thread;
active_thread = nullptr;
// invoke the dispatcher
invoke_dispatcher(event->time);
// add new event based on if this is the last CPU burst
Event* e;
if (event->thread->bursts.size() == 0) { // last CPU burst
e = new Event(Event::Type::THREAD_COMPLETED, event->time, event->thread);
} else {
event->thread->set_state(Thread::State::BLOCKED, event->time);
e = new Event(Event::Type::IO_BURST_COMPLETED,
event->time + event->thread->bursts.front()->length,
event->thread);
}
add_event(e);
}
void Simulation::handle_io_burst_completed(const Event* event) {
assert(event->thread->current_state == Thread::State::BLOCKED);
// set corresponding thread to ready
event->thread->set_state(Thread::State::READY, event->time);
// pop the io burst
assert(event->thread->bursts.front()->type == Burst::Type::IO);
// change the system stats first
stats.io_time += event->thread->bursts.front()->length;
event->thread->bursts.pop();
// enqueue the thread in the scheduler
scheduler->enqueue(event, event->thread);
// invoke the dispatcher
invoke_dispatcher(event->time);
}
void Simulation::handle_thread_completed(const Event* event) {
// set the thread state to exit
assert(event->thread->current_state == Thread::State::RUNNING);
event->thread->set_state(Thread::State::EXIT, event->time);
// the dispatcher has already been invoked by this time (in handle_cpu_burst_completed), there is
// no need to call it again
}
void Simulation::handle_thread_preempted(const Event* event) {
// set the thread to ready
assert(event->thread->current_state == Thread::State::RUNNING);
event->thread->set_state(Thread::State::READY, event->time);
// decrease cpu burst
assert(event->thread->bursts.front()->type == Burst::Type::CPU);
assert((size_t)event->thread->bursts.front()->length > event->scheduling_decision->time_slice);
event->thread->bursts.front()->length -= event->scheduling_decision->time_slice;
// enqueue the thread in the scheduler
scheduler->enqueue(event, event->thread);
prev_thread = active_thread;
active_thread = nullptr;
invoke_dispatcher(event->time);
}
void Simulation::handle_dispatcher_invoked(const Event* event) {
// get current desicion and set the current thread
SchedulingDecision* dec = scheduler->get_next_thread(event);
// check for decision
if (dec == nullptr) return;
Thread* next_thread = dec->thread;
// check for next thread
if (next_thread == nullptr) return;
Event* e;
if (prev_thread == nullptr || next_thread->process != prev_thread->process) { // process switch
e = new Event(Event::Type::PROCESS_DISPATCH_COMPLETED,
event->time + process_switch_overhead,
next_thread,
dec);
// change the system stats
stats.dispatch_time += process_switch_overhead;
} else { // thread switch
e = new Event(Event::Type::THREAD_DISPATCH_COMPLETED,
event->time + thread_switch_overhead,
next_thread,
dec);
stats.dispatch_time += thread_switch_overhead;
}
add_event(e);
// the logger won't print for DISPATCHER_INVOKED since it is called with a nullptr thread,
// call it in this function for the custom message
logger.print_verbose(event, e->thread, dec->explanation);
active_thread = next_thread; // set here to show that the processor is busy
}
void Simulation::invoke_dispatcher(const int time) {
// if the provessor is idle, add a dispatch event
if (active_thread == nullptr) {
Event* e = new Event(Event::Type::DISPATCHER_INVOKED, time, nullptr);
add_event(e);
}
}
//==============================================================================
// Utility methods
//==============================================================================
void Simulation::add_event(Event* event) {
if (event != nullptr) {
events.push(event);
}
}
void Simulation::read_file(const string& filename) {
ifstream file(filename.c_str());
if (!file) {
cerr << "Unable to open simulation file: " << filename << endl;
exit(EXIT_FAILURE);
}
size_t num_processes;
// Read the total number of processes, as well as the dispatch overheads.
file >> num_processes >> thread_switch_overhead >> process_switch_overhead;
// Read in each process.
for (size_t p = 0; p < num_processes; p++) {
Process* process = read_process(file);
processes[process->pid] = process;
}
}
Process* Simulation::read_process(istream& in) {
int pid, type;
size_t num_threads;
// Read in the process ID, its type, and the number of threads.
in >> pid >> type >> num_threads;
// Create the process and register its existence in the processes map.
Process* process = new Process(pid, (Process::Type) type);
// Read in each thread in the process.
for (size_t tid = 0; tid < num_threads; tid++) {
process->threads.push_back(read_thread(in, tid, process));
}
return process;
}
Thread* Simulation::read_thread(istream& in, int tid, Process* process) {
int arrival_time;
size_t num_cpu_bursts;
// Read in the thread's arrival time and its number of CPU bursts.
in >> arrival_time >> num_cpu_bursts;
Thread* thread = new Thread(arrival_time, tid, process);
// Read in each burst in the thread.
for (size_t n = 0, burst_length; n < num_cpu_bursts * 2 - 1; n++) {
in >> burst_length;
Burst::Type burst_type = (n % 2 == 0)
? Burst::CPU
: Burst::IO;
thread->bursts.push(new Burst(burst_type, burst_length));
}
// Add an arrival event for the thread.
events.push(new Event(Event::THREAD_ARRIVED, thread->arrival_time, thread));
return thread;
}
SystemStats Simulation::calculate_statistics() {
stats.total_cpu_time = stats.service_time + stats.dispatch_time;
stats.total_idle_time = stats.total_time - stats.total_cpu_time;
stats.cpu_utilization = (double)stats.total_cpu_time / (double)stats.total_time * 100.0;
stats.cpu_efficiency = (double)stats.service_time / (double)stats.total_time * 100.0;
// sum up all the threads and their reponse and turnaround times
for (pair<int, Process*> entry : processes) {
Process* proc = entry.second;
stats.thread_counts[proc->type] += proc->threads.size();
double res_time = 0.0;
double ta_time = 0.0;
for (Thread* t : proc->threads) {
res_time += t->response_time();
ta_time += t->turnaround_time();
}
stats.avg_thread_response_times[proc->type] += res_time;
stats.avg_thread_turnaround_times[proc->type] += ta_time;
}
// make the stats averages
for (int i = 0; i < 4; i++) {
// don't divide by zero
if (stats.thread_counts[i] > 0) {
stats.avg_thread_response_times[i] /= stats.thread_counts[i];
stats.avg_thread_turnaround_times[i] /= stats.thread_counts[i];
}
}
return stats;
}
| true |
874cc406ce4f947b7bd4ad4b6017375a8287c02f | C++ | rushingfox/AlgorithmHomework | /homework3/question3/question3.cpp | GB18030 | 1,121 | 3 | 3 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
const string arr1 = "apple";
const string arr2 = "peach";
const int m = 5;
const int n = 5;
vector<char> result;
void solvedp(int(&dp)[m + 1][n + 1]);
int main()
{
int dp[m+1][n+1];
solvedp(dp);
int i = m ;
int j = n ;
while (i!=0||j!=0)
{
if (i>=1&&dp[i-1][j]==dp[i][j])
{
result.push_back(arr1[i - 1]);
i-=1;
}
else if (j>=1&&dp[i][j-1]==dp[i][j])
{
result.push_back(arr2[j - 1]);
j -= 1;
}
else if (i>=1&&j>=1&&dp[i][j-1]!=dp[i][j]&&dp[i-1][j]!=dp[i][j])//ʱarr1[i-1]arr2[j-1]
{
result.push_back(arr1[i - 1]);
i -= 1;
j -= 1;
}
}
for (int i = result.size()-1; i>=0; i--)
{
cout << result[i];
}
system("pause");
return 0;
}
void solvedp(int (&dp)[m+1][n+1])
{
for (int i = 0; i < m + 1; i++)
{
for (int j = 0; j < n + 1; j++)
{
if (i==0||j==0)
{
dp[i][j] = 0;
}
else
{
if (arr1[i - 1] == arr2[j - 1])
{
dp[i][j] = dp[i - 1][j - 1] + 1;
}
else
{
dp[i][j] = dp[i][j - 1] > dp[i - 1][j] ? dp[i][j - 1] : dp[i - 1][j];
}
}
}
}
} | true |
5d52e71fa2843a4e1ce8aebb22af98234ee0d736 | C++ | EnsekiTT/wasa-ailot | /Arduino/IMU_Fusion_Board/IMU_Fusion_Board.ino | UTF-8 | 4,740 | 2.8125 | 3 | [] | no_license | /* IMU Fusion Board - ADXL345 & IMU3000
Example Arduino Sketch to read the Gyro and Accelerometer Data
Written by www.hobbytronics.co.uk
See the latest version at www.hobbytronics.co.uk/arduino-adxl345-imu3000
08-Apr-2011
*/
#define GYRO 0x68 // gyro I2C address
#define GYRO_XOUT_H 0x1D // IMU-3000 Register address for GYRO_XOUT_H
#define REG_TEMP 0x1B // IMU-3000 Register address for
#define ACCEL 0x53 // Accel I2c Address
#define ADXL345_POWER_CTL 0x2D
#define PI 3.14159265358979
byte buffer[14]; // Array to store ADC values
float gyro_x;
float gyro_y;
float gyro_z;
float accel_x;
float accel_y;
float accel_z;
float RwAcc[3]; //normalized accel vector(x,y,z)
float RwGyro[3]; //Gyro data (x,y,z)
float temp;
unsigned long curtime;
unsigned long oldTime = 0;
unsigned long newTime;
unsigned long interval;
int i;
long sum_x = 0;
long sum_y = 0;
long sum_z = 0;
#include <Wire.h>
void setup()
{
Serial.begin(57600);
Wire.begin();
// Set Gyro settings
// Sample Rate 1kHz, Filter Bandwidth 42Hz, Gyro Range 500 d/s
writeTo(GYRO, 0x16, 0x1B);
//set accel register data address
writeTo(GYRO, 0x18, 0x32);
// set accel i2c slave address
writeTo(GYRO, 0x14, ACCEL);
// Set passthrough mode to Accel so we can turn it on
writeTo(GYRO, 0x3D, 0x08);
// set accel power control to 'measure'
writeTo(ACCEL, ADXL345_POWER_CTL, 8);
// set accel range to +-2 g, and change accel output to MSB
writeTo(ACCEL, 0x31, 0x04);
//cancel pass through to accel, gyro will now read accel for us
writeTo(GYRO, 0x3D, 0x28);
writeTo(GYRO, 0x0C, 0xFF);
writeTo(GYRO, 0x0D, 0xc0);
writeTo(GYRO, 0x0E, 0xFF);
writeTo(GYRO, 0x0F, 0x8b);
writeTo(GYRO, 0x10, 0x00);
writeTo(GYRO, 0x11, 0x0c);
Serial.println("Start");
}
// Write a value to address register on device
void writeTo(int device, byte address, byte val) {
Wire.beginTransmission(device); // start transmission to device
Wire.write(address); // send register address
Wire.write(val); // send value to write
Wire.endTransmission(); // end transmission
}
void loop()
{
// Read the Gyro X, Y and Z and Accel X, Y and Z all through the gyro
// First set the register start address for X on Gyro
Wire.beginTransmission(GYRO);
Wire.write(REG_TEMP); //Register Address GYRO_XOUT_H
Wire.endTransmission();
// New read the 14 data bytes
Wire.beginTransmission(GYRO);
Wire.requestFrom(GYRO,14); // Read 14 bytes
i = 0;
while(Wire.available())
{
buffer[i] = Wire.read();
i++;
}
Wire.endTransmission();
curtime = micros();
newTime = curtime;
interval = newTime - oldTime;
oldTime = newTime;
//Combine bytes into integers
temp = buffer[0] << 8 | buffer[1];
// Gyro format is MSB first
gyro_x = buffer[2] << 8 | buffer[3];
gyro_y = buffer[4] << 8 | buffer[5];
gyro_z = buffer[6] << 8 | buffer[7];
// Accel is LSB first. Also because of orientation of chips
// accel y output is in same orientation as gyro x
// and accel x is gyro -y
accel_x = buffer[9] << 8 | buffer[8];
accel_y = buffer[11] << 8 | buffer[10];
accel_z = buffer[13] << 8 | buffer[12];
//accel vector
RwAcc[0] = accel_x;
RwAcc[1] = accel_y;
RwAcc[2] = accel_z;
normalize3DVector(RwAcc);
temp = map(temp,-32768,2048,-40.00,85.00);
// Print out what we have
sum_x += gyro_x;
sum_y += gyro_y;
sum_z += gyro_z;
Serial.print(sum_x); // echo the number received to screen
Serial.print(",");
Serial.print(sum_y); // echo the number received to screen
Serial.print(",");
Serial.print(sum_z); // echo the number received to screen
Serial.print(",");
Serial.print(temp);
Serial.print(",");
Serial.print(gyro_x); // echo the number received to screen
Serial.print(",");
Serial.print(gyro_y); // echo the number received to screen
Serial.print(",");
Serial.print(gyro_z); // echo the number received to screen
Serial.print(",");
Serial.print(RwAcc[0]); // echo the number received to screen
Serial.print(",");
Serial.print(RwAcc[1]); // echo the number received to screen
Serial.print(",");
Serial.print(RwAcc[2]); // echo the number received to screen
Serial.println(""); // prints carriage return
delay(10); // wait for a second
}
void normalize3DVector(float* vector) {
static float R;
R = sqrt(vector[0]*vector[0] + vector[1]*vector[1] + vector[2]*vector[2]);
vector[0] /= R;
vector[1] /= R;
vector[2] /= R;
}
| true |