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
35278148ea9b6333621d688dffc3eff307229615
C++
zhangli344236745/Linux-Tutorial
/db_tutorial_cpp/tutorial11/db.cpp
UTF-8
28,206
2.75
3
[ "MIT" ]
permissive
#include <iostream> #include <cstring> #include <string> #include <fcntl.h> #include <unistd.h> enum MetaCommandResult { META_COMMAND_SUCCESS, META_COMMAND_UNRECOGNIZED_COMMAND }; enum PrepareResult { PREPARE_SUCCESS, PREPARE_NEGATIVE_ID, PREPARE_STRING_TOO_LONG, PREPARE_SYNTAX_ERROR, PREPARE_UNRECOGNIZED_STATEMENT }; enum StatementType { STATEMENT_INSERT, STATEMENT_SELECT }; enum ExecuteResult { EXECUTE_SUCCESS, EXECUTE_TABLE_FULL, EXECUTE_DUPLICATE_KEY }; enum NodeType { NODE_INTERNAL, NODE_LEAF }; #define COLUMN_USERNAME_SIZE 32 #define COLUMN_EMAIL_SIZE 255 class Row { public: uint32_t id; char username[COLUMN_USERNAME_SIZE + 1]; char email[COLUMN_EMAIL_SIZE + 1]; Row() { id = 0; username[0] = '\0'; email[0] = '\0'; } Row(uint32_t id, const char *username, const char *email) { this->id = id; strncpy(this->username, username, COLUMN_USERNAME_SIZE + 1); strncpy(this->email, email, COLUMN_EMAIL_SIZE + 1); } }; #define size_of_attribute(Struct, Attribute) sizeof(((Struct *)0)->Attribute) const uint32_t ID_SIZE = size_of_attribute(Row, id); const uint32_t USERNAME_SIZE = size_of_attribute(Row, username); const uint32_t EMAIL_SIZE = size_of_attribute(Row, email); const uint32_t ID_OFFSET = 0; const uint32_t USERNAME_OFFSET = ID_OFFSET + ID_SIZE; const uint32_t EMAIL_OFFSET = USERNAME_OFFSET + USERNAME_SIZE; const uint32_t ROW_SIZE = ID_SIZE + USERNAME_SIZE + EMAIL_SIZE; void serialize_row(Row &source, void *destination) { memcpy((char *)destination + ID_OFFSET, &(source.id), ID_SIZE); strncpy((char *)destination + USERNAME_OFFSET, source.username, USERNAME_SIZE); strncpy((char *)destination + EMAIL_OFFSET, source.email, EMAIL_SIZE); } void deserialize_row(void *source, Row &destination) { memcpy(&(destination.id), (char *)source + ID_OFFSET, ID_SIZE); strncpy(destination.username, (char *)source + USERNAME_OFFSET, USERNAME_SIZE); strncpy(destination.email, (char *)source + EMAIL_OFFSET, EMAIL_SIZE); } #define TABLE_MAX_PAGES 100 const uint32_t PAGE_SIZE = 4096; /* * Common Node Header Layout */ const uint32_t NODE_TYPE_SIZE = sizeof(uint8_t); const uint32_t NODE_TYPE_OFFSET = 0; const uint32_t IS_ROOT_SIZE = sizeof(uint8_t); const uint32_t IS_ROOT_OFFSET = NODE_TYPE_SIZE; const uint32_t PARENT_POINTER_SIZE = sizeof(uint32_t); const uint32_t PARENT_POINTER_OFFSET = IS_ROOT_OFFSET + IS_ROOT_SIZE; const uint8_t COMMON_NODE_HEADER_SIZE = NODE_TYPE_SIZE + IS_ROOT_SIZE + PARENT_POINTER_SIZE; class Node { protected: void *node; public: Node() {} Node(void *node) : node(node) {} NodeType get_node_type() { uint8_t value = *((uint8_t *)((char *)node + NODE_TYPE_OFFSET)); return (NodeType)value; } void set_node_type(NodeType type) { *((uint8_t *)((char *)node + NODE_TYPE_OFFSET)) = (uint8_t)type; } void *get_node() { return node; } bool is_node_root() { uint8_t value = *((uint8_t *)((char *)node + IS_ROOT_OFFSET)); return value == 1; } void set_node_root(bool is_root) { *((uint8_t *)((char *)node + IS_ROOT_OFFSET)) = is_root ? 1 : 0; } virtual uint32_t get_node_max_key(); }; /* * Leaf Node Header Layout */ const uint32_t LEAF_NODE_NUM_CELLS_SIZE = sizeof(uint32_t); const uint32_t LEAF_NODE_NUM_CELLS_OFFSET = COMMON_NODE_HEADER_SIZE; const uint32_t LEAF_NODE_NEXT_LEAF_SIZE = sizeof(uint32_t); const uint32_t LEAF_NODE_NEXT_LEAF_OFFSET = LEAF_NODE_NUM_CELLS_OFFSET + LEAF_NODE_NUM_CELLS_SIZE; const uint32_t LEAF_NODE_HEADER_SIZE = COMMON_NODE_HEADER_SIZE + LEAF_NODE_NUM_CELLS_SIZE + LEAF_NODE_NEXT_LEAF_SIZE; /* * Leaf Node Body Layout */ const uint32_t LEAF_NODE_KEY_SIZE = sizeof(uint32_t); const uint32_t LEAF_NODE_KEY_OFFSET = 0; const uint32_t LEAF_NODE_VALUE_SIZE = ROW_SIZE; const uint32_t LEAF_NODE_VALUE_OFFSET = LEAF_NODE_KEY_OFFSET + LEAF_NODE_KEY_SIZE; const uint32_t LEAF_NODE_CELL_SIZE = LEAF_NODE_KEY_SIZE + LEAF_NODE_VALUE_SIZE; const uint32_t LEAF_NODE_SPACE_FOR_CELLS = PAGE_SIZE - LEAF_NODE_HEADER_SIZE; const uint32_t LEAF_NODE_MAX_CELLS = LEAF_NODE_SPACE_FOR_CELLS / LEAF_NODE_CELL_SIZE; const uint32_t LEAF_NODE_RIGHT_SPLIT_COUNT = (LEAF_NODE_MAX_CELLS + 1) / 2; const uint32_t LEAF_NODE_LEFT_SPLIT_COUNT = (LEAF_NODE_MAX_CELLS + 1) - LEAF_NODE_RIGHT_SPLIT_COUNT; class LeafNode : public Node { public: LeafNode() {} LeafNode(void *node) : Node(node) {} void initialize_leaf_node() { set_node_type(NODE_LEAF); set_node_root(false); *leaf_node_num_cells() = 0; *leaf_node_next_leaf() = 0; // 0 represents no sibling } uint32_t *leaf_node_num_cells() { return (uint32_t *)((char *)node + LEAF_NODE_NUM_CELLS_OFFSET); } void *leaf_node_cell(uint32_t cell_num) { return (char *)node + LEAF_NODE_HEADER_SIZE + cell_num * LEAF_NODE_CELL_SIZE; } uint32_t *leaf_node_key(uint32_t cell_num) { return (uint32_t *)leaf_node_cell(cell_num); } void *leaf_node_value(uint32_t cell_num) { return (char *)leaf_node_cell(cell_num) + LEAF_NODE_KEY_SIZE; } uint32_t get_node_max_key() override { return *leaf_node_key(*leaf_node_num_cells() - 1); } u_int32_t *leaf_node_next_leaf() { return (u_int32_t *)((char *)node + LEAF_NODE_NEXT_LEAF_OFFSET); } }; /* * Internal Node Header Layout */ const uint32_t INTERNAL_NODE_NUM_KEYS_SIZE = sizeof(uint32_t); const uint32_t INTERNAL_NODE_NUM_KEYS_OFFSET = COMMON_NODE_HEADER_SIZE; const uint32_t INTERNAL_NODE_RIGHT_CHILD_SIZE = sizeof(uint32_t); const uint32_t INTERNAL_NODE_RIGHT_CHILD_OFFSET = INTERNAL_NODE_NUM_KEYS_OFFSET + INTERNAL_NODE_NUM_KEYS_SIZE; const uint32_t INTERNAL_NODE_HEADER_SIZE = COMMON_NODE_HEADER_SIZE + INTERNAL_NODE_NUM_KEYS_SIZE + INTERNAL_NODE_RIGHT_CHILD_SIZE; /* * Internal Node Body Layout */ const uint32_t INTERNAL_NODE_KEY_SIZE = sizeof(uint32_t); const uint32_t INTERNAL_NODE_CHILD_SIZE = sizeof(uint32_t); const uint32_t INTERNAL_NODE_CELL_SIZE = INTERNAL_NODE_CHILD_SIZE + INTERNAL_NODE_KEY_SIZE; class InternalNode : public Node { public: InternalNode() {} InternalNode(void *node) : Node(node) {} void initialize_internal_node() { set_node_type(NODE_INTERNAL); set_node_root(false); *internal_node_num_keys() = 0; } uint32_t *internal_node_num_keys() { return (uint32_t *)((char *)node + INTERNAL_NODE_NUM_KEYS_OFFSET); } u_int32_t *internal_node_right_child() { return (u_int32_t *)((char *)node + INTERNAL_NODE_RIGHT_CHILD_OFFSET); } uint32_t *internal_node_cell(uint32_t cell_num) { return (uint32_t *)((char *)node + INTERNAL_NODE_HEADER_SIZE + cell_num * INTERNAL_NODE_CELL_SIZE); } uint32_t *internal_node_child(uint32_t child_num) { uint32_t num_keys = *internal_node_num_keys(); if (child_num > num_keys) { std::cout << "Tried to access child_num " << child_num << " > num_keys " << num_keys << std::endl; exit(EXIT_FAILURE); } else if (child_num == num_keys) { return internal_node_right_child(); } else { return internal_node_cell(child_num); } } uint32_t *internal_node_key(uint32_t key_num) { return internal_node_cell(key_num) + INTERNAL_NODE_CHILD_SIZE; } uint32_t get_node_max_key() override { return *internal_node_key(*internal_node_num_keys() - 1); } }; uint32_t Node::get_node_max_key() { if (get_node_type() == NODE_LEAF) { LeafNode *leaf_node = (LeafNode *)this; return *leaf_node->leaf_node_key(*leaf_node->leaf_node_num_cells() - 1); } else { InternalNode *internal_node = (InternalNode *)this; return *internal_node->internal_node_key(*internal_node->internal_node_num_keys() - 1); } } class Pager { private: int file_descriptor; uint32_t file_length; void *pages[TABLE_MAX_PAGES]; uint32_t num_pages; public: Pager(const char *filename); void *get_page(uint32_t page_num); void pager_flush(uint32_t page_num); void print_tree(uint32_t page_num, uint32_t indentation_level); uint32_t get_unused_page_num(); friend class Table; }; Pager::Pager(const char *filename) { file_descriptor = open(filename, O_RDWR | // Read/Write mode O_CREAT, // Create file if it does not exist S_IWUSR | // User write permission S_IRUSR // User read permission ); if (file_descriptor < 0) { std::cerr << "Error: cannot open file " << filename << std::endl; exit(EXIT_FAILURE); } file_length = lseek(file_descriptor, 0, SEEK_END); num_pages = file_length / PAGE_SIZE; if (file_length % PAGE_SIZE != 0) { std::cerr << "Db file is not a whole number of pages. Corrupt file." << std::endl; exit(EXIT_FAILURE); } for (uint32_t i = 0; i < TABLE_MAX_PAGES; i++) { pages[i] = nullptr; } } void *Pager::get_page(uint32_t page_num) { if (page_num > TABLE_MAX_PAGES) { std::cout << "Tried to fetch page number out of bounds. " << page_num << " > " << TABLE_MAX_PAGES << std::endl; exit(EXIT_FAILURE); } if (pages[page_num] == nullptr) { // Cache miss. Allocate memory and load from file. void *page = malloc(PAGE_SIZE); uint32_t num_pages = file_length / PAGE_SIZE; // We might save a partial page at the end of the file if (file_length % PAGE_SIZE) { num_pages += 1; } if (page_num <= num_pages) { lseek(file_descriptor, page_num * PAGE_SIZE, SEEK_SET); ssize_t bytes_read = read(file_descriptor, page, PAGE_SIZE); if (bytes_read == -1) { std::cout << "Error reading file: " << errno << std::endl; exit(EXIT_FAILURE); } } pages[page_num] = page; if (page_num >= num_pages) { this->num_pages = page_num + 1; } } return pages[page_num]; } void Pager::pager_flush(uint32_t page_num) { if (pages[page_num] == nullptr) { std::cout << "Tried to flush null page" << std::endl; exit(EXIT_FAILURE); } off_t offset = lseek(file_descriptor, page_num * PAGE_SIZE, SEEK_SET); if (offset == -1) { std::cout << "Error seeking: " << errno << std::endl; exit(EXIT_FAILURE); } ssize_t bytes_written = write(file_descriptor, pages[page_num], PAGE_SIZE); if (bytes_written == -1) { std::cout << "Error writing: " << errno << std::endl; exit(EXIT_FAILURE); } } void indent(uint32_t level) { for (uint32_t i = 0; i < level; i++) { std::cout << " "; } } void Pager::print_tree(uint32_t page_num, uint32_t indentation_level) { Node *node = new Node(get_page(page_num)); uint32_t num_keys, child; switch (node->get_node_type()) { case (NODE_LEAF): num_keys = *((LeafNode *)node)->leaf_node_num_cells(); indent(indentation_level); std::cout << "- leaf (size " << num_keys << ")" << std::endl; for (uint32_t i = 0; i < num_keys; i++) { indent(indentation_level + 1); std::cout << "- " << *((LeafNode *)node)->leaf_node_key(i) << std::endl; } break; case (NODE_INTERNAL): num_keys = *((InternalNode *)node)->internal_node_num_keys(); indent(indentation_level); std::cout << "- internal (size " << num_keys << ")" << std::endl; for (uint32_t i = 0; i < num_keys; i++) { child = *((InternalNode *)node)->internal_node_child(i); print_tree(child, indentation_level + 1); indent(indentation_level + 1); std::cout << "- key " << *((InternalNode *)node)->internal_node_key(i) << std::endl; } child = *((InternalNode *)node)->internal_node_right_child(); print_tree(child, indentation_level + 1); break; } } /* Until we start recycling free pages, new pages will always go onto the end of the database file */ uint32_t Pager::get_unused_page_num() { return num_pages; } class Table; class Cursor { private: Table *table; uint32_t page_num; uint32_t cell_num; bool end_of_table; public: Cursor(Table *table); Cursor(Table *table, uint32_t page_num, uint32_t cell_num); void *cursor_value(); void cursor_advance(); void leaf_node_insert(uint32_t key, Row &value); void leaf_node_split_and_insert(uint32_t key, Row &value); friend class DB; }; class Table { private: uint32_t root_page_num; Pager pager; public: Table(const char *filename) : pager(filename) { root_page_num = 0; if (pager.num_pages == 0) { // New file. Initialize page 0 as leaf node. LeafNode root_node = pager.get_page(0); root_node.initialize_leaf_node(); root_node.set_node_root(true); } } Cursor *table_find(uint32_t key); Cursor *internal_node_find(uint32_t key, uint32_t page_num); void create_new_root(uint32_t right_child_page_num); ~Table(); friend class Cursor; friend class DB; }; Cursor::Cursor(Table *table) { Cursor *cursor = table->table_find(0); this->table = table; this->page_num = cursor->page_num; this->cell_num = cursor->cell_num; LeafNode root_node = table->pager.get_page(cursor->page_num); uint32_t num_cells = *root_node.leaf_node_num_cells(); this->end_of_table = (num_cells == 0); } Cursor::Cursor(Table *table, uint32_t page_num, uint32_t key) { this->table = table; this->page_num = page_num; this->end_of_table = false; LeafNode root_node = table->pager.get_page(page_num); uint32_t num_cells = *root_node.leaf_node_num_cells(); // Binary search uint32_t min_index = 0; uint32_t one_past_max_index = num_cells; while (one_past_max_index != min_index) { uint32_t index = (min_index + one_past_max_index) / 2; uint32_t key_at_index = *root_node.leaf_node_key(index); if (key == key_at_index) { this->cell_num = index; return; } if (key < key_at_index) { one_past_max_index = index; } else { min_index = index + 1; } } this->cell_num = min_index; } void *Cursor::cursor_value() { void *page = table->pager.get_page(page_num); return LeafNode(page).leaf_node_value(cell_num); } void Cursor::cursor_advance() { LeafNode leaf_node = table->pager.get_page(page_num); cell_num += 1; if (cell_num >= *leaf_node.leaf_node_num_cells()) { /* Advance to next leaf node */ uint32_t next_page_num = *leaf_node.leaf_node_next_leaf(); if (next_page_num == 0) { /* This was rightmost leaf */ end_of_table = true; } else { page_num = next_page_num; cell_num = 0; } } } void Cursor::leaf_node_insert(uint32_t key, Row &value) { LeafNode leaf_node = table->pager.get_page(page_num); uint32_t num_cells = *leaf_node.leaf_node_num_cells(); if (num_cells >= LEAF_NODE_MAX_CELLS) { // Node full leaf_node_split_and_insert(key, value); return; } if (cell_num < num_cells) { // make room for new cell for (uint32_t i = num_cells; i > cell_num; i--) { memcpy(leaf_node.leaf_node_cell(i), leaf_node.leaf_node_cell(i - 1), LEAF_NODE_CELL_SIZE); } } // insert new cell *leaf_node.leaf_node_num_cells() += 1; *leaf_node.leaf_node_key(cell_num) = key; serialize_row(value, leaf_node.leaf_node_value(cell_num)); } void Cursor::leaf_node_split_and_insert(uint32_t key, Row &value) { /* Create a new node and move half the cells over. Insert the new value in one of the two nodes. Update parent or create a new parent. */ LeafNode old_node = table->pager.get_page(page_num); uint32_t new_page_num = table->pager.get_unused_page_num(); LeafNode new_node = table->pager.get_page(new_page_num); new_node.initialize_leaf_node(); *new_node.leaf_node_next_leaf() = *old_node.leaf_node_next_leaf(); *old_node.leaf_node_next_leaf() = new_page_num; /* All existing keys plus new key should be divided evenly between old (left) and new (right) nodes. Starting from the right, move each key to correct position. */ for (int32_t i = LEAF_NODE_MAX_CELLS; i >= 0; i--) { LeafNode destination_node; if (i >= LEAF_NODE_LEFT_SPLIT_COUNT) { destination_node = new_node; } else { destination_node = old_node; } uint32_t index_within_node = i % LEAF_NODE_LEFT_SPLIT_COUNT; LeafNode destination = destination_node.leaf_node_cell(index_within_node); if (i == cell_num) { serialize_row(value, destination_node.leaf_node_value(index_within_node)); *destination_node.leaf_node_key(index_within_node) = key; } else if (i > cell_num) { memcpy(destination.get_node(), old_node.leaf_node_cell(i - 1), LEAF_NODE_CELL_SIZE); } else { memcpy(destination.get_node(), old_node.leaf_node_cell(i), LEAF_NODE_CELL_SIZE); } } /* Update cell count on both leaf nodes */ *old_node.leaf_node_num_cells() = LEAF_NODE_LEFT_SPLIT_COUNT; *new_node.leaf_node_num_cells() = LEAF_NODE_RIGHT_SPLIT_COUNT; if (old_node.is_node_root()) { return table->create_new_root(new_page_num); } else { std::cout << "Need to implement updating parent after split" << std::endl; exit(EXIT_FAILURE); } } Cursor *Table::internal_node_find(uint32_t page_num, uint32_t key) { InternalNode node = pager.get_page(page_num); uint32_t num_keys = *node.internal_node_num_keys(); /* Binary search to find index of child to search */ uint32_t min_index = 0; uint32_t max_index = num_keys; /* there is one more child than key */ while (max_index != min_index) { uint32_t index = (min_index + max_index) / 2; uint32_t key_to_right = *node.internal_node_key(index); if (key_to_right >= key) { max_index = index; } else { min_index = index + 1; } } uint32_t child_num = *node.internal_node_child(min_index); Node child = pager.get_page(child_num); switch (child.get_node_type()) { case NODE_INTERNAL: return internal_node_find(child_num, key); case NODE_LEAF: default: return new Cursor(this, child_num, key); } } Cursor *Table::table_find(uint32_t key) { Node root_node = pager.get_page(root_page_num); if (root_node.get_node_type() == NODE_LEAF) { return new Cursor(this, root_page_num, key); } else { return internal_node_find(root_page_num, key); } } void Table::create_new_root(uint32_t right_child_page_num) { /* Handle splitting the root. Old root copied to new page, becomes left child. Address of right child passed in. Re-initialize root page to contain the new root node. New root node points to two children. */ InternalNode root = pager.get_page(root_page_num); Node right_child = pager.get_page(right_child_page_num); uint32_t left_child_page_num = pager.get_unused_page_num(); Node left_child = pager.get_page(left_child_page_num); /* Left child has data copied from old root */ memcpy(left_child.get_node(), root.get_node(), PAGE_SIZE); left_child.set_node_root(false); /* Root node is a new internal node with one key and two children */ root.initialize_internal_node(); root.set_node_root(true); *root.internal_node_num_keys() = 1; *root.internal_node_child(0) = left_child_page_num; uint32_t left_child_max_key = left_child.get_node_max_key(); *root.internal_node_key(0) = left_child_max_key; *root.internal_node_right_child() = right_child_page_num; } Table::~Table() { for (uint32_t i = 0; i < pager.num_pages; i++) { if (pager.pages[i] == nullptr) { continue; } pager.pager_flush(i); free(pager.pages[i]); pager.pages[i] = nullptr; } int result = close(pager.file_descriptor); if (result == -1) { std::cout << "Error closing db file." << std::endl; exit(EXIT_FAILURE); } for (uint32_t i = 0; i < TABLE_MAX_PAGES; i++) { void *page = pager.pages[i]; if (page) { free(page); pager.pages[i] = nullptr; } } } class Statement { public: StatementType type; Row row_to_insert; }; class DB { private: Table *table; public: DB(const char *filename) { table = new Table(filename); } void start(); void print_prompt(); bool parse_meta_command(std::string &command); MetaCommandResult do_meta_command(std::string &command); PrepareResult prepare_insert(std::string &input_line, Statement &statement); PrepareResult prepare_statement(std::string &input_line, Statement &statement); bool parse_statement(std::string &input_line, Statement &statement); void execute_statement(Statement &statement); ExecuteResult execute_insert(Statement &statement); ExecuteResult execute_select(Statement &statement); ~DB() { delete table; } }; void DB::print_prompt() { std::cout << "db > "; } bool DB::parse_meta_command(std::string &command) { if (command[0] == '.') { switch (do_meta_command(command)) { case META_COMMAND_SUCCESS: return true; case META_COMMAND_UNRECOGNIZED_COMMAND: std::cout << "Unrecognized command: " << command << std::endl; return true; } } return false; } MetaCommandResult DB::do_meta_command(std::string &command) { if (command == ".exit") { delete (table); std::cout << "Bye!" << std::endl; exit(EXIT_SUCCESS); } else if (command == ".btree") { std::cout << "Tree:" << std::endl; Node root_node = table->pager.get_page(table->root_page_num); table->pager.print_tree(0, 0); return META_COMMAND_SUCCESS; } else if (command == ".constants") { std::cout << "Constants:" << std::endl; std::cout << "ROW_SIZE: " << ROW_SIZE << std::endl; std::cout << "COMMON_NODE_HEADER_SIZE: " << COMMON_NODE_HEADER_SIZE << std::endl; std::cout << "LEAF_NODE_HEADER_SIZE: " << LEAF_NODE_HEADER_SIZE << std::endl; std::cout << "LEAF_NODE_CELL_SIZE: " << LEAF_NODE_CELL_SIZE << std::endl; std::cout << "LEAF_NODE_SPACE_FOR_CELLS: " << LEAF_NODE_SPACE_FOR_CELLS << std::endl; std::cout << "LEAF_NODE_MAX_CELLS: " << LEAF_NODE_MAX_CELLS << std::endl; return META_COMMAND_SUCCESS; } else { return META_COMMAND_UNRECOGNIZED_COMMAND; } } PrepareResult DB::prepare_insert(std::string &input_line, Statement &statement) { statement.type = STATEMENT_INSERT; char *insert_line = (char *)input_line.c_str(); char *keyword = strtok(insert_line, " "); char *id_string = strtok(NULL, " "); char *username = strtok(NULL, " "); char *email = strtok(NULL, " "); if (id_string == NULL || username == NULL || email == NULL) { return PREPARE_SYNTAX_ERROR; } int id = atoi(id_string); if (id < 0) { return PREPARE_NEGATIVE_ID; } if (strlen(username) > COLUMN_USERNAME_SIZE) { return PREPARE_STRING_TOO_LONG; } if (strlen(email) > COLUMN_EMAIL_SIZE) { return PREPARE_STRING_TOO_LONG; } statement.row_to_insert = Row(id, username, email); return PREPARE_SUCCESS; } PrepareResult DB::prepare_statement(std::string &input_line, Statement &statement) { if (!input_line.compare(0, 6, "insert")) { return prepare_insert(input_line, statement); } else if (!input_line.compare(0, 6, "select")) { statement.type = STATEMENT_SELECT; return PREPARE_SUCCESS; } else { return PREPARE_UNRECOGNIZED_STATEMENT; } } bool DB::parse_statement(std::string &input_line, Statement &statement) { switch (prepare_statement(input_line, statement)) { case PREPARE_SUCCESS: return false; case (PREPARE_NEGATIVE_ID): std::cout << "ID must be positive." << std::endl; return true; case (PREPARE_STRING_TOO_LONG): std::cout << "String is too long." << std::endl; return true; case PREPARE_SYNTAX_ERROR: std::cout << "Syntax error. Could not parse statement." << std::endl; return true; case PREPARE_UNRECOGNIZED_STATEMENT: std::cout << "Unrecognized keyword at start of '" << input_line << "'." << std::endl; return true; } return false; } ExecuteResult DB::execute_insert(Statement &statement) { LeafNode leaf_node = table->pager.get_page(table->root_page_num); uint32_t num_cells = *leaf_node.leaf_node_num_cells(); Cursor *cursor = table->table_find(statement.row_to_insert.id); if (cursor->cell_num < num_cells) { uint32_t key_at_index = *leaf_node.leaf_node_key(cursor->cell_num); if (key_at_index == statement.row_to_insert.id) { return EXECUTE_DUPLICATE_KEY; } } cursor->leaf_node_insert(statement.row_to_insert.id, statement.row_to_insert); delete cursor; return EXECUTE_SUCCESS; } ExecuteResult DB::execute_select(Statement &statement) { // start of the table Cursor *cursor = new Cursor(table); Row row; while (!cursor->end_of_table) { deserialize_row(cursor->cursor_value(), row); std::cout << "(" << row.id << ", " << row.username << ", " << row.email << ")" << std::endl; cursor->cursor_advance(); } delete cursor; return EXECUTE_SUCCESS; } void DB::execute_statement(Statement &statement) { ExecuteResult result; switch (statement.type) { case STATEMENT_INSERT: result = execute_insert(statement); break; case STATEMENT_SELECT: result = execute_select(statement); break; } switch (result) { case EXECUTE_SUCCESS: std::cout << "Executed." << std::endl; break; case (EXECUTE_DUPLICATE_KEY): std::cout << "Error: Duplicate key." << std::endl; break; case EXECUTE_TABLE_FULL: std::cout << "Error: Table full." << std::endl; break; } } void DB::start() { while (true) { print_prompt(); std::string input_line; std::getline(std::cin, input_line); if (parse_meta_command(input_line)) { continue; } Statement statement; if (parse_statement(input_line, statement)) { continue; } execute_statement(statement); } } int main(int argc, char const *argv[]) { if (argc < 2) { std::cout << "Must supply a database filename." << std::endl; exit(EXIT_FAILURE); } DB db(argv[1]); db.start(); return 0; }
true
e629389b296643ee6d82429b4445afde41dde93e
C++
XiaotaoGuo/Leetcode-Solution-In-Cpp
/tree/medium/145.BinaryTreePostorderTraversal.cpp
UTF-8
1,800
3.609375
4
[ "Apache-2.0" ]
permissive
/* * @lc app=leetcode id=145 lang=cpp * * [145] Binary Tree Postorder Traversal * * https://leetcode.com/problems/binary-tree-postorder-traversal/description/ * * algorithms * Medium (55.73%) * Likes: 2082 * Dislikes: 104 * Total Accepted: 415.3K * Total Submissions: 742.6K * Testcase Example: '[1,null,2,3]' * * Given the root of a binary tree, return the postorder traversal of its * nodes' values. * * * Example 1: * * * Input: root = [1,null,2,3] * Output: [3,2,1] * * * Example 2: * * * Input: root = [] * Output: [] * * * Example 3: * * * Input: root = [1] * Output: [1] * * * Example 4: * * * Input: root = [1,2] * Output: [2,1] * * * Example 5: * * * Input: root = [1,null,2] * Output: [2,1] * * * * Constraints: * * * The number of the nodes in the tree is in the range [0, 100]. * -100 <= Node.val <= 100 * * * * * Follow up: * * Recursive solution is trivial, could you do it iteratively? * * * */ // @lc code=start /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), * right(right) {} * }; */ #include <stack> #include <vector> class Solution { public: std::vector<int> postorderTraversal(TreeNode* root) { std::vector<int> result; dfs(root, result); return result; } private: void dfs(TreeNode* root, std::vector<int>& result) { if (!root) return; dfs(root->left, result); dfs(root->right, result); result.push_back(root->val); } }; // @lc code=end
true
5f0cbc6813c8e121e616a9591f49d53eab58a03b
C++
dazhiwang/for-copying-line-number
/Desktop/EECS482/P1/p1.cpp
UTF-8
2,096
2.6875
3
[]
no_license
#include <iostream> #include <fstream> #include <sstream> #include <string> #include <cstdlib> #include <cstdio> #include <vector> #include <queue> #include <algorithm> #include <iomanip> #include <limits> #include <cmath> #include "thread.h" using namespace std; mutex mutex1; //mutex mutex2; cv cv1; cv cv2; int track = 0; int totalnum=0; int max_disk_queue; vector<thread> t2; vector<pair<int, int>> diskQueue; vector<queue<int>> disks; void requester(void* a){ intptr_t num= (intptr_t) a; //cout<<"222 "<<num<<endl; //mutex1.lock(); //mutex1.unlock(); mutex1.lock(); //cout<<"diskQueue size: "<<diskQueue.size()<<endl; //cout<<"totalnum: "<<totalnum<<endl; while(diskQueue.size()==max_disk_queue || totalnum==0){ cv1.wait(mutex1); } if(!disks[num].empty()){ cout<<"requester "<< num <<" track "<<disks[num].front()<<endl; diskQueue.push_back(make_pair(num, disks[num].front())); disks[num].pop(); totalnum--; } cv2.signal(); mutex1.unlock(); } void service_request(void* a){ //cout<<"111\n"; mutex1.lock(); for(int i=0; i<disks.size(); ++i){ thread t2 ((thread_startfunc_t) requester, (void *)i); } mutex1.unlock(); mutex1.lock(); while(diskQueue.size()<max_disk_queue && totalnum>0){ cv2.wait(mutex1); } int min=abs(track-diskQueue[0].second); int n=0; for(int i=1; i<diskQueue.size(); ++i){ if(abs(track-diskQueue[i].second) < min){ min=abs(track-diskQueue[i].second); n=i; } } track=diskQueue[n].second; cout<<"service requester "<<diskQueue[n].first<<" track "<<diskQueue[n].second<<endl; diskQueue.erase(diskQueue.begin()+n); cv1.signal(); mutex1.unlock(); } int main(int argc, char * argv[]){ max_disk_queue = atoi(argv[1]); for(int i=2; i<argc; ++i){ ifstream fs; fs.open(argv[i]); queue<int> tmp; int t; while(fs >> t){ tmp.push(t); totalnum++; } fs.close(); disks.push_back(tmp); //cout<<disks.back().size()<<endl; } cpu::boot((thread_startfunc_t) service_request, (void *) 0, 0); }
true
29b56e4b7cb8dd9fb719123df714175142cad15f
C++
coolnaut/CPP_program
/C++内存管理/C++内存管理/内存管理.h
GB18030
3,852
3.390625
3
[]
no_license
#pragma once #include<iostream> using namespace std; void CMemory() { //malloc(size_t ize) //ڶϷһ鳤Ϊsizeֽڵ //sizeΪҪڴռijȣظ׵ַ int* p1 = (int*)malloc(sizeof(int)); //calloc(size_t count, size_t size //ڶϷcountsizeֽڵ //ĿռеÿһλʼΪ int *p2 = (int*)calloc(1, sizeof(int)); //realloc(void *ptr, size_t size); //һѾ˵ַָ·ռ䣬ptrΪԭеĿռ int* p3 = (int*)realloc(p2, 3); } // void CppMemory() { int* p1 = new int; int * p2 = new int(10); int* p3 = new int[3]; } //Զ class MemoryTest { public: MemoryTest() :data_(0) {} private: int data_; }; void Test() { MemoryTest* t1 = (MemoryTest*)malloc(sizeof(MemoryTest)); new(t1) MemoryTest;//newλʽѷԭʼڴռеù캯ʼһ free(t1); MemoryTest* t2 = new MemoryTest; delete t2; MemoryTest* t3= new MemoryTest[3]; delete [] t3; } //λnewʽ //ѷԭʼڴռеù캯ʼһ class NewPress { public: NewPress() :data_(0) { cout << "λnewʽ" << endl; } private: int data_; }; //һֻ࣬ڶϴ //1. Ĺ캯˽У˽Сֹ˵ÿջɶ //2. ṩһ̬ijԱڸþ̬ԱɶѶĴ class HeapObj { public: //ɾ̬ģе static HeapObj getObj() { HeapObj* obj = new HeapObj;//ڶϽڴ return *obj; } private: HeapObj(); HeapObj(const HeapObj& d); int data_; }; //һֻ࣬ջϴ //1. Ĺ캯˽С //2. 첻ãΪǸѾеĶջɶ //2. ṩһ̬ijԱڸþ̬ԱջĴ class StackObj { static StackObj getObj() { return StackObj(); } private: StackObj() :data_(0) { } //ɾ operator new(size_t size)䲻ڶϴ void* operator new(size_t size) = delete; void operator delete(void* p) = delete; private: int data_; }; //ģʽ // //캯Ϳ캯˽ //һ̬Ա̬Աڳг֮ǰɳʼ //ṩһ̬ȡ̬Ա class Singleton { static Singleton& getObj() { return obj_; } private: static Singleton obj_;//ֱӶһԱΪ޷ĴСǷ Singleton() {}; Singleton(const Singleton &) = delete; }; Singleton Singleton::obj_ ; #include<mutex> class Singleton2 { public: static Singleton2* getObj() { if (obj2_ = nullptr)//μ飬Ч { mtx_.lock();//֤ڴֻһ if (obj2_ == nullptr) { obj2_ = new Singleton2; } mtx_.unlock(); } return obj2_; } class Gc//пޣͷԴ { public: ~Gc()//һڲΪڱеᷢݹ { if (obj2_) { delete obj2_; obj2_ = nullptr; } } }; private: Singleton2() {} Singleton2(const Singleton&) = delete; static Singleton2* obj2_;//ָֻռĸֽڣûж󣬵ҪʱŴ static mutex mtx_; }; Singleton2* Singleton2::obj2_ = nullptr; mutex Singleton2::mtx_;
true
79a4c85e4d4acb5eaea381d65d4120fa35bcd8d9
C++
thegamer1907/Code_Analysis
/CodesNew/4016.cpp
UTF-8
1,580
2.671875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int n, q; int search(long long int sum[], int left, int right, long long int key){ if (right < left){ return -1; } int mid = (left+right)/2; if (sum[mid] == key) { return mid+1; } if (sum[mid] > key) { if (mid > 0 && sum[mid-1] < key) { return mid; } if (mid == 0) { return 0; } return search(sum, left, mid-1, key); } if (mid < n-1 && sum[mid+1] > key) { return mid+1; } if (mid == n-1) { return n; } return search(sum, mid+1, right, key); } int main(){ scanf("%d%d", &n, &q); long long int a[n], arrow = 0; long long int sum[n]; for (int i = 0; i < n; i++) { scanf("%lld", a+i); } sum[0] = a[0]; for (int i = 1; i < n; i++) { sum[i] = sum[i-1]+a[i]; } int last = 0; int killed = 0; for (int i = 0; i < q; i++) { //last = arrow; scanf("%lld", &arrow); long long int index = arrow+((killed)?sum[killed-1]:0)+last; int key = search(sum, 0, n-1, index); if (key == n) { cout << n << endl; killed = 0; last = 0; continue; } if (key <= killed) { cout << n - killed << endl; last += arrow; continue; } else{ cout << n - key << endl; last = arrow-(sum[key-1] - ((killed)?sum[killed-1]:0))+last; killed = key; } } return 0; }
true
4de6524696eb9180e680239fa4e39021aeae3586
C++
theophie/AID
/sketch_nov29a.ino
UTF-8
2,410
2.640625
3
[]
no_license
const int pedalSensor =A0; const int snareSensor=A1; const int hihatSensor=A4; const int threshold = 300; int pS = 0; int sS=0; int hS=0; //int snareTimer = -1; int pedalTimer = -1; //int hihatTimer = -1; //int noteBuzz; // Data received from the serial port //int noteBuzzer; //char noteBuzzer[3]; void setup(){ Serial.begin(9600); // Start serial communication at 9600 bps } void loop(){ pS = analogRead(pedalSensor); sS=analogRead(snareSensor); hS=analogRead(hihatSensor); // if the sensor reading is greater than the threshold: // for(int i=0,i<3,i++){ if (hS >= threshold && pedalTimer == -1) { pedalTimer = 200; //map(pS, 0, 1023, 0, 100); //Serial.write(pS); Serial.write(1); } if (sS >= threshold && pedalTimer == -1) { pedalTimer = 200; //map(pS, 0, 1023, 0, 100); //Serial.write(pS); Serial.write(101); } if (pS >= threshold && pedalTimer == -1) { pedalTimer = 200; //map(pS, 0, 1023, 0, 100); //Serial.write(pS); Serial.write(201); } if(pedalTimer > 0) { pedalTimer--; if(pedalTimer == 0) { pedalTimer = -1; } } // if (pS >= threshold && pedalTimer == -1) { // map(pS, 0, 1023, 0, 100); // pedalTimer = 1000; // } // // if(pedalTimer > 0) { // pedalTimer--; // if(pedalTimer == 0) { // // pS = map(0, 0, 0, 0, 0); // pedalTimer = -1; // } // } // // if (sS >= threshold && snareTimer == -1) { // map(sS, 0, 1023, 0, 100); // snareTimer = 1000; // } // // if(snareTimer > 0) { // snareTimer--; // if(snareTimer == 0) { // // pS = map(0, 0, 0, 0, 0); // snareTimer = -1; // } // } // // if (hS >= threshold && hihatTimer == -1) { // map(hS, 0, 1023, 0, 100); // hihatTimer = 1000; // } // // if(hihatTimer > 0) { // hihatTimer--; // if(hihatTimer == 0) { // // pS = map(0, 0, 0, 0, 0); // hihatTimer = -1; // } // } // if (sS >= threshold) { // // map(sS, 0, 1023, 101, 200); // Serial.write(sS); // //delay(100); // // // //Serial.println(pS);// Stop sound... // } // if (hS >= threshold) { // // map(hS, 0, 1023, 201, 300); // Serial.write(hS); // //delay(100); // // // }
true
5e498449711c9ae9b99bfe09378464a8e65f4af0
C++
nicolasjinchereau/microwave
/core/source/MW/System/Window.ixx
UTF-8
3,740
2.5625
3
[]
no_license
/*--------------------------------------------------------------* * Copyright (c) 2022 Nicolas Jinchereau. All rights reserved. * *--------------------------------------------------------------*/ export module Microwave.System.Window; import Microwave.Graphics.RenderTarget; import Microwave.Math; import Microwave.System.Dispatcher; import Microwave.System.EventHandlerList; import Microwave.System.Object; import Microwave.System.Pointers; import <cstdint>; import <string>; import <vector>; export namespace mw { inline namespace gfx { class HWSurface; } inline namespace system { class App; class Window; enum class Keycode : int { A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, Num0, Num1, Num2, Num3, Num4, Num5, Num6, Num7, Num8, Num9, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, Back, Forward, VolumeUp, VolumeDown, VolumeMute, Space, Backspace, Del, LeftArrow, RightArrow, UpArrow, DownArrow, Alt, Ctrl, Shift, Enter, Escape, Equals, Minus, LeftBracket, RightBracket, Quote, Semicolon, Backslash, Comma, Slash, Period, Grave, Tab, // OS specific keycodes not included above will be returned from TranslateKey as (Keycode::Unknown + keycode) Unknown }; class IWindowEventHandler { public: virtual ~IWindowEventHandler() = default; virtual void OnCreate(Window* window) {} virtual void OnShow(Window* window) {} virtual void OnGotFocus(Window* window) {} virtual void OnLostFocus(Window* window) {} virtual void OnHide(Window* window) {} virtual void OnDestroy(Window* window) {} virtual void OnClose(Window* window) {} // window close button pressed virtual void OnMove(Window* window, IVec2 pos) {} virtual void OnResize(Window* window, IVec2 size) {} virtual void OnKeyDown(Window* window, Keycode key) {} virtual void OnKeyUp(Window* window, Keycode key) {} virtual void OnPointerDown(Window* window, IVec2 pos, int id) {} virtual void OnPointerMove(Window* window, IVec2 pos, int id) {} virtual void OnPointerUp(Window* window, IVec2 pos, int id) {} }; class Window : public RenderTarget { protected: static gptr<Window> New(const std::string title, const IVec2& pos, const IVec2& size); friend App; EventHandlerList<IWindowEventHandler> eventHandlers; mutable gptr<HWSurface> surface; public: virtual ~Window(){}; virtual void SetTitle(const std::string& title) = 0; virtual std::string GetTitle() const = 0; virtual void SetPos(const IVec2& pos) = 0; virtual IVec2 GetPos() const = 0; virtual void SetSize(const IVec2& size) = 0; //virtual IVec2 GetSize() const = 0; virtual bool IsVisible() const = 0; virtual void SetResizeable(bool resizeable) = 0; virtual bool IsResizeable() const = 0; virtual void Show() = 0; virtual void Hide() = 0; virtual void Close() = 0; virtual uintptr_t GetHandle() const = 0; virtual void AddEventHandler(const gptr<IWindowEventHandler>& handler); virtual void RemoveEventHandler(const gptr<IWindowEventHandler>& handler); virtual void OnCreate(); virtual void OnShow(); virtual void OnGotFocus(); virtual void OnLostFocus(); virtual void OnHide(); virtual void OnDestroy(); virtual void OnClose(); virtual void OnMove(IVec2 pos); virtual void OnResize(IVec2 size); virtual void OnKeyDown(Keycode key); virtual void OnKeyUp(Keycode key); virtual void OnPointerDown(IVec2 pos, int id); virtual void OnPointerMove(IVec2 pos, int id); virtual void OnPointerUp(IVec2 pos, int id); }; } // system } // mw
true
9c54d1e2fef1673d0e4ac0b5d2a6f97c1b8a0dde
C++
cburris2/csci333-lab1
/pe1.cpp
UTF-8
240
2.875
3
[]
no_license
#include <iostream> using std::cout; using std::endl; int add(int a); int main(){ cout<< add(1000) << endl; return 0; } int add(int a){ int sum=0; for (int i=0; i<a; i++) { if (i%3==0 || i%5==0) { sum+=i; } } return sum; }
true
5e330d0ec61ac934b39659dd8258d6992276a31c
C++
coderdamin/PAT-Basic-Level-Practise
/C++/1009.cpp
GB18030
1,439
3.640625
4
[]
no_license
// // һӢҪд򣬽еʵ˳ߵ //ʽ // һһڸܳȲ80ַַɵʺɿոɣеӢĸСд֣ɵַ // ֮1ոֿ뱣֤ĩβûжĿո //ʽ // ÿռһУľӡ // // Hello World Here I Come // // Come I Here World Hello #include <iostream> using namespace std; #define SWAP(val1, val2) \ {\ val1 ^= val2; \ val2 ^= val1; \ val1 ^= val2; \ } void Solution_1(); void Solution_2(); int main() { Solution_1(); } void Solution_1() { char acInput[81] = { 0 }; cin.getline(acInput, 80); unsigned char uLen = strlen(acInput); for (int i = 0; i < (uLen >> 1); ++i) { SWAP(acInput[i], acInput[uLen - 1 - i]); } unsigned char uPosBegin = 0; for (int i = 0; i < uLen; ++i) { if (acInput[i] == ' ' || (i == (uLen - 1) && ++i)) { for (int j = uPosBegin; j < ((uPosBegin + i - 1) >> 1); ++j) { SWAP(acInput[j], acInput[uPosBegin + i - 1 - j]); } uPosBegin = i + 1; } } cout << acInput << endl; return 0; } void Solution_2() { // ʴбȻ }
true
1c4a3121f853d9cda52e5247938725038e91ac14
C++
24380974/dpdk_router-1
/test/test.cc
UTF-8
1,760
3.078125
3
[ "Apache-2.0" ]
permissive
#include <limits.h> #include <gtest/gtest.h> extern "C" { #include "../router.h" #include "../routing_table.h" } #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> struct ether_addr port_id_to_mac[4]; void check_address(uint8_t a, uint8_t b, uint8_t c, uint8_t d, int next_hop) { int ip = IPv4(a,b,c,d); struct routing_table_entry* info = get_next_hop(ip); ASSERT_TRUE(info != NULL) << "entry for " << (int) a << "." << (int) b << "." << (int) c << "." << (int) d << " is null"; EXPECT_EQ(next_hop, info->dst_port) << ip << " failed"; EXPECT_EQ(0, memcmp(&info->dst_mac, &port_id_to_mac[next_hop], sizeof(struct ether_addr))) << ip << " failed"; print_routing_table_entry(info); } TEST(VERY_SIMPLE_TEST, SIMPLE_ADDRESSES) { // create dummy mac addresses for (int i = 0; i < 4; ++i) { for (int a = 0; a < 6; ++a) { port_id_to_mac[i].addr_bytes[a] = (uint8_t) i*10; } } // init routing table stuff printf("Try to add routes.\n"); add_route(IPv4(10,0,10,0), 24, &port_id_to_mac[0], 0); add_route(IPv4(10,0,10,128), 32, &port_id_to_mac[2], 2); add_route(IPv4(10,0,10,129), 32, &port_id_to_mac[3], 3); add_route(IPv4(10,0,40,10), 32, &port_id_to_mac[1], 1); printf("Routes added.\n"); // call once before test build_routing_table(); print_next_hop_tab(); // test cases check_address(10, 0, 40, 10, 1); EXPECT_EQ(NULL, get_next_hop(IPv4(10,0,9,255))); for(int i = 0; i < 256; ++i) { if(i == 128) check_address(10, 0, 10, i%256, 2); else if(i == 129) check_address(10, 0, 10, i%256, 3); else check_address(10, 0, 10, i%256, 0); } EXPECT_EQ(NULL, get_next_hop(IPv4(10,0,11,0))); } int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
true
342abf21ccfdc5be9bac123cc8c86f71915ba718
C++
NightHunters/Drawer_console
/Canvas.cpp
GB18030
19,117
2.828125
3
[]
no_license
#include "Canvas.h" #include<iostream> using namespace std; Canvas::Canvas() { pen.setColor(QColor(0, 0, 0, 255)); height = 0; width = 0; flag = false; } void Canvas::resetCanvas(int wid, int hei) { width = wid; height = hei; QPixmap p(wid, hei); pix = p.copy(); pix.fill(QColor(255, 255, 255, 255)); flag = true; } void Canvas::saveCanvas(string name) { string pic_name = name + ".bmp"; pix.save(pic_name.c_str()); } void Canvas::setColor(int r, int g, int b) { pen.setColor(QColor(r, g, b)); } void Canvas::translate(int dx,int dy,vector<Command>::iterator it) { if (strcmp(it->argv[0], "drawLine") == 0)//ƽ߶ { int temp = 0; temp = atoi(it->argv[2]); temp += dx; itoa(temp, it->argv[2], 10); temp = atoi(it->argv[3]); temp += dy; itoa(temp, it->argv[3], 10); temp = atoi(it->argv[4]); temp += dx; itoa(temp, it->argv[4], 10); temp = atoi(it->argv[5]); temp += dy; itoa(temp, it->argv[5], 10); } else if (strcmp(it->argv[0], "drawPolygon") == 0)//ƽƶ { int temp = 0; int n = atoi(it->argv[2]); for (int i = 0; i < n; i++) { temp = atoi(it->argv[4 + i * 2]); temp += dx; itoa(temp, it->argv[4 + i * 2], 10); } for (int i = 0; i < n; i++) { temp = atoi(it->argv[5 + i * 2]); temp += dy; itoa(temp, it->argv[5 + i * 2], 10); } } else if (strcmp(it->argv[0], "drawEllipse") == 0)//ƽԲ { int temp = 0; temp = atoi(it->argv[2]); temp += dx; itoa(temp, it->argv[2], 10); temp = atoi(it->argv[3]); temp += dy; itoa(temp, it->argv[3], 10); } else if (strcmp(it->argv[0], "drawCurve") == 0)//ƽ { int temp = 0; int n = atoi(it->argv[2]); for (int i = 0; i < n; i++) { temp = atoi(it->argv[4 + i * 2]); temp += dx; itoa(temp, it->argv[4 + i * 2], 10); } for (int i = 0; i < n; i++) { temp = atoi(it->argv[5 + i * 2]); temp += dy; itoa(temp, it->argv[5 + i * 2], 10); } } } void Canvas::rotate(int x, int y, double a, vector<Command>::iterator it) { if (strcmp(it->argv[0], "drawLine") == 0)//ת߶ { double temp = 0; int temp_x = 0, temp_y = 0;//¼ؼ temp_x = atoi(it->argv[2]); temp_y = atoi(it->argv[3]); temp = x + (temp_x - x)*cos(a) - (temp_y - y)*sin(a); itoa(int(temp + 0.5), it->argv[2], 10); temp = y + (temp_x - x)*sin(a) + (temp_y - y)*cos(a); itoa(int(temp + 0.5), it->argv[3], 10); temp_x = atoi(it->argv[4]); temp_y = atoi(it->argv[5]); temp = x + (temp_x - x)*cos(a) - (temp_y - y)*sin(a); itoa(int(temp + 0.5), it->argv[4], 10); temp = y + (temp_x - x)*sin(a) + (temp_y - y)*cos(a); itoa(int(temp + 0.5), it->argv[5], 10); } else if (strcmp(it->argv[0], "drawPolygon") == 0)//ת { double temp = 0; int temp_x = 0, temp_y = 0; int n = atoi(it->argv[2]); for (int i = 0; i < n; i++) { temp_x = atoi(it->argv[4 + i * 2]); temp_y = atoi(it->argv[5 + i * 2]); temp = x + (temp_x - x)*cos(a) - (temp_y - y)*sin(a); itoa(int(temp + 0.5), it->argv[4 + i * 2], 10); temp = y + (temp_x - x)*sin(a) + (temp_y - y)*cos(a); itoa(int(temp + 0.5), it->argv[5 + i * 2], 10); } } else if (strcmp(it->argv[0], "drawCurve") == 0)//ת { double temp = 0; int temp_x = 0, temp_y = 0; int n = atoi(it->argv[2]); for (int i = 0; i < n; i++) { temp_x = atoi(it->argv[4 + i * 2]); temp_y = atoi(it->argv[5 + i * 2]); temp = x + (temp_x - x)*cos(a) - (temp_y - y)*sin(a); itoa(int(temp + 0.5), it->argv[4 + i * 2], 10); temp = y + (temp_x - x)*sin(a) + (temp_y - y)*cos(a); itoa(int(temp + 0.5), it->argv[5 + i * 2], 10); } } } void Canvas::scale(int x, int y, float s, vector<Command>::iterator it) { if (strcmp(it->argv[0], "drawLine") == 0)//߶ { int temp = 0; float transfer_to = 0; temp = atoi(it->argv[2]); transfer_to = temp*s + x*(1 - s); itoa(int(transfer_to + 0.5), it->argv[2], 10); temp = atoi(it->argv[3]); transfer_to = temp*s + y*(1 - s); itoa(int(transfer_to + 0.5), it->argv[3], 10); temp = atoi(it->argv[4]); transfer_to = temp*s + x*(1 - s); itoa(int(transfer_to + 0.5), it->argv[4], 10); temp = atoi(it->argv[5]); transfer_to = temp*s + y*(1 - s); itoa(int(transfer_to + 0.5), it->argv[5], 10); } else if (strcmp(it->argv[0], "drawPolygon") == 0)//Ŷ { int temp = 0; float transfer_to = 0; int n = atoi(it->argv[2]); for (int i = 0; i < n; i++) { temp = atoi(it->argv[4 + i * 2]); transfer_to = temp*s + x*(1 - s); itoa(int(transfer_to + 0.5), it->argv[4 + i * 2], 10); } for (int i = 0; i < n; i++) { temp = atoi(it->argv[5 + i * 2]); transfer_to = temp*s + y*(1 - s); itoa(int(transfer_to + 0.5), it->argv[5 + i * 2], 10); } } else if (strcmp(it->argv[0], "drawEllipse") == 0)//Բ { int temp = 0; float transfer_to = 0; temp = atoi(it->argv[2]); transfer_to = temp*s + x*(1 - s); itoa(int(transfer_to + 0.5), it->argv[2], 10); temp = atoi(it->argv[3]); transfer_to = temp*s + y*(1 - s); itoa(int(transfer_to + 0.5), it->argv[3], 10);//ĵ temp = atoi(it->argv[4]); transfer_to = temp*s; itoa(int(transfer_to + 0.5), it->argv[4], 10); temp = atoi(it->argv[5]); transfer_to = temp*s; itoa(int(transfer_to + 0.5), it->argv[5], 10);//ų뾶 } else if (strcmp(it->argv[0], "drawCurve") == 0)// { int temp = 0; float transfer_to = 0; int n = atoi(it->argv[2]); for (int i = 0; i < n; i++) { temp = atoi(it->argv[4 + i * 2]); transfer_to = temp*s + x*(1 - s); itoa(int(transfer_to + 0.5), it->argv[4 + i * 2], 10); } for (int i = 0; i < n; i++) { temp = atoi(it->argv[5 + i * 2]); transfer_to = temp*s + y*(1 - s); itoa(int(transfer_to + 0.5), it->argv[5 + i * 2], 10); } } } void Canvas::clip_by_cohen_sutherland(int xL, int yB, int xR, int yT, vector<Command>::iterator &it) { if (strcmp(it->argv[0], "drawLine") == 0)//߶ { double x1 = atoi(it->argv[2]); double y1 = atoi(it->argv[3]); double x2 = atoi(it->argv[4]); double y2 = atoi(it->argv[5]); for (int i = 0; i < 4; i++) { int area_code1 = 0, area_code2 = 0;// if (x1 < xL) area_code1 |= 0b0001; if (x1 > xR) area_code1 |= 0b0010; if (y1 < yB) area_code1 |= 0b0100; if (y1 > yT) area_code1 |= 0b1000; if (x2 < xL) area_code2 |= 0b0001; if (x2 > xR) area_code2 |= 0b0010; if (y2 < yB) area_code2 |= 0b0100; if (y2 > yT) area_code2 |= 0b1000; if (area_code1 == 0 && area_code2 == 0)//߶ȫڴ { itoa(int(x1 + 0.5), it->argv[2], 10); itoa(int(y1 + 0.5), it->argv[3], 10); itoa(int(x2 + 0.5), it->argv[4], 10); itoa(int(y2 + 0.5), it->argv[5], 10); return; } if ((area_code1 & area_code2) != 0) { cout << "߶βڲüڣ" << endl; //itoa(0, it->argv[6], 10); strcpy(it->argv[1], "hide"); return; } if (area_code1 == 0)//P1P2 { double temp = 0; temp = x1; x1 = x2; x2 = temp; temp = y1; y1 = y2; y2 = temp; temp = area_code1; area_code1 = area_code2; area_code2 = temp; } if ((area_code1 & 0b1000) != 0) { x1 = (yT - y1)*(x1 - x2) / (y1 - y2) + x1; y1 = yT; } else if ((area_code1 & 0b0100) != 0) { x1 = (yB - y1)*(x1 - x2) / (y1 - y2) + x1; y1 = yB; } else if ((area_code1 & 0b0010) != 0) { y1 = (xR - x1)*(y1 - y2) / (x1 - x2) + y1; x1 = xR; } else if ((area_code1 & 0b0001) != 0) { y1 = (xL - x1)*(y1 - y2) / (x1 - x2) + y1; x1 = xL; } } } } void Canvas::update_u(double p, double q, double &u1, double &u2) { double r = 0; if (p < 0) { r = q / p; if (r > u1) u1 = r; } else if (p > 0) { r = q / p; if (r < u2) u2 = r; } else { if (q < 0) { cout << "߶βڲüڣ" << endl; return; } } } void Canvas::clip_by_liang_barsky(int xL, int yB, int xR, int yT, vector<Command>::iterator &it) { if (strcmp(it->argv[0], "drawLine") == 0)//߶ { double x1 = atoi(it->argv[2]); double y1 = atoi(it->argv[3]); double x2 = atoi(it->argv[4]); double y2 = atoi(it->argv[5]); double p1 = x1 - x2; double p2 = x2 - x1; double p3 = y1 - y2; double p4 = y2 - y1; double q1 = x1 - xL; double q2 = xR - x1; double q3 = y1 - yB; double q4 = yT - y1; double u1 = 0, u2 = 1; update_u(p1, q1, u1, u2); update_u(p2, q2, u1, u2); update_u(p3, q3, u1, u2); update_u(p4, q4, u1, u2); if (u1 <= u2) { double temp_x = x1 + u1*p2; double temp_y = y1 + u1*p4; itoa(int(temp_x + 0.5), it->argv[2], 10); itoa(int(temp_y + 0.5), it->argv[3], 10); temp_x = x1 + u2*p2; temp_y = y1 + u2*p4; itoa(int(temp_x + 0.5), it->argv[4], 10); itoa(int(temp_y + 0.5), it->argv[5], 10); } else { cout << "߶βڲüڣ" << endl; //itoa(0, it->argv[6], 10); strcpy(it->argv[1], "hide"); return; } } } void Canvas::preprocess(string commandfile, string savepath)//ͼԪ任 { ifstream fin(commandfile); if (!fin) { cout << "ļʧܣ" << endl; return; } vector<Command>::iterator it; Command c; Command c1; while (fin >> c) { vector<Command>::iterator outset = vec.begin();//ǵ if (strcmp(c.argv[0], "translate") == 0)//ƽ { int dx = atoi(c.argv[2]); int dy = atoi(c.argv[3]); for (it = outset; it != vec.end(); it++) { if (strcmp(it->argv[1], c.argv[1]) == 0) { translate(dx, dy, it); } } } else if (strcmp(c.argv[0], "rotate") == 0)//ת { int x = atoi(c.argv[2]); int y = atoi(c.argv[3]);//ת int r = atoi(c.argv[4]);//תǶ double pi = 4.0*atan(1); double a = r*pi / 180;//Ƕת for (it = outset; it != vec.end(); it++) { if (strcmp(it->argv[1], c.argv[1]) == 0) { rotate(x, y, a, it); } } } else if (strcmp(c.argv[0], "scale") == 0)// { int x = atoi(c.argv[2]); int y = atoi(c.argv[3]); float s = atof(c.argv[4]); for (it = outset; it != vec.end(); it++) { if (strcmp(it->argv[1], c.argv[1]) == 0) { scale(x, y, s, it); } } } else if (strcmp(c.argv[0], "clip") == 0)//߶βü { int xL = atoi(c.argv[2]); int yB = atoi(c.argv[3]); int xR = atoi(c.argv[4]); int yT = atoi(c.argv[5]); if (strcmp(c.argv[6], "Cohen-Sutherland") == 0) { for (it = outset; it != vec.end(); it++) { if (strcmp(it->argv[1], c.argv[1]) == 0) { clip_by_cohen_sutherland(xL, yB, xR, yT, it); } } } else if (strcmp(c.argv[6], "Liang-Barsky") == 0) { for (it = outset; it != vec.end(); it++) { if (strcmp(it->argv[1], c.argv[1]) == 0) { clip_by_liang_barsky(xL, yB, xR, yT, it); } } } } else if (strcmp(c.argv[0], "resetCanvas") == 0) { vec.push_back(c); outset = vec.end() - 1; } else if (strcmp(c.argv[0], "saveCanvas") == 0) { process(outset); if (!flag) { cout << "û" << endl; continue; } string fullpicture;//ͼƬַ fullpicture = savepath + c.argv[1]; saveCanvas(fullpicture); } else if (strcmp(c.argv[0], "drawPolygon") == 0) { fin >> c1; c.add_command(c1); vec.push_back(c); } else if (strcmp(c.argv[0], "drawCurve") == 0) { fin >> c1; c.add_command(c1); vec.push_back(c); } else vec.push_back(c); } cout << "over" << endl; fin.close(); } void Canvas::process(vector<Command>::iterator outset) { vector<Command>::iterator it; for (it = outset; it != vec.end(); it++) { Command c= *it; if (strcmp(c.argv[0], "resetCanvas") == 0)//û { int width, height; width = atoi(c.argv[1]); height = atoi(c.argv[2]); if (width < 10 || width>1000 || height < 10 || height>1000) { cout << "ƣΧ[10,1000]" << endl; continue; } resetCanvas(width, height); } else if (strcmp(c.argv[0], "setColor") == 0)//ûɫ { int r, g, b; r = atoi(c.argv[1]); g = atoi(c.argv[2]); b = atoi(c.argv[3]); if (r < 0 || r>255 || g < 0 || g>255 || b < 0 || b>255) { cout << "ȷRGBֵΧ[0,255]" << endl; continue; } setColor(r, g, b); } else if (strcmp(c.argv[0], "drawLine") == 0)//߶ { if (!flag) { cout << "û" << endl; continue; } if (strcmp(c.argv[1], "hide") != 0) { int x1, y1, x2, y2; x1 = atoi(c.argv[2]); y1 = atoi(c.argv[3]); x2 = atoi(c.argv[4]); y2 = atoi(c.argv[5]); if (x1<0 || x1>width || x2<0 || x2>width || y1<0 || y1>height || y2<0 || y2>height) { cout << "߶ζ˵㲻ܳΧ" << endl; continue; } if (strcmp(c.argv[6], "DDA") == 0) { Paint p(&pix); p.setPen(pen); p.drawline_DDA(x1, y1, x2, y2); } else if (strcmp(c.argv[6], "Bresenham") == 0) { Paint p(&pix); p.setPen(pen); p.drawline_Bresenham(x1, y1, x2, y2); } } } else if (strcmp(c.argv[0], "drawPolygon") == 0)//ƶ { if (!flag) { cout << "û" << endl; continue; } int n = atoi(c.argv[2]); int *x = new int[n]; int *y = new int[n]; for (int i = 0; i < n; i++) { x[i] = atoi(c.argv[2 * i + 4]); y[i] = atoi(c.argv[2 * i + 5]); } if (strcmp(c.argv[3], "DDA") == 0) { Paint p(&pix); p.setPen(pen); p.drawpolygon_DDA(n, x, y); } else if (strcmp(c.argv[3], "Bresenham") == 0) { Paint p(&pix); p.setPen(pen); p.drawpolygon_Bresenham(n, x, y); } } else if (strcmp(c.argv[0], "drawEllipse") == 0)//Բ { int x, y, rx, ry; x = atoi(c.argv[2]); y = atoi(c.argv[3]); rx = atoi(c.argv[4]); ry = atoi(c.argv[5]); Paint p(&pix); p.setPen(pen); p.drawellipse(x, y, rx, ry); } else if (strcmp(c.argv[0], "drawCurve") == 0) { if (!flag) { cout << "û" << endl; continue; } int n = atoi(c.argv[2]); int *x = new int[n]; int *y = new int[n]; for (int i = 0; i < n; i++) { x[i] = atoi(c.argv[2 * i + 4]); y[i] = atoi(c.argv[2 * i + 5]); } if (strcmp(c.argv[3], "Bezier") == 0) { Paint p(&pix); p.setPen(pen); p.drawcurse_Bezier(n, x, y); } else if (strcmp(c.argv[3], "B-spline") == 0) { Paint p(&pix); p.setPen(pen); p.drawcurse_B_spline(n, x, y); } } else//ʵֹ { cout << "ܾڴ" << endl; } } } void Canvas::identify_command_by_file(string commandfile,string savepath) { ifstream fin(commandfile); if (!fin) { cout << "ļʧܣ" << endl; return; } Command c; while (fin >> c) { if (strcmp(c.argv[0], "resetCanvas") == 0)//û { int width, height; width = atoi(c.argv[1]); height = atoi(c.argv[2]); if (width < 10 || width>1000 || height < 10 || height>1000) { cout << "ƣΧ[10,1000]" << endl; continue; } resetCanvas(width, height); } else if (strcmp(c.argv[0], "saveCanvas") == 0)//滭 { if (!flag) { cout << "û" << endl; continue; } string fullpicture;//ͼƬַ fullpicture = savepath + c.argv[1]; saveCanvas(fullpicture); } else if (strcmp(c.argv[0], "setColor") == 0)//ûɫ { int r, g, b; r = atoi(c.argv[1]); g = atoi(c.argv[2]); b = atoi(c.argv[3]); if (r < 0 || r>255 || g < 0 || g>255 || b < 0 || b>255) { cout << "ȷRGBֵΧ[0,255]" << endl; continue; } setColor(r, g, b); } else if (strcmp(c.argv[0], "drawLine") == 0)//߶ { if (!flag) { cout << "û" << endl; continue; } int x1, y1, x2, y2; x1 = atoi(c.argv[2]); y1 = atoi(c.argv[3]); x2 = atoi(c.argv[4]); y2 = atoi(c.argv[5]); if (x1<0 || x1>width || x2<0 || x2>width || y1<0 || y1>height || y2<0 || y2>height) { cout << "߶ζ˵㲻ܳΧ" << endl; continue; } if (strcmp(c.argv[6], "DDA") == 0) { Paint p(&pix); p.setPen(pen); p.drawline_DDA(x1, y1, x2, y2); } else if (strcmp(c.argv[6], "Bresenham") == 0) { Paint p(&pix); p.setPen(pen); p.drawline_Bresenham(x1, y1, x2, y2); } else cout << "δʵ㷨" << endl; } else if (strcmp(c.argv[0], "drawPolygon") == 0)//ƶ { if (!flag) { cout << "û" << endl; continue; } int n = atoi(c.argv[2]); int *x = new int[n]; int *y = new int[n]; for (int i = 0; i < n; i++) { x[i] = atoi(c.argv[2 * i + 4]); y[i] = atoi(c.argv[2 * i + 5]); } if (strcmp(c.argv[3], "DDA") == 0) { Paint p(&pix); p.setPen(pen); p.drawpolygon_DDA(n, x, y); } else if (strcmp(c.argv[3], "Bresenham") == 0) { Paint p(&pix); p.setPen(pen); p.drawpolygon_Bresenham(n,x,y); } } else if (strcmp(c.argv[0], "drawEllipse") == 0)//Բ { int x, y, rx, ry; x = atoi(c.argv[2]); y = atoi(c.argv[3]); rx = atoi(c.argv[4]); ry = atoi(c.argv[5]); Paint p(&pix); p.setPen(pen); p.drawellipse(x, y, rx, ry); } else if (strcmp(c.argv[0], "drawCurve") == 0) { if (!flag) { cout << "û" << endl; continue; } int n = atoi(c.argv[2]); int *x = new int[n]; int *y = new int[n]; for (int i = 0; i < n; i++) { x[i] = atoi(c.argv[2 * i + 4]); y[i] = atoi(c.argv[2 * i + 5]); } if (strcmp(c.argv[3], "Bezier") == 0) { Paint p(&pix); p.setPen(pen); p.drawcurse_Bezier(n, x, y); } else if (strcmp(c.argv[3], "B-spline") == 0) { Paint p(&pix); p.setPen(pen); p.drawcurse_B_spline(n, x, y); } } else//ʵֹ { cout << "ܾڴ" << endl; } } fin.close(); cout << "over" << endl; } void Canvas::test() { string commandfile, savepath; cin >> commandfile >> savepath; //identify_command_by_file(commandfile,savepath); preprocess(commandfile,savepath); }
true
dafab43665a6266a1cbd17f596ae2d82282ac26b
C++
nrupprecht/Manta
/include/manta/parser/ParseNode.h
UTF-8
696
2.890625
3
[]
no_license
// // Created by Nathaniel Rupprecht on 2/2/21. // #pragma once #include "manta/utility/ParserUtility.hpp" namespace manta { struct ParseNode { explicit ParseNode(const std::string& designator); ParseNode &operator=(const ParseNode &node); void Add(const std::string &str); void Add(const std::shared_ptr<ParseNode> &node); std::string printTerminals() const; std::string printTree(int level = 0) const; //! Node label. std::string designator; //! \brief All the children of the Node. std::vector<std::shared_ptr<ParseNode>> children; }; //! \brief Stream operator to write a ParseNode. std::ostream &operator<<(std::ostream &out, const ParseNode &node); } // namespace manta
true
b082815c1d9f30b726ea2915ec001a79ad6b48ea
C++
oyefremov/hana
/include/boost/hana/detail/array.hpp
UTF-8
1,215
2.96875
3
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
/*! @file Defines `boost::hana::detail::array`. @copyright Louis Dionne 2015 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_HANA_DETAIL_ARRAY_HPP #define BOOST_HANA_DETAIL_ARRAY_HPP #include <boost/hana/detail/std/size_t.hpp> namespace boost { namespace hana { namespace detail { //! @ingroup group-details //! A minimal `std::array` with better `constexpr` support. template <typename T, detail::std::size_t Size> struct array { constexpr T& operator[](detail::std::size_t n) { return elems_[n]; } constexpr T const& operator[](detail::std::size_t n) const { return elems_[n]; } constexpr detail::std::size_t size() const noexcept { return Size; } T elems_[Size > 0 ? Size : 1]; constexpr T* begin() noexcept { return elems_; } constexpr T const* begin() const noexcept { return elems_; } constexpr T* end() noexcept { return elems_ + Size; } constexpr T const* end() const noexcept { return elems_ + Size; } }; }}} // end namespace boost::hana::detail #endif // !BOOST_HANA_DETAIL_ARRAY_HPP
true
3665dfe56d80b7181f1001704a5cc061f9666cac
C++
barks333/codechef
/flow14.cpp
UTF-8
365
2.546875
3
[]
no_license
#include<iostream> using namespace std; int main() { int t; float h,cc,ts; cin>>t; while(t--) { cin>>h>>cc>>ts; if(h>50 && cc<0.7 && ts>5600) cout<<10<<endl; else if(h>50 && cc<0.7) cout<<9<<endl; else if(cc<0.7 and ts>5600) cout<<8<<endl; else if(h>50 and ts>5600) cout<<7<<endl; else if(h>50 || cc<0.7 || ts>5600) cout<<6<<endl; else cout<<5<<endl; } return 0; }
true
226a46e38f80f3b3683eee052cc1174ae75b9dc2
C++
CaptainTsao/ts
/src/time_series_reader.cpp
UTF-8
5,049
2.9375
3
[]
no_license
// // Created by transwarp on 2021/6/22. // #include "time_series_reader.h" #include <iomanip> #include <boost/lexical_cast.hpp> std::vector<std::string> ReadHeader(std::ifstream &in_file, CsvFileDefinition &definition) { std::vector<std::string> result; std::string header_line; std::getline(in_file, header_line); size_t position = 0; do { position = header_line.find(definition.Separator); auto col_name = header_line.substr(0, position); header_line.erase(0, position + definition.Separator.length()); result.push_back(col_name); } while (std::string::npos != position); definition.Header = result; return result; } SharedTimeSeriesPtr TimeSeriesReaderCSV::Read(File &file, const int max_rows) { /* Initialize time series */ auto result = std::make_shared<TimeSeries>(file.GetPath()); result->init(definition_.Columns); result->SetDecimals(definition_.Decimals); /* Open file and set last position */ std::ifstream input_file(file.GetPath(), std::ios::in); input_file.seekg(last_file_position_, input_file.beg); /* Read header */ std::vector<std::string> header; if (definition_.HasHeader && last_file_position_ == 0) { header = ReadHeader(input_file, definition_); } else { header = definition_.Header; } result->SetColumnNames(header); std::string line, token; size_t position = 0; int count = 0; while ((count++ < max_rows) && std::getline(input_file, line)) { std::vector<std::string> record; do { position = line.find(definition_.Separator); token = line.substr(0, position); line.erase(0, position + definition_.Separator.length()); record.push_back(token); } while (position != std::string::npos); result->AddRecord(record); record.clear(); } last_file_position_ = input_file.tellg(); input_file.close(); return result; } void WriteLine(std::ofstream &ofstm, std::vector<std::string> line_items, CsvFileDefinition &definition) { std::string line; for (int i = 0; i < line_items.size(); ++i) { line += line_items[i]; if (i < line_items.size() - 1) line += definition.Separator; } ofstm << line << std::endl; } void TimeSeriesReaderCSV::Write(File &file, TimeSeries &time_series) { std::ofstream out_file(file.GetPath(), std::ios::app); /* Write header as columns names */ if (definition_.HasHeader) { WriteLine(out_file, time_series.GetColumnNames(), definition_); definition_.HasHeader = false; } for (size_t i = 0; i < time_series.GetRecordsCount(); ++i) { WriteLine(out_file, time_series.GetRecordAsStrings(i), definition_); } out_file.close(); } void TimeSeriesReader::WriteFileDefinition(File &file, FileDefinition &definition) { std::ofstream out_file(file.GetPath(), std::ios::out); for (int i = 0; i < definition.Columns.size(); ++i) { out_file << definition.Header[i] << ','; out_file << GetDataTypeSize(definition.Columns[i]) << ','; if (definition.Decimals.size() > i) { out_file << definition.Decimals[i]; } else { out_file << "0"; } } out_file.close(); } FileDefinition TimeSeriesReader::ReadFileDefinition(File &file) { FileDefinition result; std::ifstream input_file(file.GetPath(), std::ios::in); std::string line, name, type, decimal; EnumParser<DataType> type_parser; size_t position = 0; while (std::getline(input_file, line)) { /* Get Name */ position = line.find(','); name = line.substr(0, position); line.erase(0, position + 1); /* Get Type */ position = line.find(','); type = line.substr(0, position); line.erase(0, position + 1); // GET DECIMAL decimal = line; result.Header.push_back(name); result.Columns.push_back(type_parser.Parse(type)); result.Decimals.push_back(boost::lexical_cast<int>(decimal)); } input_file.close(); return result; } SharedTimeSeriesPtr TimeSeriesReaderBinary::Read(File &file, const int max_rows) { /* Initialize time series */ auto result = std::make_shared<TimeSeries>(file.GetPath()); result->init(definition_.Columns); result->SetDecimals(definition_.Decimals); size_t size = result->GetRecordSize(); size += alignment_; result->SetColumnNames(definition_.Header); char *data = new char[size]; int count = 0; while ((count++ <= max_rows) && (-1 != file.ReadRaw(data, size))) { result->AddRecord(data); } delete[] data; return result; } void TimeSeriesReaderBinary::Write(File &file, TimeSeries &time_series) { size_t size = time_series.GetRecordSize() + alignment_; char *data = new char[size]; for (size_t i = 0; i < time_series.GetRecordsCount(); ++i) { size_t offset = 0; memset(data, 0, size); for (auto &raw_data:time_series.GetRawRecordData(i)) { memcpy(data + offset, raw_data.raw_data_, raw_data.raw_size_); offset += raw_data.raw_size_; } if (file.WriteRaw(data, size)) { throw std::runtime_error("Error while writing to a file."); } } delete[]data; }
true
cae8f5956eb84620dfad34e91a66997f63ff1f24
C++
isuckatdrifting/Iapetos
/Issac/Classes/Service/PlayerService.cpp
UTF-8
4,361
2.53125
3
[ "MIT" ]
permissive
#include "PlayerService.h" #include "cocos2d.h" USING_NS_CC; PlayerService* PlayerService::getInstance() { if (inst_ == nullptr) { inst_ = new (std::nothrow) PlayerService(); CCASSERT(inst_, "FATAL: Not enough memory"); } return inst_; } void PlayerService::init() { model_ = PlayerViewModel(); max_health = 7;//初始血量6个半心(3颗心) defaultAttack_ = 1.3; model_.setHealth(max_health); model_.setAttack(defaultAttack_); model_.setMoveSpeed(150); model_.setShootInterval(0.4); model_.setTearExistingTime(20); model_.setTearSpeed(100); model_.setRadiusSize(10); model_.setBodyMass(100); model_.setEnBounce(false); model_.setEnFly(false); model_.setBombNum(2); } int PlayerService::getHealth() const { return model_.getHealth(); } void PlayerService::setHealth(int health) { model_.setHealth(health); } void PlayerService::decreaseHealth(int dHealth) { model_.setHealth(model_.getHealth() - dHealth); } void PlayerService::increaseHealth(int dHealth) { model_.setHealth(model_.getHealth() + dHealth); } double PlayerService::getAttack() const { return model_.getAttack(); } void PlayerService::setAttack(double attack) { model_.setAttack(attack); } void PlayerService::decreaseAttack(double dAttack) { model_.setAttack(model_.getAttack() - dAttack); } void PlayerService::increaseAttack(double dAttack) { model_.setAttack(model_.getAttack() + dAttack); } double PlayerService::getMoveSpeed() const { return model_.getMoveSpeed(); } void PlayerService::setMoveSpeed(double move_speed) { model_.setMoveSpeed(move_speed); } void PlayerService::decreaseMoveSpeed(double dmove_speed) { model_.setMoveSpeed(model_.getMoveSpeed() - dmove_speed); } void PlayerService::increaseMoveSpeed(double dmove_speed) { model_.setMoveSpeed(model_.getMoveSpeed() + dmove_speed); } double PlayerService::getTearSpeed() const { return model_.getTearSpeed(); } void PlayerService::setTearSpeed(double tear_speed) { model_.setTearSpeed(tear_speed); } void PlayerService::decreaseTearSpeed(double dtear_speed) { model_.setTearSpeed(model_.getTearSpeed() - dtear_speed); } void PlayerService::increaseTearSpeed(double dtear_speed) { model_.setTearSpeed(model_.getTearSpeed() + dtear_speed); } int PlayerService::getTearExistingTime() const { return model_.getTearExistingTime(); } void PlayerService::setTearExistingTime(int tear_existing_time) { model_.setTearExistingTime(tear_existing_time); } void PlayerService::decreaseTearExistingTime(double dtear_existing_time) { model_.setTearExistingTime(model_.getTearExistingTime() - dtear_existing_time); } void PlayerService::increaseTearExistingTime(double dtear_existing_time) { model_.setTearExistingTime(model_.getTearExistingTime() + dtear_existing_time); } double PlayerService::getShootInterval() const { return model_.getShootInterval(); } void PlayerService::setShootInterval(double shoot_interval) { model_.setShootInterval(shoot_interval); } void PlayerService::decreaseShootInterval(double dshoot_interval) { model_.setShootInterval(model_.getShootInterval() - dshoot_interval); } void PlayerService::increaseShootInterval(double dshoot_interval) { model_.setShootInterval(model_.getShootInterval() + dshoot_interval); } double PlayerService::getRadiusSize() const { return model_.getRadiusSize(); } void PlayerService::setRadiusSize(double radiusSize) { model_.setRadiusSize(radiusSize); } double PlayerService::getBodyMass() const { return model_.getBodyMass(); } void PlayerService::setBodyMass(double bodyMass) { model_.setBodyMass(bodyMass); } bool PlayerService::getEnFly() const { return model_.getEnFly(); } void PlayerService::setEnFly(bool enFly) { model_.setEnFly(enFly); } bool PlayerService::getEnBounce() const { return model_.getEnBounce(); } void PlayerService::setEnBounce(bool enBounce) { model_.setEnBounce(enBounce); } int PlayerService::getBombNum() const { return model_.getBombNum(); } void PlayerService::setBombNum(int bombNum) { model_.setBombNum(bombNum); } PlayerService::PlayerService() { max_health = 7;//初始血量6个半心(3颗心) defaultAttack_ = 1.3; } PlayerService* PlayerService::inst_ = nullptr;
true
7e284f9fe4a8cb1b721de7aefe11f1ae4800a8da
C++
handsomebsn/data-structure
/3/3.31.cpp
UTF-8
3,097
3.390625
3
[ "BSD-3-Clause" ]
permissive
#include<stdio.h> #include<stdlib.h> #define INFEASIBLE -1//参数不合法 #define OK 1 #define ERROR 0 #define OVERFLOW -2 typedef char ElemType; typedef int Status;//函数状态 typedef struct Node { ElemType data; struct Node *next; }Node,*Ptrnode; typedef struct { Ptrnode front; Ptrnode rear; int length; }Queue; Status InitQueue(Queue &q){ q.front=q.rear=(Ptrnode)malloc(sizeof(Node)); if(!q.front)return OVERFLOW; q.front->next=NULL; q.length=0; return OK; } Status DestoryQueue(Queue &q){ while(q.front){ q.rear=q.front->next; free(q.front); q.front=q.rear; } } Status EnQueue(Queue &q,ElemType x){ Ptrnode p=(Ptrnode)malloc(sizeof(Node)); if(!p)return OVERFLOW; p->data=x; p->next=q.rear->next; q.rear->next=p; q.rear=p; // q.length++; return OK; } Status DeQueue(Queue &q,ElemType &x){ if(q.front==q.rear)return ERROR; x=q.front->next->data; Ptrnode tmp=q.front->next; q.front->next=tmp->next; free(tmp); // q.length--; return OK; } ElemType DeQueue(Queue &q){ if(q.front==q.rear){printf("queue is empty\n");exit(-1);} ElemType x; x=q.front->next->data; Ptrnode tmp=q.front->next; q.front->next=tmp->next; if(q.rear==tmp) q.rear=q.front; free(tmp); return x; } int QueueLength(const Queue &q){ return q.length; } /****stack****/ //栈的顺序表实现 #define STACK_INT_SIZE 100 #define STACKINCREMENT 50 typedef struct{ ElemType *data;//动态数组 int top;//栈顶 int stacksize;//当前已分配的存储空间大小 }Stack; Status InitStack(Stack &S); Status DestroyStack(Stack &S); Status ClearStack(Stack &S); Status StackEmpty(const Stack &S); int StackLength(const Stack &S); Status GetTop(const Stack &S,ElemType &e); Status Push(Stack &S,ElemType e); Status Pop(Stack &S,ElemType &e); ElemType Pop(Stack &S); Status InitStack(Stack &S){ S.data=(ElemType*)malloc(sizeof(ElemType)*STACK_INT_SIZE); S.stacksize=STACK_INT_SIZE; S.top=0; } Status StackEmpty(const Stack &S){ return S.top==0; } Status GetTop(const Stack &S,ElemType &e){ if(S.top==0)return ERROR; e=S.data[S.top-1]; return OK; } Status Push(Stack &S,ElemType e){ if(S.top==S.stacksize){ S.data=(ElemType*)realloc(S.data,(S.stacksize+STACKINCREMENT)*sizeof(ElemType)); if(!S.data)return OVERFLOW; S.stacksize+=STACKINCREMENT; } S.data[S.top++]=e; } Status Pop(Stack &S,ElemType &e){ if(S.top==0)return ERROR; e=S.data[--S.top]; return OK; } ElemType Pop(Stack &S){ if(S.top==0){printf("Stack is empty\n"); exit(-1);} return S.data[--S.top]; } Status DestroyStack(Stack &S){ free(S.data); S.stacksize=0; S.top=0; return OK; } Status ClearStack(Stack &S){ S.top=0; return OK; } int StackLength(const Stack &S){ return S.top; } bool fun3_31(char str[]){ int i=0; Stack S;InitStack(S); Queue Q;InitQueue(Q); while(str[i]!='@'){ Push(S,str[i]); EnQueue(Q,str[i]); i++; } while(!StackEmpty(S)){ if(Pop(S)!=DeQueue(Q)) return false; } return true; } int main(){ char str[200]; while(true){ scanf("%s",str); if(fun3_31(str)) printf("yes\n"); else printf("no\n"); } return 0; }
true
01b1a57e23a4095ef5538937246a98d183e4da86
C++
kushkgp/CompetitiveCode
/Arijit/test.cpp
UTF-8
2,501
2.828125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; vector<string> split_string(string); void kMarsh(vector<string> grid) { int m = grid.size(); int n = grid[0].length(); int left[m+1][n+1], up[m+1][n+1]; for( int j = 0; j < n; j++ ) { for( int i = 0; i < m; i++ ) { if( grid[i][j] == 'x' ) up[i][j] = 0; else if( i == 0 ) up[0][j] = 1; else up[i][j] = up[i-1][j] + 1; } } int ans = INT_MIN; for(int i=0;i<n-1;i++) for(int j= i+1;j<n;j++) { int val = -1; for(int k=0;k<m;k++) { int up1 = (grid[i][k] == 'x')?0:1; if((up[j][k] - up[i][k] + up1) == (j-i+1)) { if(val==-1) val=k; else { if( (k-val)>0 && (j-i)>0 ) ans = max(ans,(2*(k-val)) + (2*(j-i))); } } if(grid[i][k] == 'x' || grid[j][k] == 'x') val = -1; } } if( ans <= 0 ) cout<<"impossible"<<endl; else cout<<ans<<endl; return; } int main() { string mn_temp; getline(cin, mn_temp); vector<string> mn = split_string(mn_temp); int m = stoi(mn[0]); int n = stoi(mn[1]); vector<string> grid(m); for (int grid_itr = 0; grid_itr < m; grid_itr++) { string grid_item; getline(cin, grid_item); grid[grid_itr] = grid_item; } kMarsh(grid); return 0; } vector<string> split_string(string input_string) { string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { return x == y and x == ' '; }); input_string.erase(new_end, input_string.end()); while (input_string[input_string.length() - 1] == ' ') { input_string.pop_back(); } vector<string> splits; char delimiter = ' '; size_t i = 0; size_t pos = input_string.find(delimiter); while (pos != string::npos) { splits.push_back(input_string.substr(i, pos - i)); i = pos + 1; pos = input_string.find(delimiter, i); } splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); return splits; }
true
14691351848c29eef5330d9ba0d42d9acd9c841d
C++
RichardHancock/Game-Engine-Programming
/Engine/internal/networking/SocketBase.h
UTF-8
1,191
3.4375
3
[]
no_license
#pragma once #include <string> #include <queue> /** @brief A socket base class. */ class SocketBase { public: /** @brief Constructor. @param [in,out] inHostname The hostname. @param inPort The port. */ SocketBase(std::string& inHostname, int inPort); /** @brief Query if this Socket is open. @return True if open, false if not. */ bool isOpen(); /** @brief Sets receive buffer length. @param newLength Length of the buffer. */ void setReceiveBufferLength(int newLength); /** @brief Sends a message. @param message The message. @return True if it succeeds, false if it fails. */ virtual bool sendMsg(std::string message) = 0; /** @brief Determines if we can receive message. @return True if it succeeds, false if it fails. */ virtual bool recvMsg() = 0; protected: /** @brief The queue of received messages. */ std::queue<std::string> queue; /** @brief The hostname. */ std::string hostname; /** @brief The port. */ int port; /** @brief True if open. */ bool open; /** @brief Length of the receive buffer. */ int receiveBufferLength; };
true
8de29682c688f82959946fb04ede022c79b5c506
C++
ntraft/ubc-WAM95
/robot/senses/qd2co_system.h
UTF-8
749
2.640625
3
[]
no_license
#include "stdheader.h" #include "utils.h" class Qd2CoSystem : public systems::System { public: //Input<double> input_time; Input<Quaterniond> input_qd; Output<co_type> output_co; protected: Output<co_type>::Value* output_value_co; public: Qd2CoSystem(const std::string& sysName = "Qd2CoSystem") : systems::System(sysName), output_co(this, &output_value_co), input_qd(this) //input_time(this) {} virtual ~Qd2CoSystem() { mandatoryCleanUp(); } protected: virtual void operate(){ const Quaterniond& readings_qd = input_qd.getValue(); co_type readings_co = qd2co(&readings_qd); output_value_co->setData(&readings_co); } public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW };
true
a1b8fbe065f622f0673f71a6931f3a29de13e4c9
C++
vcato/qt-quick-6502-emulator
/unit_tests/immediate_mode_AND.cpp
UTF-8
6,099
2.890625
3
[]
no_license
#include "addressing_mode_helpers.hpp" struct AND_Immediate_Expectations { constexpr AND_Immediate_Expectations &accumulator(const uint8_t v) { a = v; return *this; } uint8_t a; NZFlags flags; }; using ANDImmediate = AND<Immediate, AND_Immediate_Expectations, 2>; using ANDImmediateMode = ParameterizedInstructionExecutorTestFixture<ANDImmediate>; static void StoreTestValueAtImmediateAddress(InstructionExecutorTestFixture &fixture, const ANDImmediate &instruction_param) { fixture.fakeMemory[instruction_param.address.instruction_address + 1] = instruction_param.address.immediate_value; } static void SetupAffectedOrUsedRegisters(InstructionExecutorTestFixture &fixture, const ANDImmediate &instruction_param) { fixture.r.a = instruction_param.requirements.initial.a; fixture.r.SetFlag(FLAGS6502::N, instruction_param.requirements.initial.flags.n_value.expected_value); fixture.r.SetFlag(FLAGS6502::Z, instruction_param.requirements.initial.flags.z_value.expected_value); } template<> void LoadInstructionIntoMemoryAndSetRegistersToInitialState( InstructionExecutorTestFixture &fixture, const ANDImmediate &instruction_param) { SetupRAMForInstructionsThatHaveImmediateValue(fixture, instruction_param); SetupAffectedOrUsedRegisters(fixture, instruction_param); } template<> void RegistersAreInExpectedState(const Registers &registers, const AND_Immediate_Expectations &expectations) { EXPECT_THAT(registers.a, Eq(expectations.a)); EXPECT_THAT(registers.GetFlag(FLAGS6502::N), Eq(expectations.flags.n_value.expected_value)); EXPECT_THAT(registers.GetFlag(FLAGS6502::Z), Eq(expectations.flags.z_value.expected_value)); } template<> void MemoryContainsInstruction(const InstructionExecutorTestFixture &fixture, const Instruction<AbstractInstruction_e::AND, Immediate> &instruction) { EXPECT_THAT(fixture.fakeMemory.at( fixture.executor.registers().program_counter ), Eq( OpcodeFor(AbstractInstruction_e::AND, AddressMode_e::Immediate) )); EXPECT_THAT(fixture.fakeMemory.at( fixture.executor.registers().program_counter + 1), Eq(instruction.address.immediate_value)); } template<> void MemoryContainsExpectedComputation(const InstructionExecutorTestFixture &/* fixture */, const ANDImmediate &/* instruction */) { } // We will basically be testing the AND truth table here with specially chosen values. static const std::vector<ANDImmediate> ANDImmediateModeTestValues { ANDImmediate{ // Beginning of a page Immediate().address(0x0000).value(0x00), ANDImmediate::Requirements{ .initial = { .a = 0, .flags = { }}, .final = { .a = 0, .flags = { .n_value = { .expected_value = false }, .z_value = { .expected_value = true } } }} }, ANDImmediate{ // One before the end of a page Immediate().address(0x00FE).value(0xFF), ANDImmediate::Requirements{ .initial = { .a = 0, .flags = { }}, .final = { .a = 0, .flags = { .n_value = { .expected_value = false }, .z_value = { .expected_value = true } } }} }, ANDImmediate{ // Crossing a page boundary Immediate().address(0x00FF).value(0), ANDImmediate::Requirements{ .initial = { .a = 0xFF, .flags = { }}, .final = { .a = 0, .flags = { .n_value = { .expected_value = false }, .z_value = { .expected_value = true } } }} }, ANDImmediate{ Immediate().address(0x8000).value(0xFF), ANDImmediate::Requirements{ .initial = { .a = 0xFF, .flags = { }}, .final = { .a = 0xFF, .flags = { .n_value = { .expected_value = true }, .z_value = { .expected_value = false } } }} }, ANDImmediate{ // Check for masking out the high bit Immediate().address(0x8000).value(0x80), ANDImmediate::Requirements{ .initial = { .a = 0xFF, .flags = { }}, .final = { .a = 0x80, .flags = { .n_value = { .expected_value = true }, .z_value = { .expected_value = false } } }} }, ANDImmediate{ // Use alternating bits for a zero result Immediate().address(0x8000).value(0b10101010), ANDImmediate::Requirements{ .initial = { .a = 0b01010101, .flags = { }}, .final = { .a = 0x00, .flags = { .n_value = { .expected_value = false }, .z_value = { .expected_value = true } } }} }, ANDImmediate{ // Use the same bits for the same result Immediate().address(0x8000).value(0b01010101), ANDImmediate::Requirements{ .initial = { .a = 0b01010101, .flags = { }}, .final = { .a = 0b01010101, .flags = { .n_value = { .expected_value = false }, .z_value = { .expected_value = false } } }} }, ANDImmediate{ // Use the same bits for the same result (not the same pattern as before) Immediate().address(0x8000).value(0b10101010), ANDImmediate::Requirements{ .initial = { .a = 0b10101010, .flags = { }}, .final = { .a = 0b10101010, .flags = { .n_value = { .expected_value = true }, .z_value = { .expected_value = false } } }} } }; TEST_P(ANDImmediateMode, TypicalInstructionExecution) { TypicalInstructionExecution(*this, GetParam()); } INSTANTIATE_TEST_SUITE_P(AndImmediateAtVariousAddresses, ANDImmediateMode, testing::ValuesIn(ANDImmediateModeTestValues) );
true
8f5ad271fd197ad417bfa6912afb43078808013d
C++
yip-jek/RevenueAudit
/src/base/src/gsignal.cpp
UTF-8
2,139
2.796875
3
[]
no_license
#include "gsignal.h" #include <iostream> #include <signal.h> #include "log.h" namespace base { Log* GSignal::s_pLog = NULL; bool GSignal::s_bQuit = false; bool GSignal::Init(Log* pLog) { if ( NULL == pLog ) { return false; } s_pLog = pLog; if ( SetSignal(SIGTERM, SglFuncQuit) == SIG_ERR ) { std::cout << "Signal SIGTERM error!" << std::endl; s_pLog->Output("Signal SIGTERM error!"); return false; } if ( SetSignal(SIGINT, SglFuncQuit) == SIG_ERR ) { std::cout << "Signal SIGINT error!" << std::endl; s_pLog->Output("Signal SIGINT error!"); return false; } if ( SetSignal(SIGQUIT, SglFuncQuit) == SIG_ERR ) { std::cout << "Signal SIGQUIT error!" << std::endl; s_pLog->Output("Signal SIGQUIT error!"); return false; } std::cout << "[INIT] Set signal OK." << std::endl; s_pLog->Output("[INIT] Set signal OK."); return true; } bool GSignal::IsRunning() { return !s_bQuit; } sgl_fun* GSignal::SetSignal(int sig_no, sgl_fun* f) { struct sigaction sig_ac; sig_ac.sa_handler = f; sigemptyset(&sig_ac.sa_mask); sig_ac.sa_flags = 0; if ( SIGALRM == sig_no ) { #ifdef SA_INTERRUPT sig_ac.sa_flags |= SA_INTERRUPT; #endif } else { #ifdef SA_RESTART sig_ac.sa_flags |= SA_RESTART; #endif } struct sigaction n_sig_ac; if ( sigaction(sig_no, &sig_ac, &n_sig_ac) < 0 ) { return SIG_ERR; } return n_sig_ac.sa_handler; } void GSignal::SglFuncQuit(int sig) { s_bQuit = true; if ( SIGTERM == sig ) { std::cout << "Signal SIGTERM received! Ready to quit ..." << std::endl; s_pLog->Output("Signal SIGTERM received! Ready to quit ..."); } else if ( SIGINT == sig ) { std::cout << "Signal SIGINT received! Ready to quit ..." << std::endl; s_pLog->Output("Signal SIGINT received! Ready to quit ..."); } else if ( SIGQUIT == sig ) { std::cout << "Signal SIGQUIT received! Ready to quit ..." << std::endl; s_pLog->Output("Signal SIGQUIT received! Ready to quit ..."); } else { std::cout << "Unknown signal (" << sig << ") received! Ready to quit ..." << std::endl; s_pLog->Output("Unknown signal (%d) received! Ready to quit ...", sig); } } } // namespace base
true
8fd57f38cc798e530ab883f38f7b7c75e8aaaa2f
C++
jezowska/SDiZO-Projekt
/Projekt 2/graph_array.cpp
WINDOWS-1250
5,923
3.296875
3
[]
no_license
#include "graph_array.h" using namespace std; GraphArray::GraphArray(int v, int e) { n = v; size = e; cost = 0; //tworzenie tablic ze wskaznikow zadeklarowanych w pliku naglowkowym d = new int[n]; p = new int[n]; key = new int[n]; pp = new int[n]; graph = new int* [n]; inQ = new bool[n]; for (int i = 0; i < n; i++) { //tworzymy tablic dwuwymiarow graph[i] = new int[n]; for (int j = 0; j < n; j++) { //tworzymy tablic dwuwymiarow graph[i][j] = 0; } inQ[i] = true; } } void GraphArray::add(int v, int u, int e) { if (e <= 0) { cout << "Waga powinna byc dodatnia" << endl; return; } graph[v][u] = e; graph[u][v] = -e; //dodanie ujemnej krawedzi, aby rozpoznac graf skierowany, ale takze przy mst moc zrobic abs i aby graf byl czytany jako nieskierowany } void GraphArray::print() { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << graph[i][j] << " "; if (graph[i][j] < 10) cout << " "; } cout << endl; } } void GraphArray::print2() { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << abs(graph[i][j]) << " "; if (graph[i][j] < 10) cout << " "; } cout << endl; } } void GraphArray::dijkstra(int start) { priority_queue<Pii, Vii, greater<Pii>> Q; //do kolejki dodajemy co ma byc kolejce, na jakiej konstrukcji budowana jest kolejka i typ sortowania for (int i = 0; i < n; i++) //uzupelniamy tablice d i p odpowiednio najwiekszym intem i najmniejszym - zeby zapobiec zlemu dzialaniu algorytmu { d[i] = INT_MAX; p[i] = NULL; } d[start] = 0; p[start] = start; Q.push(make_pair(d[start], start)); //wrzucamy na kolejke nasz wierzcholek startowy i jego droge do samego siebie (0) while (!Q.empty()) { int u = Q.top().second; // pobieramy z gory kolejki wierzcholek o najmniejszym d Q.pop();//usuwamy pare z kolejki for (int i = 0; i < n; i++) { // szukamy polaczenia z innym wierzcholkiem, a nastepnie //pobieramy numer i wage krawedzi miedzy naszym pobranym z kolejki wierzcholkiem i int w = graph[u][i]; int distance = w + d[u]; if (w > 0 && d[i] > distance) //sprawdzamy czy nasza krawedz istnieje //i czy droga do poprzedniego wiercholka i waga krawedzi miedzy poprzednim, a aktualnym jest mniejsza niz dotychczasowa droga do danego wierzcholka { d[i] = distance; //zmieniamy dotychczasowa droge p[i] = u; // poprzedni wierzcholek ustawiamy na aktualny Q.push(make_pair(d[i], i)); // wrzucamy nasza nowa pare do kolejki } } } print_dijkstra(start); } void GraphArray::print_dijkstra(int start) { vector<int> path; cout << "End Dist Path" << endl; for (int i = 0; i < n; i++) { int x = i; if (d[i] != INT_MAX) //sprawdzamy czy zaszly zmiany w naszej drodze i czy istnieje polaczenie do danego wierzcholka z wierzcholka startowego { cout << i << " | " << d[i] << " | "; x = p[x]; path.push_back(x); while (x != start) { //chodzimy po tablicy p i szukamy poprzednikow, aby ustalic sciezke z wierzcholka startowego if (p[x] != INT_MIN) { x = p[x]; path.push_back(x); } } while (!path.empty()) { cout << path.back() << " "; if (path.back() < 10) cout << " "; path.pop_back(); } cout << i << endl; } } cout << endl; } void GraphArray::prim(int start) { priority_queue<Pii, Vii, greater<Pii>> Q; //do kolejki dodajemy co ma byc kolejce, na jakiej konstrukcji budowana jest kolejka i typ sortowania cost = 0; for (int i = 0; i < n; i++) { key[i] = INT_MAX; p[i] = NULL; inQ[i] = true; } key[start] = 0; p[start] = 0; Q.push(make_pair(key[start], start)); //wrzucamy wierzcholek do kolejki while (!Q.empty()) { int u = Q.top().second; //pobieramy wierzcholek z kolejki inQ[u] = false; //zaznaczamy, ze dany wierzcholek zostal odwiedzony Q.pop(); for (int i = 0; i < n; i++) { // szukamy polaczenia z innym wierzcholkiem, a nastepnie //pobieramy numer i wage krawedzi miedzy naszym pobranym z kolejki wierzcholkiem i wierzcholkiem i \ int w = abs(graph[u][i]); if (w > 0) { if (inQ[i] == true && w < key[i]) { //jesli wierzcholek jest w kolejce i nasza waga jest mniejsza niz dotychczasowo ustalona roboczo waga //to zmieniamy wage i poprzedni wierzcholek key[i] = w; p[i] = u; Q.push(make_pair(key[i], i)); //wrzucamy nasz wierzcholek do kolejki } } } } print_prim(); } void GraphArray::print_prim() { cout << "V U Cost" << endl; for (int i = 1; i < n; i++) { if (key[i] != INT_MAX) { cout << p[i] << " " << i << " " << key[i] << endl; cost += key[i]; } } cout << "MST = " << cost << endl; } GraphArray::~GraphArray() { delete d; delete p; delete pp; delete key; delete graph; }
true
c421b3942ebd6e1cf6ebc90d04d39c7b0dce3cc2
C++
sbreeden25/ChangeUp
/src/v5_hal/firmware/include/kinematics/IDriveKinematics.h
UTF-8
2,218
2.71875
3
[]
no_license
#pragma once #include "api.h" #include "nodes/subsystems/drivetrain_nodes/IDriveNode.h" #include "math/Pose.h" #include "util/Encoders.h" #include "util/Timer.h" #include "eigen/Eigen/Dense" class IDriveKinematics { protected: Rotation2Dd m_initial_angle; Pose m_pose = Pose(Vector2d(0, 0), Rotation2Dd()); bool m_pose_reset = true; float m_ticks_to_distance_m; Timer m_timer; void m_updateCurrentPosition(Vector2d robot_velocity, float theta_velocity, float delta_time); public: struct FourMotorPercentages { float left_front_percent; float left_rear_percent; float right_front_percent; float right_rear_percent; }; IDriveKinematics(EncoderConfig encoder_config, Pose current_pose=Pose()); /** * This function returns the current pose of the robot * * @returns Pose object containing the position and rotation of the robot */ Pose getPose(); /** * This function sets the current pose of the robot * * @param current_pose pose to set the robot to */ void setCurrentPose(Pose current_pose); /** * This function takes in encoder values of all motors, and uses them to update * the position of the robot based on the change of position over time * * @param encoder_vals struct holding encoder values for all motors */ virtual void updateForwardKinematics(IDriveNode::FourMotorDriveEncoderVals encoder_vals) = 0; /** * This function takes in movements of a drivetrain in the x, y, and theta axes. * The inputs of this function must be of the same units (m/s, volts, etc.) and * the function will return the proportion of the supplied maximum to send to each * of four motors * * @param x float representing the x-movement of the drivetrain * @param y float representing the y-movement of the drivetrain * @param theta float representing the rotational movement of the drivetrain * @returns struct containing percentage of the supplied maximum to send to each motor */ virtual FourMotorPercentages inverseKinematics(float x, float y, float theta, float max) = 0; ~IDriveKinematics(); };
true
717247eb6f594f7b9e886c6fb24ab5ca6fa9234e
C++
edgeofmoon/GraphView2017
/MySimple2DGrid.h
UTF-8
2,383
2.53125
3
[]
no_license
#pragma once #include "MyVec.h" #include "MyArray.h" #include "MyLine.h" class MySimple2DGrid { public: MySimple2DGrid(void); ~MySimple2DGrid(void); void SetRange(float startx, float endx, float starty, float endy); void SetRange(const MyVec2f& start, const MyVec2f& end); void SetXDivision(int n); void SetYDivision(int n); MyVec2f GetLowPos() const {return mStart;}; MyVec2f GetHighPos() const {return mEnd;}; int GetDivisionX() const {return mDivisionX;}; int GetDivisionY() const {return mDivisionY;}; virtual int GetStatusByte(MyVec2f pos) const; virtual bool IsIndexValid(const MyVec2i& index) const; virtual MyVec2i GetGridIndex(MyVec2f pos) const; virtual MyVec2i ClampIndex(const MyVec2i& idx) const; virtual MyArray2i* MakePassGridIndexArray(MyVec2f start, MyVec2f end) const; virtual float GetCellWidth() const; virtual float GetCellHeight() const; virtual MyVec2f GetCellSize() const; virtual MyVec2f GetLowPos(const MyVec2i& idx) const; //MyArray2i* MakeCellsAround(const MyVec2f& center, float maxDistance) const; MyArray2f* MakeContourArray(const MyArray2i& inArray, bool clockWise = true) const; MyArray2i* MakeBoxCollidingCells(const MyVec2f& low, const MyVec2f high) const; static bool IsCellConnected(const MyVec2i& idx1, const MyVec2i& idx2, bool diagCounts = false); static bool IsCellConnected(const MyVec2i& idx1, const MyArray2i& idxArray, bool diagCounts = false); static bool IsCellConnected(const MyArray2i& idxArray1, const MyArray2i& idxArray2, bool diagCounts = false); static MyArray2i* MakeContourCellIndexArray(const MyArray2i& inArray, bool diagCounts = false); static MyArray2i* MakeContourIndexArray(const MyArray2i& inContourArray, bool clockWise = true); static MyArray2i* MakeContourIndexArray(const MyVec2i& idx, int neighborByte = 0, bool clockWise = true); static int GetConnectionByte(const MyVec2i& source, const MyVec2i& target); static int GetConnectionByte(const MyVec2i& idx, const MyArray2i& idxArray); protected: MyVec2f mStart, mEnd; int mDivisionX; int mDivisionY; private: bool CohenSutherlandLineClip(const MyVec2f& start, const MyVec2f& end, MyVec2f& outStart, MyVec2f& outEnd) const; static const int INSIDE = 0; // 0000 static const int LEFT = 1; // 0001 static const int RIGHT = 2; // 0010 static const int BOTTOM = 4; // 0100 static const int TOP = 8; // 1000 };
true
1e6d3200afae4d00c3004a56fb6dc81dc7172be4
C++
nirme/rpg_game_engine
/Profiler.h
UTF-8
1,710
2.5625
3
[]
no_license
#pragma once #ifndef _PROFILER #define _PROFILER #include "utility.h" #include "Logger.h" #include <assert.h> #define MAX_PROFILER_SAMPLES 20 #define IDS_PROFILE_HEADER1 " Min : Avg : Max : # : Profile Name" #define IDS_PROFILE_HEADER2 "--------------------------------------------" #define IDS_PROFILE_SAMPLE "%3.1f : %3.1f : %3.1f : %3d : %s" struct SingleSample; class ProfileSample; class ProfilerOutputHandler; class ProfileLogHandler; struct SingleSample { bool isValid; bool isUsed; UINT callCount; std::string name; float startTime; float totalTime; float childTime; int parentCount; float averagePc; float minPc; float maxPc; unsigned long dataCount; SingleSample() { isValid=false; dataCount=0; averagePc=minPc=maxPc=-1; } }; class ProfileSample { public: ProfileSample(std::string sampleName); ~ProfileSample(); static void output(); static void resetSample(std::string sampleName); static void resetAll(); static ProfilerOutputHandler *outputHandler; protected: int sampleIndex; int parentIndex; inline float getTime(){ return (float)timeGetTime(); } static SingleSample samples[MAX_PROFILER_SAMPLES]; static int lastOpenedSample; static int openSampleCount; static float rootBegin, rootEnd; }; class ProfilerOutputHandler { public: virtual void beginOutput()=0; virtual void sample(float fMin, float fAvg, float fMax, int callCount, std::string name, int parentCount)=0; virtual void endOutput()=0; }; class ProfileLogHandler : public ProfilerOutputHandler { public: void beginOutput(); void endOutput(); void sample(float fMin, float fAvg, float fMax, int callCount, std::string name, int parentCount); }; #endif //_PROFILER
true
2e489d961672de275d7138c117a5c1dceb0c43e2
C++
arnottkid/CS302
/Sorting/src/sort_stdin.cpp
UTF-8
420
2.984375
3
[]
no_license
#include <iostream> #include <vector> #include <cstdlib> #include <cstdio> #include "sorting.hpp" using namespace std; void usage(const char *s) { cerr << "usage: sort_driver size iterations seed double-check(yes|no) print(yes|no)\n"; if (s != NULL) cerr << s << endl; exit(1); } main(int argc, const char **argv) { vector <double> v; double d; while (cin >> d) v.push_back(d); sort_doubles(v, true); }
true
bd043cba08fedfa154e89f74a70fcf1f11c50020
C++
bayram53/online-judge
/codeforces.com/149/5/5.cpp
UTF-8
474
2.796875
3
[]
no_license
# include <stdio.h> # include <stdlib.h> # include <algorithm> # include <string.h> using namespace std; int gcd(int n,int m) { if(m==0) return n; return gcd(m,n%m); } int lcm(int a,int b) { return a/gcd(a,b)*b; } struct students { int a,b; }; int function (void const *x,void const *y) { students m=*(students*)x; students n=*(students*)y; if(m.a==n.a) return m.b-n.b; else return m.a-n.a; } int main() { } //qsort(t,n,sizeof(students),function);
true
bd36aa3a30e9ea7ce002a2817b417bbeeba98f87
C++
sharkduino/Arduino_Animal_Tag
/animal_tag/gyro.cpp
UTF-8
2,574
2.953125
3
[]
no_license
#include "gyro.hpp" #include <Arduino.h> #include <SD.h> #include "fxas_2.h" #include "debug.h" // Size of software buffer (samples) constexpr signed char buffer_s = 32; // Size of hardware buffer (samples) constexpr signed char buffer_h = 32; static FXAS2::sample buffer[buffer_s]; static signed char buffer_i; /* * Setup the gyroscope's internal buffer, do some * debugging reports */ void gyro_setup(FXAS2::Range range, FXAS2::ODR odr) { DBGSTR("Gyroscope buffer size: "); DBG(buffer_s + buffer_h); DBGSTR(" (software + hardware)\n"); FXAS2::begin(odr, range, true); // enable burst-reading } /* * Read as many bytes as possible from the gyroscope's FIFO * into our buffer. */ void gyro_read_all() { if (!gyro_is_active()) { DBGSTR("ERROR: G. not active\n"); return; } if (buffer_i >= buffer_s) { DBGSTR("ERROR: G.FULL\n"); return; } DBGSTR("G.read\n"); byte reads_left = buffer_s - buffer_i; byte reads = (reads_left < 32) ? reads_left : 32; FXAS2::readBurst(buffer, reads); buffer_i += reads; } /* * Write every value in the software and then hardware buffer to the SD card. * If half is true, only write half of the buffer. (Used with downsampled accelerometer) */ void gyro_write(File sd, bool half) { if (!gyro_is_active()) { DBGSTR("ERROR: G. not active"); } // Write software buffer sd.write((byte *) buffer, sizeof(buffer)); // Write hardware buffer gyro_reset(); gyro_read_all(); sd.write((byte *) buffer, sizeof(buffer) >> half); } /* * Get the software buffer's fullness */ bool gyro_full() { return buffer_i >= buffer_s; } /* * Reset the gyro buffer so that it can be used again. */ void gyro_reset() { buffer_i = 0; #if CLEAR_BUFFERS for (int i=0; i<buffer_s; i++) { buffer[i] = {0, 0, 0}; } #endif } /* * Set the gyroscope to active or standby mode. */ void gyro_set_active(bool active) { if (active) { FXAS2::active(); } else { FXAS2::standby(); } } /* * Get the gyroscope's current status: active (true) or standy. */ bool gyro_is_active() { return FXAS2::isActive; } /* * Return the gyroscope's scale in DPS. This is written to the header */ float gyro_scale() { switch (FXAS2::currentRange) { case FXAS2::Range::DPS_2000: return 2000.0; break; case FXAS2::Range::DPS_1000: return 1000.0; break; case FXAS2::Range::DPS_500: return 500.0; break; case FXAS2::Range::DPS_250: return 250.0; break; } } /* * Size, in bytes, of a single SD card write. */ unsigned short gyro_write_size() { return (buffer_s + buffer_h) * sizeof(FXAS2::sample); }
true
9f3b314ad1fe7d174c89852b0530d47366a0a7f3
C++
jmdeal/ray-tracer
/src/geometry/Sphere.h
UTF-8
626
2.921875
3
[]
no_license
#pragma once #include <optional> #include "IHittable.h" #include "Ray.h" #include "Vec3.h" class Sphere : public IHittable { public: Sphere() = delete; Sphere(math::Vec3 origin, double radius, std::shared_ptr<Material> mat) : origin_(origin), radius_(radius), mat_ptr_(mat) {} std::optional<HitRecord> Hit(const math::Ray &ray, double min_dist, double max_dist) const override; math::Vec3 GetOrigin() const { return origin_; } double GetRadius() const { return radius_; } private: math::Vec3 origin_; double radius_; std::shared_ptr<Material> mat_ptr_; };
true
b3ac278daf9c05ddb9279947b20d7d4833718ca1
C++
vCharbonnieras/Projet_multimedia
/main_console.cpp
UTF-8
4,708
2.875
3
[]
no_license
#include <iostream> #include <sstream> #include "string" #include <vector> #include <opencv2/opencv.hpp> #include "Lighten_darken.cpp" #include "cv_canny_edge.cpp" #include "cv_stitching/cv_stitching.cpp" #include "Dilatation_erosion.cpp" #include "Face_identification_recognition.cpp" using namespace std; using namespace cv; Mat img = imread("mark.jpg"); Mat e = img; String window1 = "Image"; /**Load an image*/ int loadImage(string path) { img = imread(path); // Check for failure if (!img.data) { printf(" No image data \n"); return 1; } e = img; cout << path << " successfully loaded\n"; imshow(window1,e); waitKey(0); return 0; } /**Split line by Character*/ vector<string> splitByChar(string &str, char delim) { string buf; // Have a buffer string stringstream ss(str); // Insert the string into a stream vector<string> tokens; // Create vector to hold our words while (getline(ss, buf, delim)) { tokens.push_back(buf); } return tokens; } /**Resize function*/ int resize(vector<string> opt) { int Xf; int xy[2] = {}; if (opt.size() == 1) { Xf = stod(opt[0]); resize(img, e, Size(int(img.cols * Xf), int(img.cols * Xf))); return 0; } else if (opt.size() == 2) { int i = 0; while (i < 2) { xy[i] = stod(opt[i]); i += 1; } resize(img, e, Size(xy[0], xy[1])); imshow(window1,e); waitKey(0); } else { return 1; } } int darken(vector<string> opt) { //lighten/darken float valContrast = stof(opt[1]); float valBrightness = stof(opt[2]); e = lightImg(e,valContrast,valBrightness); imshow(window1,e); waitKey(0); return 0; } int stitching(vector<string> opt) { // Should make another image? e = cv_stitching(opt); } int main() { /**Variables*/ ofstream log; log.open("log.txt"); vector<string> line; string input; string command; /**Starting loop*/ cout << "Enter command line\n"; while (true) { /**print the edit image*/ //imshow(window1, e); //waitKey(); cout << ">>"; /**get inputed line*/ getline(cin, input); /**split line*/ if (!input.empty()) { line = splitByChar(input, ' '); //get the command command = line[0]; /**Register to log*/ log << command << endl; /**Switch according to command entered*/ if (command == "resize") { line.erase(line.begin()); resize(line); } else if (command == "load") { if (line.size() == 2) { loadImage(line[1]); } } else if (command == "darken" or command == "lighten") { darken(line); } else if (command == "erosion" or command=="dilatation") { dilatation_erosion(e); } else if (command == "stitching") { stitching(line); } else if (command == "face") { face(e,"Image"); } else if (command == "canny") { cannyEdge(e); //to do } else if (command == "save") { /**save changes of edit to image*/ img = e; } else if (command == "exit") { break; } else if (command == "help") { //print all command cout << "\t darken [contrast] [brightness] \t change the brightness and the contrast of the document" <<endl; cout << "\t dilatation \t\t\t\t not implemented" <<endl; cout << "\t erosion \t\t\t\t not implemented" <<endl; cout << "\t exit \t\t\t\t\t exit the program" <<endl; cout << "\t help \t\t\t\t\t print all commands" <<endl; cout << "\t lighten [contrast] [brightness] \t same as darken" <<endl; cout << "\t load [path] \t\t\t\t load a documment from the path" <<endl; cout << "\t resize [newXValue] [newYValue] \t resize the document to set the lenght to X and the height to Y" <<endl; cout << "\t save \t\t\t\t\t not implemented" <<endl; cout << "\t stiching \t\t\t\t Stitches images with similar border. To see usage type ? or \"help\" " <<endl; } else { /**unknown command message*/ cout << "'" << input << "'" << "is an unknown command.help for information.\n"; } } } log.close(); destroyAllWindows(); return 0; }
true
7ac002e215384ba0bf30ce61932289ee53c9b29a
C++
algoboy101/LeetCodeCrowdsource
/backup/source/cpp/[351]安卓系统手势解锁.cpp
UTF-8
1,689
3.1875
3
[]
no_license
//我们都知道安卓有个手势解锁的界面,是一个 3 x 3 的点所绘制出来的网格。 // // 给你两个整数,分别为 m 和 n,其中 1 ≤ m ≤ n ≤ 9,那么请你统计一下有多少种解锁手势,是至少需要经过 m 个点,但是最多经过不超过 n 个 //点的。 // // // // 先来了解下什么是一个有效的安卓解锁手势: // // // 每一个解锁手势必须至少经过 m 个点、最多经过 n 个点。 // 解锁手势里不能设置经过重复的点。 // 假如手势中有两个点是顺序经过的,那么这两个点的手势轨迹之间是绝对不能跨过任何未被经过的点。 // 经过点的顺序不同则表示为不同的解锁手势。 // // // // // // // // // 解释: // // | 1 | 2 | 3 | //| 4 | 5 | 6 | //| 7 | 8 | 9 | // // 无效手势:4 - 1 - 3 - 6 //连接点 1 和点 3 时经过了未被连接过的 2 号点。 // // 无效手势:4 - 1 - 9 - 2 //连接点 1 和点 9 时经过了未被连接过的 5 号点。 // // 有效手势:2 - 4 - 1 - 3 - 6 //连接点 1 和点 3 是有效的,因为虽然它经过了点 2 ,但是点 2 在该手势中之前已经被连过了。 // // 有效手势:6 - 5 - 4 - 1 - 9 - 2 //连接点 1 和点 9 是有效的,因为虽然它经过了按键 5 ,但是点 5 在该手势中之前已经被连过了。 // // // // 示例: // // 输入: m = 1,n = 1 //输出: 9 // // Related Topics 动态规划 回溯算法 //leetcode submit region begin(Prohibit modification and deletion) class Solution { public: int numberOfPatterns(int m, int n) { } }; //leetcode submit region end(Prohibit modification and deletion)
true
c5ba6ad41a279889d48c3b732a9f260be86bc4b4
C++
contrechoc/arduino_scripts
/scareCrowdeLuxe/scareCrowdeLuxe.ino
UTF-8
3,187
3.109375
3
[]
no_license
#include "pitches.h" // notes in the melody: int melody[] = { NOTE_C4, NOTE_G3,NOTE_G3, NOTE_A3, NOTE_G3,0, NOTE_B3, NOTE_C4}; // note durations: 4 = quarter note, 8 = eighth note, etc.: int noteDurations[] = { 4, 8, 8, 4,4,4,4,4 }; #include <Servo.h> Servo myservo1; // create servo object to control a servo // a maximum of eight servo objects can be created Servo myservo2; int pos = 0; // variable to store the servo position int teller = 0; void setup(){ //LED afdeling pinMode( 7, OUTPUT);//7 LED1 pinMode( 6, OUTPUT);//GND digitalWrite(6, LOW); pinMode( 5, OUTPUT);//7 LED2 //knop pinMode(13, INPUT); pinMode(12, OUTPUT); digitalWrite(12, HIGH); //sound pinMode(3, OUTPUT); pinMode(2, OUTPUT); digitalWrite(2, LOW); //ldr pinMode(14, OUTPUT); pinMode(16, OUTPUT); digitalWrite(14, LOW); digitalWrite(16, HIGH); myservo1.attach(9); myservo2.attach(10); Serial.begin(9600); } void loop(){ if ( digitalRead( 13) == HIGH){ for(int i = 0; i<10 ; i++) { tone(3, 1000 + 100*i, 300); delay(100); } lampjesAan(); soundOn(); armpjes(); } else { allesUit(); } int sensorReading = analogRead(A1) ; if ( teller < 5){ // play the pitch: tone(3, sensorReading*3, 100); teller++; } if ( sensorReading < 150 ) { teller = 0; //LED 10 seconden aan lampjesAan(); delay(500); } else { lampjesUit(); } } void allesUit(){ soundOff(); armpjesOff(); lampjesUit(); } void soundOn(){ // iterate over the notes of the melody: for (int thisNote = 0; thisNote < 8; thisNote++) { // to calculate the note duration, take one second // divided by the note type. //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc. int noteDuration = 1000/noteDurations[thisNote]; tone(3, melody[thisNote],noteDuration); // to distinguish the notes, set a minimum time between them. // the note's duration + 30% seems to work well: int pauseBetweenNotes = noteDuration * 1.30; delay(pauseBetweenNotes); // stop the tone playing: noTone(8); } } void soundOff(){ //kan later nog meer.... } void armpjesOff(){ } void armpjes(){ for(pos = 0; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees { // in steps of 1 degree myservo1.write(pos); // tell servo to go to position in variable 'pos' myservo2.write(pos); tone(3, 1000 + pos*10, 300); delay(15); // waits 15ms for the servo to reach the position } for(pos = 180; pos>=1; pos-=1) // goes from 180 degrees to 0 degrees { myservo1.write(pos); // tell servo to go to position in variable 'pos' myservo2.write(pos); tone(3, 1000 + pos*10, 300); delay(15); // waits 15ms for the servo to reach the position } } void lampjesAan(){ digitalWrite(7, HIGH); digitalWrite(5, HIGH); } void lampjesUit(){ digitalWrite(7, LOW); digitalWrite(5, LOW); delay(100); }
true
86940de1e86701e0996d342ce4eb3d31896b2a53
C++
lee-younggwan/Algorithm
/백준/이런저런/boj_11656.cpp
UTF-8
456
2.578125
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <iostream> #include <string> #include <vector> #include <stack> #include <queue> #include <algorithm> using namespace std; string str; int main() { int i, len; getline(cin, str); len = str.length(); vector <string> vec(len); for (i = 0; i < len; i++) { vec[i] = str; str.erase(0, 1); } sort(vec.begin(), vec.end()); for (i = 0; i < len; i++) cout << vec[i] << "\n"; return 0; }
true
7083ecabf0f34a9eb9bcae212578a58d076ee73f
C++
rsgysel/ChordAlg
/ChordAlgSrc/tests/lb_triang_triangulation_tests.cpp
UTF-8
1,393
2.703125
3
[ "MIT" ]
permissive
#include "gtest/gtest.h" #include "ChordAlgSrc/graph.h" #include "ChordAlgSrc/lb_triang.h" #include "ChordAlgSrc/triangulation.h" #include "test_graphs.h" class LBTriangTest : public ::testing::Test { public: void SetUp() { G_ = nullptr; H_ = nullptr; } void TearDown() { delete G_; delete H_; } void Read(chordalg::AdjacencyLists& A) { if (G_ || H_) { FAIL() << "Use Read once in your test."; } else { G_ = new chordalg::Graph(new chordalg::AdjacencyLists(A)); H_ = chordalg::LBTriang::Run(*G_); EXPECT_EQ(H_->IsMinimalTriangulation(), true); } } protected: chordalg::Graph* G_; chordalg::Triangulation* H_; }; // LBTriangTest ////////////////////////////// // Minimal Triangulation Tests // LBTriang should always return a minimal triangulation TEST_F(LBTriangTest, AtomTestMinimalTriangulation) { Read(atom_test); } TEST_F(LBTriangTest, BipartiteReductionMinimalTriangulation) { Read(bipartite_reduction); } TEST_F(LBTriangTest, DimacsTestMinimalTriangulation) { Read(dimacs_test); } TEST_F(LBTriangTest, IndependentSetMinimalTriangulation) { Read(independent_set); } TEST_F(LBTriangTest, ManyMinsepsFourMinimalTriangulation) { Read(many_minseps_four); } TEST_F(LBTriangTest, TreeMinimalTriangulation) { Read(tree); }
true
744fcce6ec4a97808227122c3ec5d223cde80d8e
C++
NidhishKumarReddy/Coding
/LeetCode/Top-Interview-Questions/Best-Time-to-Buy-and-Sell-Stock.cpp
UTF-8
436
2.953125
3
[]
no_license
class Solution { public: int maxProfit(vector<int>& prices) { int n = prices.size(); int max = INT_MIN; int profit = 0; int ans = 0; for(int i = n-1; i>=0; i--){ if(prices[i] > max){ max = prices[i]; } profit = max - prices[i]; if(profit > ans){ ans = profit; } } return ans; } };
true
b6bf04a25d890fed3f9e278d785394dbc25841e1
C++
LeverImmy/Codes
/比赛/学校/2019-9-13测试/source/PC14_刘子潮/pool.cpp
UTF-8
1,132
2.53125
3
[]
no_license
#include<cstdio> inline int read() { register int x=0; register char ch=getchar(); while(ch<'0' || ch>'9') { ch=getchar(); } while(ch>='0' && ch<='9') { x=x*10+ch-'0',ch=getchar(); } return x; } const int T=100005,mod=1000000007; int t,k,l,r; inline long long int ny(int x) { if(x==1) { return 1; } register long long int mini=mod/x,sum=mini*x; while(true) { if(sum==1) { return mini; } sum+=((mod-sum)/x)*x+x,mini+=(mod-sum)/x+1,sum%=mod; } } inline long long int C(int x,int y) { if(x>y || x<0 || y<0) { return 0; } if(x>y/2) { x=y-x; } register long long int ans=1; for(register int i=y;i>=y-x+1;--i) { ans*=i,ans%=mod; } for(register int i=x;i>=1;--i) { ans*=ny(i),ans%=mod; } return ans; } int main() { freopen("pool.in","r",stdin); freopen("pool.out","w",stdout); t=read(),k=read(); register long long int ans; register int x; for(register int i=1;i<=t;++i) { ans=0,l=read(),r=read(); for(register int j=l;j<=r;++j) { x=((j+1)/(k+1)); for(register int m=0;m<=x;++m) { ans+=C(m,j+1-m*k),ans%=mod; } } printf("%lld\n",ans); } return 0; }
true
ebf6a4a00920327a62293d90e07ec1720476880b
C++
maximborodin/mipt-algorithms-2016-spring
/lcs/main.cpp
UTF-8
2,379
3.34375
3
[]
no_license
#include <iostream> #include <vector> #include <cstring> #include <algorithm> #include <ctime> #include "advancedAlgorithm.h" #include "trivialAlgorithm.h" void stringsGen (std::string& str1, std::string& str2, unsigned int len1, unsigned int len2, unsigned int alphabetSize) { str1.resize(len1); str2.resize(len2); for (int j = 0;j < len1;j++){ str1[j] = static_cast<char>(rand() % alphabetSize) + 'a'; } for (int j = 0;j < len2;j++){ str2[j] = static_cast<char>(rand() % alphabetSize) + 'a'; } } bool checkAnswers (std::vector<std::vector<unsigned int> >& ans1, std::vector<std::vector<unsigned int> >& ans2) { if (ans1.size() != ans2.size()) { return false; } for (size_t i = 0;i < ans1.size();i++){ if (ans1[i].size() != ans2[i].size()){ return false; } for (size_t j = 0;j < ans1[i].size();j++){ if (ans1[i][j] != ans2[i][j]){ return false; } } } return true; } void check (unsigned int testsCount, unsigned int alphabetSize) { alphabetSize = std::min (static_cast<int>(alphabetSize), 26); for (int i = 0;i < testsCount;i++){ std::string str1, str2; int len1 = rand() % 501; // по-хорошему, следует установить % 2001, но тогда int len2 = rand() % 501; // trivial algorithm работает довольно долго( stringsGen (str1, str2, len1, len2, alphabetSize); std::vector<std::vector<unsigned int> > ans1, ans2; ans1 = calculateSuffixPrefixLCS(str1, str2); ans2 = trivialCalculate(str1, str2); if (len1 > 50 || len2 > 50) { std::cout << "Large test" << std::endl; } else { std::cout << "Small test: " << std::endl; std::cout << " String1: " << str1 << std::endl; std::cout << " String2: " << str2 << std::endl; } if (checkAnswers(ans1, ans2)){ std::cout << "Test #" << i << " checked successful" << std::endl; } else{ std::cout << "Test #" << i << " something went wrong" << std::endl; return; } } std::cout << "LCS works right" << std::endl; } int main() { srand(time(NULL)); check(30, 26); return 0; }
true
aed3f6e8c2b5822ed13ba7f5f2129f6dc8a0708a
C++
Hishmat786/C-
/num.cpp
UTF-8
148
2.5625
3
[]
no_license
#include<iostream> using namespace std; int main() { int d,num; cin>>num; while(num>0) { d=num%10; num/=10; cout<<d<<" "; } }
true
4d865a4f969933a169b4f47dbce39d02e3f0a65d
C++
chawkinsuf/ImageTL
/src/SOWAIterator.h
UTF-8
920
2.6875
3
[ "MIT" ]
permissive
#ifndef __SOWAITERATOR_H__ #define __SOWAITERATOR_H__ // Disable warnings about ignoring throws declarations #pragma warning( disable : 4290 ) #include <numeric> #include <iterator> #include <algorithm> #include <cmath> #include "Image.h" #include "ImageException.h" #include "Template.h" #include "OWAIterator.h" namespace ImageTL { template<class Type> class SOWAIterator : public OWAIterator<Type> { public: SOWAIterator(const Image<Type>* image); SOWAIterator(const Image<Type>* image, ConstantTemplate<Type>* tLinkC, ConstantTemplate<Type>* tLinkS); virtual typename ConvolutionIterator<Type>::value_type operator*(); void normalizeLinkedTemplate(); protected: ConstantTemplate<Type>* m_tLinkS; }; } // Include the function definitions in the header if we aren't using a compiled library #ifdef IMAGETL_NO_LIBRARY #include "SOWAIterator.cpp" #endif #endif
true
a121c2ddc8089f89f6eaff0a8eec5d9622e371ca
C++
jac08h/Leetcode-Study-Plan
/Data Structure I/DAY1/maximum_Sum_subarray.cpp
UTF-8
656
3.21875
3
[]
no_license
// Question Link :- https://leetcode.com/problems/maximum-subarray/ #include <bits/stdc++.h> using namespace std; int maxSubArray(vector<int> &nums) { int ans = nums[0], i, j, sum = 0; for (i = 0; i < nums.size(); i++) { sum += nums[i]; ans = max(sum, ans); sum = max(sum, 0); } return ans; } int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<int> nums; for (int i = 0; i < n; i++) { int temp; cin >> temp; nums.push_back(temp); } cout<<maxSubArray(nums)<<endl; } return 0; }
true
4fd7bf221536e028db13e3b9887cd1dd908468ed
C++
GabeOchieng/ggnn.tensorflow
/program_data/PKU_raw/88/199.c
UTF-8
224
2.53125
3
[]
no_license
void main() { char a[40]; int i=0; gets(a); printf("\n"); while(*(a+i)!='\0') { if(*(a+i)>='0'&&*(a+i)<='9') printf("%c",*(a+i)); else if(*(a+i+1)>='0'&&*(a+i+1)<='9') printf("\n"); i++; } }
true
e4e050601c831fcfce255f0bb605786f0582497f
C++
rahulratheesh/datastructures
/mystack_client.cpp
UTF-8
330
2.640625
3
[]
no_license
#include "mystack.h" int main() { MyStack<string> stack; stack.push("Rahul"); stack.push("Rakesh"); stack.push("Ramkesh"); cout << stack.isEmpty() << endl; cout << stack.pop() << endl; cout << stack.pop() << endl; cout << stack.pop() << endl; cout << stack.isEmpty() << endl; return 0; }
true
d8ef989c2e5c6faedaffae31db956668bdac530e
C++
takeuchiwataru/TakeuchiWataru_QMAX
/吉田学園情報ビジネス専門学校 竹内亘/13_ハッカソン冬/開発環境/接待ゴルフ/result.cpp
SHIFT_JIS
3,048
2.53125
3
[]
no_license
//--------------------------------------------------------------------- // Ug [result.cpp] // Author : Mikiya Meguro //--------------------------------------------------------------------- #include "result.h" #include "manager.h" #include "scene.h" #include "Logo.h" //#include "bg.h" #include "fade.h" //#include "resultlogo.h" //-------------------------------------------- //UgNX RXgN^ //-------------------------------------------- CResult::CResult() { m_nCntTimer = 0; } //-------------------------------------------- //UgNX fXgN^ //-------------------------------------------- CResult::~CResult() { } //-------------------------------------------- //IuWFNg̐ //-------------------------------------------- CResult *CResult::Create(void) { //Ug̃|C^ CResult *pResult; pResult = new CResult; //Ug̏ pResult->Init(); //Ug̏Ԃ return pResult; } //============================================================================= // //============================================================================= HRESULT CResult::Init(void) { //eNX`⃂f̓ǂݍ CLogo::Load(); //IuWFNg̐ CLogo::Create(D3DXVECTOR3(SCREEN_WIDTH / 2, 200, 0), 400, 200); //vXG^[̐ //CPressEnter::Create(D3DXVECTOR3(SCREEN_WIDTH / 2, 650, 0), 150); return S_OK; } //============================================================================= // UgNX I //============================================================================= void CResult::Uninit(void) { //eNX`⃂f̔j CLogo::UnLoad(); CScene::ReleaseAll(); } //============================================================================= // UgNX XV //============================================================================= void CResult::Update(void) { //L[{[h擾 CInputKeyboard *pInput = CManager::GetInputKeyboard(); //Rg[[擾 CDirectInput *pInputJoypad = CManager::GetJoypad(); //TEh擾 CSound *pSound = CManager::GetSound(); //؂ւ if (pInput->GetTrigger(DIK_RETURN) == true && CFade::GetFade() == CFade::FADE_NONE || pInputJoypad->GetAnyButton(0) == true && CFade::GetFade() == CFade::FADE_NONE) { //pSound->PlaySound(pSound->SOUND_LABEL_SE_DECIDE); CFade::SetFade(CManager::MODE_RANKING); } //؂ւ(^C}[) m_nCntTimer++; if (m_nCntTimer >= 420 && CFade::GetFade() == CFade::FADE_NONE) { CFade::SetFade(CManager::MODE_RANKING); m_nCntTimer = 0; } CDebugProc::Print(1, " Ug\n"); } //============================================================================= // UgNX `揈 //============================================================================= void CResult::Draw(void) { }
true
ec6d7fefa3bc8ee8f110321e1fa5385103fb9de7
C++
12tg12tg/katanaZERO
/API_FrameWork/camera.h
UHC
2,460
2.6875
3
[]
no_license
#pragma once #include "singleton.h" enum class CAMERASTATE { FOLLOWPIVOT, CHANGEPIVOT, SHAKE }; struct tagShakeTime { int current; int max; int cool; }; enum FADEKIND { FADE_IN, FADE_OUT }; struct tagFadeInfo { FADEKIND fadeKind; bool isStart; int minus; int alpha; }; class camera : public Singleton<camera> { private: //ʱȭ float _cameraSizeX; float _cameraSizeY; CAMERASTATE _state; RECT _cameraRect; float _pivotX, _pivotY; float _maxX, _maxY; float _minX, _minY; float _distanceX, _distanceY; //밪 float _absDistanceX, _absDistanceY; //ǹ float _changePivotX; float _changePivotY; float _changeSpeed; //ǹǥ POINT _moveToPivot; //ȭ鶳. POINT _shakePivot; POINT _savePivot; float _shakePower; tagShakeTime _shakeTime; bool _isShake; //̵ξƿ tagFadeInfo _fadeInfo; //Ŭ̾Ʈ ȭ ũ ݿ 콺 ߰ - 20210827 īŸ RECT _clientGameRc; public: camera(); ~camera(); //ǹǥ, ü ִ/ּũ, Ÿ. HRESULT init(float pivotX, float pivotY, float maxX, float maxY, float minX, float minY, float disX, float disY); HRESULT init(float pivotX, float pivotY, float maxX, float maxY, float minX, float minY, float disX, float disY, float sizeX, float sizeY); void update(); void release(); //̵ξƿ void FadeInit(int time, FADEKIND fadeKind); void FadeStart(); void FadeUpdate(); void FadeRender(HDC hdc); bool& getFadeIsStart() { return _fadeInfo.isStart; } //ī޶ : ṉ̀, ǹٲٱ, ȭ鶳 void movePivot(float x, float y); void ChangePivot(float x, float y, float speed); void setShake(float power, int time, int cool); //ǹݿ ǥ&콺 int getRelativeX(float x); int getRelativeY(float y); POINT getRelativePoint(POINT pt); POINT getRelativeMouse(); POINT getClientMouse(); void setClientRect(RECT rc) { _clientGameRc = rc; } //getter float getPivotX() { return _pivotX; } float getPivotY() { return _pivotY; } float getDistanceX() { return _distanceX; } float getDistanceY() { return _distanceY; } bool getIsShake() { return _isShake; } RECT getRect() { return _cameraRect; } RECT getRelativeRect(RECT rc); //ī޶ getter/setter void setCMState(CAMERASTATE state) { _state = state; } CAMERASTATE getCMState() { return _state; } };
true
eb5fd62df3101e95dbf5dcc3407ea92a37230000
C++
shivral/cf
/1000/30/1032b.cpp
UTF-8
609
3.1875
3
[ "Unlicense" ]
permissive
#include <iostream> #include <string> void solve(const std::string& s) { const size_t n = s.length(); unsigned r = 1; while ((n + r - 1) / r > 20) ++r; const unsigned c = (n + r - 1) / r, k = c * r % n; std::cout << r << ' ' << c << '\n'; for (size_t i = 0, j = 0; i < r; ++i) { if (i < k) { std::cout << s.substr(j, c - 1) << '*' << '\n'; j += c - 1; } else { std::cout << s.substr(j, c) << '\n'; j += c; } } } int main() { std::string s; std::cin >> s; solve(s); return 0; }
true
d772e16f765246f6b23068449e7a7f5de31ef03f
C++
lingjf/h2unit
/source/json/h2_select.cpp
UTF-8
2,059
2.859375
3
[ "Apache-2.0" ]
permissive
struct h2_json_select { struct value { int index; h2_string key; }; h2_vector<value> values; h2_json_select(const char* selector) { enum { st_idle, st_in_dot, st_in_bracket }; int state = 0; const char *s = nullptr, *p = selector; do { switch (state) { case st_idle: if (*p == '.') { state = st_in_dot; s = p + 1; } else if (*p == '[') { state = st_in_bracket; s = p + 1; } break; case st_in_dot: if (*p == '.') { // end a part if (s < p) add(s, p, true); // restart a new part state = st_in_dot; s = p + 1; } else if (*p == '[') { // end a part if (s < p) add(s, p, true); // restart a new part state = st_in_bracket; s = p + 1; } else if (*p == '\0') { if (s < p) add(s, p, true); state = st_idle; } break; case st_in_bracket: if (*p == ']') { if (s < p) add(s, p, false); state = st_idle; } break; } } while (*p++); } void add(const char* start, const char* end, bool only_key) // [start, end) { start = strip_left(start, end); end = strip_right(start, end); if (start < end) { if (!only_key) { if (strspn(start, "-0123456789") == (size_t)(end - start)) { values.push_back({atoi(start), ""}); return; } else if ((*start == '\"' && *(end - 1) == '\"') || (*start == '\'' && *(end - 1) == '\'')) { ++start, --end; } } if (start < end) values.push_back({0, h2_string(end - start, start)}); } } };
true
f268b39fce8a810a9a6c320e25181b6b813c0f99
C++
benardp/Wickbert
/Particles/nv_pbuffer.cpp
UTF-8
7,635
2.515625
3
[]
no_license
//only included if WB_USE_CG is 1 #ifdef WB_USE_CG // make sure glh_ext is only compiled once #include "nv_pbuffer.h" #include <iostream> using namespace std; #define REQUIRED_EXTENSIONS "WGL_ARB_extensions_string " \ "WGL_ARB_pbuffer " \ "WGL_NV_render_texture_rectangle " \ "WGL_ARB_pixel_format " \ "WGL_NV_render_depth_texture " \ "GL_ARB_multitexture " #define MAX_ATTRIBS 256 #define MAX_PFORMATS 256 /* This routine doesn't seem to find the WGL extensions so it will fail * but not bomb out. */ void nv_pbuffer::testExtensions() { cerr << glGetString(GL_EXTENSIONS) << endl; if(!glewIsSupported(REQUIRED_EXTENSIONS)) { char *ext = (char *)glGetString(GL_EXTENSIONS); cerr << "Some necessary extensions were not supported:" << endl << REQUIRED_EXTENSIONS; cerr << "Supported Extensions: " << glGetString(GL_EXTENSIONS) << endl << endl; cerr << "Supported Renderer: " << glGetString(GL_RENDERER) << endl << endl; //exit(0); } } nv_pbuffer::~nv_pbuffer() { if ( hpbuffer ) { // Only delete the context if it belongs to us. if (onecontext == FALSE) wglDeleteContext( hglrc ); wglReleasePbufferDCARB(hpbuffer, hdc); wglGetLastError(); wglDestroyPbufferARB(hpbuffer); wglGetLastError(); hpbuffer = 0; } } nv_pbuffer::nv_pbuffer(int width, int height, int pass) { memset(this,0,sizeof(nv_pbuffer)); HDC hdc = wglGetCurrentDC(); int pixelformat = GetPixelFormat(hdc); HGLRC hglrc = wglGetCurrentContext(); wglGetLastError(); // Query for a suitable pixel format based on the specified mode. int format; int pformat[MAX_PFORMATS]; unsigned int nformats; int iattributes[2*MAX_ATTRIBS]; float fattributes[2*MAX_ATTRIBS]; int nfattribs = 0; int niattribs = 0; // Attribute arrays must be "0" terminated - for simplicity, first // just zero-out the array entire, then fill from left to right. memset(iattributes,0,sizeof(int)*2*MAX_ATTRIBS); memset(fattributes,0,sizeof(float)*2*MAX_ATTRIBS); // Since we are trying to create a pbuffer, the pixel format we // request (and subsequently use) must be "p-buffer capable". iattributes[niattribs ] = WGL_DRAW_TO_PBUFFER_ARB; iattributes[++niattribs] = GL_TRUE; // Since we're trying to create a depth texture of the entire // screen (which may have an arbitrary aspect ratio) we need // a texture rectangle. if (pass == 1) { iattributes[++niattribs] = WGL_BIND_TO_TEXTURE_RECTANGLE_DEPTH_NV; iattributes[++niattribs] = GL_TRUE; } else if (pass == 2) { iattributes[++niattribs] = WGL_RED_BITS_ARB; iattributes[++niattribs] = 16; iattributes[++niattribs] = WGL_GREEN_BITS_ARB; iattributes[++niattribs] = 16; iattributes[++niattribs] = WGL_BLUE_BITS_ARB; iattributes[++niattribs] = 16; iattributes[++niattribs] = WGL_ALPHA_BITS_ARB; iattributes[++niattribs] = 16; iattributes[++niattribs] = WGL_FLOAT_COMPONENTS_NV; iattributes[++niattribs] = GL_TRUE; iattributes[++niattribs] = WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGBA_NV; iattributes[++niattribs] = GL_TRUE; } PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB"); if ( !wglChoosePixelFormatARB( hdc, iattributes, fattributes, MAX_PFORMATS, pformat, &nformats ) ) { cerr << "pbuffer creation error: wglChoosePixelFormatARB() failed.\n"; exit( -1 ); } wglGetLastError(); if ( nformats <= 0 ) { cerr << "pbuffer creation error: Couldn't find a suitable pixel format.\n"; exit( -1 ); } // Ideally, we'd like to share the same context we're currently using for our // rendering window with the pbuffer. In order to do this, the pixel formats // must be the same for both the pbuffer and the rendering window. So, we check // to see if whatever pixel format we're using for our rendering window is in the // list of appropriate formats we just created. If it, we use the existing context // and if not, we'll create a new context. format = pformat[0]; if (pass == 1) { for (unsigned int i = 0; i < MAX_PFORMATS; i++) { if (pformat[i] == pixelformat) { format = pixelformat; onecontext = true; break; } } } // set the pbuffer attributes... memset(iattributes,0,sizeof(int)*2*MAX_ATTRIBS); niattribs = 0; // we need to render to a depth texture if (pass == 1) { iattributes[niattribs] = WGL_DEPTH_TEXTURE_FORMAT_NV; iattributes[++niattribs] = WGL_TEXTURE_DEPTH_COMPONENT_NV; } else if (pass == 2) { iattributes[niattribs] = WGL_TEXTURE_FORMAT_ARB; iattributes[++niattribs] = WGL_TEXTURE_FLOAT_RGBA_NV; } // and we need to render to a rectangle iattributes[++niattribs] = WGL_TEXTURE_TARGET_ARB; iattributes[++niattribs] = WGL_TEXTURE_RECTANGLE_NV; PFNWGLCREATEPBUFFERARBPROC wglCreatePbufferARB = (PFNWGLCREATEPBUFFERARBPROC)wglGetProcAddress("wglCreatePbufferARB"); // Create the p-buffer. this->hpbuffer = wglCreatePbufferARB( hdc, format, width, height, iattributes ); if ( this->hpbuffer == 0) { cerr << "pbuffer creation error: wglCreatePbufferARB() failed\n"; wglGetLastError(); return; } wglGetLastError(); PFNWGLGETPBUFFERDCARBPROC wglGetPbufferDCARB = (PFNWGLGETPBUFFERDCARBPROC)wglGetProcAddress("wglGetPbufferDCARB"); // Get the device context. this->hdc = wglGetPbufferDCARB( this->hpbuffer ); if ( this->hdc == 0) { cerr << "pbuffer creation error: wglGetPbufferDCARB() failed\n"; wglGetLastError(); return; } wglGetLastError(); // Create a context for the p-buffer IF we're not using the same context as the // current rendering window. if (onecontext == true) this->hglrc = hglrc; else this->hglrc = wglCreateContext( this->hdc ); if ( this->hglrc == 0) { cerr << "pbuffer creation error: wglCreateContext() failed\n"; wglGetLastError(); return; } wglGetLastError(); PFNWGLQUERYPBUFFERARBPROC wglQueryPbufferARB = (PFNWGLQUERYPBUFFERARBPROC)wglGetProcAddress("wglQueryPbufferARB"); // Determine the actual width and height we were able to create. wglQueryPbufferARB( this->hpbuffer, WGL_PBUFFER_WIDTH_ARB, &this->width ); wglQueryPbufferARB( this->hpbuffer, WGL_PBUFFER_HEIGHT_ARB, &this->height ); } // If we get an error, crash the program! void nv_pbuffer::wglGetLastError() { DWORD err = GetLastError(); switch(err) { case ERROR_INVALID_PIXEL_FORMAT: cerr << "Win32 Error: ERROR_INVALID_PIXEL_FORMAT\n"; exit(-1); break; case ERROR_NO_SYSTEM_RESOURCES: cerr << "Win32 Error: ERROR_NO_SYSTEM_RESOURCES\n"; exit(-1); break; case ERROR_INVALID_DATA: cerr << "Win32 Error: ERROR_INVALID_DATA\n"; exit(-1); break; case ERROR_INVALID_WINDOW_HANDLE: cerr << "Win32 Error: ERROR_INVALID_WINDOW_HANDLE\n"; exit(-1); break; case ERROR_RESOURCE_TYPE_NOT_FOUND: cerr << "Win32 Error: ERROR_RESOURCE_TYPE_NOT_FOUND\n"; exit(-1); break; case ERROR_SUCCESS: // no error break; default: cerr << "Win32 Error: " << err << endl; exit(-1); break; } SetLastError(0); } #endif
true
b474070b29c923b967ca5072997d2b6569c8b4ff
C++
zv/metamage_1
/base/chars/encoding/utf8.cc
UTF-8
2,081
3.015625
3
[]
no_license
/* utf8.cc ------- */ #include "encoding/utf8.hh" namespace chars { static inline bool is_continuation_byte( utf8_t c ) { return (c & 0xC0) == 0x80; } void put_code_point_into_utf8( unichar_t uc, unsigned n_bytes, char* p ) { switch ( n_bytes ) { default: case 0: break; case 1: p[0] = uc; break; case 2: p[0] = 0xC0 | uc >> 6 & 0x1F; p[1] = 0x80 | uc & 0x3F; break; case 3: p[0] = 0xE0 | uc >> 12 & 0x0F; p[1] = 0x80 | uc >> 6 & 0x3F; p[2] = 0x80 | uc & 0x3F; break; case 4: p[0] = 0xF0 | uc >> 18 & 0x07; p[1] = 0x80 | uc >> 12 & 0x3F; p[2] = 0x80 | uc >> 6 & 0x3F; p[3] = 0x80 | uc & 0x3F; break; } } unichar_t get_next_code_point_from_utf8( const char*& p, const char* end ) { const unsigned n_bytes = count_utf8_bytes_in_char( p[0] ); if ( n_bytes == 0 || p + n_bytes > end ) { return unichar_t( -1 ); } switch ( n_bytes ) { // These return or fall through case 4: if ( !is_continuation_byte( p[3] ) ) return unichar_t( -1 ); case 3: if ( !is_continuation_byte( p[2] ) ) return unichar_t( -1 ); case 2: if ( !is_continuation_byte( p[1] ) ) return unichar_t( -1 ); default: break; } unichar_t result = unichar_t( -1 ); switch ( n_bytes ) { case 1: result = p[0]; break; case 2: result = (p[0] & 0x1F) << 6 | p[1] & 0x3F; break; case 3: result = (p[0] & 0x0F) << 12 | (p[1] & 0x3F) << 6 | p[2] & 0x3F; if ( result < 0x800 || result >= 0xD800 && result < 0xE000 ) { // overlong encoding, or surrogate return unichar_t( -1 ); } break; case 4: result = (p[0] & 0x07) << 18 | (p[1] & 0x3F) << 12 | (p[2] & 0x3F) << 6 | p[3] & 0x3F; if ( result < 0x10000 ) { return unichar_t( -1 ); } break; default: return unichar_t( -1 ); } p += n_bytes; return result; } }
true
2b65861183ed2884d715ae5ba2a87bf96257298f
C++
creator83/stm8s003
/cpp/prj/use_spi.cpp
UTF-8
918
2.515625
3
[]
no_license
#include "stm8s.h" #include "spi.h" #include "delay.h" #include "tact.h" Tact frq; Spi spi1 (Spi::div128); Pin cs (Gpio::C, 4, Gpio::lowSpeed); void spi_transmitte_byte (uint8_t d) { cs.clear(); spi1.transfer (d); cs.set(); } int main() { cs.set(); while (1){ for (uint8_t i=0;i<8;++i){ spi_transmitte_byte (1<<i); delay_ms (100); } for (uint8_t i=6;i>0;--i){ spi_transmitte_byte (1<<i); delay_ms (100); } /* delay_ms (200); spi1.transfer (0x0F); delay_ms (200); for (uint8_t i = 8;i<16;++i) { spi1.transfer_16 (1<<i); delay_ms (20); } for (int8_t i = 0;i<8;++i) { spi1.transfer_16 (1<<i); delay_ms (20); } for (int8_t i = 6;i>=0;--i) { spi1.transfer_16 (1<<i); delay_ms (20); } for (int8_t i = 15;i>8;--i) { spi1.transfer_16 (1<<i); delay_ms (20); } */ } }
true
070e7a9df3d58fc51f6a0b5f90a90b35fd3f6d18
C++
kicchi/Procon
/AtCoder/others/nanka/A/main.cpp
UTF-8
1,307
2.671875
3
[]
no_license
#include<iostream> #include<vector> #include<string> #include<cstdlib> #include<sstream> #include<queue> #include<deque> #include<cmath> #include<algorithm> #include<stack> #include<map> #include<set> #include<iomanip> #define INF 2147483647 #define lli long long int #define MOD 1000000007 using namespace std; typedef vector<int> vi; typedef vector< vector<int> > vvi; typedef pair<int,int> pii; typedef vector<pair<int,int>> vpii; void printv(vi v){ for(int i = 0; i < v.size(); i++){ cout << v[i] << " "; }cout << endl; return ; } bool check(vi x){ for (int i = 0; i < x.size(); i++){ if (x[i] != 0) return false; } return true; } bool locate(vi x, int xi,int index){ //cout << x.size() << endl; for (int i = 0; i < x.size(); i++){ if (x[i] == xi){ if (index != i){ return false; } } } return true; } int dfs(vi x,int ans){ if (check(x)){ cout << 1 << endl; return 1; } printv(x); for (int i = 0; i < x.size(); i++){ x[i] -= 1; if (locate(x,x[i],i) and x[i] >= 0){ ans += dfs(x,ans); } x[i] += 1; x[i] -= 2; if (locate(x,x[i],i) and x[i] >= 0){ ans += dfs(x,ans); } x[i] += 2; } return ans; } int main() { int n; cin >> n; vi x(n); for (int i = 0; i < n; i++){ cin >> x[i]; } cout << dfs(x,0) << endl; return 0; }
true
cd06ea6c4a316bed5bd35297083aed027b770ca6
C++
HONGJICAI/LeetCode
/cpp/977.SquaresofaSortedArray.cpp
UTF-8
684
3.109375
3
[]
no_license
class Solution { // Runtime: 100 ms, faster than 96.05% of C++ online submissions for Squares of a Sorted Array. public: vector<int> sortedSquares(vector<int>& A) { vector<int> res; int mid = lower_bound(begin(A), end(A), 0) - begin(A); for (int r = mid, l = mid - 1; r < A.size() || l >= 0;) { int lval=l>=0?A[l]*A[l]:numeric_limits<int>::max(); int rval=r<A.size()?A[r]*A[r]:numeric_limits<int>::max(); if(lval<rval){ res.push_back(lval); --l; } else{ res.push_back(rval); ++r; } } return res; } };
true
8e927452172995f9c345763decfcd2615d7e4c9a
C++
blewert/a3-udp-chair-cancel-axes
/src/pcars/PCarsMemory.cpp
UTF-8
1,428
2.53125
3
[]
no_license
#include "..\..\include\pcars\PCarsMemory.h" using namespace PCars; SharedMemoryClient::SharedMemoryClient(void) { } SharedMemoryClient::~SharedMemoryClient(void) { } void SharedMemoryClient::BlockUntilDetected(bool waitingAnimation) { if (!waitingAnimation) { while ((this->game = this->GetSharedMemory()) == NULL); } else { const int delay = 100; while ((this->game = this->GetSharedMemory()) == NULL) { Sleep(delay); std::cout << "\b\\" << std::flush; Sleep(delay); std::cout << "\b|" << std::flush; Sleep(delay); std::cout << "\b/" << std::flush; Sleep(delay); std::cout << "\b-" << std::flush; } std::cout << std::endl; } } SharedMemoryData::SharedMemory* PCars::SharedMemoryClient::GetSharedMemory(void) const { // Open the memory-mapped file HANDLE fileHandle = OpenFileMappingA(PAGE_READONLY, FALSE, MAP_OBJECT_NAME); if (fileHandle == NULL) return NULL; // Get the data structure SharedMemoryData::SharedMemory* sharedData = new SharedMemoryData::SharedMemory; //Get map sharedData = (SharedMemoryData::SharedMemory*)MapViewOfFile(fileHandle, PAGE_READONLY, 0, 0, sizeof(SharedMemoryData::SharedMemory)); if (sharedData == NULL) { CloseHandle(fileHandle); return NULL; } // Ensure we're sync'd to the correct data version if (sharedData->mVersion != SharedMemoryData::SHARED_MEMORY_VERSION) return NULL; //And return it return sharedData; }
true
9597425a789cfefecdcc75d3e83d24ef7d1120d0
C++
rising-stark/Competitive-Questions
/LeetCode/30-Day Challenge/Day16_LongestValidParenthesis.cpp
UTF-8
2,356
3.6875
4
[]
no_license
/* https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/530/week-3/3301/ Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules: Any left parenthesis '(' must have a corresponding right parenthesis ')'. Any right parenthesis ')' must have a corresponding left parenthesis '('. Left parenthesis '(' must go before the corresponding right parenthesis ')'. '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string. An empty string is also valid. Example 1: Input: "()" Output: True Example 2: Input: "(*)" Output: True Example 3: Input: "(*))" Output: True Note: The string size will be in the range [1, 100]. */ class Solution { bool res(string s, int i, int c){ if(c<0){ return false; } if(i==s.length()){ if(c==0){ return true; }else{ return false; } } if(s[i]=='('){ return res(s, i+1, c+1); }else if(s[i]==')'){ return res(s, i+1, c-1); }else{ bool a,b,d; a=b=d=false; a=res(s, i+1, c+1); b=res(s, i+1, c-1); d=res(s, i+1, c); return (a || b || d); } } public: bool checkValidString(string s) { int i,n; stack<int> b,c; //return res(s, 0, 0); n=s.length(); for(i=0;i<n;i++){ if(s[i]=='(') b.push(i); else if(s[i]=='*'){ c.push(i); }else{ if(b.empty()){ if(c.empty()) return false; else { c.pop(); } }else{ b.pop(); } } //cout<<"i= "<<i<<"c = "<<c<<" b= "<<b<<endl; } while(!b.empty() && !c.empty()){ int x=b.top(); int y=c.top(); if(y>x){ b.pop(); c.pop(); }else{ return false; } } if(b.empty()) return true; return false; } };
true
bccee18e2bae10a45c295e1673d76a876ea5c870
C++
andrefmrocha/MIEIC_18_19_AEDA_PT2
/src/Company.cpp
UTF-8
35,013
3.125
3
[ "MIT" ]
permissive
/* * Created on: 30/10/2018 * Author: joaomartins * * Company.cpp */ #include "Company.h" #include <string> using namespace std; static unsigned maxRepairs = 4; Company::Company(double cardValue, Date d) { this->cardValue = cardValue; date=d; } void Company::createCourt() { // Creates a new Court and saves it Court newcourt(date.getYear()); tennisCourts.push_back(newcourt); } void Company::addRepairer(std::string name, std::string gender) { Supporter ts(name, gender); this->techSupport.push(ts); } vector<Court> Company::getCourts() { return tennisCourts; } vector<Teacher> Company::getTeachers() { vector<Teacher> temp; for(auto i : teachers) { if(i.getStatus()) temp.push_back(i); } return temp; } Teacher Company::getTeacher(std::string teacherName) { for(auto i: teachers) { if (i.getName() == teacherName) { Teacher temp = i; teachers.erase(i); return temp; } } throw(NoTeacherRegistered(teacherName)); } User Company::getUser(string userName) { set<User>::iterator it = users.begin(); while (it != users.end()) { if (it->getName() == userName) { User a = *it; users.erase(it); return a; } else it++; } throw NoUserRegistered(userName); } vector<Reservation*>::iterator Company::getScheduledReservation( vector<Reservation*> &reservs, const int &month, const int &day, const double &startingHour, const unsigned int &duration) { Reservation res(month,day,startingHour,0,duration); for(auto i = reservs.begin(); i != reservs.end(); i++) { if(**i == res) { return i; } } return reservs.end(); } vector<Lesson*>::iterator Company::getScheduledLesson(std::string teacherName, vector<Lesson*> &lessons, const int &month, const int &day, const double &startingHour, const unsigned int &duration) { Lesson l(month, day, startingHour, 0, duration, teacherName); for(auto i = lessons.begin(); i!= lessons.end(); i++) { if(**i == l) { return i; } } return lessons.end(); } bool Company::makeLesson(int month,int day,double startingHour,string userName) { // Checks if its a possible date if(month < date.getMonth() || (month == date.getMonth() && day < date.getDay())) { return false; } User u; Teacher temp; try { u = getUser(userName); // Gets the user temp = getTeacher(u.getTeacher()); if(!temp.getStatus()) { throw (InactiveTeacher(temp.getName())); } for(auto &j : tennisCourts) // Finds the first court where it can reserve the Class { if(j.reserveClass(month,day,startingHour,u,temp)) { teachers.insert(temp); users.insert(u); return true; } } teachers.insert(temp); users.insert(u); return false; } catch(NoUserRegistered &u) { // If the user doesn't exist cout << u.what() << endl; return false; } catch(NoTeacherRegistered &t) // If the teacher doesn't exist { users.insert(u); cout << t.what() << endl; return false; } catch(InactiveTeacher &i) //if the teacher find is inactive { users.insert(u); teachers.insert(temp); cout << i.what() << endl; return false; } } bool Company::makeFree(int month,int day,double startingHour, int duration,string username) { // Checks if its a possible date if(month < date.getMonth() || (month == date.getMonth() && day < date.getDay())) { cout << "Invalid date. " << endl; return false; } if(duration > 4) { cout << "Duration exceeds allowed period. " << endl; return false; } try { User u; u= getUser(username); // Gets the user for(size_t j =0; j<tennisCourts.size();j++) //Reserves the first available court { if(tennisCourts[j].reserveFree(month,day,startingHour,duration,u)) { users.insert(u); return true; } } users.insert(u); return false; } catch(NoUserRegistered &u) { //Checks if the user is registered cout << u.what() << endl; return false; } } bool Company::checkNIF(int nif) { set<User>::iterator it = users.begin(); while (it != users.end()) { if ( (it->getNIF() == nif && it->isActive() ) || to_string(nif).size() != 9) { cout << to_string(nif).size() << endl; return false; } else it++; } if(to_string(nif).size() != 9) return false; else return true; } bool Company::registerUser(string name, int age,bool isGold,string gender, string address, int nif, bool active) { if (age <0) //Checks if it's a possible age throw(InvalidAge(age)); if(!checkNIF(nif)) throw(InvalidNIF(nif)); try { User u; u= getUser(name); if(u.isActive() == false) { u.editAge(age); u.editAdress(address); u.editNIF(nif); u.editIsGold(isGold); u.editGender(gender); u.changeActive(true); users.insert(u); Teacher temp = getTeacher(u.getTeacher()); temp.addStudent(); teachers.insert(temp); return true; } else { users.insert(u);//Checks if there's a user already registered throw (AlreadyRegisteredUser(name)); } } catch(NoUserRegistered &u) { Teacher t2 = *teachers.begin(); for(auto i: teachers) { //Adds a teacher to the student if (t2.getnStudents() >= i.getnStudents() && i.getStatus()) t2 = i; } teachers.erase(t2); t2.addStudent(); teachers.insert(t2); User newUser(name,age,gender,isGold,t2.getName(), address, nif, true); users.insert(newUser); return true; } catch(AlreadyRegisteredUser &u) { cout << u.what() << endl; return false; } } bool Company::registerTeacher(string teacherName, int age,string gender) { if (age <0) //Checks if it's a possible age throw(InvalidAge(age)); Teacher temp; try { temp = getTeacher(teacherName); //try to find if the wanted teacher is already registered if(temp.getStatus()) //if the teacher is found and already in service, an exception is thrown throw(AlreadyRegisteredTeacher(teacherName)); else { //if the teacher is found and is inactive temp.setStatus(true); teachers.insert(temp); return true; } } catch(NoTeacherRegistered &t) { bool subst = false; for(auto i: teachers) { if(i.getName() != "" && !i.getStatus()) //search the teachers table to find a available one { temp = i; subst = true; break; } } if(!subst) { //if there is none, create a teacher with the wanted parameter temp.editName(teacherName); temp.editAge(age); temp.editGender(gender); } teachers.insert(temp); return true; } catch(AlreadyRegisteredTeacher &u) { cout << u.what() << endl; return false; } } void Company::makeUserReport(User &a, int month,string userName,string teacherName) { Teacher temp; try { temp = getTeacher(teacherName); Report* newr = new Report(userName,teacherName,a.getReservations()); a.setReport(newr,month); } catch(IncorrectMonth &e) //Checks if the month exists { teachers.insert(temp); cout << e.what() << endl; } catch (ReportAlreadyExists &r) //Checks if there's already report for that day { teachers.insert(temp); cout << r.what() << endl; } teachers.insert(temp); } void Company::makeUserInvoice(User &a, string userName,int month) { try { // Makes the invoice and saves it Invoice* newinvoice = new Invoice(a.getName(),a.getTeacher(),a.getReservations(), a.getisGold()); a.setInvoice(newinvoice,month); } catch(IncorrectMonth &e) //Checks if the month doesn't exist { cout << e.what() << endl; } catch (InvoiceAlreadyExists &i) //Checks if the invoice exists { cout << i.what() << endl; } } void Company::scheduleRepair(int day, int month, unsigned ID) { if(this->tennisCourts.size() < ID) throw NoCourtID(ID); Date d(day, month, this->date.getYear()); vector<Supporter> aux; while(!this->techSupport.empty()) { Supporter sup = this->techSupport.top(); this->techSupport.pop(); if(sup.checkAvailability(d) && sup.numRepairs() < maxRepairs) { sup.scheduleRepair(d, this->date, ID); this->techSupport.push(sup); for(auto &i: aux) { this->techSupport.push(i); } return; } else { aux.push_back(sup); } } for(const auto &i: aux) { this->techSupport.push(i); } throw NoSupporterAvailable(day, month); } void Company::updateAvailableDays() { vector<Supporter> aux; while(!this->techSupport.empty()) { Supporter sup = this->techSupport.top(); --sup; aux.push_back(sup); this->techSupport.pop(); } for(const auto &i: aux) { this->techSupport.push(i); } } Company Company::operator++() { ++this->date; //Increments the date if(date.getDay() == 1) { //Checks if the date changes month and year in order to do Invoices and Reports set<User>::iterator it; for(it = users.begin(); it !=users.end(); it++) { User a = *it; users.erase(it); if(date.getMonth() == 1) { a.cleanVectors(); makeUserReport(a, 12,a.getName(),a.getTeacher()); makeUserInvoice(a, a.getName(),12); } else { makeUserReport(a, date.getMonth()-1,a.getName(),a.getTeacher()); makeUserInvoice(a, a.getName(),date.getMonth()-1); } a.cleanReservations(date.getMonth()); users.insert(a); } for(auto i:teachers) { Teacher temp = i; temp.cleanReservation(date.getMonth()); teachers.erase(i); teachers.insert(temp); } } this->updateAvailableDays(); return *this; } //---------------------------------------------------------------------------------------------------------------- void Company::changeName(string name, string newName, int flag) { if (flag == 0) { Teacher temp = getTeacher(name); for(auto i: temp.getLessons()) { i->setTeacher(newName); } for(auto i: users) { if(i.getTeacher() == name) { User u = i; users.erase(u); for(auto j: u.getReservations()) { j->setTeacher(newName); } u.editTeacher(newName); users.insert(u); } } temp.editName(newName); teachers.insert(temp); } else { User a = getUser(name); a.editName(newName); users.insert(a); } } void Company::changeAge(string name, int newAge, int flag) { if (flag == 0) { Teacher temp = getTeacher(name); temp.editAge(newAge); teachers.insert(temp); } else { User a = getUser(name); a.editAge(newAge); users.insert(a); } } void Company::changeGender(string name, string newgender, int flag) { if (flag == 0) { Teacher temp = getTeacher(name); temp.editName(newgender); teachers.insert(temp); } else { User a = getUser(name); a.editGender(newgender); users.insert(a); } } void Company::changeisGold(string name, bool isGold) { User a = getUser(name); a.editIsGold(isGold); users.insert(a); } //need to implement in main void Company::changeNIF(std::string name, int newNIF) { if(!checkNIF(newNIF)) throw(InvalidNIF(newNIF)); User a = getUser(name); a.editNIF(newNIF); users.insert(a); } void Company::changeAddress(std::string name, std::string newAdress) { User a = getUser(name); a.editAdress(newAdress); users.insert(a); } bool Company::modifyReservation(std::string username, int month, int day, double startingHour, unsigned int duration, int newMonth, int newDay, double newStartHour, unsigned int newDuration) { User u; Teacher temp; Reservation* res = NULL; try { u = getUser(username); //try and get the user vector<Reservation*> reservs = u.getReservations(); // retrieve the reservations vector<Reservation*>::iterator itRes = getScheduledReservation(reservs, month, day, startingHour, duration); // get the position on the vector if( itRes == reservs.end()) { throw NoReservation(username); } res = *itRes; if(getScheduledReservation(reservs,newMonth,newDay,newStartHour,newDuration) != reservs.end()) { throw ReservationAlreadyExists(username); } if(!res->getTeacher().empty()) { // if the reservation is a lesson temp = getTeacher(u.getTeacher()); vector<Lesson*> lessons = temp.getLessons(); // retrieve the teachers lessons vector<Lesson*>::iterator itLesson = getScheduledLesson(temp.getName(),lessons,month,day,startingHour,duration); if(getScheduledLesson(temp.getName(),lessons,newMonth,newDay,newStartHour,newDuration) != lessons.end()) { // check if the teacher already has a lesson scheduled for the new date throw TeacherUnavailable(temp.getName()); } //check court availability and change lesson bool flag = true; for(auto &i: this->tennisCourts) { if(i.isOccupied(month, day, startingHour, duration)) { i.unsetReservation(month, day, startingHour, duration); lessons.erase(itLesson); reservs.erase(itRes); u.setReservations(reservs); temp.setLessons(lessons); users.insert(u); teachers.insert(temp); if(this->makeLesson(newMonth, newDay, newStartHour, username)) { flag = false; break; } else throw CourtReserved(newMonth, newDay, newStartHour); } } if(flag) throw NoCourtfound(month, day, startingHour); return true; } else { // if its a free reservation //check court availability and change free bool flag = true; for(auto i: this->tennisCourts) { if(i.isOccupied(month, day, startingHour, duration)) { i.unsetReservation(month, day, startingHour, duration); reservs.erase(itRes); u.setReservations(reservs); users.insert(u); if(this->makeFree(newMonth, newDay, newStartHour, newDuration, username)) { flag = false; break; } else throw CourtReserved(newMonth, newDay, newStartHour); } } if(flag) throw NoCourtfound(month, day, startingHour); return true; } } catch (NoUserRegistered &u) { cout << u.what() << endl; cout << "Your old Reservation has now been removed" << endl; return false; } catch (NoReservation &r) { users.insert(u); cout << r.what() << endl; cout << "Your old Reservation has now been removed" << endl; return false; } catch (TeacherUnavailable &t) { users.insert(u); cout << t.what() << endl; cout << "Your old Reservation has now been removed" << endl; return false; } catch(ReservationAlreadyExists & r) { users.insert(u); teachers.insert(temp); cout << r.what() << endl; cout << "Your old Reservation has now been removed" << endl; return false; } catch (NoCourtfound &c){ users.insert(u); if(!res->getTeacher().empty()) teachers.insert(temp); cout << c.what() << endl; cout << "Your old Reservation has now been removed" << endl; } catch (CourtReserved & c){ users.insert(u); if(!res->getTeacher().empty()) teachers.insert(temp); cout << c.what() << endl; cout << "Your old Reservation has now been removed" << endl; } } //returns true if at least one lesson is rescheduled bool Company::rescheduleLessons(std::vector<Reservation *> &reservs, Teacher &subst, string username) { vector<Reservation *> rejects; vector<Lesson *> lsns = subst.getLessons(); for (auto j = reservs.begin(); j != reservs.end(); j++) { if(!(**j).getTeacher().empty()) { bool found = false; for (auto i : lsns) { if (**j == *i) { rejects.push_back(*j); //add to the rejected lessons reservs.erase(j); //remove from user reservations j--; found = true; break; } } if (!found) { (**j).setTeacher(subst.getName()); lsns.push_back(dynamic_cast<Lesson *>(*j)); } } } subst.setLessons(lsns); if (!rejects.empty()) { cout << "The user: " << username << "has the following lessons unscheduled:" << endl; int n = 1; for (auto i: rejects) { cout << "Lesson nº " << n << ":\t Day/Month: " << i->getDay() << "/" << i->getMonth() << "\t Time: " << i->getStartingHour() << ":" << i->getStartingHour() + i->getDuration() << endl; free(i); } } return rejects.size() != lsns.size(); } void Company::rescheduleRepair(unsigned id, unsigned day, unsigned month, unsigned newDay, unsigned newMonth) { try{ unscheduleRepair(id, day, month); } catch(NoRepair &u) { cout << u.what() << endl; } catch(BadDate &u) { cout << u.what() << endl; } try{ scheduleRepair(newDay, newMonth, id); } catch(NoSupporterAvailable &u) { cout << u.what() << endl; } catch(NoCourtID &u) { cout << u.what() << endl; } catch(BadDate &u) { cout << u.what() << endl; } } //---------------------------------------------------------------------------------------------------------------- bool Company::showReport(string name, int month) { User u; try { u = getUser(name); //Gets the user } catch(NoUserRegistered &e) { //Checks if the user doesn't exist cout << e.what() << endl; return false; } try { cout << u.getReport(month) << endl; //Gets the report based on the month } catch (IncorrectMonth &e) //Checks if the month is possible { users.insert(u); cout << e.what() << endl; return false; } catch (ReportNotAvailable &e) //Checks if the report is available { users.insert(u); cout << e.what() << endl; return false; } users.insert(u); return true; } bool Company::showInvoice(string name,int month) { User u; try { u = getUser(name); //Gets the user } catch(NoUserRegistered &e) { //Checks if the user exists cout << e.what() << endl; return false; } try { cout << u.getInvoice(month) << endl; //Gets the invoice } catch (IncorrectMonth &e) //Checks if the month exists { users.insert(u); cout << e.what() << endl; return false; } catch (InvoiceNotAvailable &e) //Checks if the invoice is available { users.insert(u); cout << e.what() << endl; return false; } users.insert(u); return true; } void Company::showUsers() { //Shows all users set<User>::iterator it = users.begin(); for (size_t i = 0; i < users.size(); i++) { User a = *it; cout << "User no. " << i + 1 << ":" << endl; a.show(); cout << endl; it++; } } bool compareTeacher (Teacher &t1,Teacher &t2) { //Compares 2 teachers return t1.getName() < t2.getName(); } void Company::showTeachers() { //Shows all teachers vector<Teacher> listing; for(auto i: teachers) { listing.push_back(i); } sort(listing.begin(),listing.end(),compareTeacher); int n=0; for(auto i: listing) { n++; cout << "Teacher no. " << n << ":" << endl; i.show(); cout << endl; } } void Company::showTeacher(std::string teacher) { try { Teacher temp = getTeacher(teacher); teachers.insert(temp); temp.show(); cout << endl; } catch (NoTeacherRegistered &e) //Checks if the teacher exists { cout << e.what() << endl; } } void Company::showUser(std::string name) { try { User u = getUser(name); //Gets a specific user u.show(); cout << endl; users.insert(u); } catch (NoUserRegistered &e) //Checks if the user exists { cout << e.what() << endl; } } void Company::showCourts() { for(size_t i=0; i<tennisCourts.size();i++) { cout << "Court ID:" << (i+1) << " - "; this->tennisCourts[i].hoursleft(this->date.getMonth(), this->date.getDay()); } cout << "There is a maximum of " << tennisCourts[0].getMaxUsers() << " per court." << endl; cout << endl; } void Company::showUserReservations(std::string name) { try { User u = getUser(name); users.insert(u); vector <Reservation*> reservations = u.getReservations(); for(size_t i =0;i<reservations.size(); i++) { cout << "Reservation number " << i+1 << ": " << endl; reservations[i]->show(); cout << endl; } } catch (NoUserRegistered &e) { cout << e.what() << endl; } } void Company::showTeacherLessons(std::string teacher) { try { Teacher temp = getTeacher(teacher); teachers.insert(temp); vector <Lesson*> lessons = temp.getLessons(); int n =0; for(auto i: lessons) { n++; cout << "Lesson number " << n << ": " << endl; i->show(); cout << endl; } } catch (NoTeacherRegistered &e) { cout << e.what() << endl; } } void Company::showDate() { cout << date.getDay() << "-" << date.getMonth() << "-"<< date.getYear() << endl << endl; } void Company::listAllRepairers() const { if(this->techSupport.empty()) cout << "The company does not possess any Repairers" << endl; else { priority_queue<Supporter> copy = this->techSupport; while(!copy.empty()) { cout << copy.top(); copy.pop(); } } } //------------------------------------------------------------------------------------------------------------------ void Company::indentation(std::ofstream &outfile, int indentation) { for(int i = 0; i < indentation; i++) { outfile << "\t"; } } void Company::storeInfo(std::ofstream &outfile, int indent) { indentation(outfile, indent); outfile << "{" << endl; indent++; indentation(outfile, indent); //Stores the tennis courts outfile << "\"tennisCourts\": [" << endl; indent++; for(unsigned int i = 0; i < this->tennisCourts.size(); i++) { this->tennisCourts[i].storeInfo(outfile, indent); if(i+1 != this->tennisCourts.size()) outfile << "," << endl; else { outfile << endl; } } indent--; indentation(outfile, indent); outfile << "]," << endl; indentation(outfile, indent); //Saves the users in the company outfile << "\"users\": [" << endl; indent++; for(set<User>::iterator it = users.begin(); it != users.end(); ) { User a; a = *it; a.storeInfo(outfile, indent); indentation(outfile, indent); it++; if( it != this->users.end()) { indentation(outfile, indent); outfile << "," << endl; } } indent--; indentation(outfile, indent); outfile << "]," << endl; indentation(outfile, indent); //Saves the teachers in the company outfile << "\"teachers\": [" << endl; indent++; for(tabTeach::iterator i = teachers.begin(); i != this->teachers.end();) { Teacher temp = *i; temp.storeInfo(outfile, indent); i++; if(i != this->teachers.end()) { indentation(outfile, indent); outfile << "," << endl; } else { //outfile << endl; } } indent--; indentation(outfile, indent); outfile << "]," << endl; indentation(outfile, indent); //Saves the repairer in the company outfile << "\"repairers\": [" << endl; indent++; priority_queue<Supporter> temp = techSupport; while(!techSupport.empty()) { Supporter s = techSupport.top(); s.storeInfo(outfile, indent); techSupport.pop(); if(!techSupport.empty()) { indentation(outfile, indent); outfile << "," << endl; } } indent--; indentation(outfile, indent); outfile << "]," << endl; indentation(outfile, indent); //Saves value of the card outfile << "\"cardValue\": " << this->cardValue << "," << endl; indentation(outfile, indent); //Saves the date information outfile << "\"Date\": " << endl; indent++; date.storeInfo(outfile,indent); outfile << endl; indent--; indentation(outfile, indent); outfile << "}" << endl; } void Company::readInfo(std::ifstream &infile) { string savingString; while (getline(infile, savingString)) { //Gets all the tennis courts if (savingString.find("tennisCourts") != string::npos) { while (getline(infile, savingString)) { if (savingString.find("\t],") != string::npos) { break; } if(savingString.find('{') != string::npos) { Court c; c.readInfo(infile); tennisCourts.push_back(c); } } } //Gets all the users info if (savingString.find("users") != string::npos) { while (getline(infile, savingString)) { if (savingString.find(']') != string::npos) { break; } User u; u.loadClass(infile); users.insert(u); } } //Gets all the teachers info if (savingString.find("teachers") != string::npos) { while (getline(infile, savingString)) { if (savingString.find(']') != string::npos) { break; } Teacher t; t.loadClass(infile); teachers.insert(t); getline(infile,savingString); } } //Gets all the repairers info if (savingString.find("repairers") != string::npos) { while (getline(infile, savingString)) { if (savingString.find("],") != string::npos) { break; } if(savingString.find("{") != string::npos) { Supporter t; t.readInfo(infile); techSupport.push(t); // getline(infile,savingString); } } } //Gets the card Value if (savingString.find("cardValue") != string::npos) { savingString = savingString.substr(savingString.find("cardValue") + 11); savingString = savingString.substr(0, savingString.find(',')); this->cardValue = stod(savingString); } //Gets the Date info if (savingString.find("Date") != string::npos) { Date d; d.readInfo(infile); this->date = d; } } } //------------------------------------------------------------------------------------------------------------------ void Company::removeRepairer(unsigned id) { vector<Supporter> aux; while(!this->techSupport.empty()) { Supporter sup = this->techSupport.top(); this->techSupport.pop(); if(sup.getID() == id) { for(auto &i: aux) { this->techSupport.push(i); } for(auto i: sup.getRepairDates()) { try { this->scheduleRepair(i.getRepairDate().getDay(), i.getRepairDate().getMonth(), i.getSupID()); } catch(NoSupporterAvailable &e) { cout << e.what(); } } return; } else { aux.push_back(sup); } } for(const auto &i: aux) { this->techSupport.push(i); } throw NoSupporterID(id); } //remove the teacher from active status and reassign his/her students to another teach and reschedule all possible lessons bool Company::removeActiveTeacher(std::string teacher) { Teacher rem_teacher; try { rem_teacher = getTeacher(teacher); if(!rem_teacher.getStatus()) throw (InactiveTeacher(teacher)); //get the removed teacher's lessons to be rescheduled vector<Lesson*> mLessons = rem_teacher.getLessons(); Teacher new_teacher(teacher,0,""); bool found_active = false; for(auto j:teachers) { //find the first teacher active in the table if(j.getStatus()) { new_teacher = j; found_active = true; break; } } if(!found_active) //if there are none an exception is thrown { throw (NoActiveTeachersLeft(teacher)); } //remove the teacher active status rem_teacher.setStatus(false); // set to inactivity rem_teacher.cleanVectors(); // clear lessons rem_teacher.cleanNStudents(); //clear nº students assigned teachers.insert(rem_teacher); // keep in the record set<User>::iterator aux; for(set<User>::iterator it = users.begin(); it != users.end();) //reassign another teacher to each student affected { //distribuiting accordingly across the rest of the teachers if(it->getTeacher() == rem_teacher.getName()) { for (auto j: teachers) { if (new_teacher.getnStudents() >= j.getnStudents() && j.getStatus()) new_teacher = j; } teachers.erase(new_teacher); new_teacher.addStudent();// add a student to the substitute teacher std::vector<Reservation *> reservs = it->getReservations(); rescheduleLessons(reservs, new_teacher,it->getName()); // reschedule the possible lessons teachers.insert(new_teacher); User u = *it; aux = it; aux++; users.erase(it); u.editTeacher(new_teacher.getName());//ana side u.editReservations(reservs); //ana side users.insert(u); it = aux; } else { it++; } } return true; } catch(NoTeacherRegistered &t) { cout << t.what() << endl; return false; } catch(InactiveTeacher &i) { teachers.insert(rem_teacher); cout << i.what() << endl; return false; } catch(NoActiveTeachersLeft &a) { teachers.insert(rem_teacher); cout << a.what() << endl; return false; } } void Company::deleteUser(string name) { User u = this->getUser(name); users.insert(u); Teacher temp = getTeacher(u.getTeacher()); temp.removeStudent(); teachers.insert(temp); for(auto i : u.getReservations()) { deleteReservation(name,i->getMonth(),i->getDay(),i->getStartingHour(),i->getDuration()); } u = this->getUser(name); u.deleteUser(); users.insert(u); } void Company::listAvailableRepairers(unsigned daysUntilAvailable) const { priority_queue<Supporter> copy = this->techSupport; while (!copy.empty()) { if(copy.top().getDaysUntilAvailable() < daysUntilAvailable) cout << copy.top(); copy.pop(); } } void Company::unscheduleRepair(unsigned id, unsigned day, unsigned month) { vector<Supporter> aux; Repair rp(0, Date(day, month, this->date.getYear())); while(!this->techSupport.empty()) { Supporter sup = this->techSupport.top(); this->techSupport.pop(); auto it = sup.getRepairDates().find(rp); if(it != sup.getRepairDates().end()) { if(it->getSupID() == id) { sup.getRepairDates().erase(it); this->techSupport.push(sup); for(const auto &i: aux) { this->techSupport.push(i); } return; } } aux.push_back(sup); } for(const auto &i: aux) { this->techSupport.push(i); } throw NoRepair(day, month, id); } bool Company::deleteReservation(std::string username, int month, int day, double startingHour, unsigned int duration) { User u; Teacher temp; Reservation* res = NULL; try { u = getUser(username); //try and get the user vector<Reservation*> reservs = u.getReservations(); // retrieve the reservations vector<Reservation*>::iterator itRes = getScheduledReservation(reservs, month, day, startingHour, duration); // get the position on the vector if( itRes == reservs.end()) { throw NoReservation(username); } res = *itRes; if(!res->getTeacher().empty()) { // if the reservation is a lesson temp = getTeacher(u.getTeacher()); vector<Lesson*> lessons = temp.getLessons(); // retrieve the teachers lessons vector<Lesson*>::iterator itLesson = getScheduledLesson(temp.getName(),lessons,month,day,startingHour,duration); bool flag = true; for(auto & i: this->tennisCourts) { if(i.isOccupied(month, day, startingHour, duration)) { i.unsetReservation(month, day, startingHour, duration); flag = false; break; } } if(flag) throw NoCourtfound(month, day, startingHour); lessons.erase(itLesson); //remove from users' reservation and teachers' lessons reservs.erase(itRes); //delete *itLesson; //delete *itRes; u.setReservations(reservs); temp.setLessons(lessons); teachers.insert(temp); users.insert(u); return true; } else { // if its a free reservation bool flag = true; for(auto i: this->tennisCourts) { if(i.isOccupied(month, day, startingHour, duration)) { i.unsetReservation(month, day, startingHour, duration); flag = false; break; } } if(flag) throw NoCourtfound(month, day, startingHour); reservs.erase(itRes); u.setReservations(reservs); users.insert(u); return true; } } catch (NoUserRegistered &u) { cout << u.what() << endl; return false; } catch (NoReservation &r) { users.insert(u); cout << r.what() << endl; return false; } catch (NoCourtfound &c){ users.insert(u); if(!res->getTeacher().empty()) teachers.insert(temp); cout << c.what() << endl; } } void Company::changeRepairerName(unsigned id, std::string newName) { vector<Supporter> aux; while(!this->techSupport.empty()) { Supporter sup = this->techSupport.top(); this->techSupport.pop(); if(sup.getID() == id) { sup.setName(newName); this->techSupport.push(sup); for(const auto &i: aux) this->techSupport.push(i); return; } aux.push_back(sup); } for(const auto &i: aux) this->techSupport.push(i); throw NoSupporterID(id); } //--------------------------------------------------------------------------------------------------------- //Exception Handling string NoReservation::what() const { return "No Reservation available under user: " + name + " under those conditions"; } string NoUserRegistered::what() const { return "The user with name: " + name + ", is not registered in the system. Please register first."; } string NoTeacherRegistered::what() const { return "The teacher with name: " + name + ", is not registered in the system. Please register first."; } std::string NoSupporterAvailable::what() const { return "There are no supporters available at " + to_string(this->day) + " of " + to_string(this->month) + " \n"; } string InvalidAge::what() const { return "This age is invalid: " + to_string(this->age); } string AlreadyRegisteredUser::what() const { return "There is already a registered user with the name: " + this->name; } string AlreadyRegisteredTeacher::what() const { return "There is already a registered teacher with the name: " + this->name; } std::string InactiveTeacher::what() const { return "The teacher with name: " + name + ", is not currently working for the company."; } std::string NoActiveTeachersLeft::what() const { return "The teacher with name: " + name + ", is the last teacher available. Cannot be removed."; } std::string InvalidNIF::what() const { return "Invalid NIF: " + to_string(nif); } std::string NoSupporterID::what() const { return "The supporter with the ID " + to_string(this->ID) + " is not registered in this company\n"; } std::string NoCourtID::what() const { return "The Court with the ID " + to_string(this->ID) + " is not registered in this company\n"; } std::string ReservationAlreadyExists::what() const { return "There is already a reservation made at that time for the user: " + this->name; } std::string TeacherUnavailable::what() const { return "The teacher: " + this->name + " is not available at that time." ; } std::string NoRepair::what() const { return "No Repair scheduled to the date of " + to_string(this->month) + " on the " + to_string(this->day) + " for the" + + " Court Number " + to_string(this->id); }
true
e72e43392884144a87d370d6a2e64353c11f1756
C++
afikur/UVA-Solutions
/11934 Magic Formula.cpp
UTF-8
397
2.8125
3
[]
no_license
/* Afikur Rahman (afikur) UVA 11934 Date: 20.02.17 */ #include <iostream> using namespace std; int main() { int a,b,c,d,L, counter; while(cin>>a>>b>>c>>d>>L) { if(!a && !b && !c && !d && !L) break; counter = 0; for(int i=0; i<=L; i++) { if((a*i*i + b*i + c) % d == 0) counter++; } cout<<counter<<endl; } return 0; }
true
0b50d316afe58b7f50f9ca12926713b4e9b64443
C++
LinusNeuman/tbs
/TBSA/Source/PathFinding/NavGraph/NavHandle.h
UTF-8
3,480
2.921875
3
[]
no_license
/* *Author: Hampus Huledal *Date: 2016-05-13 */ #pragma once #include "NavGraph/Graph/NavGraph.h" class NavEdge; class NavVertex; struct EdgeHandle { NavHandle myHandle; EdgeHandle() { myHandle = 0; myGraph = nullptr; } EdgeHandle(NavHandle aHandle, NavGraph* aGraph) { myHandle = aHandle; myGraph = aGraph; } EdgeHandle& operator=(const NavHandle& aHandle) { CheckNull(); myHandle = aHandle; return *this; } EdgeHandle operator+(const NavHandle& aHandle) const { CheckNull(); return EdgeHandle(myHandle + aHandle, myGraph); } EdgeHandle& operator+=(const NavHandle& aHandle) { CheckNull(); myHandle += aHandle; return *this; } EdgeHandle operator-(const NavHandle& aHandle) const { CheckNull(); return EdgeHandle(myHandle - aHandle, myGraph); } EdgeHandle& operator-=(const NavHandle& aHandle) { CheckNull(); myHandle -= aHandle; return *this; } EdgeHandle operator*(const NavHandle& aHandle) const { CheckNull(); return EdgeHandle(myHandle * aHandle, myGraph); } EdgeHandle& operator*=(const NavHandle& aHandle) { CheckNull(); myHandle *= aHandle; return *this; } EdgeHandle operator/(const NavHandle& aHandle) const { CheckNull(); return EdgeHandle(myHandle - aHandle, myGraph); } EdgeHandle& operator/=(const NavHandle& aHandle) { CheckNull(); myHandle /= aHandle; return *this; } NavEdge* operator->() const { CheckNull(); return myGraph->GetEdge(myHandle); } bool Null() const { return myGraph == nullptr; } void CheckNull()const { if (Null() == true) { DL_ASSERT(false, "ERROR: Handle is not initialized!!"); } } private: NavGraph * myGraph; }; struct VertexHandle { NavHandle myHandle; VertexHandle() { myHandle = 0; myGraph = nullptr; } VertexHandle(NavHandle aHandle, NavGraph* aGraph) { myHandle = aHandle; myGraph = aGraph; } bool operator==(const VertexHandle& aVertex) const { CheckNull(); return myHandle == aVertex.myHandle && myGraph == aVertex.myGraph; } bool operator!=(const VertexHandle& aVertex)const { return ! (*this == aVertex); } VertexHandle& operator=(const NavHandle& aHandle) { myHandle = aHandle; return *this; } VertexHandle operator+(const NavHandle& aHandle) const { CheckNull(); return VertexHandle(myHandle + aHandle, myGraph); } VertexHandle& operator+=(const NavHandle& aHandle) { CheckNull(); myHandle += aHandle; return *this; } VertexHandle operator-(const NavHandle& aHandle) const { CheckNull(); return VertexHandle(myHandle - aHandle, myGraph); } VertexHandle& operator-=(const NavHandle& aHandle) { CheckNull(); myHandle -= aHandle; return *this; } VertexHandle operator*(const NavHandle& aHandle) const { CheckNull(); return VertexHandle(myHandle * aHandle, myGraph); } VertexHandle& operator*=(const NavHandle& aHandle) { CheckNull(); myHandle *= aHandle; return *this; } VertexHandle operator/(const NavHandle& aHandle) const { CheckNull(); return VertexHandle(myHandle - aHandle, myGraph); } VertexHandle& operator/=(const NavHandle& aHandle) { CheckNull(); myHandle /= aHandle; return *this; } NavVertex* operator->() const { CheckNull(); return myGraph->GetVertex(myHandle); } bool Null() const { return myGraph == nullptr; } void CheckNull()const { if (Null() == true) { DL_ASSERT(false, "ERROR: Handle is not initialized!!"); } } private: NavGraph * myGraph; };
true
e7cd20c12e7af5b5aaa1b34016d4dac21c1ec192
C++
seleneal1996/PRACTICA1_CC2
/Ejercicio3/main.cpp
UTF-8
5,203
3.390625
3
[]
no_license
#include <iostream> #include <stdlib.h> using namespace std; void quickSort(int a[],int primero,int ultimo) { int central,pivote,i,j; //CAPTUTA DE LA POSICION CENTRAL DEL ARREGLO central=(primero+ultimo)/2; // CAPTURA DEL VALOR MEDIO DEL ARREGLO pivote=a[central]; //SIRVE PARA SEPARAR LOS SEGMENTOS i=primero; j=ultimo; //RECORRIDO do { //SEPARANDO EN DOS PARTES EL ARREGLO while(a[i]<pivote) i++;; //ESTOY SEPARANDO LOS VALORES MENORES AL PIVOTE while(a[j]>pivote) j--;; //ESTOY SEPARANDO LOS VALORES MAYORES AL PIVOTE if(i<=j) { //INTERCAMBIANDO LOS VALORES int temporal; temporal=a[i]; a[i]=a[j]; a[j]=temporal; i++; j--; } } while(i<=j); //SI EL PRIMERO DE LA POSICION VA A SER MENOR DE LA POSICION J ENTONCES: if(primero<j) quickSort(a,primero,j); //SI LA POCION I VA SER MENOR QUE EL ULTIMO if(i<ultimo) quickSort(a,i,ultimo); } void merge_(int a[],int aux[], int inicio, int mitad,int fin) { //Mezclar las dos sublistas en una sola lista ordenada. int inicio_end,tam,aux_pos; mitad=(inicio+fin)/2; inicio_end=mitad-1; aux_pos=inicio; tam=fin-inicio+1; while(inicio <=inicio_end && mitad<=fin) { if(a[inicio]<=a[mitad]) { aux[aux_pos]=a[inicio]; aux_pos = aux_pos+1; inicio=inicio+1; } else { aux[aux_pos]=a[mitad]; aux_pos=aux_pos+1; mitad=mitad+1; } } while(inicio<=inicio_end) { aux[aux_pos]=a[inicio]; inicio=inicio+1; aux_pos=aux_pos+1; } while(mitad<=fin) { aux[aux_pos]=a[mitad]; mitad=mitad+1; aux_pos=aux_pos+1; } for(int i=0;i<tam;i++) { a[fin]=aux[fin]; fin=fin-1; } } void mergeSort(int a[], int aux[],int inicio,int fin) { int mitad; if(fin>inicio) { //Dividir la ,lista desordenada en dos sublistas de aproximadamente la mitad del tamaño. mitad=(fin+inicio)/2; //Ordenar cada sublista recursivamente aplicando el ordenamiento por mezcla. mergeSort(a,aux,inicio,mitad); mergeSort(a,aux,mitad+1,fin); merge_(a,aux,inicio,mitad+1,fin); for(int i=inicio;i<=fin;i++){ cout<<a[i]<<" "; } cout<<"----"<<inicio<<" "<<fin<<endl; } } int main() { int opcion,a[100],tam,aux[100]; cout<<"¿OPCION?"<<endl; cout<<"1).QuickSort"<<endl; cout<<"2).MergeSort"<<endl; cout<<"3).InsertionSort"<<endl; cin>>opcion; cout<<"¿Tamaño del arreglo?"<<endl; cin>>tam; system("clear"); //RELLENAR ARREGLO*********** for(int i=0;i<tam;i++) { cout<<"a["<<i<<"]="; cin>>a[i]; } //MOSTRANDO SU ARREGLO******* for(int i=0;i<tam;i++) { cout<<a[i]<<" "; } //IMPLEMENTACION DEL MENU DE OPCIONES********* if(opcion==1||opcion==2||opcion==3||opcion==4) { if(opcion==1) { system("clear"); quickSort(a,0,tam-1); cout<<"\n**ORDENADO POR QUICKSORT**"<<endl; for(int i=0;i<tam;i++) { cout<<a[i]<<" "; } cout<<endl; } else if(opcion==2) { system("clear"); mergeSort(a,aux,0,tam-1); cout<<"\n**ORDENADO POR MERGESORT**"<<endl; for(int i=0;i<tam;i++) { cout<<a[i]<<" "; } cout<<endl; } else if(opcion==3) { system("clear"); //insertionSort(a,tam); //Consta de tomar uno por uno los elementos de un arreglo y recorrerlo hacia su posición con respecto a los anteriormente ordenados. int i,pos,auxi; for(i=0;i<tam;i++) { pos=i; auxi=a[i]; while((pos>0)&&(a[pos-1]>auxi)) // numero a su izq { //INTERCAMBIO a[pos]=a[pos-1]; pos--; //La posicion va disminuyendo } a[pos]=auxi; cout<<"FLAG"<<auxi<<"-"; } cout<<"\n**ORDENADO POR INSERTION_SORT**"<<endl; for(int i=0;i<tam;i++) { cout<<a[i]<<" "; } cout<<endl; //DE MAYOR A MENOR :V for(int i=tam-1;i>=0;i--) { cout<<a[i]<<" "; } } } else { cout << "¡¡¡Entrada no valida!!!" << endl << "Intente de nuevo" << endl; } }
true
7c191ab7242655a5914b78d3b5f6c76497c22ad4
C++
srinivasdasu/leetcode
/Subsets (I & II).cc
UTF-8
4,624
3.796875
4
[]
no_license
/* Subsets http://leetcode.com/onlinejudge#question_78 Given a set of distinct integers, S, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example, If S = [1,2,3], a solution is: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ] ======================================================================= Subsets II http://leetcode.com/onlinejudge#question_90 Given a collection of integers that might contain duplicates, S, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example, If S = [1,2,2], a solution is: [ [2], [1], [1,2,2], [2,2], [1,2], [] ] */ // ====================================================== // recursive version, top down approach // ====================================================== class Solution { public: // ====================================================== // Subsets I vector<vector<int> > subsets(vector<int> &S) { if(S.size() == 0) return vector<vector<int> >(1, vector<int>()); sort(S.begin(), S.end()); // sort S at first int x = S.back(); // srote the max item S.pop_back(); // erase the last vector<vector<int> > result = subsets(S); // get the subsets without x for(int i=result.size()-1; i>=0; --i) { result.push_back(result[i]); result.back().push_back(x); // copy the subsets and add x to end } return result; } // end of: vector<vector<int> > subsets(vector<int> &S) // ====================================================== // Subsets II vector<vector<int> > subsetsWithDup(vector<int> &S) { if(S.size() == 0) return vector<vector<int> >(1, vector<int>()); sort(S.begin(), S.end()); // sort S at first int x = S.back(), num = 0; // srote the max item and frequency while(S.size()>0 && S.back()==x) {S.pop_back(); ++num;} // erase the max item and count frequency vector<vector<int> > result = subsetsWithDup(S); // get the subsets without x for(int i=result.size()-1; i>=0; --i) { result.push_back(result[i]); // copy the subsets and add x to end result.back().push_back(x); for(int j=2; j<=num; ++j) { // let candidate appear 1 ~ num times result.push_back(result.back()); // copy the subsets and add x to end result.back().push_back(x); } } return result; } // end of: vector<vector<int> > subsetsWithDup(vector<int> &S) }; // ====================================================== // iterative version, bottom up approach // ====================================================== class Solution { public: // ====================================================== // Subsets I vector<vector<int> > subsets(vector<int> &S) { sort(S.begin(), S.end()); // sort S before getting result vector<vector<int> > result(1, vector<int>()); // put empty set at first for(int i=0; i<S.size(); ++i) { // generate subsets that contains S[0~i] for(int j=result.size()-1; j>=0; --j) { // get the subsets without S[i] result.push_back(result[j]); // copy the subsets and add S[i] to end result.back().push_back(S[i]); } } return result; } // ====================================================== // Subsets II vector<vector<int> > subsetsWithDup(vector<int> &S) { sort(S.begin(), S.end()); // sort S before getting result vector<vector<int> > result(1, vector<int>()); // put empty set at first for(int i=0, num=1; i<S.size(); i+=num, num=1) { // generate subsets that contains S[0~i] while(i+num<S.size() && S[i+num]==S[i]) ++num; // count the frequency of S[i] for(int j=result.size()-1; j>=0; --j) { // get the subsets without S[i] result.push_back(result[j]); // copy the subsets and add S[i] to end result.back().push_back(S[i]); // let S[i] appear 1 time for(int k=2; k<=num; ++k) { // let S[i] appear 2 ~ num times result.push_back(result.back()); // copy the subsets and add S[i] to end result.back().push_back(S[i]); } } } return result; } };
true
c6c26060cf18418d258cca47965cb024443360a6
C++
keshavjoshi142/Code-Archive
/DP/ValidParanthesis.cpp
UTF-8
829
2.6875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; string A; int dp[100000]; int max1; int func(int i) { if(i <= 0) return 0; if(dp[i] == 0) { if(A[i] == ')') { if(A[i-1] == '(') dp[i] = 2 + func(i-2); else { //cout << A[i-1] << endl; int a = func(i-1); if(i -a -1 >= 0 && A[i - a -1] == '(') { dp[i] = 2 + func(i-1); if(i-a-2 >= 0) dp[i] += dp[i-a-2]; } else dp[i] = 0; } } else { dp[i] = 0; } } /*if(dp[i] > max1) max1 = dp[i];*/ return dp[i]; } int main() { cin >> A; max1 = INT_MIN; cout << A.size() << endl; //cout << func(A.size()-1) << endl; for(int i=0 ; i<A.size() ;i++) { memset(dp , 0 , sizeof(dp)); int a = func(i); cout << a << endl; max1 = max(max1 , a); } cout << max1 << endl; }
true
a68fb68352b1d2d089894cef976cec3da41c8be5
C++
zalbhathena/Thesis-Test-Application
/HPA* Program/bin/DCDTsrc/gs_heap.h
UTF-8
4,832
3.328125
3
[]
no_license
/*======================================================================= Copyright 2010 Marcelo Kallmann. All Rights Reserved. This software is distributed for noncommercial use only, without any warranties, and provided that all copies contain the full copyright notice licence.txt located at the base folder of the distribution. =======================================================================*/ # ifndef GS_HEAP_H # define GS_HEAP_H /** \file gs_heap.h * Template for a heap based on GsArray. */ # include "gs_array.h" /*! \class GsHeap gs_heap.h \brief Heap based on a GsArray GsHeap implements a heap ordered binary tree based on a GsArray object. For maximum performance, GsHeap does not honor constructors or destructors of its elements X, so user-managed pointers should be used in case of more complex classes, in the same design line as GsArray. The heap is ordered according to its associated cost. The remove() method will always remove the minimum cost element (from the top). Class X is the element type, and Y is the cost type. Type Y will usually be int, float or double. */ template <typename X, typename Y> class GsHeap { private : struct Elem { X e; Y c; }; GsArray<Elem> _heap; public : /*! Default constructor. */ GsHeap () {} /*! Copy constructor. */ GsHeap ( const GsHeap& h ) : _heap(h._heap) {} /*! Set the capacity of the internal array */ void capacity ( int c ) { _heap.capacity(c); } /*! Returns true if the heap is empty, false otherwise. */ bool empty () const { return _heap.empty(); } /*! Returns the number of elements in the queue. */ int size () const { return _heap.size(); } /*! Initializes as an empty heap */ void init () { _heap.size(0); } /*! Compress the internal heap array */ void compress () { _heap.compress(0); } /*! Make the heap have the given size, by removing the worst elements. Only applicable when s < size(). */ void size ( int s ) { if ( s<=0 ) { init(); return; } if ( s>=size() ) return; GsArray<Elem> tmp(s,s); while ( tmp.size()<s ) { tmp.push() = _heap.top(); remove(); } init(); while ( tmp.size()>0 ) { insert ( tmp.top().e, tmp.top().c ); tmp.pop(); } } /*! Insert a new element with the given cost */ void insert ( const X& elem, Y cost ) { // insert at the end: _heap.push(); _heap.top().e = elem; _heap.top().c = cost; // swim up: (parent of elem k is k/2) Elem tmp; int k=_heap.size(); while ( k>1 && _heap[k/2-1].c>_heap[k-1].c ) { GS_SWAP ( _heap[k/2-1], _heap[k-1] ); k = k/2; } } /*! Removes the element in the top of the heap, which is always the element with lowest cost. */ void remove () { // put last element in top: _heap[0] = _heap.pop(); // sink down: (children of node k are 2k and 2k+1) int j; int k=1; int n=_heap.size(); Elem tmp; while ( 2*k<=n ) { j=2*k; if ( j<n && _heap[j-1].c>_heap[j].c ) j++; if ( !(_heap[k-1].c>_heap[j-1].c) ) break; GS_SWAP ( _heap[k-1], _heap[j-1] ); k=j; } } /*! Get a reference to the top element of the the heap, which is always the element with lowest cost. */ const X& top () const { return _heap[0].e; } /*! Get the lowest cost in the heap, which is always the cost of the top element. */ Y lowest_cost () const { return _heap[0].c; } /*! Returns elem i (0<=i<size) for inspection */ const X& elem ( int i ) const { return _heap[i].e; } /*! Returns the cost of elem i (0<=i<size) for inspection */ Y cost ( int i ) const { return _heap[i].c; } /*! Assumes elements X are pointers and deletes all stored elements, and set the heap to size 0 */ void delete_all () { while (_heap.size()) delete _heap.pop().e; } /*! Assumes elements X are pointers, so it will first delete the top() element of the heap and then call remove() */ void delremove () { delete _heap[0].e; remove(); } /*! Output all elements of the heap in an ordered fashion for debugging. */ friend GsOutput& operator<< ( GsOutput& o, const GsHeap<X,Y>& ch ) { GsHeap<X,Y> h(ch); o << '['; while ( h.size()>0 ) { o << gspc << h.elem(0) << ':' << h.cost(0); h.remove(); } return o << ' ' << ']'; } }; //============================== end of file =============================== #endif // GS_HEAP_H
true
cc570d59106c61d9686468c489ecc7702d64b7a4
C++
kdesai12/Arduino
/PatientDevice/PatientDevice.ino
UTF-8
1,637
2.5625
3
[]
no_license
#include <SPI.h> #include <nRF24L01.h> #include <RF24.h> #include <RF24_config.h> #include <RF24Network.h> RF24 radio(9,10); // Network uses that radio RF24Network network(radio); // Address of our node const uint16_t this_node = 1; // Address of the other node const uint16_t other_node = 0; const uint64_t pipe1 = 0xE8E8F0F0E1LL; // How often to send 'hello world to the other unit const unsigned long interval = 2000; //ms // When did we last send? unsigned long last_sent; void setup(void) { SPI.begin(); radio.begin(); network.begin(/*channel*/ 90, /*node address*/ this_node); //radio.begin(); // optionally, increase the delay between retries & # of retries //radio.setRetries(15,20); //radio.setChannel(100); //radio.openWritingPipe(pipe1); //delay(10000); } void loop(void) { sendDataNetwork(); } void sendDataNetwork() { // Pump the network regularly network.update(); // If it's time to send a message, send it! unsigned long now = millis(); if ( now - last_sent > interval ) { last_sent = now; //toggleLED(); printf("Sending...\r\n"); const char* hello = "Hello, world!"; RF24NetworkHeader header(/*to node*/ other_node); bool ok = network.write(header,hello,strlen(hello)); if (ok) printf("\tok.\r\n"); else { printf("\tfailed.\r\n"); delay(250); // extra delay on fail to keep light on longer } //toggleLED(); } } void sendData(int patientNumber) { radio.stopListening(); //Serial.println(patientNumber); int sent = radio.write(&patientNumber,sizeof(int)); Serial.println(sent); radio.startListening(); }
true
faef83464421342aa73575ce597a8aea4ce4f409
C++
maximejotterand/cppcourse-brunel
/src/Neurone_unittest.cpp
UTF-8
1,691
2.78125
3
[]
no_license
#include "neurone.hpp" #include "network.hpp" #include "gtest/gtest.h" #include <iostream> #include <cmath> #include "Constant.hpp" namespace { TEST(NeuroneTest, Pos_input) { Neurone n; n.setCourant(1.0); //First update n.update(0.1, false); EXPECT_EQ((c1 * 0.0) + (1.0 * R * c2), n.getPot()); //After several updates n.update(500, false); //The neuron should never value 20 but tend to 20 because external courant is 1.0 EXPECT_EQ(0, (n.getSpikes()).size()); EXPECT_GT(1E-3, std::fabs(19.999 - n.getPot())); } TEST(NeuroneTest, t_spikes) { Neurone n2; n2.setCourant(1.01); n2.update(92.3, false); //Update until the first spike to occur //EXPECT_EQ(0, (n2.getSpikes()).size()); EXPECT_EQ(0, n2.getSize()); n2.update(0.1, false); //Then the neuron is reset EXPECT_EQ(1, n2.getSize()); EXPECT_EQ(0, n2.getPot()); } TEST(TwoNeurons, receive) { Neurone n1; Neurone n2; n1.setCourant(1.01); //Updating until n1 spikes + the delay if (n1.update(92.4, false)) { n2.receive(J); } n2.update(D, false); EXPECT_EQ(0.1, n2.getPot()); } TEST(TwoNeurons, neuron2_spikes) { Neurone n3; Neurone n4; n3.setCourant(1.01); n4.setCourant(1.0); //n4 cannot spike because the input current is 1.0 //So its potential will tend to 20 but never reach //With the excitation of the n3 it will be able to spike n4.update(184.9, false); if (n3.update(184.9, false)) { n4.receive(J); } //Before the spike n4.update(D, false); EXPECT_EQ(0, n4.getSize()); //Spike occured n4.update(0.1, false); EXPECT_EQ(1, n4.getSize()); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } }
true
bd411b13a14d9508a8080a3bb0c476b88e1ad4ae
C++
psykano/Tag
/src/game/ClientEventSystem.cpp
UTF-8
1,603
2.71875
3
[]
no_license
#include "ClientEventSystem.h" void ClientEventSystem::step(float dt) { for (std::vector<float>::iterator it = dtsSinceLastReceivedMovementInputEvent.begin(); it != dtsSinceLastReceivedMovementInputEvent.end(); ++it) { *it += dt; } for (std::map<unsigned int, float>::iterator it = dtsSinceLastMovementInputEvent.begin(); it != dtsSinceLastMovementInputEvent.end(); ++it) { ++it->second; } // lots TODO here! *** } void ClientEventSystem::playerConnectedEvent(unsigned int playerNum) { if (playerNum >= dtsSinceLastReceivedMovementInputEvent.size()) { dtsSinceLastReceivedMovementInputEvent.push_back(0); } else { dtsSinceLastReceivedMovementInputEvent.at(playerNum) = 0; } } void ClientEventSystem::playerDisconnectedEvent(unsigned int playerNum) { } void ClientEventSystem::playerMovementInputEvent(unsigned int playerNum, float x, float z, float dt) { ++myMovementInputEvents.at(playerNum); movementInputEvents.push_back(MovementInputEvent(playerNum, x, z, dt)); // send input event *** TODO //queueMovementInputMessage(playerNum, x, z, dt); } void ClientEventSystem::addLocalPlayer(unsigned int playerNum) { myReceivedMovementInputEvents[playerNum] = 0; myMovementInputEvents[playerNum] = 0; dtsSinceLastMovementInputEvent[playerNum] = 0; } void ClientEventSystem::receivedPlayerMovementInputEvent(unsigned int playerNum, float x, float z, float dt, float e) { if (myReceivedMovementInputEvents.count(playerNum) > 0) { ++myReceivedMovementInputEvents.at(playerNum); } receivedMovementInputEvents.push_back(ReceivedMovementInputEvent(playerNum, x, z, dt, e)); }
true
b145169a69a834226edda5acb2a51c7762de83d6
C++
firoorg/firo
/src/elysium/test/strtoint64_tests.cpp
UTF-8
2,978
2.921875
3
[ "MIT" ]
permissive
#include "elysium/parse_string.h" #include "test/test_bitcoin.h" #include <boost/test/unit_test.hpp> #include <stdint.h> #include <string> using namespace elysium; BOOST_FIXTURE_TEST_SUITE(elysium_strtoint64_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(strtoint64_invidisible) { // zero amount BOOST_CHECK(StrToInt64("0", false) == 0); // big num BOOST_CHECK(StrToInt64("4000000000000000", false) == static_cast<int64_t>(4000000000000000LL)); // max int64 BOOST_CHECK(StrToInt64("9223372036854775807", false) == static_cast<int64_t>(9223372036854775807LL)); } BOOST_AUTO_TEST_CASE(strtoint64_invidisible_truncate) { // ignore any char after decimal mark BOOST_CHECK(StrToInt64("8.76543210123456878901", false) == 8); BOOST_CHECK(StrToInt64("8.765432101.2345687890", false) == 8); BOOST_CHECK(StrToInt64("2345.AbCdEhf71z1.23", false) == 2345); } BOOST_AUTO_TEST_CASE(strtoint64_invidisible_invalid) { // invalid, number is negative BOOST_CHECK(StrToInt64("-4", false) == 0); // invalid, number is over max int64 BOOST_CHECK(StrToInt64("9223372036854775808", false) == 0); // invalid, minus sign in string BOOST_CHECK(StrToInt64("2345.AbCdEFG71z88-1.23", false) == 0); } BOOST_AUTO_TEST_CASE(strtoint64_divisible) { // range 0 to max int64 BOOST_CHECK(StrToInt64("0.000", true) == 0); BOOST_CHECK(StrToInt64("92233720368.54775807", true) == static_cast<int64_t>(9223372036854775807LL)); // check padding BOOST_CHECK(StrToInt64("0.00000004", true) == 4); BOOST_CHECK(StrToInt64("0.0000004", true) == 40); BOOST_CHECK(StrToInt64("0.0004", true) == 40000); BOOST_CHECK(StrToInt64("0.4", true) == 40000000); BOOST_CHECK(StrToInt64("4.0", true) == 400000000); // truncate after 8 digits BOOST_CHECK(StrToInt64("40.00000000000099", true) == static_cast<int64_t>(4000000000LL)); BOOST_CHECK(StrToInt64("92233720368.54775807000", true) == static_cast<int64_t>(9223372036854775807LL)); } BOOST_AUTO_TEST_CASE(strtoint64_divisible_truncate) { // truncate after 8 digits BOOST_CHECK(StrToInt64("40.00000000000099", true) == static_cast<int64_t>(4000000000LL)); BOOST_CHECK(StrToInt64("92233720368.54775807000", true) == static_cast<int64_t>(9223372036854775807LL)); BOOST_CHECK(StrToInt64("92233720368.54775807000", true) == static_cast<int64_t>(9223372036854775807LL)); } BOOST_AUTO_TEST_CASE(strtoint64_divisible_invalid) { // invalid, number is over max int64 BOOST_CHECK(StrToInt64("92233720368.54775808", true) == 0); // invalid, more than one decimal mark in string BOOST_CHECK(StrToInt64("1234..12345678", true) == 0); // invalid, alpha chars in string BOOST_CHECK(StrToInt64("1234.12345A", true) == 0); // invalid, number is negative BOOST_CHECK(StrToInt64("-4.0", true) == 0); // invalid, minus sign in string BOOST_CHECK(StrToInt64("4.1234-5678", true) == 0); } BOOST_AUTO_TEST_SUITE_END()
true
75e1dbf15dc0e5961677e5142d61cc775526dd27
C++
patrick1973/hs1-opgave-uitwerkingen
/ArduinoCodePrakticumEE21_opdracht2a/ArduinoCodePrakticumEE21_opdracht2a.ino
UTF-8
761
2.953125
3
[]
no_license
#include <Bounce2.h> const int BUTTON_PIN = 2; const int LED_PIN = 3; int ledState = LOW; // Instantiate a Bounce object Bounce debouncer = Bounce(); void setup() { // Setup the button pinMode(BUTTON_PIN,INPUT); digitalWrite(BUTTON_PIN,HIGH); // After setting up the button, setup Bounce object debouncer.attach(BUTTON_PIN); debouncer.interval(5); //Setup the LED pinMode(LED_PIN,OUTPUT); digitalWrite(LED_PIN,ledState); } void loop() { boolean stateChanged = debouncer.update(); int state = debouncer.read(); // Detect the falling edge if ( stateChanged && state == LOW ) { if ( ledState == LOW ) { ledState = HIGH; } else { ledState = LOW; } digitalWrite(LED_PIN,ledState); } }
true
4fe57e628e860ecd4294ccd2494ae1821fc93683
C++
mrdylan123/ReSharperPresentatie
/ResharperPresentatie/ResharperFuncties.h
UTF-8
588
2.625
3
[]
no_license
#pragma once #include <string> // Use different include and unused #include <math.h> class ResharperFuncties // Non-default destructor { public: ResharperFuncties(); ~ResharperFuncties(); int getX(); // Member function may be 'const' in source file void includeString(); static void variableNotInitialized(); void missingDefaultCase(); void addForwardDeclaration(ForwardDeclaration a) // Add forward declaration { } static void constString(std::string string); private: // Alt insert op members: code generation int x_; int y; // Private member, add underscore: x_; };
true
72a57909b9b7deefa56df69fd9de436f25335642
C++
JaechanAn/algorithm-study
/Jinaria/three problem per day/2020.1/2020.1.3/2850.cpp
UTF-8
805
2.546875
3
[]
no_license
#include <cstdio> #include <vector> #include <algorithm> using namespace std; int main() { int N; long long M; scanf("%d %lld", &N, &M); vector<long long> tree(N); for (int i = 0; i < N; ++i) scanf("%lld", &tree[i]); long long left = 0; long long right = 0x7fffffffffffffff; long long maxNum = 0; while (left <= right) { long long mid = (left + right) / 2; long long result = 0; for (int i = 0; i < N; ++i) { long long t = tree[i] - mid; if (t < 0) continue; result += t; } if (result >= M) { left = mid + 1; if (mid > maxNum) maxNum = mid; } else { right = mid - 1; } } printf("%lld\n", maxNum); }
true
10c924661142b437e42a7ccaa576dc52d958cd68
C++
speedhunter001/cpp
/oop-quiz-1.cpp
UTF-8
2,083
3.296875
3
[]
no_license
#include <iostream> #include <cassert> using namespace std; int fun1(string s,int pos){ string x; if (pos<0) return 0; int digit; x=s[pos]; digit=stoi(x); return digit; } string fun2(string s1,string s2){ int d1,d2,maximum,sum; int carry=0; string sum_string,sum_string_in_tens,out_string; if ( s2.length()<s1.length() ){ while ( s2.length()<s1.length() ){ s2 = "0" + s2; } } else if ( s1.length()<s2.length() ){ while ( s1.length()<s2.length() ){ s1 = "0" + s1; } } maximum = max(s1.length(),s2.length()); out_string = ""; for (int i=maximum-1; i>=0; i--){ d1 = fun1(s1,i); d2 = fun1(s2,i); sum = d1 + carry + d2; if ( (d1 + d2) >10 ){ sum_string_in_tens = to_string(sum); sum_string = sum_string_in_tens[1] ; carry = fun1(sum_string_in_tens,0); out_string = sum_string + out_string; } else if ( (d1 + d2) <10 ){ sum_string = to_string(sum); carry = 0; out_string = sum_string + out_string; } } return out_string; } string fun3(string s){ string string_input_chunk = ""; string string_output = ""; for (int i=0; i<s.length(); i++){ if ( s[i] == ' ' || i+1 == s.length() ){ if ( s[i] != ' ') string_input_chunk = string_input_chunk + s[i]; string_output = string_input_chunk + ' ' + string_output; string_input_chunk = ""; } else string_input_chunk = string_input_chunk + s[i]; } return string_output; } /* void test_fun2(){ assert ("3333333333333333333333344444444555555555555555555" == fun2("1111111111111111111111111111111222222222222222222","2222222222222222222222233333333333333333333333333") ); cout << "yahoo the test passed" <<endl; } */ int main(){ int x[] = {1,2,3}; cout<<fun1("123",1)<<endl; // cout <<to_string(fun1("123",1))<<endl; //to_string is used for converting a number in a string form // cout << max(5,10) <<endl; //cout <<fun2("1111111111111111111111111111111222222222222222222","2222222222222222222222233333333333333333333333333") <<endl; cout <<fun2("1234","19") <<endl; cout <<fun3("My name is Ammar") <<endl; return 0; }
true
01c8f71de5fb13c03de869ac6ee82154ff00cfa4
C++
lukemonaghan/YR01_03_Refactor_BitwiseConversion
/Conversion/Conversion.cpp
UTF-8
13,382
3.015625
3
[]
no_license
//Luke Monaghan - 11/05/2013 - Base 2,10,16 conversion #include "stdafx.h" #include "Convert.h" #include <string.h> #include <iostream> #include <climits> #include <time.h> #define MAXBITS 32 using namespace std; bool running = true; char buffer[48] = {'h','e','l','p'}; Converter ConManager; void getinput(){ ////////////////////////////////////////////////////////////////////////////////////////////////////// Extra Commands if (_strcmpi(buffer, "Exit") == 0){ running = false; return; } if (_strcmpi(buffer, "help") == 0 ){ cout << endl << "Commands" << endl << endl << " - Exit - Closes program" << endl << " - Help - Displays this Help Window" << endl << " - seed - Enter a seed to be used for random functions" << endl << " - Show - Shows the current values saved for both sets" << endl << endl << " - BinFlip - Flips the Current Binary and converts to Hex/Decimal" << endl << " - DecFlip - Flips the Current Decimal and converts to Hex/Binary" << endl << " - HexRand - Chooses random Hex sequence and converts." << endl << " - DecRand - Chooses random Decimal number and converts." << endl << " - BinRand - Chooses random Binary Sequence and converts." << endl << endl << " - BitShift - Shift the binary bits and converts to hex/decimal." << endl << " - <N or >N where N is the shift distance." << endl << endl << " - Decimal / Dec - Input Decimal Number and converts." << endl << " - HexaDecimal / Hex - Input Hexadecimal sequence and converts." << endl << " - Binary / Bin - Input Binary Sequence and converts." << endl << " - Input all 32 bits or \"Nx0000\"" << endl << " - where N = Position(from left) and 0 is bits" << endl; return; } ////////////////////////////////////////////////////////////////////////////////////////////////////// Key codes (debugging) if (_strcmpi(buffer, "keycode") == 0 ){ char temp = ' '; cout << "KEY : ";cin >> temp; cout << (unsigned int)temp; return; } if (_strcmpi(buffer, "ASCII") == 0 ){ int temp = 0; cout << "ASCII CODE : ";cin >> temp; cout << char(temp); return; } if (_strcmpi(buffer, "seed") == 0 ){ int temp = 0; cout << "Seed Value : ";cin >> temp; srand(temp); return; } if (_strcmpi(buffer, "genrand") == 0 ){ int temp = 0; cout << "Loops : ";cin >> temp; for (int i = 0; i < temp; i++){ cout << ConManager.DecRand() << endl; } return; } ////////////////////////////////////////////////////////////////////////////////////////////////////// if (_strcmpi(buffer, "Show") == 0 ){ ConManager.Show(); } ////////////////////////////////////////////////////////////////////////////////////////////////////// if (_strcmpi(buffer, "And") == 0 ){ cout << "Checking First Binary sequence and Second Binary sequence" << endl; ConManager.And(); } ////////////////////////////////////////////////////////////////////////////////////////////////////// if (_strcmpi(buffer, "Or") == 0 ){ cout << "Checking First Binary sequence Second Binary sequence" << endl; ConManager.Or(); } ////////////////////////////////////////////////////////////////////////////////////////////////////// bit Shifting if (_strcmpi(buffer, "BitShift") == 0 ){ bool shifter; cout << "Binary Sequence to shift - 0 or 1 : "; cin >> shifter; cout << "direction and amount : "; cin >> buffer; if (buffer[0] == '<' || buffer[0] == '>'){ for (int i = 1; i < strlen(buffer); i++){ if (buffer[i] >= '9' || buffer[i] <= '0'){ cout << "Error with command at index " << i << " with char " << buffer[i] << endl; return; } } } int base = 1; int decimal = 0; for (int i = strlen(buffer)-1; i > 0; i--){ decimal += (buffer[i] - '0')*base; base*=10; } cout << decimal << endl; bool BinaryTemp[MAXBITS]; for (int i = 0; i <MAXBITS ; i++){ if (!shifter) { BinaryTemp[i] = ConManager.Binary[i]; }else{ BinaryTemp[i] = ConManager.Binary2[i]; } } if (buffer[0] == '>'){ int j; for (int i = 31; i >=0 ; i--){ j = i-decimal; if (j < 0 || j > MAXBITS-1){ j = 0; }else{ j = BinaryTemp[j]; } if (!shifter) { ConManager.Binary[i] = j; }else{ ConManager.Binary2[i] = j; } } }else if (buffer[0] == '<'){ int j; for (int i = 31; i >=0 ; i--){ j = i+decimal; if (j < 0 || j > MAXBITS-1){ j = 0; }else{ j = BinaryTemp[j]; } if (!shifter) { ConManager.Binary[i] = j; }else{ ConManager.Binary2[i] = j; } } } //Convert to Decimal and hex ConManager.Bin2Dec(shifter); ConManager.Bin2Hex(shifter); //Show ConManager.Show(); return; } ////////////////////////////////////////////////////////////////////////////////////////////////////// Fliping if (_strcmpi(buffer, "BinFlip") == 0 ){ bool shifter; cout << "Binary Sequence to flip - 0 or 1 : "; cin >> shifter; //Flip the binary ConManager.BinFlip(shifter); //Convert to Decimal and hex ConManager.Bin2Dec(shifter); ConManager.Bin2Hex(shifter); //Show ConManager.Show(); return; } if (_strcmpi(buffer, "DecFlip") == 0 ){ bool shifter; cout << "Use on - 0 or 1 : "; cin >> shifter; //Flip the binary ConManager.DecFlip(shifter); //Check if its below 0 and do required tasks ConManager.Dec2Bin(shifter); ConManager.Dec2Hex(shifter); //Show ConManager.Show(); return; } if (_strcmpi(buffer, "HexFlip") == 0 ){ bool shifter; cout << "Hexadecial Sequence to use - 0 or 1 : "; cin >> shifter; //Flip the binary ConManager.HexFlip(shifter); //Check if its below 0 and do required tasks ConManager.Hex2Dec(shifter); ConManager.Hex2Bin(shifter); //Show ConManager.Show(); return; } ////////////////////////////////////////////////////////////////////////////////////////////////////// Random sequence Functions if (_strcmpi(buffer, "BinRand") == 0 ){ bool shifter; cout << "Binary Sequence to use - 0 or 1 : "; cin >> shifter; //reset ConManager.Reset(shifter); //Generate the binary sequence if (!shifter){ for (int i = 0; i < 32; i++){ ConManager.Binary[i] = bool(rand()%2); } }else{ for (int i = 0; i < 32; i++){ ConManager.Binary2[i] = bool(rand()%2); } } //Convert to Decimal and Hex ConManager.Bin2Dec(shifter); ConManager.Bin2Hex(shifter); //Display the 3 outputs ConManager.Show(); return; } if (_strcmpi(buffer, "DecRand") == 0 ){ bool shifter; cout << "Binary Sequence to use - 0 or 1 : "; cin >> shifter; //reset ConManager.Reset(shifter); //Create random decimal number if (!shifter){ ConManager.Decimal = ConManager.DecRand(); }else{ ConManager.Decimal2 = ConManager.DecRand(); } ConManager.Dec2Hex(shifter); ConManager.Dec2Bin(shifter); //Display the 3 outputs ConManager.Show(); return; } if (_strcmpi(buffer, "HexRand") == 0 ){ bool shifter; cout << "Binary Sequence to use - 0 or 1 : "; cin >> shifter; //reset ConManager.Reset(shifter); //Generate random hex sequence if (!shifter){ for (int i = 0; i < 8; i++){ ConManager.Hex[i] = ConManager.RandHexChar(); } }else{ for (int i = 0; i < 8; i++){ ConManager.Hex2[i] = ConManager.RandHexChar(); } } //Convert to Decimal and Binary ConManager.Hex2Dec(shifter); ConManager.Hex2Bin(shifter); //Display the 3 outputs ConManager.Show(); return; } ////////////////////////////////////////////////////////////////////////////////////////////////////// Decimal input if (_strcmpi(buffer, "Decimal") == 0 || _strcmpi(buffer, "Dec") == 0){ bool shifter; cout << "Binary Sequence to use - 0 or 1 : "; cin >> shifter; //reset ConManager.Reset(shifter); //setup temp bools for error and negative bool error = false; bool neg = false; //get input cout << endl << "Decimal Number : "; cin >> buffer; //check if its negative if (buffer[0] == '-'){ neg = true; for (int i = 0; i < strlen(buffer); i++){ buffer[i] = buffer[i+1]; } } //check for weird chars (not numbers) for (int i = 0; i < strlen(buffer); i++){ if (buffer[i] < '0' || buffer[i] > '9'){ error = true; cout << int(buffer[i]) << " : error with decimal number of " << buffer[i] << " at index " << i << endl; return; } } //if there is no weird chars, run the converter to int if (error == false){ int base = 1; if (!shifter){ ConManager.Decimal = 0; for (int i = strlen(buffer)-1; i > -1; i--){ ConManager.Decimal += (buffer[i] - '0')*base; base*=10; } }else{ ConManager.Decimal2 = 0; for (int i = strlen(buffer)-1; i > -1; i--){ ConManager.Decimal2 += (buffer[i] - '0')*base; base*=10; } } //finally convert the decimal to binary and hex if (neg == true){ if (!shifter){ ConManager.Decimal *= -1; }else{ ConManager.Decimal2 *= -1; } } ConManager.Dec2Hex(shifter); ConManager.Dec2Bin(shifter); } //show the results ConManager.Show(); return; } ////////////////////////////////////////////////////////////////////////////////////////////////////// Binary Input if (_strcmpi(buffer, "Binary") == 0 || _strcmpi(buffer, "Bin") == 0){ bool shifter; cout << "Binary Sequence to use - 0 or 1 : "; cin >> shifter; //reset the 3 values ConManager.Reset(shifter); //setup the error bool bool error = false; //get input cout << endl << "32 Digit Binary Number : "; cin >> buffer; //error check for (int i = 0; i < strlen(buffer); i++){ if (buffer[i] < '0' || buffer[i] > '9'){ if (buffer[i]=='x' && (i == 1 || i == 2) && strlen(buffer)<MAXBITS){ continue; } error = true; cout << "error with binary section at index " << i << endl; return; } } //complete 32 bit binary sequence if (strlen(buffer)==32){ for (int i = 0; i < 32; i++){ if (!shifter){ ConManager.Binary[i] = buffer[i] - '0'; }else{ ConManager.Binary2[i] = buffer[i] - '0'; } } //binary chunk }else if(strlen(buffer)<32 && (buffer[1]=='x' || buffer[2]=='x')){ int offset = 0; int off2 = 0; //check if the offset is greater than 10 if (buffer[1]=='x'){ offset = buffer[0] - '0'; off2 = 2; } if (buffer[2]=='x'){ offset = (buffer[0] - '0')*10; offset += buffer[1] - '0'; off2 = 3; } //check its not going past the end of the array if (offset+(strlen(buffer)-off2)>MAXBITS){ error = true; cout << "Binary goes outside the 32 bits" << endl; ConManager.Show(); return; } //finally do its thing for (int i = offset; i < offset+(strlen(buffer)-off2); i++){ if (buffer[i+off2-offset] - '0' != 0){ if (!shifter){ ConManager.Binary[i] = true; }else{ ConManager.Binary2[i] = true; } }else{ if (!shifter){ ConManager.Binary[i] = false; }else{ ConManager.Binary2[i] = false; } } } }else{ //display error cout << "error with input" << endl; } //Convert to Decimal and Hexadecimal ConManager.Bin2Dec(shifter); ConManager.Bin2Hex(shifter); //Display the 3 outputs ConManager.Show(); return; } ////////////////////////////////////////////////////////////////////////////////////////////////////// hexadecimal Input if (_strcmpi(buffer, "Hexadecimal") == 0 || _strcmpi(buffer, "Hex") == 0){ bool shifter; cout << "Binary Sequence to use - 0 or 1 : "; cin >> shifter; //Reset Hex Bin and Dec ConManager.Reset(shifter); //setup the error bool bool error = false; //get the input cout << endl << "8 Digit Hex Number : "; cin >> buffer; //check its than 8 digits if (strlen(buffer)==8){ for (int i = 0; i < 8; i++){ //convert caps to lowercase if ( buffer[i] <= 'z' && buffer[i] >= 'a'){buffer[i]-=MAXBITS;} //check its not from 0-9 or from A-F if ((buffer[i] > 'F' || buffer[i] < 'A') && (buffer[i] > '9' || buffer[i] < '0')){ error = true; cout << "Error with Hex Value of " << buffer << " at index " << i << endl; return; } } //If no errors in input, convert to char array if (error == false){ for (int i = 0; i < 8; i++){ if (!shifter){ ConManager.Hex[i] = buffer[i]; }else{ ConManager.Hex2[i] = buffer[i]; } } } //display error }else{ cout << "Error with input, you need 8 digits, you had " << strlen(buffer) << endl; } //Convert hex to decimal and binary ConManager.Hex2Dec(shifter); ConManager.Hex2Bin(shifter); //display the 3 outputs ConManager.Show(); return; } } int main() { //Set time to random srand(time(NULL)); cout << "------------------------------- BitWise Conversions ---------------------------" << endl << "--------------------------------- Luke Monaghan -------------------------------" << endl; //Get input (this just displays help as its set by default) getinput(); do{ //Get command cout << endl << "Command : "; cin >> buffer; //Run command getinput(); //if not running close }while(running==true); return 1+1-1-1; }
true
c863fa72b3df67feb98032a1a5ce1ff0cc9b7e10
C++
Taoaoxiang/PracticeLeetCode
/Problems/0KXXX/0K1XX/0K11X/No_119_Pascals-Triangle-II.cpp
UTF-8
1,705
3.71875
4
[]
no_license
//Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle. // //Note that the row index starts from 0. // // //In Pascal's triangle, each number is the sum of the two numbers directly above it. // //Example: // //Input: 3 //Output: [1,3,3,1] // //Follow up: // //Could you optimize your algorithm to use only O(k) extra space? //Runtime: 4 ms, faster than 100.00% of C++ online submissions for Pascal's Triangle II. //Memory Usage : 8.4 MB, less than 81.52% of C++ online submissions for Pascal's Triangle II. // I think this solution uses extra O(k) space :) class Solution { public: vector<int> getRow(int rowIndex) { vector<int> rtn = { 1 }; if (rowIndex == 0) { return rtn; } for (int i = 1; i <= rowIndex; ++i) { rtn.insert(rtn.begin(), 0); for (int pos = 0; pos < rtn.size() - 1; ++pos) { rtn[pos] += rtn[pos + 1]; } } return rtn; } }; //Runtime: 8 ms, faster than 16.16% of C++ online submissions for Pascal's Triangle II. //Memory Usage : 8.9 MB, less than 8.53% of C++ online submissions for Pascal's Triangle II. class Solution { public: vector<int> getRow(int rowIndex) { if (rowIndex == 0) { return { 1 }; } else if (rowIndex == 1) { return { 1, 1 }; } vector<vector<int>> rtn(rowIndex + 1, vector<int>()); vector<vector<int>> vAll(rowIndex + 1, vector<int>(rowIndex + 1, 1)); for (int row = 0; row <= rowIndex; ++row) { for (int col = 0; col <= (rowIndex - row); ++col) { //cout << "Row=>" << row << ", Col=>" << col << endl; if (row != 0 && col != 0) { vAll[row][col] = vAll[row - 1][col] + vAll[row][col - 1]; } rtn[row + col].push_back(vAll[row][col]); } } return rtn[rowIndex]; } };
true
6abaa7559f607c0623f4d92b95af56aa76d3b090
C++
TobeyChao/CPlusPlus_Primer_Learn
/Sort/Main.cpp
UTF-8
306
3.078125
3
[]
no_license
#include "Sort.h" #include <vector> #include <iostream> int main(int argc, char* argv[]) { std::vector<int> nums{ 20, 35, 44, 29, 29, 56, 45, 74, 32, 51, 64, 57, 11, 2 }; Sort sort; sort.CountingSort(nums); for (auto element : nums) { std::cout << element << " "; } system("pause"); return 0; }
true
67f469de923da39f6614f63784b7cbedbc8750f3
C++
PabloHorno/Riego-Autonomo
/RiegoAutonomo/chrono.h
UTF-8
502
3.1875
3
[]
no_license
#pragma once class chrono { public: chrono() {} unsigned long resultado; void start() { if(time == 0) time = millis(); } unsigned long getTime() { return millis() - time; } void end() { resultado = millis() - time; time = 0; } void delay(unsigned long time, void (*callback_func)()) { this->start(); if (this->getTime() > time) { Serial.print("Resultado "); Serial.println(this->getTime()); this->end(); callback_func(); } } private: unsigned long time; };
true
154907051c754a29725be1a5923e13c60a442d7a
C++
Monster88Ra/RayTracer
/trunk/RayTracer/RayTracer/src/Triangle.cpp
UTF-8
3,540
2.78125
3
[ "MIT" ]
permissive
#include "Triangle.h" #include "Intersection.h" Triangle::Triangle(): Object(), m_V0(), m_V1(), m_V2(), m_Normal(), m_UV0(), m_UV1(), m_UV2() { } Triangle::Triangle(Vector3f v0, Vector3f v1, Vector3f v2, const Material & lightingMaterial): Object(lightingMaterial), m_V0(v0), m_V1(v1), m_V2(v2), m_UV0(), m_UV1(), m_UV2() { Vector3f e1 = v2 - v0; Vector3f e2 = v1 - v0; m_Normal = Vector3f::Cross(e1, e2); m_Normal.Normalize(); ConstructAABB(); } Triangle::Triangle(Vector3f v0, Vector3f v1, Vector3f v2, Vector3f normal, const Material & lightingMaterial): Object(lightingMaterial), m_V0(v0), m_V1(v1), m_V2(v2), m_Normal(normal), m_UV0(), m_UV1(), m_UV2() { } bool Triangle::IsIntersectingRay(Ray ray, float * out_ValueT, Intersection * out_Intersection) { if (!IsEnable()) { return false; } //just test the front face float gradient = Vector3f::Dot(m_Normal, ray.direction); if (!(gradient < 0.0f)) { return false; } // reference from Fundamental of Computer Graphics // E1 E2 Vector3f E1 = m_V1 - m_V0; Vector3f E2 = m_V2 - m_V0; Vector3f P = Vector3f::Cross(ray.direction, E2); // determinant float det = Vector3f::Dot(P, E1); // Vector T Vector3f T; if (det > 0) { T = ray.origin - m_V0; } else { det *= -1; T = m_V0 - ray.origin; } // if det is near 0, ray lies in the same plane of triangle if (det < _EPSILON) { return false; } float u, v; u = Vector3f::Dot(P, T); // check u is >=0 and < =1 if (u < 0.0f || u >det) { return false; } // Vector Q Vector3f Q; Q = Vector3f::Cross(T, E1); // caculate v v = Vector3f::Dot(Q, ray.direction); // check v is >=0 and v + u <= 1 if (v < 0.0f || (u + v > det)) { return false; } //caculate the t float t = Vector3f::Dot(Q, E2); float invDet = 1.0f / det; t *= invDet; u *= invDet; v *= invDet; if (out_ValueT) { if (out_Intersection && t < *out_ValueT) { *out_ValueT = t; ConstructIntersection(ray.origin + t * ray.direction, out_Intersection); } else if (t > *out_ValueT) { return false; } } return true; } Material Triangle::GetMaterial(Vector3f surfacepoint) { const TextureInfo &diffuseinfo = m_Material.GetDiffuseTexture(); if (!diffuseinfo.texture) { return m_Material; } float B[3]; // get U V by barycentric ComputeBarycentricCoords3d(m_V0, m_V1, m_V2, surfacepoint, B); // U V coordinate Vector2f UV = B[0] * m_UV0 + B[1] * m_UV1 + B[2] * m_UV2; UV.x *= diffuseinfo.UAxisScale; UV.y *= diffuseinfo.VAxisScale; m_Material.SetDiffuse(diffuseinfo.texture->GetSample(UV.x, UV.y)); return m_Material; } void Triangle::SetUVCoordinate(const Vector2f & UV0, const Vector2f & UV1, const Vector2f & UV2) { m_UV0 = UV0; m_UV1 = UV1; m_UV2 = UV2; } Triangle::~Triangle() { } void Triangle::ConstructIntersection(Vector3f IntersectionPoint, Intersection * IntersectionOut) { IntersectionOut->object = this; IntersectionOut->normal = m_Normal; IntersectionOut->point = IntersectionPoint; } void Triangle::ConstructAABB(Vector3f Min, Vector3f Max) { Max = Vector3f(std::max({ m_V0.x, m_V1.x, m_V2.x }), std::max({ m_V0.y, m_V1.y, m_V2.y }), std::max({ m_V0.z, m_V1.z, m_V2.z })); Min = Vector3f(std::min({ m_V0.x, m_V1.x, m_V2.x }), std::min({ m_V0.y, m_V1.y, m_V2.y }), std::min({ m_V0.z, m_V1.z, m_V2.z })); SetBoundingBox(AABB(Min, Max)); }
true
4b5da1e5b795ead7ec3abe10f701ad4abeba58d2
C++
ForyMurguia/2048
/2048/RandomTreeNode.cpp
UTF-8
4,504
3.390625
3
[]
no_license
#include "RandomTreeNode.h" RandomTreeNode::RandomTreeNode() { } RandomTreeNode::~RandomTreeNode() { for (auto child : myChildren) { if (child) delete child; } } double RandomTreeNode::getFitness() { return myFitness; } void RandomTreeNode::initPlayerNode(GameState & gameState, RandomTreeNode *parent) { myParent = parent; myFitness = double(gameState.getFitness()); myChildren.resize(4); for (int i = 0; i < 4; i++) { myChildren[i] = nullptr; } } void RandomTreeNode::initRandomNode(GameState & gameState, RandomTreeNode *parent) { myParent = parent; myChildren.resize(gameState.getNumFreeTiles() * 2); for (int i = gameState.getNumFreeTiles() - 1; i >= 0; i--) { GameState newGameState; newGameState.copy(gameState); newGameState.addTile(i, 1); myChildren[i * 2] = new RandomTreeNode; myChildren[i * 2]->initPlayerNode(newGameState, this); newGameState.copy(gameState); newGameState.addTile(i, 2); myChildren[i * 2 + 1] = new RandomTreeNode; myChildren[i * 2 + 1]->initPlayerNode(newGameState, this); } updateRandomFitness(); } void RandomTreeNode::updatePlayerFitness() { bool empty = true; for (auto child : myChildren) { if (child) { double currFit = child->getFitness(); if (empty) { empty = false; myFitness = currFit; } else { if (myFitness < currFit) { myFitness = currFit; } } } } } void RandomTreeNode::updateRandomFitness() { int8_t num_child = 0; for (auto child : myChildren) { if (child) { double currFit = child->getFitness(); if (num_child == 0) { myFitness = currFit; } else { myFitness += currFit; } num_child++; } } if (num_child > 0) { myFitness /= num_child; } } RandomTreeNode* RandomTreeNode::getParent() { return myParent; } RandomTreeNode * RandomTreeNode::getChild(int8_t index) { return myChildren[index]; } RandomTreeNode * RandomTreeNode::addChild(int8_t index, GameState & gameState) { myChildren[index] = new RandomTreeNode; myChildren[index]->initRandomNode(gameState, this); return myChildren[index]; } RandomTreeNode * RandomTreeNode::makeMove(InputDirection direction, int8_t newPosition, int8_t newValue, GameState &gameState) { if (myChildren[direction] == nullptr) { myChildren[direction] = new RandomTreeNode; GameState newGameState; newGameState.copy(gameState); newGameState.move(direction); myChildren[direction]->initRandomNode(newGameState, this); } for (int i = 1; i < 4; i++) { auto currNode = myChildren[(direction + i) % 4]; if (currNode) { delete currNode; myChildren[(direction + i) % 4] = nullptr; } } return myChildren[direction]->getChild(newPosition * 2 + (newValue - 1)); } void RandomTreeNode::explorePlayer(GameState &gameState) { for (int i = 0; i < 4; i++) { GameState newGameState; newGameState.copy(gameState); if (newGameState.move(static_cast<InputDirection>(i))) { if (myChildren[i] == nullptr) { myChildren[i] = new RandomTreeNode; myChildren[i]->initRandomNode(newGameState, this); } myChildren[i]->exploreRandom(newGameState); } } } void RandomTreeNode::exploreRandom(GameState & gameState) { static GameState currentState; GameState newState; currentState.copy(gameState); RandomTreeNode *currentNode = this; while (true) { int8_t newPosition = currentState.randomTile(); int8_t newValue = currentState.randomTileValue(); currentState.addTile(newPosition, newValue); int64_t currPoints = currentState.getPoints(); if (currPoints > ourTopPoints) { ourTopPoints = currPoints; cout << "Improved to " << currPoints << endl; } currentNode = currentNode->getChild(newPosition * 2 + newValue - 1); int8_t numValid = 0; int8_t validDir[4]; for (int i = 0; i < 4; i++) { newState.copy(currentState); if (newState.move(static_cast<InputDirection>(i))) { validDir[numValid] = i; numValid++; } } if (numValid == 0) { break; } int8_t newDirection = validDir[rand() % numValid]; currentState.move(static_cast<InputDirection>(newDirection)); if (currentNode->getChild(newDirection) == nullptr) { currentNode = currentNode->addChild(newDirection, currentState); } else { currentNode = currentNode->getChild(newDirection); } } while (currentNode != myParent) { currentNode->updatePlayerFitness(); currentNode = currentNode->getParent(); currentNode->updateRandomFitness(); currentNode = currentNode->getParent(); } } volatile int64_t RandomTreeNode::ourTopPoints = 0;
true
16286ea352642df7d045835afec461a83aa8ce09
C++
pizixuan/Experiments
/Data Structure/Experiment_08/Test_03.cpp
UTF-8
3,507
3.84375
4
[]
no_license
/* 假设二叉树采用二叉链存储结构存储,编写一个程序实现以下功能: (a)求二叉树b的节点个数并输出; (b)求二叉树b的叶子节点个数并输出; (c)求二叉树b的宽度; 二叉树为:N(a(n,C(h(H,g))),K(o(,U(I,v)),e(r(s,i),t(y)))) */ #include <stdio.h> #include <malloc.h> #define MAXSIZE 20 typedef char ElemType; typedef struct node{ ElemType data; struct node * lchild; struct node * rchild; }BTNode; struct{ int wid = 0; }Width[MAXSIZE]; void createBTree(BTNode * &t, ElemType * str){ BTNode * store[MAXSIZE]; BTNode * temp; int top = -1; int order = 0; t = NULL; for (int i = 0; str[i] != '\0'; i++){ switch (str[i]){ case '(': //接下来是左节点 top++; store[top] = temp; order = 1; break; case ',': //接下来是右节点 order = 2; break; case ')': //栈顶节点的子树结束 top--; break; default : temp = (BTNode *)malloc(sizeof(BTNode)); temp->data = str[i]; temp->lchild = temp->rchild = NULL; if (t == NULL) t = temp; else{ if (order == 1) store[top]->lchild = temp; if (order == 2) store[top]->rchild = temp; } } } } void dispBTree(BTNode * t){ if (t != NULL){ printf("%c", t->data); if (t->lchild != NULL || t->rchild != NULL){ printf("("); dispBTree(t->lchild); if (t->rchild != NULL) printf(","); dispBTree(t->rchild); printf(")"); } } } void numsOfBTreeNode(BTNode * &t, int &n, int &leafn){ //求树的高度 if (t != NULL){ n++; //不为空则num+1 if (t->lchild == NULL && t->rchild == NULL){ //若为叶子节点 leafn++; printf("%c ", t->data); //输出节点值 } numsOfBTreeNode(t->lchild, n, leafn); numsOfBTreeNode(t->rchild, n, leafn); } } void maxWidthOfBTree(BTNode * &t, int &h){ //求树的宽度 if (t != NULL){ h++; Width[h].wid++; maxWidthOfBTree(t->lchild, h); maxWidthOfBTree(t->rchild, h); h--; } } void outPut(){ BTNode * tree; int num = 0; int leafNum = 0; int h = 0; //树的高度 ElemType str[] = "N(a(n,C(h(H,g))),K(o(,U(I,v)),e(r(s,i),t(y))))"; printf("创建的原树:"); createBTree(tree, str); dispBTree(tree); printf("\n二叉树的所有叶子节点为:"); numsOfBTreeNode(tree, num, leafNum); printf("\n二叉树的叶子节点数量为:%d", leafNum); printf("\n二叉树的节点数量:%d", num); maxWidthOfBTree(tree, h); int maxWidth = 0; for (int i = 1; Width[i].wid != 0;i++){ if (Width[i].wid > maxWidth) maxWidth = Width[i].wid; } printf("\n二叉树的最大宽度:%d", maxWidth); } int main(void){ outPut(); return 0; }
true
d52e6505f851d8215dc952f5d75481190e471190
C++
guptaprakhariitr/File_Server
/include/Request.hpp
UTF-8
1,983
2.515625
3
[]
no_license
#pragma once #include "../include/Client.hpp" #include<string> #include <poll.h> #define COMPLETED 1 #define ONGOING 0 class Request { private: Client client; // for storing the address of the cleint char buffer[BUFSIZ] = "\0"; // for receiving ftp request and file data const char *bigBuffer; // for sending the list of files char *varBuffer; char *result; std::string list; // same as bigBuffer but in c++ string std::string pathname; enum class State : unsigned char // for maintaining the state of the request { FETCHING, LISTING, SENDING, RECEIVING }; State state = State::FETCHING; // initially retrieve ftp request from the client int bytes_sent = 0, bytes_recvd = 0, bytes_left = 0; char fileSize[64]; bool isGlobal = false; int fetchFtpRequest(); int recvFileFromClient(); int sendListToClient(); int sendFileToClient(); // functions for parsing the ftp request after fetching it int parseFtpRequest(); int parseListRequest(); int parseUploadRequest(const std::string &filename); int parseDownloadRequest(const std::string &filename); int parseAndExecuteRenameRequest(const std::string &new_filename, const std::string &old_filename); int parseAndExecuteDeleteRequest(const std::string &filename); // functions for authentication bool login_user(std::string username, std::string password); bool register_user(std::string username, std::string password); public: ~Request(); int sockfd, diskfilefd; struct pollfd *pollFd; int accept_request(int server_socket); int handle_request(); int send_file(); int delete_file(); int get_file(); int rename_file(); int get_file_list(); void send_ack(const char c); // int send_data(const char *buffer, const int size); // int recv_data(char *filename); char *recv_string(); };
true
8a9d7c0f48807cf53acc70e01e158dce4b788262
C++
Thecarisma/serenity
/Kernel/Lock.h
UTF-8
1,539
2.765625
3
[ "BSD-2-Clause" ]
permissive
#pragma once #include <AK/Assertions.h> #include <AK/Types.h> #include <Kernel/Arch/i386/CPU.h> #include <Kernel/KSyms.h> #include <Kernel/Scheduler.h> class Thread; extern Thread* current; static inline u32 CAS(volatile u32* mem, u32 newval, u32 oldval) { u32 ret; asm volatile( "cmpxchgl %2, %1" : "=a"(ret), "+m"(*mem) : "r"(newval), "0"(oldval) : "cc", "memory"); return ret; } class Lock { public: Lock(const char* name = nullptr) : m_name(name) { } ~Lock() {} void lock(); void unlock(); bool unlock_if_locked(); const char* name() const { return m_name; } private: volatile u32 m_lock { 0 }; u32 m_level { 0 }; Thread* m_holder { nullptr }; const char* m_name { nullptr }; }; class Locker { public: [[gnu::always_inline]] inline explicit Locker(Lock& l) : m_lock(l) { lock(); } [[gnu::always_inline]] inline ~Locker() { unlock(); } [[gnu::always_inline]] inline void unlock() { m_lock.unlock(); } [[gnu::always_inline]] inline void lock() { m_lock.lock(); } private: Lock& m_lock; }; #define LOCKER(lock) Locker locker(lock) template<typename T> class Lockable { public: Lockable() {} Lockable(T&& resource) : m_resource(move(resource)) { } Lock& lock() { return m_lock; } T& resource() { return m_resource; } T lock_and_copy() { LOCKER(m_lock); return m_resource; } private: T m_resource; Lock m_lock; };
true
31bb7a6c0c1f6ce32939da5de3fc9bd4bea8b411
C++
1ridescent/ACM
/annual/CJ14/A.cpp
UTF-8
687
2.796875
3
[]
no_license
#include <iostream> #include <set> #include <cstring> using namespace std; int N, X; set< pair<int, int> > S; int main2() { S.clear(); cin >> N >> X; for(int i = 0; i < N; i++) { int x; cin >> x; S.insert( make_pair(x, i) ); } int cnt = 0; while(!S.empty()) { set< pair<int, int> >::iterator first = S.begin(); int x = first->first; S.erase(first); set< pair<int, int> >::iterator next = S.upper_bound( make_pair(X - x, 1000000) ); if(next != S.begin()) { next--; S.erase(next); cnt++; } else break; } cout << N - cnt << endl; } int main() { int T; cin >> T; for(int t = 1; t <= T; t++) { cout << "Case #" << t << ": "; main2(); } }
true
87358ee7d3da3e456a0b6248928c4030dfb2666a
C++
shu-man-ski/OOP-Labs
/Lab-3/Lab-3/SemipreciousStone.cpp
WINDOWS-1251
926
3.34375
3
[]
no_license
#include <iostream> #include "Stone.h" using namespace std; Stone::SemipreciousStone::SemipreciousStone() { cout << "\t\t|| ||" << endl; price = 0; stone = new Stone; } Stone::SemipreciousStone::~SemipreciousStone() { cout << "\t\t|| ||" << endl; delete stone; } void Stone::SemipreciousStone::setWeightSemipreciousStone(int Weight) { stone->weight = Weight; } int Stone::SemipreciousStone::getWeightSemipreciousStone() { return stone->weight; } void Stone::SemipreciousStone::setPriceSemipreciousStone(int Price) { price = Price; } int Stone::SemipreciousStone::getPriceSemipreciousStone() { return price; } void Stone::SemipreciousStone::printSemipreciousStone() { cout << "| : " << stone->weight << " " << endl; cout << "| : " << price << "$" << endl; }
true
d2543d217f9dcd32ae43de6b0be124fe9dfdb67b
C++
dleliuhin/cservice_template
/src/pack/pack.h
UTF-8
1,493
2.53125
3
[ "DOC" ]
permissive
/*! \file pack.h * \brief Data package from multiple sensors. * * \authors Dmitrii Leliuhin * \date July 2020 */ //======================================================================================= #pragma once #include "defs.h" //======================================================================================= /*! \class Data * \brief Message wrapper class. */ class Data { public: /*! \fn void clear(); * \brief Clear data members. */ void clear(); //----------------------------------------------------------------------------------- /*! \fn const int64_t & timestamp() const; * \brief timestamp getter. * \return Saved timestamp. */ const int64_t & timestamp() const; //----------------------------------------------------------------------------------- private: //! \brief Raw data timestamp. int64_t _timestamp {0}; }; //======================================================================================= //======================================================================================= /*! \struct Pack * \param data ZCM data entry. */ struct Pack { Data data; // ... Add new data entry if you need fusion. //----------------------------------------------------------------------------------- /*! \fn void clear(); * \brief Clear all data entries. */ void clear(); }; //=======================================================================================
true
3ab141b66b5e690447ab476be0dfc44818151992
C++
walkdis/-1
/DoNotEx.cpp
UTF-8
270
2.53125
3
[]
no_license
// Copyright 2015 <Anna Simakova> #include "DoNotEx.h" #include <string> EmployeeDoNotExist::EmployeeDoNotExist(const string& name) :exception() { msg = "Sotr: " + name + " do not exist"; } const char * EmployeeDoNotExist::what() const throw() { return msg.c_str(); }
true
062f46cec1d6d891fdf1fa39f52792368d766a59
C++
ZixinLiu/leetcode
/113.path-sum-ii.cpp
UTF-8
1,210
3.46875
3
[]
no_license
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void pathSumHelp(TreeNode * root, int sum, int current, vector<int> v, vector<vector<int>> & res) { if(root == nullptr) return; // since the node could be positive or negative, //therefore, we have to go to the bottom to determine wether we should include current path v.push_back(root -> val); // current remeber the sum of to current path (include crrent root) current += root -> val; if(current == sum && !root -> left && !root -> right) { res.push_back(v); return; } pathSumHelp(root -> left, sum, current, v, res); pathSumHelp(root -> right, sum, current, v, res); } vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<vector<int>> res; if(root == nullptr) return res; vector<int> v; int current = 0; pathSumHelp(root, sum, current, v, res); return res; } };
true
207dbcb1ee5bda2552f5870224bb0683b16f8835
C++
RaissaVieira/Atividades-LP1
/roteiro2-LP1/Questao3/Funcionario.h
UTF-8
346
2.53125
3
[]
no_license
#ifndef FUNCIONARIO_H #define FUNCIONARIO_H #include <string> class Funcionario { protected: std::string nome; int matricula; public: Funcionario(/* args */); void getNome(std::string nome); std::string setNome(); void getMatricula(int matricula); int setMatricula(); virtual double calculaSalario(); }; #endif
true
19f8ad38f2b04ccd76ef323258e8cde9fadb7cf9
C++
yyqian/cpp-arsenal
/src/unp/byte_order.cpp
UTF-8
286
2.859375
3
[ "MIT" ]
permissive
#include <stdio.h> int little_endian(){ int x = 1; return *(char*)&x; } int big_endian(){ return !little_endian(); } int main(){ if(big_endian()) printf("big_endian\n"); if(little_endian()) printf("little_endian\n"); return 0; }
true
57b436e686ab86716d2eb307b6e9052704a2c14a
C++
nourtcs369/g33k
/ArduinoProjects/2014/HariTetris/_14_ImprovedCollisionDetection/_14_ImprovedCollisionDetection.ino
UTF-8
11,323
3
3
[]
no_license
// Arduino Tetris // by Hari Wiguna, 2014 // If this project inspires you, please post me a comment on github, youtube (hwiguna), or on g33k.blogspot.com // I'd love to see your version. // v0.14 - Need to distinguish collisions. ie: collision with side walls should STILL make it fall down. // If we move the piece to where it's supposed to be, would it collide with anything? // Yes, collision was detected. // Is shape supposed to fall now? // Yes, shape is supposed to fall now // Would it collide if we just move it down and not sideways? // Yes, we collide with something below even when we do not move sideways at all // We're done with this piece. Slap that piece onto the board and get a new piece // No, if we ignore sideways, piece can still move down. // well, don't move it sideway. Justmove it down then! // No, shape is not yet time for shape to fall // Ignore the request because piece can't move without hitting something. // No, there are no collision // Move the piece to where it's supposed to go // v0.13 - Dropped pieces now pile up when it can't go down further. // v0.12 - _12_CollisionDetection. There are now three bitmaps: one contains the borders, another is the shape being manipulated, and last represents the LED matrix. // v0.11 - Use _11_AccelerometerToButtons to tweak max-min values to make the control feels right // v0.10 - Let's control shapes with accelerometer input (using only X and Y) // v0.9 - Discovered that analogRead(A3) always returns 0 when timer is enabled?! // v0.8 - // v0.7 - Finally, draw Tetris shapes! // The 16x16 bitmap. Each array element is a row (16 pixels on the X axis). 0,0 is bottom left of LED matrix. int screen[16]; // Represents final bitmap shown on the LED Matrix int boardLayer[16]; // This is the whole board minus the current shape controlled by user. int shapeLayer[16]; // This is the size of the whole board, but only contains the shape at its "next" location. //-- Shift register pins -- const byte Row_RCLK = 11; // Register Clock: Positive edge triggers shift register to output (White wire) const byte Row_SRCLK = 12; // Shift Register Clock: Positive edge triggers SER input into shift register (Yellow wire) const byte Row_SER = 13; // Serial input, read in on positive edge of SRCLK (Blue wire) const byte Col_RCLK =5; // Register Clock: Positive edge triggers shift register to output (White wire) const byte Col_SRCLK = 6; // Shift Register Clock: Positive edge triggers SER input into shift register (Yellow wire) const byte Col_SER = 7; // Serial input, read in on positive edge of SRCLK (Blue wire) const int xSensor = A4; // x refers to game x, A4 is actually connected to accelerometer Y axis const int ySensor = A5; int twoBytes; int cycles = 0; byte currentRotation = 0; // 0..3 clockwise rotation int currentX = 6; // No such thing as a signed byte :-( int currentY = 12; int currentShape = 0; int xSaved = currentX; int ySaved = currentY; int rotateDelay = 4; int dropDelay = 1; //=== Tetris Shapes === // Each row of this array represents one 4x4 shape in all its four rotations. // I used a spreadsheet to convert bitmap bit patterns into the hex numbers below. int shapes[][4] = { { 0x0000, 0x4404, 0xE6EC, 0x444}, // 0. T { 0x0000, 0x0808, 0x6C6C, 0xC4C4}, // 1. S { 0x0000, 0x0404, 0xCCCC, 0x6868}, // 2. Z { 0x0000, 0x40C0, 0x4E42, 0x684E}, // 3. L { 0x0000, 0x2060, 0x284E, 0x6E42}, // 4. J { 0x0000 ,0x0000, 0x6666, 0x6666}, // 5. O { 0x4040, 0x4040, 0x4F4F, 0x4040}, // 6. I // { 0x0001, 0x0022, 0x0444, 0x8888}, // { 0x0000, 0x0000, 0x000, 0x8CEF} }; //=== Tetris shape & board routines === unsigned int GetShapeRow(byte whichShape, byte whichRotation, byte row) { unsigned int shape = 0xF000 & (shapes[whichShape][row] << (4*whichRotation) ); return shape; } void DrawShape(int* bitmap, byte whichShape, byte whichRotation, byte xOffset, byte yOffset) { for (byte r=0; r<4; r++) { unsigned int shape = GetShapeRow(whichShape, whichRotation, r); shape = shape >> (xOffset); byte bitmapY = 3-r+yOffset; bitmap[bitmapY] = bitmap[bitmapY] | shape; } } void UpdateBoard() { // Read accelerometer int xOffset = 0; int yOffset = 0; byte proposedRot; ReadSensors(&xOffset, &yOffset); proposedRot = currentRotation; // Moving up is actually "rotate" if (yOffset==1) { yOffset = 0; if ( (rotateDelay--) == 0) { rotateDelay = 4; proposedRot = currentRotation + 1; if (proposedRot>3) proposedRot = 0; } } // Is it time for shape to fall down? if (dropDelay-- == 0) { dropDelay=8; yOffset = -1; } // If we move the piece to where it's supposed to be, would it collide with anything? if (HasCollision(currentShape, proposedRot, currentX+xOffset, currentY+yOffset)) { // Yes, collision was detected. // Is shape supposed to fall now? if (yOffset==-1) { // Yes, shape is supposed to fall now // Would it collide if we just move it down and not sideways? if (HasCollision(currentShape, proposedRot, currentX, currentY+yOffset)) { // Yes, we collide with something below even when we do not move sideways at all // We're done with this piece. Slap that piece onto the board and get a new piece DrawShape(boardLayer, currentShape,proposedRot, currentX, currentY); CopyBitmap(boardLayer, screen); CheckForFullRows(); NewShape(); } else { // No, if we ignore sideways, piece can still move down. // well, don't move it sideways. Just move it down then! currentY += yOffset; currentRotation = proposedRot; ClearBitmap(shapeLayer); DrawShape(shapeLayer, currentShape,currentRotation, currentX, currentY); CopyBitmap(boardLayer, screen); OverlayBitmap(shapeLayer, screen); } } else { // No, shape is not yet time for shape to fall // Ignore the request because piece can't move without hitting something. } } else { // No, there are no collision // Move the piece to where it's supposed to go currentX += xOffset; currentY += yOffset; currentRotation = proposedRot; ClearBitmap(shapeLayer); DrawShape(shapeLayer, currentShape,currentRotation, currentX, currentY); CopyBitmap(boardLayer, screen); OverlayBitmap(shapeLayer, screen); } } void NewShape() { currentX=6; currentY = 12; currentRotation = 0; currentShape = random( sizeof(shapes)/(4*sizeof(int)) ); } void CheckForFullRows() { for (byte r=1; r< 16; r++) { if (boardLayer[r] == 0xFFFF) { RemoveFullRow(r); } } } void RemoveFullRow(int fullRowToRemove) { // Shift all rows down for (byte r=fullRowToRemove; r<15; r++) { boardLayer[r] = boardLayer[r+1]; } boardLayer[15] = 0x8001; // Set top row to only contain the leftmost and rightmost dots } void ReadSensors(int* xOffset, int* yOffset) { int xValue = analogRead(xSensor); int yValue = analogRead(ySensor); // These maxMin refers to game coord not actual accelerometer axis const int yMax = 300; //250; // Top-down = Rotate const int yMin = 200; //185; // Top-up = Drop piece const int xMax = 410; //390; // Right-down = Shift right const int xMin = 340; //330; // Left-down = shift left *xOffset = 0; *yOffset = 0; if (yValue > yMax) (*yOffset)++; if (yValue < yMin) (*yOffset)--; if (*yOffset==0) { if (xValue > xMax) (*xOffset)++; if (xValue < xMin) (*xOffset)--; } } void NewGame() { ClearBitmap(boardLayer); DrawBoard(boardLayer); } void DrawBoard(int* bitmap) { for (byte r=0; r<16; r++) { PlotDot(bitmap, 0, r, 1); PlotDot(bitmap, 15, r, 1); PlotDot(bitmap, r,0, 1); } } //=== Collision Detection === bool HasCollision(int* bitmap1, int* bitmap2) { // Take two bitmaps: boardLayer (walls and accumulated shapes), and shapeLayer (shape being tested) // If any of the rows has common bits between the two bitmaps, we have a collision! bool hasCollision = false; for (byte r=0; r<16; r++) { if ((bitmap1[r] & bitmap2[r]) != 0) { hasCollision=true; break; } } return hasCollision; } bool HasCollision(byte currentShape, byte proposedRot, int proposedX, int proposedY) { ClearBitmap(shapeLayer); DrawShape(shapeLayer, currentShape,proposedRot, proposedX, proposedY); return HasCollision(shapeLayer, boardLayer); } //=== Bitmap Utilities === void ClearBitmap(int* bitmap) { for (byte r=0; r<16; r++) { bitmap[r] = 0; } } void PlotDot(int* bitmap, byte x, byte y, byte isOn) { if (isOn) bitSet(bitmap[y], x); else bitClear(bitmap[y], x); } void CopyBitmap(int* sourceLayer, int* targetLayer) { memcpy(targetLayer, sourceLayer, sizeof(screen)); } void OverlayBitmap(int* topLayer, int* targetLayer) { for (byte r=0; r<16; r++) { targetLayer[r] |= topLayer[r]; } } //=== LED Matrix routines === void RefreshScreen(int* bitmap) { for (byte r=0; r<16; r++) { // Turn off all X bits before turning on the row, so we won't get shadowing of the previous X pattern twoBytes = 0; WriteX( highByte(twoBytes), lowByte(twoBytes) ); // Turn on ONE row at a time twoBytes = 0; bitSet(twoBytes,r); twoBytes = ~twoBytes; // Rows need to be pulled to negative. So invert before pushing bits to shift registers WriteY( highByte(twoBytes), lowByte(twoBytes) ); // Now that the row is on, turn on the appropriate bit pattern for that row. twoBytes = bitmap[r]; WriteX( highByte(twoBytes), lowByte(twoBytes) ); // Let humans enjoy that row pattern for a few microseconds. delayMicroseconds(300); // was 400 } } void WriteY(byte hiByte, byte loByte) { digitalWrite(Row_RCLK, LOW); shiftOut(Row_SER, Row_SRCLK, LSBFIRST, loByte); // When sending LSBFirst, send loByte, then HiByte shiftOut(Row_SER, Row_SRCLK, LSBFIRST, hiByte); digitalWrite(Row_RCLK, HIGH); }; void WriteX(byte hiByte, byte loByte) { digitalWrite(Col_RCLK, LOW); shiftOut(Col_SER, Col_SRCLK, LSBFIRST, loByte); shiftOut(Col_SER, Col_SRCLK, LSBFIRST, hiByte); // When sending MSBFirst, send hiByte, then loByte digitalWrite(Col_RCLK, HIGH); }; //=== SETUP === void setup() { randomSeed(analogRead(0)); SetupShiftRegisterPins(); SetupInterruptRoutine(); } void SetupInterruptRoutine() { cli(); // Stop interrupts TCCR0A = 0; // TCCR0B = 0; TCNT0 = 0; // Counter // compare match register = [ 16,000,000Hz/ (prescaler * desired interrupt frequency) ] - 1 OCR0A = 255; //(16*10^6) / (2000*64) - 1; // OCR0A/OCR02A can be up to 255, OCR1A up to 65535 TCCR0A |= (1 << WGM01); // Turn on CTC mode TCCR0B |= (1 << CS01) | (1 << CS00); // turn on bits for 64 prescaler TIMSK0 |= (1 << OCIE0A); // enable timer compare interrupt sei(); // allow interrupts } ISR(TIMER0_COMPA_vect) { cycles++; RefreshScreen( screen ); if ((cycles % 5) == 0) UpdateBoard(); } void SetupShiftRegisterPins() { pinMode(Row_RCLK,OUTPUT); pinMode(Row_SRCLK,OUTPUT); pinMode(Row_SER,OUTPUT); pinMode(Col_RCLK,OUTPUT); pinMode(Col_SRCLK,OUTPUT); pinMode(Col_SER,OUTPUT); NewGame(); } void loop() { }
true
bfbc8ac37e2c4553e715265d3e113b4f28646508
C++
jswilder/squealing-prune
/lab8/WordHash.h
UTF-8
1,692
3.515625
4
[]
no_license
// Jeremy Wilder // Lab 8 #ifndef WORDHASH_H #define WORDHASH_H #include <string> #include <iostream> #include <fstream> using namespace std; class WordHash{ public: string words[103]; int count[103]; int size; WordHash(int s); void addWord(string word); string findCommon(); }; WordHash::WordHash(int s){ size = s; string str1 = ""; for( int i=0; i<size; i++){ count[i] = 0; words[i] = str1; } } string WordHash::findCommon(){ int x,i,j; x = count[0]; j = 0; for(i=0; i<103; i++){ if( count[i] > x ){ x = count[i]; j = i; } else{ x = x; j = j; } } return words[j]; } void WordHash::addWord(string word){ //Takes the ascii of the first letter for hash calculation int a = (int)word[0]; //Calculates the position in array a = (( 37*a ) % 103 ); int x, i; //If its not empty, but it is the same word, increment count if( count != 0 && word == words[a] ){ count[a]++; } //If empty, add the word if( count[a] == 0 ){ words[a] = word; count[a]++; } //If not equal zero but the words arent the same, PROBE!!! if( count!= 0 && word != words[a] ){ i = 1; while( i<103 ){ x = (( a + i ) % 103); //If words are equal, increment count, quit loop if( word == words[x] ){ count[x]++; i = 5000; //Ends the loop } //If it finds and empty slot, add the word, quit loop if( count[x] == 0 ){ words[x] = word; count[x]++; i = 5000; //Ends the loop } //If conditions aren't met, move to the next position if( count != 0 || word != words[x] ){ i++; } } } } #endif
true
533c396788977d2d8c623360db18837bb80bcf71
C++
stephenlombardi/icggame
/src/ActorModel.cpp
UTF-8
4,007
2.671875
3
[]
no_license
#include "ActorModel.h" //ActorModel::ActorModel( ) : currentWeapon( 0 ) { } //ActorModel::ActorModel( const std::string & _name, float _mass, float _boundingRadius, float _speed ) : name( _name ), position( vec3f( 0.0f ) ), velocity( vec3f( 0.0f ) ), orientation( Vector3( 1.0f, 0.0f, 0.0f ) ), force( vec3f( 0.0f ) ), health( 0.0f ), mass( _mass ), boundingRadius( _boundingRadius ), speed( _speed ), state( "idle" ), stateStart( 0.0f ), currentWeapon( 0 ), homingPowerup( false ), attackDelayModifier( 1.0f ), speedModifier( 1.0f ), powerupLevel( 0 ) { } ActorModel::ActorModel( const std::string & _name, float _mass, float _boundingRadius, float _speed ) : name( _name ), position( vec3f( 0.0f ) ), velocity( vec3f( 0.0f ) ), orientation( Vector3( 1.0f, 0.0f, 0.0f ) ), force( vec3f( 0.0f ) ), health( 0.0f ), mass( _mass ), boundingRadius( _boundingRadius ), speed( _speed ), deathtime( 0.0f ), currentWeapon( 0 ), homingPowerup( false ), attackDelayModifier( 1.0f ), speedModifier( 1.0f ), powerupLevel( 0 ) { } const std::string & ActorModel::getName( ) const { return name; } // game stuff float & ActorModel::getHealth( ) { return health; } float ActorModel::getHealth( ) const { return health; } bool & ActorModel::hasHomingPowerup( ) { return homingPowerup; } bool ActorModel::hasHomingPowerup( ) const { return homingPowerup; } float & ActorModel::getAttackDelayModifier( ) { return attackDelayModifier; } float ActorModel::getAttackDelayModifier( ) const { return attackDelayModifier; } float & ActorModel::getSpeedModifier( ) { return speedModifier; } float ActorModel::getSpeedModifier( ) const { return speedModifier; } int & ActorModel::getPowerupLevel( ) { return powerupLevel; } int ActorModel::getPowerupLevel( ) const { return powerupLevel; } Weapon & ActorModel::getCurrentWeapon( ) { assert( currentWeapon ); return *currentWeapon; } const Weapon & ActorModel::getCurrentWeapon( ) const { assert( currentWeapon ); return *currentWeapon; } bool ActorModel::addWeapon( Weapon weapon ) { bool found = false; for( std::list< Weapon >::iterator iter = weapons.begin( ); iter != weapons.end( ); ++iter ) { if( weapon == *iter ) { found = true; break; } } if( found ) { return false; } else { weapons.push_back( weapon ); if( !currentWeapon ) { currentWeapon = &weapons.back( ); } return true; } } void ActorModel::switchWeapon( int weapon ) { std::list< Weapon >::iterator iter = weapons.begin( ); for( int i = 0; i < weapon && iter != weapons.end( ); ++iter, ++i ); if( iter != weapons.end( ) ) { currentWeapon = &*iter; } } const std::list< Weapon > & ActorModel::getWeapons( ) const { return weapons; } void ActorModel::removeWeapons( ) { weapons.clear( ); currentWeapon = 0; } // something //std::string & ActorModel::getState( ) { return state; } //const std::string & ActorModel::getState( ) const { return state; } //float & ActorModel::getStateStart( ) { return stateStart; } //float ActorModel::getStateStart( ) const { return stateStart; } float & ActorModel::getDeathTime( ) { return deathtime; } float ActorModel::getDeathTime( ) const { return deathtime; } // physics stuff vec3f & ActorModel::getPosition( ) { return position; } const vec3f & ActorModel::getPosition( ) const { return position; } vec3f & ActorModel::getVelocity( ) { return velocity; } const vec3f & ActorModel::getVelocity( ) const { return velocity; } vec3f & ActorModel::getForce( ) { return force; } const vec3f & ActorModel::getForce( ) const { return force; } vec3f & ActorModel::getOrientation( ) { return orientation; } const vec3f & ActorModel::getOrientation( ) const { return orientation; } float & ActorModel::getMass( ) { return mass; } float ActorModel::getMass( ) const { return mass; } float & ActorModel::getBoundingRadius( ) { return boundingRadius; } float ActorModel::getBoundingRadius( ) const { return boundingRadius; } float & ActorModel::getSpeed( ) { return speed; } float ActorModel::getSpeed( ) const { return speed; }
true
3a89d729c5943feef8cfe963b6e3ec2ee6058f78
C++
siddharthkhabia/c-file
/edit distance.cpp
UTF-8
1,273
2.984375
3
[]
no_license
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <limits.h> #include <algorithm> #include <vector> #include <string> using namespace std; int min(int a,int b,int c) { if(a<=b && a<=c) { return a; } else if (b<=a && b<=c) { return b; /* code */ } else { return c; } } int foo(int s1,int s2, string A,string B, std::vector<std::vector<int> > &tab) { if (s1==A.size()) { return (B.size()-s2); } else if (s2==B.size()) { return (A.size()-s1); /* code */ } else if (tab[s1][s2]>0) { return tab[s1][s2]; } else { if (A[s1]==B[s2]) { int k = (foo(s1+1,s2+1,A,B,tab)); tab[s1][s2]=k; return k; } else { int k = 1+min((foo(s1+1,s2+1,A,B,tab)),(foo(s1,s2+1,A,B,tab)),(foo(s1+1,s2,A,B,tab)) ); tab[s1][s2]=k; return k; } } } int main(int argc, char const *argv[]) { string A,B; cin>>A>>B; std::vector<int> v(B.size(),-1); std::vector<std::vector<int> > tab(A.size(),v); int c = foo(0,0,A,B,tab); cout<<c<<endl; return 0; }
true
71e382ee7116467d23fe465704125b5bda68d01d
C++
phubbard67/mathing_around
/main.cpp
UTF-8
656
2.921875
3
[]
no_license
#include <iostream> #include <stdio.h> #include <stdlib.h> #include "powerOfTwo.h" #include "graph.h" int main(int argc, char *argv[]) { //computeTwoToTheN(); struct Graph* graph; int shortestPathDist; graph = createGraph(); printf("The Graph, where 1 is blocked, and 0 is clear"); printGraph(graph); //no need to worry about a false return from BFS //the randGraphGen already checks to make sure //there is a path from start to finish shortestPathDist = BFS(graph, true); printf("The shortest distance from graph[0][0] to graph[%d - 1][%d - 1]: %d\n", graph->height, graph->width, shortestPathDist); deleteGraph(graph); return 0; }
true
22c9388aabe355c9055f602f07e269784613f999
C++
mateka/pmizer
/pmizer_cmd/pmizer_app.cpp
UTF-8
2,779
2.90625
3
[ "MIT" ]
permissive
#include "pmizer_app.h" #include <iostream> #include <pmize/image.h> #include <pmize/to_sphere_map.h> #include <xmp/meta_engine.h> namespace pmizer { pmizer_app::pmizer_app() : m_options{ "Pmizer\t-App for converting cubemaps to panoramic photos" } { namespace po = ::boost::program_options; m_options.add_options() ("help", "shows help message") ("input,i", po::value<::std::experimental::filesystem::path>(&m_input)->required(), "path to cubemap image") ("output,o", po::value<::std::experimental::filesystem::path>(&m_output)->required(), "path to output image") ("width,w", po::value<::std::size_t>(&m_width)->required(), "output image width") ("height,h", po::value<::std::size_t>(&m_height)->required(), "output image height") ("author,a", po::value<::std::string>(&m_author), "output image author") ("title,t", po::value<::std::string>(&m_title), "output image title") ("description,d", po::value<::std::string>(&m_description), "output image description") ("camera", po::value<::std::string>(&m_camera), "output image camera model") ("url", po::value<::std::string>(&m_url), "output image base URL") ("fov", po::value<double>(&m_fov)->default_value(75.0), "output image initial Field Of View") ; } void pmizer_app::run(int argc, char *argv[]) { try { if (!(parse_cmd(argc, argv))) return; ::std::cout << "Converting to panorama..." << ::std::flush; to_sphere_map(); ::std::cout << "done." << std::endl; ::std::cout << "Adding XMP meta..." << ::std::flush; add_meta(); ::std::cout << "done." << std::endl; } catch (const std::exception& ex) { ::std::cerr << ex.what() << ::std::endl; } } bool pmizer_app::parse_cmd(int argc, char *argv[]) { try { namespace po = ::boost::program_options; po::variables_map cmd_variables; po::store(po::parse_command_line(argc, argv, m_options), cmd_variables); if (cmd_variables.count("help")) { ::std::cout << m_options << std::endl; return false; } po::notify(cmd_variables); return true; } catch (const std::exception& ex) { ::std::cout << m_options << std::endl; ::std::cerr << ex.what() << ::std::endl; } return false; } void pmizer_app::to_sphere_map() { namespace gil = ::boost::gil; auto cubemap = ::pmize::load_image(m_input); ::pmize::image_t output(m_width, m_height); ::pmize::to_sphere_map(gil::view(cubemap), gil::view(output)); ::pmize::save_image(m_output, output); } void pmizer_app::add_meta() { using namespace ::xmp; meta_engine engine; auto xmp_meta = engine.file_meta(m_output, m_width, m_height); xmp_meta.set_author(m_author); xmp_meta.set_title(m_title); xmp_meta.set_description(m_description); xmp_meta.set_url(m_url); xmp_meta.set_fov(m_fov); xmp_meta.set_camera(m_camera); xmp_meta.write(); } }
true
d45a03cb19769a52981e3c5d175d5afd1822369e
C++
matbut/Algorithms-And-Data-Structures
/0-Simple-Algorithms/3-Recursion/3.16-Skoki-po-tablicy.cpp
UTF-8
810
3.140625
3
[]
no_license
#include <iostream> #include <cstdlib> #include <ctime> #include <windows.h> using namespace std; const int MAX=10; void generuj(int tab[]){ srand(time(0)); for(int i=0;i<MAX;i++){ tab[i]=rand()%8+2; cout << tab[i] << " "; } cout << endl; } bool skoki(int i,int tab[],int &droga){ cout << i << endl; if (i>=MAX) return false; if (i==MAX-1) { return true; } int tmp=tab[i]; for(int d=2;d<=tmp;d++){ if(tmp%d==0){ droga=10*droga+tab[i]; if(skoki(i+d,tab,droga)) return true; while(tmp%d==0) tmp=tmp/d; } } return false; } int main(){ int tab[MAX]; generuj(tab); int droga=0; if (skoki(0,tab,droga)) cout << "Da sie, droga to: " << droga; else cout << "Nie da sie"; }
true
f6d23da3f8a5f2ceb1c3ca206a739a08547815e5
C++
arunansu/Algorithms
/CPP/GraphDirectedAcyclicity.cpp
UTF-8
883
3.484375
3
[]
no_license
#include <iostream> #include <vector> using std::vector; using std::pair; bool isCyclic(vector<vector<int>> &adj, int v, vector<bool> &visited) { if (visited[v]) { return true; } else { visited[v] = true; for (size_t i = 0; i < adj[v].size(); ++i) { if (visited[adj[v][i]]) { return true; } else { return isCyclic(adj, adj[v][i], visited); } } } return false; } int acyclic(vector<vector<int>> &adj) { //write your code here if (adj.empty()) return 0; std::vector<bool> visited(adj.size(), false); for (size_t i = 0; i < adj.size(); ++i) { if (isCyclic(adj, i, visited)) return 1; } return 0; } int main() { size_t n, m; std::cin >> n >> m; vector<vector<int>> adj(n, vector<int>()); for (size_t i = 0; i < m; i++) { int x, y; std::cin >> x >> y; adj[x - 1].push_back(y - 1); } std::cout << acyclic(adj); }
true
067c548ff6bc87b1c8f4cccfc04a4a22e599c937
C++
hornehm/HW02
/src/HW02App.cpp
UTF-8
4,436
3.234375
3
[]
no_license
/** * *CSE 274 B *@author Heather Horne * *This assignment satisfies A, B, D, and E for Homework #2. I realize this *is all in one .cpp file, but I had a hard time putting each class in their *separate .cpp and .h files. * *I've used the reverse method from Dr. Brinkman's CSE 274 Class * **/ #include "cinder/app/AppBasic.h" #include "cinder/gl/gl.h" #include "cinder/gl/Texture.h" #include "cinder/gl/TextureFont.h" #include "DoubleLinkedList.h" #include "Node.h" #include "Circle.h" using namespace ci; using namespace ci::app; using namespace std; /** *HW02App * *I tried first using open gl, but turned to using a surface instead. * Unfortunately, it ended up working really well. I just wish I would have * done it sooner. **/ class HW02App:public AppBasic { public: void setup(); void mouseDown( MouseEvent event ); void keyDown( KeyEvent event); void update(); void draw(); void prepareSettings(Settings* settings); void mouseScroll(MouseEvent event); void clearSurface(); private: static const int appWidth = 800; static const int appHeight = 600; static const int textureSize = 1024; DoubleLinkedList* list; bool controls; //Surface Surface* mySurface; uint8_t* dataArray; //Font for message Font f; gl::TextureFontRef textFont; }; void HW02App::prepareSettings(Settings* settings){ settings->setWindowSize(appWidth, appHeight); settings->setResizable(false); } void HW02App::setup() { mySurface = new Surface(textureSize, textureSize, false); //Make Circles! Circle* c1 = new Circle(200, 300, 50.0, Color8u(0, 0, 255)); Circle* c2 = new Circle(100, 300, 50.0, Color8u(255, 0, 0)); Circle* c3 = new Circle(300, 300, 50.0, Color8u(0, 255, 0)); Circle* c4 = new Circle(400, 300, 50.0, Color8u(255, 255, 255)); //Doubly Circular Node list list = new DoubleLinkedList(); list->addToList(c1); list->addToList(c2); list->addToList(c3); list->addToList(c4); //Set controls to true to show them controls = true; //set up font f = Font( "Arial", 24 ); textFont = gl::TextureFont::create(f); } void HW02App::mouseScroll(MouseEvent event){ float wheel; wheel = event.getWheelIncrement(); list->update(5); } void HW02App::mouseDown( MouseEvent event ) { int x1 = event.getX(); int y1 = event.getY(); if(event.isLeftDown()){ Circle* c = new Circle(x1, y1, 50.0, Color8u(100, 0, 100)); list->addToList(c); } else if(event.isRightDown()){ list->findClickedCircle(event.getX(),event.getY()); } } void HW02App::keyDown( KeyEvent event){ //if 1, reverse the list if(event.getChar() == '1'){ list->reverseList(); } //if ?, display controls if(event.getChar()== '?'){ controls = !controls; } //if s, move down if(event.getChar() == 's'){ list->update(1); } //if w, move up if(event.getChar() == 'w'){ list->update(2); } //if d, move left if(event.getChar() == 'd'){ list->update(3); } //if a, move right if(event.getChar() == 'a'){ list->update(4); } } void HW02App::clearSurface(){ uint8_t* dataArray = (*mySurface).getData(); //clears background to black. for(int y = 0; y < appHeight; y++){ for(int x = 0; x < appWidth; x++){ int offset = 3* (x + y*textureSize); dataArray[offset] = 0; dataArray[offset+1] = 0; dataArray[offset+2] = 0; } } } void HW02App::update() { clearSurface(); uint8_t* dataArray = (*mySurface).getData(); list->drawAll(dataArray); } void HW02App::draw() { //I've taken code from Lucy's and Jordan Komnick's Homework 2 project to make my text show if(controls){ std::string str("Welcome! This app allows you to use circles to draw colorful backgrounds.\n\n\n\n" "Press '?' to enter and exit control description.\nPress '1' to reverse the circles.\nPress Mouse-2 to select a circle" " to draw with.\nPress 'w' to move a circle up." "\nPress 's' to move a circle down.\nPress 'a' to move a circle left.\nPress 'd' to move a circle right." "\nPress w, a, s, or d while scrolling to make the circle move further." "\nLeft-Click to add a purple circle!"); gl::color(Color8u(0, 0, 0)); gl::enableAlphaBlending(); gl::color(Color(255, 50, 50)); Rectf boundsRect( 40, textFont->getAscent() + 40, getWindowWidth() - 40, getWindowHeight() - 40 ); textFont ->drawStringWrapped(str, boundsRect); gl::color(Color8u(255, 255, 255)); } else{ gl::clear(Color(0, 0, 0)); gl::draw(*mySurface); } } CINDER_APP_BASIC( HW02App, RendererGl )
true
93e7e19f5b46f34ed0fcadacd4ae189ade2ab759
C++
designgreenhouse/arduino
/Blink_LED_w_tempsensor_001/Blink_LED_w_tempsensor_001.ino
UTF-8
2,329
2.9375
3
[ "CC0-1.0" ]
permissive
/* experiment för att testa och lära hur man läser analog och digital input, samt sätter en digital utgång och skriver ut ett analogt värde. Kopplar till github komponenter * Arduino R3 * tinkerkit sensorshield * tinkerkit LED * tinkerkit pushbutton * tinkerkit temperatur sensor Lars Lindmark, Design Greenhouse 2015 */ // constants won't change. They're used here to const int sensorIn = A0; // temperatursensor (middle terminal) connected to tinkerkit O0 const int buttonPin = A1; // the number of the pushbutton pin const int ledO0 = 11; // select the pin for the tinkerLED const int pin13 = 13; // select the pin for the outputLED // variables will change: int sensorValue = 0; // variable to store the value coming from the tempsensor int buttonState = 0; // variable for reading the pushbutton status int outputValue = 0; // value output to the PWM (analog out) void setup() { // put your setup code here, to run once: pinMode(13, OUTPUT); // initialize digital pin 13 as an output. pinMode(11, OUTPUT); // initialize digital pin 11 as an output O0 on thinkercad. pinMode(A0,INPUT); // initialize analog pin a0 as an input O0 on thinkercad. pinMode(buttonPin, INPUT); // initialize the pushbutton pin as an input: Serial.begin(9600); // initialize serial communications at 9600 bps: } void loop() { buttonState = digitalRead(buttonPin); // read the state of the pushbutton value: // check if the pushbutton is pressed. // if it is, the buttonState is HIGH: if (buttonState == HIGH) { // turn yellow LED on: digitalWrite(11, HIGH); // set LED on delay(1000); // wait for a second digitalWrite(11,LOW); // set LED off delay(1000); // wait for a second } else { // turn green LED on: digitalWrite(13, HIGH); // set LED on delay(1000); // wait for a second digitalWrite(13,LOW); // set LED off delay(1000); // wait for a second } sensorValue = analogRead(sensorIn); // read the value from the sensor: outputValue = map(sensorValue, 0, 1023, 0, 255); // map it to the range of the analog out: //omvandla sensorvärde till temperatur i grader Celsius // print the results to the serial monitor: Serial.print("sensor = " ); Serial.print(sensorValue); Serial.print("\t output = "); Serial.println(outputValue); }
true
4c2c59135ed1486b1bd65ab8497b5ebe5a9a2aa8
C++
matteo1994/CUDA_ChromaKey_Advanced
/Utility.cpp
UTF-8
4,722
2.78125
3
[]
no_license
#include <stdio.h> #include <math.h> #include "Utility.h" #include <iostream> const double pi() { return acos(-1); } float ColorRGB::RGBtoYf(ColorYCbCr* cY) { float tmp, tmp1, tmp2; cY->Y = 0.257*this->r + 0.504*this->g + 0.098*this->b; tmp1 = -0.148*this->r - 0.291*this->g + 0.439*this->b; tmp2 = 0.439*this->r - 0.368*this->g - 0.071*this->b; tmp = sqrt(tmp1*tmp1 + tmp2 * tmp2); cY->Cb = 127 * (tmp1 / tmp); cY->Cr = 127 * (tmp2 / tmp); return tmp; } ColorYCbCr& ColorRGB::RGBtoY() { ColorYCbCr* cY = new ColorYCbCr(); cY->Y = 0.257*this->r + 0.504*this->g + 0.098*this->b; cY->Cb = -0.148*this->r - 0.291*this->g + 0.439*this->b; cY->Cr = 0.439*this->r - 0.368*this->g - 0.071*this->b; return *cY; } ColorRGB& ColorYCbCr::YtoRGB() { ColorRGB* cRGB = new ColorRGB(); float tmp = 1.164*this->Y + 1.596*this->Cr; tmp = (tmp > 0) ? tmp : 0; cRGB->r = (tmp < 255) ? tmp : 255; tmp = 1.164*this->Y - 0.813*this->Cr - 0.392*this->Cb; tmp = (tmp > 0) ? tmp : 0; cRGB->g = (tmp < 255) ? tmp : 255; tmp = 1.164*this->Y + 2.017*this->Cb; tmp = (tmp > 0) ? tmp : 0; cRGB->b = (tmp < 255) ? tmp : 255; return *cRGB; } KeyColor::KeyColor(ColorRGB color, float angle, float noise_level) { cRGB = ColorRGB(color.r, color.g, color.b); cYCbCr = ColorYCbCr(); this->angle = angle; this->noise_level = noise_level; float kgl = cRGB.RGBtoYf(&cYCbCr); accept_angle_cos = cos(pi() * angle / 180); accept_angle_sin = sin(pi() * angle / 180); float tmp = 0xF * tan(pi() * angle / 180); if (tmp > 0xFF) tmp = 0xFF; accept_angle_tg = tmp; tmp = 0xF / tan(pi() * angle / 180); if (tmp > 0xFF) tmp = 0xFF; accept_angle_ctg = tmp; tmp = 1 / (kgl); this->one_over_kc = 0xFF * 2 * tmp - 0xFF; tmp = 0xF * (float)(cYCbCr.Y) / kgl; if (tmp > 0xFF) tmp = 0xFF; kfgy_scale = tmp; if (kgl > 127) kgl = 127; kg = kgl; } ImageBMP::ImageBMP(char * filename) { this->filename = filename; this->height = 0; this->width = 0; this->valid = 1; this->datapos = -1; this->file = nullptr; } int get32bitFromFile(FILE * f) { /*reads a 32 bit int from file*/ int a, b, c, d; a = getc(f); b = getc(f); c = getc(f); d = getc(f); /*printf("get32 %i %i %i %i ", a, b, c, d);*/ return (a + 256 * b + 65536 * c + 16777216 * d); } int closeCauseError() { exit(0); return 0; } ImageBMP& ImageBMP::readFile() { errno_t err = fopen_s(&this->file, this->filename, "rb"); if (err != 0) { perror("Error opening the file: "); //std::cout << "Errore"; this->valid = 0; return *this; } //Read file's header /*check magic number*/ char b = (char)getc(this->file); char m = (char)getc(this->file); if (b != 'B' || m != 'M') { this->valid = 0; return *this; } this->valid = 1; this->filesize = get32bitFromFile(this->file); /*skip past reserved section*/ getc(this->file); getc(this->file); getc(this->file); getc(this->file); this->datapos = get32bitFromFile(this->file); /*get width and height from fixed positions*/ fseek(this->file, 18, SEEK_SET); this->width = get32bitFromFile(this->file); this->height = get32bitFromFile(this->file); return *this; } ImageBMP& ImageBMP::copyHeaderFrom(ImageBMP* o) { errno_t err = fopen_s(&this->file, this->filename, "wb+"); if (err != 0) { perror("Error opening the file: "); this->valid = 0; printf("\nExit\n"); return *this; } err = fopen_s(&o->file, o->filename, "rb"); if (err != 0) { perror("Error opening the file: "); o->valid = 0; printf("\nExit\n"); return *this; } fseek(o->file, 0, SEEK_SET); for (int i = 0; i < o->datapos; i++) { fputc(getc(o->file), this->file); } for (int i = 0; i < o->filesize; i++) { fputc(0, this->file); } this->datapos = o->datapos; this->filesize = o->filesize; this->height = o->height; this->width = o->width; this->valid = 1; return *this; } ImageBMP& ImageBMP::writePixelMap(ColorRGB* map) { int pos = this->datapos; int mx = 3 * this->width; switch (mx % 4) { case 1: mx = mx + 3; break; case 2: mx = mx + 2; break; case 3: mx = mx + 1; break; } /* Fill matrix for Foreground and Background */ int i, j; for (i = 0; i < this->height; i++) { fseek(this->file, pos, SEEK_SET); for (j = pos; j < (this->width + pos); j++) { fputc(map[i * this->width + (j - pos)].b, this->file); fputc(map[i * this->width + (j - pos)].g, this->file); fputc(map[i * this->width + (j - pos)].r, this->file); } pos = mx + pos; } return *this; }
true
7cd68e71c9ace10b7c019913da242a5cd2baa65b
C++
Kulpreet-Singh/Competitive-Programming-Practice
/zscaler practice/docquity.cpp
UTF-8
902
2.875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int reduce(int input1, int input2[]) { vector<pair<int, int>> mp; for(int i=0;i<input1;i++){ mp.push_back(make_pair(input2[i],i+1)); } int n= input1; int max=0; sort(mp.begin(),mp.end()); for(int i=0;i<n-1;i++) { int sum=0; auto itr = mp.begin(); int k=0; while(k<i){ itr++; k++; } auto itr2 = itr; while(itr!=mp.end()) { sum = sum + itr->first * itr->second; if(itr->second > itr2->second){ itr->second -= 1; } itr++; } if(sum>max) max=sum; } return max; } int main(){ int n=5; int input[] = {-1,-9,0,5,-7}; cout<<reduce(n, input)<<endl; return 0; }
true
8cde7015214f9f933f06bf0b6105062a918735a4
C++
syvjohan/cppFun
/TicTacToe2/TicTacToe2/ConsoleView.cpp
UTF-8
2,659
3.265625
3
[]
no_license
#include "Defs.h" #include "ConsoleView.h" #include "GameBoard.h" #include <iostream> #include <string> using namespace std; ConsoleView::ConsoleView() { } ConsoleView::~ConsoleView() { } void ConsoleView::HandleInput() { model->SetState(GS_MAINMENU); do { int choice = -1; cin >> choice; if (model->ValidateInput(choice)) { if (choice == 1) { model->SetState(GS_GAME); return; } else if (choice == 2) { model->SetState(GS_QUIT); return; } } else { printf("\nInvalid input try again!\n"); ClearStream(); } } while (model->CurrentState() != GS_QUIT); } void ConsoleView::Draw() { if (model->CurrentState() == GS_MAINMENU) { DrawMainMenu(); } else if (model->CurrentState() == GS_GAME) { DrawHighscore(); DrawGameBoard(); GameMode(); } } void ConsoleView::DrawMainMenu() { printf("\t\t-------------------------------------------------\n"); printf("\t\t\tPress 1 to start a new game\n" "\t\t\tPress 2 to exit\n"); printf("\t\t-------------------------------------------------\n"); } void ConsoleView::DrawGameBoard() { printf("\n\n"); for (int i = 0; i != 3; ++i) { printf("\n\t\t-------------------------------------------------\n"); printf("\t\t|"); printf("\t\t|"); printf("\t\t|"); printf("\t\t|\n"); printf("\t\t|"); for (int j = 0; j != 3; ++j) { if (model->boarder[i][j] != 0) { printf("\t%c", model->boarder[i][j] == 1 ? 'X' : 'O'); } else { printf("\t%i", i * 3 + j); } printf("\t|"); } } printf("\n\t\t-------------------------------------------------\n"); } void ConsoleView::DrawWinner() { printf("\t\t-------------------------------------------------\n"); printf("\t\tCongratulations you won!\n"); } void ConsoleView::DrawHighscore() { printf("\nPlayer 1 (O) wins: %i", model->GetP1Score()); printf("\nPlayer 2 (X) wins: %i", model->GetP2Score()); } void ConsoleView::GameMode() { int input; do { printf("\nChoose a number to mark on the board (0 - 8): "); cin >> input; if (model->ValidNumber(input, 8, 0)) { // Insert value into array (border). if (model->UpdateBorder(input)) { model->NumbOfMoves(); // count++ DrawGameBoard(); //Check for winner. if (model->CheckForWinner() != 0) { model->HighScore(); DrawWinner(); model->Reset(); DrawMainMenu(); } } else { printf("\nPlace is already occupied!\n"); ClearStream(); } } else { printf("\nInvalid input, try again!\n"); ClearStream(); } } while (model->CurrentState() != GS_MAINMENU); } void ConsoleView::ClearStream() { cin.clear(); cin.ignore(std::numeric_limits<streamsize>::max(), ' '); }
true
ec86e99d23757668a90b03c9aaf55a17babecfe8
C++
ricbit/Oldies
/2012-02-spojlib/chinese_test.cc
UTF-8
366
3
3
[]
no_license
#include "gtest/gtest.h" #include "chinese.h" TEST(ChineseRemainderTest, Eval) { int mods[4] = {3, 5, 7, 13}; int rems[4] = {1, 2, 3, 4}; ChineseRemainder<int> crt(std::vector<int>(mods, mods + 4)); int ans = crt.eval(std::vector<int>(rems, rems + 4)); EXPECT_EQ(1, ans % 3); EXPECT_EQ(2, ans % 5); EXPECT_EQ(3, ans % 7); EXPECT_EQ(4, ans % 13); }
true
482749c807df332cde61d016b6211176c15b1d93
C++
AndreasArvidsson/WinDSP
/lib/DSP/src/SineSweepGenerator.cpp
UTF-8
1,219
2.859375
3
[ "MIT" ]
permissive
#include "SineSweepGenerator.h" #define _USE_MATH_DEFINES #include "math.h" //M_PI #include "Convert.h" SineSweepGenerator::SineSweepGenerator(const size_t sampleRate, const double frequencyStart, const double frequencyEnd, const double duration, const double gain) { _sampleRate = sampleRate; _frequencyStart = frequencyStart; _amplitude = Convert::dbToLevel(gain); _numSamples = (size_t)(sampleRate * duration); _freqDelta = (frequencyEnd - frequencyStart) / (sampleRate * duration); reset(); } const double SineSweepGenerator::getFrequency() const { return _frequency; } const size_t SineSweepGenerator::getNumSamples() const { return _numSamples; } const double SineSweepGenerator::next() { const double out = _amplitude * sin(_phase); ++_index; if (_index == _numSamples) { reset(); } else { _phase += _phaseDelta; _frequency += _freqDelta; updatePhaseDelta(); } return out; } void SineSweepGenerator::reset() { _frequency = _frequencyStart; _phase = 0.0; _index = 0; updatePhaseDelta(); } const void SineSweepGenerator::updatePhaseDelta() { _phaseDelta = (2 * M_PI * _frequency) / _sampleRate; }
true