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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
b86998a619ce18966027bd411231050b05998697 | C++ | mettledrum/Dijkstra_vs_Bellman-Ford | /Dijkstra/unionFunctions.cpp | UTF-8 | 2,253 | 3.328125 | 3 | [] | no_license | //Andrew Hoyle 810-32-3651
//3412 Algorithms
//Dijkstra's Algorithm
//3/21/12
#include <limits>
#include "unionFunctions.h"
void greeting()
{
std::cout << "Dijkstra's algorithm using only positive, directed edges...\n"
"Also, nodes cannot be connected to themselves./n"
"The nodes will be assigned \"parent\" values and weights from the\n"
"parent values. A MCST can be traced from the starting node to any\n"
"other node in the connected graph whose edges are typed in the\n"
"\"edges\" file. Please press any key and then <ENTER> to continue.\n";
char c;
std::cin >> c;
std::cout << std::endl;
}
void describeMatrix()
{
std::cout << "Here is the adjacency matrix based on the \"edges\" infile:\n";
}
//add some error checking
int getStartNode(const int& vn)
{
std::cout << "Please enter the node number you want the MCST to begin on\n"
"followed by <ENTER>. It must be larger or equal to 1, and less than\n"
"or equal to " << vn << ".\n";
int tempInt;
std::cin >> tempInt;
return tempInt;
}
simpVert extract_min(std::vector<simpVert>& sv)
{
//make a temp simpVert with awfully large numbers
simpVert theMin;
theMin.key=std::numeric_limits<int>::max();
theMin.extracted=false;
theMin.label=std::numeric_limits<int>::max();
theMin.parent=std::numeric_limits<int>::max();
for(int i=0; i<sv.size(); ++i)
{
//<= is NECESSARY because you don't want SEG FAULT from the Min!
if( (sv[i].key<=theMin.key) && (sv[i].extracted==false) )
theMin=sv[i];
}
return theMin;
}
void displayDijk(const std::vector<simpVert>& sv)
{
//show source node
for(int i=0; i<sv.size(); ++i)
{
if(sv[i].key==0)
std::cout << "vertex: " << sv[i].label << " is SOURCE";
else
std::cout << "vertex: " << sv[i].label << " has parent: " << sv[i].parent << ", and key: " << sv[i].key;
std::cout << std::endl;
}
}
void describeDijk()
{
std::cout << "Here is the output of vertices with their parents and keys:\n";
}
size_t getMatrixDims(std::ifstream& inny)
{
size_t tempNumb;
inny >> tempNumb;
return tempNumb;
}
| true |
3cd7086b9054782f4e9a3035bd5d6c1ee8ff4abe | C++ | ProfessionalLearner/c-plus-plus-red-belt | /Week 3/Programming Assignment 2/src/swap_sort_copy.cpp | UTF-8 | 1,016 | 3.53125 | 4 | [] | no_license | #include <vector>
#include <algorithm>
#include <memory>
#include <numeric>
using namespace std;
template <typename T>
void Swap(T* first, T* second) {
auto temp = *first;
*first = *second;
*second = temp;
}
template <typename T>
void SortPointers(vector<T*>& pointers) {
sort(begin(pointers), end(pointers), [](T* lhs, T* rhs) {
return *lhs < *rhs;
});
}
template <typename T>
void ReversedCopy(T* source, size_t count, T* destination) {
auto src_begin = source;
auto src_end = source + count;
auto dst_begin = destination;
auto dst_end = destination + count;
if(dst_end <= src_begin || src_end <= dst_begin) {
reverse_copy(src_begin, src_end, dst_begin);
} else if(dst_begin > src_begin) {
for (size_t i = 0; src_begin + i < dst_begin; i++) {
*(dst_end - 1 - i) = *(src_begin + i);
}
reverse(dst_begin, src_end);
} else {
for(size_t i = 0; src_end - 1 - i >= dst_end; i++) {
*(dst_begin + i) = *(src_end - 1 - i);
}
reverse(src_begin, dst_end);
}
}
int main() {
return 0;
}
| true |
e3856615254f480230c8820e836f9b51b2343446 | C++ | MOIPA/MyAlgorithm | /C++/斐波那契数列.cpp | UTF-8 | 240 | 3.40625 | 3 | [] | no_license | #include<iostream>
using namespace std;
int Fibsequence(int n) {
if (n == 0)return 0;
if (n == 1)return 1;
if (n > 1) return Fibsequence(n - 1)+Fibsequence(n-2);
}
int main(void) {
int n;
cin >> n;
cout<<Fibsequence(n);
return 0;
} | true |
20648d69493e2d4a9c5b4de24a0f46f51ee707a6 | C++ | GhulamMustafaGM/C-Programming | /01-C++ Programing/33.cpp | UTF-8 | 497 | 4.15625 | 4 | [] | no_license | /*C++ program - calcuate area and circumference of circle */
#include <iostream>
using namespace std;
int main()
{
float r, area, circum;
cout << "\nEnter the radious of the circle:";
cin >> r;
area = 3.14 * r * r;
circum = 2 * 3.14 * r;
cout << "Area of the circle = " << area << "\nCircumference of the circle = "
<< circum << endl;
return 0;
}
/*output
Enter the radious of the circle:5
Area of the circle = 78.5
Circumference of the circle = 31.4
*/ | true |
92a6bc04e771cd42849bd2e55c1c0b3f7d9274b6 | C++ | Gkx1995/BSON_doc_filter | /filter_generator.cpp | UTF-8 | 22,189 | 2.578125 | 3 | [] | no_license | //
// Created by kai on 8/3/18.
//
#include "filter_generator.h"
//////////////////////////////////////////////////////////
// Filter methods
//////////////////////////////////////////////////////////
using namespace CommonConstants;
// Constructor
Filter::Filter(std::string& query, const std::string& shard_keys) {
perform_pegtl_parser(query, shard_keys);
}
// Destructor
Filter::~Filter() {
long filters_size;
filters_size = filters.size();
for (auto i = 0; i < filters_size; i++) {
bson_destroy(filters.at(i));
}
delete(&arg_map);
}
void Filter::perform_pegtl_parser(std::string& query, const std::string& shard_keys) {
auto* parser = new Parser();
parser->perform_pegtl_parser(query, arg_map);
generate_data_type_map();
try {
generate_filters();
} catch (const char *msg) {
std::cerr << msg << std::endl;
}
append_shard_keys_and_id(shard_keys);
}
void Filter::append_shard_keys_and_id(const std::string &shard_keys) {
std::istringstream iss(shard_keys);
std::string shard_key;
std::string _id;
extra_select_count = 0;
while (std::getline(iss, shard_key, ' ')) {
if (!shard_key.empty()
&& std::find(arg_map[SELECTED_FIELD_LIST].begin(), arg_map[SELECTED_FIELD_LIST].end(), shard_key) == arg_map[SELECTED_FIELD_LIST].end()) {
arg_map[SELECTED_FIELD_LIST].push_back(shard_key);
extra_select_count++;
std::cout << "Query not included shard key. Adding shard key to select_fields_list: " << shard_key << std::endl;
}
}
_id = "_id";
if (std::find(arg_map[SELECTED_FIELD_LIST].begin(), arg_map[SELECTED_FIELD_LIST].end(), _id) == arg_map[SELECTED_FIELD_LIST].end()) {
arg_map[SELECTED_FIELD_LIST].push_back(_id);
extra_select_count++;
std::cout << "Query not included _id. Adding shard key to select_fields_list: " << _id << std::endl;
}
}
const bson_t* Filter::get_input_doc_if_satisfied_filter (const bson_t* input_doc) {
Projector* projector = NULL;
if (!should_insert(input_doc))
return nullptr;
projector = new Projector(arg_map[SELECTED_FIELD_LIST], extra_select_count);
return projector->get_input_doc_if_satisfied_filter(input_doc);
}
bool Filter::should_insert(const bson_t* input_doc) {
long filters_count = filters.size();
long restrictions_count = arg_map[QUERY_FIELD_LIST].size();
bool should_insert;
auto* restrictions_satisfied_arr = new bool[restrictions_count];
// no restrictions, all satisfied
if (restrictions_count == 0)
return true;
for (long i = 0, filter_idx = 0; i < restrictions_count; i++) {
int flag;
bson_iter_t doc_iter;
bson_iter_t target_iter;
bson_iter_t filter_iter;
std::string _field;
std::string _operator;
std::string _datatype;
std::cout << "Input doc: " << bson_as_json(input_doc, NULL) << std::endl;
_field = arg_map[QUERY_FIELD_LIST].at(i);
_operator = arg_map[NUMERIC_OPERATOR_LIST].at(i);
_datatype = arg_map[DATA_TYPE_LIST].at(i);
// first handle * and ! operator
if (_operator == "*" || _operator == "!") {
bool exists;
// check existence of field
exists = bson_iter_init(&doc_iter, input_doc)
&& bson_iter_find_descendant(&doc_iter, _field.c_str(), &target_iter)
&& bson_iter_type(&target_iter) == data_type_map[_datatype];
flag = exists ? 0 : IGNORE_NUM;
}
// handle normal operators
else if (filter_idx < filters_count) {
// check if the filter is a dot-notation key or not
if (_field.find('.') != std::string::npos) {
// check if input doc contains this dot field
if (bson_iter_init(&doc_iter, input_doc) && bson_iter_find_descendant(&doc_iter, _field.c_str(), &target_iter)) {
int cmp_rst;
bson_iter_init(&filter_iter, filters.at(filter_idx));
bson_iter_next(&filter_iter);
// std::cout << "target iter type: " << bson_iter_type(&target_iter) << ", filter iter type: " << bson_iter_type(&filter_iter) << std::endl;
cmp_rst = filter_compare_elements(&target_iter, &filter_iter);
if (cmp_rst == IGNORE_NUM) {
flag = IGNORE_NUM;
}
else if (cmp_rst > 0) {
flag = 1;
} else {
flag = cmp_rst < 0 ? -1 : 0;
}
// did not find this dot field
} else {
flag = IGNORE_NUM;
}
} else {
flag = filter_compare_object(input_doc, filters.at(filter_idx));
}
filter_idx++;
}
restrictions_satisfied_arr[i] = filter_satisfied(flag, _operator);
std::cout << "restriction : " << i << ", flag: " << flag << ", satisfied : " << restrictions_satisfied_arr[i] << std::endl;
}
should_insert = restrictions_satisfied_arr[0];
long bool_relations_size = arg_map[BOOL_OPERATOR_LIST].size();
// only one filter
if (bool_relations_size == 0) {
return should_insert;
}
else if (restrictions_count > 0 && bool_relations_size == restrictions_count - 1) {
should_insert = satisfy_query(restrictions_satisfied_arr);
} else {
//TODO: throw exception
}
delete[] restrictions_satisfied_arr;
return should_insert;
}
bool Filter::satisfy_query(bool restrictions_satisfied_arr[]) {
std::stack<std::string> bool_expr_stack;
std::vector<std::string> bool_expr_list;
bool satisfy_query;
std::string bool_operator;
std::string restriction;
bool restriction_value;
bool braced_value;
std::string curt_symbol;
std::string pushed_value;
bool_expr_list = arg_map[BOOL_EXPR_LIST];
satisfy_query = false;
// we already checks the validation of braces in the checker, so we do not check again here
for (int i = 0; i < bool_expr_list.size(); i++) {
curt_symbol = bool_expr_list.at(i);
if (curt_symbol != ")") {
bool_expr_stack.push(curt_symbol);
// std::cout << "stack pushed: " << curt_symbol << std::endl;
}
// we never push ")" into stack, only take it to backtrack latest "(" in stack
else {
// current top element must be a restriction
// top element has not been modified and is still index of restrictions_satisfied_arr
if (bool_expr_stack.top().find_first_not_of("0123456789") == std::string::npos) {
braced_value = restrictions_satisfied_arr[stoi(bool_expr_stack.top())];
// std::cout << "stack poped: " << bool_expr_stack.top() << std::endl;
bool_expr_stack.pop();
// else bool_expr_stack.top() should have been modified as "true" or "false"
} else {
braced_value = bool_expr_stack.top() == "true";
// std::cout << "stack poped: " << bool_expr_stack.top() << std::endl;
bool_expr_stack.pop();
}
while (!bool_expr_stack.empty() && bool_expr_stack.top() != "(") {
// there must exist one or more [restriction, bool_operator] combinations
bool_operator = bool_expr_stack.top();
// std::cout << "stack poped: " << bool_expr_stack.top() << std::endl;
bool_expr_stack.pop();
restriction = bool_expr_stack.top();
// std::cout << "stack poped: " << bool_expr_stack.top() << std::endl;
bool_expr_stack.pop();
if (restriction.find_first_not_of("0123456789") == std::string::npos) {
restriction_value = restrictions_satisfied_arr[stoi(restriction)];
} else {
restriction_value = restriction == "true";
}
if (bool_operator == "|")
braced_value = braced_value || restriction_value;
else
// else bool_operator is "&"
braced_value = braced_value && restriction_value;
}
if (!bool_expr_stack.empty() && bool_expr_stack.top() == "(") {
// std::cout << "stack poped: " << bool_expr_stack.top() << std::endl;
bool_expr_stack.pop();
// the current deepest braced expression in stack is replaced with pushed value
pushed_value = braced_value ? "true" : "false";
bool_expr_stack.push(pushed_value);
// std::cout << "stack pushed: " << bool_expr_stack.top() << std::endl;
}
}
}
if (!bool_expr_stack.empty()) {
// deal with non-braced expression
if (bool_expr_stack.top().find_first_not_of("0123456789") == std::string::npos) {
braced_value = restrictions_satisfied_arr[stoi(bool_expr_stack.top())];
} else {
braced_value = bool_expr_stack.top() == "true";
}
// std::cout << "stack poped: " << bool_expr_stack.top() << std::endl;
bool_expr_stack.pop();
while (!bool_expr_stack.empty()) {
// there must exist one or more [restriction, bool_operator] combinations
bool_operator = bool_expr_stack.top();
// std::cout << "stack poped: " << bool_expr_stack.top() << std::endl;
bool_expr_stack.pop();
restriction = bool_expr_stack.top();
// std::cout << "stack poped: " << bool_expr_stack.top() << std::endl;
bool_expr_stack.pop();
if (restriction.find_first_not_of("0123456789") == std::string::npos) {
restriction_value = restrictions_satisfied_arr[stoi(restriction)];
} else {
restriction_value = restriction == "true";
}
if (bool_operator == "|")
braced_value = braced_value || restriction_value;
else
// else bool_operator is "&"
braced_value = braced_value && restriction_value;
}
}
satisfy_query = braced_value;
std::cout << "input doc satisfy all the restrictions: " << satisfy_query << std::endl;
return satisfy_query;
}
void Filter:: generate_data_type_map() {
// generate data type map
data_type_map["eod"] = BSON_TYPE_EOD;
data_type_map["double"] = BSON_TYPE_DOUBLE;
data_type_map["utf8"] = BSON_TYPE_UTF8;
data_type_map["document"] = BSON_TYPE_DOCUMENT;
data_type_map["array"] = BSON_TYPE_ARRAY;
data_type_map["binary"] = BSON_TYPE_BINARY;
data_type_map["undefined"] = BSON_TYPE_UNDEFINED;
data_type_map["oid"] = BSON_TYPE_OID;
data_type_map["bool"] = BSON_TYPE_BOOL;
data_type_map["date_time"] = BSON_TYPE_DATE_TIME;
data_type_map["null"] = BSON_TYPE_NULL;
data_type_map["regex"] = BSON_TYPE_REGEX;
data_type_map["dbpointer"] = BSON_TYPE_DBPOINTER;
data_type_map["code"] = BSON_TYPE_CODE;
data_type_map["symbol"] = BSON_TYPE_SYMBOL;
data_type_map["codewscope"] = BSON_TYPE_CODEWSCOPE;
data_type_map["int32"] = BSON_TYPE_INT32;
data_type_map["timestamp"] = BSON_TYPE_TIMESTAMP;
data_type_map["int64"] = BSON_TYPE_INT64;
data_type_map["decimal128"] = BSON_TYPE_DECIMAL128;
data_type_map["maxkey"] = BSON_TYPE_MAXKEY;
data_type_map["minkey"] = BSON_TYPE_MINKEY;
}
void Filter::generate_filters() {
// no filters, just insert it
if (arg_map.empty())
return;
if (arg_map.find(QUERY_FIELD_LIST) != arg_map.end() &&
arg_map.find(QUERY_VALUE_LIST) != arg_map.end() &&
arg_map.find(DATA_TYPE_LIST) != arg_map.end()) {
std::vector<std::string> field_list = arg_map[QUERY_FIELD_LIST];
std::vector<std::string> term_list = arg_map[QUERY_VALUE_LIST];
std::vector<std::string> data_type_list = arg_map[DATA_TYPE_LIST];
std::vector<std::string> _operator_list = arg_map[NUMERIC_OPERATOR_LIST];
if (field_list.size() == term_list.size()
&& data_type_list.size() == term_list.size()) {
long size = field_list.size();
for (long i = 0; i < size; i++) {
// we do not generate filter for "*" and "!", we directly handle them in should_insert()
if (_operator_list.at(i) != "*" && _operator_list.at(i) != "!") {
try {
filters.push_back(generate_filter(field_list.at(i), term_list.at(i), data_type_list.at(i)));
} catch (const char *msg) {
std::cerr << msg << std::endl;
}
}
}
} else {
throw "Error: Query parsed wrong! Fields amount is not equal to term amount!";
}
} else {
std::cout << "No restrictions." << std::endl;
}
}
bson_t* Filter::generate_filter(std::string& field, std::string& term, std::string& dataType) {
std::istringstream iss(field);
std::vector<std::string> tokens;
std::string token;
long size;
bson_t* filter;
while (std::getline(iss, token, '.')) {
if (!token.empty()) {
tokens.push_back(token);
}
}
size = tokens.size();
filter = generate_unnested_filter(tokens.at(size - 1), term, dataType);
return filter;
}
// do not support nested query:
// BSON_TYPE_DOCUMENT, BSON_TYPE_ARRAY, BSON_TYPE_REGEX, BSON_TYPE_CODEWSCOPE, BSON_TYPE_CODE
// also do not support: BSON_TYPE_OID, BSON_TYPE_DBPOINTER, BSON_TYPE_BINARY, BSON_TYPE_EOD, BSON_TYPE_UNDEFINED, BSON_TYPE_TIMESTAMP
// support: BSON_TYPE_DOUBLE, BSON_TYPE_UTF8, BSON_TYPE_BOOL, BSON_TYPE_DATE_TIME, BSON_TYPE_NULL, BSON_TYPE_SYMBOL
// BSON_TYPE_INT32, BSON_TYPE_TIMESTAMP, BSON_TYPE_DECIMAL128, BSON_TYPE_MAXKEY, BSON_TYPE_MINKEY
bson_t* Filter::generate_unnested_filter(std::string& field, std::string& term, std::string& dataType) {
bson_t* b;
unsigned long _data_type;
const bson_t *sub_doc;
const bson_t *array;
bson_subtype_t binary_subtype;
const uint8_t *binary;
uint32_t binary_length;
bson_oid_t oid_oid;
bool bool_flag;
int64_t datetime_val;
const char *reg_options, *regex;
const char *collection;
bson_oid_t *dbp_oid;
const char *code_javascript;
const char *cws_javascript;
const bson_t *cws_scope;
uint32_t timestamp;
uint32_t increment;
bson_decimal128_t decimal128;
b = bson_new();
// _data_type = std::stoul(dataType, nullptr, 16);
_data_type = data_type_map[dataType];
if (_data_type == BSON_TYPE_EOD) {
throw "Error: Filter not generated, data type should not be BSON_TYPE_EOD!";
}
else if (_data_type == BSON_TYPE_DOUBLE) {
BSON_APPEND_DOUBLE(b, field.c_str(), std::stod(term));
}
else if (_data_type == BSON_TYPE_UTF8) {
BSON_APPEND_UTF8(b, field.c_str(), term.c_str());
}
else if (_data_type == BSON_TYPE_ARRAY) {
// TODO: need to specifically define this case
std::cerr << "Currently we do not support directly query for array type" << std::endl;
}
else if (_data_type == BSON_TYPE_DOCUMENT) {
// TODO: need to specifically define this case
std::cerr << "Currently we do not support directly query for document type" << std::endl;
}
else if (_data_type == BSON_TYPE_BINARY) {
// TODO: need to specifically define this case
std::cerr << "Currently we do not support directly query for binary type" << std::endl;
}
else if (_data_type == BSON_TYPE_UNDEFINED) {
BSON_APPEND_UNDEFINED(b, field.c_str());
}
else if (_data_type == BSON_TYPE_OID) {
bson_oid_init_from_string(&oid_oid, term.c_str());
BSON_APPEND_OID(b, field.c_str(), &oid_oid);
}
else if (_data_type == BSON_TYPE_BOOL) {
// "0"for false, and "1" or "true"
bool_flag = term == "1";
BSON_APPEND_BOOL(b, field.c_str(), bool_flag);
}
else if (_data_type == BSON_TYPE_DATE_TIME) {
// value is assumed to be in UTC format of milliseconds since the UNIX epoch. value MAY be negative
datetime_val = std::strtoll(term.c_str(), nullptr, 10);
BSON_APPEND_DATE_TIME(b, field.c_str(), datetime_val);
}
else if (_data_type == BSON_TYPE_NULL) {
BSON_APPEND_NULL(b, field.c_str());
}
else if (_data_type == BSON_TYPE_REGEX) {
// TODO: need to include [const char *options] as a param
std::cerr << "Currently we do not support directly query for regex type" << std::endl;
}
else if (_data_type == BSON_TYPE_DBPOINTER) {
//TODO: need to specifically define OID
// Warning: The dbpointer field type is DEPRECATED and should only be used when interacting with legacy systems.
std::cerr << "Currently we do not support directly query for dbpointer type" << std::endl;
}
else if (_data_type == BSON_TYPE_CODE) {
//javascript: A UTF-8 encoded string containing the javascript.
code_javascript = term.c_str();
BSON_APPEND_CODE(b, field.c_str(), code_javascript);
}
else if (_data_type == BSON_TYPE_SYMBOL) {
// Appends a new field to bson of type BSON_TYPE_SYMBOL.
// This BSON type is deprecated and should not be used in new code.
BSON_APPEND_SYMBOL(b, field.c_str(), term.c_str());
}
else if (_data_type == BSON_TYPE_CODEWSCOPE) {
//TODO: need to specifically define [const bson_t *scope]
// scope: Optional bson_t containing the scope for javascript.
std::cerr << "Currently we do not support directly query for codewscope type" << std::endl;
}
else if (_data_type == BSON_TYPE_INT32) {
BSON_APPEND_INT32(b, field.c_str(), std::stoi(term));
}
else if (_data_type == BSON_TYPE_INT64) {
BSON_APPEND_INT64(b, field.c_str(), std::stoi(term));
}
else if (_data_type == BSON_TYPE_TIMESTAMP) {
// This function is not similar in functionality to bson_append_date_time().
// Timestamp elements are different in that they include only second precision and an increment field.
// They are primarily used for intra-MongoDB server communication.
std::istringstream iss(term);
std::vector<std::string> tokens;
std::string token;
while (std::getline(iss, token, '_')) {
if (!token.empty())
tokens.push_back(token);
}
timestamp = strtoul(tokens.at(0).c_str(), NULL, 10);
increment = strtoul(tokens.at(1).c_str(), NULL, 10);
BSON_APPEND_TIMESTAMP(b, field.c_str(), timestamp, increment);
}
else if (_data_type == BSON_TYPE_DECIMAL128) {
bson_decimal128_from_string(term.c_str(), &decimal128);
BSON_APPEND_DECIMAL128(b, field.c_str(), &decimal128);
}
else if (_data_type == BSON_TYPE_MAXKEY) {
BSON_APPEND_MAXKEY(b, field.c_str());
}
else if (_data_type == BSON_TYPE_MINKEY) {
BSON_APPEND_MINKEY(b, field.c_str());
}
std::cout << "filter generated: " << bson_as_json(b, NULL) << std::endl;
return b;
}
bool Filter::filter_satisfied (int flag, std::string& _operator) {
if (flag == 1) {
return _operator == ">=" || _operator == ">" || _operator == "!=" || _operator == "*";
}
else if (flag == 0) {
return _operator == "=" || _operator == ">=" || _operator == "<=" || _operator == "*";
}
else if (flag == -1) {
return _operator == "<=" || _operator == "<" || _operator == "!=" || _operator == "*";
} else if (flag == IGNORE_NUM) {
return _operator == "!";
}
// this statement should not be reached since we only have 4 flags
return false;
}
void Filter::print_map() {
for (auto map_it = arg_map.begin(); map_it != arg_map.end(); ++map_it) {
std::cout << "\n\nkey: " << map_it -> first << std::endl;
for (auto it = map_it -> second.begin() ; it != map_it -> second.end(); ++it)
std::cout << "\t" << *it;
}
std::cout << std::endl;
}
void Filter::print_filters() {
unsigned long size = filters.size();
std::cout << "We have " << size << " filters!" << std::endl;
if (size != 0) {
for (auto it = filters.begin(); it != filters.end(); it++) {
std::cout << "\t" << bson_as_json(*it, NULL) << std::endl;
}
std::cout << std::endl;
}
}
bson_t* Filter::generate_input_doc() {
bson_decimal128_t decimal128;
bson_t* input_doc;
bson_oid_t oid;
bson_t* a = bson_new();
bson_t* b = bson_new();
bson_t* c = bson_new();
bson_oid_init(&oid, NULL);
input_doc = BCON_NEW("foo", "{", "bar", "[", "{", "baz_0", BCON_INT32 (0), "}", "{", "baz_1", BCON_INT32 (1), "}", "]", "}");
BSON_APPEND_OID(input_doc, "_id", &oid);
BSON_APPEND_BOOL(input_doc, "bool", true);
BSON_APPEND_UTF8(input_doc, "utf8", "99");
BSON_APPEND_DOUBLE(input_doc, "double", 10.50);
BSON_APPEND_INT32(input_doc, "int32", 200);
BSON_APPEND_INT64(input_doc, "int64", 300);
BSON_APPEND_DATE_TIME(input_doc, "date_time", 400);
BSON_APPEND_SYMBOL(input_doc, "symbol", "***");
BSON_APPEND_MAXKEY(input_doc, "maxkey");
BSON_APPEND_MINKEY(input_doc, "minkey");
BSON_APPEND_NULL(input_doc, "null");
BSON_APPEND_INT32(input_doc, "in t 32", 1000);
BSON_APPEND_BOOL(input_doc, "b o o l", false);
BSON_APPEND_UNDEFINED(input_doc, "undefined");
BSON_APPEND_UTF8(input_doc, "utf 8", "utf 8");
// generate nested element {document:{a: {b: {c: 1}}}}
BSON_APPEND_INT32(c, "c", 1);
BSON_APPEND_DOCUMENT(b, "b", c);
BSON_APPEND_DOCUMENT(a, "a", b);
BSON_APPEND_DOCUMENT(input_doc, "document", a);
bson_decimal128_from_string("500", &decimal128);
BSON_APPEND_DECIMAL128(input_doc, "decimal128", &decimal128);
return input_doc;
} | true |
7d9e01597ef8922808c1f64a15bfe03f5a913cb9 | C++ | mubai-victor/Algorithm | /线性规划网络流/线性规划/main.cpp | UTF-8 | 3,886 | 3.015625 | 3 | [] | no_license | //线性规划的单纯形算法
//author:mubai edition:1.0 time:2019年09月21日20:23:50
#include "iostream"
#include "iomanip"
#define MAXSIZE 100
#define INF 10e6
using namespace std;
double kernel[MAXSIZE][MAXSIZE];
int basicVar[MAXSIZE]={1,3,6,7},nonBasicVar[MAXSIZE]={2,4,5};
void print(int basic,int nonbasic);
void DCXA(int basic,int nonbasic);
int main(int argc,char **argv)
{
//初始化kernel中的数据。
kernel[0][0]=0;
kernel[0][1]=2.5;
kernel[0][2]=2.8;
kernel[0][3]=76.25;
kernel[1][0]=0;
kernel[1][1]=1;
kernel[1][2]=0;
kernel[1][3]=-5;
kernel[2][0]=0;
kernel[2][1]=0;
kernel[2][2]=1;
kernel[2][3]=-2;
kernel[3][0]=12000;
kernel[3][1]=0;
kernel[3][2]=0;
kernel[3][3]=1;
kernel[4][0]=1000;
kernel[4][1]=0.1;
kernel[4][2]=0.08;
kernel[4][3]=0.05;
print(4,3);
DCXA(4,3);
print(4,3);
return 0;
}
void print(int basic,int nonbasic)
{
cout<<"List is shown above:"<<endl;
cout<<setw(7)<<" ";
cout<<setw(7)<<"b";
for(int i=0;i<nonbasic;i++){
cout<<setw(7)<<"x"<<nonBasicVar[i];
}
cout<<endl;
cout<<setw(8)<<" c";
for(int i=0;i<=nonbasic;i++){
cout<<setw(7)<<kernel[0][i];
}
cout<<endl;
for(int i=0;i<basic;i++){
cout<<setw(7)<<"x"<<basicVar[i];
for(int j=0;j<=nonbasic;j++){
cout<<setw(7)<<kernel[i+1][j];
}
cout<<endl;
}
}
void DCXA(int basic,int nonbasic)
{
double maxRow=0,minColumn=INF;
int row=-1,column=-1;
while(1){
maxRow=0;
for(int i=1;i<=nonbasic;i++){
if(maxRow<kernel[0][i]){//寻找入基列。
maxRow=kernel[0][i];
row=i;
}
if(kernel[0][i]>0){//检查入基列的正的检验数对应的列向量分量是否都是小于等于0的
int j=1;
for(;j<=basic;j++){
if(kernel[i][j]>0){
break;
}
}
if(j>basic){
cout<<"No solution!"<<endl;
return;
}
}
}
if(maxRow<=0){//如果最大的入基列对应的检验数小于等于0,说明找到了最优解
cout<<"Find the maximum value:"<<kernel[0][0]<<endl;
return;
}
minColumn=INF;//寻找离基行。
for(int i=1;i<=basic;i++){
if(kernel[i][row]!=0&&kernel[i][0]/kernel[i][row]>0&&minColumn>kernel[i][0]/kernel[i][row]){
minColumn=kernel[i][0]/kernel[i][row];
column=i;
}
}
char temp=basicVar[column - 1];//交换入基列,离基行。
basicVar[column - 1]=nonBasicVar[row - 1];
nonBasicVar[row - 1]=temp;
int swap=row;
row=column;
column=swap;
for(int i=0;i<=basic;i++){//计算kernel各个位置的新值。
if(i!=row){
for(int j=0;j<=nonbasic;j++){
if(j!=column){
if(i==0&&j==0){
kernel[0][0]+=kernel[row][0]*kernel[0][column]/kernel[row][column];
}
else{
kernel[i][j]-=kernel[row][j]*kernel[i][column]/kernel[row][column];
}
}
}
}
}
for(int i=0;i<=basic;i++){
if(i!=row){
kernel[i][column]=-kernel[i][column]/kernel[row][column];
}
}
for(int i=0;i<=nonbasic;i++){
if(i!=column){
kernel[row][i]=kernel[row][i]/kernel[row][column];
}
}
kernel[row][column]=1/kernel[row][column];
print(4,3);
}
} | true |
df4e0d8929a4587a077779d15d97e4165d7abc00 | C++ | bvignesh/15-745_repo | /source_codes/hw3/junhanz/LICM/dataflow.cpp | UTF-8 | 10,205 | 2.78125 | 3 | [] | no_license | // 15-745 S16 Assignment 2: dataflow.cpp
// Group:
////////////////////////////////////////////////////////////////////////////////
#include "dataflow.h"
namespace llvm {
// Create the analysis object
DataFlowAnalysis::DataFlowAnalysis(char &ID) : FunctionPass(ID){
//Reset inner data elements
resetObject();
}
//The main analysis pass
bool DataFlowAnalysis::runOnFunction(Function& F){
//First do a scan of the function to know how many program pointers and what the domain is
for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
BasicBlock* block = FI;
int BBbegin = ppNum;
for (BasicBlock::iterator i = block->begin(), e = block->end(); i!=e; ++i) {
//Each instruction is a value
Value *I = i;
if(!isa<PHINode>(I)){
//There is a program point for every instruction -- except PHINode instructions
ppNum++;
}
std::vector<Value *> ToAdd = addToDomain(i);
if(!ToAdd.empty()){
for(auto ToAddElement : ToAdd){
//Add each element to the domain
checkAndAddToDomain(ToAddElement);
}
}
}
//Map where are the entrance and exit for this basic block are
BBinfoMap[block]={BBbegin, ppNum, std::vector<Value *>()};
//There is an extra program point after a basic block
ppNum++;
}
//Now with the BBinfo initiated, add the PHINode info to it
for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
BasicBlock* block = FI;
for (BasicBlock::iterator i = block->begin(), e = block->end(); i!=e; ++i) {
//Each instruction is a value
Value *I = i;
if(PHINode *phi = dyn_cast<PHINode>(I)){
for(PHINode::block_iterator phiBBi=phi->block_begin(); phiBBi!=phi->block_end(); ++phiBBi){
BasicBlock *phiBB = *phiBBi;
BBinfoMap[phiBB].FollowingPHINodes.push_back(I);
}
}
}
}
//Next init the programPoints, we now know the domain size, aka the BitVector Size
//set the initial value for the BitVector
BitVector initVal = BitVector(domainSize, initialInterior());
//and create the BitVector
programPoints = std::vector<BitVector>(ppNum,initVal);
//boundry value
BitVector bdyVal = BitVector(domainSize, boundaryCondition());
//Then is the main part, the actual analysis pass
if(isForwardPass()){
//The direction is forward
programPoints[0]=bdyVal;
//keep iterating until nothing changes
while(forwardPass(F)){
//printResult(F);
//outs() << "\n\n";
}
}else{
//The direction is backward
programPoints[ppNum-1]=bdyVal;
//keep iterating until nothing changes
while(backwardPass(F)){
//printResult(F);
//outs() << "\n\n";
}
}
//prints the result
printResult(F);
//clear all the information for the current function
resetObject();
//Analysis pass does not change anything
return false;
}
void DataFlowAnalysis::getAnalysisUsage(AnalysisUsage& AU) const {
AU.setPreservesAll();
}
BitVector DataFlowAnalysis::genKillTransferFunction(BitVector &lastResult, Value ¤tInst,
std::function<std::vector<Value *> (Value&)> genFunc, std::function<bool (Value&, Value&)> killFunc,
std::vector<Value *> &Domain){
BitVector currentResult = BitVector(lastResult);
//See if there are any elements to kill
for(int i=0;i<currentResult.size();i++){
if(currentResult[i]){
//If the current bit is set, sees if it can remain to be set
if(killFunc(currentInst,*(Domain[i]))){
//If the kill function decides to kill this element
currentResult[i]=false;
}
}
}
//See if there are any elements to add
std::vector<Value *> genVals = genFunc(currentInst);
for(Value *toAdd : genVals){
auto index = std::find(Domain.begin(), Domain.end(), toAdd);
if(index!=Domain.end()){
currentResult[index-Domain.begin()]=true;
}
}
return currentResult;
}
//reset the pass inner data
void DataFlowAnalysis::resetObject(){
Domain.clear();
domainSize=0;
programPoints.clear();
ppNum=0;
BBinfoMap.clear();
}
//Checks if the giving value is not already in domian, if not then add to domain
void DataFlowAnalysis::checkAndAddToDomain(Value *v){
if(std::find(Domain.begin(),Domain.end(),v)==Domain.end()){
//Not already in Domain add it to domain
Domain.push_back(v);
domainSize++;
}
}
//does a forward pass return true if something have been updated
bool DataFlowAnalysis::forwardPass(Function& F){
int currentppNum=0;
bool changed = false;
for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
BasicBlock* block = FI;
if(BBinfoMap[block].beginIndx!=0){
//If the basic block isn't the first basic block, we have to get entry value
BitVector newVal = BitVector(domainSize, initialInterior());
for (pred_iterator PI = pred_begin(block), E = pred_end(block); PI != E; ++PI) {
BasicBlock *Pred = *PI;
//merge the values with the exit values of all the predecessors
newVal=meet(newVal, programPoints[BBinfoMap[Pred].endIndx]);
}
//Then process all the PHINodes at the beginning
for (BasicBlock::iterator i = block->begin(), e = block->end(); i!=e; ++i){
Value *I = i;
if(PHINode *phi = dyn_cast<PHINode>(I)){
newVal = phiTransferFunction(newVal, *I, block);
}else{
break;
}
}
//See if anything have changed
changed |= (newVal!=programPoints[currentppNum]);
//update the might be new values
programPoints[currentppNum]=newVal;
}
//Transfer function computes the exit point of each instruction
currentppNum++;
for (BasicBlock::iterator i = block->begin(), e = block->end(); i!=e; ++i) {
//Each instruction is a value
Value *I = i;
if(isa<PHINode>(I)){
//We've already dealt with the PHINode instructions
continue;
}
//Gets the new value of the current program point
BitVector newVal = transferFunction(programPoints[currentppNum-1], *I);
//See if anything have changed
changed |= (newVal!=programPoints[currentppNum]);
//update the might be new values
programPoints[currentppNum]=newVal;
//There is a program point for every instruction
currentppNum++;
}
}
return changed;
}
//does a backward pass return true if somethinng have been updated
bool DataFlowAnalysis::backwardPass(Function& F){
int currentppNum=ppNum;
bool changed = false;
for (Function::iterator FI = F.end(), FE = F.begin(); FI != FE;) {
//decrements here as no reverse iterator is provided and can follow the end begin comparison
--FI;
BasicBlock* block = FI;
//Transfer function computes the entry point of each instruction
--currentppNum;
if(BBinfoMap[block].endIndx!=ppNum-1){
//If the basic block isn't the last basic block, we have to get exit value
BitVector newVal = BitVector(domainSize, initialInterior());
for (succ_iterator PI = succ_begin(block), E = succ_end(block); PI != E; ++PI) {
BasicBlock *Succ = *PI;
//merge the values with the entry values of all the successors
newVal=meet(newVal, programPoints[BBinfoMap[Succ].beginIndx]);
}
//Then process all the PHINodes at the beginning
for (auto i = BBinfoMap[block].FollowingPHINodes.rbegin(), e = BBinfoMap[block].FollowingPHINodes.rend(); i!=e; ++i){
Value *I = *i;
if(PHINode *phi = dyn_cast<PHINode>(I)){
//This should always hold true
newVal = phiTransferFunction(newVal, *I, block);
}
}
//See if anything have changed
changed |= (newVal!=programPoints[currentppNum]);
//update the might be new values
programPoints[currentppNum]=newVal;
}
for (BasicBlock::reverse_iterator i = block->rbegin(), e = block->rend(); i!=e; ++i) {
//Each instruction is a value
Value *I = &(*i);
if(isa<PHINode>(I)){
//We ignore PHINodes here
continue;
}
//There is a program point for every instruction
--currentppNum;
//Gets the new value of the current program point
BitVector newVal = transferFunction(programPoints[currentppNum+1], *I);
//See if anything have changed
changed |= (newVal!=programPoints[currentppNum]);
//update the might be new values
programPoints[currentppNum]=newVal;
}
}
return changed;
}
//prints out the result of the set
void DataFlowAnalysis::printSet(BitVector& BV){
outs() << "{";
bool isFirst = true;
for(int i=0;i<domainSize;i++){
if(BV[i]){
if(isFirst){
isFirst=false;
}else{
outs() << " , ";
}
outs() << toString(*(Domain[i]));
}
}
outs() << "}\n";
}
void DataFlowAnalysis::printResult(Function& F){
int currentppNum=0;
outs() << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
BasicBlock* block = FI;
if(isForwardPass()){
printSet(programPoints[currentppNum]);
for (BasicBlock::iterator i = block->begin(), e = block->end(); i!=e; ++i) {
//Each instruction is a value
Value *I = i;
outs() << "\t\t\t\t\t\t\t\t";
I->print(outs());
outs() << "\n";
if(isa<PHINode>(I)){
continue;
}
currentppNum++;
printSet(programPoints[currentppNum]);
}
currentppNum++;
}else{
for (BasicBlock::iterator i = block->begin(), e = block->end(); i!=e; ++i) {
//Each instruction is a value
Value *I = i;
if(!isa<PHINode>(I)){
printSet(programPoints[currentppNum]);
currentppNum++;
}
outs() << "\t\t\t\t\t\t\t\t";
I->print(outs());
outs() << "\n";
}
printSet(programPoints[currentppNum]);
currentppNum++;
}
outs() << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
}
}
}
| true |
370c898b81e4a6d9630da14819e02e4a7680feff | C++ | gauravengine/CPP_Freak | /450_DSA/graph/struct.cpp | UTF-8 | 623 | 3.21875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
struct cell
{
int x,y,dis;
cell(){
cout<<"bonjour"<<endl;
x=1;
y=1;
dis=1;
}
cell(int x,int y,int dis) :x(x),y(y),dis(dis)
{
cout<<"intialization list constructor"<<endl;
}
};
int main(){
// cell t(2,3,4);
// cout<<"t.x: "<<t.x<<endl;
// cout<<"t.y: "<<t.y<<endl;
// cout<<"t.dis: "<<t.dis<<endl;
// queue<cell> q;
// q.push(cell(5,6,7));
// cell m= q.front();
cell m= cell(5,6,7);
cout<<"m.x: "<<m.x<<endl;
cout<<"m.y: "<<m.y<<endl;
cout<<"m.dis: "<<m.dis<<endl;
} | true |
d7c24b91702c53d1460c2518a5d40c8c9dfd298f | C++ | cmmakerclub/iotworkshop | /codes/basic-esp8266/esp8266_basic_httpget/esp8266_basic_httpget.ino | UTF-8 | 1,277 | 2.8125 | 3 | [] | no_license | /**
BasicHTTPClient.ino
Created on: 24.05.2015
*/
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
const char* ssid = "........";
const char* password = "........";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
HTTPClient http;
Serial.print("[HTTP] begin...\n");
http.begin("http://192.168.1.12/test.html"); //HTTP
Serial.print("[HTTP] GET...\n");
// start connection and send HTTP header
int httpCode = http.GET();
// httpCode will be negative on error
if (httpCode > 0) {
// HTTP header has been send and Server response header has been handled
Serial.printf("[HTTP] GET... code: %d\n", httpCode);
// file found at server
if (httpCode == HTTP_CODE_OK) {
String payload = http.getString();
Serial.println(payload);
}
} else {
Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
delay(10000);
}
| true |
5e1a75ab49a6bc3b27150f5740719fb78ae8d6d2 | C++ | DahamChoi/Algorithm-Troubleshooting-Strategies | /모스 부호 사전/모스 부호 사전.cpp | UTF-8 | 1,520 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
void generate(int n, int m, string s) {
// 기저 사례 : n = m = 0
if (n == 0 && m == 0) {
return;
}
if (n > 0) generate(n - 1, m, s + "-");
if (m > 0) generate(n, m - 1, s + "o");
}
int skip;
void generate2(int n, int m, string s) {
// 기저 사례 : skip < 0
if (skip < 0) return;
// 기저 사례 : n = m = 0
if (n == 0 && m == 0) {
--skip;
return;
}
if (n > 0) generate2(n - 1, m, s + "-");
if (m > 0) generate2(n, m - 1, s + "o");
}
// K의 최댓값 + 100, 오버플로를 막기 위해 이보다 큰 값은 구하지 않는다.
const int M = 1000000000 + 100;
int bino[201][201];
void calcBino() {
memset(bino, 0, sizeof(bino));
for (int i = 0; i <= 200; i++) {
bino[i][0] = bino[i][i] = 1;
for (int j = 1; j < i; j++) {
bino[i][j] = min(M, bino[i - 1][j - 1] + bino[i - 1][j]);
}
}
}
void generate3(int n, int m, string s) {
if (skip < 0) return;
if (n == 0 && m == 0) {
--skip;
return;
}
if (bino[n + m][n] <= skip) {
skip -= bino[n + m][n];
return;
}
if (n > 0) generate3(n - 1, m, s + "-");
if (m > 0) generate3(n, m - 1, s + "o");
}
string kth(int n, int m, int skip) {
if (n == 0) return string(m, 'o');
if (skip < bino[n + m - 1][n - 1]) {
return "-" + kth(n - 1, m, skip);
}
return "o" + kth(n, m - 1, skip - bino[n + m - 1][n - 1]);
}
int main() {
ios::sync_with_stdio(false); cin.tie(NULL);
int T; cin >> T;
while (T--) {
int N, M, K; cin >> N >> M >> K;
}
return 0;
} | true |
6b36ba4a2922d7b3a3d48db64709976d31003fbd | C++ | LuyzThu/MyAccount | /MyAccount/SavingAccount.h | UTF-8 | 843 | 3 | 3 | [] | no_license | #ifndef _SAVING_ACCOUNT_H_
#define _SAVING_ACCOUNT_H_
#include <string>
#include "Date.h"
using namespace std;
class SavingAccount
{
public:
SavingAccount(Date date, string id, double rate);
string getId() const { return id; }
double getBalance() const{ return balance; }
double getRate() const { return rate; }
void show() const;
void deposit(Date date, double amount, string desc);
void withdraw(Date date, double amount, string desc);
void settle(Date date);
static double getTotal() { return total; }
private:
string id;
double balance, rate, accumulation;
static double total;
Date lastDate;
void record(Date date, double amount, string desc);
void error(string msg) const;
double accumulate(Date date) const
{
return accumulation + balance * (date - lastDate);
}
};
#endif // !_SAVING_ACCOUNT_H_
#pragma once
| true |
a5f8d8529f40c7a24c910c3ef78236f94a781245 | C++ | lalanne/UnitTestTalk | /src/code/allTests.cpp | UTF-8 | 674 | 3.5625 | 4 | [] | no_license | TEST(stack_tests, lifo_behaviour_with_1_element) {
Stack<float> stack;
stack.push(2.5);
EXPECT_EQ(2.5, stack.pop());
}
TEST(stack_tests, lifo_behaviour_with_3_element) {
Stack<int> stack;
stack.push(2);
stack.push(1);
stack.push(14);
EXPECT_EQ(14, stack.pop());
EXPECT_EQ(1, stack.pop());
EXPECT_EQ(2, stack.pop());
}
TEST(stack_tests, pop_of_empty_stack) {
Stack<int> stack;
EXPECT_EQ(stack.pop(), EmptyStackException);
}
TEST(stack_tests, exceeding_stack_limit) {
Stack<double> stack(3);
stack.push(3.4);
stack.push(2.4);
stack.push(4.4);
EXPECT_THROW(stack.push(7.8), ExceedsStackSizeException);
}
| true |
244625f46af8d952081ad6950ef70188f3629213 | C++ | roborams256/MainRobotCode | /TriggerWheel.cpp | UTF-8 | 1,246 | 2.71875 | 3 | [] | no_license | #include "TriggerWheel.h"
TriggerWheel::TriggerWheel(int spikeChannel, double launchTime){
triggerRelay = new Relay(SPIKE_TRIGGER); // default should be both directions
// start in the hold direction
//Hold();
launchPeriod = launchTime;
semi = false;
pulse = false;
timer = new Timer();
timer->Reset();
}
void TriggerWheel::Off(void){
triggerRelay->Set(Relay::kOff);
}
void TriggerWheel::Hold(void){
// was kReverse with Ice wheel
triggerRelay->Set(Relay::kReverse);
}
void TriggerWheel::FireAuto(void){
triggerRelay->Set(Relay::kForward);
DEBUG_PRINT("FIRE auto\n");
}
void TriggerWheel::SetLaunchPeriod(double launchTime)
{
launchPeriod = launchTime;
}
void TriggerWheel::FireSemiAuto()
{
DEBUG_PRINT("FIRE semiauto\n");
if (semi) return; //don't allow re-firing
timer->Stop();
timer->Reset();
timer->Start();
FireAuto();
semi = true;
}
bool TriggerWheel::IsFiring(){
return semi;
}
void TriggerWheel::Update()
{
//DEBUG_PRINT("Timer %lf\n Semi %d\n",timer->Get(), semi);
if (semi && timer->HasPeriodPassed(launchPeriod))
{
Hold();
timer->Stop();
timer->Reset();
semi = false;
}
else{
//DEBUG_PRINT("Timer: %f\n", timer->Get());
}
return;
}
| true |
b1480d2ca656b023353f74777421dbe7a41f138c | C++ | Paul199406/algorithm | /06_PrintListInReversedOrder/PrintListInReversedOrder.cpp | UTF-8 | 1,457 | 3.65625 | 4 | [] | no_license | //author:lijiwei
//date:2020/2/9
#include <iostream>
#include <stack>
using namespace std;
#define nullptr 0
struct ListNode
{
int m_nValue;
ListNode* m_pNext;
};
ListNode* CreateListNode(int value)
{
ListNode* pNode = new ListNode();
pNode->m_nValue = value;
pNode->m_pNext = nullptr;
return pNode;
}
void ConnectListNodes(ListNode* pCurrent, ListNode* pNext)
{
if(pCurrent == nullptr)
{
cout << "Error to connect two nodes." << endl;
return;
}
pCurrent->m_pNext = pNext;
}
void PrintListReversing(ListNode* pHead)
{
if ( pHead == nullptr )
return ;
stack<int> st;
ListNode* pNode = pHead;
while ( pNode != nullptr )
{
st.push(pNode->m_nValue);
pNode = pNode->m_pNext;
}
cout << "List Reversing: " << endl;
while( !st.empty() )
{
cout << st.top() << "->";
st.pop();
}
cout << "NULL" << endl;
}
int main()
{
ListNode * pNode1;
ListNode * pNode2;
ListNode * pNode3;
ListNode * pNode4;
pNode1 = CreateListNode(1);
pNode2 = CreateListNode(2);
pNode3 = CreateListNode(3);
pNode4 = CreateListNode(4);
//list1:1->2->3
ConnectListNodes(pNode1,pNode2);
ConnectListNodes(pNode2,pNode3);
cout << "List1:1->2->3" << endl;
PrintListReversing(pNode1);
cout << "List2:4" << endl;
PrintListReversing(pNode4);
return 0;
}
| true |
bcf1e426da1173edc6ebe8b5c88758360f9aec79 | C++ | baileyforrest/cxm | /cxm/lex/token.cc | UTF-8 | 2,119 | 2.515625 | 3 | [
"MIT"
] | permissive | #include "cxm/lex/token.h"
std::string_view TokenTypeToString(TokenType token_type) {
#define CASE_STR(token) \
case TokenType::token: \
return #token
switch (token_type) {
CASE_STR(kEof);
CASE_STR(kLBrace);
CASE_STR(kRBrace);
CASE_STR(kLParen);
CASE_STR(kRParen);
CASE_STR(kSemi);
CASE_STR(kComma);
CASE_STR(kLBrack);
CASE_STR(kRBrack);
CASE_STR(kArrow);
CASE_STR(kDot);
CASE_STR(kCond);
CASE_STR(kColon);
CASE_STR(kScope);
CASE_STR(kAssign);
CASE_STR(kPlusEq);
CASE_STR(kMinusEq);
CASE_STR(kStarEq);
CASE_STR(kDivEq);
CASE_STR(kModEq);
CASE_STR(kBitXorEq);
CASE_STR(kBitOrEq);
CASE_STR(kBitAndEq);
CASE_STR(kRShiftEq);
CASE_STR(kLShiftEq);
CASE_STR(kEq);
CASE_STR(kNe);
CASE_STR(kLt);
CASE_STR(kGt);
CASE_STR(kLe);
CASE_STR(kGe);
CASE_STR(kRShift);
CASE_STR(kLShift);
CASE_STR(kLogicAnd);
CASE_STR(kLogicOr);
CASE_STR(kLogicNot);
CASE_STR(kPlus);
CASE_STR(kMinus);
CASE_STR(kStar);
CASE_STR(kDiv);
CASE_STR(kMod);
CASE_STR(kBitAnd);
CASE_STR(kBitOr);
CASE_STR(kBitXor);
CASE_STR(kBitNot);
CASE_STR(kBreak);
CASE_STR(kCase);
CASE_STR(kClass);
CASE_STR(kConst);
CASE_STR(kContinue);
CASE_STR(kDefault);
CASE_STR(kElse);
CASE_STR(kEnum);
CASE_STR(kFn);
CASE_STR(kFor);
CASE_STR(kIf);
CASE_STR(kIn);
CASE_STR(kInclude);
CASE_STR(kLet);
CASE_STR(kMut);
CASE_STR(kPrivate);
CASE_STR(kPublic);
CASE_STR(kReturn);
CASE_STR(kSizeof);
CASE_STR(kStatic);
CASE_STR(kStaticAssert);
CASE_STR(kStruct);
CASE_STR(kSwitch);
CASE_STR(kThisType);
CASE_STR(kUnion);
CASE_STR(kUsing);
CASE_STR(kVolatile);
CASE_STR(kWhile);
CASE_STR(kId);
CASE_STR(kString);
CASE_STR(kChar);
CASE_STR(kIntLit);
CASE_STR(kFloatLit);
}
#undef CASE_STR
return "UNKNOWN";
}
std::ostream& operator<<(std::ostream& os, const Token& token) {
os << TokenTypeToString(token.type) << "(" << token.text << ")";
return os;
}
| true |
db4583d7b2f9aa0aa1dd96119a33050c27213273 | C++ | Alexander-Golova/acousticsProblemDim3 | /directProblem/Inhomogeneity.cpp | UTF-8 | 2,048 | 2.59375 | 3 | [] | no_license | #include "stdafx.h"
#include "Inhomogeneity.h"
using namespace std;
void SetRefractionIndex(vector<float> & xi) noexcept
{
const float sigma = 16.0f;
size_t coord;
for (size_t i = 0; i < N; ++i)
{
for (size_t j = 0; j < N; ++j)
{
for (size_t k = 0; k < N; ++k)
{
coord = N_SQUARED * i + N * j + k;
xi[coord] = 0.4f * exp(-(pow(i * step - 0.6f, 2) + pow(j * step - 0.6f, 2) + pow(k * step - 0.6f, 2)) * sigma);
}
}
}
}
void WriteRefractionIndex(vector<float>& xi, string name) noexcept
{
ofstream file_xi(name);
file_xi << fixed << setprecision(6);
for (size_t i = 0; i < N_QUBE; ++i)
{
file_xi << xi[i] << " ";
}
file_xi.close();
}
void SetArrayA(vector<complex<float>> & a) noexcept
{
float dist;
size_t coord;
vector<float> index(N, 1.0f);
for (size_t i = 1; i < N - 1; ++i)
{
index[i] = 1.0f;
}
index[0] = 0.5f;
index[NUMBER_PARTITION_POINTS] = 0.5f;
for (size_t i = 0; i < N; ++i)
{
for (size_t j = 0; j < N; ++j)
{
for (size_t k = 0; k < N; ++k)
{
for (size_t p = 0; p < N; ++p)
{
for (size_t q = 0; q < N; ++q)
{
for (size_t r = 0; r < N; ++r)
{
dist = sqrtf(static_cast<float>((i - p) * (i - p) + (j - q) * (j - q) + (k - r) * (k - r)));
coord = N_FIFTH_DEGREE * i + N_FOURTH_DEGREE * j + N_QUBE * k + N_SQUARED * p + N * q + r;
if (dist > 0.000001f) // DBL_EPSILON
{
a[coord] = -exp(dist * I * omega / c_0) * index[p] * index[q] * index[r] * pow(omega, 2) * pow(step, 2) * INV_FOUR_PI / dist; // TODO
}
else
{
a[coord] = 0.0f;
}
}
}
}
}
}
}
}
void WriteArrayA(vector<complex<float>> & a, string name) noexcept
{
ofstream f_a(name);
f_a << fixed << setprecision(6);
for (size_t i = 0; i < N_SIXTH_DEGREE; ++i)
{
f_a << a[i] << " ";
}
f_a.close();
}
void LoadingArrayA(std::vector<std::complex<float>>& a, std::string name) noexcept
{
ifstream f_a(name);
for (size_t i = 0; i < N_SIXTH_DEGREE; ++i)
{
f_a >> a[i];
}
f_a.close();
}
| true |
31557193fbfe31592f764bfde0decfef4543fe3b | C++ | renebarto/Simulate | /source/components/core/test/src/Test/DateTimeTest.cpp | UTF-8 | 84,206 | 3.109375 | 3 | [] | no_license | #include "unit-test-c++/UnitTestC++.h"
#include "core/DateTime.h"
#include "core/Exception.h"
#include "core/TimeSpan.h"
using namespace std;
namespace Core
{
namespace Test
{
class DateTimeTest : public UnitTestCpp::TestFixture
{
public:
virtual void SetUp();
virtual void TearDown();
};
void DateTimeTest::SetUp()
{
}
void DateTimeTest::TearDown()
{
}
TEST_FIXTURE(DateTimeTest, Construction)
{
DateTime dateTime;
EXPECT_EQ(1970, dateTime.Year());
EXPECT_EQ(1, dateTime.Month());
EXPECT_EQ(1, dateTime.MonthDay());
EXPECT_EQ(MonthType::January, dateTime.MonthName());
EXPECT_EQ(WeekDayType::Thursday, dateTime.WeekDay());
EXPECT_EQ(1, dateTime.YearDay());
EXPECT_EQ(0, dateTime.Hour());
EXPECT_EQ(0, dateTime.Minute());
EXPECT_EQ(0, dateTime.Second());
EXPECT_EQ(0, dateTime.MicroSeconds());
EXPECT_EQ(1970, dateTime.WeekNumberingYear());
EXPECT_EQ(1, dateTime.WeekOfYear());
}
TEST_FIXTURE(DateTimeTest, ConstructionCopy)
{
int year = 2014;
int month = 2;
int day = 26;
int yearDay = 57;
MonthType monthName = MonthType::February;
int hour = 1;
int minute = 2;
int second = 3;
int microSeconds = 4;
int weekNumberingYear = 2014;
int weekOfYear = 9;
DateTime dateTime(year, month, day, hour, minute, second, microSeconds);
DateTime dateTime2(dateTime);
EXPECT_EQ(year, dateTime2.Year());
EXPECT_EQ(month, dateTime2.Month());
EXPECT_EQ(day, dateTime2.MonthDay());
EXPECT_EQ(monthName, dateTime2.MonthName());
EXPECT_EQ(WeekDayType::Wednesday, dateTime2.WeekDay());
EXPECT_EQ(yearDay, dateTime2.YearDay());
EXPECT_EQ(hour, dateTime2.Hour());
EXPECT_EQ(minute, dateTime2.Minute());
EXPECT_EQ(second, dateTime2.Second());
EXPECT_EQ(microSeconds, dateTime2.MicroSeconds());
EXPECT_EQ(weekNumberingYear, dateTime2.WeekNumberingYear());
EXPECT_EQ(weekOfYear, dateTime2.WeekOfYear());
}
TEST_FIXTURE(DateTimeTest, ConstructionYearMonthDayHourMinuteSecondMicroSecond)
{
int year = 2014;
int month = 2;
int day = 26;
int yearDay = 57;
MonthType monthName = MonthType::February;
WeekDayType weekDay = WeekDayType::Wednesday;
int hour = 1;
int minute = 2;
int second = 3;
int microSeconds = 4;
int weekNumberingYear = 2014;
int weekOfYear = 9;
DateTime dateTime(year, month, day, hour, minute, second, microSeconds);
EXPECT_EQ(year, dateTime.Year());
EXPECT_EQ(month, dateTime.Month());
EXPECT_EQ(day, dateTime.MonthDay());
EXPECT_EQ(monthName, dateTime.MonthName());
EXPECT_EQ(weekDay, dateTime.WeekDay());
EXPECT_EQ(yearDay, dateTime.YearDay());
EXPECT_EQ(hour, dateTime.Hour());
EXPECT_EQ(minute, dateTime.Minute());
EXPECT_EQ(second, dateTime.Second());
EXPECT_EQ(microSeconds, dateTime.MicroSeconds());
EXPECT_EQ(weekNumberingYear, dateTime.WeekNumberingYear());
EXPECT_EQ(weekOfYear, dateTime.WeekOfYear());
}
TEST_FIXTURE(DateTimeTest, ConstructionYearMonthDayHourMinuteSecondMicroSecondEndOfYear)
{
int year = 2013;
int month = 12;
int day = 31;
int yearDay = 365;
MonthType monthName = MonthType::December;
WeekDayType weekDay = WeekDayType::Tuesday;
int hour = 1;
int minute = 2;
int second = 3;
int microSeconds = 4;
int weekNumberingYear = 2014;
int weekOfYear = 1;
DateTime dateTime(year, month, day, hour, minute, second, microSeconds);
EXPECT_EQ(year, dateTime.Year());
EXPECT_EQ(month, dateTime.Month());
EXPECT_EQ(day, dateTime.MonthDay());
EXPECT_EQ(monthName, dateTime.MonthName());
EXPECT_EQ(weekDay, dateTime.WeekDay());
EXPECT_EQ(yearDay, dateTime.YearDay());
EXPECT_EQ(hour, dateTime.Hour());
EXPECT_EQ(minute, dateTime.Minute());
EXPECT_EQ(second, dateTime.Second());
EXPECT_EQ(microSeconds, dateTime.MicroSeconds());
EXPECT_EQ(weekNumberingYear, dateTime.WeekNumberingYear());
EXPECT_EQ(weekOfYear, dateTime.WeekOfYear());
}
TEST_FIXTURE(DateTimeTest, ConstructionYearMonthDayHourMinuteSecond)
{
int year = 2014;
int month = 2;
int day = 26;
int yearDay = 57;
MonthType monthName = MonthType::February;
WeekDayType weekDay = WeekDayType::Wednesday;
int hour = 1;
int minute = 2;
int second = 3;
int microSeconds = 0;
DateTime dateTime(year, month, day, hour, minute, second);
EXPECT_EQ(year, dateTime.Year());
EXPECT_EQ(month, dateTime.Month());
EXPECT_EQ(day, dateTime.MonthDay());
EXPECT_EQ(monthName, dateTime.MonthName());
EXPECT_EQ(weekDay, dateTime.WeekDay());
EXPECT_EQ(yearDay, dateTime.YearDay());
EXPECT_EQ(hour, dateTime.Hour());
EXPECT_EQ(minute, dateTime.Minute());
EXPECT_EQ(second, dateTime.Second());
EXPECT_EQ(microSeconds, dateTime.MicroSeconds());
}
TEST_FIXTURE(DateTimeTest, ConstructionYearMonthNameDayHourMinuteSecondMicroSecond)
{
int year = 2014;
int month = 2;
int day = 26;
int yearDay = 57;
MonthType monthName = MonthType::February;
WeekDayType weekDay = WeekDayType::Wednesday;
int hour = 1;
int minute = 2;
int second = 3;
int microSeconds = 4;
DateTime dateTime(year, monthName, day, hour, minute, second, microSeconds);
EXPECT_EQ(year, dateTime.Year());
EXPECT_EQ(month, dateTime.Month());
EXPECT_EQ(day, dateTime.MonthDay());
EXPECT_EQ(monthName, dateTime.MonthName());
EXPECT_EQ(weekDay, dateTime.WeekDay());
EXPECT_EQ(yearDay, dateTime.YearDay());
EXPECT_EQ(hour, dateTime.Hour());
EXPECT_EQ(minute, dateTime.Minute());
EXPECT_EQ(second, dateTime.Second());
EXPECT_EQ(microSeconds, dateTime.MicroSeconds());
}
TEST_FIXTURE(DateTimeTest, ConstructionYearMonthNameDayHourMinuteSecond)
{
int year = 2014;
int month = 2;
int day = 26;
int yearDay = 57;
MonthType monthName = MonthType::February;
WeekDayType weekDay = WeekDayType::Wednesday;
int hour = 1;
int minute = 2;
int second = 3;
int microSeconds = 0;
DateTime dateTime(year, monthName, day, hour, minute, second);
EXPECT_EQ(year, dateTime.Year());
EXPECT_EQ(month, dateTime.Month());
EXPECT_EQ(day, dateTime.MonthDay());
EXPECT_EQ(monthName, dateTime.MonthName());
EXPECT_EQ(weekDay, dateTime.WeekDay());
EXPECT_EQ(yearDay, dateTime.YearDay());
EXPECT_EQ(hour, dateTime.Hour());
EXPECT_EQ(minute, dateTime.Minute());
EXPECT_EQ(second, dateTime.Second());
EXPECT_EQ(microSeconds, dateTime.MicroSeconds());
}
TEST_FIXTURE(DateTimeTest, ConstructionEpoch)
{
int year = 2014;
int month = 2;
int day = 26;
int yearDay = 57;
int hour = 0; // UTC
int minute = 2;
int second = 3;
int microSeconds = 0;
MonthType monthName = MonthType::February;
WeekDayType weekDay = WeekDayType::Wednesday;
time_t epochTime = 1393372923;
DateTime dateTime(epochTime);
EXPECT_EQ(year, dateTime.Year());
EXPECT_EQ(month, dateTime.Month());
EXPECT_EQ(day, dateTime.MonthDay());
EXPECT_EQ(monthName, dateTime.MonthName());
EXPECT_EQ(weekDay, dateTime.WeekDay());
EXPECT_EQ(yearDay, dateTime.YearDay());
EXPECT_EQ(hour, dateTime.Hour());
EXPECT_EQ(minute, dateTime.Minute());
EXPECT_EQ(second, dateTime.Second());
EXPECT_EQ(microSeconds, dateTime.MicroSeconds());
}
TEST_FIXTURE(DateTimeTest, ConstructionTimeSpec)
{
int year = 2014;
int month = 2;
int day = 26;
int yearDay = 57;
int hour = 0; // UTC
int minute = 2;
int second = 3;
int microSeconds = 4;
MonthType monthName = MonthType::February;
WeekDayType weekDay = WeekDayType::Wednesday;
timespec timeSpec = { 1393372923, 4000 };
DateTime dateTime(timeSpec);
EXPECT_EQ(year, dateTime.Year());
EXPECT_EQ(month, dateTime.Month());
EXPECT_EQ(day, dateTime.MonthDay());
EXPECT_EQ(monthName, dateTime.MonthName());
EXPECT_EQ(weekDay, dateTime.WeekDay());
EXPECT_EQ(yearDay, dateTime.YearDay());
EXPECT_EQ(hour, dateTime.Hour());
EXPECT_EQ(minute, dateTime.Minute());
EXPECT_EQ(second, dateTime.Second());
EXPECT_EQ(microSeconds, dateTime.MicroSeconds());
}
TEST_FIXTURE(DateTimeTest, ConstructionTimeVal)
{
int year = 2014;
int month = 2;
int day = 26;
int yearDay = 57;
int hour = 0; // UTC
int minute = 2;
int second = 3;
int microSeconds = 4;
MonthType monthName = MonthType::February;
WeekDayType weekDay = WeekDayType::Wednesday;
timeval timeVal = { 1393372923, 4 };
DateTime dateTime(timeVal);
EXPECT_EQ(year, dateTime.Year());
EXPECT_EQ(month, dateTime.Month());
EXPECT_EQ(day, dateTime.MonthDay());
EXPECT_EQ(monthName, dateTime.MonthName());
EXPECT_EQ(weekDay, dateTime.WeekDay());
EXPECT_EQ(yearDay, dateTime.YearDay());
EXPECT_EQ(hour, dateTime.Hour());
EXPECT_EQ(minute, dateTime.Minute());
EXPECT_EQ(second, dateTime.Second());
EXPECT_EQ(microSeconds, dateTime.MicroSeconds());
}
TEST_FIXTURE(DateTimeTest, Assignment)
{
int year = 2014;
int month = 2;
int day = 26;
int hour = 1;
int minute = 2;
int second = 3;
int microSeconds = 4;
DateTime dateTime(year, month, day, hour, minute, second, microSeconds);
DateTime dateTime2;
dateTime2 = dateTime;
EXPECT_EQ(year, dateTime2.Year());
EXPECT_EQ(month, dateTime2.Month());
EXPECT_EQ(day, dateTime2.MonthDay());
EXPECT_EQ(hour, dateTime2.Hour());
EXPECT_EQ(minute, dateTime2.Minute());
EXPECT_EQ(second, dateTime2.Second());
EXPECT_EQ(microSeconds, dateTime2.MicroSeconds());
}
TEST_FIXTURE(DateTimeTest, AssignmentEpoch)
{
int yearExpected = 2014;
int monthExpected = 2;
int dayExpected = 26;
int hourExpected = 0; // UTC
int minuteExpected = 2;
int secondExpected = 3;
int microSecondsExpected = 0;
time_t epochTime = 1393372923;
DateTime dateTime;
dateTime = epochTime;
EXPECT_EQ(yearExpected, dateTime.Year());
EXPECT_EQ(monthExpected, dateTime.Month());
EXPECT_EQ(dayExpected, dateTime.MonthDay());
EXPECT_EQ(hourExpected, dateTime.Hour());
EXPECT_EQ(minuteExpected, dateTime.Minute());
EXPECT_EQ(secondExpected, dateTime.Second());
EXPECT_EQ(microSecondsExpected, dateTime.MicroSeconds());
}
TEST_FIXTURE(DateTimeTest, AssignmentTimeSpec)
{
int yearExpected = 2014;
int monthExpected = 2;
int dayExpected = 26;
int hourExpected = 0; // UTC
int minuteExpected = 2;
int secondExpected = 3;
int microSecondsExpected = 4;
timespec timeSpec = { 1393372923, 4000 };
DateTime dateTime;
dateTime = timeSpec;
EXPECT_EQ(yearExpected, dateTime.Year());
EXPECT_EQ(monthExpected, dateTime.Month());
EXPECT_EQ(dayExpected, dateTime.MonthDay());
EXPECT_EQ(hourExpected, dateTime.Hour());
EXPECT_EQ(minuteExpected, dateTime.Minute());
EXPECT_EQ(secondExpected, dateTime.Second());
EXPECT_EQ(microSecondsExpected, dateTime.MicroSeconds());
}
TEST_FIXTURE(DateTimeTest, AssignmentTimeVal)
{
int yearExpected = 2014;
int monthExpected = 2;
int dayExpected = 26;
int hourExpected = 0; // UTC
int minuteExpected = 2;
int secondExpected = 3;
int microSecondsExpected = 4;
timeval timeVal = { 1393372923, 4 };
DateTime dateTime;
dateTime = timeVal;
EXPECT_EQ(yearExpected, dateTime.Year());
EXPECT_EQ(monthExpected, dateTime.Month());
EXPECT_EQ(dayExpected, dateTime.MonthDay());
EXPECT_EQ(hourExpected, dateTime.Hour());
EXPECT_EQ(minuteExpected, dateTime.Minute());
EXPECT_EQ(secondExpected, dateTime.Second());
EXPECT_EQ(microSecondsExpected, dateTime.MicroSeconds());
}
TEST_FIXTURE(DateTimeTest, CastOperatorEpochMicroSecondsFromLocalTime)
{
int year = 2014;
int month = 2;
int day = 26;
int hour = 1;
int minute = 2;
int second = 3;
int microSeconds = 4;
DateTime dateTime(year, month, day, hour, minute, second, microSeconds);
time_t epochExpected = 1393372923;
EXPECT_EQ(epochExpected, time_t(dateTime));
}
TEST_FIXTURE(DateTimeTest, CastOperatorEpochMicroSecondsFromUTCTime)
{
int year = 2014;
int month = 2;
int day = 26;
int hour = 0;
int minute = 2;
int second = 3;
int microSeconds = 4;
DateTime dateTime = DateTime::CreateUTC(year, month, day, hour, minute, second, microSeconds);
time_t epochExpected = 1393372923;
EXPECT_EQ(epochExpected, time_t(dateTime));
}
TEST_FIXTURE(DateTimeTest, CastOperatorTimeSpec)
{
int year = 2014;
int month = 2;
int day = 26;
int hour = 1;
int minute = 2;
int second = 3;
int microSeconds = 4;
DateTime dateTime(year, month, day, hour, minute, second, microSeconds);
timespec timeSpecExpected = { 1393372923, 4000 };
timespec timeSpecActual = timespec(dateTime);
EXPECT_EQ(timeSpecExpected.tv_sec, timeSpecActual.tv_sec);
EXPECT_EQ(timeSpecExpected.tv_nsec, timeSpecActual.tv_nsec);
}
TEST_FIXTURE(DateTimeTest, CastOperatorTimeVal)
{
int year = 2014;
int month = 2;
int day = 26;
int hour = 1;
int minute = 2;
int second = 3;
int microSeconds = 4;
DateTime dateTime(year, month, day, hour, minute, second, microSeconds);
timeval timeValExpected = { 1393372923, 4 };
timeval timeValActual = timeval(dateTime);
EXPECT_EQ(timeValExpected.tv_sec, timeValActual.tv_sec);
EXPECT_EQ(timeValExpected.tv_usec, timeValActual.tv_usec);
}
TEST_FIXTURE(DateTimeTest, AddAssignment)
{
int year = 2014;
int month = 2;
int day = 26;
int hour = 1;
int minute = 2;
int second = 3;
int microSeconds = 4;
DateTime dateTime(year, month, day, hour, minute, second, microSeconds);
TimeSpan add(4000000123450000);
dateTime += add;
int yearExpected = 2014;
int monthExpected = 4;
int dayExpected = 13;
int hourExpected = 9;
int minuteExpected = 8;
int secondExpected = 43;
int microSecondsExpected = 123454;
EXPECT_EQ(yearExpected, dateTime.Year());
EXPECT_EQ(monthExpected, dateTime.Month());
EXPECT_EQ(dayExpected, dateTime.MonthDay());
EXPECT_EQ(hourExpected, dateTime.Hour());
EXPECT_EQ(minuteExpected, dateTime.Minute());
EXPECT_EQ(secondExpected, dateTime.Second());
EXPECT_EQ(microSecondsExpected, dateTime.MicroSeconds());
}
TEST_FIXTURE(DateTimeTest, SubtractAssignment)
{
int year = 2014;
int month = 2;
int day = 26;
int hour = 1;
int minute = 2;
int second = 3;
int microSeconds = 4;
DateTime dateTime(year, month, day, hour, minute, second, microSeconds);
TimeSpan subtract(4000000123450000);
dateTime -= subtract;
int yearExpected = 2014;
int monthExpected = 1;
int dayExpected = 10;
int hourExpected = 17;
int minuteExpected = 55;
int secondExpected = 22;
int microSecondsExpected = 876554;
EXPECT_EQ(yearExpected, dateTime.Year());
EXPECT_EQ(monthExpected, dateTime.Month());
EXPECT_EQ(dayExpected, dateTime.MonthDay());
EXPECT_EQ(hourExpected, dateTime.Hour());
EXPECT_EQ(minuteExpected, dateTime.Minute());
EXPECT_EQ(secondExpected, dateTime.Second());
EXPECT_EQ(microSecondsExpected, dateTime.MicroSeconds());
}
TEST_FIXTURE(DateTimeTest, Equals)
{
int year1 = 2014;
int month1 = 3;
int day1 = 26;
int hour1 = 12;
int minute1 = 34;
int second1 = 56;
int microSeconds1 = 789;
int year2 = 2016;
int month2 = 4;
int day2 = 30;
int hour2 = 13;
int minute2 = 35;
int second2 = 57;
int microSeconds2 = 789123;
DateTime dateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
DateTime dateTime1(year2, month1, day1, hour1, minute1, second1, microSeconds1);
DateTime dateTime2(year1, month2, day1, hour1, minute1, second1, microSeconds1);
DateTime dateTime3(year1, month1, day2, hour1, minute1, second1, microSeconds1);
DateTime dateTime4(year1, month1, day1, hour2, minute1, second1, microSeconds1);
DateTime dateTime5(year1, month1, day1, hour1, minute2, second1, microSeconds1);
DateTime dateTime6(year1, month1, day1, hour1, minute1, second2, microSeconds1);
DateTime dateTime7(year1, month1, day1, hour1, minute1, second1, microSeconds2);
DateTime dateTime8(year1, month1, day1, hour1, minute1, second1, microSeconds1);
EXPECT_TRUE(dateTime.Equals(dateTime));
EXPECT_FALSE(dateTime.Equals(dateTime1));
EXPECT_FALSE(dateTime.Equals(dateTime2));
EXPECT_FALSE(dateTime.Equals(dateTime3));
EXPECT_FALSE(dateTime.Equals(dateTime4));
EXPECT_FALSE(dateTime.Equals(dateTime5));
EXPECT_FALSE(dateTime.Equals(dateTime6));
EXPECT_FALSE(dateTime.Equals(dateTime7));
EXPECT_TRUE(dateTime.Equals(dateTime8));
EXPECT_TRUE(dateTime8.Equals(dateTime));
EXPECT_FALSE(dateTime1.Equals(dateTime));
}
TEST_FIXTURE(DateTimeTest, LessThan)
{
int year1 = 2014;
int month1 = 3;
int day1 = 26;
int hour1 = 12;
int minute1 = 34;
int second1 = 56;
int microSeconds1 = 789;
int year2 = 2016;
int month2 = 4;
int day2 = 30;
int hour2 = 13;
int minute2 = 35;
int second2 = 57;
int microSeconds2 = 789123;
DateTime dateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
DateTime dateTime1(year2, month1, day1, hour1, minute1, second1, microSeconds1);
DateTime dateTime2(year1, month2, day1, hour1, minute1, second1, microSeconds1);
DateTime dateTime3(year1, month1, day2, hour1, minute1, second1, microSeconds1);
DateTime dateTime4(year1, month1, day1, hour2, minute1, second1, microSeconds1);
DateTime dateTime5(year1, month1, day1, hour1, minute2, second1, microSeconds1);
DateTime dateTime6(year1, month1, day1, hour1, minute1, second2, microSeconds1);
DateTime dateTime7(year1, month1, day1, hour1, minute1, second1, microSeconds2);
DateTime dateTime8(year1, month1, day1, hour1, minute1, second1, microSeconds1);
EXPECT_FALSE(dateTime.LessThan(dateTime));
EXPECT_TRUE(dateTime.LessThan(dateTime1));
EXPECT_TRUE(dateTime.LessThan(dateTime2));
EXPECT_TRUE(dateTime.LessThan(dateTime3));
EXPECT_TRUE(dateTime.LessThan(dateTime4));
EXPECT_TRUE(dateTime.LessThan(dateTime5));
EXPECT_TRUE(dateTime.LessThan(dateTime6));
EXPECT_TRUE(dateTime.LessThan(dateTime7));
EXPECT_FALSE(dateTime.LessThan(dateTime8));
EXPECT_FALSE(dateTime1.LessThan(dateTime));
EXPECT_FALSE(dateTime2.LessThan(dateTime));
EXPECT_FALSE(dateTime3.LessThan(dateTime));
EXPECT_FALSE(dateTime4.LessThan(dateTime));
EXPECT_FALSE(dateTime5.LessThan(dateTime));
EXPECT_FALSE(dateTime6.LessThan(dateTime));
EXPECT_FALSE(dateTime7.LessThan(dateTime));
EXPECT_FALSE(dateTime8.LessThan(dateTime));
}
TEST_FIXTURE(DateTimeTest, NowLocal)
{
DateTime currentDateTime = DateTime::NowLocal();
time_t timeVal = time(0);
#if defined(_MSC_VER)
#pragma warning (disable: 4996)
#endif
tm timeLocal = *localtime(&timeVal);
#if defined(_MSC_VER)
#pragma warning (default: 4996)
#endif
EXPECT_EQ(timeLocal.tm_year + 1900, currentDateTime.Year());
EXPECT_EQ(timeLocal.tm_mon + 1, currentDateTime.Month());
EXPECT_EQ(timeLocal.tm_mday, currentDateTime.MonthDay());
EXPECT_EQ(timeLocal.tm_hour, currentDateTime.Hour());
EXPECT_EQ(timeLocal.tm_min, currentDateTime.Minute());
EXPECT_EQ(timeLocal.tm_sec, currentDateTime.Second());
}
TEST_FIXTURE(DateTimeTest, NowUTC)
{
DateTime currentDateTime = DateTime::NowUTC();
time_t timeVal = time(0);
#if defined(_MSC_VER)
#pragma warning (disable: 4996)
#endif
tm timeLocal = *gmtime(&timeVal);
#if defined(_MSC_VER)
#pragma warning (default: 4996)
#endif
EXPECT_EQ(timeLocal.tm_year + 1900, currentDateTime.Year());
EXPECT_EQ(timeLocal.tm_mon + 1, currentDateTime.Month());
EXPECT_EQ(timeLocal.tm_mday, currentDateTime.MonthDay());
EXPECT_EQ(timeLocal.tm_hour, currentDateTime.Hour());
EXPECT_EQ(timeLocal.tm_min, currentDateTime.Minute());
EXPECT_EQ(timeLocal.tm_sec, currentDateTime.Second());
}
TEST_FIXTURE(DateTimeTest, CreateUTCYearMonthDayHourMinuteSecond)
{
int year = 2014;
int month = 2;
int day = 26;
int hour = 1;
int minute = 2;
int second = 3;
int microSeconds = 0;
DateTime dateTime = DateTime::CreateUTC(year, month, day, hour, minute, second);
EXPECT_EQ(year, dateTime.Year());
EXPECT_EQ(month, dateTime.Month());
EXPECT_EQ(day, dateTime.MonthDay());
EXPECT_EQ(hour, dateTime.Hour());
EXPECT_EQ(minute, dateTime.Minute());
EXPECT_EQ(second, dateTime.Second());
EXPECT_EQ(microSeconds, dateTime.MicroSeconds());
}
TEST_FIXTURE(DateTimeTest, CreateUTCYearMonthDayHourMinuteSecondMicroSecond)
{
int year = 2014;
int month = 2;
int day = 26;
int hour = 1;
int minute = 2;
int second = 3;
int microSeconds = 4;
DateTime dateTime = DateTime::CreateUTC(year, month, day, hour, minute, second, microSeconds);
EXPECT_EQ(year, dateTime.Year());
EXPECT_EQ(month, dateTime.Month());
EXPECT_EQ(day, dateTime.MonthDay());
EXPECT_EQ(hour, dateTime.Hour());
EXPECT_EQ(minute, dateTime.Minute());
EXPECT_EQ(second, dateTime.Second());
EXPECT_EQ(microSeconds, dateTime.MicroSeconds());
}
TEST_FIXTURE(DateTimeTest, CreateUTCYearMonthNameDayHourMinuteSecond)
{
int year = 2014;
int month = 2;
MonthType monthName = MonthType::February;
int day = 26;
int hour = 1;
int minute = 2;
int second = 3;
int microSeconds = 0;
DateTime dateTime = DateTime::CreateUTC(year, monthName, day, hour, minute, second);
EXPECT_EQ(year, dateTime.Year());
EXPECT_EQ(month, dateTime.Month());
EXPECT_EQ(day, dateTime.MonthDay());
EXPECT_EQ(hour, dateTime.Hour());
EXPECT_EQ(minute, dateTime.Minute());
EXPECT_EQ(second, dateTime.Second());
EXPECT_EQ(microSeconds, dateTime.MicroSeconds());
}
TEST_FIXTURE(DateTimeTest, CreateUTCYearMonthNameDayHourMinuteSecondMicroSecond)
{
int year = 2014;
int month = 2;
MonthType monthName = MonthType::February;
int day = 26;
int hour = 1;
int minute = 2;
int second = 3;
int microSeconds = 4;
DateTime dateTime = DateTime::CreateUTC(year, monthName, day, hour, minute, second, microSeconds);
EXPECT_EQ(year, dateTime.Year());
EXPECT_EQ(month, dateTime.Month());
EXPECT_EQ(day, dateTime.MonthDay());
EXPECT_EQ(hour, dateTime.Hour());
EXPECT_EQ(minute, dateTime.Minute());
EXPECT_EQ(second, dateTime.Second());
EXPECT_EQ(microSeconds, dateTime.MicroSeconds());
}
TEST_FIXTURE(DateTimeTest, CreateLocalYearMonthDayHourMinuteSecond)
{
int year = 2014;
int month = 2;
int day = 26;
int hour = 1;
int minute = 2;
int second = 3;
int microSeconds = 0;
DateTime dateTime = DateTime::CreateLocal(year, month, day, hour, minute, second);
EXPECT_EQ(year, dateTime.Year());
EXPECT_EQ(month, dateTime.Month());
EXPECT_EQ(day, dateTime.MonthDay());
EXPECT_EQ(hour, dateTime.Hour());
EXPECT_EQ(minute, dateTime.Minute());
EXPECT_EQ(second, dateTime.Second());
EXPECT_EQ(microSeconds, dateTime.MicroSeconds());
}
TEST_FIXTURE(DateTimeTest, CreateLocalYearMonthDayHourMinuteSecondMicroSecond)
{
int year = 2014;
int month = 2;
int day = 26;
int hour = 1;
int minute = 2;
int second = 3;
int microSeconds = 4;
DateTime dateTime = DateTime::CreateLocal(year, month, day, hour, minute, second, microSeconds);
EXPECT_EQ(year, dateTime.Year());
EXPECT_EQ(month, dateTime.Month());
EXPECT_EQ(day, dateTime.MonthDay());
EXPECT_EQ(hour, dateTime.Hour());
EXPECT_EQ(minute, dateTime.Minute());
EXPECT_EQ(second, dateTime.Second());
EXPECT_EQ(microSeconds, dateTime.MicroSeconds());
}
TEST_FIXTURE(DateTimeTest, CreateLocalYearMonthNameDayHourMinuteSecond)
{
int year = 2014;
int month = 2;
MonthType monthName = MonthType::February;
int day = 26;
int hour = 1;
int minute = 2;
int second = 3;
int microSeconds = 0;
DateTime dateTime = DateTime::CreateLocal(year, monthName, day, hour, minute, second);
EXPECT_EQ(year, dateTime.Year());
EXPECT_EQ(month, dateTime.Month());
EXPECT_EQ(day, dateTime.MonthDay());
EXPECT_EQ(hour, dateTime.Hour());
EXPECT_EQ(minute, dateTime.Minute());
EXPECT_EQ(second, dateTime.Second());
EXPECT_EQ(microSeconds, dateTime.MicroSeconds());
}
TEST_FIXTURE(DateTimeTest, CreateLocalYearMonthNameDayHourMinuteSecondMicroSecond)
{
int year = 2014;
int month = 2;
MonthType monthName = MonthType::February;
int day = 26;
int hour = 1;
int minute = 2;
int second = 3;
int microSeconds = 4;
DateTime dateTime = DateTime::CreateLocal(year, monthName, day, hour, minute, second, microSeconds);
EXPECT_EQ(year, dateTime.Year());
EXPECT_EQ(month, dateTime.Month());
EXPECT_EQ(day, dateTime.MonthDay());
EXPECT_EQ(hour, dateTime.Hour());
EXPECT_EQ(minute, dateTime.Minute());
EXPECT_EQ(second, dateTime.Second());
EXPECT_EQ(microSeconds, dateTime.MicroSeconds());
}
#if defined(__GNUC__)
TEST_FIXTURE(DateTimeTest, OffsetFromUTC)
{
DateTime dateTime = DateTime::CreateLocal(2014, 02, 26, 1, 2, 3, 567891);
time_t time = dateTime;
tm localTime = *localtime(&time);
int64_t expected = localTime.tm_gmtoff * DateTime::MicroSecondsPerSecond;
int64_t actual = dateTime.OffsetFromUTC().MicroSeconds();
EXPECT_EQ(expected, actual);
}
#endif
#if defined(__GNUC__)
TEST_FIXTURE(DateTimeTest, OffsetFromUTC_SummerTime)
{
DateTime dateTime = DateTime::CreateLocal(2014, 06, 26, 1, 2, 3, 567891);
time_t time = dateTime;
tm localTime = *localtime(&time);
int64_t expected = localTime.tm_gmtoff * DateTime::MicroSecondsPerSecond;
int64_t actual = dateTime.OffsetFromUTC().MicroSeconds();
EXPECT_EQ(expected, actual);
}
#endif
#if defined(__GNUC__)
TEST_FIXTURE(DateTimeTest, TimeZoneNameLocal)
{
DateTime dateTime(2014, 02, 26, 1, 2, 3, 567891);
time_t time = dateTime;
tm localTime = *localtime(&time);
string nameExpected = localTime.tm_zone;
string nameActual = dateTime.TimeZoneName();
EXPECT_EQ(nameExpected, nameActual);
}
#endif
#if defined(__GNUC__)
TEST_FIXTURE(DateTimeTest, TimeZoneNameLocalSummerTime)
{
DateTime dateTime(2014, 06, 26, 1, 2, 3, 567891);
time_t time = dateTime;
tm localTime = *localtime(&time);
string nameExpected = localTime.tm_zone;
string nameActual = dateTime.TimeZoneName();
EXPECT_EQ(nameExpected, nameActual);
}
#endif
#if defined(__GNUC__)
TEST_FIXTURE(DateTimeTest, TimeZoneNameUTC)
{
DateTime dateTime = DateTime::CreateUTC(2014, 02, 26, 1, 2, 3, 567891);
time_t time = dateTime;
tm localTime = *gmtime(&time);
string nameExpected = localTime.tm_zone;
string nameActual = dateTime.TimeZoneName();
EXPECT_EQ(nameExpected, nameActual);
}
#endif
TEST_FIXTURE(DateTimeTest, IsDayLightSavings)
{
DateTime dateTime = DateTime::CreateLocal(2014, 02, 26, 1, 2, 3, 567891);
EXPECT_FALSE(dateTime.IsDaylightSavings());
dateTime = DateTime::CreateLocal(2014, 06, 26, 1, 2, 3, 567891);
EXPECT_TRUE(dateTime.IsDaylightSavings());
}
TEST_FIXTURE(DateTimeTest, ConvertToLocalTime)
{
DateTime dateTimeUTC = DateTime::CreateUTC(2014, 02, 26, 1, 2, 3, 567891);
DateTime dateTimeLocal = dateTimeUTC.ConvertToLocalTime();
int year = 2014;
int month = 2;
int day = 26;
int hour = 2;
int minute = 2;
int second = 3;
int microSeconds = 567891;
EXPECT_EQ(year, dateTimeLocal.Year());
EXPECT_EQ(month, dateTimeLocal.Month());
EXPECT_EQ(day, dateTimeLocal.MonthDay());
EXPECT_EQ(hour, dateTimeLocal.Hour());
EXPECT_EQ(minute, dateTimeLocal.Minute());
EXPECT_EQ(second, dateTimeLocal.Second());
EXPECT_EQ(microSeconds, dateTimeLocal.MicroSeconds());
}
TEST_FIXTURE(DateTimeTest, ConvertToUTCTime)
{
DateTime dateTimeLocal = DateTime::CreateLocal(2014, 02, 26, 1, 2, 3, 567891);
DateTime dateTimeUTC = dateTimeLocal.ConvertToUTCTime();
int year = 2014;
int month = 2;
int day = 26;
int hour = 0;
int minute = 2;
int second = 3;
int microSeconds = 567891;
EXPECT_EQ(year, dateTimeUTC.Year());
EXPECT_EQ(month, dateTimeUTC.Month());
EXPECT_EQ(day, dateTimeUTC.MonthDay());
EXPECT_EQ(hour, dateTimeUTC.Hour());
EXPECT_EQ(minute, dateTimeUTC.Minute());
EXPECT_EQ(second, dateTimeUTC.Second());
EXPECT_EQ(microSeconds, dateTimeUTC.MicroSeconds());
}
TEST_FIXTURE(DateTimeTest, PrintTo)
{
DateTime dateTime(2014, 02, 26, 1, 2, 3, 567891);
ostringstream stream;
PrintTo(dateTime, stream);
EXPECT_EQ("2014-02-26 01:02:03.567891", stream.str());
}
TEST_FIXTURE(DateTimeTest, PrintToFormatted)
{
DateTime dateTime = DateTime::CreateUTC(2014, 02, 26, 1, 2, 3);
ostringstream stream;
dateTime.PrintTo(stream, "%F %T");
EXPECT_EQ("2014-02-26 01:02:03", stream.str());
#if defined(__GNUC__)
stream.str("");
dateTime.PrintTo(stream, "%F %T %Z");
EXPECT_EQ("2014-02-26 01:02:03 GMT", stream.str());
#endif
}
TEST_FIXTURE(DateTimeTest, PrintToFormattedInvalidFormatString)
{
DateTime dateTime = DateTime::CreateUTC(2014, 02, 26, 1, 2, 3);
ostringstream stream;
EXPECT_THROW(dateTime.PrintTo(stream, ""), Exception);
}
TEST_FIXTURE(DateTimeTest, OperatorAddTimeSpanDateTime)
{
DateTime dateTime(2014, 2, 26, 1, 2, 3, 567891);
TimeSpan timeSpan;
DateTime actual;
DateTime expected;
timeSpan = 1000; // One microsecond
actual = timeSpan + dateTime;
expected = DateTime::CreateLocal(2014, 2, 26, 1, 2, 3, 567892);
EXPECT_EQ(expected, actual);
timeSpan = 1000000000; // One second
actual = timeSpan + dateTime;
expected = DateTime::CreateLocal(2014, 2, 26, 1, 2, 4, 567891);
EXPECT_EQ(expected, actual);
timeSpan = 60000000000ll; // One minute
actual = timeSpan + dateTime;
expected = DateTime::CreateLocal(2014, 2, 26, 1, 3, 3, 567891);
EXPECT_EQ(expected, actual);
timeSpan = 3600000000000ll; // One hour
actual = timeSpan + dateTime;
expected = DateTime::CreateLocal(2014, 2, 26, 2, 2, 3, 567891);
EXPECT_EQ(expected, actual);
timeSpan = 86400000000000ll; // One day
actual = timeSpan + dateTime;
expected = DateTime::CreateLocal(2014, 2, 27, 1, 2, 3, 567891);
EXPECT_EQ(expected, actual);
timeSpan = (28 + 31 + 30) * 86400000000000ll; // Three months (28 + 31 + 30 days)
// Adds one extra hour due to summer time (CET->CEST)
actual = timeSpan + dateTime;
expected = DateTime::CreateLocal(2014, 5, 26, 2, 2, 3, 567891);
EXPECT_EQ(expected, actual);
timeSpan = 365 * 86400000000000ll; // One year (365 days)
actual = timeSpan + dateTime;
expected = DateTime::CreateLocal(2015, 2, 26, 1, 2, 3, 567891);
EXPECT_EQ(expected, actual);
timeSpan = 40000000500000000ll;
// Adds one extra hour due to summer time (CET->CEST)
actual = timeSpan + dateTime;
expected = DateTime::CreateLocal(2015, 6, 4, 1, 8, 44, 67891);
EXPECT_EQ(expected, actual);
}
TEST_FIXTURE(DateTimeTest, OperatorAddDateTimeTimeSpan)
{
DateTime dateTime(2014, 2, 26, 1, 2, 3, 567891);
TimeSpan timeSpan;
DateTime actual;
DateTime expected;
timeSpan = 1000; // One microsecond
actual = dateTime + timeSpan;
expected = DateTime::CreateLocal(2014, 2, 26, 1, 2, 3, 567892);
EXPECT_EQ(expected, actual);
timeSpan = 1000000000; // One second
actual = dateTime + timeSpan;
expected = DateTime::CreateLocal(2014, 2, 26, 1, 2, 4, 567891);
EXPECT_EQ(expected, actual);
timeSpan = 60000000000ll; // One minute
actual = dateTime + timeSpan;
expected = DateTime::CreateLocal(2014, 2, 26, 1, 3, 3, 567891);
EXPECT_EQ(expected, actual);
timeSpan = 3600000000000ll; // One hour
actual = dateTime + timeSpan;
expected = DateTime::CreateLocal(2014, 2, 26, 2, 2, 3, 567891);
EXPECT_EQ(expected, actual);
timeSpan = 86400000000000ll; // One day
actual = dateTime + timeSpan;
expected = DateTime::CreateLocal(2014, 2, 27, 1, 2, 3, 567891);
EXPECT_EQ(expected, actual);
timeSpan = (28 + 31 + 30) * 86400000000000ll; // Three months (28 + 31 + 30 days)
// Adds one extra hour due to summer time (CET->CEST)
actual = dateTime + timeSpan;
expected = DateTime::CreateLocal(2014, 5, 26, 2, 2, 3, 567891);
EXPECT_EQ(expected, actual);
timeSpan = 365 * 86400000000000ll; // One year (365 days)
actual = dateTime + timeSpan;
expected = DateTime::CreateLocal(2015, 2, 26, 1, 2, 3, 567891);
EXPECT_EQ(expected, actual);
timeSpan = 40000000500000000ll;
// Adds one extra hour due to summer time (CET->CEST)
actual = dateTime + timeSpan;
expected = DateTime::CreateLocal(2015, 6, 4, 1, 8, 44, 67891);
EXPECT_EQ(expected, actual);
}
TEST_FIXTURE(DateTimeTest, OperatorSubtractDateTimeTimeSpan)
{
DateTime dateTime(2014, 2, 26, 1, 2, 3, 100000);
TimeSpan timeSpan;
DateTime actual;
DateTime expected;
timeSpan = 1000; // One microsecond
actual = dateTime - timeSpan;
expected = DateTime::CreateLocal(2014, 2, 26, 1, 2, 3, 99999);
EXPECT_EQ(expected, actual);
timeSpan = 1000000000; // One second
actual = dateTime - timeSpan;
expected = DateTime::CreateLocal(2014, 2, 26, 1, 2, 2, 100000);
EXPECT_EQ(expected, actual);
timeSpan = 60000000000ll; // One minute
actual = dateTime - timeSpan;
expected = DateTime::CreateLocal(2014, 2, 26, 1, 1, 3, 100000);
EXPECT_EQ(expected, actual);
timeSpan = 3600000000000ll; // One hour
actual = dateTime - timeSpan;
expected = DateTime::CreateLocal(2014, 2, 26, 0, 2, 3, 100000);
EXPECT_EQ(expected, actual);
timeSpan = 86400000000000ll; // One day
actual = dateTime - timeSpan;
expected = DateTime::CreateLocal(2014, 2, 25, 1, 2, 3, 100000);
EXPECT_EQ(expected, actual);
timeSpan = (31 + 31 + 30 + 31 + 30 + 31) * 86400000000000ll; // Six months (31 + 31 + 30 + 31 + 30 + 31 days)
// Adds one extra hour due to summer time (CET->CEST)
actual = dateTime - timeSpan;
expected = DateTime::CreateLocal(2013, 8, 26, 2, 2, 3, 100000);
EXPECT_EQ(expected, actual);
timeSpan = 365 * 86400000000000ll; // One year (365 days)
actual = dateTime - timeSpan;
expected = DateTime::CreateLocal(2013, 2, 26, 1, 2, 3, 100000);
EXPECT_EQ(expected, actual);
timeSpan = 40000000123450000ll;
// Adds one extra hour due to summer time (CET->CEST)
actual = dateTime - timeSpan;
expected = DateTime::CreateLocal(2012, 11, 20, 1, 55, 22, 976550);
EXPECT_EQ(expected, actual);
}
TEST_FIXTURE(DateTimeTest, OperatorSubtractDateTimeDateTime)
{
DateTime dateTime1(2014, 2, 26, 1, 2, 3, 100000);
DateTime dateTime2;
TimeSpan actual;
TimeSpan expected;
dateTime2 = DateTime::CreateLocal(2014, 2, 26, 1, 2, 3, 99999);
actual = dateTime1 - dateTime2;
expected = 1000; // One microsecond
EXPECT_EQ(expected, actual);
dateTime2 = DateTime::CreateLocal(2014, 2, 26, 1, 2, 2, 100000);
actual = dateTime1 - dateTime2;
expected = 1000000000; // One second
EXPECT_EQ(expected, actual);
dateTime2 = DateTime::CreateLocal(2014, 2, 26, 1, 1, 3, 100000);
actual = dateTime1 - dateTime2;
expected = 60000000000ll; // One minute
EXPECT_EQ(expected, actual);
dateTime2 = DateTime::CreateLocal(2014, 2, 26, 0, 2, 3, 100000);
actual = dateTime1 - dateTime2;
expected = 3600000000000ll; // One hour
EXPECT_EQ(expected, actual);
dateTime2 = DateTime::CreateLocal(2014, 2, 25, 1, 2, 3, 100000);
actual = dateTime1 - dateTime2;
expected = 86400000000000ll; // One day
EXPECT_EQ(expected, actual);
// Add one extra hour due to summer time (CET->CEST)
dateTime2 = DateTime::CreateLocal(2013, 8, 26, 2, 2, 3, 100000);
actual = dateTime1 - dateTime2;
expected = (31 + 31 + 30 + 31 + 30 + 31) * 86400000000000ll; // Six months (31 + 31 + 30 + 31 + 30 + 31 days)
EXPECT_EQ(expected, actual);
dateTime2 = DateTime::CreateLocal(2013, 2, 26, 1, 2, 3, 100000);
actual = dateTime1 - dateTime2;
expected = 365 * 86400000000000ll; // One year (365 days)
EXPECT_EQ(expected, actual);
// Add one extra hour due to summer time (CET->CEST)
dateTime2 = DateTime::CreateLocal(2012, 11, 20, 1, 55, 22, 976550);
actual = dateTime1 - dateTime2;
expected = 40000000123450000ll;
EXPECT_EQ(expected, actual);
}
TEST_FIXTURE(DateTimeTest, OperatorEqualsDateTimeDateTime)
{
int year1 = 2014;
int month1 = 3;
int day1 = 26;
int hour1 = 12;
int minute1 = 34;
int second1 = 56;
int microSeconds1 = 789;
int year2 = 2016;
int month2 = 4;
int day2 = 30;
int hour2 = 13;
int minute2 = 35;
int second2 = 57;
int microSeconds2 = 789123;
DateTime dateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
DateTime dateTime1(year2, month1, day1, hour1, minute1, second1, microSeconds1);
DateTime dateTime2(year1, month2, day1, hour1, minute1, second1, microSeconds1);
DateTime dateTime3(year1, month1, day2, hour1, minute1, second1, microSeconds1);
DateTime dateTime4(year1, month1, day1, hour2, minute1, second1, microSeconds1);
DateTime dateTime5(year1, month1, day1, hour1, minute2, second1, microSeconds1);
DateTime dateTime6(year1, month1, day1, hour1, minute1, second2, microSeconds1);
DateTime dateTime7(year1, month1, day1, hour1, minute1, second1, microSeconds2);
DateTime dateTime8(year1, month1, day1, hour1, minute1, second1, microSeconds1);
EXPECT_FALSE(dateTime == dateTime1);
EXPECT_FALSE(dateTime == dateTime2);
EXPECT_FALSE(dateTime == dateTime3);
EXPECT_FALSE(dateTime == dateTime4);
EXPECT_FALSE(dateTime == dateTime5);
EXPECT_FALSE(dateTime == dateTime6);
EXPECT_FALSE(dateTime == dateTime7);
EXPECT_TRUE(dateTime == dateTime8);
}
TEST_FIXTURE(DateTimeTest, OperatorEqualsTimeSpecDataTime)
{
int year1 = 2014;
int month1 = 3;
int day1 = 26;
int hour1 = 12;
int minute1 = 34;
int second1 = 56;
int microSeconds1 = 789;
int year2 = 2016;
int month2 = 4;
int day2 = 30;
int hour2 = 13;
int minute2 = 35;
int second2 = 57;
int microSeconds2 = 789123;
DateTime dateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec1 = (timespec)DateTime(year2, month1, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec2 = (timespec)DateTime(year1, month2, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec3 = (timespec)DateTime(year1, month1, day2, hour1, minute1, second1, microSeconds1);
timespec timeSpec4 = (timespec)DateTime(year1, month1, day1, hour2, minute1, second1, microSeconds1);
timespec timeSpec5 = (timespec)DateTime(year1, month1, day1, hour1, minute2, second1, microSeconds1);
timespec timeSpec6 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second2, microSeconds1);
timespec timeSpec7 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds2);
timespec timeSpec8 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
EXPECT_FALSE(timeSpec1 == dateTime);
EXPECT_FALSE(timeSpec2 == dateTime);
EXPECT_FALSE(timeSpec3 == dateTime);
EXPECT_FALSE(timeSpec4 == dateTime);
EXPECT_FALSE(timeSpec5 == dateTime);
EXPECT_FALSE(timeSpec6 == dateTime);
EXPECT_FALSE(timeSpec7 == dateTime);
EXPECT_TRUE(timeSpec8 == dateTime);
}
TEST_FIXTURE(DateTimeTest, OperatorEqualsTimeValDataTime)
{
int year1 = 2014;
int month1 = 3;
int day1 = 26;
int hour1 = 12;
int minute1 = 34;
int second1 = 56;
int microSeconds1 = 789;
int year2 = 2016;
int month2 = 4;
int day2 = 30;
int hour2 = 13;
int minute2 = 35;
int second2 = 57;
int microSeconds2 = 789123;
DateTime dateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal1 = (timeval)DateTime(year2, month1, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal2 = (timeval)DateTime(year1, month2, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal3 = (timeval)DateTime(year1, month1, day2, hour1, minute1, second1, microSeconds1);
timeval timeVal4 = (timeval)DateTime(year1, month1, day1, hour2, minute1, second1, microSeconds1);
timeval timeVal5 = (timeval)DateTime(year1, month1, day1, hour1, minute2, second1, microSeconds1);
timeval timeVal6 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second2, microSeconds1);
timeval timeVal7 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds2);
timeval timeVal8 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
EXPECT_FALSE(timeVal1 == dateTime);
EXPECT_FALSE(timeVal2 == dateTime);
EXPECT_FALSE(timeVal3 == dateTime);
EXPECT_FALSE(timeVal4 == dateTime);
EXPECT_FALSE(timeVal5 == dateTime);
EXPECT_FALSE(timeVal6 == dateTime);
EXPECT_FALSE(timeVal7 == dateTime);
EXPECT_TRUE(timeVal8 == dateTime);
}
TEST_FIXTURE(DateTimeTest, OperatorEqualsDateTimeTimeSpec)
{
int year1 = 2014;
int month1 = 3;
int day1 = 26;
int hour1 = 12;
int minute1 = 34;
int second1 = 56;
int microSeconds1 = 789;
int year2 = 2016;
int month2 = 4;
int day2 = 30;
int hour2 = 13;
int minute2 = 35;
int second2 = 57;
int microSeconds2 = 789123;
DateTime dateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec1 = (timespec)DateTime(year2, month1, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec2 = (timespec)DateTime(year1, month2, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec3 = (timespec)DateTime(year1, month1, day2, hour1, minute1, second1, microSeconds1);
timespec timeSpec4 = (timespec)DateTime(year1, month1, day1, hour2, minute1, second1, microSeconds1);
timespec timeSpec5 = (timespec)DateTime(year1, month1, day1, hour1, minute2, second1, microSeconds1);
timespec timeSpec6 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second2, microSeconds1);
timespec timeSpec7 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds2);
timespec timeSpec8 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
EXPECT_FALSE(dateTime == timeSpec1);
EXPECT_FALSE(dateTime == timeSpec2);
EXPECT_FALSE(dateTime == timeSpec3);
EXPECT_FALSE(dateTime == timeSpec4);
EXPECT_FALSE(dateTime == timeSpec5);
EXPECT_FALSE(dateTime == timeSpec6);
EXPECT_FALSE(dateTime == timeSpec7);
EXPECT_TRUE(dateTime == timeSpec8);
}
TEST_FIXTURE(DateTimeTest, OperatorEqualsDateTimeTimeVal)
{
int year1 = 2014;
int month1 = 3;
int day1 = 26;
int hour1 = 12;
int minute1 = 34;
int second1 = 56;
int microSeconds1 = 789;
int year2 = 2016;
int month2 = 4;
int day2 = 30;
int hour2 = 13;
int minute2 = 35;
int second2 = 57;
int microSeconds2 = 789123;
DateTime dateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal1 = (timeval)DateTime(year2, month1, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal2 = (timeval)DateTime(year1, month2, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal3 = (timeval)DateTime(year1, month1, day2, hour1, minute1, second1, microSeconds1);
timeval timeVal4 = (timeval)DateTime(year1, month1, day1, hour2, minute1, second1, microSeconds1);
timeval timeVal5 = (timeval)DateTime(year1, month1, day1, hour1, minute2, second1, microSeconds1);
timeval timeVal6 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second2, microSeconds1);
timeval timeVal7 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds2);
timeval timeVal8 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
EXPECT_FALSE(dateTime == timeVal1);
EXPECT_FALSE(dateTime == timeVal2);
EXPECT_FALSE(dateTime == timeVal3);
EXPECT_FALSE(dateTime == timeVal4);
EXPECT_FALSE(dateTime == timeVal5);
EXPECT_FALSE(dateTime == timeVal6);
EXPECT_FALSE(dateTime == timeVal7);
EXPECT_TRUE(dateTime == timeVal8);
}
TEST_FIXTURE(DateTimeTest, OperatorNotEqualsDateTimeDateTime)
{
int year1 = 2014;
int month1 = 3;
int day1 = 26;
int hour1 = 12;
int minute1 = 34;
int second1 = 56;
int microSeconds1 = 789;
int year2 = 2016;
int month2 = 4;
int day2 = 30;
int hour2 = 13;
int minute2 = 35;
int second2 = 57;
int microSeconds2 = 789123;
DateTime dateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
DateTime dateTime1(year2, month1, day1, hour1, minute1, second1, microSeconds1);
DateTime dateTime2(year1, month2, day1, hour1, minute1, second1, microSeconds1);
DateTime dateTime3(year1, month1, day2, hour1, minute1, second1, microSeconds1);
DateTime dateTime4(year1, month1, day1, hour2, minute1, second1, microSeconds1);
DateTime dateTime5(year1, month1, day1, hour1, minute2, second1, microSeconds1);
DateTime dateTime6(year1, month1, day1, hour1, minute1, second2, microSeconds1);
DateTime dateTime7(year1, month1, day1, hour1, minute1, second1, microSeconds2);
DateTime dateTime8(year1, month1, day1, hour1, minute1, second1, microSeconds1);
EXPECT_TRUE(dateTime != dateTime1);
EXPECT_TRUE(dateTime != dateTime2);
EXPECT_TRUE(dateTime != dateTime3);
EXPECT_TRUE(dateTime != dateTime4);
EXPECT_TRUE(dateTime != dateTime5);
EXPECT_TRUE(dateTime != dateTime6);
EXPECT_TRUE(dateTime != dateTime7);
EXPECT_FALSE(dateTime != dateTime8);
}
TEST_FIXTURE(DateTimeTest, OperatorNotEqualsTimeSpecDateTime)
{
int year1 = 2014;
int month1 = 3;
int day1 = 26;
int hour1 = 12;
int minute1 = 34;
int second1 = 56;
int microSeconds1 = 789;
int year2 = 2016;
int month2 = 4;
int day2 = 30;
int hour2 = 13;
int minute2 = 35;
int second2 = 57;
int microSeconds2 = 789123;
DateTime dateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec1 = (timespec)DateTime(year2, month1, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec2 = (timespec)DateTime(year1, month2, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec3 = (timespec)DateTime(year1, month1, day2, hour1, minute1, second1, microSeconds1);
timespec timeSpec4 = (timespec)DateTime(year1, month1, day1, hour2, minute1, second1, microSeconds1);
timespec timeSpec5 = (timespec)DateTime(year1, month1, day1, hour1, minute2, second1, microSeconds1);
timespec timeSpec6 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second2, microSeconds1);
timespec timeSpec7 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds2);
timespec timeSpec8 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
EXPECT_TRUE(timeSpec1 != dateTime);
EXPECT_TRUE(timeSpec2 != dateTime);
EXPECT_TRUE(timeSpec3 != dateTime);
EXPECT_TRUE(timeSpec4 != dateTime);
EXPECT_TRUE(timeSpec5 != dateTime);
EXPECT_TRUE(timeSpec6 != dateTime);
EXPECT_TRUE(timeSpec7 != dateTime);
EXPECT_FALSE(timeSpec8 != dateTime);
}
TEST_FIXTURE(DateTimeTest, OperatorNotEqualsTimeValDateTime)
{
int year1 = 2014;
int month1 = 3;
int day1 = 26;
int hour1 = 12;
int minute1 = 34;
int second1 = 56;
int microSeconds1 = 789;
int year2 = 2016;
int month2 = 4;
int day2 = 30;
int hour2 = 13;
int minute2 = 35;
int second2 = 57;
int microSeconds2 = 789123;
DateTime dateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal1 = (timeval)DateTime(year2, month1, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal2 = (timeval)DateTime(year1, month2, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal3 = (timeval)DateTime(year1, month1, day2, hour1, minute1, second1, microSeconds1);
timeval timeVal4 = (timeval)DateTime(year1, month1, day1, hour2, minute1, second1, microSeconds1);
timeval timeVal5 = (timeval)DateTime(year1, month1, day1, hour1, minute2, second1, microSeconds1);
timeval timeVal6 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second2, microSeconds1);
timeval timeVal7 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds2);
timeval timeVal8 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
EXPECT_TRUE(timeVal1 != dateTime);
EXPECT_TRUE(timeVal2 != dateTime);
EXPECT_TRUE(timeVal3 != dateTime);
EXPECT_TRUE(timeVal4 != dateTime);
EXPECT_TRUE(timeVal5 != dateTime);
EXPECT_TRUE(timeVal6 != dateTime);
EXPECT_TRUE(timeVal7 != dateTime);
EXPECT_FALSE(timeVal8 != dateTime);
}
TEST_FIXTURE(DateTimeTest, OperatorNotEqualsDateTimeTimeSpec)
{
int year1 = 2014;
int month1 = 3;
int day1 = 26;
int hour1 = 12;
int minute1 = 34;
int second1 = 56;
int microSeconds1 = 789;
int year2 = 2016;
int month2 = 4;
int day2 = 30;
int hour2 = 13;
int minute2 = 35;
int second2 = 57;
int microSeconds2 = 789123;
DateTime dateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec1 = (timespec)DateTime(year2, month1, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec2 = (timespec)DateTime(year1, month2, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec3 = (timespec)DateTime(year1, month1, day2, hour1, minute1, second1, microSeconds1);
timespec timeSpec4 = (timespec)DateTime(year1, month1, day1, hour2, minute1, second1, microSeconds1);
timespec timeSpec5 = (timespec)DateTime(year1, month1, day1, hour1, minute2, second1, microSeconds1);
timespec timeSpec6 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second2, microSeconds1);
timespec timeSpec7 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds2);
timespec timeSpec8 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
EXPECT_TRUE(dateTime != timeSpec1);
EXPECT_TRUE(dateTime != timeSpec2);
EXPECT_TRUE(dateTime != timeSpec3);
EXPECT_TRUE(dateTime != timeSpec4);
EXPECT_TRUE(dateTime != timeSpec5);
EXPECT_TRUE(dateTime != timeSpec6);
EXPECT_TRUE(dateTime != timeSpec7);
EXPECT_FALSE(dateTime != timeSpec8);
}
TEST_FIXTURE(DateTimeTest, OperatorNotEqualsDateTimeTimeVal)
{
int year1 = 2014;
int month1 = 3;
int day1 = 26;
int hour1 = 12;
int minute1 = 34;
int second1 = 56;
int microSeconds1 = 789;
int year2 = 2016;
int month2 = 4;
int day2 = 30;
int hour2 = 13;
int minute2 = 35;
int second2 = 57;
int microSeconds2 = 789123;
DateTime dateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal1 = (timeval)DateTime(year2, month1, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal2 = (timeval)DateTime(year1, month2, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal3 = (timeval)DateTime(year1, month1, day2, hour1, minute1, second1, microSeconds1);
timeval timeVal4 = (timeval)DateTime(year1, month1, day1, hour2, minute1, second1, microSeconds1);
timeval timeVal5 = (timeval)DateTime(year1, month1, day1, hour1, minute2, second1, microSeconds1);
timeval timeVal6 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second2, microSeconds1);
timeval timeVal7 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds2);
timeval timeVal8 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
EXPECT_TRUE(dateTime != timeVal1);
EXPECT_TRUE(dateTime != timeVal2);
EXPECT_TRUE(dateTime != timeVal3);
EXPECT_TRUE(dateTime != timeVal4);
EXPECT_TRUE(dateTime != timeVal5);
EXPECT_TRUE(dateTime != timeVal6);
EXPECT_TRUE(dateTime != timeVal7);
EXPECT_FALSE(dateTime != timeVal8);
}
TEST_FIXTURE(DateTimeTest, OperatorLessDateTimeDateTime)
{
int year1 = 2014;
int month1 = 3;
int day1 = 26;
int hour1 = 12;
int minute1 = 34;
int second1 = 56;
int microSeconds1 = 789;
int year2 = 2016;
int month2 = 4;
int day2 = 30;
int hour2 = 13;
int minute2 = 35;
int second2 = 57;
int microSeconds2 = 789123;
DateTime dateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
DateTime dateTime1(year2, month1, day1, hour1, minute1, second1, microSeconds1);
DateTime dateTime2(year1, month2, day1, hour1, minute1, second1, microSeconds1);
DateTime dateTime3(year1, month1, day2, hour1, minute1, second1, microSeconds1);
DateTime dateTime4(year1, month1, day1, hour2, minute1, second1, microSeconds1);
DateTime dateTime5(year1, month1, day1, hour1, minute2, second1, microSeconds1);
DateTime dateTime6(year1, month1, day1, hour1, minute1, second2, microSeconds1);
DateTime dateTime7(year1, month1, day1, hour1, minute1, second1, microSeconds2);
DateTime dateTime8(year1, month1, day1, hour1, minute1, second1, microSeconds1);
EXPECT_TRUE(dateTime < dateTime1);
EXPECT_TRUE(dateTime < dateTime2);
EXPECT_TRUE(dateTime < dateTime3);
EXPECT_TRUE(dateTime < dateTime4);
EXPECT_TRUE(dateTime < dateTime5);
EXPECT_TRUE(dateTime < dateTime6);
EXPECT_TRUE(dateTime < dateTime7);
EXPECT_FALSE(dateTime < dateTime8);
}
TEST_FIXTURE(DateTimeTest, OperatorLessTimeSpecDateTime)
{
int year1 = 2014;
int month1 = 3;
int day1 = 26;
int hour1 = 12;
int minute1 = 34;
int second1 = 56;
int microSeconds1 = 789;
int year2 = 2016;
int month2 = 4;
int day2 = 30;
int hour2 = 13;
int minute2 = 35;
int second2 = 57;
int microSeconds2 = 789123;
DateTime dateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec1 = (timespec)DateTime(year2, month1, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec2 = (timespec)DateTime(year1, month2, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec3 = (timespec)DateTime(year1, month1, day2, hour1, minute1, second1, microSeconds1);
timespec timeSpec4 = (timespec)DateTime(year1, month1, day1, hour2, minute1, second1, microSeconds1);
timespec timeSpec5 = (timespec)DateTime(year1, month1, day1, hour1, minute2, second1, microSeconds1);
timespec timeSpec6 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second2, microSeconds1);
timespec timeSpec7 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds2);
timespec timeSpec8 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
EXPECT_FALSE(timeSpec1 < dateTime);
EXPECT_FALSE(timeSpec2 < dateTime);
EXPECT_FALSE(timeSpec3 < dateTime);
EXPECT_FALSE(timeSpec4 < dateTime);
EXPECT_FALSE(timeSpec5 < dateTime);
EXPECT_FALSE(timeSpec6 < dateTime);
EXPECT_FALSE(timeSpec7 < dateTime);
EXPECT_FALSE(timeSpec8 < dateTime);
}
TEST_FIXTURE(DateTimeTest, OperatorLessTimeValDateTime)
{
int year1 = 2014;
int month1 = 3;
int day1 = 26;
int hour1 = 12;
int minute1 = 34;
int second1 = 56;
int microSeconds1 = 789;
int year2 = 2016;
int month2 = 4;
int day2 = 30;
int hour2 = 13;
int minute2 = 35;
int second2 = 57;
int microSeconds2 = 789123;
DateTime dateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal1 = (timeval)DateTime(year2, month1, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal2 = (timeval)DateTime(year1, month2, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal3 = (timeval)DateTime(year1, month1, day2, hour1, minute1, second1, microSeconds1);
timeval timeVal4 = (timeval)DateTime(year1, month1, day1, hour2, minute1, second1, microSeconds1);
timeval timeVal5 = (timeval)DateTime(year1, month1, day1, hour1, minute2, second1, microSeconds1);
timeval timeVal6 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second2, microSeconds1);
timeval timeVal7 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds2);
timeval timeVal8 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
EXPECT_FALSE(timeVal1 < dateTime);
EXPECT_FALSE(timeVal2 < dateTime);
EXPECT_FALSE(timeVal3 < dateTime);
EXPECT_FALSE(timeVal4 < dateTime);
EXPECT_FALSE(timeVal5 < dateTime);
EXPECT_FALSE(timeVal6 < dateTime);
EXPECT_FALSE(timeVal7 < dateTime);
EXPECT_FALSE(timeVal8 < dateTime);
}
TEST_FIXTURE(DateTimeTest, OperatorLessDateTimeTimeSpec)
{
int year1 = 2014;
int month1 = 3;
int day1 = 26;
int hour1 = 12;
int minute1 = 34;
int second1 = 56;
int microSeconds1 = 789;
int year2 = 2016;
int month2 = 4;
int day2 = 30;
int hour2 = 13;
int minute2 = 35;
int second2 = 57;
int microSeconds2 = 789123;
DateTime dateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec1 = (timespec)DateTime(year2, month1, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec2 = (timespec)DateTime(year1, month2, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec3 = (timespec)DateTime(year1, month1, day2, hour1, minute1, second1, microSeconds1);
timespec timeSpec4 = (timespec)DateTime(year1, month1, day1, hour2, minute1, second1, microSeconds1);
timespec timeSpec5 = (timespec)DateTime(year1, month1, day1, hour1, minute2, second1, microSeconds1);
timespec timeSpec6 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second2, microSeconds1);
timespec timeSpec7 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds2);
timespec timeSpec8 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
EXPECT_TRUE(dateTime < timeSpec1);
EXPECT_TRUE(dateTime < timeSpec2);
EXPECT_TRUE(dateTime < timeSpec3);
EXPECT_TRUE(dateTime < timeSpec4);
EXPECT_TRUE(dateTime < timeSpec5);
EXPECT_TRUE(dateTime < timeSpec6);
EXPECT_TRUE(dateTime < timeSpec7);
EXPECT_FALSE(dateTime < timeSpec8);
}
TEST_FIXTURE(DateTimeTest, OperatorLessDateTimeTimeVal)
{
int year1 = 2014;
int month1 = 3;
int day1 = 26;
int hour1 = 12;
int minute1 = 34;
int second1 = 56;
int microSeconds1 = 789;
int year2 = 2016;
int month2 = 4;
int day2 = 30;
int hour2 = 13;
int minute2 = 35;
int second2 = 57;
int microSeconds2 = 789123;
DateTime dateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal1 = (timeval)DateTime(year2, month1, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal2 = (timeval)DateTime(year1, month2, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal3 = (timeval)DateTime(year1, month1, day2, hour1, minute1, second1, microSeconds1);
timeval timeVal4 = (timeval)DateTime(year1, month1, day1, hour2, minute1, second1, microSeconds1);
timeval timeVal5 = (timeval)DateTime(year1, month1, day1, hour1, minute2, second1, microSeconds1);
timeval timeVal6 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second2, microSeconds1);
timeval timeVal7 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds2);
timeval timeVal8 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
EXPECT_TRUE(dateTime < timeVal1);
EXPECT_TRUE(dateTime < timeVal2);
EXPECT_TRUE(dateTime < timeVal3);
EXPECT_TRUE(dateTime < timeVal4);
EXPECT_TRUE(dateTime < timeVal5);
EXPECT_TRUE(dateTime < timeVal6);
EXPECT_TRUE(dateTime < timeVal7);
EXPECT_FALSE(dateTime < timeVal8);
}
TEST_FIXTURE(DateTimeTest, OperatorGreaterDateTimeDateTime)
{
int year1 = 2014;
int month1 = 3;
int day1 = 26;
int hour1 = 12;
int minute1 = 34;
int second1 = 56;
int microSeconds1 = 789;
int year2 = 2016;
int month2 = 4;
int day2 = 30;
int hour2 = 13;
int minute2 = 35;
int second2 = 57;
int microSeconds2 = 789123;
DateTime dateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
DateTime dateTime1(year2, month1, day1, hour1, minute1, second1, microSeconds1);
DateTime dateTime2(year1, month2, day1, hour1, minute1, second1, microSeconds1);
DateTime dateTime3(year1, month1, day2, hour1, minute1, second1, microSeconds1);
DateTime dateTime4(year1, month1, day1, hour2, minute1, second1, microSeconds1);
DateTime dateTime5(year1, month1, day1, hour1, minute2, second1, microSeconds1);
DateTime dateTime6(year1, month1, day1, hour1, minute1, second2, microSeconds1);
DateTime dateTime7(year1, month1, day1, hour1, minute1, second1, microSeconds2);
DateTime dateTime8(year1, month1, day1, hour1, minute1, second1, microSeconds1);
EXPECT_FALSE(dateTime > dateTime1);
EXPECT_FALSE(dateTime > dateTime2);
EXPECT_FALSE(dateTime > dateTime3);
EXPECT_FALSE(dateTime > dateTime4);
EXPECT_FALSE(dateTime > dateTime5);
EXPECT_FALSE(dateTime > dateTime6);
EXPECT_FALSE(dateTime > dateTime7);
EXPECT_FALSE(dateTime > dateTime8);
}
TEST_FIXTURE(DateTimeTest, OperatorGreaterTimeSpecDateTime)
{
int year1 = 2014;
int month1 = 3;
int day1 = 26;
int hour1 = 12;
int minute1 = 34;
int second1 = 56;
int microSeconds1 = 789;
int year2 = 2016;
int month2 = 4;
int day2 = 30;
int hour2 = 13;
int minute2 = 35;
int second2 = 57;
int microSeconds2 = 789123;
DateTime dateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec1 = (timespec)DateTime(year2, month1, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec2 = (timespec)DateTime(year1, month2, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec3 = (timespec)DateTime(year1, month1, day2, hour1, minute1, second1, microSeconds1);
timespec timeSpec4 = (timespec)DateTime(year1, month1, day1, hour2, minute1, second1, microSeconds1);
timespec timeSpec5 = (timespec)DateTime(year1, month1, day1, hour1, minute2, second1, microSeconds1);
timespec timeSpec6 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second2, microSeconds1);
timespec timeSpec7 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds2);
timespec timeSpec8 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
EXPECT_TRUE(timeSpec1 > dateTime);
EXPECT_TRUE(timeSpec2 > dateTime);
EXPECT_TRUE(timeSpec3 > dateTime);
EXPECT_TRUE(timeSpec4 > dateTime);
EXPECT_TRUE(timeSpec5 > dateTime);
EXPECT_TRUE(timeSpec6 > dateTime);
EXPECT_TRUE(timeSpec7 > dateTime);
EXPECT_FALSE(timeSpec8 > dateTime);
}
TEST_FIXTURE(DateTimeTest, OperatorGreaterTimeValDateTime)
{
int year1 = 2014;
int month1 = 3;
int day1 = 26;
int hour1 = 12;
int minute1 = 34;
int second1 = 56;
int microSeconds1 = 789;
int year2 = 2016;
int month2 = 4;
int day2 = 30;
int hour2 = 13;
int minute2 = 35;
int second2 = 57;
int microSeconds2 = 789123;
DateTime dateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal1 = (timeval)DateTime(year2, month1, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal2 = (timeval)DateTime(year1, month2, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal3 = (timeval)DateTime(year1, month1, day2, hour1, minute1, second1, microSeconds1);
timeval timeVal4 = (timeval)DateTime(year1, month1, day1, hour2, minute1, second1, microSeconds1);
timeval timeVal5 = (timeval)DateTime(year1, month1, day1, hour1, minute2, second1, microSeconds1);
timeval timeVal6 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second2, microSeconds1);
timeval timeVal7 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds2);
timeval timeVal8 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
EXPECT_TRUE(timeVal1 > dateTime);
EXPECT_TRUE(timeVal2 > dateTime);
EXPECT_TRUE(timeVal3 > dateTime);
EXPECT_TRUE(timeVal4 > dateTime);
EXPECT_TRUE(timeVal5 > dateTime);
EXPECT_TRUE(timeVal6 > dateTime);
EXPECT_TRUE(timeVal7 > dateTime);
EXPECT_FALSE(timeVal8 > dateTime);
}
TEST_FIXTURE(DateTimeTest, OperatorGreaterDateTimeTimeSpec)
{
int year1 = 2014;
int month1 = 3;
int day1 = 26;
int hour1 = 12;
int minute1 = 34;
int second1 = 56;
int microSeconds1 = 789;
int year2 = 2016;
int month2 = 4;
int day2 = 30;
int hour2 = 13;
int minute2 = 35;
int second2 = 57;
int microSeconds2 = 789123;
DateTime dateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec1 = (timespec)DateTime(year2, month1, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec2 = (timespec)DateTime(year1, month2, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec3 = (timespec)DateTime(year1, month1, day2, hour1, minute1, second1, microSeconds1);
timespec timeSpec4 = (timespec)DateTime(year1, month1, day1, hour2, minute1, second1, microSeconds1);
timespec timeSpec5 = (timespec)DateTime(year1, month1, day1, hour1, minute2, second1, microSeconds1);
timespec timeSpec6 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second2, microSeconds1);
timespec timeSpec7 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds2);
timespec timeSpec8 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
EXPECT_FALSE(dateTime > timeSpec1);
EXPECT_FALSE(dateTime > timeSpec2);
EXPECT_FALSE(dateTime > timeSpec3);
EXPECT_FALSE(dateTime > timeSpec4);
EXPECT_FALSE(dateTime > timeSpec5);
EXPECT_FALSE(dateTime > timeSpec6);
EXPECT_FALSE(dateTime > timeSpec7);
EXPECT_FALSE(dateTime > timeSpec8);
}
TEST_FIXTURE(DateTimeTest, OperatorGreaterDateTimeTimeVal)
{
int year1 = 2014;
int month1 = 3;
int day1 = 26;
int hour1 = 12;
int minute1 = 34;
int second1 = 56;
int microSeconds1 = 789;
int year2 = 2016;
int month2 = 4;
int day2 = 30;
int hour2 = 13;
int minute2 = 35;
int second2 = 57;
int microSeconds2 = 789123;
DateTime dateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal1 = (timeval)DateTime(year2, month1, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal2 = (timeval)DateTime(year1, month2, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal3 = (timeval)DateTime(year1, month1, day2, hour1, minute1, second1, microSeconds1);
timeval timeVal4 = (timeval)DateTime(year1, month1, day1, hour2, minute1, second1, microSeconds1);
timeval timeVal5 = (timeval)DateTime(year1, month1, day1, hour1, minute2, second1, microSeconds1);
timeval timeVal6 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second2, microSeconds1);
timeval timeVal7 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds2);
timeval timeVal8 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
EXPECT_FALSE(dateTime > timeVal1);
EXPECT_FALSE(dateTime > timeVal2);
EXPECT_FALSE(dateTime > timeVal3);
EXPECT_FALSE(dateTime > timeVal4);
EXPECT_FALSE(dateTime > timeVal5);
EXPECT_FALSE(dateTime > timeVal6);
EXPECT_FALSE(dateTime > timeVal7);
EXPECT_FALSE(dateTime > timeVal8);
}
TEST_FIXTURE(DateTimeTest, OperatorLessEqualDateTimeDateTime)
{
int year1 = 2014;
int month1 = 3;
int day1 = 26;
int hour1 = 12;
int minute1 = 34;
int second1 = 56;
int microSeconds1 = 789;
int year2 = 2016;
int month2 = 4;
int day2 = 30;
int hour2 = 13;
int minute2 = 35;
int second2 = 57;
int microSeconds2 = 789123;
DateTime dateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
DateTime dateTime1(year2, month1, day1, hour1, minute1, second1, microSeconds1);
DateTime dateTime2(year1, month2, day1, hour1, minute1, second1, microSeconds1);
DateTime dateTime3(year1, month1, day2, hour1, minute1, second1, microSeconds1);
DateTime dateTime4(year1, month1, day1, hour2, minute1, second1, microSeconds1);
DateTime dateTime5(year1, month1, day1, hour1, minute2, second1, microSeconds1);
DateTime dateTime6(year1, month1, day1, hour1, minute1, second2, microSeconds1);
DateTime dateTime7(year1, month1, day1, hour1, minute1, second1, microSeconds2);
DateTime dateTime8(year1, month1, day1, hour1, minute1, second1, microSeconds1);
EXPECT_TRUE(dateTime <= dateTime1);
EXPECT_TRUE(dateTime <= dateTime2);
EXPECT_TRUE(dateTime <= dateTime3);
EXPECT_TRUE(dateTime <= dateTime4);
EXPECT_TRUE(dateTime <= dateTime5);
EXPECT_TRUE(dateTime <= dateTime6);
EXPECT_TRUE(dateTime <= dateTime7);
EXPECT_TRUE(dateTime <= dateTime8);
}
TEST_FIXTURE(DateTimeTest, OperatorLessEqualTimeSpecDateTime)
{
int year1 = 2014;
int month1 = 3;
int day1 = 26;
int hour1 = 12;
int minute1 = 34;
int second1 = 56;
int microSeconds1 = 789;
int year2 = 2016;
int month2 = 4;
int day2 = 30;
int hour2 = 13;
int minute2 = 35;
int second2 = 57;
int microSeconds2 = 789123;
DateTime dateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec1 = (timespec)DateTime(year2, month1, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec2 = (timespec)DateTime(year1, month2, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec3 = (timespec)DateTime(year1, month1, day2, hour1, minute1, second1, microSeconds1);
timespec timeSpec4 = (timespec)DateTime(year1, month1, day1, hour2, minute1, second1, microSeconds1);
timespec timeSpec5 = (timespec)DateTime(year1, month1, day1, hour1, minute2, second1, microSeconds1);
timespec timeSpec6 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second2, microSeconds1);
timespec timeSpec7 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds2);
timespec timeSpec8 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
EXPECT_FALSE(timeSpec1 <= dateTime);
EXPECT_FALSE(timeSpec2 <= dateTime);
EXPECT_FALSE(timeSpec3 <= dateTime);
EXPECT_FALSE(timeSpec4 <= dateTime);
EXPECT_FALSE(timeSpec5 <= dateTime);
EXPECT_FALSE(timeSpec6 <= dateTime);
EXPECT_FALSE(timeSpec7 <= dateTime);
EXPECT_TRUE(timeSpec8 <= dateTime);
}
TEST_FIXTURE(DateTimeTest, OperatorLessEqualTimeValDateTime)
{
int year1 = 2014;
int month1 = 3;
int day1 = 26;
int hour1 = 12;
int minute1 = 34;
int second1 = 56;
int microSeconds1 = 789;
int year2 = 2016;
int month2 = 4;
int day2 = 30;
int hour2 = 13;
int minute2 = 35;
int second2 = 57;
int microSeconds2 = 789123;
DateTime dateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal1 = (timeval)DateTime(year2, month1, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal2 = (timeval)DateTime(year1, month2, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal3 = (timeval)DateTime(year1, month1, day2, hour1, minute1, second1, microSeconds1);
timeval timeVal4 = (timeval)DateTime(year1, month1, day1, hour2, minute1, second1, microSeconds1);
timeval timeVal5 = (timeval)DateTime(year1, month1, day1, hour1, minute2, second1, microSeconds1);
timeval timeVal6 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second2, microSeconds1);
timeval timeVal7 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds2);
timeval timeVal8 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
EXPECT_FALSE(timeVal1 <= dateTime);
EXPECT_FALSE(timeVal2 <= dateTime);
EXPECT_FALSE(timeVal3 <= dateTime);
EXPECT_FALSE(timeVal4 <= dateTime);
EXPECT_FALSE(timeVal5 <= dateTime);
EXPECT_FALSE(timeVal6 <= dateTime);
EXPECT_FALSE(timeVal7 <= dateTime);
EXPECT_TRUE(timeVal8 <= dateTime);
}
TEST_FIXTURE(DateTimeTest, OperatorLessEqualDateTimeTimeSpec)
{
int year1 = 2014;
int month1 = 3;
int day1 = 26;
int hour1 = 12;
int minute1 = 34;
int second1 = 56;
int microSeconds1 = 789;
int year2 = 2016;
int month2 = 4;
int day2 = 30;
int hour2 = 13;
int minute2 = 35;
int second2 = 57;
int microSeconds2 = 789123;
DateTime dateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec1 = (timespec)DateTime(year2, month1, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec2 = (timespec)DateTime(year1, month2, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec3 = (timespec)DateTime(year1, month1, day2, hour1, minute1, second1, microSeconds1);
timespec timeSpec4 = (timespec)DateTime(year1, month1, day1, hour2, minute1, second1, microSeconds1);
timespec timeSpec5 = (timespec)DateTime(year1, month1, day1, hour1, minute2, second1, microSeconds1);
timespec timeSpec6 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second2, microSeconds1);
timespec timeSpec7 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds2);
timespec timeSpec8 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
EXPECT_TRUE(dateTime <= timeSpec1);
EXPECT_TRUE(dateTime <= timeSpec2);
EXPECT_TRUE(dateTime <= timeSpec3);
EXPECT_TRUE(dateTime <= timeSpec4);
EXPECT_TRUE(dateTime <= timeSpec5);
EXPECT_TRUE(dateTime <= timeSpec6);
EXPECT_TRUE(dateTime <= timeSpec7);
EXPECT_TRUE(dateTime <= timeSpec8);
}
TEST_FIXTURE(DateTimeTest, OperatorLessEqualDateTimeTimeVal)
{
int year1 = 2014;
int month1 = 3;
int day1 = 26;
int hour1 = 12;
int minute1 = 34;
int second1 = 56;
int microSeconds1 = 789;
int year2 = 2016;
int month2 = 4;
int day2 = 30;
int hour2 = 13;
int minute2 = 35;
int second2 = 57;
int microSeconds2 = 789123;
DateTime dateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal1 = (timeval)DateTime(year2, month1, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal2 = (timeval)DateTime(year1, month2, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal3 = (timeval)DateTime(year1, month1, day2, hour1, minute1, second1, microSeconds1);
timeval timeVal4 = (timeval)DateTime(year1, month1, day1, hour2, minute1, second1, microSeconds1);
timeval timeVal5 = (timeval)DateTime(year1, month1, day1, hour1, minute2, second1, microSeconds1);
timeval timeVal6 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second2, microSeconds1);
timeval timeVal7 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds2);
timeval timeVal8 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
EXPECT_TRUE(dateTime <= timeVal1);
EXPECT_TRUE(dateTime <= timeVal2);
EXPECT_TRUE(dateTime <= timeVal3);
EXPECT_TRUE(dateTime <= timeVal4);
EXPECT_TRUE(dateTime <= timeVal5);
EXPECT_TRUE(dateTime <= timeVal6);
EXPECT_TRUE(dateTime <= timeVal7);
EXPECT_TRUE(dateTime <= timeVal8);
}
TEST_FIXTURE(DateTimeTest, OperatorGreaterEqualDateTimeDateTime)
{
int year1 = 2014;
int month1 = 3;
int day1 = 26;
int hour1 = 12;
int minute1 = 34;
int second1 = 56;
int microSeconds1 = 789;
int year2 = 2016;
int month2 = 4;
int day2 = 30;
int hour2 = 13;
int minute2 = 35;
int second2 = 57;
int microSeconds2 = 789123;
DateTime dateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
DateTime dateTime1(year2, month1, day1, hour1, minute1, second1, microSeconds1);
DateTime dateTime2(year1, month2, day1, hour1, minute1, second1, microSeconds1);
DateTime dateTime3(year1, month1, day2, hour1, minute1, second1, microSeconds1);
DateTime dateTime4(year1, month1, day1, hour2, minute1, second1, microSeconds1);
DateTime dateTime5(year1, month1, day1, hour1, minute2, second1, microSeconds1);
DateTime dateTime6(year1, month1, day1, hour1, minute1, second2, microSeconds1);
DateTime dateTime7(year1, month1, day1, hour1, minute1, second1, microSeconds2);
DateTime dateTime8(year1, month1, day1, hour1, minute1, second1, microSeconds1);
EXPECT_FALSE(dateTime >= dateTime1);
EXPECT_FALSE(dateTime >= dateTime2);
EXPECT_FALSE(dateTime >= dateTime3);
EXPECT_FALSE(dateTime >= dateTime4);
EXPECT_FALSE(dateTime >= dateTime5);
EXPECT_FALSE(dateTime >= dateTime6);
EXPECT_FALSE(dateTime >= dateTime7);
EXPECT_TRUE(dateTime >= dateTime8);
}
TEST_FIXTURE(DateTimeTest, OperatorGreaterEqualTimeSpecDateTime)
{
int year1 = 2014;
int month1 = 3;
int day1 = 26;
int hour1 = 12;
int minute1 = 34;
int second1 = 56;
int microSeconds1 = 789;
int year2 = 2016;
int month2 = 4;
int day2 = 30;
int hour2 = 13;
int minute2 = 35;
int second2 = 57;
int microSeconds2 = 789123;
DateTime dateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec1 = (timespec)DateTime(year2, month1, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec2 = (timespec)DateTime(year1, month2, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec3 = (timespec)DateTime(year1, month1, day2, hour1, minute1, second1, microSeconds1);
timespec timeSpec4 = (timespec)DateTime(year1, month1, day1, hour2, minute1, second1, microSeconds1);
timespec timeSpec5 = (timespec)DateTime(year1, month1, day1, hour1, minute2, second1, microSeconds1);
timespec timeSpec6 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second2, microSeconds1);
timespec timeSpec7 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds2);
timespec timeSpec8 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
EXPECT_TRUE(timeSpec1 >= dateTime);
EXPECT_TRUE(timeSpec2 >= dateTime);
EXPECT_TRUE(timeSpec3 >= dateTime);
EXPECT_TRUE(timeSpec4 >= dateTime);
EXPECT_TRUE(timeSpec5 >= dateTime);
EXPECT_TRUE(timeSpec6 >= dateTime);
EXPECT_TRUE(timeSpec7 >= dateTime);
EXPECT_TRUE(timeSpec8 >= dateTime);
}
TEST_FIXTURE(DateTimeTest, OperatorGreaterEqualTimeValDateTime)
{
int year1 = 2014;
int month1 = 3;
int day1 = 26;
int hour1 = 12;
int minute1 = 34;
int second1 = 56;
int microSeconds1 = 789;
int year2 = 2016;
int month2 = 4;
int day2 = 30;
int hour2 = 13;
int minute2 = 35;
int second2 = 57;
int microSeconds2 = 789123;
DateTime dateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal1 = (timeval)DateTime(year2, month1, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal2 = (timeval)DateTime(year1, month2, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal3 = (timeval)DateTime(year1, month1, day2, hour1, minute1, second1, microSeconds1);
timeval timeVal4 = (timeval)DateTime(year1, month1, day1, hour2, minute1, second1, microSeconds1);
timeval timeVal5 = (timeval)DateTime(year1, month1, day1, hour1, minute2, second1, microSeconds1);
timeval timeVal6 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second2, microSeconds1);
timeval timeVal7 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds2);
timeval timeVal8 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
EXPECT_TRUE(timeVal1 >= dateTime);
EXPECT_TRUE(timeVal2 >= dateTime);
EXPECT_TRUE(timeVal3 >= dateTime);
EXPECT_TRUE(timeVal4 >= dateTime);
EXPECT_TRUE(timeVal5 >= dateTime);
EXPECT_TRUE(timeVal6 >= dateTime);
EXPECT_TRUE(timeVal7 >= dateTime);
EXPECT_TRUE(timeVal8 >= dateTime);
}
TEST_FIXTURE(DateTimeTest, OperatorGreaterEqualDateTimeTimeSpec)
{
int year1 = 2014;
int month1 = 3;
int day1 = 26;
int hour1 = 12;
int minute1 = 34;
int second1 = 56;
int microSeconds1 = 789;
int year2 = 2016;
int month2 = 4;
int day2 = 30;
int hour2 = 13;
int minute2 = 35;
int second2 = 57;
int microSeconds2 = 789123;
DateTime dateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec1 = (timespec)DateTime(year2, month1, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec2 = (timespec)DateTime(year1, month2, day1, hour1, minute1, second1, microSeconds1);
timespec timeSpec3 = (timespec)DateTime(year1, month1, day2, hour1, minute1, second1, microSeconds1);
timespec timeSpec4 = (timespec)DateTime(year1, month1, day1, hour2, minute1, second1, microSeconds1);
timespec timeSpec5 = (timespec)DateTime(year1, month1, day1, hour1, minute2, second1, microSeconds1);
timespec timeSpec6 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second2, microSeconds1);
timespec timeSpec7 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds2);
timespec timeSpec8 = (timespec)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
EXPECT_FALSE(dateTime >= timeSpec1);
EXPECT_FALSE(dateTime >= timeSpec2);
EXPECT_FALSE(dateTime >= timeSpec3);
EXPECT_FALSE(dateTime >= timeSpec4);
EXPECT_FALSE(dateTime >= timeSpec5);
EXPECT_FALSE(dateTime >= timeSpec6);
EXPECT_FALSE(dateTime >= timeSpec7);
EXPECT_TRUE(dateTime >= timeSpec8);
}
TEST_FIXTURE(DateTimeTest, OperatorGreaterEqualDateTimeTimeVal)
{
int year1 = 2014;
int month1 = 3;
int day1 = 26;
int hour1 = 12;
int minute1 = 34;
int second1 = 56;
int microSeconds1 = 789;
int year2 = 2016;
int month2 = 4;
int day2 = 30;
int hour2 = 13;
int minute2 = 35;
int second2 = 57;
int microSeconds2 = 789123;
DateTime dateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal1 = (timeval)DateTime(year2, month1, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal2 = (timeval)DateTime(year1, month2, day1, hour1, minute1, second1, microSeconds1);
timeval timeVal3 = (timeval)DateTime(year1, month1, day2, hour1, minute1, second1, microSeconds1);
timeval timeVal4 = (timeval)DateTime(year1, month1, day1, hour2, minute1, second1, microSeconds1);
timeval timeVal5 = (timeval)DateTime(year1, month1, day1, hour1, minute2, second1, microSeconds1);
timeval timeVal6 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second2, microSeconds1);
timeval timeVal7 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds2);
timeval timeVal8 = (timeval)DateTime(year1, month1, day1, hour1, minute1, second1, microSeconds1);
EXPECT_FALSE(dateTime >= timeVal1);
EXPECT_FALSE(dateTime >= timeVal2);
EXPECT_FALSE(dateTime >= timeVal3);
EXPECT_FALSE(dateTime >= timeVal4);
EXPECT_FALSE(dateTime >= timeVal5);
EXPECT_FALSE(dateTime >= timeVal6);
EXPECT_FALSE(dateTime >= timeVal7);
EXPECT_TRUE(dateTime >= timeVal8);
}
} // namespace Test
} // namespace Core
| true |
660b0845095b9ef6f588b3f83c14723f1ab420d5 | C++ | mimseong/BaekJoon | /14717.cpp | UTF-8 | 1,432 | 2.609375 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <functional>
#include <string>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <cmath>
#define xx first
#define yy second
#define all(x) (x).begin(), (x).end()
using namespace std;
using i64 = long long;
using ii = pair<int, int>;
using ii64 = pair<i64, i64>;
bool comp(const pair<int, int>& a, const pair<int, int>& b)
{
if (a.xx == a.yy)
{
if (b.xx == b.yy && a.xx < b.xx)
return true;
return false;
}
else
{
if (b.xx == b.yy)
return true;
if ((a.xx + a.yy) % 10 < (b.xx + b.yy) % 10)
return true;
return false;
}
}
int main()
{
ii n;
scanf("%d %d", &n.xx, &n.yy);
vector<int> card;
for (int i = 0; i < 2; i++)
{
for (int j = 1; j <= 10; j++)
{
card.emplace_back(j);
}
}
card.erase(find(card.begin(), card.end(), n.xx));
card.erase(find(card.begin(), card.end(), n.yy));
vector<ii> v;
for (int i = 0; i < card.size(); i++)
{
for (int j = i + 1; j < card.size(); j++)
{
v.emplace_back(card[i], card[j]);
}
}
int ans = 0;
for (int i = 0; i < v.size(); i++)
{
if (comp(v[i], n))
ans++;
}
printf("%.3lf\n", (double)ans / v.size());
return 0;
} | true |
8a2e51b4e4f59c9205707aa4fedf9430a869fe8e | C++ | junhyeon47/baekjoon-algorithm | /src/baekjoon_11655.cpp | UTF-8 | 649 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int main(){
string input;
getline(cin, input);
for(int i=0; i<input.size(); ++i){
if('a' <= input[i] && 'z' >= input[i]){
if(input[i] + 13 > 'z'){
input[i] = (input[i]+13-'a')%26 + 'a';
}else{
input[i] = input[i] + 13;
}
}else if('A' <= input[i] && 'Z' >= input[i]){
if(input[i] + 13 > 'Z'){
input[i] = (input[i]+13-'A')%26 + 'A';
}else{
input[i] = input[i] + 13;
}
}
}
cout<<input<<endl;
return 0;
} | true |
658b1a8f8d26947ec65385dee64495b1e4064713 | C++ | wuqingze/algorithm | /Heap/code/HeapSort.cc | UTF-8 | 1,222 | 3.1875 | 3 | [] | no_license | #include <algorithm>
template<typename T, class RandomIt, class Compare>
void sort(RandomIt first, RandomIt end, Compare less =
[](const T& o1, const T& o2){ return o1<o2;}){
int n = end - first;
if(n == 0) return;
auto arr = first;
auto fixup = [arr, less](int i){
while(i>0){
int parent = (i-1)/2;
if(less(arr[parent], arr[i])){
std::swap(arr[parent], arr[i]);
i = parent;
}else return;
}
};
for(int i=1;i<n;i++) fixup(i);
auto fixdown = [arr, less](int len){
int i=0;
while(i<len){
int mx = i;
int left = 2*i+1;
int right = 2*i+2;
if(left<len and less(arr[mx], arr[left])){
mx = left;
}
if(right<len and less(arr[mx], arr[right])){
mx = right;
}
if(mx != i){
std::swap(arr[i], arr[mx]);
i = mx;
}else return;
}
};
int len = n;
for(int i=n-1;i>=0; i--){
std::swap(arr[0], arr[i]);
len -= 1;
fixdown(len);
}
}
int main(){
sort(nums, nums+3);
return 0;
}
| true |
a4931f5e9ebbd4b46b2bb9c873126e420088ed9d | C++ | JSlowgrove/LevelHEngine-GEP-Assignment-2 | /LevelHEngine/States/CannonGame/States/WinLose.h | UTF-8 | 996 | 2.90625 | 3 | [
"MIT"
] | permissive | #pragma once
#include <memory>
#include "../../State.h"
#include "../../StateManager.h"
#include "../../../ResourceManagement/Text.h"
/**
@brief A State that contains and runs the Demo.
*/
class WinLose : public State
{
public:
/**
@brief Constructs the State object.
@param stateManager A pointer to the StateManager.
@param window A pointer to the window in use.
*/
WinLose(StateManager* stateManager, SDL_Window* window, bool inGameStart, int score);
/**
@brief Destructs the State object.
*/
~WinLose();
/**
@brief Handles the State input.
@returns If false then quit the State.
*/
bool input();
/**
@brief A function to update the State.
*/
void update();
/**
@brief A function to draw the State to the screen.
*/
void draw();
private:
///The background music id.
std::string backgroundMusicID;
///The Win Lose image
std::string winLoseID;
///A boolean for if this is at the game start
bool gameStart;
///A pointer for the score text
Text* scoreText;
}; | true |
c47aa9742819df2aa8656d408a1139cf01eedf95 | C++ | prachikush/oop-projects | /box.cpp | UTF-8 | 292 | 2.703125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int i,j,k,l,b;
cout <<" enter the number of rows and columns: "<<endl;
cin>>l>>b;
for(i=0;i<l;i++)
{
for(j=0;j<b;j++)
{
if(i==0||i==(l-1) ||j==0||j==(b-1))
{
cout<<"*";
}
else
{
cout<<" ";
}
}cout <<endl;
}
}
| true |
ea982509e721cc3661de7c01926ccb5cbb932d31 | C++ | DavidSaxon/Reverie | /src/omicron/rendering/shading/Texture.cpp | UTF-8 | 1,851 | 3.0625 | 3 | [] | no_license | #include "Texture.hpp"
namespace omi {
//------------------------------------------------------------------------------
// CONSTRUCTORS
//------------------------------------------------------------------------------
Texture::Texture() :
m_id (0),
m_visible(true) {
}
Texture::Texture( GLuint id, const glm::vec2& dimensions ) :
m_id (id),
m_dimensions( dimensions ),
m_visible (true) {
}
Texture::Texture(const Texture& other) :
m_id ( other.m_id ),
m_dimensions( other.m_dimensions ),
m_visible ( true ) {
}
//------------------------------------------------------------------------------
// DESTRUCTOR
//------------------------------------------------------------------------------
Texture::~Texture() {
}
//------------------------------------------------------------------------------
// OPERATORS
//------------------------------------------------------------------------------
const Texture& Texture::operator=(const Texture& other) {
m_id = other.m_id;
m_dimensions = other.m_dimensions;
m_visible = other.m_visible;
return *this;
}
//------------------------------------------------------------------------------
// PUBLIC MEMBER FUNCTIONS
//------------------------------------------------------------------------------
void Texture::update() {
// do nothing
}
GLuint Texture::getId() const {
return m_id;
}
tex::Type Texture::getType() const {
return tex::TEXTURE;
}
const glm::vec2& Texture::getDimensions() const
{
return m_dimensions;
}
bool Texture::isVisible() const {
return m_visible;
}
} // namespace omi
| true |
91098820a3d162a2e75208e996b3ddbb4a73cb93 | C++ | xxmen/ACMTraining | /2014-08-24&25/ural1277(最小割).cpp | UTF-8 | 2,766 | 2.515625 | 3 | [] | no_license | /*
求最小割,但是由于给出的是每个点的容量,所以需要将每个点拆为两个点,之间连边,容量为点的容量,
两个城市如果相连则容量置为无穷大。然后求最大流看是否大于已有警察数。拆点的时候将点i拆为i和i+n。
*/
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
typedef long long LL;
const int INF = 1<<30;
const int maxn = 210;
struct edge{
int v, c, next;
}e[50000];
int n, m, k, s, f, ans, flow, minw, edgeNum, head[maxn], now[maxn], h[maxn], gap[maxn];
bool found;
void Init()
{
memset(head, -1, sizeof(head));
edgeNum = 0;
}
void addEdge(int x, int y, int c)
{
e[edgeNum].v = y;e[edgeNum].next = head[x];e[edgeNum].c = c;head[x] = edgeNum++;
e[edgeNum].v = x;e[edgeNum].next = head[y];e[edgeNum].c = 0;head[y] = edgeNum++;
}
void SAP(int x, int st, int ed, int n)
{
if (x == ed)
{
found = true;
flow += minw;
return;
}
int p = now[x], minh = n - 1, mw = minw;
while (p != -1)
{
if (e[p].c > 0 && h[x] == h[e[p].v] + 1)
{
minw = min(minw, e[p].c);
SAP(e[p].v, st, ed, n);
if (h[st] >= n) return;
if (found) break;
minw = mw;
}
p = e[p].next;
}
if (found)
{
e[p].c -= minw;
e[p ^ 1].c += minw;
}
else
{
for (p = head[x]; p != -1; p = e[p].next)
{
if (e[p].c > 0 && h[e[p].v] < minh)
{
minh = h[e[p].v];
now[x] = p;
}
}
gap[h[x]]--;
if (!gap[h[x]]) h[st] = n;
h[x] = minh + 1;
gap[h[x]]++;
}
}
void MaxFlow(int st, int ed, int n)
{
memset(h, 0, sizeof(h));
memset(gap, 0, sizeof(gap));
gap[0] = n;
flow = 0;
while (h[st] < n)
{
found = false;
minw = 1 << 30;
SAP(st, st, ed, n);
}
}
int id(int i, int j)
{
return (i - 1) * m + j;
}
int main()
{
while (~scanf("%d", &k))
{
scanf("%d%d%d%d", &n, &m, &s, &f);
Init();
for (int i = 1; i <= n; i++)
{
int R;
scanf("%d", &R);
if (i != s && i != f)
addEdge(i, n + i, R);
}
for (int i = 1; i <= m; i++)
{
int x, y;
scanf("%d%d", &x, &y);
addEdge(x + n, y, INF);
addEdge(y + n, x, INF);
}
if (s == f)
{
puts("NO");
continue;
}
memcpy(now, head, sizeof(head));
MaxFlow(f + n, s, 2 * n);
if (flow > k) puts("NO");
else puts("YES");
}
return 0;
}
| true |
9d654dba24035f43482119b3edb9cf5e0ff808cd | C++ | ghrua/KeepCoding | /leetcode/hard/329.cpp | UTF-8 | 1,526 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <map>
#include <string>
#include <set>
#include <utility>
#include <climits>
#include <vector>
#include <queue>
using namespace std;
#define LL long long
class Solution {
private:
struct node {
int x, y, val;
};
struct cmp {
bool operator() (node n1, node n2) {
return n1.val > n2.val;
}
};
public:
int longestIncreasingPath(vector<vector<int> >& matrix) {
if (!matrix.size())
return 0;
int row = matrix.size(), col = matrix[0].size();
vector<vector<int> > vec(row, vector<int>(col, 1));
priority_queue<node, vector<node>, cmp> pq;
int dir[4][2] = {-1, 0, 1, 0, 0, 1, 0, -1};
int optimal = 1;
for (int i=0; i < row; i++)
for (int j=0; j < col; j++) {
node tn;
tn.x = i; tn.y = j; tn.val = matrix[i][j];
pq.push(tn);
}
while (!pq.empty()) {
node top = pq.top(); pq.pop();
for (int i=0; i < 4; i++) {
int x = top.x+dir[i][0], y = top.y+dir[i][1];
if (x < 0 || x >= row || y < 0 || y >= col || matrix[top.x][top.y] <= matrix[x][y])
continue;
vec[top.x][top.y] = max(vec[top.x][top.y], vec[x][y]+1);
}
if (vec[top.x][top.y] > optimal)
optimal++;
}
return optimal;
}
};
int main() {
ios_base::sync_with_stdio(false);
}
| true |
0d2c2b4b70169568cbe9be506fcd66d38f048073 | C++ | Lightene/boj | /cpp/10845.cpp | UTF-8 | 1,440 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#define MAX 100000
using namespace std;
int arr[MAX];
int f, b;
void push(int input) {
b++;
arr[b] = input;
}
void pop() {
if (f > b)
cout << "-1\n";
else {
cout << arr[f] << "\n";
f++;
}
}
void size() {
if (b - f < -1)
cout << 0 << "\n";
else
cout << (b - f) + 1 << "\n";
}
void empty() {
if (b - f > -1)
cout << 0 << "\n";
else
cout << 1 << "\n";
}
void front() {
if (b >= f)
cout << arr[f] << "\n";
else
cout << -1 << "\n";
}
void back() {
if (b >= f)
cout << arr[b] << "\n";
else
cout << -1 << "\n";
}
int main() {
int cnt;
f = 0;
b = -1;
cin >> cnt;
for (int i = 1; i <= cnt; i++) {
string cmd;
cin >> cmd;
if (cmd == "push") {
int tmp;
cin >> tmp;
push(tmp);
continue;
}
if (cmd == "pop") {
pop();
continue;
}
if (cmd == "empty") {
empty();
continue;
}
if (cmd == "size") {
size();
continue;
}
if (cmd == "front") {
front();
continue;
}
if (cmd == "back") {
back();
continue;
}
}
return 0;
} | true |
83201941f8e0f4e40ad0712168539ab57c2ab6f0 | C++ | AnnaBratucu/data-structures | /ex2/main.cpp | UTF-8 | 4,013 | 4.125 | 4 | [] | no_license | #include<iostream>
#include<cstdlib>
#include<string>
#include<cstdio>
using namespace std;
const int TABLE_SIZE = 128;
/*
* HashEntry Class Declaration
*/
class HashEntry
{
public:
int key;
int value;
HashEntry(int key, int value)
{
this->key = key;
this->value = value;
}
};
/*
* HashMap Class Declaration
*/
class HashMap
{
private:
HashEntry **table;
public:
HashMap()
{
table = new HashEntry * [TABLE_SIZE];
for (int i = 0; i< TABLE_SIZE; i++)
{
table[i] = NULL;
}
}
/*
* Hash Function
*/
int HashFunc(int key)
{
return key % TABLE_SIZE;
}
/*
* Insert Element at a key
*/
void Insert(int key, int value)
{
int hash = HashFunc(key);
while (table[hash] != NULL && table[hash]->key != key)
{
hash = HashFunc(hash + 1);
}
if (table[hash] != NULL)
delete table[hash];
table[hash] = new HashEntry(key, value);
}
/*
* Search Element at a key
*/
int Search(int key)
{
int hash = HashFunc(key);
while (table[hash] != NULL && table[hash]->key != key)
{
hash = HashFunc(hash + 1);
}
if (table[hash] == NULL)
return -1;
else
return table[hash]->value;
}
/*
* Remove Element at a key
*/
void Remove(int key)
{
int hash = HashFunc(key);
while (table[hash] != NULL)
{
if (table[hash]->key == key)
break;
hash = HashFunc(hash + 1);
}
if (table[hash] == NULL)
{
cout<<"No Element found at key "<<key<<endl;
return;
}
else
{
delete table[hash];
}
cout<<"Element Deleted"<<endl;
}
~HashMap()
{
for (int i = 0; i < TABLE_SIZE; i++)
{
if (table[i] != NULL)
delete table[i];
delete[] table;
}
}
};
/*
* Main Contains Menu
*/
int main()
{
HashMap hash;
int key, value;
int choice;
while (1)
{
cout<<"\n----------------------"<<endl;
cout<<"Operations on Hash Table"<<endl;
cout<<"\n----------------------"<<endl;
cout<<"1.Add new user"<<endl;
cout<<"2.Login"<<endl;
cout<<"3.Delete user"<<endl;
cout<<"4.Update password"<<endl;
cout<<"5.Exit"<<endl;
cout<<"Enter your choice: ";
cin>>choice;
switch(choice)
{
case 1:
cout<<"Enter login ID: ";
cin>>key;
cout<<"Enter password: ";
cin>>value;
hash.Insert(key, value);
break;
case 2:
cout<<"Enter login ID: ";
cin>>key;
if (hash.Search(key) == -1)
{
cout<<"No element found at key "<<key<<endl;
continue;}
cout<<"Enter password: ";
cin>>value;
if(hash.Search(key)==value)
{ cout<<"Correct password";
continue;}
else
{
cout<<"Not correct!";
}
break;
case 3:
cout<<"Enter login ID to be deleted: ";
cin>>key;
hash.Remove(key);
break;
case 4:
cout<<"Enter ID of password you want updated: ";
cin>>key;
hash.Remove(key);
cout<<"Put your ID again: ";
cin>>key;
cout<<"New password: ";
cin>>value;
hash.Insert(key, value);
break;
case 5:
exit(1);
default:
cout<<"\nEnter correct option\n";
}
}
return 0;
}
| true |
879e4a728c6a4f5c62bf2e377f001114e7b202bf | C++ | tangj1992/Data-Structure-and-Algorithms | /cpp/Sort.h | UTF-8 | 755 | 2.5625 | 3 | [] | no_license | #ifndef SINGLELIST_SORT_H
#define SINGLELIST_SORT_H
/**
* 各种排序算法
*/
class Sort{
public:
static void bubbleSort(int arr[], int size);
static void insertionSort(int arr[], int size);
static void selectionSort(int arr[], int size);
static void mergeSort(int arr[], int size);
static void quickSort(int arr[], int size);
static int topk(int arr[], int size, unsigned int k);
static void countingSort(int arr[], int size);
private:
static void merge(int arr[], int start, int p, int end);
static void mergeSort(int arr[], int start, int end);
static int partition(int arr[], int start, int end);
static void quickSort(int arr[], int start, int end);
};
void testSort();
#endif //SINGLELIST_SORT_H
| true |
d67b8a50accb4bbd1800ff1bc83cb8da3cafc131 | C++ | wincentbalin/QMLPiano | /qmlpiano.cpp | UTF-8 | 1,878 | 2.625 | 3 | [] | no_license | #include <QtGui/QApplication>
#include "qmlapplicationviewer.h"
#include "qmlpiano.hpp"
void Piano::noteOn(int keyIndex)
{
unsigned char noteOn = 144; // Note On, first channel
unsigned char velocity = 100;
sendNoteMessage(noteOn, keyIndex, velocity);
}
void Piano::noteOff(int keyIndex)
{
unsigned char noteOff = 128; // Note Off, first channel
unsigned char velocity = 100;
sendNoteMessage(noteOff, keyIndex, velocity);
}
void Piano::initMIDI()
{
// Initialize MIDI object
midiOut_ = new RtMidiOut("QMLPiano Out");
// If available, open first MIDI port and get its name
if(midiOut_->getPortCount() == 0)
{
portName_ = "Unavailable";
}
else
{
midiOut_->openPort();
portName_ = midiOut_->getPortName().c_str();
}
}
void Piano::cleanupMIDI()
{
// Close port
midiOut_->closePort();
// Clean up MIDI object
delete midiOut_;
}
int Piano::key2midi(int index)
{
// Calculate MIDI note value
int midiNote = (octave_ + 5) * 12 + index;
// Ensure values of MIDI note being standard
if(midiNote < 0)
midiNote = 0;
else if(midiNote > 127)
midiNote = 127;
return midiNote;
}
// Look up MIDI statuses at http://www.midi.org/techspecs/midimessages.php
void Piano::sendNoteMessage(unsigned char status, int keyIndex, unsigned char velocity)
{
std::vector<unsigned char> message;
// Assemble MIDI message
message.push_back(status);
message.push_back(key2midi(keyIndex)); // Note
message.push_back(velocity);
// Send it
midiOut_->sendMessage(&message);
}
Q_DECL_EXPORT int main(int argc, char *argv[])
{
QApplication app(argc, argv);
qmlRegisterType<Piano>("QMLPiano", 1, 0, "Piano");
QDeclarativeView view(QUrl::fromLocalFile("qml/QMLPiano/UI.qml"));
view.show();
return app.exec();
}
| true |
ed09375d3db9ece77fc1c9e1b51517fe9e45d507 | C++ | VSerain/bob-v-0 | /src/Manager.cpp | UTF-8 | 3,669 | 3.171875 | 3 | [] | no_license | #include "./Manager.h"
const int MAX_SPEED = 150;
const int BOT_LENGTH = 160;
const int BOT_WIDTH = 80;
const int WHEEL_RAY = 65;
Manager::Manager(Head head, AbstarctServo frontWheel, DCMotor leftMotor, DCMotor rightMotor, int debug): head(head), frontWheel(frontWheel), leftMotor(leftMotor), rightMotor(rightMotor) {
this->debug = debug;
if (debug == 1) {
Serial.begin(9600);
}
this->setMotorsSpeed(1);
}
int Manager::loop() {
// Step 1 get front distance
double distance = this->head.getDistance(0);
if (distance < 50) {
this->setMotorsSpeed(0); // Stop Motors
delay(500);
distance = this->head.getDistance(0); // Recompute distance after stoping
int futurRotation = this->head.getBestRotation(75, 15); // Find the best rotation (max distance)
if (futurRotation == 0) return 1;
this->turn(futurRotation * -1, -1, BOT_LENGTH); // reverse gear
this->setMotorsSpeed(0.2); // not stop motor
}
else if (distance < 600) {
this->setMotorsSpeed(0.4);
int futurRotation = this->head.getBestRotation(30, 30); // Find the best rotation (max distance)
this->turn(futurRotation, 0.4, BOT_LENGTH);
}
else {
float speed = max(0.4, distance / 1200);
this->setMotorsSpeed(speed);
int futurRotation = this->head.getBestRotation(20, 20); // Find the best rotation (max distance)
this->turn(futurRotation, speed, BOT_LENGTH);
}
return 0;
}
void Manager::turn(int rotation, double speed, double distance) {
this->frontWheel.rotate(rotation);
double speedMotorRight = this->computeDifferentielSpeed(rotation, 0, speed);
double speedMotorLeft = this->computeDifferentielSpeed(rotation, 1, speed);
if (speed > 0) {
distance = distance / 4;
}
long waitTime = this->computeDelayWithDistance(distance, speed);
if (speed < 0) {
double anglePercentage = abs(rotation) / 0.9 / 100;
waitTime = waitTime * anglePercentage;
if (rotation > 0) {
speedMotorLeft = speed;
speedMotorRight = speed * -1;
}
else {
speedMotorLeft = speed * -1;
speedMotorRight = speed;
}
}
this->leftMotor.setSpeed(speedMotorLeft);
this->rightMotor.setSpeed(speedMotorRight);
delay(waitTime);
this->frontWheel.rotate(0);
this->head.setRotation(0);
}
long Manager::computeDelayWithDistance(double distance, double speed) {
if (distance == INFINITY || distance > 800) {
distance = 800;
}
if (distance < 2) {
distance = 100;
}
double rpm = MAX_SPEED * (speed > 0 ? speed : speed * -1);
double currentRealSpeed = rpm * (WHEEL_RAY * PI) / 60 / 1000; // mm/ms
return distance / currentRealSpeed;
}
double Manager::computeDifferentielSpeed(int angle, int side, double speed) {
double rayon = computeRayByAngle(BOT_WIDTH, BOT_LENGTH, angle, 2);
double vExt = speed * ((rayon + BOT_WIDTH/2) / rayon);
double vInt = speed * ((rayon - BOT_WIDTH/2) / rayon);
if (side == 0 && angle > 0) return vInt;
if (side == 1 && angle < 0) return vInt;
return vExt;
}
double Manager::computeDifferentielSpeed(int rotation, int side) {
return this->computeDifferentielSpeed(rotation, side, 100);
}
void Manager::setMotorsSpeed(double speed) {
if (speed == 0.0) {
this->leftMotor.setSpeed(this->leftMotor.getSpeed() > 0 ? -1.0 : 1.0);
this->rightMotor.setSpeed(this->rightMotor.getSpeed() > 0 ? -1.0 : 1.0);
delay(50);
}
this->leftMotor.setSpeed(speed);
this->rightMotor.setSpeed(speed);
}
| true |
0d8891fbbb167d622dc6da5962273871f15500bc | C++ | amnagrawal/Competetive-coding | /Codechef/NUKES.cpp | UTF-8 | 242 | 2.6875 | 3 | [] | no_license | //https://www.codechef.com/problems/NUKES
#include <iostream>
using namespace std;
int main() {
long int a;
int n, k;
cin>>a;
cin>>n>>k;
while(k--) {
cout<<a%(n+1)<<" ";
a = a/(n+1);
}
return 0;
}
| true |
282687e0c585a75836f27d0bc18e329cec799db9 | C++ | JaroslavUrbann/ICPC-library | /data-structures/interval_set.cpp | UTF-8 | 1,353 | 2.875 | 3 | [] | no_license | // quite slow
// inclusive, exclusive
struct iset{
typedef int T;
set<tuple<T,T,T>>longest; // len, l, r
set<pair<T,T>>ints;
set<pair<T,T>>::iterator insert(T l,T r){
auto it=ints.lower_bound({l,INT_MIN});
if(it!=ints.begin()){
auto[lp,rp]=*prev(it);
if(l<=rp){
it=erase(prev(it));
l=min(l,lp);
r=max(r,rp);
}
}
for(;it!=ints.end();it=erase(it)){
auto[ln,rn]=*it;
if(ln>r)break;
r=max(r,rn);
}
longest.insert({r-l,l,r}); // m
return ints.insert({l,r}).first;
}
// erases any segment, returns first segment after r
set<pair<T,T>>::iterator erase(T l,T r){
auto it=ints.lower_bound({l,INT_MIN});
if(it!=ints.begin()){
auto[lp,rp]=*prev(it);
if(l<rp){
erase(prev(it));
it=next(insert(lp,l));
if(r<rp)return insert(r,rp);
}
}
while(it!=ints.end()){
auto[ln,rn]=*it;
if(r<=ln)break;
it=erase(it);
if(r<rn)return insert(r,rn);
}
return it;
}
set<pair<T,T>>::iterator erase(const set<pair<T,T>>::iterator&it){
if(it==ints.end())return it;
auto[l,r]=*it;
longest.erase({r-l,l,r}); // m
return ints.erase(it);
}
set<pair<T,T>>::iterator begin(){return ints.begin();}
set<pair<T,T>>::iterator end(){return ints.end();}
set<pair<T,T>>::iterator find(T l,T r){return ints.find({l,r});}
T maxlen(){return longest.empty()?0:get<0>(*longest.rbegin());}
};
| true |
78c33632f33787b5bca17c66ef75dd9b0d1a9c25 | C++ | Dot-H/random | /adaptative_struct/test.cpp | UTF-8 | 329 | 2.84375 | 3 | [] | no_license | #include <iostream>
template <std::size_t N>
constexpr uint8_t nBytes() {
return (sizeof(N) + 1) - x86_lzcnt(N);
}
template <std::size_t N>
struct Size {
constexpr std::size_t size() const { nBytes<N>(); }
};
int main(int argc, char* argv[])
{
Size<128> s;
std::cout << s.size() << std::endl;
return 0;
}
| true |
2d24bf409e360f7e963bbf99dfd14ba4e8eddfcc | C++ | jiwoo1218/Room-Escape-30806 | /RoomEscape.c.cpp | UTF-8 | 12,780 | 2.71875 | 3 | [] | no_license | /*
개발자: 박지우, 윤민혁, 정민태
개발일: 2021.09.07
문의: p0312181@naver.com
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#define TRUE 1
#define FALSE 0
void intro();
void room();
void frame(); //1. 액자
void bed(); //2. 침대
void fridge(); //3. 수정중
void safebox(); //4. 수정중
void closet(); //5. 수정중
void door(); //6. 수정중
void door_password();
int isBrokenFrame = FALSE; //액자 파손여부
int isBrokenBed = FALSE; //침대 파손여부
int isFindMagnifyingGlass = FALSE; //돋보기 습득여부
int isFindGoldKey = FALSE; //금색 열쇠 획득 여부
int isFindSilverKey = FALSE; //은색 열쇠 획득 여부
int isOpenSafebox = FALSE; //금고 오픈 여부
int main() {
int menu;
while(1) {
printf("비버의 방\n\n");
printf("1. 게임 시작\n");
printf("0. 응 안해\n");
printf(">> ");
scanf("%d", &menu);
switch(menu) {
case 1:
intro();
room();
break;
case 0:
return 0;
default:
printf("입력 오류\n\n");
break;
}
}
}
void intro() {
system("cls");
printf("\n\n");
printf("오늘은 소꿉친구 미란이와 놀이공원에 가는 날이다.\n\n");
Sleep(1500);
printf("놀이공원 화장실 가는 골목에서.\n");
Sleep(2500);
printf("검은 조직에 밀거래 현장을 발견하게 되고\n");
Sleep(1500);
printf("사진을 찍고 도망가려던 찰나에 뒤통수를 맞았당\n\n");
Sleep(2500);
printf("눈을 떠보니 낯선 방안에 들어와있다..\n");
Sleep(1500);
printf("천장에는 비버사진이 도배되어있다..\n\n");
Sleep(1500);
printf("여긴 어디지..? 이곳에서 탈출해야된다..\n\n");
Sleep(1500);
printf("집에는 찌찌닭발이 날 기다리고 있어!.\n\n");
Sleep(1500);
system("pause");
}
void room() {
int menu;
while(1) {
system("cls");
printf("[비버의 방]\n\n");
printf("방 안에서 할 수 있는 것들을 찾아보자.\n\n");
printf("1. 책상 2.라꾸라꾸침대 3. 냉장고\n");
printf("4. 화장실 5. 옷장 6. 탈출구\n");
printf(">> ");
scanf("%d", &menu);
switch(menu) {
case 1:
if(isBrokenFrame) {
printf("\n침대를 부서버렸다. 더 이상 찾을 수 없다.\n");
system("pause");
} else {
frame();
}
break;
case 2:
bed();
break;
case 3:
fridge();
break;
case 4:
safebox();
break;
case 5:
closet();
break;
case 6:
door();
break;
default:
printf("\n# ERROR # 입력값 오류\n");
system("pause");
}
}
}
void frame(){//1. 책상
int menu;
while(1) {
system("cls");
printf("[비버의 방]-[책상]\n\n");
printf("방안에 큰책상이 있다.\n\n");
printf("1. 책상을 살펴본다\n");
printf("2. 책상을 부순다\n");
printf("0. 돌아가기\n");
printf(">> ");
scanf("%d", &menu);
switch(menu) {
case 1:
if(isFindMagnifyingGlass) {
} else {
printf("\n책상에는 별거없는거 같다 .\n\n");
}
break;
case 2:
isBrokenFrame = TRUE;
printf("\n 책상. 파괴한다..\n");
printf("크쏘!!! 철제 책상이라니!!\n\n");
printf("좀더 레벨업을 해야될거 같다.\n\n");
system("pause");
return;
case 0:
return;
default:
printf("\n응 틀렸엉 다시 써1\n\n");
break;
}
system("pause");
}
}
void bed() {//2. 침대
int menu;
while(1) {
system("cls");
printf("[원룸]-[라꾸라꾸침대]\n\n");
printf("구석에 라꾸라꾸침대가 있다.\n\n");
printf("1. 라꾸라꾸침대 밑을 살펴본다\n");
printf("2. 라꾸라꾸침대를 살펴본다\n");
printf("3. 이불을 살펴본다\n");
printf("0. 돌아가기\n");
printf(">> ");
scanf("%d", &menu);
switch(menu) {
case 1:
if(isBrokenBed) {
printf("\n라꾸라꾸 침대는 파괴되었다..\n\n");
} else {
printf("\n먼지가 가득하다 어우더러웡.\n");
}
system("pause");
break;
case 2:
if(isBrokenBed) {
printf("\n침대가 부서져서 더 이상 찾을 수 없다.\n\n");
} else {
system("cls");
printf("[원룸]-[침대]-[침대]\n\n");
printf("\n그저 평범한 라꾸라꾸 침대처럼 보인다.\n\n");
printf("1. 침대를『파괴』한다.\n");
printf("2. 침대를『살려』준다.\n");
printf(">> ");
scanf("%d", &menu);
switch(menu) {
case 1:
isBrokenBed = TRUE; //침대 부서짐
printf("\n# 침대가『파괴』되었다. \n\n");
printf("1. 잔해를 뒤진다.\n");
printf("2. 가만히 둔다.\n");
printf(">> ");
scanf("%d", &menu);
switch(menu) {
case 1:
printf("\n파란색 메모장이 있다. 비밀번호 인건가?\n");
printf("내 수준에 풀수 없는 문제는 없지..크크\n");
printf("MON = 3 \n TUE =5 \n WED =4 \n THU = ?\n\n");
printf("EZ하노\n");
break;
case 2:
printf("\n치우기 귀찮다. 그냥 두자.\n\n");
break;
default:
printf("\n결정을 못했다. 돌아가자.\n\n");
break;
}
break;
case 2:
printf("\n와타시가 특별히『생존』시켜주도록 하지...\n\n");
break;
default:
printf("\n결정을 못했다. 돌아가자.\n\n");
break;
}
}
system("pause");
break;
case 3:
system("cls");
printf("[원룸]-[침대]-[이불]\n\n");
printf("\n베개에서는 특이한 점이 보이지 않는다.\n\n");
printf("1. 이불 사이를 뒤진다\n");
printf("2. 이불을 찢어버린다\n");
printf(">> ");
scanf("%d", &menu);
switch(menu) {
case 1:
if(isFindGoldKey) {
printf("\n열쇠말고 다른것은 보이지 않는다 .\n\n");
} else {
isFindGoldKey = TRUE; //금색 열쇠 획득
printf("\n이불 속에서 열쇠하나를 발견했다. 어디에 쓰는거지?\n\n");
}
break;
case 2:
printf("\n내가 누워야 하니까 내비두자..\n\n");
break;
default:
printf("\n아몰랑. 돌아가자.\n\n");
break;
}
system("pause");
break;
case 0:
return;
default:
printf("# ERROR # 응아니야\n\n");
system("pause");
}
}
}
void fridge(){//3. 냉장고
int menu;
while(1) {
system("cls");
printf("[비버의방]-[냉장고 ]\n\n");
printf("LG 신상 냉장고가 방한켠에 있다 뭐가있는지 볼까낭.\n");
printf("음식 뒤지게 많넹.\n\n");
printf("1. LPG 를 살펴본다\n");
printf("2. 해물탕을 살펴본다\n");
printf("3. 사과를 살펴본다\n");
printf("4. 뉴트리아앞다리를 살펴본다\n");
printf("5. 닭발을 살펴본다\n");
printf("0. 돌아가기\n");
printf(">> ");
scanf("%d", &menu);
switch(menu) {
case 1:
printf("\n\n");
printf("\n 이게 왜 여기 있는거지 수현이 집인가?\n\n");
break;
case 2:
printf("\n 물비린내가 심하게난다 상한건가?..\n\n");
break;
case 3:
printf("\n벌레가 기어다닌다 상표를보니 PALDOCOMPANY 라고 써있다..\n\n");
break;
case 4:
printf("\n다2빙을 하려는 그의 의지가 보인다..\n\n");
break;
case 5:
printf("\n 상표만 찌찌닭발이고 쭈쭈닭발이였다.\n얼른 나가서 찌닭을 먹어야겠어!\n\n");
break;
case 0:
return;
default:
printf("\n qudtls ㅋㅋ\n\n");
break;
}
system("pause");
}
}
void safebox(){//4.장실
int menu;
while(1) {
system("cls");
printf("[비버의 방]-[화장실]\n");
printf("물비린내가 나는 화장실이다.\n\n");
printf("1. 화장실 문을 연다\n");
printf("2. 화장실 문을 부순다\n");
printf("3. 화장실 문을 살펴본다\n");
printf("0. 돌아가기\n");
printf(">> ");
scanf("%d", &menu);
switch(menu) {
case 1:
if(isOpenSafebox) {
printf("\n응 이미 열었어 ㅋㅋ 까먹었으면 다시하셈 ㅋㅋ.\n\n");
break;
}
if(isFindGoldKey && isFindSilverKey) {
isFindMagnifyingGlass = TRUE; //화장실 습득
isOpenSafebox = TRUE; //화장실 열었음
printf("\n화장실 세면대에 메모장이 있다\n");
printf("메모지에는 큰 글씨로 글이 적혀있다.\n\n");
printf("'하츠네미쿠의 나이는?.\nㅋㅋ개쉽네\n");
printf("빨리 풀고 찌닭 먹으러 가야징'\n\n");
printf("부히R부히R 후헤헤m\n\n");
} else {
printf("\n화장실에 열쇠가 왜 2개나 필요하냐고!!.\n\n");
}
break;
case 2:
printf("\n『파괴』해야겠군\n\n");
printf("\n 크쏘!!! 뭔놈에 집이 전부다 철로 만들었어\n\n");
break;
case 3:
printf("\n아니 뭔데 화장실에 열쇠구멍이 두개임?\n\n");
break;
case 0:
return;
default:
printf("\n똑바로좀 써라 손가락 문제있음? \n\n");
break;
}
system("pause");
}
}
void closet(){//5. 옷장
int menu;
while(1) {
system("cls");
printf("[비버의 방]-[옷장]\n\n");
printf("방 한쪽을 가득 채울 정도의 큰 옷장이다.\n\n");
printf("1. 수현이 옷을 살펴본다\n");
printf("2. 동현이 옷을 살펴본다\n");
printf("3. 석현이 옷을 살펴본다\n");
printf("4. 석진이 옷을 살펴본다\n");
printf("5. 옷장을 부순다\n");
printf("0. 돌아가기\n");
printf(">> ");
scanf("%d", &menu);
switch(menu) {
case 1:
if(isFindSilverKey) {
printf("\n 수현이 옷에는 더이상 찾을게 없어보인다 쓸모없는놈.\n\n");
} else {
isFindSilverKey = TRUE; //은색 열쇠 찾음
printf("\n수현이 옷 주머니에 은색열쇠와 LPG명함이 있다.\n\n");
}
break;
case 2:
printf("\n동현이 옷사이에 메모지가 들어있다\n\n");
printf("\n 9 + 3 = 12 \n 5 + 10 = 3 \n 7 + 9= 4 \n 15 + 6 = ???\n\n");
printf("개쉽노ㅋ");
break;
case 3:
printf("\n석현이 옷에는 찌찌닭발 명함이 들어있다.\n\n");
break;
case 4:
printf("\n석진이 옷에는 썩은 사과와 팔도청과 명함이 들어있다.\n\n");
break;
case 5:
printf("\n후후후 『옷장』이라...\n부숴 버려쥬지..\n크쏘!!!!!!!!!!!\n철제옷장인걸 까먹어 버렸다..랄까?\n\n");
break;
case 0:
return;
default:
printf("\n야레야레..손나박하나..\n\n");
break;
}
system("pause");
}
}
void door(){//6. 출입문
int menu;
while(1) {
system("cls");
printf("[비버의방]-[탈출구]\n\n");
printf("오잉 문이 여기있었넹.\n");
printf("문 앞에는 화이트보드에 글귀가 써있다.\n\n");
printf("1. 화이트보드를 살펴본다\n");
printf("2. 비밀번호를 입력한다\n");
printf("0. 돌아가기\n");
printf(">> ");
scanf("%d", &menu);
switch(menu) {
case 1:
printf("\n화이트보드에는 간단하게 몇줄써있다?\n\n");
printf("방에있는 힌트 요소를 모아 비밀번호를 입력해 탈출하라.\n\n");
printf("그러게 왜 사진 찍어가지고 처 잡혀옴ㅋㅋ\n");
break;
case 2:
door_password();
break;
case 0:
return;
default:
printf("\n응 아니야 다시해 ㅋㅋ\n\n");
break;
}
system("pause");
}
}
void door_password() {
char pass[5] = "6169", temp[5];
system("cls");
printf("\n\n [ PASSWORD ]\n\n");
printf(">> ");
scanf("%s", &temp);
if(!strcmp(pass, temp)) {
system("cls");
printf("\n\n아ㅋㅋ 드디어 나왔네 ㅋㅋ.\n\n");
printf("아 배 뒤지게 고프네.\n");
printf("아 그나저나 여기 어디지 ㅋㅋ\n");
printf("아몰랑 집가서 찌닭이나 먹어야지.\n\n");
printf("그 이후 주인공은 우여곡절 끝에 집에 돌아가 상한 찌닭을 보고 분노하였고..\n\n");
printf("그 다음..");
printf("#1.SAD ENDING");
system("pause");
exit(0);
} else {
printf("\n\n비밀번호 누가모름 ㅋㅋ 아ㅋㅋ 너만 모름 ㅋㅋ\n\n");
return;
}
}
| true |
de36ef304c741b68260044648df3e5efff375565 | C++ | Jabed27/C-datastructure-and-algorithm | /STL/vectorSort.cpp | UTF-8 | 863 | 3.234375 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<algorithm>
#include<iterator>
using namespace std;
int myfunc(int a,int b){
return (a>b);
}
int main(){
vector <int >vec;
vector <int >::iterator it;
vec.push_back(30);
vec.push_back(78);
vec.push_back(-9);
vec.push_back(65);
sort(vec.begin(),vec.end());/// assending
for(int i = 0;i<4;i++){
cout<<vec[i]<<"\t";
}
cout<<"\n";
sort(vec.begin(),vec.end(),myfunc); ///desending
for(it = vec.begin();it!= vec.end();it++){
cout<<*it<<"\t";
}
cout<<"\n";
sort(vec.begin(),vec.begin()+3);
for(it = vec.begin();it!= vec.end();it++){
cout<<*it<<"\t";
}
}
| true |
a85c862ef9942c69c8bfe246f21523bb75a28502 | C++ | sunzhijuns/li_cl_algorithm | /MaxHeap.h | UTF-8 | 6,547 | 3.546875 | 4 | [] | no_license | //
// Created by sunzhijun on 18-2-3.
//
#ifndef SUANFA_MAXHEAP_H
#define SUANFA_MAXHEAP_H
#include <iostream>
#include <string.h>
#include <cassert>
#include<math.h>
#include<string>
#include <typeinfo>
template<typename Item>
class MaxHeap{
private:
Item* _data;
int _count;
int _capacity;
private:
void __ShiftUp(int index){
while(HasParent(index) && GetParent(index) < Get(index)){
Swap(index, GetParentIndex(index));
index = GetParentIndex(index);
}
}
void __ShiftDown(int index){
while(HasLeftChild(index)){
int child_index = GetLeftChildIndex(index);
if(HasRightChild(index) &&
Get(child_index) < Get(GetRightChildIndex(index))){
child_index = GetRightChildIndex(index);
}
if(Get(index) >= Get(child_index)){
break;
}
Swap(index, child_index);
index = child_index;
}
}
void __Enlarge(){
_capacity *= 2;
std::cout << "/* Enlarge "<<_capacity/2+1 << "->"<<_capacity+1 << " */"<<std::endl;
Item* data = new Item[_capacity + 1];
memcpy(data, _data, (_count + 1) * sizeof(Item));
delete[] _data;
_data = data;
}
/*辅助的公共函数*/
public:
bool HasParent(int index){
return index/2 > 0;
}
bool HasLeftChild(int index){
return 2*index <= _count;
}
Item GetLeftChildIndex(int parent_index){
return parent_index*2;
}
bool HasRightChild(int index){
return (2*index+1) <= _count;
}
Item GetRightChildIndex(int parent_index){
return parent_index*2 + 1;
}
Item GetParent(int index){
return _data[index/2];
}
int GetParentIndex(int index){
return index / 2;
}
Item Get(int index){
return _data[index];
}
void Swap(int a, int b){
std::swap(_data[a],_data[b]);
}
/*实现主要功能的公共函数*/
public:
MaxHeap(Item data[], int n){
_data = new Item[n+1];
_capacity = n;
for (int i = 0; i < n; ++i) {
_data[i+1] = data[i];
}
_count = n;
//Heapify
for (int i = _count/2; i >= 1; --i) {
__ShiftDown(i);
}
}
MaxHeap(int capacity){
_data = new Item[capacity + 1];
_count = 0;
_capacity = capacity;
}
~MaxHeap(){
delete[] _data;
}
int Size(){
return _count;
}
bool IsEmpty(){
return _count == 0;
}
void Insert(Item item){
if(_count + 1 > _capacity){
__Enlarge();
}
_data[_count+1] = item;
_count++;
__ShiftUp(_count);
}
Item ExtractMax(){
assert(_count > 0);
Item return_item = _data[1];
_data[1] = _data[_count];
_count --;
__ShiftDown(1);
return return_item;
}
void Print(){
for (int i = 0; i <= _count; ++i) {
std::cout<<_data[i]<<" ";
}
std::cout<<std::endl;
}
public:
// 以树状打印整个堆结构
void TestPrint(){
using namespace std;
// 我们的testPrint只能打印100个元素以内的堆的树状信息
if( Size() >= 100 ){
std::cout<<"This print function can only work for less than 100 int";
return;
}
// 我们的testPrint只能处理整数信息
if( typeid(Item) != typeid(int) ){
std::cout <<"This print function can only work for int item";
return;
}
cout<<"The max heap size is: "<<Size()<<endl;
cout<<"Data in the max heap: ";
for( int i = 1 ; i <= Size() ; i ++ ){
// 我们的testPrint要求堆中的所有整数在[0, 100)的范围内
assert( _data[i] >= 0 && _data[i] < 100 );
cout<<_data[i]<<" ";
}
cout<<endl;
cout<<endl;
int n = Size();
int max_level = 0;
int number_per_level = 1;
while( n > 0 ) {
max_level += 1;
n -= number_per_level;
number_per_level *= 2;
}
int max_level_number = int(pow(2, max_level-1));
int cur_tree_max_level_number = max_level_number;
int index = 1;
for( int level = 0 ; level < max_level ; level ++ ){
string line1 = string(max_level_number*3-1, ' ');
int cur_level_number = min(_count-int(pow(2,level))+1,int(pow(2,level)));
bool isLeft = true;
for( int index_cur_level = 0 ; index_cur_level < cur_level_number ; index ++ , index_cur_level ++ ){
putNumberInLine( _data[index] , line1 , index_cur_level , cur_tree_max_level_number*3-1 , isLeft );
isLeft = !isLeft;
}
cout<<line1<<endl;
if( level == max_level - 1 )
break;
string line2 = string(max_level_number*3-1, ' ');
for( int index_cur_level = 0 ; index_cur_level < cur_level_number ; index_cur_level ++ )
putBranchInLine( line2 , index_cur_level , cur_tree_max_level_number*3-1 );
cout<<line2<<endl;
cur_tree_max_level_number /= 2;
}
}
private:
void putNumberInLine( int num, std::string &line, int index_cur_level, int cur_tree_width, bool isLeft){
int sub_tree_width = (cur_tree_width - 1) / 2;
int offset = index_cur_level * (cur_tree_width+1) + sub_tree_width;
assert(offset + 1 < line.size());
if( num >= 10 ) {
line[offset + 0] = '0' + num / 10;
line[offset + 1] = '0' + num % 10;
}
else{
if( isLeft)
line[offset + 0] = '0' + num;
else
line[offset + 1] = '0' + num;
}
}
void putBranchInLine( std::string &line, int index_cur_level, int cur_tree_width){
int sub_tree_width = (cur_tree_width - 1) / 2;
int sub_sub_tree_width = (sub_tree_width - 1) / 2;
int offset_left = index_cur_level * (cur_tree_width+1) + sub_sub_tree_width;
assert( offset_left + 1 < line.size() );
int offset_right = index_cur_level * (cur_tree_width+1) + sub_tree_width + 1 + sub_sub_tree_width;
assert( offset_right < line.size() );
line[offset_left + 1] = '/';
line[offset_right + 0] = '\\';
}
};
#endif //SUANFA_MAXHEAP_H
| true |
d64da670be4cad079ef53e4060a0e0cc514a8dfa | C++ | jianjiachenghub/CLanguageProgramming | /C++/重载运算符.cpp | UTF-8 | 391 | 3.359375 | 3 | [] | no_license | #include<iostream.h>
class complex
{
public:
complex(){real=0;imag=0;}
complex(double r,double i)
{
real=r;imag=i;
}
complex operator+(complex &c2)
{
return complex(real+c2.real,imag+c2.imag);
}
private:
double real,imag;
};
int main()
{
complex c1(5,4),c2(6,10),c3;
c3=c1+c2;
cout<<c3<<endl;
}
| true |
df4606ed5a5564f3b4fa45067942086bfe4c23c9 | C++ | cavallo5/cpp_scripts | /src/Calcolo di un numero romano.cpp | UTF-8 | 909 | 3.21875 | 3 | [] | no_license | #include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
int n,i,valore,risultato;
char x;
risultato=0;
cout<<"Programma per il calcolo di un numero romano"<<endl;
cout<<"Quante cifre? ";
cin>>n;
i=0;
while (i<n)
{
cout<<"Inserire il "<<i<<" valore ";
cin>>x;
switch (x)
{
case 'I':valore=1;break;
case 'V':valore=5;break;
case 'X':valore=10;break;
case 'L':valore=50;break;
case 'C':valore=100;break;
case 'D':valore=500;break;
case 'M':valore=1000;break;
default:cout<<"Carattere errato"<<endl;
}
risultato=risultato+valore;
i++;
}
cout<<"Il numero e' "<<risultato<<endl;
system("PAUSE");
return 0;
}
| true |
9d75e598f2eccc08ac2a42ffd03bd1c3826077b0 | C++ | raviswan/Elixir | /UCSD_DataStructures_Algorithms_Course/BinaryTree/binTree.cpp | UTF-8 | 9,781 | 3.375 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <cstdio>
#include "binTree.h"
using namespace std;
const int MAX_VALUE = 65535;
const int MIN_VALUE = 0;
/*--------------Binary Tree Node definition-------------------*/
int compareNodes(void* key1, void* key2){
BinTreeNode* node1 = (BinTreeNode*) key1;
BinTreeNode* node2 = (BinTreeNode*) key2;
if(*(int*)node1->getData() < *(int*)node2->getData())
return -1;
else
return 1;
}
/*Tree Node Constructor*/
BinTreeNode::BinTreeNode(void *data):left(NULL),right(NULL),data(data){
}
BinTreeNode::~BinTreeNode(){
}
BinTreeNode* BinTreeNode::getLeftNode() const{
return this->left;
}
BinTreeNode* BinTreeNode::getRightNode() const{
return this->right;
}
BinTreeNode* BinTreeNode::getParentNode() const{
return this->parent;
}
void* BinTreeNode::getData() const{
return data;
}
int BinTreeNode::setLeftNode(void* data) {
this->left = new BinTreeNode(data);
return SUCCESS;
}
int BinTreeNode::setRightNode(void* data) {
this->right = new BinTreeNode(data);
return SUCCESS;
}
int BinTreeNode::setParent(BinTreeNode* parent) {
this->parent = parent;
return SUCCESS;
}
int BinTreeNode::setLeftToNull() {
this->left = NULL;
return SUCCESS;
}
int BinTreeNode::setRightToNull() {
this->right = NULL;
return SUCCESS;
}
bool BinTreeNode::isLeafNode() const{
if(this->left == NULL && this->right==NULL)
return true;
return false;
}
/*--------------Binary Tree definition-------------------*/
/*Binary Tree Constructor*/
BinTree::BinTree():size(0),root(NULL),leafCount(0),height(-1),firstNodeFlag(false){
}
BinTree::~BinTree(){
}
int BinTree::getTreeSize() const{
return this->size;
}
BinTreeNode* BinTree::getRoot() const{
return this->root;
}
int BinTree::insertLeft(BinTreeNode* parent,void *data){
/*If we are inserting a new root*/
if(parent==NULL){
if(this->size==0){
root = new BinTreeNode(data);
this->size++;
return SUCCESS;
}
return FAILURE;
}
/*If left of parent is empty*/
if(parent->getLeftNode()==NULL){
/*Inserting node to left of parent*/
if(parent->setLeftNode(data) == SUCCESS){
this->size++;
return SUCCESS;
}
}
return FAILURE;
}
/*Insert a node to right of parent node*/
int BinTree::insertRight(BinTreeNode* parent,void* data){
/*If we are inserting a new root*/
if(parent==NULL){
if(this->size==0){
root = new BinTreeNode(data);
this->size++;
return SUCCESS;
}
return FAILURE;
}
/*If right of parent is empty*/
if(parent->getRightNode()==NULL){
/*Inserting node to right of parent*/
if(parent->setRightNode(data) == SUCCESS){
this->size++;
return SUCCESS;
}
}
return FAILURE;
}
/*Insert a node to right of parent node*/
void BinTree::connectToParent(BinTreeNode* child,BinTreeNode* parent){
child->setParent(parent);
}
void BinTree::removeLeft(BinTreeNode* parent){
BinTreeNode *toRemove;
/*No removal from emtpy tree*/
if(this->size == 0)
return;
/*If deleting from root*/
if(parent == NULL)
toRemove = this->root;
else
toRemove = parent->getLeftNode();
/*recursively remove all nodes to left of parent*/
if(toRemove != NULL){
this->removeLeft(toRemove);
this->removeRight(toRemove);
//this->destroyData(toRemove);
}
delete(toRemove);
this->size--;
}
void BinTree::removeRight(BinTreeNode* parent){
BinTreeNode *toRemove;
/*No removal from emtpy tree*/
if(this->size == 0)
return;
/*if deleting from root*/
if(parent == NULL)
toRemove = this->root;
else
toRemove = parent->getRightNode();
/*recursively remove all nodes to right of parent*/
if(toRemove != NULL){
this->removeLeft(toRemove);
this->removeRight(toRemove);
//this->destroyData(toRemove);
}
delete(toRemove);
this->size--;
}
int BinTree::destroyData(BinTreeNode* data){
if(data){
delete data;
return SUCCESS;
}
else{
printf("Nothing to delete\n");
return SUCCESS;
}
}
int BinTree::countLeaves() {
leafCount = 0;
doCountLeaves(root);
return leafCount;
}
/*Recursively count the number of leaves*/
void BinTree::doCountLeaves(BinTreeNode* node){
if(node == NULL)
return;
if(node->isLeafNode()){
leafCount++;
}
doCountLeaves(node->getLeftNode());
doCountLeaves(node->getRightNode());
}
/*Count number of non-leaves in the tree*/
int BinTree::countNonLeaves(){
return(size - countLeaves());
}
/*Get the height of a tree*/
int BinTree::getHeight(){
return (doGetHeight(root));
}
/*Recursively find height of tree. Tree with root alone has zero height*/
int BinTree::doGetHeight(BinTreeNode* node) {
if(node==NULL)
return -1;
int l = doGetHeight(node->getLeftNode());
int r = doGetHeight(node->getRightNode());
/*Compute which side has a higher value*/
height = 1 + std::max(l,r);
return height;
}
/*-------------PRE-ORDER TRAVERSAL----------*/
void BinTree::printPreOrder(void (*print)(const void *data)){
if(root==NULL)
return;
else
doPrintPreOrder(this->root,print);
}
void BinTree::doPrintPreOrder(BinTreeNode* node,void (*print)(const void *data)){
if(node==NULL)
return;
print(node);
doPrintPreOrder(node->getLeftNode(),print);
doPrintPreOrder(node->getRightNode(),print);
}
/*-------------IN-ORDER TRAVERSAL----------*/
void BinTree::printInOrder(void (*print)(const void *data)){
if(root==NULL)
return;
else
doPrintInOrder(this->root,print);
}
void BinTree::doPrintInOrder(BinTreeNode* node,void (*print)(const void *data)){
if(node==NULL)
return;
doPrintInOrder(node->getLeftNode(),print);
print(node);
doPrintInOrder(node->getRightNode(),print);
}
/*-------------POST-ORDER TRAVERSAL----------*/
void BinTree::printPostOrder(void (*print)(const void *data)){
if(root==NULL)
return;
else
doPrintPostOrder(this->root,print);
}
void BinTree::doPrintPostOrder(BinTreeNode* node,void (*print)(const void *data)){
if(node==NULL)
return;
doPrintPostOrder(node->getLeftNode(),print);
doPrintPostOrder(node->getRightNode(),print);
print(node);
}
/*Remove all leaves of a tree*/
void BinTree::removeLeaves(){
if(root==NULL)
return;
else{
doRemoveLeaves(root);
}
}
/*recursively remove left and right leaves*/
void BinTree::doRemoveLeaves(BinTreeNode* node){
if(node==NULL)
return;
/*If left(current node) is leaf, set left = NULL, delete left(current node)*/
if ( (node->getLeftNode() != NULL) ){
if ( node->getLeftNode()->isLeafNode() == true ){
printf("Removed %d\n",*((int*)node->getLeftNode()->getData()));
node->setLeftToNull();
delete node->getLeftNode();
this->size--;
}
}
/*If right(current node) is leaf, set right = NULL, delete right(current node)*/
if ( (node->getRightNode() != NULL) ){
if ( node->getRightNode()->isLeafNode() == true ){
printf("Removed %d\n",*((int*)node->getRightNode()->getData()));
node->setRightToNull();
delete node->getRightNode();
this->size--;
}
}
doRemoveLeaves(node->getLeftNode());
doRemoveLeaves(node->getRightNode());
}
bool BinTree::isBinarySearchTree(){
if (isBST(root,MIN_VALUE,MAX_VALUE) )
return true;
else
return false;
}
bool BinTree::isBST(BinTreeNode* node,int min, int max){
if(node == NULL)
return (true);
printf("node val = %d, min = %d , max = %d\n",*(int*)node->getData(),min,max );
if( *(int*)(node->getData()) <= min || *(int*)(node->getData()) >= max){
return false;
}
return( isBST(node->getLeftNode(),min,*(int*)node->getData()) &&
isBST(node->getRightNode(),*(int*)node->getData(),max) );
}
BinTreeNode* BinTree::getLeftMostNode(BinTreeNode* node){
while(node->getLeftNode() != NULL){
node = node->getLeftNode();
}
return node;
}
/*get next node in BST without using in-order traversal*/
BinTreeNode* BinTree::getNextNodeBST(){
int parentVal;
int currVal;
int rightVal;
if (!firstNodeFlag){
if(root != NULL){
current = getLeftMostNode(root);
//printf("current=%d\n",*(int*)current->getData());
firstNodeFlag = true;
}
else{
printf("root is NULL\n");
}
}
else{
/*For a given node, compare parent and right node values*/
currVal = *((int*)current->getData());
/*if parent present*/
if(current->getParentNode() != NULL){
parentVal = * ((int*)current->getParentNode()->getData());
//printf("currVal=%d, parentVal=%d\n",currVal,parentVal );
/*if current val < parent Val, you are dealing with right subtree*/
if(currVal < parentVal){
/*if right node present*/
if(current->getRightNode() != NULL){
rightVal = * ((int*)current->getRightNode()->getData());
/*if right Val < parent Val, go down right sub-tree of current node, till you get leftmost*/
if(rightVal < parentVal){
current = getLeftMostNode(current->getRightNode());
}
}
/*when there's no right node, return parent as next*/
else{
current = current->getParentNode();
}
}
/*current val > parent Val, already in right subtree*/
else{
if(current->getRightNode()!=NULL)
current = getLeftMostNode(current->getRightNode());
/*reached end of right subtree, traverse all the way up till you find element > present*/
else{
while(currVal > parentVal){
current = current->getParentNode();
if(current == root){
break;
}
currVal = *((int*)current->getData());
parentVal = * ((int*)current->getParentNode()->getData());
//printf("currVal=%d, parentVal=%d\n",currVal,parentVal );
}
if(current == root){
printf("reached end of tree\n");
return NULL;
}
current = current->getParentNode();
}
}
}
/*reached root, so goto right subtree, starting with leftmost there*/
else{
if(current->getRightNode()!=NULL)
current = getLeftMostNode(current->getRightNode());
else{
printf("reached end of tree");
return NULL;
}
}
}
return current;
}
| true |
6021aa4c41d589d61bc3cc40a9abd06265d00cdb | C++ | mwil/wifire | /src/wftable/host/src/parser/stringterminal.h | UTF-8 | 835 | 2.734375 | 3 | [] | no_license |
#pragma once
#include <string>
#include "terminal.h"
namespace Parser {
/** \brief String (Freetext) Terminal */
class StringTerminal : public Terminal {
public:
/// pointer type
typedef boost::shared_ptr<StringTerminal> ptr;
/// const pointer type
typedef boost::shared_ptr<const StringTerminal> cptr;
private:
/// parsed text
std::string string;
/** construct a new string terminal */
StringTerminal();
public:
/** get text
* \return parsed text
*/
const std::string& get() const;
protected:
PARSE_STATE _parse(Scanner& s, std::vector<Expect>& e);
COMPLETE_STATE complete(Scanner& s, std::vector<std::string>& f) const;
FIRST_STATE first(std::vector<std::string>& f) const;
Entity::ptr _clone() const;
public:
/** create a new string terminal
* \return new string terminal
*/
static ptr New();
};
}
| true |
620c46421a15c6f2da3501fa7193afd4d6cf74ca | C++ | CME211/notes | /lecture-12/src/extraction3.cpp | UTF-8 | 477 | 3.578125 | 4 | [] | no_license | #include <iostream>
#include <sstream>
int main(int argc, char *argv[]) {
// Setup a string stream to access the command line argument
std::string arg = argv[1];
std::stringstream ss;
ss << arg;
// Attempt to extract an integer from the string stream
unsigned n = 0;
if (ss >> n) { // Test for extraction success!
std::cout << "n = " << n << std::endl;
} else {
std::cerr << "ERROR: string stream extraction failed" << std::endl;
}
return 0;
}
| true |
3f8f05b6b806a0659c3234da67ef6b8898a10aad | C++ | Dmitry-1998/ROS | /src/laba_1/src/Laboratornaya_1.cpp | UTF-8 | 1,818 | 2.90625 | 3 | [] | no_license | #include "ros/ros.h"
#include <iostream>
#include "std_msgs/Int64.h"
#include "std_msgs/Int8.h"
using namespace std;
ros::Publisher g_value_pub;
std_msgs::Int64 factorial(std_msgs::Int8 input_number)
{
std_msgs::Int64 number_beetw_1;
std_msgs::Int64 number_beetw_2;
std_msgs::Int64 output_number;
number_beetw_1.data = 1;
number_beetw_2.data = 1;
for(int i = 0; i < input_number.data; i++)
{
number_beetw_2.data = number_beetw_2.data * number_beetw_1.data;
number_beetw_1.data = number_beetw_1.data + 1;
}
output_number.data = number_beetw_2.data;
return output_number;
}
void recieve(const std_msgs::Int8& input_number)
{
ROS_INFO("Received: %d", input_number.data);
if(input_number.data < 0 || input_number.data > 20)
{
ROS_WARN("Number is so BIIIIIIIIIIIIIIIIIIG!!!");
}
else
{
std_msgs::Int64 factorial_number = factorial(input_number);
ROS_INFO("Factorial value: %ld", factorial_number.data);
g_value_pub.publish(factorial_number);
}
return;
}
int main(int argc, char **argv)
{
ROS_INFO("Start!");
ros::init(argc, argv, "factorial_number");
ros::NodeHandle n;
ros::Publisher factorial_number_pub = n.advertise<std_msgs::Int8>("/factorial_number", 10);
ros::Subscriber value_sub = n.subscribe("/factorial_number", 10, recieve);
g_value_pub = n.advertise<std_msgs::Int64>("/value", 10);
ros::Rate loop_rate(1);
std_msgs::Int8 number;
while(ros::ok)
{
number.data = rand() % 50 + 0;
factorial_number_pub.publish(number);
ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
| true |
fe43e9b3dfc071479771c35ba50272411fd9b953 | C++ | elesmera11/LED_Design | /2_Row_Multiplexing/swipe_control.cpp | UTF-8 | 2,491 | 3.109375 | 3 | [] | no_license | /*
swipe_control.cpp
Module for determining the swipe state of the device.
Depending on buffer data, will determine if device is waiting or
swiping left, right, up, or down.
Authors: Kate Chamberlin, Scott Davidsen, Fergus Duggan.
Date: 05 Sep 2018
*/
#include "swipe_control.h"
//Determines the state dependent on distance gradients.
State determine_state(float x_grad, float y_grad) {
State state = Waiting;
if (x_grad) {//if x has gradient change
if (abs(x_grad) < abs(y_grad) && y_grad) {//if y also does, choose lowest grad
if (y_grad > 0) {
state = U_Swipe;
} else {
state = D_Swipe;
}
} else {
if (x_grad > 0) {
state = R_Swipe;
} else {
state = L_Swipe;
}
}
} else if (y_grad) {
if (abs(y_grad) < abs(x_grad) && x_grad) {
if (x_grad > 0) {
state = R_Swipe;
} else {
state = L_Swipe;
}
} else {
if (y_grad > 0) {
state = U_Swipe;
} else {
state = D_Swipe;
}
}
}
return state;
}
//Process the buffers so that the gesture state can be determined.
State process_buffs(circBuf_t* x_buff, circBuf_t* y_buff) {
//local variables
float x_temp[BUFF_SIZE] = {0};
float y_temp[BUFF_SIZE] = {0};
float t_temp[BUFF_SIZE] = {0};
int size = 0;
int x_time = 1;
int y_time = 1;
//populate x buffer and x_time buffer with datapoints, ignoring zeros.
while (x_time <= BUFF_SIZE) {
int temp = readCircBuf(x_buff);
if (temp != 0) {
x_temp[size] = temp;
t_temp[size] = x_time;
size++;
}
x_time++;
}
float x[size];
float x_t[size];
for (int i = 0; i < size; i++) {
x[i] = x_temp[i];
x_t[i] = t_temp[i];
}
//populate y buffer and y_time buffer with datapoints, ignoring zeros.
size = 0;
memset(t_temp, 0, BUFF_SIZE); //reset temp time buffer to zero
while (y_time <= BUFF_SIZE) {
int temp = readCircBuf(y_buff);
if (temp != 0) {
y_temp[size] = temp;
t_temp[size] = y_time;
size++;
}
y_time++;
}
float y[size];
float y_t[size];
for (int i = 0; i < size; i++) {
y[i] = y_temp[i];
y_t[i] = t_temp[i];
}
//use linear regression to determine gradient of swipe
float x_grad = simpLinReg(x_t, x, sizeof(x_t)/sizeof(float));
float y_grad = simpLinReg(y_t, y, sizeof(y_t)/sizeof(float));
// Serial.print("X: ");
// Serial.println(x_grad, 4);
// Serial.print("Y: ");
// Serial.println(y_grad, 4);
State state = determine_state(x_grad, y_grad);
return state;
} | true |
7aa4337cbbbdc352622d7d763c742e54f4dcb2df | C++ | kevinqi34/HackerRank | /Algorithms/Warmup/Diagonal_Difference.cpp | UTF-8 | 662 | 3.046875 | 3 | [] | no_license | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
int n;
cin >> n;
// Load Matrix
vector< vector<int> > a(n,vector<int>(n));
for(int a_i = 0;a_i < n;a_i++){
for(int a_j = 0;a_j < n;a_j++){
cin >> a[a_i][a_j];
}
}
int col1_counter = 0;
int col2_counter = n - 1;
int diag1 = 0;
int diag2 = 0;
for (int row = 0; row < n; row++) {
diag1+=a[row][col1_counter];
diag2+=a[row][col2_counter];
col1_counter++;
col2_counter--;
}
cout << abs(diag1 - diag2) << endl;
return 0;
}
| true |
97ba39ec3caa3a538c6a50879cf89a2bbfc72f72 | C++ | doodoonovitch/GameTech | /CoreFx/Maths/DualQuaternion.cpp | UTF-8 | 2,365 | 2.734375 | 3 | [] | no_license | #include "stdafx.h"
#include "CoreFx.h"
namespace CoreFx
{
namespace Maths
{
// =======================================================================
// =======================================================================
DualQuaternion Conjugate(DualQuaternion const & a)
{
return DualQuaternion(glm::conjugate(a.mQr), glm::conjugate(a.mQd));
}
float Dot(DualQuaternion const & a, DualQuaternion const & b)
{
return glm::dot(a.mQr, b.mQr);
}
DualQuaternion Normalize(DualQuaternion const & q)
{
float mag = glm::dot(q.mQr, q.mQr);
assert(mag > 0.000001f);
DualQuaternion ret;
ret.mQr = q.mQr / mag;
ret.mQd = q.mQd / mag;
return ret;
}
DualQuaternion operator*(float scale, DualQuaternion const & q)
{
return DualQuaternion(scale * q.mQr, scale * q.mQd);
}
DualQuaternion operator*(DualQuaternion const & q, float scale)
{
return DualQuaternion(scale * q.mQr, scale * q.mQd);
}
DualQuaternion operator*(DualQuaternion const & lhs, DualQuaternion const & rhs)
{
return DualQuaternion(lhs.mQr * rhs.mQr, lhs.mQr * rhs.mQd + lhs.mQd * rhs.mQr);
}
DualQuaternion operator+(DualQuaternion const & lhs, DualQuaternion const & rhs)
{
return DualQuaternion(lhs.mQr + rhs.mQr, lhs.mQd + rhs.mQd);
}
glm::mat4 ToMatrix(DualQuaternion const & dualQuat)
{
DualQuaternion q = Normalize(dualQuat);
glm::mat4 m(1.f);
float w = q.mQr.w;
float x = q.mQr.x;
float y = q.mQr.y;
float z = q.mQr.z;
// Extract rotational information
m[0].x = w*w + x*x - y*y - z*z;
m[0].y = 2 * x*y + 2 * w*z;
m[0].z = 2 * x*z - 2 * w*y;
m[1].x = 2 * x*y - 2 * w*z;
m[1].y = w*w + y*y - x*x - z*z;
m[1].z = 2 * y*z + 2 * w*x;
m[2].x = 2 * x*z + 2 * w*y;
m[2].y = 2 * y*z - 2 * w*x;
m[2].z = w*w + z*z - x*x - y*y;
// Extract translation information
glm::quat t = (q.mQd * 2.0f) * glm::conjugate(q.mQr);
m[3].x = t.x;
m[3].y = t.y;
m[3].z = t.z;
return m;
//glm::mat4 identityMat = glm::mat4(1.0f);
//glm::mat4 rotMatrix = glm::mat4_cast(dualQuat.GetRotation()); //rotation is glm::quat
//glm::mat4 transMatrix = glm::translate(identityMat, dualQuat.GetTranslation());
//glm::mat4 m = transMatrix * rotMatrix;
//return m;
}
// =======================================================================
// =======================================================================
} // namespace Maths
} // namespace FxEngine
| true |
a4351af7330a3471cf3dbebd3765898250b42756 | C++ | sweetpand/LeetCode-1 | /solutions/cpp/0502.cpp | UTF-8 | 848 | 3.015625 | 3 | [] | no_license | struct Item {
int profit;
int capital;
};
class Solution {
public:
int findMaximizedCapital(int k, int W, vector<int>& Profits,
vector<int>& Capital) {
auto compareC = [](const Item& a, const Item& b) {
return a.capital > b.capital;
};
auto compareP = [](const Item& a, const Item& b) {
return a.profit < b.profit;
};
priority_queue<Item, vector<Item>, decltype(compareC)> pqCap(compareC);
priority_queue<Item, vector<Item>, decltype(compareP)> pqPro(compareP);
for (int i = 0; i < Capital.size(); ++i)
pqCap.push({Profits[i], Capital[i]});
while (k--) {
while (!pqCap.empty() && pqCap.top().capital <= W)
pqPro.push(pqCap.top()), pqCap.pop();
if (pqPro.empty()) break;
W += pqPro.top().profit, pqPro.pop();
}
return W;
}
}; | true |
1bc4e2e50543a3245419431d7408fb55356bc3e0 | C++ | Shardic/ComputerGraphics2015 | /Cylinder.cpp | UTF-8 | 1,117 | 2.859375 | 3 | [] | no_license | #include <GL/gl.h>
#include "Cylinder.h"
#define _USE_MATH_DEFINES
#include <cmath>
#include <iostream>
Cylinder::Cylinder() {
}
Cylinder::~Cylinder(){
}
void Cylinder::drawCylinder() {
glTranslated(xPos,yPos,zPos);
double majorStep = height / numMajor;
double minorStep = 2.0 * M_PI / numMinor;
int i, j;
for (i = 0; i < numMajor; ++i) {
GLfloat z0 = 0.5 * height - i * majorStep;
GLfloat z1 = z0 - majorStep;
glBegin(GL_TRIANGLE_FAN);
for (j = 0; j <= numMinor; ++j) {
double a = j * minorStep;
GLfloat x = radius * cos(a);
GLfloat y = radius * sin(a);
glVertex3f(x, y, z0);
glVertex3f(x, y, z1);
}
glEnd();
}
}
double Cylinder::getRadius() {
return radius;
}
void Cylinder::setRadius(double r) {
this->radius = r;
}
double Cylinder::getXPos() {
return xPos;
}
void Cylinder::setXPos(double x) {
this->xPos = x;
}
double Cylinder::getYPos() {
return yPos;
}
void Cylinder::setYPos(double y) {
this->yPos = y;
}
void Cylinder::setHeight(double h) {
this->height = h;
}
void Cylinder::rearangeZPos() {
this->zPos = 1;
}
| true |
5538416bb64f606bd4bb82e904238c471b132000 | C++ | kriogenia/the-parting-of-sarah | /ThePartingOfSarah/Coin.h | UTF-8 | 426 | 2.53125 | 3 | [
"MIT"
] | permissive | #pragma once
#include "Item.h"
#include "Animation.h"
class Coin :
public Item
{
public:
Coin(float x, float y, Game* game);
/* Game cycle */
void draw(int scrollX = 0, int scrollY = 0, float rotation = 0.0) override;
/* Item */
Item* getCopy(float x, float y) override;
private:
/* Item */
void applyEffect(Player* player) override;
void notify(Player* player) override;
/* Animation */
Animation* animation;
}; | true |
b40c6a407d16696490e5d51a6b824ef73d1439bb | C++ | TheIllusionistMirage/libKPEG | /include/Decoder.hpp | UTF-8 | 3,386 | 2.578125 | 3 | [] | no_license | /**
* @file Decoder.hpp
* @author Koushtav Chakrabarty (koushtav@fleptic.eu)
* @date 2000 B.C.
* @brief The implementation of a baseline, DCT JPEG decoder
*
* Decoder module is the implementation of a 8-bit Sequential
* Baseline DCT, grayscale/RGB encoder with no subsampling (4:4:4).
*/
#ifndef DECODER_HPP
#define DECODER_HPP
#include <fstream>
#include <vector>
#include <utility>
#include <bitset>
#include "Types.hpp"
#include "Image.hpp"
#include "HuffmanTree.hpp"
#include "MCU.hpp"
namespace kpeg
{
class JPEGDecoder
{
public:
enum ResultCode
{
SUCCESS ,
TERMINATE ,
ERROR ,
DECODE_INCOMPLETE ,
DECODE_DONE
};
public:
ResultCode decodeImageFile();
// void displayImage();
public:
JPEGDecoder();
JPEGDecoder( const std::string& filename );
~JPEGDecoder();
bool open( const std::string& filename );
void close();
ResultCode parseSegmentInfo( const UInt8 byte );
void printDetectedSegmentNames();
bool dumpRawData();
inline void printCurrPos()
{
std::cout << "Current file pos: 0x" << std::hex << m_imageFile.tellg() << std::endl;
}
private:
void parseJFIFSegment();
void parseQuantizationTable();
ResultCode parseSOF0Segment();
void parseHuffmanTable();
void parseSOSSegment();
void scanImageData();
void parseComment();
//
// Convert bytes of the form XXFF00YY to just XXFFYY
void byteStuffScanData();
/**
* @brief Decode the RLE-Huffman encoded image pixel data
* @author Koushtav Chakrabarty (koushtav@fleptic.eu)
*
* This function goes bit by bit over the image scan data
* and decodes it using the provided DC and AC Huffman tables
* for luminance (Y) and chrominance ( Cb & Cr ).
*/
void decodeScanData();
private:
void displayHuffmanCodes();
private:
std::string m_filename;
std::ifstream m_imageFile;
Image m_image;
std::vector<std::vector<UInt16>> m_QTables;//[4];
//int m_huffTableCount;
// For i=0..3:
// HT_i is array of size=16, where j-th element is < count-j-bits, symbol-list >
//
HuffmanTable m_huffmanTable[2][2];
std::vector< std::pair<int, int> > mDHTsScanned;
HuffmanTree m_huffmanTree[2][2];
// Image scan data
//std::vector<std::bitset<8>> m_scanData;
std::string m_scanData;
std::vector<MCU> m_MCU;
};
}
#endif // DECODER_HPP
| true |
385aa741ac6ada550cf5010b81a22cc914f3a059 | C++ | jamesrcounts/CS537 | /HW3/src/dijkstra.cpp | UTF-8 | 687 | 3.046875 | 3 | [] | no_license | #include <utility> // for pair
#include <algorithm>
#include <iterator>
#include "Parser.h"
using namespace std;
int main( int argc, char const *argv[] )
{
int start = atoi( argv[1] );
int end = atoi( argv[2] );
string filename( argv[3] );
Parser p( filename );
Graph g = p.CreateGraph();
g.ComputePaths( start );
list<vertex_t> path = g.GetShortestPathTo( end );
cout << "Distance from " << start << " to " << end << ": " <<
g.DistanceTo( end ) << endl;
cout << "Path : ";
copy( path.begin(),
path.end(),
ostream_iterator<vertex_t>( cout, " " ) );
cout << endl;
return 0;
}
| true |
7371788ecb8ba7d2fa47deccec6b44ac5db79cc7 | C++ | ryogo108/PKU | /3669.cpp | UTF-8 | 1,206 | 2.96875 | 3 | [] | no_license | //蟻本初級練習問題No.6
// 14/7/13 accepted
#include<iostream>
#include<queue>
#include<cstdio>
#define INF 10000000
#define N 320 ////map_data配列は大きめに!! これにn時間も取られるなんてもったいない!!
using namespace std;
int data[N][N];
int ans_d[ N][ N];
typedef pair<int,int> P;
int dx[4]={1,0,-1,0},dy[4]={0,1,0,-1};
int bfs(){
ans_d[0][0]=0;
if(data[0][0]==0)return -1;
queue<P> que;
que.push(P(0,0));
while(que.size()){
P p=que.front();que.pop();
int cx=p.first,cy=p.second;
if(data[cy][cx]==INF)return ans_d[cy][cx];
for(int i=0;i<4;i++){
int nx=cx+dx[i],ny=cy+dy[i];
if(0<=nx && 0<=ny && data[ny][nx]>ans_d[cy][cx]+1 && ans_d[cy][cx]+1<ans_d[ny][nx]){
que.push(P(nx,ny));
ans_d[ny][nx]=ans_d[cy][cx]+1;
}
}
}
return -1;
}
int main(){
for(int i=0;i< N;i++){
for(int j=0;j< N;j++){
data[i][j]=INF;
ans_d[i][j]=INF;
}
}
int n;
cin>>n;
for(int i=0;i<n;i++){
int x,y,t;
scanf("%d %d %d",&x,&y,&t);
data[y][x]=min(t,data[y][x]);
for(int j=0;j<4;j++){
int nx=x+dx[j],ny=y+dy[j];
if(nx>=0 && ny>=0){
data[ny][nx]=min(data[ny][nx],t);
}
}
}
cout<<bfs()<<endl;
return 0;
}
| true |
e6f6589a32b503aefa6d4f106604090ff418aa3f | C++ | jenninglim/graphics-engine | /raytracer/Source/Scene/TestModelH.cpp | UTF-8 | 4,079 | 2.984375 | 3 | [] | no_license | #include "TestModelH.h"
#include "Object.h"
#include "Box.h"
#include "Sphere.h"
void push_box(vector<Object *> &objects,
vector<Triangle> &object_tri,
const float reflectance)
{
Object * object = new Box(object_tri, reflectance);
objects.push_back(object);
object_tri.clear();
}
void push_sphere(vector<Object *> &objects,
const vec4 pos,
const float r)
{
Object * object = new Sphere(pos, r);
objects.push_back(object);
}
void push_box(vector<Object *> &objects,
vector<Triangle> &object_tri,
const float reflectance,
const float refract)
{
Object * object = new Box(object_tri, reflectance, refract);
objects.push_back(object);
object_tri.clear();
}
// Loads the Cornell Box. It is scaled to fill the volume:
// -1 <= x <= +1
// -1 <= y <= +1
// -1 <= z <= +1
void LoadTestModel( std::vector<Object *>& objects )
{
using glm::vec3;
using glm::vec4;
vector<Triangle> triangles;
// Defines colors:
vec3 red( 0.9f, 0.1f, 0.1f );
vec3 yellow( 0.9f, 0.9f, 0.1f );
vec3 green( 0.1f, 0.9f, 0.1f );
vec3 cyan( 0.1f, 0.9f, 0.9f );
vec3 blue( 0.1f, 0.1f, 0.9f );
vec3 purple( 0.9f, 0.1f, 0.9f );
vec3 white( 0.9f, 0.9f, 0.9f );
triangles.clear();
//triangles.reserve( 5*2*3 );
// ---------------------------------------------------------------------------
// Room
float L = 555; // Length of Cornell Box side.
vec4 A(L,0,0,1);
vec4 B(0,0,0,1);
vec4 C(L,0,L,1);
vec4 D(0,0,L,1);
vec4 E(L,L,0,1);
vec4 F(0,L,0,1);
vec4 G(L,L,L,1);
vec4 H(0,L,L,1);
// Floor:
triangles.push_back( Triangle( C, B, A, white ) );
triangles.push_back( Triangle( C, D, B, white ) );
// Left wall
triangles.push_back( Triangle( A, E, C, blue ) );
triangles.push_back( Triangle( C, E, G, blue ) );
// Right wall
triangles.push_back( Triangle( F, B, D, red ) );
triangles.push_back( Triangle( H, F, D, red ) );
// Ceiling
triangles.push_back( Triangle( E, F, G, white ) );
triangles.push_back( Triangle( F, H, G, white ) );
// Back wall
triangles.push_back( Triangle( G, D, C, white ) );
triangles.push_back( Triangle( G, H, D, white ) );
push_box(objects, triangles,WALL_REFLECTANCE);
// ---------------------------------------------------------------------------
// Short block
A = vec4(290,0,114,1);
B = vec4(130,0, 65,1);
C = vec4(240,0,272,1);
D = vec4( 82,0,225,1);
E = vec4(290,165,114,1);
F = vec4(130,165, 65,1);
G = vec4(240,165,272,1);
H = vec4( 82,165,225,1);
// Front
triangles.push_back( Triangle(E,B,A,white) );
triangles.push_back( Triangle(E,F,B,white) );
// Front
triangles.push_back( Triangle(F,D,B,white) );
triangles.push_back( Triangle(F,H,D,white) );
// BACK
triangles.push_back( Triangle(H,C,D,white) );
triangles.push_back( Triangle(H,G,C,white) );
// LEFT
triangles.push_back( Triangle(G,E,C,white) );
triangles.push_back( Triangle(E,A,C,white) );
// TOP
triangles.push_back( Triangle(G,F,E,white) );
triangles.push_back( Triangle(G,H,F,white) );
//push_box(objects, triangles, BOX_REFLECTANCE);
// ---------------------------------------------------------------------------
// Tall block
A = vec4(423,0,247,1);
B = vec4(265,0,296,1);
C = vec4(472,0,406,1);
D = vec4(314,0,456,1);
E = vec4(423,330,247,1);
F = vec4(265,330,296,1);
G = vec4(472,330,406,1);
H = vec4(314,330,456,1);
// Front
triangles.push_back( Triangle(E,B,A,white) );
triangles.push_back( Triangle(E,F,B,white) );
// Front
triangles.push_back( Triangle(F,D,B,white) );
triangles.push_back( Triangle(F,H,D,blue) );
// BACK
triangles.push_back( Triangle(H,C,D,white) );
triangles.push_back( Triangle(H,G,C,white) );
// LEFT
triangles.push_back( Triangle(G,E,C,white) );
triangles.push_back( Triangle(E,A,C,white) );
// TOP
triangles.push_back( Triangle(G,F,E,white) );
triangles.push_back( Triangle(G,H,F,white) );
push_box(objects, triangles,BOX_REFLECTANCE, 1.2f);
//push_sphere(objects, vec4(0.5f,0.f,-0.3f,0), 0.2f);
//push_sphere(objects, vec4(-0.5f,0.f,-0.3f,0), 0.2f);
}
| true |
470adb59ac21d4595730d2da2115930648624838 | C++ | isaurabhkr/Cpp-Practice | /palindrome.cpp | UTF-8 | 438 | 3.53125 | 4 | [] | no_license | #include <locale>
#include<iostream>
class Palindrome
{
public:
static bool isPalindrome(const std::string& word)
{
std::locale loc;
for (int i = 0; i < word.size(); i++)
if (std::tolower(word[i], loc) != std::tolower(word[word.size() - i - 1], loc))
return false;
return true;
}
};
int main()
{
std::cout << Palindrome::isPalindrome("Deleveled");
}
| true |
fabf3362b2acfa553d633f7fa18c4f6610b9f8c8 | C++ | sayedfraz/lab1part2.2 | /main/main.cpp | UTF-8 | 536 | 3.734375 | 4 | [] | no_license | #include <iostream>
using namespace std;
// Base class
class Shape
{
public:
// pure virtual function providing interface framework.
virtual int getArea() = 0;
void setPi(int p)
{
pi = p;
}
void setRaduis(int r)
{
radius = r;
}
protected:
int pi;
int radius;
};
class Circle: public Shape
{
public:
int getArea()
{
return (pi *(radius * radius));
}
};
int main(void)
{
Circle Cir;
Cir.setPi(5);
Cir.setRaduis(7);
// Print the area of the object.
cout << "Total Circle area: " << Cir.getArea() << endl;
return 0;
}
| true |
0cfd8d7a624801c249cc6888618eddd141374303 | C++ | rajnishgeek/DSandAlgorithmPracticeSolution | /Dynamic Programming/FlipArray.cpp | UTF-8 | 400 | 2.515625 | 3 | [] | no_license | int minFlip(vector<int> &A)
{
int sum = 0;
for (int i = 0; i < A.size(); i++)
sum += A[i];
sum /= 2;
vector<int> dp(sum + 1, INT_MAX);
dp[0] = 0;
for (int i = 0; i < A.size(); i++)
{
for (int j = sum; j >= A[i]; j--)
{
if (dp[j - A[i]] != INT_MAX)
dp[j] = min(dp[j], dp[j - A[i]] + 1);
}
}
for (int i = sum; i >= 0; i--)
if (dp[i] != INT_MAX)
return dp[i];
return 0;
} | true |
4d6a99d0dd6d782d58dc27694d944b205cc2e174 | C++ | yangzhaofeng/qp-H2S | /qpcall.h | UTF-8 | 2,986 | 2.578125 | 3 | [
"MIT"
] | permissive | #include<cmath>
#include"transfer.h"
const double _pi = 3.1415926535897932384626;
const double m_H = 1.0078250319; //amu, Pure and Applied Chemistry. 75 (6): 683–800
const double m_S = 31.97207073; //amu, Pure and Applied Chemistry. 75 (6): 683–800
const double De = 38667.2857; //cm^-1
const double alpha = 1.6627E10; //m^-1
const double frr = -9.8705E22; //cm^-1 m^-2
const double h = 6.626069934E-34; //J s
const double h_bar = 1.054571800E-34; //J s
const double beta = 92.11; //deg
const double m = m_S * m_H / (m_S + m_H); //amu
const double omega = alpha * sqrt(2.0 * cmtoj(De) / amutokg(m));
const double omegax = alpha * alpha * h_bar / (2 * amutokg(m));
const double k = omega / omegax;
const double grr = cos(beta * _pi /180) / amutokg(m_S);
/*class _laguerre
{
private:
int __n; double __alpha, __x, _result;
public:
void init(){
__n=0; __alpha=0; __x=0; _result= -1;
}
bool same(int _n,double _alpha,double _x){
return (_n==__n && _alpha==__alpha && _x==__x && result != -1);
}
void flush(){
result = -1;
}
void result_write(int _n; double _alpha,double _x,double result){
__n=_n; __alpha=_alpha; __x=_x; _result=result;
}
double result_get(){
return _result;
}
}lagu[50];*/
//double omega(double,double,double);
//double omega();
//double omegax(double,double,double);
//double omegax();
//double k();
//double grr();
//double grr(double,double);
double Nn();
double Nn(double,double,int);
int factorial(int);
double laguerre(int,double,double);
void laguerre_init();
int delta(int,int);
double E(int);
/*
#if (defined alpha) && (defined de) && (defined m)
inline double omega(){
return omega(alpha,De,m);
}
#endif
inline double omega(double _alpha, double _De, double _m){
return (_alpha * sqrt(2.0 * _De / _m));
}
#if (defined alpha) && (defined hbar) && (defined m)
inline double omegax(){
return omegax(alpha, hbar, _m);
}
#endif
inline double omegax(double _alpha, double _hbar, double _m){
return (_alpha * _alpha * _hbar / ( 2 * _m ));
}
#if (defined beta) && (defined m_S)
inline double grr(){
return grr(beta,m_S);
}
#endif
inline double grr(double _beta,double _m_S){
return cos(_beta * _pi /180) / _m_S;
}
*/
inline double Nn(double _alpha, double _k, int _n){
return sqrt(_alpha * factorial(_n) * (_k - 2 * _n - 1) / tgamma(_k - _n));
}
inline int factorial(int _n){
return tgamma(_n + 1);
}
inline double E(int n){
return h_bar * omega * (n + 0.5) - h_bar * omegax * (n + 0.5) * (n + 0.5);
}
/*double laguerre(int _n,double _alpha,double _x){
if(_n==0){
lagu[_n].result_write(_n,_alpha,_x,1);
}
if(_n==1){
lagu[_n].result_write(_n,_alpha,_x,1 + _alpha - _x);
}
if(lagu[_n].same(_n,_alpha,_x)){
return lagu[_n].result_get();
}else{
return ((2*(_n - 1) + 1 + _alpha - _x) * laguerre(_n - 1,_alpha,_x) - (_n - 1 + _alpha) * lagurre(_n - 2,_alpha,_x)) / _n;
}
}*/
/*void laguerre_init(){
for(int __i=0;__i<=49;__i++){
lagu[i].init();
}
}*/
inline int delta(int _n,int _k){
return (_n==_k);
}
| true |
1302386a44c744b547c21c754e7de198d24503a3 | C++ | Mrhuangyi/leetcode-Solutions | /Cpp/Medium/208. 实现 Trie (前缀树).cpp | UTF-8 | 1,989 | 4.15625 | 4 | [] | no_license | /*
实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。
示例:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // 返回 true
trie.search("app"); // 返回 false
trie.startsWith("app"); // 返回 true
trie.insert("app");
trie.search("app"); // 返回 true
说明:
你可以假设所有的输入都是由小写字母 a-z 构成的。
保证所有输入均为非空字符串。
*/
class TrieNode {
public:
TrieNode* child[26];
bool isWord;
TrieNode() : isWord(false) {
for(auto &a : child) a = NULL;
}
};
class Trie {
private:
TrieNode* root;
public:
/** Initialize your data structure here. */
Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
void insert(string word) {
TrieNode *p = root;
for(auto &a : word) {
int i = a - 'a';
if(!p->child[i]) {
p->child[i] = new TrieNode();
}
p = p->child[i];
}
p->isWord = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
TrieNode *p = root;
for(auto &a : word) {
int i = a - 'a';
if(!p->child[i]) {
return false;
}
p = p->child[i];
}
return p->isWord;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
TrieNode *p = root;
for(auto &a : prefix) {
int i = a - 'a';
if(!p->child[i]) {
return false;
}
p = p->child[i];
}
return true;
}
};
/**
* Your Trie object will be instantiated and called as such:
* Trie obj = new Trie();
* obj.insert(word);
* bool param_2 = obj.search(word);
* bool param_3 = obj.startsWith(prefix);
*/
| true |
3e3af41884ae510e6a3b4d4da6820661a630b1fd | C++ | tyagiakash926/Level-up-Dec | /GFG_contest/Array/l001.cpp | UTF-8 | 620 | 2.765625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
// Q - 2
//https://practice.geeksforgeeks.org/problems/find-immediate-smaller-than-x/1/?track=sp-arrays-and-searching&batchId=152#
int immediateSmaller(int arr[], int n, int x)
{
// your code here
int smaller = 0;
int imm=(int)1e9;
for(int i=0;i<n;i++){
if(x-arr[i]>0 && x-arr[i]<imm){
imm = x-arr[i];
smaller = arr[i];
}
}
return smaller==0?-1:smaller;
}
// https://practice.geeksforgeeks.org/problems/leaders-in-an-array-1587115620/1/?track=sp-arrays-and-searching&batchId=152#
int main(){
return 0;
} | true |
a75816b701f41bb716137f949274d4adf1b75fd9 | C++ | moshe31sh/Course_Bid_C-_Project | /CourseBid/bid10192015 FINAL MERGE/Shenkar_CourseBidSystem/CourseBid_Common/Formula.cpp | UTF-8 | 2,670 | 3.0625 | 3 | [] | no_license | /* ---------------------------------------------------------------------------
** This software is Shenkar College for Engineering and Design final submission
** for course "Tools of Software Engineering".
** Authors: <Ohad Sasson, Moshe Shimon, Yaron Israeli, Maor Toubian, Yossi Gleyzer>
**
** Formula.cpp
** Formula class
**
** Author: Yossi Gleyzer
** -------------------------------------------------------------------------*/
#include "Formula.h"
const string Formula::TAG_FORMULA = "formula";
/*
** Consrtuctor.
** NOTE: formulaAsString is full string as stored in DB (not only formula string itself)
*/
Formula::Formula(string formulaAsString, IStorage * storage) : IdObj(0, storage)
{
long serialS = storage->getNumberFromStringByTag(formulaAsString, storage->TAG_SERIAL);
if (serialS != this->SERIAL)
{
throw new exception(); //wrong serial
}
this->id = storage->getNumberFromStringByTag(formulaAsString, storage->TAG_ID);
this->formula = storage->getStringFromStringByTag(formulaAsString, TAG_FORMULA);
}
/*(Storage override)
** Creates record and saves to DB using IStorage from base IdObj.
** Recursiveness not works for this class, no matter if true or false - here only for inheritance.
*/
void Formula::save(bool recursive)
{
//create the record
string record = string("<" + storage->TAG_OBJ + ">");
record += string("<" + storage->TAG_SERIAL + "=\"" + static_cast<ostringstream*>(&(ostringstream() << SERIAL))->str() + "\">");
record += string("<" + storage->TAG_ID + "=\"" + static_cast<ostringstream*>(&(ostringstream() << id))->str() + "\">");
record += string("<" + TAG_FORMULA + "=\"" + formula + "\">");
record += string("<\\" + storage->TAG_OBJ + ">");
storage->save(record);
}
/*(Storage override)
Delete record and save DB using IStorage from base IdObj.
*/
void Formula::deleteMe()
{
storage->deleteObj(this->SERIAL, this->id);
storage->save();
}
/*
** Static Method - Returns a vector of all RegistrationStartDates.
*/
vector<Formula> Formula::getAllFormulas(IStorage * storage)
{
vector<Formula> allFormulas;
vector<string> formulasAsString = storage->getAll(Formula::SERIAL);
for each (string formulaAsString in formulasAsString)
{
Formula * formula = new Formula(formulaAsString, storage);
allFormulas.push_back(*formula);
}
return allFormulas;
}
/*
** Converts a RegistrationStartDate to String.
** Used for Debug purposes only!
*/
string Formula::ToString()
{
string formulaStr("Formula: [objId:" + to_string(this->id));
formulaStr += " serial: " + to_string(this->SERIAL);
formulaStr += " formula: " + this->formula;
formulaStr += "]";
return formulaStr;
} | true |
2319446ed143667546ffd13d422e30160923764f | C++ | KazeLv/PAT-advanced-level | /1003Emergency.cpp | UTF-8 | 2,442 | 2.78125 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct Way {
int m_nLength;
int m_nRescues;
};
const int inf = 999999999;
int main() {
int nCities, nRoads;
int nStart, nEnd;
cin >> nCities >> nRoads >> nStart >> nEnd; //read the first line for information
int **ppnMap = new int*[nCities];
int *pnRescues = new int[nCities];
vector<bool> vec_visit;
for (int i = 0; i < nCities; i++) { //construct standard map of graph
ppnMap[i] = new int[nCities];
for (int j = 0; j < nCities; j++) {
if (i == j) ppnMap[i][j] = 0;
else ppnMap[i][j] = inf;
}
vec_visit.push_back(false);
cin >> pnRescues[i];
}
for (int i = 0; i < nRoads; i++) {
int ter1, ter2, len; //add roads to map
cin >> ter1 >> ter2 >> len;
ppnMap[ter1][ter2] = len;
ppnMap[ter2][ter1] = len;
}
int *pnDis = new int[nCities];
int *pnMostRescues = new int[nCities];
int *pnShortestNum = new int[nCities];
fill(pnDis,pnDis+nCities,inf);
copy(pnRescues,pnRescues+nCities,pnMostRescues);
fill(pnShortestNum,pnShortestNum+nCities,0);
pnDis[nStart] = 0;
pnShortestNum[nStart] = 1;
for(int i = 0; i < nCities ; i++){
int minCity = -1, shortestRoad = inf;
for(int j = 0; j < nCities; j++){
if(vec_visit[j] == false && pnDis[j] < shortestRoad){
minCity = j;
shortestRoad = pnDis[j];
}
}
if(minCity == -1) break;
vec_visit[minCity] = true;
for(int k = 0; k < nCities; k++){
if(vec_visit[k]==false &&ppnMap[minCity][k]!=inf){
if(shortestRoad + ppnMap[minCity][k] < pnDis[k]){
pnDis[k] = shortestRoad + ppnMap[minCity][k];
pnShortestNum[k] = pnShortestNum[minCity];
pnMostRescues[k] = pnMostRescues[minCity] + pnRescues[k];
}
else if (shortestRoad + ppnMap[minCity][k] == pnDis[k]){
pnShortestNum[k] = pnShortestNum[k]+pnShortestNum[minCity];
if(pnMostRescues[minCity] + pnRescues[k] > pnMostRescues[k]){
pnMostRescues[k] = pnMostRescues[minCity] + pnRescues[k];
}
}
}
}
}
cout<<pnShortestNum[nEnd]<<" "<<pnMostRescues[nEnd];
for (int i = 0; i < nCities; i++) delete[] ppnMap[i]; //free memory
delete[] ppnMap; //
delete[] pnRescues; //
delete[] pnDis;
delete[] pnMostRescues;
delete[] pnShortestNum;
return 0;
}
/*
complete by changed dijkstra algorithm
add array for the number of shortest ways and array for mostRescues
update data when find a shortest way or equal way
*/ | true |
27b55e797f3becb5723a58f2a244913bc34a5c4d | C++ | paule32/radiovp | /ttimer.h | UTF-8 | 810 | 2.953125 | 3 | [] | no_license | #ifndef TTIMER_H
#define TTIMER_H
#include "SDL.h"
#include "SDL_timer.h"
class TTimer
{
public:
TTimer(int p_interval = 1000)
{
interval = p_interval;
accumulator = 0;
total = 0;
cur_time = last_time = SDL_GetTicks();
}
int ready()
{
return accumulator > interval;
}
int check()
{
if( ready() )
{
accumulator -= interval;
return 1;
}
return 0;
}
void update()
{
int delta;
cur_time = SDL_GetTicks();
delta = cur_time - last_time;
total += delta;
accumulator += delta;
last_time = cur_time;
}
private:
int last_time;
int cur_time;
int accumulator;
int total;
int interval;
};
#endif // TTIMER_H
| true |
bd3c5ec08e92dc7119740f9e10628231de068cf0 | C++ | weijingtao/snow | /test1.cpp | UTF-8 | 1,357 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | //
// Created by weitao on 3/5/16.
//
#include <cstdint>
#include <iostream>
#include <chrono>
#include <tuple>
#include <vector>
#include <boost/optional.hpp>
#include <string>
#include "snow.hpp"
class echo_session : public snow::session<uint32_t, uint32_t> {
public:
explicit echo_session(boost::asio::io_service &ios)
: snow::session<uint32_t, uint32_t>{ios} {
}
virtual boost::optional<uint32_t> process(const uint32_t &req) override {
SNOW_LOG_TRACE("req {}", req);
return {req + 10};
}
};
class server : public snow::server<echo_session> {
public:
virtual int check(const char *data, std::size_t size) const override {
if (size >= 4) {
return 4;
} else {
return 0;
}
}
virtual std::string encode(const response_t &rsp) const override {
SNOW_LOG_TRACE("rsp {}", rsp);
return std::string((char *) &rsp, sizeof(rsp));
}
virtual request_t decode(const char *data, std::size_t size) const override {
return *(uint32_t *) (data);
}
};
int main(int argc, char *argv[]) {
SNOW_LOG_INFO("test1 begin");
try {
server the_server;
the_server.start();
} catch (std::exception &e) {
SNOW_LOG_INFO("Exception: {}", e.what());
}
SNOW_LOG_INFO("test1 end");
return 0;
} | true |
c1bf2f55241ea53d0ad3bc60df37c502fb4d743c | C++ | GlebKirsan/coursera | /c++/3_red_belt/4_week/sportsmen/sportsmen.cpp | UTF-8 | 818 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <list>
using namespace std;
int main(){
ios_base::sync_with_stdio(0);
cin.tie(nullptr);
const int MAX_SP_MAN = 100'000;
list<int> sportsmen;
vector<list<int>::iterator> pos_in_list(MAX_SP_MAN, end(sportsmen));
int n, number, prev_sportsmen;
cin >> n;
for(int i = 0; i < n; ++i){
cin >> number >> prev_sportsmen;
if (pos_in_list[prev_sportsmen] == end(sportsmen)){
sportsmen.push_back(number);
pos_in_list[number] = prev(end(sportsmen));
} else {
pos_in_list[number] = sportsmen.insert(
pos_in_list[prev_sportsmen], number);
}
}
for(const auto& s_man : sportsmen){
cout << s_man << ' ';
}
cout << endl;
}
| true |
10fef939853c0cb14e1fcedb52c4dc018cd84362 | C++ | StanfordAHA/Halide-to-Hardware | /test/correctness/memoize.cpp | UTF-8 | 18,400 | 2.59375 | 3 | [
"MIT"
] | permissive | #include "Halide.h"
#include "HalideRuntime.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
using namespace Halide;
#ifdef _WIN32
#define DLLEXPORT __declspec(dllexport)
#else
#define DLLEXPORT
#endif
// External functions to track whether the cache is working.
int call_count = 0;
extern "C" DLLEXPORT int count_calls(halide_buffer_t *out) {
if (!out->is_bounds_query()) {
call_count++;
Halide::Runtime::Buffer<uint8_t>(*out).fill(42);
}
return 0;
}
int call_count_with_arg = 0;
extern "C" DLLEXPORT int count_calls_with_arg(uint8_t val, halide_buffer_t *out) {
if (!out->is_bounds_query()) {
call_count_with_arg++;
Halide::Runtime::Buffer<uint8_t>(*out).fill(val);
}
return 0;
}
int call_count_with_arg_parallel[8];
extern "C" DLLEXPORT int count_calls_with_arg_parallel(uint8_t val, halide_buffer_t *out) {
if (!out->is_bounds_query()) {
call_count_with_arg_parallel[out->dim[2].min]++;
Halide::Runtime::Buffer<uint8_t>(*out).fill(val);
}
return 0;
}
int call_count_staged[4];
extern "C" DLLEXPORT int count_calls_staged(int32_t stage, uint8_t val, halide_buffer_t *in, halide_buffer_t *out) {
if (in->is_bounds_query()) {
for (int i = 0; i < out->dimensions; i++) {
in->dim[i] = out->dim[i];
}
} else if (!out->is_bounds_query()) {
assert(stage < static_cast<int32_t>(sizeof(call_count_staged)/sizeof(call_count_staged[0])));
call_count_staged[stage]++;
Halide::Runtime::Buffer<uint8_t> out_buf(*out), in_buf(*in);
out_buf.for_each_value([&](uint8_t &out, uint8_t &in) {out = in + val;}, in_buf);
}
return 0;
}
void simple_free(void *user_context, void *ptr) {
free(ptr);
}
void *flakey_malloc(void * /* user_context */, size_t x) {
if ((rand() % 4) == 0) {
return nullptr;
} else {
return malloc(x);
}
}
bool error_occured = false;
void record_error(void *user_context, const char *msg) {
error_occured = true;
}
int main(int argc, char **argv) {
{
call_count = 0;
Func count_calls;
count_calls.define_extern("count_calls", {}, UInt(8), 2);
Func f, f_memoized;
f_memoized() = count_calls(0, 0);
f_memoized.compute_root().memoize();
f() = f_memoized();
f_memoized.compute_root().memoize();
Buffer<uint8_t> result1 = f.realize();
Buffer<uint8_t> result2 = f.realize();
assert(result1(0) == 42);
assert(result2(0) == 42);
assert(call_count == 1);
}
{
call_count = 0;
Param<int32_t> coord;
Func count_calls;
count_calls.define_extern("count_calls", {}, UInt(8), 2);
Func f, g;
Var x, y;
f() = count_calls(coord, coord);
f.compute_root().memoize();
g(x, y) = f();
coord.set(0);
Buffer<uint8_t> out1 = g.realize(256, 256);
Buffer<uint8_t> out2 = g.realize(256, 256);
for (int32_t i = 0; i < 256; i++) {
for (int32_t j = 0; j < 256; j++) {
assert(out1(i, j) == 42);
assert(out2(i, j) == 42);
}
}
assert(call_count == 1);
coord.set(1);
Buffer<uint8_t> out3 = g.realize(256, 256);
Buffer<uint8_t> out4 = g.realize(256, 256);
for (int32_t i = 0; i < 256; i++) {
for (int32_t j = 0; j < 256; j++) {
assert(out3(i, j) == 42);
assert(out4(i, j) == 42);
}
}
assert(call_count == 2);
}
{
call_count = 0;
Func count_calls;
count_calls.define_extern("count_calls", {}, UInt(8), 2);
Func f;
Var x, y;
f(x, y) = count_calls(x, y) + count_calls(x, y);
count_calls.compute_root().memoize();
Buffer<uint8_t> out1 = f.realize(256, 256);
Buffer<uint8_t> out2 = f.realize(256, 256);
for (int32_t i = 0; i < 256; i++) {
for (int32_t j = 0; j < 256; j++) {
assert(out1(i, j) == (42 + 42));
assert(out2(i, j) == (42 + 42));
}
}
assert(call_count == 1);
}
call_count = 0;
{
Func count_calls_23;
count_calls_23.define_extern("count_calls_with_arg", {cast<uint8_t>(23)}, UInt(8), 2);
Func count_calls_42;
count_calls_42.define_extern("count_calls_with_arg", {cast<uint8_t>(42)}, UInt(8), 2);
Func f;
Var x, y;
f(x, y) = count_calls_23(x, y) + count_calls_42(x, y);
count_calls_23.compute_root().memoize();
count_calls_42.compute_root().memoize();
Buffer<uint8_t> out1 = f.realize(256, 256);
Buffer<uint8_t> out2 = f.realize(256, 256);
for (int32_t i = 0; i < 256; i++) {
for (int32_t j = 0; j < 256; j++) {
assert(out1(i, j) == (23 + 42));
assert(out2(i, j) == (23 + 42));
}
}
assert(call_count_with_arg == 2);
}
{
Param<uint8_t> val1;
Param<uint8_t> val2;
call_count_with_arg = 0;
Func count_calls_val1;
count_calls_val1.define_extern("count_calls_with_arg", {val1}, UInt(8), 2);
Func count_calls_val2;
count_calls_val2.define_extern("count_calls_with_arg", {val2}, UInt(8), 2);
Func f;
Var x, y;
f(x, y) = count_calls_val1(x, y) + count_calls_val2(x, y);
count_calls_val1.compute_root().memoize();
count_calls_val2.compute_root().memoize();
val1.set(23);
val2.set(42);
Buffer<uint8_t> out1 = f.realize(256, 256);
Buffer<uint8_t> out2 = f.realize(256, 256);
val1.set(42);
Buffer<uint8_t> out3 = f.realize(256, 256);
val1.set(23);
Buffer<uint8_t> out4 = f.realize(256, 256);
val1.set(42);
Buffer<uint8_t> out5 = f.realize(256, 256);
val2.set(57);
Buffer<uint8_t> out6 = f.realize(256, 256);
for (int32_t i = 0; i < 256; i++) {
for (int32_t j = 0; j < 256; j++) {
assert(out1(i, j) == (23 + 42));
assert(out2(i, j) == (23 + 42));
assert(out3(i, j) == (42 + 42));
assert(out4(i, j) == (23 + 42));
assert(out5(i, j) == (42 + 42));
assert(out6(i, j) == (42 + 57));
}
}
assert(call_count_with_arg == 4);
}
{
Param<float> val;
call_count_with_arg = 0;
Func count_calls;
count_calls.define_extern("count_calls_with_arg", {cast<uint8_t>(val)}, UInt(8), 2);
Func f;
Var x, y;
f(x, y) = count_calls(x, y) + count_calls(x, y);
count_calls.compute_root().memoize();
val.set(23.0f);
Buffer<uint8_t> out1 = f.realize(256, 256);
val.set(23.4f);
Buffer<uint8_t> out2 = f.realize(256, 256);
for (int32_t i = 0; i < 256; i++) {
for (int32_t j = 0; j < 256; j++) {
assert(out1(i, j) == (23 + 23));
assert(out2(i, j) == (23 + 23));
}
}
assert(call_count_with_arg == 2);
}
{
Param<float> val;
call_count_with_arg = 0;
Func count_calls;
count_calls.define_extern("count_calls_with_arg", {memoize_tag(cast<uint8_t>(val))}, UInt(8), 2);
Func f;
Var x, y;
f(x, y) = count_calls(x, y) + count_calls(x, y);
count_calls.compute_root().memoize();
val.set(23.0f);
Buffer<uint8_t> out1 = f.realize(256, 256);
val.set(23.4f);
Buffer<uint8_t> out2 = f.realize(256, 256);
for (int32_t i = 0; i < 256; i++) {
for (int32_t j = 0; j < 256; j++) {
assert(out1(i, j) == (23 + 23));
assert(out2(i, j) == (23 + 23));
}
}
assert(call_count_with_arg == 1);
}
{
// Case with bounds computed not equal to bounds realized.
Param<float> val;
Param<int32_t> index;
call_count_with_arg = 0;
Func count_calls;
count_calls.define_extern("count_calls_with_arg", {cast<uint8_t>(val)}, UInt(8), 2);
Func f, g, h;
Var x;
f(x) = count_calls(x, 0) + cast<uint8_t>(x);
g(x) = f(x);
h(x) = g(4) + g(index);
f.compute_root().memoize();
g.vectorize(x, 8).compute_at(h, x);
val.set(23.0f);
index.set(2);
Buffer<uint8_t> out1 = h.realize(1);
assert(out1(0) == (uint8_t)(2 * 23 + 4 + 2));
assert(call_count_with_arg == 3);
index.set(4);
out1 = h.realize(1);
assert(out1(0) == (uint8_t)(2 * 23 + 4 + 4));
assert(call_count_with_arg == 4);
}
{
// Test Tuple case
Param<float> val;
call_count_with_arg = 0;
Func count_calls;
count_calls.define_extern("count_calls_with_arg", {cast<uint8_t>(val)}, UInt(8), 2);
Func f;
Var x, y, xi, yi;
f(x, y) = Tuple(count_calls(x, y) + cast<uint8_t>(x), x);
count_calls.compute_root().memoize();
f.compute_root().memoize();
Func g;
g(x, y) = Tuple(f(x, y)[0] + f(x - 1, y)[0] + f(x + 1, y)[0], f(x, y)[1]);
val.set(23.0f);
Realization out = g.realize(128, 128);
Buffer<uint8_t> out0 = out[0];
Buffer<int32_t> out1 = out[1];
for (int32_t i = 0; i < 100; i++) {
for (int32_t j = 0; j < 100; j++) {
assert(out0(i, j) == (uint8_t)(3 * 23 + i + (i - 1) + (i + 1)));
assert(out1(i, j) == i);
}
}
out = g.realize(128, 128);
out0 = out[0];
out1 = out[1];
for (int32_t i = 0; i < 100; i++) {
for (int32_t j = 0; j < 100; j++) {
assert(out0(i, j) == (uint8_t)(3 * 23 + i + (i - 1) + (i + 1)));
assert(out1(i, j) == i);
}
}
assert(call_count_with_arg == 1);
}
{
// Test cache eviction
Param<float> val;
call_count_with_arg = 0;
Func count_calls;
count_calls.define_extern("count_calls_with_arg", {cast<uint8_t>(val)}, UInt(8), 2);
Func f;
Var x, y, xi, yi;
f(x, y) = count_calls(x, y) + cast<uint8_t>(x);
count_calls.compute_root().memoize();
Func g;
g(x, y) = f(x, y) + f(x - 1, y) + f(x + 1, y);
Internal::JITSharedRuntime::memoization_cache_set_size(1000000);
for (int v = 0; v < 1000; v++) {
int r = rand() % 256;
val.set((float)r);
Buffer<uint8_t> out1 = g.realize(128, 128);
for (int32_t i = 0; i < 100; i++) {
for (int32_t j = 0; j < 100; j++) {
assert(out1(i, j) == (uint8_t)(3 * r + i + (i - 1) + (i + 1)));
}
}
}
// TODO work out an assertion on call count here.
fprintf(stderr, "Call count is %d.\n", call_count_with_arg);
// Return cache size to default.
Internal::JITSharedRuntime::memoization_cache_set_size(0);
}
{
// Test flushing entire cache with a single element larger than the cache
Param<float> val;
call_count_with_arg = 0;
Func count_calls;
count_calls.define_extern("count_calls_with_arg", {cast<uint8_t>(val)}, UInt(8), 2);
Func f;
Var x, y, xi, yi;
f(x, y) = count_calls(x, y) + cast<uint8_t>(x);
count_calls.compute_root().memoize();
Func g;
g(x, y) = f(x, y) + f(x - 1, y) + f(x + 1, y);
Internal::JITSharedRuntime::memoization_cache_set_size(1000000);
for (int v = 0; v < 1000; v++) {
int r = rand() % 256;
val.set((float)r);
Buffer<uint8_t> out1 = g.realize(128, 128);
for (int32_t i = 0; i < 100; i++) {
for (int32_t j = 0; j < 100; j++) {
assert(out1(i, j) == (uint8_t)(3 * r + i + (i - 1) + (i + 1)));
}
}
}
// TODO work out an assertion on call count here.
fprintf(stderr, "Call count before oversize realize is %d.\n", call_count_with_arg);
call_count_with_arg = 0;
Buffer<uint8_t> big = g.realize(1024, 1024);
Buffer<uint8_t> big2 = g.realize(1024, 1024);
// TODO work out an assertion on call count here.
fprintf(stderr, "Call count after oversize realize is %d.\n", call_count_with_arg);
call_count_with_arg = 0;
for (int v = 0; v < 1000; v++) {
int r = rand() % 256;
val.set((float)r);
Buffer<uint8_t> out1 = g.realize(128, 128);
for (int32_t i = 0; i < 100; i++) {
for (int32_t j = 0; j < 100; j++) {
assert(out1(i, j) == (uint8_t)(3 * r + i + (i - 1) + (i + 1)));
}
}
}
fprintf(stderr, "Call count is %d.\n", call_count_with_arg);
// Return cache size to default.
Internal::JITSharedRuntime::memoization_cache_set_size(0);
}
{
// Test parallel cache access
Param<float> val;
Func count_calls;
count_calls.define_extern("count_calls_with_arg_parallel", {cast<uint8_t>(val)}, UInt(8), 3);
Func f;
Var x, y;
// Ensure that all calls map to the same cache key, but pass a thread ID
// through to avoid having to do locking or an atomic add
f(x, y) = count_calls(x, y % 4, memoize_tag(y / 16, 0)) + cast<uint8_t>(x);
Func g;
g(x, y) = f(x, y) + f(x - 1, y) + f(x + 1, y);
count_calls.compute_at(f, y).memoize();
f.compute_at(g, y).memoize();
g.parallel(y, 16);
val.set(23.0f);
Internal::JITSharedRuntime::memoization_cache_set_size(1000000);
Buffer<uint8_t> out = g.realize(128, 128);
for (int32_t i = 0; i < 128; i++) {
for (int32_t j = 0; j < 128; j++) {
assert(out(i, j) == (uint8_t)(3 * 23 + i + (i - 1) + (i + 1)));
}
}
// TODO work out an assertion on call counts here.
for (int i = 0; i < 8; i++) {
fprintf(stderr, "Call count for thread %d is %d.\n", i, call_count_with_arg_parallel[i]);
}
// Return cache size to default.
Internal::JITSharedRuntime::memoization_cache_set_size(0);
}
{
Param<float> val;
Func f;
Var x, y;
f(x, y) = cast<uint8_t>((x << 8) + y);
Func prev_func = f;
Func stage[4];
for (int i = 0; i < 4; i++) {
std::vector<ExternFuncArgument> args(3);
args[0] = cast<int32_t>(i);
args[1] = cast<int32_t>(val);
args[2] = prev_func;
stage[i].define_extern("count_calls_staged",
args,
UInt(8), 2);
prev_func = stage[i];
}
f.compute_root();
for (int i = 0; i < 3; i++) {
stage[i].compute_root();
}
stage[3].compute_root().memoize();
Func output;
output(_) = stage[3](_);
val.set(23.0f);
Buffer<uint8_t> result = output.realize(128, 128);
for (int32_t i = 0; i < 128; i++) {
for (int32_t j = 0; j < 128; j++) {
assert(result(i, j) == (uint8_t)((i << 8) + j + 4 * 23));
}
}
for (int i = 0; i < 4; i++) {
fprintf(stderr, "Call count for stage %d is %d.\n", i, call_count_staged[i]);
}
result = output.realize(128, 128);
for (int32_t i = 0; i < 128; i++) {
for (int32_t j = 0; j < 128; j++) {
assert(result(i, j) == (uint8_t)((i << 8) + j + 4 * 23));
}
}
for (int i = 0; i < 4; i++) {
fprintf(stderr, "Call count for stage %d is %d.\n", i, call_count_staged[i]);
}
}
{
// Test out of memory handling.
Param<float> val;
Func count_calls;
count_calls.define_extern("count_calls_with_arg", {cast<uint8_t>(val)}, UInt(8), 2);
Func f;
Var x, y, xi, yi;
f(x, y) = Tuple(count_calls(x, y) + cast<uint8_t>(x), x);
count_calls.compute_root().memoize();
f.compute_root().memoize();
Func g;
g(x, y) = Tuple(f(x, y)[0] + f(x - 1, y)[0] + f(x + 1, y)[0], f(x, y)[1]);
Pipeline pipe(g);
pipe.set_error_handler(record_error);
pipe.set_custom_allocator(flakey_malloc, simple_free);
int total_errors = 0;
int completed = 0;
for (int trial = 0; trial < 100; trial++) {
call_count_with_arg = 0;
error_occured = false;
val.set(23.0f + trial);
Realization out = pipe.realize(16, 16);
if (error_occured) {
total_errors++;
} else {
Buffer<uint8_t> out0 = out[0];
Buffer<int32_t> out1 = out[1];
for (int32_t i = 0; i < 16; i++) {
for (int32_t j = 0; j < 16; j++) {
assert(out0(i, j) == (uint8_t)(3 * (23 + trial) + i + (i - 1) + (i + 1)));
assert(out1(i, j) == i);
}
}
error_occured = false;
out = pipe.realize(16, 16);
if (error_occured) {
total_errors++;
} else {
out0 = out[0];
out1 = out[1];
for (int32_t i = 0; i < 16; i++) {
for (int32_t j = 0; j < 16; j++) {
assert(out0(i, j) == (uint8_t)(3 * (23 + trial) + i + (i - 1) + (i + 1)));
assert(out1(i, j) == i);
}
}
assert(call_count_with_arg == 1);
completed++;
}
}
}
fprintf(stderr, "In 100 attempts with flakey malloc, %d errors and %d full completions occured.\n", total_errors, completed);
}
fprintf(stderr, "Success!\n");
return 0;
}
| true |
6b2b1f2089a25cbf150191503ddab51427aac04d | C++ | longkid/master-degree-thesis | /InternshipSRC/Nov.Tasks/Methods.cpp | UTF-8 | 2,232 | 3.109375 | 3 | [] | no_license | #include "Methods.hpp"
#define METHOD_COB 1
#define METHOD_COP 2
#define METHOD_FOB 3
/*
This method compute the value for each frame
*/
float
Methods::compute(const Mat &image, const AABBoxCollection &bboxes, int method)
{
float ret = 0;
int nbIntersectedBBox = 0; // used in method 1
int nbCountedPixel = 0; // used in method 2
float intersectedPercent = 0; // used in method 2
for (int i = 0; i < bboxes.size(); i++) {
AABBox bbox = bboxes[i];
switch (method) {
case METHOD_COB:
nbIntersectedBBox += compute1(image, bbox);
break;
case METHOD_COP:
nbCountedPixel = compute2(image, bbox);
intersectedPercent += nbCountedPixel / (float)(bbox.width() * bbox.height());
break;
case METHOD_FOB:
if (compute1(image, bbox) == 1)
return 1;
break;
default:
break;
}
}
switch (method) {
case METHOD_COB:
ret = nbIntersectedBBox / (float)bboxes.size();
break;
case METHOD_COP:
ret = intersectedPercent / (float)bboxes.size();
break;
default:
break;
}
return ret;
}
/*
* This method checks if a bounding box overlaps with saliency area.
* Parameters:
* - image: input image. This can be an eye-tracker map, an error map,
* or a combination of two maps
* - bbox: coordinate of bounding box
* Return value:
* 1: the bbox overlaps with saliency area inside the input image
* 0: otherwise
*/
int
Methods::compute1(const Mat &image, const AABBox &bbox)
{
for (int x = bbox.xMin(); x < bbox.xMax(); x++)
for (int y = bbox.yMin(); y < bbox.yMax(); y++)
if (image.at<unsigned char>(y, x) > 0)
return 1;
return 0;
}
/*
* This method counts the number of overlapped pixels.
* Parameters:
* - image: input image. This can be an eye-tracker map, an error map,
* or a combination of two maps
* - bbox: coordinate of bounding box
* Return value:
* The number of overlapped pixels
*/
int
Methods::compute2(const Mat &image, const AABBox &bbox)
{
int nbCountedPixel = 0;
for (int x = bbox.xMin(); x < bbox.xMax(); x++)
for (int y = bbox.yMin(); y < bbox.yMax(); y++)
if (image.at<unsigned char>(y, x) > 0)
nbCountedPixel++;
return nbCountedPixel;
}
| true |
0f043c7a806c2990d561ef9bc3704c3f94d71d83 | C++ | Maksim-Bozhko/TicTacToe_minimax | /noughtsAndCrosses/negamax/bitBoard.h | UTF-8 | 2,208 | 3.234375 | 3 | [] | no_license | #pragma once
namespace ticTacToe
{
// supposed to store bitboard of size up to 16
class BitBoard
{
using storageType = uint16_t;
public:
BitBoard() noexcept = default;
BitBoard(storageType bits) noexcept;
BitBoard& operator=(storageType bits) noexcept;
bool test(int pos) const noexcept;
int count() const noexcept;
void set(int pos) noexcept;
void reset(int pos) noexcept;
friend BitBoard operator&(const BitBoard& lhs, const BitBoard& rhs);
friend bool operator==(const BitBoard& lhs, const BitBoard& rhs);
storageType toInt() const noexcept;
private:
storageType _bits;
};
inline bool BitBoard::test(int pos) const noexcept
{
return _bits & (1u << pos);
}
inline void BitBoard::set(int pos) noexcept
{
_bits |= 1u << pos;
}
inline void BitBoard::reset(int pos) noexcept
{
_bits &= ~(1u << pos);
}
inline int BitBoard::count() const noexcept
{
static char table[256] = {
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 };
return table[_bits & 0xFFu] +
table[(_bits >> 8u) & 0xFFu]/* +
table[(_bits >> 16u) & 0xFFu] +
table[(_bits >> 24u)]*/;
}
inline BitBoard::storageType BitBoard::toInt() const noexcept
{
return _bits;
}
inline BitBoard operator&(const BitBoard& lhs, const BitBoard& rhs)
{
return lhs._bits & rhs._bits;
}
inline bool operator==(const BitBoard& lhs, const BitBoard& rhs)
{
return lhs._bits == rhs._bits;
}
}
| true |
3acd626592547365a83274de2c7c6154a42999ff | C++ | wh01683/syssoft | /WorkingSet.cpp | UTF-8 | 4,438 | 3.609375 | 4 | [] | no_license | #include "WSPage.cpp"
/**
@author: Robert Howerton
@description: This program is designed to demonstrate the working set page replacement algorithm.
@function: The working set algorithm employs a timer, a "working set" (hence the name), and a moving time window of fixed size T
the time window moves across the working set. If a particular page is not referenced for 4 iterations, that page's location
is automatically freed for use by another page.
--Moving Window :int value keeping track of the page window size
--wSet :char array keeping a working set of all characters in the current working set
*/
class WorkingSet {
private:
WSPage * WSTable;
int WSTableSize;
int t;
public:
#define MOVINGWINDOW = 4;
WorkingSet(int size) {
WSTableSize = size;
WSTable = new WSPage[size];
}
/**method to check for the requested page
//@param char: page to be checked for
//@return: true if found, false if not found
/
*/
bool checkForPage(char page) {
executor(); //initializes the executor method
int inc; //incrementer
for (int i = 0; i < WSTableSize; i++) {
if (WSTable[i].getName() == page) {
// cout << "Found page " << page << " at pos " << i << endl;
WSTable[i].use();
return true;
break;
}
}
for (inc = 0; inc < WSTableSize; inc++) {
if (WSTable[inc].isSet() != true) { //checks whether the page was set or not
// cout << "Empty page at " << inc << " adding page " << page << endl;
WSTable[inc].setName(page); //sets name of the page at the table's current index to the name of the page replacing it
WSTable[inc].use(); //sets new age for page at that location
return false;
break;
}
}
// cout << "Page fault looking for: " << page << endl;
//declares new index for oldest page, sets value using getOldest method
int tempIndex = getPageWithGreatestIterationsSinceLastReference();
WSTable[tempIndex].setName(page); //replaces oldest page with the needed page
// cout << "Added " << page << " to " << tempIndex << " : " << WSTable[tempIndex].getName() << endl;
WSTable[tempIndex].use(); //sets new age for page at that location
return false;
return 0;
}
/**
Method to cycle through the working set and delete old pages (outside time window 4)
this method will also maintain the working set. Ideally, this method will execute during the entirety of the program's runtime
@param void
@return void
*/
void executor(void) {
/** int t is the time window incrementer
* t will start at 0 and increment to 3 over time. once 3 is reached (4 total iterations), the entire WS Table is cycled through and all pages which
* are not set are deleted.*/
if (t == 3) {
t = 0;
/*If the target page is not marked AND not in the working set, delete it*/
for (int k = 0; k < WSTableSize; k++) {
if (!WSTable[k].isReffed() && findInWorkingSet(WSTable[k]) == false) WSTable[k].setName('\0');
}
}
else
t++;
}
/**
*method used to find target page in the working set
@param page to be looked for
@return boolean true if found, false if not found
*/
bool findInWorkingSet(WSPage page) {
for (int i = 0; i < WSTableSize; i++) {
if (WSTable[i].isInWS()) return true;
}
return false;
}
/**
*Finds the page with the greatest number of time iterations since the last reference. This is a condition on which
* to handle page faults. If a page fault occurs, the "preferred" page to be replaced is the one with the greatest
* number iterations since the last page reference
* @param void
* @return int: returns the index value of the page with the greatest number of iterations since last use*/
int getPageWithGreatestIterationsSinceLastReference(void){
int tempGreatestIndex = 0;
int tempGreatestIts = WSTable[0].getIts();
for (int i = 0; i < WSTableSize; i ++){
if (tempGreatestIts < WSTable[i].getIts()){
tempGreatestIndex = i;
tempGreatestIts = WSTable[i].getIts();
}
}
return tempGreatestIndex;
}
};
| true |
15847f48131f7b0b934eb69d90cae9e28fef0dea | C++ | yanleirex/cpp_concurrency | /1_thread_object/thread_object_main1.cpp | UTF-8 | 510 | 2.921875 | 3 | [] | no_license | //
// Created by yanlei on 16-9-20.
//
#include <boost/thread.hpp>
#include <unistd.h>
#include <sys/syscall.h>
#include <iostream>
using namespace std;
void show()
{
cout<<" Hello world "<<syscall(SYS_gettid)<<" "<<endl;;
}
int main()
{
boost::thread t(show);
cout<<"main pid "<<syscall(SYS_gettid)<<" "<<t.get_id()<<endl;
if(!t.joinable())
{
cout<<"thread unjoinable"<<endl;
}
else
{
cout<<"thread joinable"<<endl;
t.join();
}
return 0;
}
| true |
1211eb27c3e3a69ede5dfbbca6aa13aa548c76ba | C++ | yallawalla/H743 | /Cpp/Src/rtc.cpp | UTF-8 | 2,593 | 2.53125 | 3 | [] | no_license | /**
******************************************************************************
* @file spray.cpp
* @author Fotona d.d.
* @version
* @date
* @brief Timers initialization & ISR
*
*/
/** @addtogroup
* @{
*/
#include "rtc.h"
#include "misc.h"
#include "proc.h"
#include <string>
using namespace std;
/*******************************************************************************
* Function Name :
* Description :
* Output :
* Return : None
*******************************************************************************/
_RTC::_RTC() {
idx=0;
}
/*******************************************************************************
* Function Name :
* Description :
* Output :
* Return : None
*******************************************************************************/
_RTC::~_RTC() {
}
//_________________________________________________________________________________
void _RTC::Newline(void) {
io=_stdio(NULL);
_stdio(io);
if(io) {
HAL_RTC_GetTime(&hrtc,&time,RTC_FORMAT_BIN);
HAL_RTC_GetDate(&hrtc,&date,RTC_FORMAT_BIN);
_print("\r:time %4s,%3d-%3s-%3d,%3d::%02d::%02d",
Days[date.WeekDay-1],date.Date,Months[date.Month-1],date.Year,
time.Hours,time.Minutes,time.Seconds);
for(int i=1+4*(6-idx); i--; _print("\b"));
}
Repeat(1000,__CtrlR);
}
//_________________________________________________________________________________
int _RTC::Fkey(int t) {
switch(t) {
case __f9:
case __F9:
io=_stdio(NULL);
return __F12;
case __Up:
Increment(1,0);
break;
case __Down:
Increment(-1,0);
break;
case __Left:
Increment(0,-1);
break;
case __Right:
Increment(0,1);
break;
case __CtrlR:
Increment(0,0);
break;
}
return EOF;
}
/*******************************************************************************/
/**
* @brief TIM3 IC2 ISR
* @param : None
* @retval : None
*/
/*******************************************************************************/
void _RTC::Increment(int a, int b) {
idx= std::min(std::max(idx+b,0),6);
switch(idx) {
case 0:
date.WeekDay+=a;
break;
case 1:
date.Date+=a;
break;
case 2:
date.Month+=a;
break;
case 3:
date.Year+=a;
break;
case 4:
time.Hours+=a;
break;
case 5:
time.Minutes+=a;
break;
case 6:
time.Seconds+=a;
break;
}
if(a) {
HAL_RTC_SetTime(&hrtc,&time,RTC_FORMAT_BIN);
HAL_RTC_SetDate(&hrtc,&date,RTC_FORMAT_BIN);
}
Newline();
}
| true |
73eaf588dddfa136bdd324e3a94eae61d5eb7c48 | C++ | taktaivan/ALL_THIS... | /funofstack.cpp | UTF-8 | 667 | 3.546875 | 4 | [] | no_license | #include "ClassStack.h"
#include <iostream>
using namespace std;
void Stack::push(int new_data) {
node_s* node = new node_s;
node->data = new_data;
node->prev = top;
top = node;
size++;
}
int Stack::pop() {
if (size == 0) {
cout << "The stack is empty" << endl;
return -1;
}
else {
int save_data = top->data;
node_s* p = new node_s;
p = top;
top = top->prev;
delete p;
size--;
return save_data;
}
}
void Stack::print() {
node_s* p = new node_s;
p = top;
while (p) {
cout << p->data << endl;
p = p->prev;
}
}
bool Stack::empty() {
if (size == 0)
return true;
else
return false;
} | true |
3bb3486ecd4f77b071764da456db3b1d530f87be | C++ | bennbollay/Transport | /transport/Includes/CCVector.h | UTF-8 | 1,092 | 2.890625 | 3 | [] | no_license | #ifndef INCL_CCVECTOR
#define INCL_CCVECTOR
// This is an array of 32-bit integers
class CCVector : public ICCList
{
public:
CCVector (void);
CCVector (CCodeChain *pCC);
virtual ~CCVector (void);
int *GetArray (void);
BOOL SetElement (int iIndex, int iElement);
ICCItem *SetSize (CCodeChain *pCC, int iNewSize);
// ICCItem virtuals
virtual ICCItem *Clone (CCodeChain *pCC);
virtual ICCItem *Enum (CEvalContext *pCtx, ICCItem *pCode);
virtual int GetCount (void) { return m_iCount; }
virtual ICCItem *GetElement (int iIndex);
virtual ICCItem *Head (CCodeChain *pCC) { return GetElement(0); }
virtual CString Print (CCodeChain *pCC);
virtual ICCItem *Tail (CCodeChain *pCC);
virtual void Reset (void);
protected:
virtual void DestroyItem (CCodeChain *pCC);
virtual ICCItem *StreamItem (CCodeChain *pCC, IWriteStream *pStream);
virtual ICCItem *UnstreamItem (CCodeChain *pCC, IReadStream *pStream);
private:
CCodeChain *m_pCC; // CodeChain
int m_iCount; // Number of elements
int *m_pData; // Array of elements
};
#endif
| true |
2e81b547f92a44dd8e823222865e3d66de3a4718 | C++ | sbremner/BigNSL | /IPCidr.h | UTF-8 | 1,473 | 2.984375 | 3 | [] | no_license | /*
Author: Steven Bremner
Date: June 3, 2014
Description:
Library for parsing IP addr from CIDR to IP + mask
*/
#ifndef IPCIDR_H
#define IPCIDR_H
#include "includes.h"
typedef struct _IPCidr{
unsigned int IPaddr;
unsigned int range;
_IPCidr() : IPaddr(0), range(0) { }
inline bool InRange(unsigned int _ip) {
unsigned int netmask = ~(~(unsigned int(0)) >> range);
return (_ip & netmask) == (IPaddr & netmask);
}
} IPCidr;
std::string IntIPToString(unsigned int _ip)
{
//xxx.xxx.xxx.xxx\0 (max shuold be 16 characters including null)
char buf[256];
sprintf(buf, "%u.%u.%u.%u", (_ip >> 24) & 0xFF, (_ip >> 16) & 0xFF, (_ip >> 8) & 0xFF, _ip & 0xFF);
return std::string(buf);
}
IPCidr getCIDR(std::string _cidrStr)
{
IPCidr _cidr;
unsigned int octet[4];
if(sscanf(_cidrStr.c_str(), "%d.%d.%d.%d/%d", &octet[0], &octet[1], &octet[2], &octet[3], &_cidr.range) != 5)
{
//we didn't scan all 5... must have a scanning error
#ifdef DEBUG
printf("[DEBUG] :: %s", "Error - CIDR notation was provided incorrectly");
#endif
exit(-1);
}
//Put the IP octets into the int
_cidr.IPaddr |= (octet[0] << 24);
_cidr.IPaddr |= (octet[1] << 16);
_cidr.IPaddr |= (octet[2] << 8);
_cidr.IPaddr |= octet[3];
if(_cidr.range < 0 || _cidr.range > 31)
{
return _IPCidr(); //just return an empty CIDR IP if the input is bad
}
return _cidr; //this is the address we built
}
#endif | true |
ea606c9df170b674257e57ff2a74bea05f8f09f2 | C++ | abutlerboudakian/future_wallet | /Application/Application/Requests.cpp | UTF-8 | 18,834 | 2.765625 | 3 | [] | no_license | #include "Requests.h"
Requests::Requests(QObject * parent, bool debug) : QObject(parent)
{
this->debug = debug;
if (debug)
{
Location = "http://127.0.0.1:5000";
}
}
// -----------------------------------------------------
// Inputs |
// -----------------------------------------------------
/* Function to send user inputs to run the
* model on for an income prediction
* @param data is a QJsonObject from all three input forms
* @modifies this->Data
* @effect this->Data contains the QByteArray representatin of the server's response
* @returns a vector matching Controller->metrics
*/
std::vector<double> * Requests::getPrediction(QString userId, QJsonObject Wages, QJsonObject Invest, QJsonObject Assets, int years)
{
// Endpoint
QUrl url = QUrl(Location + QString("/submitInputs"));
// Header
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
// Set request and callbacks
QNetworkAccessManager * mgr = new QNetworkAccessManager(this);
connect(mgr,SIGNAL(finished(QNetworkReply*)),this,SLOT(readData(QNetworkReply*)));
// Body
QJsonObject body;
body.insert("userid", userId);
body.insert("wages", Wages);
body.insert("invests", Invest);
body.insert("assets", Assets);
body.insert("years", years);
// Send request
QNetworkReply * reply = mgr->post(request, QJsonDocument(body).toJson());
// Make it syncrhonous so we can process it here
QEventLoop MakeSync;
connect(mgr,SIGNAL(finished(QNetworkReply*)),&MakeSync,SLOT(quit()));
MakeSync.exec();
// Assume it is already an object
int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
reply->close();
reply->deleteLater();
std::vector<double> * metric = new std::vector<double>;
// Process The Returns
if (statusCode == 200)
{ // Success
QJsonDocument jDoc = QJsonDocument::fromJson(Data);
QJsonObject result = (jDoc.isArray() ? jDoc[0].toObject() : jDoc.object());
metric->push_back(result["wages"].toDouble());
metric->push_back(result["invests"].toDouble());
metric->push_back(result["assets"].toDouble());
metric->push_back(result["years"].toInt());
}
return metric;
}
/* Function to get the user's most recent inputs
* @param userid is the userid of the currently logged in user
* @modifies this->Data
* @effect this->Data contains the QByteArray representation of the returned user inputs,
* or an error if it failed to retrieve it
* @returns a QJsonObject of the input data
* or {"error":1} on error
*/
QJsonObject Requests::getInputs(QString userid)
{
// Endpoint
QUrl url(Location + QString("/getInputs") + QString("?userid=") + userid);
// Header
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
// Set request and callbacks
QNetworkAccessManager * mgr = new QNetworkAccessManager(this);
connect(mgr,SIGNAL(finished(QNetworkReply*)),this,SLOT(readData(QNetworkReply*)));
// Send request
QNetworkReply * reply = mgr->get(request);
// Make it syncrhonous so we can process it here
QEventLoop MakeSync;
connect(mgr,SIGNAL(finished(QNetworkReply*)),&MakeSync,SLOT(quit()));
MakeSync.exec();
int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
reply->close();
reply->deleteLater();
// Process the Returns
if (statusCode == 200)
{
QJsonDocument jDoc = QJsonDocument::fromJson(Data);
QJsonObject res = (jDoc.isArray() ? jDoc[0].toObject() : jDoc.object());
return res;
}
else
{
QJsonObject res;
res.insert("error", 1);
return res;
}
}
// -----------------------------------------------------
// Budgets |
// -----------------------------------------------------
/* Function to add a user created budget to the database
* @param budget is the BudgetData we plan to submit
* @param userid is the userid we plan to add the budget to
* @modifies this->Data
* @effect this->Data contains the QByteArray representatin of the server's response
* @returns true if the budget was added, false otherwise
*/
bool Requests::addBudget(BudgetData * budget, QString userid)
{
// Endpoint
QUrl url(Location + QString("/submitBudget"));
// Header
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
// Body
QJsonObject body, categories;
body.insert("userid", userid);
body.insert("budgetid", budget->getName());
const ChartMap * cats = budget->getBudgetChartMap();
for (ChartMap::const_iterator i = cats->begin(); i != cats->end(); i++)
{ // Add each category
categories.insert(QString::fromStdString(std::string(i->first)), i->second);
}
body.insert("categories", categories);
// Set request and callbacks
QNetworkAccessManager * mgr = new QNetworkAccessManager(this);
connect(mgr,SIGNAL(finished(QNetworkReply*)),this,SLOT(readData(QNetworkReply*)));
// Send request
QNetworkReply * reply = mgr->post(request, QJsonDocument(body).toJson());
// Make it syncrhonous so we can process it here
QEventLoop MakeSync;
connect(mgr,SIGNAL(finished(QNetworkReply*)),&MakeSync,SLOT(quit()));
MakeSync.exec();
// Process the returns
int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
reply->close();
reply->deleteLater();
if (statusCode == 200)
{
return true;
}
else
{
return false;
}
}
/* Function to get budget information on a user specific budget
* @param budgetId is the name of the budget to get
* @param userId is the user whose budget we are getting
* @modifies this->Data
* @effect this->Data contains the QByteArray representatin of the server's response
* @returns BugdetData() if it failed to get the budget data
* or the BudgetData representation of the budget on successful retrieval
*/
BudgetData * Requests::loadBudget(QString budgetId, QString userId)
{
// Endpoint
QUrl url(Location + QString("/getBudget?userid=") + userId + QString("&budgetid=") + budgetId);
// Header
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
// Set request and callbacks
QNetworkAccessManager * mgr = new QNetworkAccessManager(this);
connect(mgr,SIGNAL(finished(QNetworkReply*)),this,SLOT(readData(QNetworkReply*)));
// Send request
QNetworkReply * reply = mgr->get(request);
// Make it syncrhonous so we can process it here
QEventLoop MakeSync;
connect(mgr,SIGNAL(finished(QNetworkReply*)),&MakeSync,SLOT(quit()));
MakeSync.exec();
// Process the returns
int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
reply->close();
reply->deleteLater();
BudgetData * budget = new BudgetData;
if (statusCode == 200)
{
QJsonDocument jDoc = QJsonDocument::fromJson(Data);
QJsonObject result = (jDoc.isArray() ? jDoc[0].toObject() : jDoc.object());
budget->setName(result["name"].toString());
QJsonObject categories = result["categories"].toObject();
for (int i = 0; i < categories.keys().size(); i++)
{
QString key = categories.keys()[i];
budget->addCategory(key, categories.value(key).toDouble());
}
}
return budget;
}
/* Function to get a list of budget names the user created
* @param userId is the userid of the currently logged in user
* @modifies this->Data
* @effect this->Data contains the QByteArray representatin of the server's response
* @returns (true, a list of budget names) if successful
* (false, empty) if an error occurred.
*/
std::pair<bool, QStringList> Requests::listBudgets(QString userId)
{
// Endpoint
QUrl url(Location + QString("/getAllBudgets?userid=") + userId);
// Header
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
// Set request and callbacks
QNetworkAccessManager * mgr = new QNetworkAccessManager(this);
connect(mgr,SIGNAL(finished(QNetworkReply*)),this,SLOT(readData(QNetworkReply*)));
// Send request
QNetworkReply * reply = mgr->get(request);
// Make it syncrhonous so we can process it here
QEventLoop MakeSync;
connect(mgr,SIGNAL(finished(QNetworkReply*)),&MakeSync,SLOT(quit()));
MakeSync.exec();
// Process the returns
int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
reply->close();
reply->deleteLater();
std::pair<bool, QStringList> res;
res.first = false;
if (statusCode == 200)
{
res.first = true;
QJsonDocument jDoc = QJsonDocument::fromJson(Data);
QJsonObject result = (jDoc.isArray() ? jDoc[0].toObject() : jDoc.object());
QJsonArray names = result["budgets"].toArray();
for (int i = 0; i < names.size(); i++)
{
res.second.push_back(names[i].toString());
}
}
return res;
}
// -----------------------------------------------------
// Auth |
// -----------------------------------------------------
/* Function to login a user and get their oauth
* @param userId is the username of the person trying to log in
* @param Password is the raw password of the person trying to log in
* @modifies this->Data
* @effect this->Data contains the QByteArray representatin of the server's response
* @returns true if the user credentials match, false otherwise
*/
bool Requests::login(QString userId, QString Password)
{
// Endpoint
QUrl url(Location + QString("/login"));
// Header
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
//HTTP Basic authentication
QString head = userId + ":" + QString(QCryptographicHash::hash(Password.toLocal8Bit(), QCryptographicHash::Md5).toHex());
QByteArray data = head.toLocal8Bit().toBase64();
QString auth = "Basic " + data;
request.setRawHeader("Authorization", auth.toLocal8Bit());
// Set request and callbacks
QNetworkAccessManager * mgr = new QNetworkAccessManager(this);
connect(mgr,SIGNAL(finished(QNetworkReply*)),this,SLOT(readData(QNetworkReply*)));
// Send request
QNetworkReply * reply = mgr->post(request, "{}");
// Make it syncrhonous so we can process it here
QEventLoop MakeSync;
connect(mgr,SIGNAL(finished(QNetworkReply*)),&MakeSync,SLOT(quit()));
MakeSync.exec();
// Process the returns
int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
reply->close();
reply->deleteLater();
if (statusCode == 200)
{
return true;
}
else
{
return false;
}
}
/* Function for user to log out -- call this when app closes too
* @param userId is the id of the currently logged in user
* @modifies this->Data
* @effect this->Data contains the QByteArray representatin of the server's response
*/
void Requests::logout(QString userId)
{
// Endpoint
QUrl url(Location + QString("/logout"));
// Header
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
// Body
QJsonObject body;
body.insert("userid", userId);
// Set request and callbacks
QNetworkAccessManager * mgr = new QNetworkAccessManager(this);
connect(mgr,SIGNAL(finished(QNetworkReply*)),this,SLOT(readData(QNetworkReply*)));
// Send request
QNetworkReply * reply = mgr->post(request, QJsonDocument(body).toJson());
// Make it syncrhonous so we can process it here
QEventLoop MakeSync;
connect(mgr,SIGNAL(finished(QNetworkReply*)),&MakeSync,SLOT(quit()));
MakeSync.exec();
reply->close();
reply->deleteLater();
return;
}
/* Function to POST registration information to the database
* @param userId is the username
* @param password is the user password
* @modifies this->Data
* @effect this->Data contains the QByteArray representatin of the server's response
* @returns true if the user was created
* false otherwise
*/
bool Requests::Register(QString UserId, QString Password)
{
// Endpoint
QUrl url(Location + QString("/register"));
// Header
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
// Body
QJsonObject body;
body.insert("userid", UserId);
body.insert("password", QString(QCryptographicHash::hash(Password.toLocal8Bit(), QCryptographicHash::Md5).toHex()));
// Set request and callbacks
QNetworkAccessManager * mgr = new QNetworkAccessManager(this);
connect(mgr,SIGNAL(finished(QNetworkReply*)),this,SLOT(readData(QNetworkReply*)));
// Send request
QNetworkReply * reply = mgr->post(request, QJsonDocument(body).toJson());
// Make it syncrhonous so we can process it here
QEventLoop MakeSync;
connect(mgr,SIGNAL(finished(QNetworkReply*)),&MakeSync,SLOT(quit()));
MakeSync.exec();
// Process the returns
int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
reply->close();
reply->deleteLater();
if (statusCode == 200)
{
return true;
}
else
{
return false;
}
}
/* Function used to update the account information
* @param OriginalUserId is the original user id/email
* @param userId is the new email (keep it "" if it is not to be updated)
* @param Password is the new password (keep it "" if it is not to be updated)
* @modifies database user credentials
* @modifies this->Data
* @effects database user crecentials
* @effect this->Data contains the QByteArray representatin of the server's response
*/
bool Requests::UpdateUserInfo(QString OriginalUserId, QString userId, QString Password)
{
// Endpoint
QUrl url(Location + QString("/update"));
// Header
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
// Body
QJsonObject body;
body.insert("userid", OriginalUserId);
QJsonObject updates;
if (userId != QString(""))
{
updates.insert("userid", userId);
}
if (Password != QString(""))
{
updates.insert("password", QString(QCryptographicHash::hash(Password.toLocal8Bit(), QCryptographicHash::Md5).toHex()));
}
body.insert("updates", updates);
// Set request and callbacks
QNetworkAccessManager * mgr = new QNetworkAccessManager(this);
connect(mgr,SIGNAL(finished(QNetworkReply*)),this,SLOT(readData(QNetworkReply*)));
// Send request
QNetworkReply * reply = mgr->post(request, QJsonDocument(body).toJson());
// Make it syncrhonous so we can process it here
QEventLoop MakeSync;
connect(mgr,SIGNAL(finished(QNetworkReply*)),&MakeSync,SLOT(quit()));
MakeSync.exec();
// Process the returns
int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
reply->close();
reply->deleteLater();
if (statusCode == 200)
{
return true;
}
else
{
return false;
}
}
// -----------------------------------------------------
// Aux |
// -----------------------------------------------------
/* Function to get a list of all industries for the combo box
* @modifies this->Data
* @effect this->Data contains the QByteArray representatin of the server's response
* @returns a QStringList of industry codes
*/
QStringList Requests::getIndustries()
{
// Endpoint
QUrl url(Location + QString("/getIndustries"));
// Header
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
// Set request and callbacks
QNetworkAccessManager * mgr = new QNetworkAccessManager(this);
connect(mgr,SIGNAL(finished(QNetworkReply*)),this,SLOT(readData(QNetworkReply*)));
// Send request
QNetworkReply * reply = mgr->get(request);
// Make it syncrhonous so we can process it here
QEventLoop MakeSync;
connect(mgr,SIGNAL(finished(QNetworkReply*)),&MakeSync,SLOT(quit()));
MakeSync.exec();
// Process the returns
int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
reply->close();
reply->deleteLater();
QStringList Industries;
if (statusCode == 200)
{
QJsonDocument jDoc = QJsonDocument::fromJson(Data);
QJsonObject result = (jDoc.isArray() ? jDoc[0].toObject() : jDoc.object());
QJsonArray names = result["industries"].toArray();
for (int i = 0; i < names.size(); i++)
{
Industries.push_back(names[i].toString());
}
}
return Industries;
}
/* Function to get a list of all stock tickers for the combo box
* @modifies this->Data
* @effect this->Data contains the QByteArray representatin of the server's response
* @returns a QStringList of stock tickers
*/
QStringList Requests::getStocks()
{
// Endpoint
QUrl url(Location + QString("/getTickers"));
// Header
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
// Set request and callbacks
QNetworkAccessManager * mgr = new QNetworkAccessManager(this);
connect(mgr,SIGNAL(finished(QNetworkReply*)),this,SLOT(readData(QNetworkReply*)));
// Send request
QNetworkReply * reply = mgr->get(request);
// Make it syncrhonous so we can process it here
QEventLoop MakeSync;
connect(mgr,SIGNAL(finished(QNetworkReply*)),&MakeSync,SLOT(quit()));
MakeSync.exec();
// Process the returns
int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
reply->close();
reply->deleteLater();
QStringList Tickers;
if (statusCode == 200)
{
QJsonDocument jDoc = QJsonDocument::fromJson(Data);
QJsonObject result = (jDoc.isArray() ? jDoc[0].toObject() : jDoc.object());
QJsonArray names = result["tickers"].toArray();
for (int i = 0; i < names.size(); i++)
{
Tickers.push_back(names[i].toString());
}
}
return Tickers;
}
// Slot function to set this->Data to the repsonse data
void Requests::readData(QNetworkReply *reply)
{
Data = reply->readAll();
}
| true |
52a05b1feaaa8940c80dde92902fc9166f6a4756 | C++ | mashavorob/lfds | /include/xtomic/aux/cppbasics.hpp | UTF-8 | 3,098 | 2.84375 | 3 | [
"ISC"
] | permissive | /*
* cppbasics.hpp
*
* Created on: Mar 31, 2015
* Author: masha
*/
///
/// @file cppbasics.hpp
///
/// @brief Basic C++ macros for compatibility with C++98.
///
/// The file implements helper macro definitions including ones to mimic such great thing from
/// C++11 like variadic template arguments in C++98. Certainly these macros do not extend C++98
/// but allow you to spend less effort writing portable code.
///
#ifndef INCLUDE_CPPBASICS_HPP_
#define INCLUDE_CPPBASICS_HPP_
/// @cond HIDDEN_SYMBOLS
#include <xtomic/config.hpp>
/// @endcond
///
/// @defgroup cpp11_specifics C++11 Specifics
///
/// @brief Uniform using of C++11 specific directives when C++98 is used.
///
/// Macro definitions that provide uniform using for new C++11 features:
/// - `std::forward<>()`, `std::move()`
/// - alignment directives
///
/// Macro-definitions provide compatibility with Eclipse CDT Luna (it seems the IDE has troubles with
/// support `alignas` directive).
///
/// @{
#if XTOMIC_USE_CPP11
/// @cond HIDDEN_SYMBOLS
#define _std_forward_impl(ARGS, args) std::forward<ARGS>(args)...
#define _std_move_impl(v) std::move(v)
/// @endcond
#else
/// @cond HIDDEN_SYMBOLS
#define _std_forward_impl(ARGS, args) args
#define _std_move_impl(v) v
/// @endcond
#define nullptr 0 ///< defines `nullptr` when C++98 is used.
#define constexpr const ///< defines `constexpr` when C++98 is used.
#endif // XTOMIC_USE_CPP11
///
/// @brief Mimics std::forward<>() when C++98 is used.
///
/// Example:
///
/// @code
/// #if C++11
/// template<typename ... Args>
/// bool insert(const key_type & key, Args&&... val)
/// #else
/// bool insert(const key_type & key, const mapped_type& val)
/// #endif
/// {
/// return m_hash_table_base.insert(key, false, std_forward(Args, val));
/// }
/// @endcode
///
/// When C++11 is used then the codesnipet will expand to:
///
/// @code
/// template<typename ... Args>
/// bool insert(const key_type & key, Args&&... val)
/// {
/// return m_hash_table_base.insert(key, false, std::forward<Args>(val)...);
/// }
/// @endcode
///
/// and when C++98:
///
/// @code
/// bool insert(const key_type & key, const mapped_type& val)
/// {
/// return m_hash_table_base.insert(key, false, val);
/// }
/// @endcode
///
#define std_forward(ARGS, args) _std_forward_impl(ARGS, args)
///
/// @def std_move(v)
///
/// @brief Mimics std::move() when C++98 is used.
///
/// Example:
///
/// @code
/// class Foo
/// {
/// public:
/// #if C++11
/// Foo(Foo&& other);
/// #else
/// Foo(Foo& other);
/// #endif
/// ...
/// };
///
/// ...
/// Foo dummy( std_move(other) );
/// ...
/// @endcode
///
#define std_move(v) _std_move_impl(v)
/// @brief Mimics C++11 alignas( expression ) form.
#define align_by(size) __attribute__((aligned((size))))
/// @brief Mimics C++11 alignas( type-id ) form.
#define align_as(type) __attribute__((aligned(__alignof(type))))
/// @brief Shortcut to declare alignment for 16-bytes CAS operation (8-byte CAS on 32 bit platform)
#define align_4_cas16 align_by(sizeof(void*)*2)
/// @}
#endif /* INCLUDE_CPPBASICS_HPP_ */
| true |
ac3d9a365996a80a5759c50fa002b3f716496850 | C++ | Jmiller7023/Xenro-Engine | /Demo/Actor.h | UTF-8 | 1,689 | 2.609375 | 3 | [
"MIT"
] | permissive | #ifndef ACTOR_DEFINED
#define ACTOR_DEFINED
#include <vector>
#include <glm\glm.hpp>
#include <XenroEngine\SpriteBatch.h>
#include <string>
#include <XenroEngine\SpriteSheet.h>
#include <XenroEngine\GLTexture.h>
#include <XenroEngine\Globals.h>
#include <XenroEngine\Vertex.h>
#include <Box2D/Box2D.h>
enum class MoveDir {
UP, DOWN, LEFT, RIGHT, UPRIGHT, UPLEFT, DOWNRIGHT, DOWNLEFT, IDLE
};
class Actor
{
public:
Actor();
~Actor();
virtual void update(const std::vector<std::string>& WorldData) { }
virtual void update() { }
void draw(Xenro::SpriteBatch& spriteBatch);
void initializeActor(std::string filePath, Xenro::ColorRGBA color, glm::ivec2 SpriteSheetDims, glm::vec2 Position, glm::vec2 drawDims, glm::vec2 HitboxDims);
virtual void collideWithWorld(const std::vector<std::string>& worldData);
//Getters
glm::vec2 getPos() const {return m_position; }
glm::vec2 getDrawDims() const { return m_drawDims; }
glm::vec2 getHboxDims() const { return m_HitboxDims; }
glm::vec2 getDirection() const;
//temp
void setScale(glm::vec2 scale) { m_scale = scale; }
protected:
void checkTilePos(const std::vector<std::string>& levelData, std::vector<glm::vec2>& tilecollisions, float x, float y);
void collideWithTile(glm::vec2 tilePos);
int m_frameIndex;
void setFrameIndex(int i) { m_frameIndex = i; }
void setMoveDir(MoveDir dir) { m_moveDir = dir; }
b2Body* m_body = nullptr;
glm::vec2 m_position;
glm::vec2 m_direction = glm::vec2(1.0f, 0.0f);
Xenro::ColorRGBA m_color;
float m_speed;
Xenro::SpriteSheet m_spriteSheet;
glm::vec2 m_drawDims;
glm::vec2 m_HitboxDims;
glm::vec2 m_scale;
MoveDir m_moveDir = MoveDir::IDLE;
};
#endif //ACTOR_DEFINED | true |
1c28b6a06e4f0f6c9674d66124a8a28931b24d3b | C++ | lfdversluis/opendc-simulator | /Simulator/include/simulation/schedulers/Scheduler.h | UTF-8 | 404 | 2.671875 | 3 | [
"MIT"
] | permissive | #pragma once
#include "modeling/machine/Machine.h"
#include <vector>
namespace Simulation
{
/*
Provides a strategy for load balancing.
*/
class Scheduler
{
public:
virtual ~Scheduler()
{
}
/*
Divides the workloads over the given machines.
*/
virtual void schedule(std::vector<std::reference_wrapper<Modeling::Machine>>& machines, std::vector<Workload*> workloads) = 0;
};
}
| true |
2de91d2e6a7b3dc15e7c753a13b44b99f2bae00f | C++ | mmshaifur/Seeed_Learning_Space | /Seeed_Creator_Kit/3.Vibration Motor/1_vibration_motor/1_vibration_motor.ino | UTF-8 | 333 | 2.859375 | 3 | [
"MIT"
] | permissive |
int MoPin = 2; // vibrator Grove connected to digital pin 2
void setup() {
pinMode( MoPin, OUTPUT );
}
void loop() {
digitalWrite(MoPin, HIGH); //Turn on the vibration motor
delay(1000); //Delay for 1 second
digitalWrite(MoPin, LOW); //Turn off the vibration motor
delay(1000); //Delay for 1 second
}
| true |
3d64727d90c1562b9b88c1932a3166776d580a97 | C++ | scripter01/common | /Common/Common/utils.cpp | UTF-8 | 724 | 2.8125 | 3 | [] | no_license | #include "stdafx.h"
#include "utils.h"
int hexToInt(uint8_t* p)
{
if (p[0] >= '0' && p[0] <= '9')
return int(p[0] - '0');
if (p[0] >= 'a' && p[0] <= 'f')
return int(p[0] - 'a') + 10;
if (p[0] >= 'A' && p[0] <= 'F')
return int(p[0] - 'A') + 10;
return 0;
}
vector4 strToVec4(const std::string& color)
{
assert(color.length() >= 6 && color.length() <= 8);
uint8_t* p = (uint8_t*)color.c_str();
int r = hexToInt(p + 0) * 16 + hexToInt(p + 1);
int g = hexToInt(p + 2) * 16 + hexToInt(p + 3);
int b = hexToInt(p + 4) * 16 + hexToInt(p + 5);
int a = 0;
if (color.length() >= 8)
a = hexToInt(p + 6) * 16 + hexToInt(p + 7);
return vector4(float(r)/256.0f, float(g)/256.0f, float(b)/256.0f, float(a)/256.0f);
}
| true |
9bf13a3ea40f9781d1508778c8f59c4366edee80 | C++ | NickChapman/RuM | /Type.h | UTF-8 | 2,402 | 3.4375 | 3 | [] | no_license | //
// Created by Nick Chapman on 11/20/16.
//
#ifndef RUM_TYPE_H
#define RUM_TYPE_H
#include <string>
template<class T>
class Type {
std::string identifier;
std::string type;
T value;
public:
Type() {
identifier = "";
type = "";
};
Type(std::string type, T value) {
this->type = type;
this->value = value;
}
~Type() {}
std::string getType() const {
return this->type;
}
void setType(std::string type) {
this->type = type;
}
void setValue(T value) {
this->value = value;
}
T getValue() const {
return this->value;
}
Type<T>* getDeepCopy() {
return new Type<T>(this->getType(), this->getValue());
}
};
struct TypeStruct {
union type_union {
Type<int> *intType;
Type<float> *floatType;
Type<std::string> *stringType;
Type<bool> *boolType;
type_union() {
intType = nullptr;
}
~type_union() {
delete intType;
}
};
type_union typeUnion;
char activeType;
TypeStruct() {
typeUnion = type_union();
activeType = 'N';
}
TypeStruct(std::shared_ptr<TypeStruct> other) {
this->activeType = other->activeType;
this->typeUnion = type_union();
switch (this->activeType) {
case 'I':
this->typeUnion.intType = other->typeUnion.intType->getDeepCopy();
break;
case 'F':
this->typeUnion.floatType = other->typeUnion.floatType->getDeepCopy();
break;
case 'B':
this->typeUnion.boolType = other->typeUnion.boolType->getDeepCopy();
break;
case 'S':
this->typeUnion.stringType = other->typeUnion.stringType->getDeepCopy();
break;
default:
this->typeUnion.intType = nullptr;
}
}
const std::string activeTypeAsString() const {
switch(this->activeType) {
case 'I':
return "integer";
case 'F':
return "float";
case 'B':
return "boolean";
case 'S':
return "string";
default:
return "nullptr";
}
}
~TypeStruct() {}
};
#endif //RUM_TYPE_H
| true |
f877c97984a9c0736fb6e67f80ee18bdca39339e | C++ | balannarcis96/skylake-tools | /Crypt/Byte_Block.hpp | UTF-8 | 13,433 | 3.0625 | 3 | [
"MIT"
] | permissive | /*
* Copyright (C) 2014 Jens Thoms Toerring
*
* This file is part of AES256.
*
* AES256 is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* AES256 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#if ! defined Byte_Block_hpp_
#define Byte_Block_hpp_
// The whole thing only works on machines where a char has 8 bits,
// so make sure it's already detected at compile time when that's
// not the case!
#include <climits>
#if CHAR_BIT != 8
#error "CHAR_BIT isn't 8 which is required for the Byte_Block class"
#endif
#include "Padding_Type.hpp"
#include <algorithm>
#include <string>
#include <stdexcept>
#include <cstring>
#include <iostream>
#include <iomanip>
#include <ios>
/*---------------------------------------------*
* Utility class for dealing with blocks of fixed numbers of bytes
* (the template value) and implementing operations done on them
* all over the place.
*---------------------------------------------*/
template<size_t N>
class Byte_Block : public Padding_Type
{
template<size_t M> friend class Byte_Block;
public :
using Padding_Type::Padding_Mode;
// Constructor, sets up all data bytes with padding
Byte_Block()
{
pad(0);
}
// Constructor from an object of different length (and possible with
// an offset into its data).
template<size_t M>
Byte_Block(Byte_Block<M> const & other,
size_t offset = 0)
: m_init_len(N)
{
unsigned char const * data = other.m_data + offset;
if (offset > M) {
pad(0);
} else if (M - offset >= N) {
std::copy(data, data + N, m_data);
} else {
std::copy(data, data + M - offset, m_data);
pad(M - offset);
}
}
// Constructor from array of unsigned char of the given lenghth
// (bytes beyond the length of the object are silently dropped,
// if there are less bytes padding is appended)
Byte_Block(unsigned char const * data,
size_t length = N)
: m_init_len(N)
{
if (length >= N) {
std::copy(data, data + N, m_data);
} else {
std::copy(data, data + length, m_data);
pad(length);
}
}
// Constructor from an array of char of the given lenghth or, if
// no length is supplied (or is 0), from a C string, i.e. stopping
// at the first zero byte. Bytes beyond the size of the object are
// silently dropped and if there are less bytes padding is added.
Byte_Block(char const * data,
size_t length = 0)
: m_init_len(N)
{
if (length == 0)
length = strlen(data);
if (length >= N) {
std::copy(data, data + N, m_data);
} else {
std::copy(data, data + length, m_data);
pad(length);
}
}
// Constructor from a std::string, with an optional offset into
// its data
Byte_Block(std::string const & str,
size_t offset = 0)
: m_init_len(N)
{
char const * data = str.data() + offset;
size_t len = str.size();
if (offset >= len) {
pad(0);
} else if (len - offset >= N) {
std::copy(data, data + N, m_data);
} else {
std::copy(data, data + len - offset, m_data);
pad(len - offset);
}
}
// Destructor, overwrites all data with 0 to make sure they're not
// left in memory
~Byte_Block()
{
std::fill(m_data, m_data + N, 0);
}
// Sets the padding mode (for all instances of the class!)
static
void
set_padding_mode(Padding_Mode mode)
{
s_padding_mode = mode;
}
// Comparison operators
inline
bool
operator == (Byte_Block const & other) const
{
return ! std::memcmp(m_data, other.m_data, N);
}
inline
bool
operator != (Byte_Block const & other) const
{
return ! (*this == other);
}
// Assignment operator from other Byte_Block object (of possibly
// different size) or a std::string
template<size_t M>
Byte_Block &
operator = (Byte_Block<M> & other)
{
if (other == *this)
return *this;
if (M >= N) {
std::copy(other.m_data, other.m_data + N, m_data);
} else {
std::copy(other.m_data, other.m_data + M, m_data);
pad(M);
}
return *this;
}
Byte_Block &
operator = (std::string const & str)
{
char const * data = str.data();
size_t len = str.size();
if (len >= N) {
std::copy(data, data + N, m_data);
} else {
std::copy(data, data + len, m_data);
pad(len);
}
return *this;
}
// Operator/method for accessing an element
inline
unsigned char
operator [] (size_t index) const
{
return m_data[index];
}
inline
unsigned char &
operator [] (size_t index)
{
return m_data[index];
}
unsigned char
at(size_t index) const
{
if (index >= N)
throw std::out_of_range("Invalid acccess");
return m_data[index];
}
// XOR operator with another object (of the same size)
Byte_Block const
operator ^ (Byte_Block const & other) const
{
Byte_Block res(*this);
return res ^= other;
}
Byte_Block &
operator ^= (Byte_Block const & other)
{
for (size_t i = 0; i < N; ++i)
m_data[i] ^= other[i];
return *this;
}
// Left-shift operator
Byte_Block const
operator << (size_t bit_cnt) const
{
Byte_Block res(*this);
return res <<= bit_cnt;
}
Byte_Block &
operator <<= (size_t bit_cnt)
{
size_t byte_cnt = bit_cnt / 8;
if (byte_cnt) {
if (byte_cnt >= N) {
std::fill(m_data, m_data + N, 0);
return *this;
}
for (size_t i = 0; i < N - byte_cnt; ++i)
m_data[i] = m_data[i + byte_cnt];
std::fill(m_data + N - byte_cnt, m_data + N, 0);
bit_cnt %= 8;
}
if (bit_cnt != 0) {
for (size_t i = 0; i < N - byte_cnt - 1; ++i)
m_data[i] = (m_data[i] << bit_cnt)
| (m_data[i + 1] >> (N - bit_cnt));
m_data[N - 1] <<= bit_cnt;
}
return *this;
}
// Prefix and postfix increment operators - data in the block are
// treated as an unsigned integer type with N bytes, stored with
// LSB first
Byte_Block &
operator ++ ()
{
size_t n = 0;
while (++m_data[n] == 0 && ++n < N)
/* empty */ ;
return *this;
}
Byte_Block const
operator ++ (int)
{
Byte_Block res(*this);
++*this;
return res;
}
// Implicit conversion to array of unsigned chars
inline
operator unsigned char * ()
{
return m_data;
}
inline
operator unsigned char const * () const
{
return m_data;
}
// Implicit conversion to a pointer to chars (but with no '\0' at
// the end, so NOT usable for conversion to a C string!)
inline
operator char * ()
{
return cdata();
}
inline
operator char const * () const
{
return cdata();
}
// Returns a pointer to the data (at an optinal offset)
inline
unsigned char *
data(size_t offset = 0)
{
return m_data + offset;
}
inline
unsigned char const *
data(size_t offset = 0) const
{
return m_data + offset;
}
// Returns char pointer to the data (at an optional offset)
inline
char const *
cdata(size_t offset = 0) const
{
return reinterpret_cast<char const *>(m_data + offset);
}
inline
char *
cdata(size_t offset = 0)
{
return reinterpret_cast<char *>(m_data + offset);
}
// Returns the (copy of the) content of the data as a std::string
std::string
str() const
{
return std::string(cdata(), N);
}
// Sets the data (at an optional offset) to those of a different object
// (which may have a different length).
template<size_t M>
Byte_Block &
set(Byte_Block<M> const & src,
size_t offset = 0)
{
std::copy(src.m_data, src.m_data + std::min<size_t>((N - offset), M), m_data + offset);
return *this;
}
// Returns the objects data as a std::string. If the 'is_padded' flag
// is set (which only happens during decryption) the padding bytes will
// be removed. If the padding bytes aren't what they're supposed to be
// an exception is thrown, indicating that the message was garbled.
std::string
as_string(bool is_padded = false) const
{
size_t pos = N;
if (is_padded) {
switch (s_padding_mode) {
case PKCS7:
if (m_data[N - 1] > N) {
pos = N + 1;
break;
}
pos -= m_data[N - 1];
for (size_t i = pos; i < N - 1; ++i)
if (N - m_data[i] != pos){
pos = N + 1;
break;
}
break;
case ANSIX9_23:
if (m_data[N - 1] > N) {
pos = N + 1;
break;
}
pos -= m_data[N - 1];
for (size_t i = pos; i < N - 1; ++i)
if (m_data[i] != 0) {
pos = N + 1;
break;
}
break;
case ISO7816_4:
while (--pos > 0 && ! m_data[pos])
/* empty */ ;
if (m_data[pos] != 0x80)
pos = N + 1;
break;
case ALL_NULL :
while (--pos > 0 && ! m_data[pos])
/* empty */ ;
++pos;
break;
}
if (pos == N + 1)
throw std::invalid_argument("String to decrypt is garbled");
}
return std::string(reinterpret_cast<char const *>(m_data), pos);
}
// Returns the number of bytes initialized (excluding automatically
// added padding - needed to be able to encrypt and decrypt blocks
// with less than 16 bytes in CFB8 mode)
size_t
init_len() const
{
return m_init_len;
}
// Method for padding to the full length of N (if an initializer
// or assigned value had less bytes). How that's done depends on
// what the padding mode is set to. Input is the number of "good"
// bytes in the buffer.
Byte_Block &
pad(size_t length)
{
if (length == N) {
m_init_len = 0;
return *this;
}
switch (s_padding_mode) {
case PKCS7:
std::fill(m_data + length, m_data + N, N - length);
break;
case ANSIX9_23:
std::fill(m_data + length, m_data + N - 1, 0);
m_data[N - 1] = N - length;
break;
case ISO7816_4:
m_data[length] = 0x80;
std::fill(m_data + length + 1, m_data + N, 0);
break;
case ALL_NULL:
std::fill(m_data + length, m_data + N, 0);
break;
}
m_init_len = length;
return *this;
}
private :
// Array of data
unsigned char m_data[N];
// Number of bytes that really got initialized
unsigned int m_init_len;
// Padding mode (global, i.e. applies to all instances of the class)
static Padding_Mode s_padding_mode;
};
/*---------------------------------------------*
* Definition (and initialization of the static 's_padding_mode'
* member variable - there's one for each templated class.
*---------------------------------------------*/
template<size_t N>
typename Byte_Block<N>::Padding_Mode Byte_Block<N>::s_padding_mode =
Byte_Block<N>::ISO7816_4;
/*---------------------------------------------*
* Function for printing out the data of an object
* in a "raw" format, just an unstructured chain of
* hex nunbers (like it's used e.g. in the NIST
* documentation).
*---------------------------------------------*/
template<size_t N>
std::ostream &
operator << (std::ostream & out,
Byte_Block<N> const & block)
{
std::ios_base::fmtflags flags(out.flags());
out.flags(std::ios::hex);
for (size_t i = 0; i < N; ++i)
out << std::setw(2) << std::setfill('0')
<< static_cast<unsigned int>(block[i]);
out.flags(flags);
return out;
}
#endif
/*
* Local variables:
* tab-width: 4
* indent-tabs-mode: nil
* End:
*/
| true |
e45de29b6d48894862cc6b360c580968f2d129b7 | C++ | alexandrepoulin/freezeout | /src/mainPaper.cpp | UTF-8 | 1,315 | 2.734375 | 3 | [] | no_license | #include "../include/NumericalCalculator.h"
#include <string>
#include <stdlib.h>
int main(int argc, char* argv[]){
//files for input and output
string in;
string out;
/*
* argv[1] = hardcoded smallest x
* argv[2] = file id
* argv[3] = single case
* argv[4] = ndm
* argv[n] = mxset[n-5]
* */
string id = argv[2];
in= "C:/Users/AlexandrePoulin/Documents/relic/freezeout_v2.5/inputFiles/inputData"+id+".txt";
out= "C:/Users/AlexandrePoulin/Documents/relic/freezeout_v2.5/outputFiles/outputOmega"+id +".txt";
//initialize the numerical calculator
NumericalCalculator numCalc(in,out);
cout << "Done initializing." << endl;
float maxMass = 0;
for(int ind=5; ind<5+atoi(argv[4]); ind++){
numCalc.inputReader->mxset[ind-5] = atof(argv[ind]);
if(atof(argv[ind])>maxMass) maxMass = atof(argv[ind]);
}
numCalc.inputReader->changeMassScale(maxMass);
numCalc.inputReader->changeSmallestX(atof(argv[1]));
bool singleCase = atoi(argv[3]);
if(singleCase){
numCalc.solve(singleCase);
for(int i=0; i<1; i++) cout << numCalc.omega[i] << endl;
}
else{
numCalc.solve(false);
numCalc.outputWriter->writeOmega(numCalc.omega);
}
return 1;
}
| true |
05e5e2a4db758497dde9b4c2550e75f9a3eb1533 | C++ | qingshanLiu1998413/qingshanliu | /选择排序.cpp | GB18030 | 678 | 3.015625 | 3 | [] | no_license | #include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
struct node {
char name[20]; // ѧ
int score; // ѧɼ
} a[20];
int main() {
int n;
cin >> n;
for (int i=1; i<=n; i++) { // ѧͳɼ
cin>>a[i].name>>a[i].score;
}
for (int i=1; i<n; i++) { // ѡ
for (int j=i+1; j<=n; j++) {
if ((a[i].score<a[j].score) ||
((a[i].score==a[j].score) && (strcmp(a[i].name,a[j].name)>0))) { //
swap(a[i], a[j]);
}
}
}
for (int i=1; i<=n; i++) { // ѧͳɼÿһ
printf("%s %d\n", a[i].name, a[i].score);
}
return 0;
}
| true |
eff10b99ff1437360d5c465f3eda90ceb2d49931 | C++ | lonelam/LearnC | /shu1898/shu1898.cpp | UTF-8 | 1,717 | 3.0625 | 3 | [] | no_license | #include<iostream>
#include<cstring>
class unit
{
public:
char u[4] = { 0 };
char source[3] = { 0 };
unit();
unit(char * p);
~unit() {}
void manip(char * p);
void manip();
void out(char * p);
};
unit::unit()
{
}
unit::unit(char *p)
{
for (int i = 0; i < 4; i++)
{
if (p[i] >= 'A'&&p[i] <= 'Z')
{
u[i] = p[i] - 'A';
}
else if (p[i] >= 'a'&&p[i] <= 'z')
{
u[i] = p[i] - 'a'+26;
}
else if (p[i] >= '0'&& p[i] <= '9')
{
u[i] = p[i] - '0'+52;
}
else if (p[i] == '+')
{
u[i] = 62;
}
else if (p[i] == '/')
{
u[i] = 63;
}
else if (p[i] == '=')
{
u[i] = 0;
}
}
manip();
}
void unit::manip()
{
source[0] = (u[0] << 2) + (u[1] >> 4 );
source[1] = (u[1] << 4) + (u[2] >> 2);
source[2] = (u[2] << 6) + u[3];
}
void unit::manip(char *p)
{
for (int i = 0; i < 4; i++)
{
if (p[i] >= 'A'&&p[i] <= 'Z')
{
u[i] = p[i] - 'A';
}
else if (p[i] >= 'a'&&p[i] <= 'z')
{
u[i] = p[i] - 'a' + 26;
}
else if (p[i] >= '0'&&p[i] <='9')
{
u[i] = p[i] - '0' + 52;
}
else if (p[i] == '+')
{
u[i] = 62;
}
else if (p[i] == '/')
{
u[i] = 63;
}
else if (p[i] == '=')
{
u[i] = 0;
}
}
this ->manip();
}
void unit::out(char *p)
{
for (int i = 0; i < 3; i++)
{
p[i] = source[i];
}
}
int main()
{
unit x;
char in[10000];
char out[7500];
int n;
while (scanf("%d", &n) != EOF)
{
for (int i = 0; i < n; i++)
{
scanf("%s", in);
int j = 0;
int k = 0;
while (in[j]!='\0')
{
x.manip(in + j);
x.out(out + k);
j+=4;
k += 3;
}
out[k] = '\0';
printf("%s\n", out);
}
}
} | true |
ba600d3a04ddddc88435c49246f53f258d0fcd1e | C++ | minus9d/programming_contest_archive | /arc/074/d/d.cpp | UTF-8 | 2,051 | 2.515625 | 3 | [] | no_license | #include <iostream>
#include <sstream>
#include <string>
#include <cassert>
#include <cmath>
#include <climits>
#include <cstdio>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <algorithm>
#include <functional>
#include <numeric>
#include <iomanip>
using namespace std;
typedef unsigned int uint;
typedef long long ll;
typedef unsigned long long ull;
#define REP(i,n) for(int i = 0; i < (int)(n); ++i)
#define FOR(i,a,b) for(int i = (a); i < (int)(b); ++i)
#define ALL(c) (c).begin(), (c).end()
#define SIZE(v) ((int)v.size())
#define pb push_back
#define mp make_pair
#define mt make_tuple
vector<ll> biggest_n(vector<ll>& As, int N) {
vector<ll> sums(3*N);
multiset<ll> kept;
REP(n, 3*N) {
auto a = As[n];
if (n == 0) {
sums[n] = a;
kept.insert(a);
}
else if (n < N) {
sums[n] = sums[n-1] + a;
kept.insert(a);
}
else {
if (*kept.begin() < a) {
sums[n] = sums[n-1] - *kept.begin() + a;
kept.erase(kept.begin());
kept.insert(a);
}
else {
sums[n] = sums[n-1];
}
}
}
// for(auto s:sums) cout << s << " ";
// cout << endl;
return sums;
}
int main(void)
{
cin.sync_with_stdio(false);
int N;
cin >> N;
vector<ll> As(3*N);
REP(n, 3*N) {
cin >> As[n];
}
auto left_largeN = biggest_n(As, N);
vector<ll> Bs(3*N);
REP(i, 3*N) {
Bs[i] = -As[3*N-1-i];
}
auto right_smallN = biggest_n(Bs, N);
ll ans = 0;
FOR(i, N-1, 2*N) {
auto val1 = left_largeN[i];
auto idx = (3 * N - 1) - i - 1;
auto val2 = -right_smallN[idx];
// cout << "i, idx = " << i << "," << idx << endl;
// cout << "val1, val2 = " << val1 << "," << val2 << endl;
if (i == N-1) ans = val1 - val2;
else ans = max(ans, val1 - val2);
}
cout << ans << endl;
return 0;
}
| true |
9cda9cdaa12f1c1bcfbaa103024bf923cbfe38c0 | C++ | alexandraback/datacollection | /solutions_5630113748090880_0/C++/prob22/main.cpp | UTF-8 | 1,000 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <math.h>
#include <vector>
using namespace std;
int main() {
ifstream fin("B-small.in");
ofstream fout("B-small.txt");
int T;
fin >> T;
for(int i = 1; i<= T; i++) {
int N;
fin >> N;
int heights[2501];
for(int n = 0; n < 2501; n++)
heights[n] = 0;
for(int n = 1; n <= 2*(N)-1; n++) {
for(int j = 0; j < N; j++) {
int x;
fin >>x;
heights[x]++;
}
}
fout << "Case #" << i << ": ";
int counter = 0;
for(int n = 1; counter < N; n++) {
if(heights[n]%2==1 && counter < N-1) {
fout << n << " ";
counter ++;
}
else if(heights[n]%2==1 && counter == N-1) {
fout << n;
counter ++;
}
}
fout << endl;
}
return 0;
}
| true |
64cd60e3efacc5c44ce21d47d5c997cddad94e13 | C++ | PorterDalton1/SortingAlgorithms | /Selection.cpp | UTF-8 | 823 | 3.03125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
int lyst[100000];
ifstream myFile;
string data;
int counter = 0;
int lowest[2];
int tmp;
myFile.open("input2.txt");
while (myFile >> data)
{
lyst[counter] = stoi(data);
counter += 1;
}
for (int i = 0; i < counter; i++)
{
lowest[0] = lyst[i];
lowest[1] = i;
for (int e = i+1; e < counter; e++)
{
if (lowest[0] > lyst[e])
{
lowest[0] = lyst[e];
lowest[1] = e;
}
}
tmp = lyst[i];
lyst[i] = lowest[0];
lyst[lowest[1]] = tmp;
}
for (int i = 0; i < counter; i++)
{
cout << lyst[i] << endl;
}
return 0;
} | true |
ecc8959f4ce044df537896ca7289aaca2504e4fa | C++ | kbuzsaki/cse124-httpserver | /server.h | UTF-8 | 2,511 | 2.96875 | 3 | [] | no_license | #ifndef SERVER_H
#define SERVER_H
#include <memory>
#include "http.h"
#include "listener.h"
/*
* HttpConnection wraps a bytestream Connection object and provides higher level
* operations for processing http requests and responess.
* The `read_request` method reads and parses an HttpRequest from the connection.
* If the request is malformed it throws HttpRequestParseError. If the underlying
* connection closes, it throws ConnectionClosed.
* The `write_response` method serializes and sends an HttpResponse. It throws
* ConnectionClosed if the underlying connection closes.
*/
class HttpConnection {
BufferedConnection conn;
HttpFrame read_frame();
void write_frame(HttpFrame frame);
public:
HttpConnection(std::shared_ptr<Connection> conn);
HttpConnection(HttpConnection&&);
HttpRequest read_request();
void write_response(HttpResponse);
};
/*
* HttpListener wraps a Listener object and returns accepted connections prewrapped
* as HttpConnection objects.
*/
class HttpListener {
std::shared_ptr<Listener> listener;
public:
HttpListener(std::shared_ptr<Listener>);
HttpListener(HttpListener&&);
void listen();
HttpConnection accept();
};
/*
* HttpRequestHandler is an abstract class that represents the minimal interface for
* handling HttpRequests received by the HttpServer.
* It is implemented by FileServingHttpHandler and RequestFilterMiddleware in request_handlers.h
* and by MockHttpRequestHandler in mocks.h
*/
class HttpRequestHandler {
public:
virtual ~HttpRequestHandler() {};
virtual HttpResponse handle_request(const HttpRequest&) = 0;
};
/*
* HttpConnectionHandler is an abstract class that represents different strategies
* for handling incoming HttpConnections. It is implemented by BlockingHttpConnectionHandler,
* ThreadSpawningHttpConnectionHandler, and ThreadPoolHttpConnectionHandler in
* connection_handlers.h
*/
class HttpConnectionHandler {
public:
virtual ~HttpConnectionHandler() {};
virtual void handle_connection(HttpConnection&&) = 0;
};
/*
* HttpServer takes an HttpListener and HttpConnectionHandler and performs the mechanical
* work of reading incoming HttpConnections from the HttpListener and passing
* them off to the HttpConnectionHandler.
*/
class HttpServer {
HttpListener listener;
std::shared_ptr<HttpConnectionHandler> handler;
public:
HttpServer(HttpListener&&, std::shared_ptr<HttpConnectionHandler>);
void serve();
};
#endif //SERVER_H
| true |
b08423fc437685f8469b3d69e3af602a8037c6ea | C++ | youoj/Algorithm | /Baekjoon/[10998]A×B.cpp | UTF-8 | 202 | 3.0625 | 3 | [] | no_license | /* 10998번 AxB(Input/Output)
* https://www.acmicpc.net/problem/10998
*/
#include <iostream>
using namespace std;
int main() {
int a = 0, b = 0;
std::cin >> a >> b;
std::cout << a*b;
return 0;
} | true |
27faa972ab2ca57cf606ad44191cecff6b5f3c08 | C++ | JifeiTune/ACM | /动态规划/棋盘dp 矩阵“前缀和”.cpp | GB18030 | 2,067 | 2.78125 | 3 | [] | no_license | #include<iostream>
#include<string>
#include<memory.h>
#include<algorithm>
#include<cmath>
/*
whkӣң֪
̵иȣʹÿ鶼ǡһӣ
ɿ⣬dp[h1][h2][w1][w2]
ʾ߽߱Ϊh1h2߽Ϊw1w2ʱиȣұգ
ôͳӾӣҸ
ԤÿһϽǹ̶ΪԭϽǣ½ľӣҸ
ӾӣҸݳ㼴
*/
using namespace std;
bool che[21][21];//ijǷӣ
int Num[21][21];//(1,1)λϽǣ(i,j)Ϊ½ǵľӣҸ
int dp[21][21][21][21];
int w,h,k;
#define Sum(h1,h2,w1,w2) (Num[h2][w2]-Num[h1][w2]-Num[h2][w1]+Num[h1][w1])//ӣҸ
int dfs(int h1,int h2,int w1,int w2)//ⷶΧΪ(h1,h2](w1,w2]ʱСи
{
int tem,i,t1,t2,ans=0x7fffffff;
if(dp[h1][h2][w1][w2]!=-1)
{
return dp[h1][h2][w1][w2];
}
tem=Sum(h1,h2,w1,w2);
if(tem==1||tem==0)//ֻҪһӣһûУ
{
return dp[h1][h2][w1][w2]=0;
}
for(i=h1+1;i<h2;i++)//öٺ
{
t1=Sum(h1,i,w1,w2);
t2=Sum(i,h2,w1,w2);
if(t1>=1&&t2>=1)//ڵһи
{
ans=min(ans,w2-w1+dfs(h1,i,w1,w2)+dfs(i,h2,w1,w2));
}
}
for(i=w1+1;i<w2;i++)//ö
{
t1=Sum(h1,h2,w1,i);
t2=Sum(h1,h2,i,w2);
if(t1>=1&&t2>=1)
{
ans=min(ans,h2-h1+dfs(h1,h2,w1,i)+dfs(h1,h2,i,w2));
}
}
return dp[h1][h2][w1][w2]=ans;
}
int main()
{
int i,j,ans,X,Y,cas=1;
while(~scanf("%d%d%d",&h,&w,&k))
{
memset(dp,-1,sizeof(dp));
memset(che,0,sizeof(che));
memset(Num,0,sizeof(Num));
for(i=1;i<=k;i++)
{
scanf("%d%d",&Y,&X);
che[Y][X]=1;
}
for(i=1;i<=h;i++)//һһNum
{
for(j=1;j<=w;j++)
{
Num[i][j]=Num[i][j-1]+che[i][j]+Sum(0,i-1,j-1,j);//һ
}
}
printf("Case %d: %d\n",cas++,dfs(0,h,0,w));
}
return 0;
}
| true |
d4e54df058f015ea695da05fc53b44a2e9329d06 | C++ | cjsatuforc/FrSky_SPORT_Arduino | /FrSkySportSensorFlvss.cpp | UTF-8 | 2,437 | 2.578125 | 3 | [] | no_license | /*
FrSky FLVSS LiPo voltage sensor class for Teensy 3.x and 328P based boards
(e.g. Pro Mini, Nano, Uno)
(c) Pawelsky 20150725
Not for commercial use
*/
#include "FrSkySportSensorFlvss.h"
FrSkySportSensorFlvss::FrSkySportSensorFlvss(SensorId id)
: FrSkySportSensor(id) {}
uint32_t FrSkySportSensorFlvss::setCellData(uint8_t cellNum,
uint8_t firstCellNo, float cell1,
float cell2) {
uint16_t cell1Data = cell1 * 1000 / 2;
uint16_t cell2Data = cell2 * 1000 / 2;
uint32_t cellData = 0;
cellData = cell2Data & 0x0FFF;
cellData <<= 12;
cellData |= cell1Data & 0x0FFF;
cellData <<= 4;
cellData |= cellNum & 0x0F;
cellData <<= 4;
cellData |= firstCellNo & 0x0F;
return cellData;
}
void FrSkySportSensorFlvss::setData(float cell1, float cell2, float cell3,
float cell4, float cell5, float cell6) {
uint8_t numCells = 1; // We assume at least one cell
if (cell2 > 0) {
numCells++;
if (cell3 > 0) {
numCells++;
if (cell4 > 0) {
numCells++;
if (cell5 > 0) {
numCells++;
if (cell6 > 0) {
numCells++;
}
}
}
}
}
cellData1 = setCellData(numCells, 0, cell1, cell2);
if (numCells > 2)
cellData2 = setCellData(numCells, 2, cell3, cell4);
else
cellData2 = 0;
if (numCells > 4)
cellData3 = setCellData(numCells, 4, cell5, cell6);
else
cellData3 = 0;
}
void FrSkySportSensorFlvss::send(FrSkySportSingleWireSerial &serial, uint8_t id,
uint32_t now) {
if (sensorId == id) {
if (now > cellDataTime) {
cellDataTime = now + FLVSS_CELL_DATA_PERIOD;
switch (sensorDataIdx) {
case 0:
serial.sendData(FLVSS_CELL_DATA_ID, cellData1);
if (cellData2 != 0)
sensorDataIdx = 1;
else
sensorDataIdx = 0;
break;
case 1:
serial.sendData(FLVSS_CELL_DATA_ID, cellData2);
if (cellData3 != 0)
sensorDataIdx = 2;
else
sensorDataIdx = 0;
break;
case 2:
serial.sendData(FLVSS_CELL_DATA_ID, cellData3);
sensorDataIdx = 0;
break;
}
} else {
serial.sendEmpty(FLVSS_CELL_DATA_ID);
}
}
}
| true |
0f5345644f231ac537d0f4af16297a025b8da162 | C++ | ctyVegetableDog/leetcode | /helloLeet/0904.cpp | UTF-8 | 1,034 | 3.046875 | 3 | [] | no_license | // 水果成篮
/*
*刺鼻题让老子调了半小时,真是老了
* */
class Solution {
public:
int totalFruit(vector<int>& fruits) {
int n = fruits.size();
vector<int> last(n + 1); // 每种水果上一次出现的位置
int b1 = fruits[0], b2 =-1; // 记录当前的两种水果
int cur = 0, ans = 0, i = 0;
while (i < n && fruits[i] == b1) {
++cur;
last[b1] = i;
++i;
}
if (i == n) return cur;
b2 = fruits[i];
last[b2] = i;
++cur;
++i;
ans = max(cur, ans);
while(i < n) {
if (fruits[i] != b1 && fruits[i] != b2) {
int lastest = min(last[b1], last[b2]) == last[b1] ? b1 : b2;
cur = i - last[lastest];
if (lastest == b1) b1 = fruits[i];
else b2 = fruits[i];
} else ++cur;
last[fruits[i]] = i;
ans = max(ans, cur);
++i;
}
return ans;
}
};
| true |
e9c4cd4c8f45dd463cd18c5cd6beda1fc5e4f427 | C++ | zsh965866221/DataStructure-C | /calculateExpression.cpp | UTF-8 | 2,099 | 3.328125 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
#include "Stack.h"
bool isDigit(char c)
{
if('9'-c>=0&&c-'0'>=0)
return true;
else
return false;
}
int charToDigit(char c)
{
return c-'0';
}
int operatorLevel(char c)
{
switch(c)
{
case '+': return 1;
case '-': return 1;
case '*': return 2;
case '/': return 2;
default: return 0;
}
}
float cal(char c,float a,float b)
{
switch(c)
{
case '+': return a+b;
case '-': return a-b;
case '*': return a*b;
case '/': return a/b;
default: return 0;
}
}
int main()
{
char ss[100];
float S2[100];
int i2=0;
Stack S1;
initStack(S1);
scanf("%s",ss);
int size=strlen(ss);
for(int i=0;i<size;i++)
{
if(isDigit(ss[i]))
{
S2[i2]=charToDigit(ss[i]);
i2++;
}
else{
if(isEmpty(S1))
push(S1,ss[i]);
else{
if(ss[i]=='(')
{
push(S1,ss[i]);
}
else if(ss[i]==')')
{
char c=pop(S1);
while(c!='(')
{
float b=S2[--i2];
float a=S2[--i2];
S2[i2++]=cal(c,a,b);
c=pop(S1);
}
}
else{
char c=getTop(S1);
while(operatorLevel(ss[i])<=operatorLevel(c)&&c!='(')
{
pop(S1);
float b=S2[--i2];
float a=S2[--i2];
S2[i2++]=cal(c,a,b);
c=getTop(S1);
}
push(S1,ss[i]);
}
}
}
}
while(!isEmpty(S1))
{
char c=pop(S1);
float b=S2[--i2];
float a=S2[--i2];
S2[i2++]=cal(c,a,b);
}
printf("%.1f",S2[0]);
}
| true |
e717ee5c77a2438b6adf37b508aa3c463738a5f4 | C++ | mrsempress/PAT | /1062.cpp | UTF-8 | 1,296 | 2.703125 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
const int maxn=1e5+10;
int n,l,h,m;
struct ty{
string ID;
int vg;
int tg;
int kind;// 1:sages 2:nobleman 3:fool men 5:small man
bool operator<(const ty& o)const{
if(kind!=o.kind) return kind<o.kind;
if((vg+tg)!=(o.vg+o.tg)) return (vg+tg)>(o.vg+o.tg);
if(vg!=o.vg) return vg>o.vg;
return ID<o.ID;
}
}tmp;
vector<ty>v;
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cin>>n>>l>>h;
for(int i=1;i<=n;i++){
cin>>tmp.ID>>tmp.vg>>tmp.tg;
if(tmp.vg<l||tmp.tg<l) continue;
if(tmp.vg>=h&&tmp.tg>=h){
tmp.kind=1;v.push_back(tmp);
continue;
}
if(tmp.vg>=h){
tmp.kind=2;v.push_back(tmp);
continue;
}
if(tmp.tg>=h){
tmp.kind=5;v.push_back(tmp);
continue;
}
if(tmp.vg>=tmp.tg){
tmp.kind=3;v.push_back(tmp);
continue;
}
tmp.kind=5;v.push_back(tmp);
}
sort(v.begin(),v.end());
int len=v.size();
cout<<len<<'\n';
for(int i=0;i<len;i++){
cout<<v[i].ID<<' '<<v[i].vg<<' '<<v[i].tg<<'\n';
}
return 0;
} | true |
d56f00c62884988c78130764daab549a7bad48e0 | C++ | JuliaHolk/Zaphod | /testintersection.cpp | UTF-8 | 464 | 2.875 | 3 | [] | no_license | //
// Created by julia on 06.07.18.
//
#include <cstdio>
#include <cmath>
#include "Vec.h"
#include "Colour.h"
#include "Sphere.h"
#include "Ray.h"
#include <iostream>
/*int main(){
Vec3D st(0.0,0.0,0.0);
Vec3D dir(0,1.0,0.0);
Ray ray(st, dir);
Vec3D cent(0,42.0,0);
Colour green(0.0,0.0,0.5);
double r=2.0;
Sphere sphere(cent, r, green);
double t=sphere.intersect(ray);
std::cout << "t=" << t << std::endl;
return 0;
}
*/ | true |
d2a7d481a1ed633a658421d57dc802b47786e855 | C++ | samiqss/Software-Engineering | /csci265/lab07a/broken.cpp | UTF-8 | 4,845 | 3.609375 | 4 | [] | no_license | #include <cstdio>
#include <cmath>
#include <cstdlib>
// possible tower id values, for the source,
// destination, and auxilliary towers
enum ID { SRC, DEST, AUX };
// default size of the tower (number of disks)
const int DefaultSize = 3;
// value used to specify an empty tower
const int EMPTY = -1;
// each tower has a maximum size, current size,
// and an array of disks
struct Tower {
int currSize;
int maxSize;
int *disks;
ID id;
};
// given the number of disks and the tower id,
// allocate and initialize a tower,
// return true if successful, false otherwise
bool initialize(Tower &t, int disks, enum ID id)
{
t.currSize = 0;
t.maxSize = disks;
t.id = id;
t.disks = new int[disks];
if (!t.disks) return false;
return true;
}
// push a numbered disk onto the tower
void push(Tower &t, int diskNum)
{
t.disks[t.currSize++] = diskNum;
}
// pop a numbered disk off the tower, returning its number
// returns -1 if tower is empty
int pop(Tower &t)
{
if (t.currSize == 0) return EMPTY;
return t.disks[--t.currSize];
}
// release any memory allocated for the tower
void release(Tower &t) {
if (t.disks) delete[] t.disks;
}
// display the required move to the user
void printMove(Tower &src, Tower &dest, int diskNum)
{
printf("Move the top disk (%d) from tower %d to tower %d\n", diskNum, src.id, dest.id);
}
// draw the current tower contents, left to right
void printTower(Tower &t)
{
printf(" Tower[%d]: ", t.id);
for (int i = 0; i < t.currSize; i++) printf("%d,", t.disks[i]);
printf("\n");
}
// determine the legal move needed to get a disk from the
// specified current source to the current destination
void makeMove(Tower &currSrc, Tower &currDest)
{
// get the top disk from both towers
int srcNum = pop(currSrc);
int destNum = pop(currDest);
// see if either tower was empty, if so move TO that tower
if (srcNum == EMPTY) {
push(currSrc, destNum);
printMove(currDest, currSrc, destNum);
} else if (destNum == EMPTY) {
push(currDest, srcNum);
printMove(currSrc, currDest, srcNum);
}
// otherwise move the smaller of the two disks,
// putting the larger back first
else if (srcNum > destNum) {
push(currSrc, srcNum);
push(currSrc, destNum);
printMove(currDest, currSrc, destNum);
} else {
push(currDest, destNum);
push(currDest, srcNum);
printMove(currSrc, currDest, srcNum);
}
}
// transfer the specified number of disks from the top of the
// source tower to the top of the destination tower,
// using the auxilliary tower as needed
void transfer(int disks, Tower &src, Tower &dest, Tower &aux)
{
// the total number of moves needed is 2^disks-1
int moves = pow(2, disks);
// if the number of disks is even we need to swap our
// aux and dest towers
Tower realAux, realDest;
if ((disks % 2) == 0) {
realAux = dest;
realDest = aux;
} else {
realAux = aux;
realDest = dest;
}
// process all the moves in order,
// the direction of the move is based on both the move
// number and the value of the top disks on both towers
// (i.e. the direction may get reversed inside makeMove)
for (int mv = 1; mv <= moves-1; mv++){
if ((mv % 3) == 0) makeMove(realAux, realDest);
else if ((mv % 3) == 1) makeMove(src, realDest);
else makeMove(src, realAux);
// draw the three towers
printTower(src);
printTower(realDest);
printTower(realAux);
}
}
int main(int argc, char *argv[])
{
// number of disks to be processed,
// user can override the default with a command line argument
int numDisks = DefaultSize;
if ((argc == 2) && (atoi(argv[1]) > 0)) numDisks = atoi(argv[1]);
// set up the three towers
Tower src, dest, aux;
bool success = initialize(src, numDisks, SRC);
success = success && initialize(dest, numDisks, DEST);
success = success && initialize(aux, numDisks, AUX);
if (success) {
// let the user know what's happening
printf("\nTransferring %d disks from tower %d to tower %d\n",
numDisks, src.id, dest.id);
// push the original disks onto src,
// from largest to smallest
for (int p = numDisks; p > 0; p--) push(src, p);
// show them the original tower contents
printTower(src);
printTower(dest);
printTower(aux);
printf("\n");
// move all the disks from the source tower to the destination tower,
// using the intermediate tower
transfer(numDisks, src, dest, aux);
printf("\nDone!!!\n\n");
} else printf("\nTower allocation failed, ending program\n\n");
// free any allocated memory and end the program
release(src);
release(dest);
release(aux);
return 0;
}
| true |
39a7061b1f75ea7688f540ce50d7b7eb3e134923 | C++ | Tishkata/EGT | /Shop for T-shirts/Tshirt.cpp | UTF-8 | 2,101 | 3.640625 | 4 | [] | no_license | #include "Tshirt.h"
Tshirt::Tshirt()
{
this->brand = NULL;
this->price = 0;
this->sizeOfTshirt = 0;
this->sex = 0;
}
Tshirt::Tshirt(const char* brand, double price, int sizeOfTshirt, bool sex)
{
this->brand = new char[strlen(brand) + 1];
strcpy(this->brand, brand);
this->price = price;
this->sizeOfTshirt = sizeOfTshirt;
this->sex = sex;
}
Tshirt::Tshirt(const Tshirt& other)
{
delete[] this->brand;
this->brand = new char[strlen(other.brand) + 1];
strcpy(this->brand, other.brand);
this->price = other.price;
this->sizeOfTshirt = other.sizeOfTshirt;
this->sex = other.sex;
}
Tshirt& Tshirt::operator=(const Tshirt& other)
{
if(this != & other){
delete[] this->brand;
this->brand = new char[strlen(other.brand) + 1];
strcpy(this->brand, other.brand);
this->price = other.price;
this->sizeOfTshirt = other.sizeOfTshirt;
this->sex = other.sex;
}
return *this;
}
bool Tshirt::operator==(const Tshirt& right)
{
if(strcmp(this->brand, right.brand) == 0 && (this->price = right.price) && (this->sizeOfTshirt = right.sizeOfTshirt) && (this->sex == right.sex)){
return true;
}
return false;
}
void Tshirt::setBrand(const char* brand)
{
this->brand = new char[strlen(brand) + 1];
strcpy(this->brand, brand);
}
void Tshirt::setPrice(double price)
{
this->price = price;
}
void Tshirt::setSizeOfTshirt(int sizeOfTshirt)
{
this->sizeOfTshirt = sizeOfTshirt;
}
void Tshirt::setSex(bool sex)
{
this->sex = sex;
}
const char* Tshirt::getBrand() const
{
return this->brand;
}
double Tshirt::getPrice() const
{
return this->price;
}
int Tshirt::getSizeOfTshirt() const
{
return this->sizeOfTshirt;
}
bool Tshirt::getSex() const
{
return this->sex;
}
void Tshirt::printInfo() const
{
cout << "Brand: " << getBrand() << endl;
cout << "Price: " << getPrice() << endl;
cout << "Size of Tshirt: " << getSizeOfTshirt() << endl;
cout << "Sex: " << getSex() << endl;
}
Tshirt::~Tshirt()
{
delete[] this->brand;
}
| true |
3df3c66a89897559826fd0e6369098868c55b61d | C++ | KongkaMozumderSUST/library | /String/Z-Function/sub_string_search.cpp | UTF-8 | 644 | 2.703125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
vector<int> z_function(string s)
{
int n = (int) s.length();
vector<int> z(n);
for(int i = 1, l = 0, r = 0; i < n; ++i) {
if (i <= r)
z[i] = min (r - i + 1, z[i - l]);
while (i + z[i] < n && s[z[i]] == s[i + z[i]])
++z[i];
if (i + z[i] - 1 > r)
l = i, r = i + z[i] - 1;
}
return z;
}
int main()
{
string t,p,s;
cin>>p>>t;
s=p+"#";
s+=t;
vector<int> z = z_function(s);
for(int i=0; i<t.size(); i++)
{
if(z[i+p.size()+1]==p.size())
cout<<i<<" ";
}
return 0;
}
| true |
c301fbafb9aa72557b1337bb50925abad25d57da | C++ | prabhhav/InterviewBit | /addonetonumber.cpp | UTF-8 | 614 | 3.265625 | 3 | [] | no_license | vector<int> Solution::plusOne(vector<int> &a) {
vector<int> result;
int n = a.size();
vector<int> temp;
int carry = 1;
for(int i = n-1; i>=0; i--){
int curr = carry + a[i];
carry = curr/10;
temp.push_back(curr % 10);
}
if (carry>0){
temp.push_back(carry);
}
int len = temp.size();
while(true){
if(temp[len-1]==0){
len--;
} else {
break;
}
}
for (int i = len-1; i>=0; i--){
result.push_back(temp[i]);
}
return result;
}
| true |
b7b26d62036a8fb636cb2bc85d4ae37545c6c976 | C++ | rainbowhxch/daily-data-structure | /LinkedList/LinkedList.cpp | UTF-8 | 2,096 | 3.59375 | 4 | [] | no_license | #include "LinkedList.h"
#include <iostream>
using namespace std;
LinkedList::LinkedList()
{
head = new Node;
head->next = NULL;
length = 0;
}
int LinkedList::getLength()
{
return length;
}
int LinkedList::getElem(int pos)
{
listNode p = head->next;
int count = 1;
while (p && count < pos)
{
p = p->next;
++count;
}
if (!p || count > pos) return -1;
return p->data;
}
bool LinkedList::insertElem(int pos, int n)
{
int count = 1;
listNode p = head;
while (p && count < pos)
{
p = p->next;
++count;
}
if (!p || count > pos) return false;
listNode i = new Node;
i->data = n;
i->next = p->next;
p->next = i;
length++;
return true;
}
LinkedList::listNode LinkedList::findElem(int n)
{
listNode p = head->next;
while(p && p->data != n)
{
p = p->next;
}
return p;
}
bool LinkedList::deleteElem(int pos)
{
listNode p = head;
int count = 1;
while(p && count < pos)
{
p = p->next;
++count;
}
if (!p || pos < count) return false;
listNode t = p->next;
p->next = t->next;
delete t;
length--;
return true;
}
LinkedList* mergeList(LinkedList* a, LinkedList* b)
{
LinkedList* temp = new LinkedList();
LinkedList::listNode pa = a->head->next;
LinkedList::listNode pb = b->head->next;
LinkedList::listNode pt = temp->head;
while (pa && pb)
{
if (pa->data <= pb->data)
{
pt->next = pa;
pt = pa;
pa = pa->next;
}
else
{
pt->next = pb;
pt = pb;
pb = pb->next;
}
pt->next = pa ? pa : pb;
}
return temp;
}
void LinkedList::traverse()
{
listNode p = head->next;
while (p)
{
cout << p->data << ' ';
p = p->next;
}
cout << endl;
}
bool LinkedList::isEmpty()
{
return length == 0;
}
| true |
b5e02c1895512b10489ebe91c55cd6fb3c7dcfe9 | C++ | Seltzer/building-sketch | /Prototype/BuildingGeneration.cpp | UTF-8 | 9,986 | 2.640625 | 3 | [] | no_license | #include <algorithm>
#include "BuildingGeneration.h"
#include "Clip.h"
using namespace std;
void ExtrudeSketch(Building& building, vector<int2>& outline, vector<Stroke>& processedFeatureOutlines)
{
std::vector<float3> featurePolyFront;
std::vector<float3> featurePolyBack;
std::vector<float3> featurePolySide;
std::vector<float3> polyFront;
std::vector<float3> polyBack;
std::vector<float3> polySide;
polyFront.reserve(outline.size());
polyBack.reserve(outline.size());
polySide.reserve(4);
float tangScale = float(building.bounds.height) / building.bounds.width; // Hack to fix distortion
// The depth is 80% of the building width.
float depth = 0.8f*abs(building.bounds.width);
float2 previous = outline[0];
for (unsigned i = 0; i < outline.size(); i++)
{
float2 current = outline[i];
polyFront.push_back(float3(current.x, -current.y, depth/2));
polyBack.push_back(float3(current.x, -current.y, -depth/2));
if (i > 0) {
polySide.clear();
polySide.push_back(float3(current.x, -current.y, -depth/2));
polySide.push_back(float3(current.x, -current.y, depth/2));
polySide.push_back(float3(previous.x, -previous.y, depth/2));
polySide.push_back(float3(previous.x, -previous.y, -depth/2));
building.polys.push_back(polySide);
}
previous = current;
}
float2 uvStart(-building.bounds.width/2.0f, -building.bounds.height/2.0f);
float2 uvEnd(building.bounds.width/2.0f, building.bounds.height/2.0f);
Poly f(polyFront);
f.SetNormals(float3(0, 0, 1), float3(1, 0, 0) * tangScale, float3(0, 1, 0));
f.SetTexMapping(float3(1, 0, 0), float3(0, 1, 0), uvStart, uvEnd);
building.polys.push_back(f);
Poly b(polyBack);
b.SetNormals(float3(0, 0, -1), float3(1, 0, 0) * tangScale, float3(0, 1, 0)); // Tangents same because tex coords same
b.SetTexMapping(float3(0, 0, 1), float3(0, 1, 0), uvStart, uvEnd);
building.polys.push_back(b);
// Work out the feature polygons
/*
for (std::vector<Stroke>::iterator s = processedFeatureOutlines.begin();
s != processedFeatureOutlines.end(); s++)
{
std::vector<int2> stroke = (*s).points;
featurePolyFront.clear();
featurePolyBack.clear();
featurePolySide.clear();
featurePolyFront.reserve(stroke.size());
featurePolyBack.reserve(stroke.size());
featurePolySide.reserve(4);
// The depth is 20% of the stroke width.
float featureDepth = 0.1f*abs((*s).bounds.width);
float2 previous = stroke[0];
for (unsigned i = 0; i < stroke.size(); i++)
{
float2 current = stroke[i];
featurePolyFront.push_back(float3(current.x, -current.y, featureDepth+depth/2));
featurePolyBack.push_back(float3(current.x, -current.y, depth/2));
if (i > 0) {
featurePolySide.clear();
featurePolySide.push_back(float3(current.x, -current.y, depth/2));
featurePolySide.push_back(float3(current.x, -current.y, featureDepth+depth/2));
featurePolySide.push_back(float3(previous.x, -previous.y, featureDepth+depth/2));
featurePolySide.push_back(float3(previous.x, -previous.y, depth/2));
building.polys.push_back(featurePolySide);
}
previous = current;
}
featurePolyFront.push_back(float3(stroke[0].x, -stroke[0].y, featureDepth+depth/2));
featurePolyBack.push_back(float3(stroke[0].x, -stroke[0].y, depth/2));
building.polys.push_back(featurePolyFront);
building.polys.push_back(featurePolyBack);
}*/
building.bounds.depth = (int)depth;
}
void RotateSketch(Building& building, std::vector<int2>& outline, int rotationCount, bool mirrorSketch)
{
float rotAngle = (float)(D_PI/(rotationCount+1)); // rotate by atleast 90 degrees
std::vector<float3> polySide;
polySide.reserve(4);
float tangScale = float(building.bounds.height) / building.bounds.width; // Hack to fix distortion
// Convert old 2D outline to a 3D outline.
std::vector<float3> oldOutline;
oldOutline.reserve(outline.size());
for (int i = 0; i < outline.size(); i++)
{
float3 point = float3((float)outline[i].x, (float)outline[i].y, 0);
oldOutline.push_back(point);
}
// Mirror the sketch so everything lines up on a central axis
if (mirrorSketch) {
for (int i = 0; i < oldOutline.size()/2; i++)
{
oldOutline[oldOutline.size()-1-i].x = -oldOutline[i].x;
oldOutline[oldOutline.size()-1-i].y = oldOutline[i].y;
}
}
float2 uvStart(-building.bounds.width/2.0f, -building.bounds.height/2.0f);
float2 uvEnd(building.bounds.width/2.0f, building.bounds.height/2.0f);
for (int j = 0; j < (rotationCount+1)*2; j++)
{
// rotate the old outline by rotAngle to get the new outline.
std::vector<float3> newOutline = oldOutline;
for (int i = 0; i < newOutline.size(); i++)
{
float temp_x = newOutline[i].z*sin(rotAngle) + newOutline[i].x*cos(rotAngle);
float temp_z = newOutline[i].z*cos(rotAngle) - newOutline[i].x*sin(rotAngle);
newOutline[i].x = temp_x;
newOutline[i].z = temp_z;
}
// Build each side polygon
float3 prevPoint_oldOutline = oldOutline[0];
float3 prevPoint_newOutline = newOutline[0];
for (int i = 1; i < newOutline.size(); i++)
{
float3 currentPoint_newOutline = newOutline[i];
float3 currentPoint_oldOutline = oldOutline[i];
polySide.clear();
float3 p1(currentPoint_newOutline.x, -currentPoint_newOutline.y, currentPoint_newOutline.z);
float3 p2(currentPoint_oldOutline.x, -currentPoint_oldOutline.y, currentPoint_oldOutline.z);
float3 p3(prevPoint_oldOutline.x, -prevPoint_oldOutline.y, prevPoint_oldOutline.z);
float3 p4(prevPoint_newOutline.x, -prevPoint_newOutline.y, prevPoint_newOutline.z);
polySide.push_back(p1);
polySide.push_back(p2);
polySide.push_back(p3);
polySide.push_back(p4);
Poly p(polySide);
float3 tangent = normal(p2 - p1);
float3 bitangent = -normal(p1 - p4);
// Idealy differentiate between two halves of the space.
// When the tanget points in one half flip it.
// Thereby ensuring all the tangets are ...well
// ... consistant?
//
// But when in doubt (also lazy) H4x0r it.
// This wont work for lopsided shapes but
// thats hardly noticable.
if (i < newOutline.size()/2)
{
tangent = -tangent;
}
float3 norm = cross(tangent, bitangent);
p.SetNormals(norm, tangent * tangScale, bitangent);
p.SetTexMapping(float3(1, 0, 0), float3(0, 1, 0), uvStart, uvEnd);
building.polys.push_back(p);
prevPoint_oldOutline = currentPoint_oldOutline;
prevPoint_newOutline = currentPoint_newOutline;
}
oldOutline = newOutline;
}
}
void MirrorSketch(Building& building, vector<int2>& outline)
{
float2 uvStart(-building.bounds.width/2, -building.bounds.height/2);
float2 uvEnd(building.bounds.width/2, building.bounds.height/2);
float tangScale = float(building.bounds.height) / building.bounds.width; // Hack to fix distortion
// Magic... TODO: Proper comments
int2 previous = outline[0];
for (unsigned i = 1; i < outline.size(); i++)
{
int2 current = outline[i];
int yMax = std::max(previous.y, current.y);
int yMin = std::min(previous.y, current.y);
std::vector< std::vector<float2> > polys2d = Clip(outline, yMin, yMax);
if (yMax == yMin) // If min and max are equal we cannot interpolate height to produce a valid polygon
{
// Clip has produed a set of degenerate polygons with 4 verts each.
// Each one of these represents a horizontal rectangle, so we simply find the depth and generate them.
// We don't have to do both front and side because it's the top, we'd get everything twice.
// This special case is hilariously bigger than the general algorithm.
int minZ = std::min(previous.x, current.x);
int maxZ = std::max(previous.x, current.x);
for (unsigned p = 0; p < polys2d.size(); p++)
{
const std::vector<float2>& poly2d = polys2d[p];
assert(poly2d.size());
float minX = poly2d[0].x;
float maxX = poly2d[0].x;
for (unsigned i = 1; i < poly2d.size(); i++)
{
minX = std::min(minX, poly2d[i].x);
maxX = std::max(maxX, poly2d[i].x);
}
std::vector<float3> polyTop;
polyTop.reserve(4);
polyTop.push_back(float3(minX, -yMin, minZ));
polyTop.push_back(float3(maxX, -yMin, minZ));
polyTop.push_back(float3(maxX, -yMin, maxZ));
polyTop.push_back(float3(minX, -yMin, maxZ));
building.polys.push_back(polyTop);
}
}
for (unsigned p = 0; p < polys2d.size(); p++)
{
const std::vector<float2>& poly2d = polys2d[p];
std::vector<float3> front;
front.reserve(poly2d.size());
std::vector<float3> side;
side.reserve(poly2d.size());
for (unsigned j = 0; j < poly2d.size(); j++)
{
float2 p2d = poly2d[j];
// Interpolate based on y coordinate
float z = previous.x + float(p2d.y - previous.y) / (current.y - previous.y) * (current.x - previous.x);
front.push_back(float3(p2d.x, -p2d.y, z));
side.push_back(float3(z, -p2d.y, p2d.x));
}
float3 frontTangent(1, 0, 0);
float3 frontBinormal = normal(float3(0.0f, current.y - previous.y, previous.x - current.x));
if (frontBinormal.y < 0)
frontBinormal = -frontBinormal;
float3 frontNormal = normal(float3(0.0f, current.x - previous.x, current.y - previous.y)); // at 90 deg to binormal
//float3 frontNormal = cross(frontTangent, frontBinormal);
Poly polyFront(front);
polyFront.SetNormals(frontNormal, frontTangent * tangScale, frontBinormal);
polyFront.SetTexMapping(float3(1, 0, 0), float3(0, 1, 0), uvStart, uvEnd);
building.polys.push_back(polyFront);
float3 sideTangent(0, 0, 1);
float3 sideBinormal = normal(float3(current.x - previous.x, previous.y - current.y, 0.0f));
if (sideBinormal.y < 0)
sideBinormal = -sideBinormal;
float3 sideNormal = normal(float3(current.y - previous.y, current.x - previous.x, 0.0f));
//float3 sideNormal = cross(sideTangent, sideBinormal);
Poly polySide(side);
polySide.SetNormals(sideNormal, sideTangent * tangScale, sideBinormal);
polySide.SetTexMapping(float3(0, 0, 1), float3(0, 1, 0), uvStart, uvEnd);
building.polys.push_back(polySide);
}
previous = current;
}
} | true |