language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/** * @file byte_code.c * @brief Purpose: byte code operation * @version 1.0 * @date 04.18.2017 * @author Rundong Zhu */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include "utils/link_list.h" #include "utils/symbol_table.h" #include "utils/parsing_tree.h" #include "utils/error.h" #include "byte_code.h" static int handle_if_stmt_helper(parsing_tree_st *then_node); static void byte_code_new(link_list_st *, char *, char *, char *); static void handle_stmt_list(parsing_tree_st *, link_list_st *); static void handle_stmt(parsing_tree_st *, link_list_st *); static char *handle_boolean_value(parsing_tree_st *, link_list_st *); static char *handle_boolean_expr(parsing_tree_st *, link_list_st *); static void handle_if_stmt(parsing_tree_st *, link_list_st *); static void handle_for_stmt(parsing_tree_st *, link_list_st *); static char *handle_expr(parsing_tree_st *, link_list_st *); static char *handle_term(parsing_tree_st *, link_list_st *); static void handle_decl_stmt(parsing_tree_st *, link_list_st *); static void handle_assign_stmt(parsing_tree_st *, link_list_st *); static void handle_print_stmt(parsing_tree_st *, link_list_st *); static char *handle_res1(parsing_tree_st *, link_list_st *, char *); static char *handle_factor(parsing_tree_st *, link_list_st *); static char *handle_res2(parsing_tree_st *, link_list_st *, char *); static int temp_id = 0; static int loop_id = 0; static int if_id = 0; static int else_id = 0; /* * @brief get number of digits from an integer * @para int_num, an integer * @return 0 of failed, otherwise a valid integer */ int get_digits_num(int int_num) { int count = 0; while (int_num != 0) { int_num /= 10; ++count; } return count; } /** * @brief generate byte code from parsing tree and symbol table. * @param node, a valid tree node. * @param table, a valid symbol table object * @return NULL on failed, otherwise a valid link list. */ link_list_st *semantic_analysis(parsing_tree_st *parsing_tree_node) { link_list_st *byte_code = NULL; char *program_data = NULL; if (parsing_tree_node == NULL) return NULL; program_data = parsing_tree_get_data(parsing_tree_node); if (strcmp(program_data, "program") != 0) return NULL; byte_code = link_list_init(); parsing_tree_st *stmt_list_node = parsing_tree_get_child(parsing_tree_node); char *stmt_list_data = parsing_tree_get_data(stmt_list_node); if (strcmp(stmt_list_data, "stmt_list") == 0) { handle_stmt_list(stmt_list_node, byte_code); } else { printf("program error"); return NULL; } return byte_code; } /** * @brief handle stmt_list from parsing tree. * @param node, a valid tree node. * @param byte_code, a valid link list. */ static void handle_stmt_list(parsing_tree_st *parsing_tree_node, link_list_st *byte_code) { parsing_tree_st *stmt_node = parsing_tree_get_child(parsing_tree_node); char *stmt_data = parsing_tree_get_data(stmt_node); while (1) { if (strcmp(stmt_data, "stmt") == 0) { handle_stmt(stmt_node, byte_code); } else { error_msg(__LINE__, "stmt_list error"); } parsing_tree_st *semicolon_node = parsing_tree_get_sibling(stmt_node); char *semicolon_data = parsing_tree_get_data(semicolon_node); parsing_tree_st *stmt_list_node = parsing_tree_get_sibling(semicolon_node); if (strcmp(semicolon_data, ";") == 0 && stmt_list_node == NULL) { break; } char *stmt_list_data = parsing_tree_get_data(stmt_list_node); if (strcmp(stmt_list_data, "stmt_list") == 0) { stmt_node = parsing_tree_get_child(stmt_list_node); stmt_data = parsing_tree_get_data(stmt_node); } } } /** * @brief handle stmt from parsing tree. * @param node, a valid tree node. * @param byte_code, a valid link list. */ static void handle_stmt(parsing_tree_st *parsing_tree_node, link_list_st *byte_code) { parsing_tree_st *sub_stmt_node = parsing_tree_get_child(parsing_tree_node); char *sub_stmt_data = parsing_tree_get_data(sub_stmt_node); if (strcmp(sub_stmt_data, "decl_stmt") == 0) { handle_decl_stmt(sub_stmt_node, byte_code); } else if (strcmp(sub_stmt_data, "assign_stmt") == 0) { handle_assign_stmt(sub_stmt_node, byte_code); } else if (strcmp(sub_stmt_data, "if_stmt") == 0) { handle_if_stmt(sub_stmt_node, byte_code); } else if (strcmp(sub_stmt_data, "for_stmt") == 0) { handle_for_stmt(sub_stmt_node, byte_code); } else if (strcmp(sub_stmt_data, "print_stmt") == 0) { handle_print_stmt(sub_stmt_node, byte_code); } else { error_msg(__LINE__, "stmt error"); } } /** * @brief generate decl_stmt byte code from parsing tree. * @param node, a valid tree node * @param byte_code, a valid link list. */ static void handle_decl_stmt(parsing_tree_st *parsing_tree_node, link_list_st *byte_code) { parsing_tree_st *var_node = parsing_tree_get_child(parsing_tree_node); char *var_data = parsing_tree_get_data(var_node); if (strcmp(var_data, "var") != 0) { error_msg(__LINE__, "decl_stmt error"); } parsing_tree_st *id_node = parsing_tree_get_sibling(var_node); char *id_data = parsing_tree_get_data(id_node); byte_code_new(byte_code, "DEC", id_data, ""); } /** * @brief generate assign_stmt byte code from parsing tree. * @param node, a valid tree node. * @param byte_code, a valid link list. */ static void handle_assign_stmt(parsing_tree_st *parsing_tree_node, link_list_st *byte_code) { parsing_tree_st *id_node = parsing_tree_get_child(parsing_tree_node); parsing_tree_st *is_node = parsing_tree_get_sibling(id_node); char *id_data = parsing_tree_get_data(id_node); char *is_data = parsing_tree_get_data(is_node); if (strcmp(is_data, "is") != 0) { error_msg(__LINE__, "assign_stmt error"); } parsing_tree_st *expr_node = parsing_tree_get_sibling(is_node); char *expr_data = parsing_tree_get_data(expr_node); if (strcmp(expr_data, "expr") == 0) { expr_data = handle_expr(expr_node, byte_code); } else { error_msg(__LINE__, "assign_stmt error"); } byte_code_new(byte_code, "MOV", id_data, expr_data); free(expr_data); } /** * @brief generate if_stmt byte code from parsing tree. * @param node, a valid tree node. * @param byte_code, a valid link list. */ static void handle_if_stmt(parsing_tree_st *parsing_tree_node, link_list_st *byte_code) { if_id++; else_id++; int if_length; char *if_label; if_length = strlen("if") + get_digits_num(if_id) + strlen(":") + 1; if_label = (char *)malloc(if_length); snprintf(if_label, if_length, "if%d:", if_id); int if_end_target_len; char *if_end_target; if_end_target_len = strlen("if_end") + get_digits_num(if_id) + 1; if_end_target = (char *)malloc(if_end_target_len); snprintf(if_end_target, if_end_target_len, "if%d_end", if_id); int if_end_length; char *if_end_label; if_end_length = strlen("if_end:") + get_digits_num(if_id) + 1; if_end_label = (char *)malloc(if_end_length); snprintf(if_end_label, if_end_length, "if%d_end:", if_id); int else_target_len; char *else_target; else_target_len = strlen("else") + get_digits_num(else_id) + 1; else_target = (char *)malloc(else_target_len); snprintf(else_target, else_target_len, "else%d", else_id); int else_length; char *else_label; else_length = strlen("else") + get_digits_num(else_id) + strlen(":") + 1; else_label = (char *)malloc(else_length); snprintf(else_label, else_length, "else%d", else_id); snprintf(else_label, else_length, "else%d:", else_id); parsing_tree_st *if_node = parsing_tree_get_child(parsing_tree_node); char *if_data = parsing_tree_get_data(if_node); if (strcmp(if_data, "if") != 0) { error_msg(__LINE__, "if_stmt error"); } parsing_tree_st *brace_left_node = parsing_tree_get_sibling(if_node); char *brace_left_data = parsing_tree_get_data(brace_left_node); if (strcmp(brace_left_data, "(") != 0) error_msg(__LINE__, "if_stmt error"); parsing_tree_st *boolean_node = parsing_tree_get_sibling(brace_left_node); char *boolean_data = parsing_tree_get_data(boolean_node); parsing_tree_st *brace_right_node = parsing_tree_get_sibling(boolean_node); char *brace_right_data = parsing_tree_get_data(brace_right_node); if (strcmp(boolean_data, "boolean_expr") != 0 || strcmp(brace_right_data, ")") != 0) error_msg(__LINE__, "if_stmt error"); byte_code_new(byte_code, if_label, "", ""); char *target = NULL; int has_else = handle_if_stmt_helper(parsing_tree_get_sibling(brace_right_node)); if (has_else) { target = else_target; } else { target = if_end_target; } boolean_data = handle_boolean_expr(boolean_node, byte_code); if (strcmp(boolean_data, "=") == 0) { byte_code_new(byte_code, "JNE", target, ""); } else if (strcmp(boolean_data, "<>") == 0) { byte_code_new(byte_code, "JE", target, ""); } else if (strcmp(boolean_data, ">") == 0) { byte_code_new(byte_code, "JLE", target, ""); } else if (strcmp(boolean_data, ">=") == 0) { byte_code_new(byte_code, "JL", target, ""); } else if (strcmp(boolean_data, "<") == 0) { byte_code_new(byte_code, "JGE", target, ""); } else if (strcmp(boolean_data, "<=") == 0) { byte_code_new(byte_code, "JG", target, ""); } else { error_msg(__LINE__, "boolean_expr error"); } parsing_tree_st *then_node = parsing_tree_get_sibling(brace_right_node); parsing_tree_st *curlybrace_left_node = parsing_tree_get_sibling(then_node); parsing_tree_st *stmt_list_node = parsing_tree_get_sibling(curlybrace_left_node); char *stmt_list_data = parsing_tree_get_data(stmt_list_node); parsing_tree_st *curlybrace_right_node = parsing_tree_get_sibling(stmt_list_node); char *curlybrace_right_data = parsing_tree_get_data(curlybrace_right_node); if (strcmp(stmt_list_data, "stmt_list") != 0 || strcmp(curlybrace_right_data, "}") != 0) error_msg(__LINE__, "then_stmt error"); handle_stmt_list(stmt_list_node, byte_code); if (has_else) { byte_code_new(byte_code, "JMP", if_end_target, ""); byte_code_new(byte_code, else_label, "", ""); parsing_tree_st *else_node = parsing_tree_get_sibling(curlybrace_right_node); char *else_data = parsing_tree_get_data(else_node); if (strcmp(else_data, "else") != 0) error_msg(__LINE__, "else_stmt error"); curlybrace_left_node = parsing_tree_get_sibling(else_node); stmt_list_node = parsing_tree_get_sibling(curlybrace_left_node); stmt_list_data = parsing_tree_get_data(stmt_list_node); curlybrace_right_node = parsing_tree_get_sibling(stmt_list_node); curlybrace_right_data = parsing_tree_get_data(curlybrace_right_node); if (strcmp(stmt_list_data, "stmt_list") != 0 || strcmp(curlybrace_right_data, "}") != 0) error_msg(__LINE__, "else_stmt error"); handle_stmt_list(stmt_list_node, byte_code); } byte_code_new(byte_code, if_end_label, "", ""); free(if_label); free(if_end_target); free(if_end_label); free(else_target); free(else_label); } /** * @brief generate for_stmt byte code from parsing tree. * @param node, a valid tree node. * @param byte_code, a valid link list. */ static void handle_for_stmt(parsing_tree_st *parsing_tree_node, link_list_st *byte_code) { loop_id++; int loop_length; char *loop_string; loop_length = strlen("for") + get_digits_num(loop_id) + strlen(":") + 1; loop_string = (char *)malloc(loop_length); snprintf(loop_string, loop_length, "for%d:", loop_id); int loop_end_target_len; char *loop_end_target; loop_end_target_len = strlen("for_end") + get_digits_num(loop_id) + strlen(":") + 1; loop_end_target = (char *)malloc(loop_end_target_len); snprintf(loop_end_target, loop_end_target_len, "for%d_end", loop_id); int loop_end_len; char *loop_end_label; loop_end_len = strlen("for_end") + get_digits_num(loop_id) + strlen(":") + 1; loop_end_label = (char *)malloc(loop_end_len); snprintf(loop_end_label, loop_end_len, "for%d_end:", loop_id); int loop_target_len; char *loop_target; loop_target_len = strlen("for") + get_digits_num(loop_id) + 1; loop_target = (char *)malloc(loop_length); snprintf(loop_target, loop_target_len, "for%d", loop_id); parsing_tree_st *for_node = parsing_tree_get_child(parsing_tree_node); char *for_data = parsing_tree_get_data(for_node); if (strcmp(for_data, "for") != 0) error_msg(__LINE__, "for_stmt error"); parsing_tree_st *var_node = parsing_tree_get_sibling(for_node); if (var_node == NULL) error_msg(__LINE__, "var error"); char *var_data = parsing_tree_get_data(var_node); parsing_tree_st *from_node = parsing_tree_get_sibling(var_node); char *from_data = parsing_tree_get_data(from_node); if (strcmp(from_data, "from") != 0) error_msg(__LINE__, "from error"); parsing_tree_st *expr1_node = parsing_tree_get_sibling(from_node); char *expr1_data = parsing_tree_get_data(expr1_node); if (strcmp(expr1_data, "expr") != 0) error_msg(__LINE__, "expr1 error"); expr1_data = handle_expr(expr1_node, byte_code); byte_code_new(byte_code, "MOV", var_data, expr1_data); parsing_tree_st *to_node = parsing_tree_get_sibling(expr1_node); char *to_data = parsing_tree_get_data(to_node); if (strcmp(to_data, "to") != 0 && strcmp(to_data, "downto") != 0) error_msg(__LINE__, "to error"); parsing_tree_st *expr2_node = parsing_tree_get_sibling(to_node); char *expr2_data = parsing_tree_get_data(expr2_node); if (strcmp(expr2_data, "expr") != 0) error_msg(__LINE__, "expr2 error"); expr2_data = handle_expr(expr2_node, byte_code); byte_code_new(byte_code, loop_string, "", ""); byte_code_new(byte_code, "CMP", var_data, expr2_data); if (strcmp(to_data, "to") == 0) byte_code_new(byte_code, "JGE", loop_end_target, ""); else byte_code_new(byte_code, "JLE", loop_end_target, ""); parsing_tree_st *step_node = parsing_tree_get_sibling(expr2_node); char *step_data = parsing_tree_get_data(step_node); if (strcmp(step_data, "step") != 0) error_msg(__LINE__, "step error"); parsing_tree_st *expr3_node = parsing_tree_get_sibling(step_node); char *expr3_data = parsing_tree_get_data(expr3_node); if (strcmp(expr3_data, "expr") != 0) error_msg(__LINE__, "expr3 error"); byte_code_new(byte_code, "stmt_list:", "", ""); parsing_tree_st *curlybrace_left_node = parsing_tree_get_sibling(expr3_node); char *curlybrace_left_data = parsing_tree_get_data(curlybrace_left_node); parsing_tree_st *stmt_list_node = parsing_tree_get_sibling(curlybrace_left_node); char *stmt_list_data = parsing_tree_get_data(stmt_list_node); if (strcmp(stmt_list_data, "stmt_list")!= 0 || strcmp(curlybrace_left_data, "{") != 0) error_msg(__LINE__, "stmt_list error"); handle_stmt_list(stmt_list_node, byte_code); parsing_tree_st *curlybrace_right_node = parsing_tree_get_sibling(stmt_list_node); char *curlybrace_right_data = parsing_tree_get_data(curlybrace_right_node); if (strcmp(curlybrace_right_data, "}") != 0) error_msg(__LINE__, "right curlybrace error"); byte_code_new(byte_code, "stmt_list_end:", "", ""); expr3_data = handle_expr(expr3_node, byte_code); byte_code_new(byte_code, "MOV", var_data, expr3_data); byte_code_new(byte_code, "JMP", loop_target, ""); byte_code_new(byte_code, loop_end_label, "", ""); free(expr1_data); free(expr2_data); free(expr3_data); free(loop_string); free(loop_end_target); free(loop_end_label); free(loop_target); } /** * @brief generate print_stmt byte code from parsing tree. * @param node, a valid tree node. * @param byte_code, a valid link list. */ static void handle_print_stmt(parsing_tree_st *parsing_tree_node, link_list_st *byte_code) { parsing_tree_st *print_node = parsing_tree_get_child(parsing_tree_node); char *print_data = parsing_tree_get_data(print_node); if (strcmp(print_data, "print") != 0) { error_msg(__LINE__, "print error"); } parsing_tree_st *operand_node = parsing_tree_get_sibling(print_node); char *operand = parsing_tree_get_data(operand_node); if (strcmp(operand, "expr") != 0) error_msg(__LINE__, "expr_stmt error"); operand = handle_expr(operand_node, byte_code); byte_code_new(byte_code, "OUT", operand, ""); free(operand); } /** * @brief generate boolean_value byte code from parsing tree. * @param node, a valid tree node. * @param byte_code, a valid link list. * @return boolean value, "1" for true, "0" for false. */ static char *handle_boolean_value(parsing_tree_st *parsing_tree_node, link_list_st *byte_code) { parsing_tree_st *value_node = parsing_tree_get_child(parsing_tree_node); char *bool_value = parsing_tree_get_data(value_node); if (strcmp(bool_value, "true") == 0) return strdup("1"); return strdup("0"); } /** * @brief generate boolean_expr byte code from parsing tree. * @param node, a valid tree node. * @param byte_code, a valid link list. * @return boolean operator. */ static char *handle_boolean_expr(parsing_tree_st *parsing_tree_node, link_list_st *byte_code) { parsing_tree_st *expr1_node = parsing_tree_get_child(parsing_tree_node); char *expr1_data = parsing_tree_get_data(expr1_node); char *operator_data = NULL; char *expr2_data = NULL; if (strcmp(expr1_data, "expr") != 0 && strcmp(expr1_data, "boolean_value") != 0) error_msg(__LINE__, "boolean_expr error"); if (strcmp(expr1_data, "boolean_value") == 0) { expr1_data = handle_boolean_value(expr1_node, byte_code); operator_data = "="; expr2_data = strdup("1"); } else { expr1_data = handle_expr(expr1_node, byte_code); parsing_tree_st *operator_node = parsing_tree_get_sibling(expr1_node); operator_data = parsing_tree_get_data(operator_node); parsing_tree_st *expr2_node = parsing_tree_get_sibling(operator_node); expr2_data = parsing_tree_get_data(expr2_node); if (strcmp(expr2_data, "expr") != 0) error_msg(__LINE__, "boolean_expr error"); expr2_data = handle_expr(expr2_node, byte_code); } byte_code_new(byte_code, "CMP", expr1_data, expr2_data); free(expr1_data); free(expr2_data); return operator_data; } /** * @brief handle expr form parsing tree and symbol table. * @param byte_code, a valid link list. * @param node, a valid tree node. * @return NULL on failed, otherwise a char array. */ static char *handle_expr(parsing_tree_st *parsing_tree_node, link_list_st *byte_code) { parsing_tree_st *term_node = parsing_tree_get_child(parsing_tree_node); char *term_data = parsing_tree_get_data(term_node); parsing_tree_st *res1_node = parsing_tree_get_sibling(term_node); char *rc; //return code if (strcmp(term_data, "term") != 0) error_errno(EINVAL); rc = handle_term(term_node, byte_code); if (parsing_tree_get_child(res1_node) != NULL) { rc = handle_res1(res1_node, byte_code, rc); } return rc; } /** * @brief handle term form parsing tree and symbol table. * @param byte_code, a valid link list. * @param node, a valid tree node. * @return NULL on failed, otherwise a char array. */ static char *handle_term(parsing_tree_st *parsing_tree_node, link_list_st *byte_code) { parsing_tree_st *factor_node = parsing_tree_get_child(parsing_tree_node); char *factor_data = parsing_tree_get_data(factor_node); parsing_tree_st *res2_node = parsing_tree_get_sibling(factor_node); char *rc; //return code if (strcmp(factor_data, "factor") != 0) error_errno(EINVAL); rc = handle_factor(factor_node, byte_code); if (parsing_tree_get_child(res2_node) != NULL) { rc = handle_res2(res2_node, byte_code, rc); } return rc; } /** * @brief generate res1 byte code form link list and parsing tree. * @param byte_code, a valid link list. * @param node, a valid tree node. * @return NULL on failed, otherwise a char array. */ static char *handle_res1(parsing_tree_st *parsing_tree_node, link_list_st *byte_code, char *terms_data) { temp_id++; int temp_length; char *temp_string; temp_length = strlen("_temp") + get_digits_num(temp_id) + 1; temp_string = (char *)malloc(temp_length); snprintf(temp_string, temp_length, "_temp%d", temp_id); parsing_tree_st *operator_node = parsing_tree_get_child(parsing_tree_node); if (operator_node == NULL) { free(temp_string); temp_id--; return NULL; } parsing_tree_st *term_node = parsing_tree_get_sibling(operator_node); char *operator_data = parsing_tree_get_data(operator_node); char *term_data = parsing_tree_get_data(term_node); if (strcmp(term_data, "term") == 0) { term_data = handle_term(term_node, byte_code); } byte_code_new(byte_code, "DEC", temp_string, ""); byte_code_new(byte_code, "MOV", temp_string, terms_data); free(terms_data); if (strcmp(operator_data, "+") == 0) { byte_code_new(byte_code, "ADD", temp_string, term_data); } else if (strcmp(operator_data, "-") == 0) { byte_code_new(byte_code, "SUB", temp_string, term_data); } else { error_msg(__LINE__, "res1 error"); } free(term_data); parsing_tree_st *res1_node = parsing_tree_get_sibling(term_node); char *ret_res1 = handle_res1(res1_node, byte_code, temp_string); if (ret_res1 != NULL) { temp_string = ret_res1; } return temp_string; } /** * @brief generate factor byte code form link list and parsing tree. * @param byte_code, a valid link list. * @param node, a valid tree node. * @return NULL on failed, otherwise a char array. */ static char *handle_factor(parsing_tree_st *parsing_tree_node, link_list_st *byte_code) { parsing_tree_st *operand_node = parsing_tree_get_child(parsing_tree_node); char *operand_data = strdup(parsing_tree_get_data(operand_node)); if (strcmp(operand_data, "(") == 0) { parsing_tree_st *expr_node = parsing_tree_get_sibling(operand_node); char *expr_data = parsing_tree_get_data(expr_node); parsing_tree_st *brace_node = parsing_tree_get_sibling(expr_node); char *brace_data = parsing_tree_get_data(brace_node); if (strcmp(expr_data, "expr") == 0 && strcmp(brace_data, ")") == 0) { free(operand_data); operand_data = handle_expr(expr_node, byte_code); } } return operand_data; } /** * @brief generate res2 byte code form link list and parsing tree. * @param byte_code, a valid link list. * @param node, a valid tree node. * @return NULL on failed, otherwise a valid link list. */ static char *handle_res2(parsing_tree_st *parsing_tree_node, link_list_st *byte_code, char *factors_data) { temp_id++; int temp_length; char *temp_string; temp_length = strlen("_temp") + get_digits_num(temp_id) + 1; temp_string = (char *)malloc(temp_length); snprintf(temp_string, temp_length, "_temp%d", temp_id); parsing_tree_st *operator_node = parsing_tree_get_child(parsing_tree_node); if (operator_node == NULL) { free(temp_string); temp_id--; return NULL; } parsing_tree_st *factor_node = parsing_tree_get_sibling(operator_node); char *operator_data = parsing_tree_get_data(operator_node); char *factor_data = parsing_tree_get_data(factor_node); if (strcmp(factor_data, "factor") == 0) { factor_data = handle_factor(factor_node, byte_code); } else { error_errno(EINVAL); } byte_code_new(byte_code, "DEC", temp_string, ""); byte_code_new(byte_code, "MOV", temp_string, factors_data); free(factors_data); if (strcmp(operator_data, "*") == 0) { byte_code_new(byte_code, "MUL", temp_string, factor_data); } else if (strcmp(operator_data, "/") == 0) { byte_code_new(byte_code, "DIV", temp_string, factor_data); } else if (strcmp(operator_data, "%") == 0) { byte_code_new(byte_code, "MOD", temp_string, factor_data); } else { error_msg(__LINE__, "reds2 error"); } free(factor_data); parsing_tree_st *res2_node = parsing_tree_get_sibling(factor_node); char *ret_res2 = handle_res2(res2_node, byte_code, temp_string); if (ret_res2 != NULL) { temp_string = ret_res2; } return temp_string; } static void byte_code_new(link_list_st *byte_code, char *op_code, char *first_oprand, char *second_oprand) { char *bytecode = NULL; int bytecode_len = 0; link_node_st *new_node = NULL; if (byte_code == NULL || op_code == NULL || first_oprand == NULL || second_oprand == NULL) return; // error(); bytecode_len = strlen(op_code) + 1 + strlen(first_oprand) + 1 + strlen(second_oprand) + 1; bytecode = (char *)malloc(bytecode_len); snprintf(bytecode, bytecode_len, "%s %s %s", op_code, first_oprand, second_oprand); new_node = link_node_new(bytecode, free); link_list_append(byte_code, new_node); } static int handle_if_stmt_helper(parsing_tree_st *then_node) { return parsing_tree_get_sibling( parsing_tree_get_sibling( parsing_tree_get_sibling( parsing_tree_get_sibling( then_node ) ) ) ) != NULL; } #ifdef XTEST //tree structure parsing_tree_st *setup_expr_tree_with_number() { parsing_tree_st *expr_node = parsing_tree_new("expr", NULL); parsing_tree_st *node1 = NULL; parsing_tree_st *node2 = NULL; node1 = node2; node2 = parsing_tree_new("term", NULL); parsing_tree_set_child(expr_node, node2); node1 = parsing_tree_new("res1", NULL); parsing_tree_set_sibling(node2, node1); node1 = node2; node2 = parsing_tree_new("factor", NULL); parsing_tree_set_child(node1, node2); node1 = parsing_tree_new("res2", NULL); parsing_tree_set_sibling(node2, node1); node1 = node2; node2 = parsing_tree_new("3", NULL); parsing_tree_set_child(node1, node2); return expr_node; } int print_byte_code(link_node_st *node, void *cb_data) { char *str = link_node_get_data(node); if (str != NULL) { printf("%s\n", str); return LINK_LIST_CONTINUE; } return LINK_LIST_STOP; } int print_tree(parsing_tree_st *node, void *cb_data) { printf("%s\n", (char *)parsing_tree_get_data(node)); return TREE_TRAVERSE_CONTINUE; } void test_suite_one() { link_list_st *byte_code = NULL; printf("test suite one\n"); // Create syntax tree for "var i;" statement; parsing_tree_st *root = parsing_tree_new("program", NULL);; parsing_tree_st *node1 = parsing_tree_new("stmt_list", NULL); parsing_tree_st *node2 = parsing_tree_new("stmt", NULL); parsing_tree_set_child(root, node1); parsing_tree_set_child(node1, node2); node1 = node2; node2 = parsing_tree_new(";", NULL); parsing_tree_set_sibling(node1, node2); node2 = parsing_tree_new("decl_stmt", NULL); parsing_tree_set_child(node1, node2); node1 = node2; node2 = parsing_tree_new("var", NULL); parsing_tree_set_child(node1, node2); node1 = node2; node2 = parsing_tree_new("i", NULL); parsing_tree_set_sibling(node1, node2); byte_code = semantic_analysis(root, NULL); link_list_traverse(byte_code, print_byte_code, NULL); parsing_tree_free(root); link_list_free(byte_code); } void test_suite_two() { link_list_st *byte_code = NULL; printf("test suite two\n"); // Create syntax tree for "print i;" statement; parsing_tree_st *root = parsing_tree_new("program", NULL);; parsing_tree_st *node1 = parsing_tree_new("stmt_list", NULL); parsing_tree_st *node2 = parsing_tree_new("stmt", NULL); parsing_tree_set_child(root, node1); parsing_tree_set_child(node1, node2); node1 = node2; node2 = parsing_tree_new(";", NULL); parsing_tree_set_sibling(node1, node2); node2 = parsing_tree_new("print_stmt", NULL); parsing_tree_set_child(node1, node2); node1 = node2; node2 = parsing_tree_new("print", NULL); parsing_tree_set_child(node1, node2); node1 = node2; node2 = parsing_tree_new("expr", NULL); parsing_tree_set_sibling(node1, node2); node1 = node2; node2 = parsing_tree_new("term", NULL); parsing_tree_set_child(node1, node2); node1 = parsing_tree_new("res1", NULL); parsing_tree_set_sibling(node2, node1); node1 = node2; node2 = parsing_tree_new("factor", NULL); parsing_tree_set_child(node1, node2); node1 = parsing_tree_new("res2", NULL); parsing_tree_set_sibling(node2, node1); node1 = node2; node2 = parsing_tree_new("i", NULL); parsing_tree_set_child(node1, node2); byte_code = semantic_analysis(root, NULL); link_list_traverse(byte_code, print_byte_code, NULL); parsing_tree_free(root); link_list_free(byte_code); } void test_suite_three() { link_list_st *byte_code = NULL; printf("test suite three\n"); // Create syntax tree for "i is 3;" statement; parsing_tree_st *root = parsing_tree_new("program", NULL); parsing_tree_st *node1 = parsing_tree_new("stmt_list", NULL); parsing_tree_st *node2 = parsing_tree_new("stmt", NULL); parsing_tree_set_child(root, node1); parsing_tree_set_child(node1, node2); node1 = node2; node2 = parsing_tree_new(";", NULL); parsing_tree_set_sibling(node1, node2); node2 = parsing_tree_new("assign_stmt", NULL); parsing_tree_set_child(node1, node2); node1 = node2; node2 = parsing_tree_new("i", NULL); parsing_tree_set_child(node1, node2); node1 = parsing_tree_new("is", NULL); parsing_tree_set_sibling(node2, node1); node2 = setup_expr_tree_with_number(); parsing_tree_set_sibling(node1, node2); byte_code = semantic_analysis(root, NULL); link_list_traverse(byte_code, print_byte_code, NULL); parsing_tree_free(root); link_list_free(byte_code); } void test_suite_four() { link_list_st *byte_code = NULL; printf("test suite four\n"); // Create syntax tree for "i is i + 3;" statement; parsing_tree_st *root = parsing_tree_new("program", NULL); parsing_tree_st *node1 = parsing_tree_new("stmt_list", NULL); parsing_tree_st *node2 = parsing_tree_new("stmt", NULL); parsing_tree_set_child(root, node1); parsing_tree_set_child(node1, node2); node1 = node2; node2 = parsing_tree_new(";", NULL); parsing_tree_set_sibling(node1, node2); node2 = parsing_tree_new("assign_stmt", NULL); parsing_tree_set_child(node1, node2); node1 = node2; node2 = parsing_tree_new("i", NULL); parsing_tree_set_child(node1, node2); node1 = parsing_tree_new("is", NULL); parsing_tree_set_sibling(node2, node1); node2 = parsing_tree_new("expr", NULL); parsing_tree_set_sibling(node1, node2); node1 = node2; node2 = parsing_tree_new("term", NULL); parsing_tree_set_child(node1, node2); parsing_tree_st *node3 = parsing_tree_new("res1", NULL); parsing_tree_set_sibling(node2, node3); node1 = node2; node2 = parsing_tree_new("factor", NULL); parsing_tree_set_child(node1, node2); node1 = parsing_tree_new("res2", NULL); parsing_tree_set_sibling(node2, node1); node1 = node2; node2 = parsing_tree_new("i", NULL); parsing_tree_set_child(node1, node2); node1 = parsing_tree_new("-", NULL); parsing_tree_set_child(node3, node1); node2 = parsing_tree_new("term", NULL); parsing_tree_set_sibling(node1, node2); node1 = node2; node2 = parsing_tree_new("factor", NULL); parsing_tree_set_child(node1, node2); node3 = parsing_tree_new("res2", NULL); parsing_tree_set_sibling(node2, node3); node1 = parsing_tree_new("3", NULL); parsing_tree_set_child(node2, node1); node2 = parsing_tree_new("*", NULL); parsing_tree_set_child(node3, node2); node1 = node2; node2 = parsing_tree_new("factor", NULL); parsing_tree_set_sibling(node1, node2); node3 = parsing_tree_new("2", NULL); parsing_tree_set_child(node2, node3); byte_code = semantic_analysis(root, NULL); link_list_traverse(byte_code, print_byte_code, NULL); parsing_tree_free(root); link_list_free(byte_code); } void test_suite_five() { link_list_st *byte_code = NULL; printf("test suite five\n"); // Create syntax tree for "i is i + 10 % i;" statement; parsing_tree_st *root = parsing_tree_new("program", NULL); parsing_tree_st *node1 = parsing_tree_new("stmt_list", NULL); parsing_tree_st *node2 = parsing_tree_new("stmt", NULL); parsing_tree_set_child(root, node1); parsing_tree_set_child(node1, node2); node1 = node2; node2 = parsing_tree_new(";", NULL); parsing_tree_set_sibling(node1, node2); node2 = parsing_tree_new("assign_stmt", NULL); parsing_tree_set_child(node1, node2); node1 = node2; node2 = parsing_tree_new("i", NULL); parsing_tree_set_child(node1, node2); node1 = parsing_tree_new("is", NULL); parsing_tree_set_sibling(node2, node1); node2 = parsing_tree_new("expr", NULL); parsing_tree_set_sibling(node1, node2); node1 = node2; node2 = parsing_tree_new("term", NULL); parsing_tree_set_child(node1, node2); parsing_tree_st *node3 = parsing_tree_new("res1", NULL); parsing_tree_set_sibling(node2, node3); node1 = node2; node2 = parsing_tree_new("factor", NULL); parsing_tree_set_child(node1, node2); node1 = parsing_tree_new("res2", NULL); parsing_tree_set_sibling(node2, node1); node1 = node2; node2 = parsing_tree_new("i", NULL); parsing_tree_set_child(node1, node2); node1 = parsing_tree_new("+", NULL); parsing_tree_set_child(node3, node1); node2 = parsing_tree_new("term", NULL); parsing_tree_set_sibling(node1, node2); node1 = node2; node2 = parsing_tree_new("factor", NULL); parsing_tree_set_child(node1, node2); node3 = parsing_tree_new("res2", NULL); parsing_tree_set_sibling(node2, node3); node1 = node2; node2 = parsing_tree_new("10", NULL); parsing_tree_set_child(node1, node2); node2 = parsing_tree_new("%", NULL); parsing_tree_set_child(node3, node2); node3 = parsing_tree_new("factor", NULL); parsing_tree_set_sibling(node2, node3); node1 = parsing_tree_new("i", NULL); parsing_tree_set_child(node3, node1); byte_code = semantic_analysis(root, NULL); link_list_traverse(byte_code, print_byte_code, NULL); parsing_tree_free(root); link_list_free(byte_code); } void test_suite_six() { printf("test suite six\n"); link_list_st *byte_code = NULL; parsing_tree_st *root = parsing_tree_new("program", NULL); parsing_tree_st *node1 = parsing_tree_new("stmt_list", NULL); parsing_tree_st *node2 = parsing_tree_new("stmt", NULL); parsing_tree_set_child(root, node1); parsing_tree_set_child(node1, node2); node1 = node2; node2 = parsing_tree_new(";", NULL); parsing_tree_set_sibling(node1, node2); node2 = parsing_tree_new("if_stmt", NULL); parsing_tree_set_child(node1, node2); parsing_tree_st *if_stmt = node2; node1 = parsing_tree_new("if", NULL); parsing_tree_set_child(if_stmt, node1); node2 = parsing_tree_new("(", NULL); parsing_tree_set_sibling(node1, node2); parsing_tree_st *bool_expr = parsing_tree_new("boolean_expr", NULL); parsing_tree_set_sibling(node2, bool_expr); node1 = setup_expr_tree_with_number(); parsing_tree_set_child(bool_expr, node1); node2 = parsing_tree_new("=", NULL); parsing_tree_set_sibling(node1, node2); node1 = setup_expr_tree_with_number(); parsing_tree_set_sibling(node2, node1); node2 = parsing_tree_new(")", NULL); parsing_tree_set_sibling(bool_expr, node2); node1 = parsing_tree_new("then", NULL); parsing_tree_set_sibling(node2, node1); node2 = parsing_tree_new("{", NULL); parsing_tree_set_sibling(node1, node2); parsing_tree_st *then_stmt = parsing_tree_new("stmt_list", NULL); parsing_tree_set_sibling(node2, then_stmt); node1 = parsing_tree_new("}", NULL); parsing_tree_set_sibling(then_stmt, node1); node2 = parsing_tree_new("stmt", NULL); parsing_tree_set_child(then_stmt, node2); node1 = node2; node2 = parsing_tree_new(";", NULL); parsing_tree_set_sibling(node1, node2); node2 = parsing_tree_new("assign_stmt", NULL); parsing_tree_set_child(node1, node2); node1 = node2; node2 = parsing_tree_new("i", NULL); parsing_tree_set_child(node1, node2); node1 = parsing_tree_new("is", NULL); parsing_tree_set_sibling(node2, node1); node2 = parsing_tree_new("expr", NULL); parsing_tree_set_sibling(node1, node2); node1 = node2; node2 = parsing_tree_new("term", NULL); parsing_tree_set_child(node1, node2); parsing_tree_st *node3 = parsing_tree_new("res1", NULL); parsing_tree_set_sibling(node2, node3); node1 = node2; node2 = parsing_tree_new("factor", NULL); parsing_tree_set_child(node1, node2); node1 = parsing_tree_new("res2", NULL); parsing_tree_set_sibling(node2, node1); node1 = node2; node2 = parsing_tree_new("i", NULL); parsing_tree_set_child(node1, node2); node1 = parsing_tree_new("+", NULL); parsing_tree_set_child(node3, node1); node2 = parsing_tree_new("term", NULL); parsing_tree_set_sibling(node1, node2); node1 = node2; node2 = parsing_tree_new("factor", NULL); parsing_tree_set_child(node1, node2); node3 = parsing_tree_new("res2", NULL); parsing_tree_set_sibling(node2, node3); node1 = node2; node2 = parsing_tree_new("10", NULL); parsing_tree_set_child(node1, node2); node2 = parsing_tree_new("%", NULL); parsing_tree_set_child(node3, node2); node3 = parsing_tree_new("factor", NULL); parsing_tree_set_sibling(node2, node3); node1 = parsing_tree_new("i", NULL); parsing_tree_set_child(node3, node1); parsing_tree_prefix_traverse(root, print_tree, NULL); byte_code = semantic_analysis(root, NULL); link_list_traverse(byte_code, print_byte_code, NULL); parsing_tree_free(root); link_list_free(byte_code); } void test_suite_seven() { printf("test suite seven\n"); link_list_st *byte_code = NULL; parsing_tree_st *root = parsing_tree_new("program", NULL); parsing_tree_st *node1 = parsing_tree_new("stmt_list", NULL); parsing_tree_st *node2 = parsing_tree_new("stmt", NULL); parsing_tree_set_child(root, node1); parsing_tree_set_child(node1, node2); node1 = node2; node2 = parsing_tree_new(";", NULL); parsing_tree_set_sibling(node1, node2); parsing_tree_st *node3 = parsing_tree_new("stmt_list", NULL); parsing_tree_set_sibling(node2, node3); node2 = parsing_tree_new("decl_stmt", NULL); parsing_tree_set_child(node1, node2); node1 = parsing_tree_new("var", NULL); parsing_tree_set_child(node2, node1); node2 = parsing_tree_new("i", NULL); parsing_tree_set_sibling(node1, node2); node1 = parsing_tree_new("stmt", NULL); parsing_tree_set_child(node3, node1); node2 = parsing_tree_new(";", NULL); parsing_tree_set_sibling(node1, node2); node3 = parsing_tree_new("for_stmt", NULL); parsing_tree_set_child(node1, node3); node2 = parsing_tree_new("for", NULL); parsing_tree_set_child(node3, node2); node1 = parsing_tree_new("i", NULL); parsing_tree_set_sibling(node2, node1); node2 = parsing_tree_new("from", NULL); parsing_tree_set_sibling(node1, node2); parsing_tree_st *expr1_node = parsing_tree_new("expr", NULL); parsing_tree_set_sibling(node2, expr1_node); node2 = parsing_tree_new("term", NULL); parsing_tree_set_child(expr1_node, node2); node3 = parsing_tree_new("res1", NULL); parsing_tree_set_sibling(node2, node3); node3 = parsing_tree_new("factor", NULL); parsing_tree_set_child(node2, node3); node1 = parsing_tree_new("res2", NULL); parsing_tree_set_sibling(node3, node1); node2 = parsing_tree_new("1", NULL); parsing_tree_set_child(node3, node2); node1 = parsing_tree_new("to", NULL); parsing_tree_set_sibling(expr1_node, node1); parsing_tree_st *expr2_node = parsing_tree_new("expr", NULL); parsing_tree_set_sibling(node1, expr2_node); node2 = parsing_tree_new("term", NULL); parsing_tree_set_child(expr2_node, node2); node3 = parsing_tree_new("res1", NULL); parsing_tree_set_sibling(node2, node3); node3 = parsing_tree_new("factor", NULL); parsing_tree_set_child(node2, node3); node1 = parsing_tree_new("res2", NULL); parsing_tree_set_sibling(node3, node1); node2 = parsing_tree_new("10", NULL); parsing_tree_set_child(node3, node2); node2 = parsing_tree_new("step", NULL); parsing_tree_set_sibling(expr2_node, node2); parsing_tree_st *expr3_node = parsing_tree_new("expr", NULL); parsing_tree_set_sibling(node2, expr3_node); node2 = parsing_tree_new("term", NULL); parsing_tree_set_child(expr3_node, node2); node3 = parsing_tree_new("res1", NULL); parsing_tree_set_sibling(node2, node3); node3 = parsing_tree_new("factor", NULL); parsing_tree_set_child(node2, node3); node1 = parsing_tree_new("res2", NULL); parsing_tree_set_sibling(node3, node1); node2 = parsing_tree_new("i", NULL); parsing_tree_set_child(node3, node2); node2 = parsing_tree_new("*", NULL); parsing_tree_set_child(node1, node2); node3 = parsing_tree_new("factor", NULL); parsing_tree_set_sibling(node2, node3); node2 = parsing_tree_new("2", NULL); parsing_tree_set_child(node3, node2); node2 = parsing_tree_new("{", NULL); parsing_tree_set_sibling(expr3_node, node2); node3 = parsing_tree_new("stmt_list", NULL); parsing_tree_set_sibling(node2, node3); node1 = parsing_tree_new("stmt", NULL); parsing_tree_set_child(node3, node1); node2 = parsing_tree_new(";", NULL); parsing_tree_set_sibling(node1, node2); node2 = parsing_tree_new("print_stmt", NULL); parsing_tree_set_child(node1, node2); node1 = node2; node2 = parsing_tree_new("print", NULL); parsing_tree_set_child(node1, node2); node1 = node2; node2 = parsing_tree_new("expr", NULL); parsing_tree_set_sibling(node1, node2); node1 = node2; node2 = parsing_tree_new("term", NULL); parsing_tree_set_child(node1, node2); node1 = parsing_tree_new("res1", NULL); parsing_tree_set_sibling(node2, node1); node1 = node2; node2 = parsing_tree_new("factor", NULL); parsing_tree_set_child(node1, node2); node1 = parsing_tree_new("res2", NULL); parsing_tree_set_sibling(node2, node1); node1 = node2; node2 = parsing_tree_new("i", NULL); parsing_tree_set_child(node1, node2); node2 = parsing_tree_new("}", NULL); parsing_tree_set_sibling(node3, node2); fprintf(stderr, "This is the mocking input parsing tree: \n"); parsing_tree_prefix_traverse(root, print_tree, NULL); byte_code = semantic_analysis(root, NULL); fprintf(stderr, "This is the output byte code: \n"); link_list_traverse(byte_code, print_byte_code, NULL); parsing_tree_free(root); link_list_free(byte_code); } int main() { test_suite_one(); test_suite_two(); test_suite_three(); test_suite_four(); test_suite_five(); test_suite_six(); test_suite_seven(); return 0; } #endif // XTEST
C
/* * modgpio.h * * Created on: May 5, 2014 * Author: quangng */ #ifndef MODGPIO_H_ #define MODGPIO_H_ #define GPIO_IOC_MAGIC 'k' typedef enum {MODE_INPUT=0, MODE_OUTPUT} PIN_MODE_t; typedef enum {DIRECTION_IN = 0, DIRECTION_OUT} PIN_DIRECTION_t; struct gpio_data_write { int pin; char data; }; struct gpio_data_mode { int pin; PIN_MODE_t data; }; //in: pin to read //out: value //the value read on the pin #define GPIO_READ _IOWR(GPIO_IOC_MAGIC, 0x90, int) //in: struct(pin, data) //out: NONE #define GPIO_WRITE _IOW(GPIO_IOC_MAGIC, 0x91, struct gpio_data_write) //in: pin to request //out: success/fail // request exclusive modify privileges #define GPIO_REQUEST _IOW(GPIO_IOC_MAGIC, 0x92, int) //in: pin to free #define GPIO_FREE _IOW(GPIO_IOC_MAGIC, 0x93, int) //in: pin to toggle //out: new value #define GPIO_TOGGLE _IOWR(GPIO_IOC_MAGIC, 0x94, int) //in: struct (pin, mode[i/o]) #define GPIO_MODE _IOW(GPIO_IOC_MAGIC, 0x95, struct gpio_data_mode) #endif /* MODGPIO_H_ */
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #define BUF 512 #define MBUF 128 #define N 10 long long hashMe(unsigned char *str) { long long h = 1; int i; unsigned char magic_number = 0x5F; for (i = 0; i < 8 && i < strlen((char *)str); i++) { str[i] ^= magic_number; h *= str[i] << (i % 2); } return h; } int main() { char message[N][MBUF]; unsigned char pass[BUF]; unsigned char realpass[BUF]; FILE *file; int i; long long f, h; printf("pass: "); fgets((char *)pass, BUF, stdin); h = hashMe(pass); sprintf((char *)pass, "%llx", h); file = fopen("/home/shell2cgi/pass", "r"); if (!file) { fprintf(stderr, "Nie moge otworzyc pliku.\n"); } fscanf(file, "%s", realpass); fclose(file); if (!strcmp((char *)realpass, (char *)pass)) { system("cat secret"); } else { printf("\nWrong password.\n"); file = fopen("/home/shell2cgi/fortunes", "r"); if (!file) { fprintf(stderr, "Nie moge otworzyc pliku.\n"); } for (i = 0; i < N; i++) { fgets(message[i], BUF, file); } fclose(file); srandom((unsigned int)time(NULL)); f = h + random(); printf("\n%s", message[f % N]); } /* more secure */ exit(0); return 0; }
C
#include <stdio.h> #include <stdint.h> #include <string.h> //#define POLY 0x8408 #define POLY 0x1021 /* // 16 12 5 // this is the CCITT CRC 16 polynomial X + X + X + 1. // This works out to be 0x1021, but the way the algorithm works // lets us use 0x8408 (the reverse of the bit pattern). The high // bit is always assumed to be set, thus we only use 16 bits to // represent the 17 bit value. */ uint16_t getCrcCCITT16(uint8_t * buffer, uint32_t size); void genInitPKT(uint16_t crc); void genManifestJSON(uint16_t crc); int main(void) { FILE * fid; char fname[] = "build/main.bin"; uint32_t fsize; uint8_t data[256*1024]; uint16_t crc; fid = fopen(fname, "r"); if(fid == NULL) { printUSART0("-> ERROR: unable to open file [%s]\n", fname); return 0; } fseek(fid, 0, SEEK_END); fsize = ftell(fid); fseek(fid, 0, SEEK_SET); fread(data, fsize, 1, fid); crc = getCrcCCITT16(data, fsize); printf("wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww\n"); printf("w CRC CCITT 16 calculation app\n"); printf("w input:\t[%s]\n", fname); printf("w size: \t[%d]\n", fsize); printf("w CRC: \t[0x%04X]\n", crc); printf("wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww\n"); fclose(fid); genInitPKT(crc); genManifestJSON(crc); return 0; } // <--- 2B ---> <--- 2B ---> // | Device Type | Device revision | // | Application version | // | SoftDev. List N| SoftDev. Ver N | // | SoftDev. VerN-1| CRC CCITT 16 | //0100 FEFF – any Soft Device (for development purposes only) //0100 5A00 – compatible with the SD 7.1.0 //0200 4F00 5A00 – compatible with both SD 7.0.0 and SD 7.1.0 //0100 6400 – compatible with SD 8.0 only void genInitPKT(uint16_t crc) { uint8_t pkt[14], k; FILE * fid; fid = fopen("build/main.dat", "w+"); if(fid == NULL) { printUSART0("-> ERROR: unable to create file [main.dat]\n", 0); } for(k=0;k<8;k++) pkt[k] = 0xFF; pkt[8] = 0x01; pkt[9] = 0x00; pkt[10] = 0x64; pkt[11] = 0x00; pkt[12] = crc&0xFF; pkt[13] = (crc>>8); fwrite(pkt, 14, 1, fid); fclose(fid); } void genManifestJSON(uint16_t crc) { uint8_t data[2048], tstr[128]; uint16_t k, len; FILE * fid; for(k=0;k<2048;k++) data[k] = 0x00; fid = fopen("build/manifest.json", "w+"); if(fid == NULL) { printUSART0("-> ERROR: unable to create file [manifest.json]\n", 0); } //{ strcat(data, "{\n"); //"manifest": { strcat(data, "\t\"manifest\": {\n"); //"application": { strcat(data, "\t\t\"application\": {\n"); //"bin_file": "main.bin", strcat(data, "\t\t\t\"bin_file\": \"main.bin\",\n"); //"dat_file": "main.dat", strcat(data, "\t\t\t\"dat_file\": \"main.dat\",\n"); //"init_packet_data": { strcat(data, "\t\t\t\"init_packet_data\": {\n"); //"application_version": 4294967295, strcat(data, "\t\t\t\t\"application_version\": 4294967295,\n"); //"device_revision": 65535, strcat(data, "\t\t\t\t\"device_revision\": 65535,\n"); //"device_type": 65535, strcat(data, "\t\t\t\t\"device_type\": 65535,\n"); //"firmware_crc16": 19263, sprintf(tstr, "\t\t\t\t\"firmware_crc16\": %d,\n",crc); strcat(data, tstr); //"softdevice_req": [ strcat(data, "\t\t\t\t\"softdevice_req\": [\n"); //100 strcat(data, "\t\t\t\t\t100\n"); //] strcat(data, "\t\t\t\t]\n"); //} strcat(data, "\t\t\t}\n"); //} strcat(data, "\t\t}\n"); //} strcat(data, "\t}\n"); //} strcat(data, "}\n"); len = strlen(data); fwrite(data, len, 1, fid); fclose(fid); } //{ //"manifest": { //"application": { //"bin_file": "main.bin", //"dat_file": "main.dat", //"init_packet_data": { //"application_version": 4294967295, //"device_revision": 65535, //"device_type": 65535, //"firmware_crc16": 19263, //"softdevice_req": [ //100 //] //} //} //} //} uint16_t getCrcCCITT16(uint8_t * p_data, uint32_t size) { uint32_t i; uint16_t crc = 0xffff; for (i = 0; i < size; i++) { crc = (unsigned char)(crc >> 8) | (crc << 8); crc ^= p_data[i]; crc ^= (unsigned char)(crc & 0xff) >> 4; crc ^= (crc << 8) << 4; crc ^= ((crc & 0xff) << 4) << 1; } return crc; } //uint16_t getCrcCCITT16(uint8_t * data_p, uint32_t size) //{ //uint32_t i; //uint16_t data; //uint16_t crc = 0xffff; //if (size == 0) //return (~crc); //do //{ //for (i=0, data=(unsigned int)0xff & *data_p++; //i < 8; //i++, data >>= 1) //{ //if ((crc & 0x0001) ^ (data & 0x0001)) //crc = (crc >> 1) ^ POLY; //else crc >>= 1; //} //} while (--size); //crc = ~crc; //data = crc; //crc = (crc << 8) | (data >> 8 & 0xff); //return (crc); //}
C
#include <cs50.h> #include <stdio.h> #include <string.h> #include <ctype.h> int main(int argc, string argv[]) { //make sure command line argument number is 2 if (argc==2){ //check argv[1] is number for(int i=0,len=strlen(argv[1]);i<len;++i){ if(isdigit(argv[1][i]) ){ //normal case,need do nothing } else{ printf("Usage: ./caesar key\n"); return 1; } } int key=atoi(argv[1]); string plaintext=get_string("plaintext: "); for(int i=0,len=strlen(plaintext);i<len;++i){ //for each char in plaintext,if lowcase or upcase rotate respectively, if not do nothing if(islower(plaintext[i])){ plaintext[i]-=97; plaintext[i]=(plaintext[i]+key)%26; plaintext[i]+=97; } else if(isupper(plaintext[i])){ plaintext[i]-=65; plaintext[i]=(plaintext[i]+key)%26; plaintext[i]+=65; } } printf("ciphertext: %s\n",plaintext); } else{ printf("Usage: ./caesar key\n"); return 1; } }
C
#include <queue.h> /* Create a oddpair_XY variable */ struct oddpair_XY createOddpair_XY(int16_t OX, int16_t OY, int8_t sign) { struct oddpair_XY XY; XY.OX = OX; XY.OY = OY; XY.sign = sign; return XY; } /* Initialize a stack */ Queue_XY initQueue_XY() { Queue_XY queue; queue.head = queue.tail = NULL; return queue; } /* Test if a queue is empty */ bool emptyQueue_XY(Queue_XY queue) { return (queue.head == NULL)? true : false; } bool emptyQueueTail_XY(Queue_XY queue) { return (queue.tail == NULL)? true : false; } /* Determine the value of the top of the queue */ struct oddpair_XY summitQueue_XY(Queue_XY queue) { struct oddpair_XY value_XY = {0}; if(!emptyQueue_XY(queue)) { value_XY = queue.head->XY; } return value_XY; } struct oddpair_XY tailQueue_XY(Queue_XY queue) { struct oddpair_XY value_XY = {0}; if(!emptyQueue_XY(queue)) { value_XY = queue.tail->XY; } return value_XY; } /* Push a value into the queue */ void pushQueue_XY(Queue_XY* queue, struct oddpair_XY value) { List_XY cel; cel = (List_XY) malloc(sizeof(struct Cell)); cel->XY = value; cel->next = NULL; if(emptyQueue_XY(*queue)) { cel->prev = NULL; queue->head = queue->tail = cel; } else { cel->prev = queue->tail; (queue->tail)->next = cel; queue->tail = cel; } } /* Pop the summit of the queue */ void popQueue_XY(Queue_XY* queue) { List_XY queue_tmp; queue_tmp = queue->head; queue->head = (queue->head)->next; free(queue_tmp); } /* Free the memory of a queue */ void freeQueue_XY(Queue_XY* queue) { while(!emptyQueue_XY(*queue)) { popQueue_XY(queue); } } /* Print a queue */ void printQueue_XY(Queue_XY queue) { while(!emptyQueue_XY(queue)) { struct oddpair_XY XY_tmp = summitQueue_XY(queue); printf("%hd->(%hd, %hd)\n", XY_tmp.sign, XY_tmp.OX, XY_tmp.OY); queue.head = (queue.head)->next; } } void printQueueBack_XY(Queue_XY queue) { while(!emptyQueue_XY(queue)) { struct oddpair_XY XY_tmp = tailQueue_XY(queue); printf("%hd->(%hd, %hd)\n", XY_tmp.sign, XY_tmp.OX, XY_tmp.OY); queue.tail = (queue.tail)->prev; } }
C
/* https://stackoverflow.com/questions/342409/how-do-i-base64-encode-decode-in-c */ #ifndef BASE64_H_ #define BASE64_H_ #include <stdint.h> #define BASE64_OUTPUT_LEN(len) (4u * (((len) + 2) / 3)) void b64_init(void); void b64_encode(const uint8_t *data, uint32_t input_length, char *encoded_data); /* * *poutput_len input: max len of decoded_data, * output: actual len of decoded_data * return 0 on success */ int b64_decode(const char *data, uint32_t input_length, uint8_t *decoded_data, uint32_t *poutput_len); #endif /* BASE64_H_ */
C
#include <stdio.h> #include <stdlib.h> #include <float.h> #include <math.h> #define INF INT32_MAX //#define Test 1 /* * Check strict math settings * We rely on the assumption that we store the vertices in an order where there is an edge from vertex i to i + 1 * If slope is infinity c is in the form x - c = 0 * Make sure to cycle from the last vertex to vertex 0 */ _Bool point_in_polygon(double x, double y); struct Line { double m; double c; int x1; int y1; int x2; int y2; }*edge_equations; struct Line_Double { double m; double c; double x1; double y1; double x2; double y2; }; struct intersept{ double x; double y; } *intersepts; int **vertices; int num_vertices; int num_edges; double r(double x) { if (!((int)fabs(x))) { if ((x > 0 && x - 0.0000001 < 0) || (x < 0 && x + 0.0000001 > 0)) return round(x); } if(((int) (fabs(x) + 0.0000001) > (int) fabs(x)) || ((int) (fabs(x) - 0.0000001) < (int) fabs(x))) { return round(x); } return x; } struct Line FindMC(int x1, int y1, int x2, int y2) { struct Line line = { .m = (x1 == x2 ? INF : r(((1.0 * (y2 - y1)) / (x2 - x1)))), .c = r(((x1 == x2) ? (0 - x1) : (y1 - (x1 * (1.0 * (y2 - y1) / (x2 - x1))))))}; return line; } void make_edge_equation(int pos_in_array, int x1, int y1, int x2, int y2) { if (x1 == x2) { edge_equations[pos_in_array].m = INF; edge_equations[pos_in_array].c = 0 - x1; edge_equations[pos_in_array].x1 = x1; edge_equations[pos_in_array].y1 = y1; edge_equations[pos_in_array].x2 = x2; edge_equations[pos_in_array].y2 = y2; return; } struct Line line = FindMC(x1, y1, x2, y2); edge_equations[pos_in_array].m = line.m; edge_equations[pos_in_array].c = line.c; edge_equations[pos_in_array].x1 = x1; edge_equations[pos_in_array].y1 = y1; edge_equations[pos_in_array].x2 = x2; edge_equations[pos_in_array].y2 = y2; } double lines_intersection[2]; double intersection_vertex_number; _Bool on_same_side(int const point1[], int const point2[], struct Line current_line) { double value1 = current_line.m == INF ? r(point1[0] + current_line.c) : r(point1[1] - current_line.m * point1[0] - current_line.c); double value2 = current_line.m == INF ? r(point2[0] + current_line.c) : r(point2[1] - current_line.m * point2[0] - current_line.c); return ((value1 > 0 && value2 > 0) || (value1 < 0 && value2 < 0)) ? 1 : 0; } int is_vertex(double x, double y) { for (int i = 0; i < num_vertices; ++i) if((double)vertices[i][0] == x && (double)vertices[i][1] == y) return i; return -1; } _Bool consider_point(struct intersept in, int x1, int y1, int x2, int y2, struct Line current_line) { double slope = current_line.m; int index; if ((index = is_vertex(in.x, in.y)) > -1) { if (in.x == x1 && in.y == y1) { if (!point_in_polygon((1.0 * ((x2 * 1) - (x1 * 1000000))) / (1 - 1000000), (1.0 * ((y2 * 1) - (y1 * 1000000))) / (1 - 1000000))) { return 1; } else return 0; } else if (in.x == x2 && in.y == y2) { if (!point_in_polygon((1.0 * ((x1 * 1) - (x2 * 1000000))) / (1 - 1000000), (1.0 * ((y1 * 1) - (y2 * 1000000))) / (1 - 1000000))) { return 1; } else return 0; } if (edge_equations[index].m == slope /*|| edge_equations[(index -1) % num_edges].m == slope */|| edge_equations[(index - 1) % num_edges].m == slope) { int index_overlap = -1000; //Initialized to this to try and make it an invalid array index if (edge_equations[index].m == slope) { index_overlap = index; if (sqrt(pow(x2 - in.x, 2) + pow(y2 - in.y, 2)) < sqrt(pow(x2 - (edge_equations[index].x1 == in.x && edge_equations[index].y1 == in.y ? edge_equations[index].x2 : edge_equations[index].x1), 2) + pow(y2 - (edge_equations[index].x1 == in.x && edge_equations[index].y1 == in.y ? edge_equations[index].y2 : edge_equations[index].y1), 2))) return 0; } /*else if (edge_equations[(index + 1) % num_edges].m == slope) { index_overlap = (index + 1) % num_edges; if (sqrt(pow(x2 - in.x, 2) + pow(y2 - in.y, 2)) < sqrt(pow(x2 - (edge_equations[(index + 1) % num_edges].x1 == in.x && edge_equations[(index + 1) % num_edges].y1 == in.y ? edge_equations[(index + 1) % num_edges].x2 : edge_equations[(index + 1) % num_edges].x1), 2) + pow(y2 - (edge_equations[(index + 1) % num_edges].x1 == in.x && edge_equations[(index + 1) % num_edges].y1 == in.y ? edge_equations[(index + 1) % num_edges].y2 : edge_equations[(index + 1) % num_edges].y1), 2))) return 0; }*/else if (edge_equations[(index - 1) % num_edges].m == slope) { index_overlap = (index - 1) % num_edges; if (sqrt(pow(x2 - in.x, 2) + pow(y2 - in.y, 2)) < sqrt(pow(x2 - (edge_equations[(index - 1) % num_edges].x1 == in.x && edge_equations[(index - 1) % num_edges].y1 == in.y ? edge_equations[(index - 1) % num_edges].x2 : edge_equations[(index - 1) % num_edges].x1), 2) + pow(y2 - (edge_equations[(index - 1) % num_edges].x1 == in.x && edge_equations[(index - 1) % num_edges].y1 == in.y ? edge_equations[(index - 1) % num_edges].y2 : edge_equations[(index - 1) % num_edges].y1), 2))) return 0; } int point1[2], point2[2]; point1[0] = edge_equations[(index_overlap - 1) % num_edges].x1; point1[1] = edge_equations[(index_overlap - 1) % num_edges].y1; point2[0] = edge_equations[(index_overlap + 1) % num_edges].x2; point2[1] = edge_equations[(index_overlap + 1) % num_edges].y2; if (on_same_side(point1, point2, current_line)) return 0; else return 1; } else { int point1[] = {edge_equations[(index - 1) % num_edges].x1, edge_equations[(index - 1) % num_edges].y1}; int point2[] = {edge_equations[index].x2, edge_equations[index].y2}; if (on_same_side(point1, point2, current_line)) return 0; else return 1; } } return 1; } double find_length_using_intersepts(int intersept_counter, int x1, int y1, int x2, int y2, struct Line current_line) { double sideA = DBL_MAX, sideB = DBL_MAX; #ifdef Test for (int j = 0; j < intersept_counter; ++j) printf("%lf %lf\n", intersepts[j].x, intersepts[j].y); #endif for (int i = 0; i < intersept_counter; ++i) { if (consider_point(intersepts[i], x1, y1, x2, y2, current_line)) { double d1 = sqrt(pow((intersepts[i].y - y1), 2) + pow((intersepts[i].x - x1), 2)); double d2 = sqrt(pow((intersepts[i].y - y2), 2) + pow((intersepts[i].x - x2), 2)); if (d1 == 0.0) sideA = 0; if (d2 == 0.0) sideB = 0; //if (d1 > d2) { if (d1 < d2) { if (sideA > d1) sideA = d1; } //else if (d2 > d1) { else if (d2 < d1) { if (sideB > d2) sideB = d2; } } } return sideA + sideB + sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2)); } int find_line_intersection(struct Line_Double l1, struct Line l2) //0 if intersection not in range, 1 if it intersects at a vertex, 2 if it intersects regularly, 3 if error(never actually happens) { if (l1.m != l2.m) { double x_intersect = l2.m == INF || l1.m == INF ? (l2.m == INF ? 0 - l2.c : 0 - l1.c) : r((l2.c - l1.c) / (l1.m - l2.m)); double y_intersect = l2.m == INF ? r(x_intersect * l1.m + l1.c) : r(x_intersect * l2.m + l2.c); lines_intersection[0] = x_intersect; lines_intersection[1] = y_intersect; //Checks if the line intersects the edge within the 2 end vertices if (!((l2.x1 == l2.x2 || l2.y1 == l2.y2 ? (l2.x1 == l2.x2 ? ((y_intersect >= (l2.y1 > l2.y2 ? l2.y2 : l2.y1)) && (y_intersect <= (l2.y1 > l2.y2 ? l2.y1 : l2.y2))) : ( (x_intersect >= (l2.x1 > l2.x2 ? l2.x2 : l2.x1)) && (x_intersect <= (l2.x1 > l2.x2 ? l2.x1 : l2.x2)))) : ( x_intersect >= (l2.x1 > l2.x2 ? l2.x2 : l2.x1) && x_intersect <= (l2.x1 > l2.x2 ? l2.x1 : l2.x2))) && (l1.x1 == l1.x2 || l1.y1 == l1.y2 ? (l1.x1 == l1.x2 ? ((y_intersect >= (l1.y1 > l1.y2 ? l1.y2 : l1.y1)) && (y_intersect <= (l1.y1 > l1.y2 ? l1.y1 : l1.y2))) : ( (x_intersect >= (l1.x1 > l1.x2 ? l1.x2 : l1.x1)) && (x_intersect <= (l1.x1 > l1.x2 ? l1.x1 : l1.x2)))) : ( x_intersect >= (l1.x1 > l1.x2 ? l1.x2 : l1.x1) && x_intersect <= (l1.x1 > l1.x2 ? l1.x1 : l1.x2))))) return 0; for (int i = 0; i < num_vertices; ++i) if (x_intersect == vertices[i][0] && y_intersect == vertices[i][1]) { intersection_vertex_number = i; return 1; } return 2; } return 3; } _Bool point_in_polygon(double x, double y) { struct Line_Double current_line = {.m = 0, .c = y, .x1 = x, .y1 = y, .x2 = INF, .y2 = y}; int result; int counter = 0; int vertex_intersection_counter = 0; double val1, val2; for (int i = 0; i < num_edges; ++i) { if (current_line.m == edge_equations[i].m) { if (current_line.c == edge_equations[i].c) { int neighbours[2][2]; int neighbour_counter = 0; for (int j = 0; j < num_edges; ++j) { //Find neighbours of the vertices on the end points of the current line if (j == i) continue; if ((edge_equations[j].x1 == edge_equations[i].x1) && (edge_equations[j].y1 == edge_equations[i].y1)) { neighbours[neighbour_counter][0] = edge_equations[j].x2; neighbours[neighbour_counter++][1] = edge_equations[j].y2; } else if ((edge_equations[j].x2 == edge_equations[i].x1) && (edge_equations[j].y2 == edge_equations[i].y1)) { neighbours[neighbour_counter][0] = edge_equations[j].x1; neighbours[neighbour_counter++][1] = edge_equations[j].y1; } else if ((edge_equations[j].x1 == edge_equations[i].x2) && (edge_equations[j].y1 == edge_equations[i].y2)) { neighbours[neighbour_counter][0] = edge_equations[j].x2; neighbours[neighbour_counter++][1] = edge_equations[j].y2; } else if ((edge_equations[j].x2 == edge_equations[i].x2) && (edge_equations[j].y2 == edge_equations[i].y2)) { neighbours[neighbour_counter][0] = edge_equations[j].x1; neighbours[neighbour_counter++][1] = edge_equations[j].y1; } } val1 = current_line.m == INF ? (current_line.x1 - neighbours[0][0]) : (neighbours[0][1] - (current_line.m * neighbours[0][0]) - current_line.c); val2 = current_line.m == INF ? (current_line.x1 - neighbours[1][0]) : (neighbours[1][1] - (current_line.m * neighbours[1][0]) - current_line.c); if (!((val1 > 0 && val2 > 0) || (val1 < 0 && val2 < 0))) ++counter; } } else { result = find_line_intersection(current_line, edge_equations[i]); #ifdef Test if (result) printf(""); #endif switch (result) { case 2: { counter++; break; } case 1: { //Check if both neighbours of the intersection vertex are on the same side of the line, ignore it. int neighbours[2][2]; int neighbour_count = 0; for (int j = 0; j < num_edges; ++j) { if (edge_equations[j].x1 == lines_intersection[0] && edge_equations[j].y1 == lines_intersection[1]) { neighbours[neighbour_count][0] = edge_equations[j].x2; neighbours[neighbour_count++][1] = edge_equations[j].y2; } else if (edge_equations[j].x2 == lines_intersection[0] && edge_equations[j].y2 == lines_intersection[1]) { neighbours[neighbour_count][0] = edge_equations[j].x1; neighbours[neighbour_count++][1] = edge_equations[j].y1; } } val1 = current_line.m == INF ? (current_line.x1 - neighbours[0][0]) : (neighbours[0][1] - (current_line.m * neighbours[0][0]) - current_line.c); val2 = current_line.m == INF ? (current_line.x1 - neighbours[1][0]) : (neighbours[1][1] - (current_line.m * neighbours[1][0]) - current_line.c); if (!((val1 > 0 && val2 > 0) || (val1 < 0 && val2 < 0)) && val1 && val2) { ++vertex_intersection_counter; ++counter; break; } } } } } counter -= (vertex_intersection_counter / 2); return counter % 2; } int main(int argc, char *argv[]) { double longest_line = 0; FILE *file = fopen(argv[1], "r"); fscanf(file, "%d", &num_vertices); num_edges = num_vertices; vertices = (int **) malloc(num_vertices * sizeof(int *)); for (int i = 0; i < num_vertices; ++i) vertices[i] = (int *) malloc(2 * sizeof(int)); edge_equations = (struct Line *) malloc(num_vertices * sizeof(struct Line)); fscanf(file, "%d %d", *(vertices), *(vertices) + 1); //We need to have atleast 2 vertices for an edge to be made for (int i = 1; i < num_vertices; ++i) { fscanf(file, "%d %d", *(vertices + i), *(vertices + i) + 1); make_edge_equation(i /*/ 2*/ - 1, vertices[(i - 1) % num_vertices][0], vertices[(i - 1) % num_vertices][1], vertices[i][0], vertices[i][1]); } make_edge_equation(num_edges - 1, vertices[num_edges - 1][0], vertices[num_edges - 1][1], vertices[0][0], vertices[0][1]); #ifdef Test for (int m = 0; m < num_edges; ++m) printf("x1: %d y1: %d | x2: %d y2: %d | m: %lf c: %lf\n", edge_equations[m].x1, edge_equations[m].y1, edge_equations[m].x2, edge_equations[m].y2, edge_equations[m].m, edge_equations[m].c); #endif double x_intersect; double y_intersect; intersepts = (struct intersept *) malloc(num_edges * sizeof(struct intersept)); int intersept_counter = 0; _Bool invalid; //Set to 1 if there if an intersection is found in between the line segment for (int i = 0; i < num_vertices; ++i) for (int j = i + 1; j < num_vertices; ++j) { #ifdef Test if (i == 46 && j == 50) printf("\n"); #endif intersept_counter = 0; invalid = 0; //Construct the current line we want to consider struct Line current_line = FindMC(vertices[i][0], vertices[i][1], vertices[j][0], vertices[j][1]); current_line.x1 = vertices[i][0]; current_line.y1 = vertices[i][1]; current_line.x2 = vertices[j][0]; current_line.y2 = vertices[j][1]; if ((j != i + 1) && !(i == 0 && j == num_vertices - 1)/*Last edge*/) //We are not looking at an edge of the polygon. If we are, we have way fewer things to check. if (!point_in_polygon((1.0 * ((current_line.x2 * 1 + current_line.x1 * 1000000)) / (1 + 1000000)), (1.0 * ((current_line.y2 * 1 + current_line.y1 * 1000000)) / (1 + 1000000)))) continue; for (int l = 0; l < num_edges; ++l) intersepts[l].x = intersepts[l].y = DBL_MAX; for (int k = 0; (k < num_edges); ++k) if (current_line.m != edge_equations[k].m) { x_intersect = edge_equations[k].m == INF || current_line.m == INF ? (edge_equations[k].m == INF ? 0 - edge_equations[k].c : 0 - current_line.c) : r((edge_equations[k].c - current_line.c) / (current_line.m - edge_equations[k].m)); y_intersect = edge_equations[k].m == INF ? r(x_intersect * current_line.m + current_line.c) : r( x_intersect * edge_equations[k].m + edge_equations[k].c); //Checks if the line intersects the edge within or on the 2 end vertices if (!(edge_equations[k].x1 == edge_equations[k].x2 || edge_equations[k].y1 == edge_equations[k].y2 ? (edge_equations[k].x1 == edge_equations[k].x2 ? ((y_intersect >= (edge_equations[k].y1 > edge_equations[k].y2 ? edge_equations[k].y2 : edge_equations[k].y1)) && (y_intersect <= (edge_equations[k].y1 > edge_equations[k].y2 ? edge_equations[k].y1 : edge_equations[k].y2))) : ((x_intersect >= (edge_equations[k].x1 > edge_equations[k].x2 ? edge_equations[k].x2 : edge_equations[k].x1)) && (x_intersect <= (edge_equations[k].x1 > edge_equations[k].x2 ? edge_equations[k].x1 : edge_equations[k].x2)))) : (x_intersect >= (edge_equations[k].x1 > edge_equations[k].x2 ? edge_equations[k].x2 : edge_equations[k].x1) && x_intersect <= (edge_equations[k].x1 > edge_equations[k].x2 ? edge_equations[k].x1 : edge_equations[k].x2)/* && y_intersect > (edge_equations[k].y1 > edge_equations[k].y2 ? edge_equations[k].y2 : edge_equations[k].y1) && y_intersect < (edge_equations[k].y1 > edge_equations[k].y2 ? edge_equations[k].y1 : edge_equations[k].y2)*/))) continue; //Checks if the line drawn between 2 vertices intersects any other vertex or edge if (current_line.m == INF ? ( y_intersect > (vertices[i][1] > vertices[j][1] ? vertices[j][1] : vertices[i][1]) && y_intersect < (vertices[i][1] > vertices[j][1] ? vertices[i][1] : vertices[j][1])) : ( x_intersect > (vertices[i][0] > vertices[j][0] ? vertices[j][0] : vertices[i][0]) && x_intersect < (vertices[i][0] > vertices[j][0] ? vertices[i][0] : vertices[j][0]))) { invalid = 1; break; } intersepts[intersept_counter].x = x_intersect; intersepts[intersept_counter++].y = y_intersect; } if (!invalid) { double current_line_length_possible = find_length_using_intersepts(intersept_counter, vertices[i][0], vertices[i][1], vertices[j][0], vertices[j][1], current_line); longest_line = current_line_length_possible > longest_line ? current_line_length_possible : longest_line; } } printf("Longest line in the polygon is %lf\n", longest_line); return 0; }
C
#include "Search_Engine.h" int main() { char c; char word[100]; char fileName[9][100]; int word_num_sum = 0; int comparison_sum = 0; strcpy(fileName[0], "document1.txt"); strcpy(fileName[1], "document2.txt"); strcpy(fileName[2], "document3.txt"); strcpy(fileName[3], "document4.txt"); strcpy(fileName[4], "document5.txt"); strcpy(fileName[5], "document6.txt"); strcpy(fileName[6], "document7.txt"); strcpy(fileName[7], "document8.txt"); strcpy(fileName[8], "document9.txt"); for (int i = 0; i < 9; i++) { build_hash_table(fileName[i]); doc_index++; } for (int i = 0; i < 9; i++) { word_num_sum += db_word_number[i]; comparison_sum += comparison[i]; } printf("Total number of documents: %d\n", doc_index); printf("Total number of indexed words: %d\n", word_num_sum); printf("Total number of comparison: %d\n", comparison_sum); printf("\n"); printf("*************˻**************\n"); printf("S: ܾ ˻\n"); printf("Q: α׷ \n"); printf("**********************************\n"); while (true) { printf("Է> "); c = getch(); putch(c); c = toupper(c); switch (c) { case 'S': printf("\n"); printf("ã ܾ Էϼ> "); scanf("%s", word); int comparison = search_table(word); printf("Total number of comparison: %d\n\n", comparison); break; case 'Q': printf("\n"); exit(1); break; } } } //ؽ ̺ void build_hash_table(char *fileName) { FILE *fp; fp = fopen(fileName, "r"); while (!feof(fp)) { // оδ fscanf(fp, "%s", database[doc_index][db_word_number[doc_index]]);//Ͽ ϳ оδ. hash_insert(database[doc_index][db_word_number[doc_index]], db_word_number[doc_index]); db_word_number[doc_index]++; } } void hash_insert(char *word, int position) { node_pointer s = Hash_Table; char modified_word[100]; strcpy(modified_word, word); int length = strlen(word); for (int i = 0; i < length; i++) {// ҹڷ ٲ if('A' <= modified_word[i] && modified_word[i] <= 'Z') modified_word[i] = tolower(modified_word[i]); } for (int i = 0; i < length; i++) {//ĺ if ('a' <= modified_word[i] && modified_word[i] <= 'z') { modified_word[i] = modified_word[i]; } else { modified_word[i] = NULL; break; } } int key = hash(modified_word); s = (s + key); node_pointer new_node = (node_pointer)malloc(sizeof(node)); strcpy(new_node->word, modified_word); new_node->link = NULL; for (int i = 0; i < 9; i++) { new_node->info.count[i] = 0; } int compare; if (!s->link->word) { //ù° ڸ NULL̸ ƹ͵ Ǿ ʴٴ Ⱑ ǹǷ ڸ s->link = new_node; new_node->info.position[doc_index][++new_node->info.count[doc_index]] = position; //īƮ ϳ Ű ׿ شϴ ε ǰ ִ´. } else { // NULL ƴϸ while (s->link){ // 尡 NULL ƴϸ if (strcmp(modified_word, s->link->word) == 0) { //Ϸ ܾ ܾ comparison[doc_index]++; // Ƚ ϳ ø. s = s->link; s->info.position[doc_index][++s->info.count[doc_index]] = position; free(new_node); return; } else if (strcmp(modified_word, s->link->word) < 0) { // Ϸ ܾ ܾ ݺ comparison[doc_index]++; // Ƚ ϳ ø. new_node->link = s->link; s->link = new_node; new_node->info.position[doc_index][++new_node->info.count[doc_index]] = position; //īƮ ϳ Ű ׿ شϴ ε ǰ ִ´. return; } else s = s->link; //̵ } //尡 ׳ δ. s->link = new_node; new_node->info.position[doc_index][++new_node->info.count[doc_index]] = position; } } int hash(char* word) { return transform(word) % TABLE_SIZE; } int transform(char* word) { int number = 0; while (*word) { number += *word++; } return number; } int search_table(char *word) { node_pointer s = Hash_Table; int word_number; int word_position; char modified_word[100]; strcpy(modified_word, word); int length = strlen(word); for (int i = 0; i < length; i++) {// ҹڷ ٲ if ('A' <= modified_word[i] && modified_word[i] <= 'Z') modified_word[i] = tolower(modified_word[i]); } for (int i = 0; i < length; i++) {//ĺ if ('a' <= modified_word[i] && modified_word[i] <= 'z') { modified_word[i] = modified_word[i]; } else { modified_word[i] = NULL; break; } } int cmp = 0; //񱳿 ī Լ int key = hash(modified_word); //ܾ Ű ȯ s = s + key; //s ش ε Ű while (s->link) { // 尡 ϸ if (strcmp(modified_word, s->link->word) == 0) { cmp++; // ( ġϴ ) for (int document = 0; document < 9; document++) { word_number = s->link->info.count[document]; if (word_number == 0) continue; printf("\n<document%d.txt> %s: %d\n", document + 1, word, word_number); for (int n = 1; n <= word_number; n++) { word_position = s->link->info.position[document][n]; show(document, word_number, word_position, word); } printf("\n"); } return cmp; } cmp++; //(񱳰 ٸ ) s = s->link; } return false; } void show(int document, int number, int position, char *word) { int size = number; if (0 <= position && position <= 4) {} // ۺκ̸ ... ʵ else { printf("... "); } for (int i = 4; i >= 0; i--) { // 4ܾ if ((position - i) < 0) { continue; } else { printf("%s ", database[document][position - i]); } } for (int i = 1; i <= 4; i++) {// 4ܾ if ((position + i) >= 1000) { break; } else { printf("%s ", database[document][position + i]); } } if (position >= db_word_number[doc_index] - 4 && position <= db_word_number[doc_index]) { printf("\n"); } // ... ʵ else { printf("... \n"); } }
C
#ifndef __EEPROM__H #define __EEPROM__H #define EEPROM_ADDRESS 0xA2 #define EEPROM_SIZE 32768 /* EEPROM : addr , size , buf . */ extern bit ReadEEPROM(unsigned short address, unsigned char xdata *buf, unsigned short length); /* EEPROM : addr , size , buf . */ extern bit WriteEEPROM( unsigned short address, unsigned char xdata *buf, unsigned short length ); #endif
C
#include<linux/module.h> #include<linux/init.h> #include<linux/fs.h> #include<linux/cdev.h> MODULE_LICENSE("GPL"); // GPL license used by linux kernel developer..module stacking..some driver might not compatible with non GPL MODULE_AUTHOR("DU"); /*things need for char device * 1.device numbe:dev no. is used by linux to identify dev. * 2.cdev structure: kernel representation char device. * 2.1file operation:operations that can be done on device. * /usr/src/<your version Linux kernel>/include/linux/fs.h */ static dev_t devnum; //device no. //static allocation of dev numb-register_chardev static struct cdev _cdev;//represents char device.always after dev no. static int sample_open(struct inode *inode, struct file *filep) { printk("Sample open function\n"); return 0; } static int sample_close(struct inode *inode,struct file *filep) { printk("sample close function \n"); return 0; } struct file_operations fops= { //points to function .open = sample_open, .release = sample_close, };//Designated initialization of structture static int __init sample_init(void){ int ret; devnum =MKDEV(42,0);//used to create dev no.using major&minor no. ret=register_chrdev_region(devnum,1,"samlpe_dev");//request kernel..and if we use 3 instead of i.e. 3device acan access by 1 cdev struct if(ret){ //non zero meansnon successfull (error code in kernel) printk("kernel denied request for device number\n"); // might be same device number is used other device return ret; } cdev_init(&_cdev,&fops);//Binds cdev with file operations ret = cdev_add(&_cdev,devnum,1);//after this device is Live if(ret) { printk("unable to cdev to kernel\n"); unregister_chrdev_region(devnum, 1); return ret; } printk("Done init\n"); return 0; } static void __exit sample_exit(void){ cdev_del(&_cdev); unregister_chrdev_region(devnum,1); printk("Good Byee\n"); } module_init(sample_init);// on module init function to be executed is sample_init module_exit(sample_exit);
C
#include <stdio.h> int main() { int c, v, hun, fif, twe, ten, fiv, two; scanf("%d", &v); c=v; hun=c/100; c=c-(hun*100); fif=c/50; c=c-(fif*50); twe=c/20; c=c-(twe*20); ten=c/10; c=c-(ten*10); fiv=c/5; c=c-(fiv*5); two=c/2; c=c-(two*2); printf("%d\n", v); printf("%d nota(s) de R$ 100,00\n", hun); printf("%d nota(s) de R$ 50,00\n", fif); printf("%d nota(s) de R$ 20,00\n", twe); printf("%d nota(s) de R$ 10,00\n", ten); printf("%d nota(s) de R$ 5,00\n", fiv); printf("%d nota(s) de R$ 2,00\n", two); printf("%d nota(s) de R$ 1,00\n", c); return 0; }
C
#include <cogo/cogo_await.h> // should be invoked through CO_AWAIT() void cogo_await_await(cogo_await_t* const thiz, cogo_await_t* const co) { COGO_ASSERT(thiz && thiz->sched && co); #ifndef NDEBUG // no loop in call chain for (cogo_await_t const* node = thiz; node; node = node->caller) { COGO_ASSERT(co != node); } #endif // call stack push co->caller = thiz; // continue from resume point thiz->sched->top = co->top ? co->top : co; } // run until yield co_status_t cogo_await_resume(cogo_await_t* const co) { #define TOP (sched.top) COGO_ASSERT(co); if (CO_STATUS(co) != CO_STATUS_END) { cogo_await_sched_t sched = { .top = co->top ? co->top : co, // resume or begin }; for (;;) { TOP->sched = &sched; TOP->base.resume(TOP); switch (CO_STATUS(TOP)) { case CO_STATUS_END: // return TOP = TOP->caller; if (!TOP) { // end goto exit; } continue; case CO_STATUS_BEGIN: // await continue; default: // yield goto exit; } } exit: co->top = TOP; // save resume point } return CO_STATUS(co); #undef TOP } void cogo_await_run(cogo_await_t* const co) { COGO_ASSERT(co); while (cogo_await_resume(co) != CO_STATUS_END) { } }
C
#include <lpc214x.h> void delay(unsigned int time) { unsigned int i,j; for(i=0;i<time;i++) for(j=0;j<1000;j++); } int main() { unsigned int period=1000, i; PINSEL1 &= 0xFFFFF3FF; // Pin 0.21 as PWM5 pin PINSEL1 |= 0x00000400; PWMPR = 0x00; PWMMCR = 0x00000002; PWMMR0 = period; PWMMR5 = period/2; PWMLER = 0x000000021; PWMPCR = 0x00002000; PWMTCR = 0x00000009; //Enable PWM and TC while(1) { for(i=0;i<period;i++) { PWMMR5 = i; PWMLER = 0x000000021; delay(10); } for(i=period;i>0;i--) { PWMMR5 = i; PWMLER = 0x000000021; delay(10); } } }
C
#ifndef OSPFSFIX_H #define OSPFSFIX_H #include <errno.h> #include <stdint.h> #include "ospfs.h" #define MAX_FILENAME_LEN 1024 //Define Error Messages #define ERROR(msg) printf("%s in %s, Line:%d\n", msg, __FILE__, __LINE__) #define UNFIXABLE(msg) printf("Error Unfixable: %s\n", msg) //Define success message #define FIXED(msg) printf("Fixed Error: %s\n", msg) //Define progress check messages #define CHECK(msg) printf("TESTING %s\n", msg) #define CORRECT(msg) printf("PASSED %s CHECKS\n", msg) //Return values for the function #define FS_OK 0 #define FS_FIXED 1 #define FS_BROKEN 2 // holds info about file system, data read from input, and ospfs structures typedef struct file_system{ char filename[MAX_FILENAME_LEN + 1]; void *buffer; uint32_t buffer_size; ospfs_super_t super; ospfs_inode_t *inodes; uint32_t num_bitmap_blocks; void *bitmap; } file_system_t; // global structure that holds data for file system extern file_system_t fs; //runs primary functions to try and fix file system int fix_file_system(); void *block_pointer(uint32_t block_num); void *block_offset(uint32_t block_num, uint32_t offset); #endif
C
#ifdef _WINDOWS #define _CRTDBG_MAP_ALLOC #include <crtdbg.h> #endif #include "mjson.h" #include <assert.h> /* assert() */ #include <errno.h> /* errno, ERANGE */ #include <math.h> /* HUGE_VAL */ #include <stdio.h> /* sprintf() */ #include <stdlib.h> /* NULL, malloc(), realloc(), free(), strtod() */ #include <string.h> /* memcpy() */ #ifndef MJSON_PARSE_STACK_INIT_SIZE #define MJSON_PARSE_STACK_INIT_SIZE 256 #endif #ifndef MJSON_PARSE_STRINGIFY_INIT_SIZE #define MJSON_PARSE_STRINGIFY_INIT_SIZE 256 #endif #define EXPECT(c, ch) do { assert(*c->json == (ch)); c->json++; } while(0) #define ISDIGIT(ch) ((ch) >= '0' && (ch) <= '9') #define ISDIGIT1TO9(ch) ((ch) >= '1' && (ch) <= '9') #define PUTC(c, ch) do { *(char*)mjson_context_push(c, sizeof(char)) = (ch); } while(0) #define PUTS(c, s, len) memcpy(mjson_context_push(c, len), s, len) typedef struct { const char* json; char* stack; size_t size, top; }mjson_context; static void* mjson_context_push(mjson_context* c, size_t size) { void* ret; assert(size > 0); if (c->top + size >= c->size) { if (c->size == 0) c->size = MJSON_PARSE_STACK_INIT_SIZE; while (c->top + size >= c->size) c->size += c->size >> 1; /* c->size * 1.5 */ c->stack = (char*)realloc(c->stack, c->size); } ret = c->stack + c->top; c->top += size; return ret; } static void* mjson_context_pop(mjson_context* c, size_t size) { assert(c->top >= size); return c->stack + (c->top -= size); } static void mjson_parse_whitespace(mjson_context* c) { const char *p = c->json; while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r') p++; c->json = p; } static int mjson_parse_literal(mjson_context* c, mjson_value* v, const char* literal, mjson_type type) { size_t i; EXPECT(c, literal[0]); for (i = 0; literal[i + 1]; i++) if (c->json[i] != literal[i + 1]) return MJSON_PARSE_INVALID_VALUE; c->json += i; v->type = type; return MJSON_PARSE_OK; } static int mjson_parse_number(mjson_context* c, mjson_value* v) { const char* p = c->json; if (*p == '-') p++; if (*p == '0') p++; else { if (!ISDIGIT1TO9(*p)) return MJSON_PARSE_INVALID_VALUE; for (p++; ISDIGIT(*p); p++); } if (*p == '.') { p++; if (!ISDIGIT(*p)) return MJSON_PARSE_INVALID_VALUE; for (p++; ISDIGIT(*p); p++); } if (*p == 'e' || *p == 'E') { p++; if (*p == '+' || *p == '-') p++; if (!ISDIGIT(*p)) return MJSON_PARSE_INVALID_VALUE; for (p++; ISDIGIT(*p); p++); } errno = 0; v->u.n = strtod(c->json, NULL); if (errno == ERANGE && (v->u.n == HUGE_VAL || v->u.n == -HUGE_VAL)) return MJSON_PARSE_NUMBER_TOO_BIG; v->type = MJSON_NUMBER; c->json = p; return MJSON_PARSE_OK; } static const char* mjson_parse_hex4(const char* p, unsigned* u) { int i; *u = 0; for (i = 0; i < 4; i++) { char ch = *p++; *u <<= 4; if (ch >= '0' && ch <= '9') *u |= ch - '0'; else if (ch >= 'A' && ch <= 'F') *u |= ch - ('A' - 10); else if (ch >= 'a' && ch <= 'f') *u |= ch - ('a' - 10); else return NULL; } return p; } static void mjson_encode_utf8(mjson_context* c, unsigned u) { if (u <= 0x7F) PUTC(c, u & 0xFF); else if (u <= 0x7FF) { PUTC(c, 0xC0 | ((u >> 6) & 0xFF)); PUTC(c, 0x80 | ( u & 0x3F)); } else if (u <= 0xFFFF) { PUTC(c, 0xE0 | ((u >> 12) & 0xFF)); PUTC(c, 0x80 | ((u >> 6) & 0x3F)); PUTC(c, 0x80 | ( u & 0x3F)); } else { assert(u <= 0x10FFFF); PUTC(c, 0xF0 | ((u >> 18) & 0xFF)); PUTC(c, 0x80 | ((u >> 12) & 0x3F)); PUTC(c, 0x80 | ((u >> 6) & 0x3F)); PUTC(c, 0x80 | ( u & 0x3F)); } } #define STRING_ERROR(ret) do { c->top = head; return ret; } while(0) static int mjson_parse_string_raw(mjson_context* c, char** str, size_t* len) { size_t head = c->top; unsigned u, u2; const char* p; EXPECT(c, '\"'); p = c->json; for (;;) { char ch = *p++; switch (ch) { case '\"': *len = c->top - head; *str = mjson_context_pop(c, *len); c->json = p; return MJSON_PARSE_OK; case '\\': switch (*p++) { case '\"': PUTC(c, '\"'); break; case '\\': PUTC(c, '\\'); break; case '/': PUTC(c, '/' ); break; case 'b': PUTC(c, '\b'); break; case 'f': PUTC(c, '\f'); break; case 'n': PUTC(c, '\n'); break; case 'r': PUTC(c, '\r'); break; case 't': PUTC(c, '\t'); break; case 'u': if (!(p = mjson_parse_hex4(p, &u))) STRING_ERROR(MJSON_PARSE_INVALID_UNICODE_HEX); if (u >= 0xD800 && u <= 0xDBFF) { /* surrogate pair */ if (*p++ != '\\') STRING_ERROR(MJSON_PARSE_INVALID_UNICODE_SURROGATE); if (*p++ != 'u') STRING_ERROR(MJSON_PARSE_INVALID_UNICODE_SURROGATE); if (!(p = mjson_parse_hex4(p, &u2))) STRING_ERROR(MJSON_PARSE_INVALID_UNICODE_HEX); if (u2 < 0xDC00 || u2 > 0xDFFF) STRING_ERROR(MJSON_PARSE_INVALID_UNICODE_SURROGATE); u = (((u - 0xD800) << 10) | (u2 - 0xDC00)) + 0x10000; } mjson_encode_utf8(c, u); break; default: STRING_ERROR(MJSON_PARSE_INVALID_STRING_ESCAPE); } break; case '\0': STRING_ERROR(MJSON_PARSE_MISS_QUOTATION_MARK); default: if ((unsigned char)ch < 0x20) STRING_ERROR(MJSON_PARSE_INVALID_STRING_CHAR); PUTC(c, ch); } } } static int mjson_parse_string(mjson_context* c, mjson_value* v) { int ret; char* s; size_t len; if ((ret = mjson_parse_string_raw(c, &s, &len)) == MJSON_PARSE_OK) mjson_set_string(v, s, len); return ret; } static int mjson_parse_value(mjson_context* c, mjson_value* v); static int mjson_parse_array(mjson_context* c, mjson_value* v) { size_t i, size = 0; int ret; EXPECT(c, '['); mjson_parse_whitespace(c); if (*c->json == ']') { c->json++; v->type = MJSON_ARRAY; v->u.a.size = 0; v->u.a.e = NULL; return MJSON_PARSE_OK; } for (;;) { mjson_value e; mjson_init(&e); if ((ret = mjson_parse_value(c, &e)) != MJSON_PARSE_OK) break; memcpy(mjson_context_push(c, sizeof(mjson_value)), &e, sizeof(mjson_value)); size++; mjson_parse_whitespace(c); if (*c->json == ',') { c->json++; mjson_parse_whitespace(c); } else if (*c->json == ']') { c->json++; v->type = MJSON_ARRAY; v->u.a.size = size; size *= sizeof(mjson_value); memcpy(v->u.a.e = (mjson_value*)malloc(size), mjson_context_pop(c, size), size); return MJSON_PARSE_OK; } else { ret = MJSON_PARSE_MISS_COMMA_OR_SQUARE_BRACKET; break; } } /* Pop and free values on the stack */ for (i = 0; i < size; i++) mjson_free((mjson_value*)mjson_context_pop(c, sizeof(mjson_value))); return ret; } static int mjson_parse_object(mjson_context* c, mjson_value* v) { size_t i, size; mjson_member m; int ret; EXPECT(c, '{'); mjson_parse_whitespace(c); if (*c->json == '}') { c->json++; v->type = MJSON_OBJECT; v->u.o.m = 0; v->u.o.size = 0; return MJSON_PARSE_OK; } m.k = NULL; size = 0; for (;;) { char* str; mjson_init(&m.v); /* parse key */ if (*c->json != '"') { ret = MJSON_PARSE_MISS_KEY; break; } if ((ret = mjson_parse_string_raw(c, &str, &m.klen)) != MJSON_PARSE_OK) break; memcpy(m.k = (char*)malloc(m.klen + 1), str, m.klen); m.k[m.klen] = '\0'; /* parse ws colon ws */ mjson_parse_whitespace(c); if (*c->json != ':') { ret = MJSON_PARSE_MISS_COLON; break; } c->json++; mjson_parse_whitespace(c); /* parse value */ if ((ret = mjson_parse_value(c, &m.v)) != MJSON_PARSE_OK) break; memcpy(mjson_context_push(c, sizeof(mjson_member)), &m, sizeof(mjson_member)); size++; m.k = NULL; /* ownership is transferred to member on stack */ /* parse ws [comma | right-curly-brace] ws */ mjson_parse_whitespace(c); if (*c->json == ',') { c->json++; mjson_parse_whitespace(c); } else if (*c->json == '}') { size_t s = sizeof(mjson_member) * size; c->json++; v->type = MJSON_OBJECT; v->u.o.size = size; memcpy(v->u.o.m = (mjson_member*)malloc(s), mjson_context_pop(c, s), s); return MJSON_PARSE_OK; } else { ret = MJSON_PARSE_MISS_COMMA_OR_CURLY_BRACKET; break; } } /* Pop and free members on the stack */ free(m.k); for (i = 0; i < size; i++) { mjson_member* m = (mjson_member*)mjson_context_pop(c, sizeof(mjson_member)); free(m->k); mjson_free(&m->v); } v->type = MJSON_NULL; return ret; } static int mjson_parse_value(mjson_context* c, mjson_value* v) { switch (*c->json) { case 't': return mjson_parse_literal(c, v, "true", MJSON_TRUE); case 'f': return mjson_parse_literal(c, v, "false", MJSON_FALSE); case 'n': return mjson_parse_literal(c, v, "null", MJSON_NULL); default: return mjson_parse_number(c, v); case '"': return mjson_parse_string(c, v); case '[': return mjson_parse_array(c, v); case '{': return mjson_parse_object(c, v); case '\0': return MJSON_PARSE_EXPECT_VALUE; } } int mjson_parse(mjson_value* v, const char* json) { mjson_context c; int ret; assert(v != NULL); c.json = json; c.stack = NULL; c.size = c.top = 0; mjson_init(v); mjson_parse_whitespace(&c); if ((ret = mjson_parse_value(&c, v)) == MJSON_PARSE_OK) { mjson_parse_whitespace(&c); if (*c.json != '\0') { v->type = MJSON_NULL; ret = MJSON_PARSE_ROOT_NOT_SINGULAR; } } assert(c.top == 0); free(c.stack); return ret; } #if 0 // Unoptimized static void mjson_stringify_string(mjson_context* c, const char* s, size_t len) { size_t i; assert(s != NULL); PUTC(c, '"'); for (i = 0; i < len; i++) { unsigned char ch = (unsigned char)s[i]; switch (ch) { case '\"': PUTS(c, "\\\"", 2); break; case '\\': PUTS(c, "\\\\", 2); break; case '\b': PUTS(c, "\\b", 2); break; case '\f': PUTS(c, "\\f", 2); break; case '\n': PUTS(c, "\\n", 2); break; case '\r': PUTS(c, "\\r", 2); break; case '\t': PUTS(c, "\\t", 2); break; default: if (ch < 0x20) { char buffer[7]; sprintf(buffer, "\\u%04X", ch); PUTS(c, buffer, 6); } else PUTC(c, s[i]); } } PUTC(c, '"'); } #else static void mjson_stringify_string(mjson_context* c, const char* s, size_t len) { static const char hex_digits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; size_t i, size; char* head, *p; assert(s != NULL); p = head = mjson_context_push(c, size = len * 6 + 2); /* "\u00xx..." */ *p++ = '"'; for (i = 0; i < len; i++) { unsigned char ch = (unsigned char)s[i]; switch (ch) { case '\"': *p++ = '\\'; *p++ = '\"'; break; case '\\': *p++ = '\\'; *p++ = '\\'; break; case '\b': *p++ = '\\'; *p++ = 'b'; break; case '\f': *p++ = '\\'; *p++ = 'f'; break; case '\n': *p++ = '\\'; *p++ = 'n'; break; case '\r': *p++ = '\\'; *p++ = 'r'; break; case '\t': *p++ = '\\'; *p++ = 't'; break; default: if (ch < 0x20) { *p++ = '\\'; *p++ = 'u'; *p++ = '0'; *p++ = '0'; *p++ = hex_digits[ch >> 4]; *p++ = hex_digits[ch & 15]; } else *p++ = s[i]; } } *p++ = '"'; c->top -= size - (p - head); } #endif static void mjson_stringify_value(mjson_context* c, const mjson_value* v) { size_t i; switch (v->type) { case MJSON_NULL: PUTS(c, "null", 4); break; case MJSON_FALSE: PUTS(c, "false", 5); break; case MJSON_TRUE: PUTS(c, "true", 4); break; case MJSON_NUMBER: c->top -= 32 - sprintf(mjson_context_push(c, 32), "%.17g", v->u.n); break; case MJSON_STRING: mjson_stringify_string(c, v->u.s.s, v->u.s.len); break; case MJSON_ARRAY: PUTC(c, '['); for (i = 0; i < v->u.a.size; i++) { if (i > 0) PUTC(c, ','); mjson_stringify_value(c, &v->u.a.e[i]); } PUTC(c, ']'); break; case MJSON_OBJECT: PUTC(c, '{'); for (i = 0; i < v->u.o.size; i++) { if (i > 0) PUTC(c, ','); mjson_stringify_string(c, v->u.o.m[i].k, v->u.o.m[i].klen); PUTC(c, ':'); mjson_stringify_value(c, &v->u.o.m[i].v); } PUTC(c, '}'); break; default: assert(0 && "invalid type"); } } char* mjson_stringify(const mjson_value* v, size_t* length) { mjson_context c; assert(v != NULL); c.stack = (char*)malloc(c.size = MJSON_PARSE_STRINGIFY_INIT_SIZE); c.top = 0; mjson_stringify_value(&c, v); if (length) *length = c.top; PUTC(&c, '\0'); return c.stack; } void mjson_free(mjson_value* v) { size_t i; assert(v != NULL); switch (v->type) { case MJSON_STRING: free(v->u.s.s); break; case MJSON_ARRAY: for (i = 0; i < v->u.a.size; i++) mjson_free(&v->u.a.e[i]); free(v->u.a.e); break; case MJSON_OBJECT: for (i = 0; i < v->u.o.size; i++) { free(v->u.o.m[i].k); mjson_free(&v->u.o.m[i].v); } free(v->u.o.m); break; default: break; } v->type = MJSON_NULL; } mjson_type mjson_get_type(const mjson_value* v) { assert(v != NULL); return v->type; } int mjson_get_boolean(const mjson_value* v) { assert(v != NULL && (v->type == MJSON_TRUE || v->type == MJSON_FALSE)); return v->type == MJSON_TRUE; } void mjson_set_boolean(mjson_value* v, int b) { mjson_free(v); v->type = b ? MJSON_TRUE : MJSON_FALSE; } double mjson_get_number(const mjson_value* v) { assert(v != NULL && v->type == MJSON_NUMBER); return v->u.n; } void mjson_set_number(mjson_value* v, double n) { mjson_free(v); v->u.n = n; v->type = MJSON_NUMBER; } const char* mjson_get_string(const mjson_value* v) { assert(v != NULL && v->type == MJSON_STRING); return v->u.s.s; } size_t mjson_get_string_length(const mjson_value* v) { assert(v != NULL && v->type == MJSON_STRING); return v->u.s.len; } void mjson_set_string(mjson_value* v, const char* s, size_t len) { assert(v != NULL && (s != NULL || len == 0)); mjson_free(v); v->u.s.s = (char*)malloc(len + 1); memcpy(v->u.s.s, s, len); v->u.s.s[len] = '\0'; v->u.s.len = len; v->type = MJSON_STRING; } size_t mjson_get_array_size(const mjson_value* v) { assert(v != NULL && v->type == MJSON_ARRAY); return v->u.a.size; } mjson_value* mjson_get_array_element(const mjson_value* v, size_t index) { assert(v != NULL && v->type == MJSON_ARRAY); assert(index < v->u.a.size); return &v->u.a.e[index]; } size_t mjson_get_object_size(const mjson_value* v) { assert(v != NULL && v->type == MJSON_OBJECT); return v->u.o.size; } const char* mjson_get_object_key(const mjson_value* v, size_t index) { assert(v != NULL && v->type == MJSON_OBJECT); assert(index < v->u.o.size); return v->u.o.m[index].k; } size_t mjson_get_object_key_length(const mjson_value* v, size_t index) { assert(v != NULL && v->type == MJSON_OBJECT); assert(index < v->u.o.size); return v->u.o.m[index].klen; } mjson_value* mjson_get_object_value(const mjson_value* v, size_t index) { assert(v != NULL && v->type == MJSON_OBJECT); assert(index < v->u.o.size); return &v->u.o.m[index].v; }
C
#include<stdio.h> void main() { int i,sum=0,size; int num[]={}; printf("Enter the number of Array size\t"); scanf("%d",&size); printf("Array size is = %d\n",size); for(i=0; i<size; i++){ scanf("%d",&num[i]); sum=sum+num[i]; } printf("Total number is = %d",sum); }
C
#include "backtracking.h" //Matriz com as possibilidades de cores de cada vértice. //Cada linha i corresponde ao id vértice i //e cada coluna j (j > 0) corresponde à cor j. //A posição [i][0] indica quantas cores o vértice i pode assumir. int **possibilidades; //Inicializa a matriz de possibilidades. void inicializa_possibilidades(Sudoku *sudoku){ int i, j; int n = sudoku->grafo->n; //Iniciando a matriz. possibilidades = vetor2d(n, sudoku->dimensao + 1); for(i=0; i<n; i++){ possibilidades[i][0] = sudoku->dimensao; for(j=1; j<=sudoku->dimensao; j++){ //Inicialmente todas as cores são possíveis. possibilidades[i][j] = 1; } } for(i=0; i<n; i++){ int cor = sudoku->grafo->cor[i]; if(cor > 0){ atualiza_possibilidades(sudoku, i, cor); } } } //Atualiza a matriz de possibilidades quando um vértice é colorido. void atualiza_possibilidades(Sudoku *sudoku, int v, int cor){ int i, j; //Zerando as possibilidades de cores de cor já que o vértice está colorido. for(i=0; i<=sudoku->dimensao; i++){ possibilidades[v][i] = 0; } //Zerando as possibilidades de cores dos vértices adjacentes à i. for(i=0; i<sudoku->grafo->hiper_arestas_por_vertice; i++){ int pos = sudoku->grafo->pos_hiper_aresta[v][i]; for(j=0; j<sudoku->grafo->tam_hiper_arestas; j++){ int u = sudoku->grafo->hiper_aresta[pos][j]; if(u != v){ int cor2 = sudoku->grafo->cor[u]; if(cor2 == 0 && possibilidades[u][cor] == 1){ possibilidades[u][cor] = 0; possibilidades[u][0]--; } } } } } //Tenta colorir um vértice. Se conseguir, então a matriz de //possibilidades é atualizada. void exato_colore(Sudoku *sudoku, int id, int cor){ if(grafo_colore_vertice(sudoku->grafo, id, cor) == true){ atualiza_possibilidades(sudoku, id, cor); } } //Função principal. bool algoritmo_exato(Sudoku *sudoku){ inicializa_possibilidades(sudoku); while(true){ Exato_Estado estado_vertice = poda_vertice(sudoku); if(estado_vertice == FIM){ return true; } Exato_Estado estado_hiper = poda_hiper_aresta(sudoku); if(estado_hiper == FIM){ return true; } if(estado_vertice == NAO_COLORIU && estado_hiper == NAO_COLORIU){ return backtracking(sudoku); } } } //Funções de poda. Podem resolver o sudoku. Exato_Estado poda_vertice(Sudoku *sudoku){ int i; int n = sudoku->grafo->n; Exato_Estado estado = FIM; for(i=0; i<n; i++){ if(possibilidades[i][0] > 0){ if(estado == FIM){ estado = NAO_COLORIU; } } if(possibilidades[i][0] == 1){ int cor; for(cor=1; cor<=sudoku->dimensao; cor++){ if(possibilidades[i][cor] == 1){ exato_colore(sudoku, i, cor); estado = COLORIU; } } } } return estado; } Exato_Estado poda_hiper_aresta(Sudoku *sudoku){ int c, i, j; int d = sudoku->dimensao; Exato_Estado estado = FIM; int total = 0; for(c=1; c<=d; c++){ int id; for(i=0; i<sudoku->grafo->qtd_hiper_arestas; i++){ total = 0; id = 0; for(j=0; j<sudoku->grafo->tam_hiper_arestas && total <= 1; j++){ int v = sudoku->grafo->hiper_aresta[i][j]; if(possibilidades[v][0] > 0){ if(estado == FIM){ estado = NAO_COLORIU; } } if(possibilidades[v][c] == 1){ total++; id = v; } } if(total == 1){ exato_colore(sudoku, id, c); estado = COLORIU; } } } return estado; } //Funções de tentativa e erro. void define_estaticos(int *vetor_combinacao, Grafo *grafo){ int i; for( i = 0; i < grafo->n; i++){ if(grafo->cor[i] > 0){ vetor_combinacao[i] = estatico; } } } bool backtracking(Sudoku *sudoku){ int k = 0; int menor_id_livre; int *vetor_combinacao = vetor1d(sudoku->grafo->n); define_estaticos(vetor_combinacao, sudoku->grafo); for(menor_id_livre=0; menor_id_livre<sudoku->grafo->n && vetor_combinacao[menor_id_livre] == estatico; menor_id_livre++){} if(menor_id_livre == sudoku->grafo->n){ return true; } while(vetor_combinacao[menor_id_livre] <= sudoku->dimensao && k < sudoku->grafo->n){ if(vetor_combinacao[k] == estatico){ k++; }else{ vetor_combinacao[k]++; while(possibilidades[k][vetor_combinacao[k]] == 0){ vetor_combinacao[k]++; } if(vetor_combinacao[menor_id_livre] > sudoku->dimensao){ return false; }else if(vetor_combinacao[k] > sudoku->dimensao){ vetor_combinacao[k] = 0; grafo_colore_vertice(sudoku->grafo, k, 0); k--; while(k>0 && vetor_combinacao[k] == estatico){ k--; } }else if(grafo_colore_vertice(sudoku->grafo, k, vetor_combinacao[k])){ k++; } } } return true; }
C
/* Pam'Console'logger by wC Description: Thiz enables you to log a tty to a file! =) According to a advisorie at www.securityfocus.com: A vulnerability exists in the pam_console PAM module, included as part of any Linux system running PAM. pam_console exists to own certain devices to users logging in to the console of a Linux machine. It is designed to allow only console users to utilize things such as sound devices. It will chown devices to users upon logging in, and chown them back to being owned by root upon logout. However, as certain devices do not have a 'hangup' mechanism, like a tty device, it is possible for a local user to continue to monitor activity on certain devices after logging out. This could allow an malicious user to sniff other users console sessions, and potentially obtain the root password if the root user logs in, or a user su's to root. They could also surreptitiously execute commands as the user on the console. Vulnerable : RedHat Linux 6.2 sparc RedHat Linux 6.2 i386 RedHat Linux 6.2 alpha RedHat Linux 6.1 sparc RedHat Linux 6.1 i386 RedHat Linux 6.1 alpha RedHat Linux 6.0 sparc RedHat Linux 6.0 i386 RedHat Linux 6.0 alpha Notice: I didnt code this from scratch cause there was allready a exploit available at the securityfocus site! I just added a easy feature to let thiz biatx log'to a file :] If you dont like it..dont use it ;) Sintaxe: Do the follownig to log a tty and output it to the screen... progname </dev/ttyN to spy on> -output Do the follownig to log a tty and output it to a logfile... progname </dev/ttyN to spy on> -l <logfilename> Who am i: Genetik Team Member [email protected] */ #include <stdio.h> #include <sys/fcntl.h> void sintaxe(char *progname) { printf("\n\tPam'console'logger by wC\n\n"); printf("Sintaxe: %s </dev/ttyN to spy on> -output\n",progname); printf(" -l <logfilename>\n"); printf("If you want to leave this running on background had a &\n"); printf("to the end of the sintaxe...\n"); printf("Please edit the source file and read the top'commentz\n"); printf("Thankz to securityfocus for the advisorie and the *original* code\n"); printf("Flamez to: [email protected]\n\n"); } main(int argc,char *argv[]) { char buf[80*24]; int sf; FILE *fx; if (argc<3) { sintaxe(argv[0]); exit(-1); } else { printf("\n\tPam'console'logger by wC\n\n"); if (strcasecmp(argv[2],"-output")==0) { sf=open(argv[1],O_RDWR); while (1) { lseek(sf,0,0); read(sf,buf,sizeof(buf)); write(1,"\033[2J\033[H",7); write(1,buf,sizeof(buf)); usleep(10000); } } else if ((strcasecmp(argv[2],"-l")==0) && (argc>=4)) { sf=open(argv[1],O_RDWR); while (1) { lseek(sf,0,0); read(sf,buf,sizeof(buf)); fx=fopen(argv[3],"a"); fputs(buf,fx); usleep(10000); } } else sintaxe(argv[0]); } } /* www.hack.co.za [14 June 2000]*/
C
#include <stdio.h> #define MOD 1000000007 unsigned long long int apow(unsigned long long int,unsigned long long int); int main(){ unsigned long long int t,n,ans,q,p; scanf("%llu",&t); while(t--){ scanf("%llu",&n); ans = ((n%MOD)*apow(2,(n-1)))%MOD; printf("%llu\n",ans); } } unsigned long long int apow(unsigned long long int b, unsigned long long int e){ unsigned long long int res=1; for (;;){ if (e&1){ res=((res%MOD)*(b%MOD))%MOD; } e >>= 1; if (!e) break; b=((b%MOD)*(b%MOD))%MOD; } return res; }
C
#include <stdio.h> using namespace std; int count(string s, int K) { int n = s.length(); for (int i = 0; i < n; i++) { { c=c+; } } return C * K + (K * (K - 1) / 2) * c1 * c2; } int main() { string S = "abcb"; int k = 2; cout << countOccurrences(S, k) << endl; return 0; }
C
#include <stdio.h> #include <stdlib.h> int main() { typedef struct { int i; char c; } foo; foo s; foo* t = (foo*) malloc(sizeof(foo)); s.i = 53; s.c = 'w'; (*t).i = 64; // t->a = 75; printf("s.i = %d, s.c = %c, t.a = %d\n", s.i, s.c, t->i); return 0; }
C
// test.opt.c #include <stdio.h> #include <stdlib.h> long kmul_o_s32_p_23 (long x) { long t0; long t1; long t2; long t3; long t4; long t5; long t6; long t7; long t8; long t9; long t10; long t11; long t12; long t13; long t14; long t15; long y; t0 = x; t1 = t0 << 1; t2 = t1 + x; t3 = t2 << 3; t4 = t3 - x; y = t4; return (y); } int main(int argc, char *argv[]) { int a, b; a = atoi(argv[1]); b = kmul_o_s32_p_23(a); printf("b = %d\n", b); return b; }
C
/* * adsr.h * * Created on: Oct 10, 2020 * Author: Zac */ #ifndef INC_ADSR_H_ #define INC_ADSR_H_ #include <stdint.h> #include <stdbool.h> #define SAMPLE_FREQ 40000 typedef enum { ENV_INIT = 0, ENV_ATTACK, ENV_DECAY, ENV_SUSTAIN, ENV_RELEASE }ADSR_STATE; typedef struct { uint16_t attack; uint16_t decay; float sustain; uint16_t release; uint32_t tick; float amplitude; bool note_on; ADSR_STATE state; }ADSR; void ADSR_init (ADSR *adsr, uint16_t a, uint16_t d, float s, uint16_t r); void ADSR_set_vals (ADSR *adsr, uint16_t a, uint16_t d, float s, uint16_t r); void ADSR_set_attack (ADSR *adsr, uint16_t a); void ADSR_set_decay (ADSR *adsr, uint16_t d); void ADSR_set_sustain (ADSR *adsr, float s); void ADSR_set_release (ADSR *adsr, uint16_t r); void ADSR_note_on (ADSR *adsr); void ADSR_note_off (ADSR *adsr); float ADSR_get_next (ADSR *adsr); #endif /* INC_ADSR_H_ */
C
/* ============================================================================ Name : clase7.c Author : Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdio_ext.h> #include <stdlib.h> #include <string.h> //Linux #define PURGAR __fpurge(stdin); //Windows //#define PURGAR fflush(stdin); #define EXIT_ERROR -1 #define QTY_CHARS 50 #define QTY_NOMBRES 5 int getString (char *pResultado, char *pMensaje, char *pMensajeError, int minimo, int maximo, int reintentos); int imprimirArrayString(char aNombre[][QTY_CHARS], int cantidad); void insercionString(char array[][QTY_CHARS], int limite); int imprimirArrayStringInt(char array[][QTY_CHARS], int cantidad, int arrayLong[]); void insercionStringInt(char array[][QTY_CHARS], int limite, int arrayInt[]); /*int getLong( long *pResultado, char *pMensaje, char *pMensajeError, long minimo, long maximo, int reintentos) { int retorno = EXIT_ERROR; long buffer; if( pResultado != NULL && pMensaje != NULL && pMensajeError != NULL && minimo < maximo && reintentos >= 0) { do { printf("%s", pMensaje); PURGAR if(scanf("%d",&buffer)==1) { if(buffer >= minimo && buffer <= maximo) { retorno = EXIT_SUCCESS; *pResultado = buffer; break; } } printf("%s",pMensajeError); reintentos--; }while(reintentos >= 0); } return retorno; }*/ int getInt( int *pResultado, char *pMensaje, char *pMensajeError, int minimo, int maximo, int reintentos) { int retorno = EXIT_ERROR; int buffer; if( pResultado != NULL && pMensaje != NULL && pMensajeError != NULL && minimo < maximo && reintentos >= 0) { do { printf("%s", pMensaje); PURGAR if(scanf("%d",&buffer)==1) { if(buffer >= minimo && buffer <= maximo) { retorno = EXIT_SUCCESS; *pResultado = buffer; break; } } printf("%s",pMensajeError); reintentos--; }while(reintentos >= 0); } return retorno; } int getString (char *pResultado, char *pMensaje, char *pMensajeError, int minimo, int maximo, int reintentos) { int retorno = EXIT_ERROR; char buffer[500]; if( pResultado != NULL && pMensaje != NULL && pMensajeError != NULL && minimo < maximo && reintentos >= 0) { do { printf("%s",pMensaje); PURGAR fgets(buffer,sizeof(buffer),stdin); buffer[strlen(buffer)-1] = '\0'; if(strlen(buffer)>=minimo && strlen(buffer) <= maximo) { strncpy(pResultado,buffer,maximo+1); retorno = 0; break; } printf("%s",pMensajeError); reintentos--; }while(reintentos >= 0); } return retorno; } int main(void) { char arrayNombres[QTY_NOMBRES][QTY_CHARS]; int arrayDni[QTY_NOMBRES]; int i; for(i=0;i<QTY_NOMBRES;i++){ getString (arrayNombres[i], "Ingrese un nombre", "Error", 0, 49, 2); getInt(&arrayDni[i], "Ingrese el dni", "Error", 0, 99999999, 2); } //insercionString(arrayNombres, QTY_NOMBRES); insercionStringInt(arrayNombres, QTY_NOMBRES, arrayDni ); imprimirArrayStringInt(arrayNombres, QTY_NOMBRES, arrayDni); return EXIT_SUCCESS; } int imprimirArrayStringInt(char array[][QTY_CHARS], int cantidad, int arrayInt[]){ int i; int retorno = -1; if(array!=NULL && arrayInt!=NULL && cantidad > 0){ retorno = 0; for(i=0;i<cantidad;i++){ printf("%s %d\n",array[i], arrayInt[i]); } } return retorno; } int imprimirArrayString(char array[][QTY_CHARS], int cantidad){ int i; int retorno = -1; if(array!=NULL && cantidad > 0){ retorno = 0; for(i=0;i<cantidad;i++){ printf("%s\n",array[i]); } } return retorno; } void insercionString(char array[][QTY_CHARS], int limite){ int i; int j; int flagOrdeno; char swap[QTY_CHARS]; for(i=1; i<limite; i++){ j=i; flagOrdeno = 1; while(flagOrdeno != 0 && j!=0){ flagOrdeno = 0; if(strcmp(array[j-1], array[j]) > 0){ strcpy(swap, array[j-1]); strcpy(array[j-1], array[j]); strcpy(array[j], swap); flagOrdeno = 1; } j--; } } } void insercionStringInt(char array[][QTY_CHARS], int limite, int arrayInt[]){ int i; int j; int flagOrdeno; char swap[QTY_CHARS]; int swapInt; for(i=1; i<limite; i++){ j=i; flagOrdeno = 1; while(flagOrdeno != 0 && j!=0){ flagOrdeno = 0; if(strncmp(array[j-1], array[j], QTY_CHARS) > 0){ strncpy(swap, array[j-1], QTY_CHARS); strncpy(array[j-1], array[j], QTY_CHARS); strncpy(array[j], swap, QTY_CHARS); swapInt = arrayInt[j-1]; arrayInt[j-1] = arrayInt[j]; arrayInt[j] = swapInt; flagOrdeno = 1; }else if(strncmp(array[j-1], array[j], QTY_CHARS)==0 && arrayInt[j-1] > arrayInt[j]){ strncpy(swap, array[j-1], QTY_CHARS); strncpy(array[j-1], array[j], QTY_CHARS); strncpy(array[j], swap, QTY_CHARS); swapInt = arrayInt[j-1]; arrayInt[j-1] = arrayInt[j]; arrayInt[j] = swapInt; flagOrdeno = 1; } j--; } } }
C
#include <stdio.h> #include <stdlib.h> int input(){ /* This function asks for the card name to be enetered and change the value of the card value depedning on the entry*/ char card_name[3]; { puts("Enter the card_name: "); scanf("%2s", card_name); int val = 0; switch(card_name[0]) { case 'K': case 'Q': case 'J': val = 10; break; case 'A': val = 11; break; case 'X': break; default: val = atoi(card_name);} return val; } } // int val_range(int value) { /* This function check is the card value is outside range 1-10 and if it is ,the fucntion returns a string */ if ((value < 1)||(value > 10)) { puts("I don't understand that value!"); } } int valtest(int value2,int cur_count){ /* function evalutes if card value meets 2 condition and updates the counter accordingly. It also prints the current counter*/ if ((value2 > 2) && (value2 < 7)) { cur_count++; } else if (value2 == 10) { cur_count --; } printf("Current count: %d\n",cur_count); return cur_count;} int main(){ int value2test = 0; int count = 1; while(value2test != -1) { value2test = input(); printf("%d\n",value2test ); val_range(value2test); count = valtest(value2test,count);} return 0; }
C
#include <stdio.h> #define BITS_PER_LONG 32 unsigned long __fls(unsigned long word) { int num = BITS_PER_LONG - 1; #if BITS_PER_LONG == 64 if (!(word & (~0ul << 32))) { num -= 32; word <<= 32; } #endif if (!(word & (~0ul << (BITS_PER_LONG-16)))) { num -= 16; word <<= 16; } if (!(word & (~0ul << (BITS_PER_LONG-8)))) { num -= 8; word <<= 8; } if (!(word & (~0ul << (BITS_PER_LONG-4)))) { num -= 4; word <<= 4; } if (!(word & (~0ul << (BITS_PER_LONG-2)))) { num -= 2; word <<= 2; } if (!(word & (~0ul << (BITS_PER_LONG-1)))) num -= 1; return num; } int main() { unsigned long item=0; item |= 1<<23; item |= 1<<11; printf("%lu\n", __fls(item)); return 0; }
C
//实验一 词法分析器 #include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> char *Key[8]={"begin","integer","function","if","then","else","read","write"}; //定义保留字(关键字) char ch; //新读入字符 char token[20]; //已读入字符 int letter(char c){ //判断字母的函数 if(((c>='a')&&(c<='z'))||((c>='A')&&(c<='Z'))) return 1; else return 0; } int digit(char c){ //判断数字的函数 if (c>='0'&&c<='9') return 1; else return 0; } int reserve(char *token){ //处理关键字(保留字)的函数 int i; for(i=0;i<8;i++){ if((strcmp(token,Key[i]))==0) return i; } return -1; } void LexAnalyze(FILE *fp){ char token[20]={'\0'}; char ch; int i,c; ch=fgetc(fp); //开始获取字符 if(letter(ch)){ //判断该字符是否是字母 token[0]=ch; ch=fgetc(fp); i=1; while(letter(ch)||digit(ch)){ //判断该字符是否是字母或者数字 token[i]=ch; i++; ch=fgetc(fp); } token[i]='\0'; fseek(fp,-1,1); c=reserve(token); //判断是否保留字(关键字) if(c==-1) printf("%s\t\t普通标识符\t$SYMBOL\n\n",token); else if(c==0) printf("%s\t\t关键字\t\t$BEGIN\n\n",token); else if(c==1) printf("%s\t\t关键字\t\t$INT\n\n",token); else if(c==2) printf("%s\t关键字\t\t$FUN\n\n",token); else if(c==3) printf("%s\t\t关键字\t\t$IF\n\n",token); else if(c==4) printf("%s\t\t关键字\t\t$THEN\n\n",token); else if(c==5) printf("%s\t\t关键字\t\t$ELSE\n\n",token); else if(c==6) printf("%s\t\t关键字\t\t$READ\n\n",token); else if(c==7) printf("%s\t\t关键字\t\t$WRITE\n\n",token); } else if(digit(ch)){ //判断是否为数字 token[0]=ch; ch=fgetc(fp); i=1; while(digit(ch)){ token[i]=ch; i++; ch=fgetc(fp); } token[i]='\0'; fseek(fp,-1,1); printf("%s\t\t常数\t\t$CONSTANT\n\n",token); } else{ token[0]=ch; switch(ch){ case '(': printf("%s\t\t界符\t\t$LPAR\n\n",token); break; case ')': printf("%s\t\t界符\t\t$RPAR\n\n",token); break; case ',': printf("%s\t\t界符\t\t$COM\n\n",token); break; case ';': printf("%s\t\t界符\t\t$SEM\n\n",token); break; case '+': printf("%s\t\t算数运算符\t$ADD\n\n",token); break; case '-': printf("%s\t\t算数运算符\t$SUB\n\n",token); break; case '*': printf("%s\t\t算数运算符\t$MUL\n\n",token); break; case '/': printf("%s\t\t算数运算符\t$DIV\n\n",token); break; case ':': ch=fgetc(fp); token[1]=ch; if(ch=='='){ printf("%s\t\t算数表达式\t$ASSIGN\n\n",token); } else{ fseek(fp,-1,1); printf("%s\t\t界符\t\t$COL\n\n",token); } break; case '<': ch=fgetc(fp); token[1]=ch; if(ch=='='){ printf("%s\t\t关系运算符\t$LE\n\n",token); } else{ fseek(fp,-1,1); printf("%s\t\t关系运算符\n\n",token); } break; case '>': ch=fgetc(fp); token[1]=ch; if(ch=='='){ printf("%s\t\t关系运算符\t\t$GE\n\n",token); } else{ fseek(fp,-1,1); printf("%s\t\t关系运算符\n\n",token); } break; default: printf("ERROR(未定义或无法识别)!\n\n"); break; } } } int main (void){ char in_fn[30]; FILE *fp; printf("请输入文件路径和名字:"); while(true){ gets(in_fn); if((fp=fopen(in_fn,"r"))!=NULL) break; else printf("文件路径错误!"); } printf("词法分析如下:\n\n"); printf("单词符号\t类别\t\t助记符\n\n"); while((ch=fgetc(fp))!=EOF){ if(ch==' '||ch=='\t'||ch=='\n'){} //跳过空格、制表符、换行符 else{ fseek(fp,-1,1); LexAnalyze(fp); } }; getchar(); return 0; }
C
#include "binlog.h" #include <stdio.h> #include <errno.h> #include <string.h> #include <unistd.h> #define LEN 1024 int readlog(void) { char buf[LEN]="BUF"; int ret=0; ret = binlog_read(buf,LEN,0); printf("ret=%d,err=%s\n",ret,strerror(errno)); if(ret>0) { buf[ret]=0; printf("buf=%s\n",buf); } return ret; } int main() { while(readlog()>=0) { } return 0; }
C
#include <assert.h> #include "account.h" int main() //@ requires true; //@ ensures true; { account_t* my_account = create_account(-100); account_deposit(my_account, 200); int w1 = account_withdraw(my_account, 50); assert(w1 == 50); int b1 = account_get_balance(my_account); assert(b1 == 150); int w2 = account_withdraw(my_account, 300); assert(w2 == 250); int b2 = account_get_balance(my_account); assert(b2 == -100); dispose_account(my_account); return 0; }
C
void printBlock(unsigned long long int *block) { for(int i = 0;i < 64;i ++){ printf("%lld",(*block>>i)&1ULL); if((i & 7) == 7) printf("\n"); } } void initialize(unsigned long long int *block, int row, int column, int size) { *block = 0; unsigned long long add = (1ULL << size) -1; for(int i = row;i < row+size;i ++) *block |= (unsigned long long)(add << (i*8+column)); return; } int moveLeft(unsigned long long int *block) { if(*block & 0X0101010101010101ULL) return 0; *block >>= 1; return 1; } int moveRight(unsigned long long int *block) { if(*block & 0X8080808080808080ULL) return 0; *block <<= 1; return 1; } int moveUp(unsigned long long int *block) { if(*block & 0X00000000000000FFULL) return 0; *block >>= 8; return 1; } int moveDown(unsigned long long int *block) { if(*block & 0XFF00000000000000ULL) return 0; *block <<= 8; return 1; }
C
#include <arpa/inet.h> #include <netinet/in.h> #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #define total_minions 3 //use this to define total no. of receiving minions int indicator =1; int number=0; int a[2048]; int arraylen=0; char buffer[2048]; int factor; int sum[200]; int final_sum=0; int h=0; int flag=0; void * clientThread(void *arg) { int newSocket = *((int *)arg); int i=0; printf("client has joined\n\n"); int recvlen; recvlen=recv(newSocket,buffer,sizeof(buffer),0); buffer[recvlen]='\0'; //printf("%d\n\n",recvlen); if(recvlen<0); { perror("error in recieving"); } int num=0; while(buffer[i]!='\0') { if(buffer[i]==',') { i++; a[arraylen]=num; arraylen++; num=0; } else { num=(num*10)+(buffer[i]-'0'); i++; } } //printf("\n%d\n\n",arraylen); //printf("%d %d %d %d %d %d\n\n",a[0],a[1],a[2],a[3],a[4],a[5]); } void * socketThread(void *arg) { int newSocket = *((int *)arg); printf("Entered into a new thread\n"); //printf("value of number is %d\n",number); int threadid; //creating threadid to allow sending of data threadid=number-1; //printf("the value of threadid is %d \n",threadid); //sleep(30); factor=arraylen/total_minions; //printf("\n the value of factor is %d \n",factor); int m; m=send(newSocket,&factor,sizeof(int),0); //sending value of factor to determine the size of recieved array by minions if(m<0) { perror("error in sending factor\n"); } int p; //printf("now sending data\n"); //printf("\n threadid %d and factor value is %d ",threadid,factor); for(p=threadid*factor;p<(threadid+1)*factor;p++) { //printf("\n packet sent \n"); int s; s=send(newSocket,&a[p],sizeof(int),0); //sending array elements one by one if(s<0) { perror("error in sending"); } } int f; f=recv(newSocket,&sum[threadid],sizeof(int),0); //receiving sum from the minions printf("\nthe sum recieved is %d\n",sum[threadid]); flag++; } int main(int argc,char *argv[]) { struct sockaddr_in serverAddr; int socketfd;//file descriptor for socket id if(argc<2)//if portno. is not provided as an argument then exit(-1) { fprintf(stderr,"use %s <port>\n",argv[0]); exit(-1); } int portno =atoi(argv[1]); //using atoi to read argument as an integer socketfd = socket(AF_INET,SOCK_STREAM,0); //using IPv4 connection and TCP protocol if(!socketfd) //socketfd returns 0 if any error in creating socket { perror("Error in opening socket"); exit(-1); } serverAddr.sin_family=AF_INET; serverAddr.sin_addr.s_addr=htonl(INADDR_ANY); //use this to specify IP of the server or use a local address for tranferring of data serverAddr.sin_port=htons(portno); if(bind(socketfd,(struct sockaddr *)&serverAddr,sizeof(serverAddr))<0) //binding of socketfd to the port { perror("failed to bind"); exit(4); } if(listen(socketfd,50)) //50 specifies the maximum no. of backlog connections { perror("error in listen "); exit(2); } int optval=1; setsockopt(socketfd,SOL_SOCKET,SO_REUSEADDR,(const void *)&optval,sizeof(int)); // unknown function struct sockaddr_in clientAddr; int cliLen=sizeof(clientAddr); pthread_t minions[30]; pthread_t client; cliLen= sizeof(clientAddr); int newSocket1=accept(socketfd,(struct sockaddr *)&clientAddr,&cliLen); //accept call returns a newsocket file descriptor if(newSocket1<0) { perror("Error in accept"); exit(6); } if( pthread_create(&client, NULL, clientThread, &newSocket1) != 0 ) printf("Failed to create thread\n"); pthread_join(client,NULL); printf("the array recieved is :\n"); int k; for(k=0;k<arraylen;k++) { printf("%d ",a[k]); } printf("\n"); //printf("%s \n",buffer); int i = 0; while(1) { cliLen= sizeof(clientAddr); int newSocket=accept(socketfd,(struct sockaddr *)&clientAddr,&cliLen); if(newSocket<0) { perror("Error in accept"); continue; } number++; if( pthread_create(&minions[i++], NULL, socketThread, &newSocket) != 0 ) //thread creation for minions printf("Failed to create thread\n"); //pthread_join(minions[i++],NULL); if(number==total_minions) { int v; for(v=0;v<number;v++) { pthread_join(minions[v],NULL); } } if(flag==total_minions) //final sending of the sum of numbers { int u,p; for(p=0;p<total_minions;p++) { final_sum=final_sum+sum[p]; } u=send(newSocket1,&final_sum,sizeof(int),0); //printf("package sent"); } } return 0; }
C
// Structure1.cpp : ܼ α׷ մϴ. // #include "stdafx.h" struct Student { // Student ̸ ڷ char name[10]; // ̸ char address[20]; // ּ int Year; // г }; int main() { int a = 10; Student s; // struct Student s; system("pause"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> typedef struct { //graphe représenté par une matrice d'adjacence int nombre_sommet; int ** matrice_adjacence; } graphe; void affiche_graphe(graphe G){ int i,j; printf("Graphe avec %d sommets \n",G.nombre_sommet); for(i = 0; i<G.nombre_sommet; i++){ printf("Voisins de %d: ",i); for(j = 0; j < G.nombre_sommet; j++){ //if(G.matrice_adjacence[i][j]) //printf("%d ",j); printf("%d ",G.matrice_adjacence[i][j]); } printf("\n"); } } void degre(graphe G, int i){ int nbre_sommet=0; for(int k = 0; k<G.nombre_sommet; k++){ if(G.matrice_adjacence[i][k]==1){ nbre_sommet = nbre_sommet +1; } //return nbre_sommet; } printf("son degre est : %d",nbre_sommet); //return nbre_sommet; } graphe init_graphe(int n){//créé un graphe dont tous les sommets sont isolés graphe G; G.nombre_sommet = n; G.matrice_adjacence=malloc(sizeof (*G.matrice_adjacence)*n); int i=0; for(i=0;i<n;i++) { G.matrice_adjacence[i]=malloc(sizeof(**G.matrice_adjacence)*n); } int j=0; for(i=0;i<n;i++) { for(j=0;j<n;j++) { G.matrice_adjacence[i][j]=0; } } return G; } graphe complet_graphe(int n){//créé un graphe complet graphe G; G.nombre_sommet = n; G.matrice_adjacence=malloc(sizeof (*G.matrice_adjacence)*n); int i=0; for(i=0;i<n;i++) { G.matrice_adjacence[i]=malloc(sizeof(**G.matrice_adjacence)*n); } int j=0; for(i=0;i<n;i++) { for(j=0;j<n;j++) { G.matrice_adjacence[i][j]=0; if(i!=j) { G.matrice_adjacence[i][j]=1; } } } return G; } graphe cycle_graphe(int n){//créé un cycle graphe G; G.nombre_sommet = n; G.matrice_adjacence=malloc(sizeof (*G.matrice_adjacence)*n); int i=0; for(i=0;i<n;i++) { G.matrice_adjacence[i]=malloc(sizeof(**G.matrice_adjacence)*n); } int j; for(j=0;j<n;j++) { if(j!=n-1) { G.matrice_adjacence[j][j+1]=1; } G.matrice_adjacence[n-1][0]=1; } return G; } void libere_graphe(graphe G){ for(int i=0; i<G.nombre_sommet; i++ ) { free(G.matrice_adjacence[i]); } free(G.matrice_adjacence); } graphe graphe_arbre(int *pere, int n){ graphe G; G.nombre_sommet = n; G.matrice_adjacence=malloc(sizeof (*G.matrice_adjacence)*n); int val=0; for(int i=0;i<n;i++) { G.matrice_adjacence[i]=malloc(sizeof(**G.matrice_adjacence)*n); } for(int k=0;k<G.nombre_sommet;k++) { if(pere[k]!=-1) { val=pere[k]; G.matrice_adjacence[val][k]=1; } } for(int l=0;l<G.nombre_sommet;l++) { for(int p=0; p<G.nombre_sommet;p++) { if(G.matrice_adjacence[l][p]!=1) { G.matrice_adjacence[l][p]=0; } } } return G; } int main(){ /* Tests pour vérifier si vos implémentations sont correctes*/ /*graphe g=init_graphe(4); affiche_graphe(g); printf("\n"); graphe H = complet_graphe(5); affiche_graphe(H); printf("\n"); degre(g, 2); printf("\n"); graphe H = cycle_graphe(5); affiche_graphe(H); libere_graphe(H);*/ int T[4]={-1,0,0,1}; graphe g=graphe_arbre(T,4); affiche_graphe(g); }
C
// 2.2堆栈 #include "stdio.h" #include "stdlib.h" //堆栈的链表实现 typedef int ElemType; typedef struct Snode *PtrlToSNode; struct Snode { ElemType data; PtrlToSNode next; }; typedef PtrlToSNode Stack; Stack createStack(){ Stack s; s=(PtrlToSNode)malloc(sizeof(Snode)); s->next=NULL; return s; } //判空 bool Empty(Stack S){ return (S->next==NULL); } //push方法 bool push(Stack S,ElemType x){ PtrlToSNode tmp; tmp=(PtrlToSNode)malloc(sizeof(Snode)); tmp->data=x; tmp->next=S->next; S->next=tmp; return true; } //pop方法 ElemType pop(Stack S){ PtrlToSNode tmp=S->next; if (Empty(S)) { return NULL; }else{ S->next=tmp->next; ElemType returndata=tmp->data; free(tmp); return returndata; } } int main(int argc, char const *argv[]) { Stack s; s=createStack(); push(s,2); push(s,3); int result1=pop(s); int result2=pop(s); printf("%d %d\n",result1,result2 ); } //改文件的可执行文件为stack
C
/* * Disk testing utility. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #define BLOCKSZ 1024 char *progname; int verbose; int fd; void block_write (unsigned bn, unsigned char *data) { unsigned addr = bn * BLOCKSZ; int ret, i; if (verbose) { printf ("Write block to address %06X.\n", addr); printf (" %02x", data[0]); for (i=1; i<BLOCKSZ; i++) printf ("-%02x", data[i]); printf ("\n"); } ret = lseek (fd, addr, 0); if (ret != addr) { printf ("Seek error at %06X: result %06X, expected %06X.\n", addr, ret, addr); exit (-1); } ret = write (fd, data, BLOCKSZ); if (ret != BLOCKSZ) { printf ("Write error at %06X: %s\n", addr, strerror(ret)); exit (-1); } } void block_read (unsigned bn, unsigned char *data) { unsigned addr = bn * BLOCKSZ; int ret, i; if (verbose) printf ("Read block from address %06X.\n", addr); ret = lseek (fd, addr, 0); if (ret != addr) { printf ("Seek error: result %06X, expected %06X.\n", ret, addr); exit (-1); } ret = read (fd, data, BLOCKSZ); if (ret != BLOCKSZ) { printf ("Read error at %06X: %s\n", addr, strerror(ret)); exit (-1); } if (verbose) { printf (" %02x", data[0]); for (i=1; i<BLOCKSZ; i++) printf ("-%02x", data[i]); printf ("\n"); } } /* * Fill an array with pattern data. * When alt=~0, use counter starting from given value. * Otherwise, use pattern-alt-pattern-alt ans so on. */ void data_fill (unsigned char *data, unsigned pattern, unsigned alt) { int i; for (i=0; i<BLOCKSZ; ++i) { if (alt == ~0) data[i] = pattern++; else data[i] = (i & 1) ? alt : pattern; } } void data_check (unsigned char *data, unsigned char *rdata) { int i; for (i=0; i<BLOCKSZ; ++i) { if (rdata[i] != data[i]) printf ("Data error: offset %d written %02X read %02X.\n", i, data[i], rdata[i]); } } void test_alternate (unsigned blocknum) { unsigned char data [BLOCKSZ]; unsigned char rdata [BLOCKSZ]; printf ("Testing block %u at address %06X.\n", blocknum, blocknum * BLOCKSZ); data_fill (data, 0x55, 0xAA); block_write (blocknum, data); block_read (blocknum, rdata); data_check (data, rdata); data_fill (data, 0xAA, 0x55); block_write (blocknum, data); block_read (blocknum, rdata); data_check (data, rdata); printf ("Done.\n"); } void test_counter (unsigned blocknum) { unsigned char data [BLOCKSZ]; unsigned char rdata [BLOCKSZ]; printf ("Testing block %u at address %06X.\n", blocknum, blocknum * BLOCKSZ); data_fill (data, 0, ~0); block_write (blocknum, data); block_read (blocknum, rdata); data_check (data, rdata); printf ("Done.\n"); } void test_blocks (unsigned blocknum) { unsigned char data [BLOCKSZ]; unsigned char rdata [BLOCKSZ]; unsigned bn; int i; /* Pass 1: write data. */ for (i=0; ; i++) { /* Use block numbers 0, 1, 2, 4, 8, 16... blocknum (inclusive). */ if (i == 0) bn = 0; else bn = 1 << (i - 1); if (bn > blocknum) bn = blocknum; printf ("Writing block %u at address %06X.\n", bn, bn * BLOCKSZ); /* Use counter pattern, different for every next block. */ data_fill (data, i, ~0); block_write (bn, data); if (bn == blocknum) break; } /* Pass 2: read and check. */ for (i=0; ; i++) { /* Use block numbers 0, 1, 2, 4, 8, 16... blocknum (inclusive). */ if (i == 0) bn = 0; else bn = 1 << (i - 1); if (bn > blocknum) bn = blocknum; printf ("Reading block %u at address %06X.\n", bn, bn * BLOCKSZ); /* Use counter pattern, different for every next block. */ data_fill (data, i, ~0); block_read (bn, rdata); data_check (data, rdata); if (bn == blocknum) break; } printf ("Done.\n"); } void fill_blocks (unsigned blocknum, unsigned char pattern) { unsigned char data [BLOCKSZ]; unsigned char rdata [BLOCKSZ]; unsigned bn; printf ("Testing blocks 0-%u with byte value %02X.\n", blocknum, pattern); for (bn=0; bn<=blocknum; bn++) { /* Use counter pattern, different for every next block. */ data_fill (data, pattern, pattern); block_write (bn, data); block_read (bn, rdata); data_check (data, rdata); if (bn == blocknum) break; } printf ("Done.\n"); } void usage () { fprintf (stderr, "Disk testing utility.\n"); fprintf (stderr, "Usage:\n"); fprintf (stderr, " %s [options] device [blocknum]\n", progname); fprintf (stderr, "Options:\n"); fprintf (stderr, " -a -- test a block with alternate pattern 55/AA\n"); fprintf (stderr, " -c -- test a block with counter pattern 0-1-2...FF\n"); fprintf (stderr, " -b -- test blocks 0-1-2-4-8...blocknum\n"); fprintf (stderr, " -f pattern -- fill blocks 0...blocknum with given byte value\n"); fprintf (stderr, " -v -- verbose mode\n"); exit (-1); } int main (int argc, char **argv) { int aflag = 0, bflag = 0, cflag = 0, fflag = 0; unsigned blocknum = 0, pattern = 0; progname = *argv; for (;;) { switch (getopt (argc, argv, "abcf:v")) { case EOF: break; case 'a': aflag = 1; continue; case 'c': cflag = 1; continue; case 'b': bflag = 1; continue; case 'f': fflag = 1; pattern = strtoul (optarg, 0, 0); continue; case 'v': verbose = 1; continue; default: usage (); } break; } argc -= optind; argv += optind; if (argc < 1 || argc > 2 || aflag + bflag + cflag + fflag == 0) usage (); fd = open (argv[0], O_RDWR); if (fd < 0) { perror (argv[0]); return -1; } if (argc > 1) blocknum = strtoul (argv[1], 0, 0); if (aflag) test_alternate (blocknum); if (cflag) test_counter (blocknum); if (bflag) test_blocks (blocknum); if (fflag) fill_blocks (blocknum, pattern); return 0; }
C
#include "block.h" int main(int argc, char ** argv) { if (stdout_is_piped()) // other wise you don't see the seg fault setup_segfault_handling(argv); assert_stdin_is_piped(); assert_stdout_is_piped(); //assert_stdin_or_out_is_piped(); static char column_name[1000] = ""; static int sort_that_column = 0; static int debug = 0; static int reverse = 0; int c; while (1) { static struct option long_options[] = { {"column", required_argument, 0, 'c'}, {"sort", no_argument, 0, 's'}, {"reverse", no_argument, 0, 'r'}, {"debug", no_argument, &debug, 1}, {0, 0, 0, 0} }; int option_index = 0; c = getopt_long(argc, argv, "c:sr", long_options, &option_index); if (c == -1) break; switch (c) { case 0: break; case 'c': strncpy(column_name, optarg, sizeof(column_name)); break; case 's': sort_that_column = 1; break; case 'r': reverse = 1; break; default: abort(); } } struct Block * block = NULL; while ((block = read_block(stdin))) { int column_id = get_column_id_by_name_or_exit(block, column_name); struct Column * column = get_column(block, column_id); struct Block * newblock = new_block(); newblock = copy_all_attributes(newblock, block); newblock = copy_all_columns(newblock, block); newblock = add_command(newblock, argc, argv); int i; for (i = 0 ; i < block->num_rows ; i++) { void * cell = get_cell(block, i, column_id); int j; for (j = 0 ; j < newblock->num_rows ; j++) { if (memcmp(cell, get_cell(newblock, j, column_id), column->bsize)==0) { // found break; } } if (j == newblock->num_rows) // not found { newblock = add_row(newblock); memcpy(get_row(newblock, newblock->num_rows-1), get_row(block, i), block->row_bsize); } } if (sort_that_column == 1 && column->type == TYPE_INT) newblock = sort_block_using_int32_column(newblock, column_id, reverse); write_block(stdout, newblock); free_block(newblock); free_block(block); } }
C
const double EPSI = 1E-8; double sqr(double x) { return x * x; } int sgn(double x) { if (x > EPSI) return 1; if (x < -EPSI) return -1; return 0; } struct Point { double x, y; Point() { } Point(double _x, double _y) : x(_x), y(_y) { } void read() { scanf("%lf%lf", &x, &y); } Point operator +(Point p) const { return Point(x+p.x, y+p.y); } Point operator -(Point p) const { return Point(x-p.x, y-p.y); } Point operator *(double c) const { return Point(x*c, y*c); } Point operator /(double c) const { return Point(x/c, y/c); } bool operator ==(Point p) const { return sgn(x-p.x) == 0 && sgn(y-p.y) == 0; } bool operator <(const Point &p) const { return sgn(x-p.x) < 0 || (sgn(x-p.x) == 0 && sgn(y-p.y) < 0); } }; struct Line { double a, b, c; Line() { } Line(double _a, double _b, double _c) : a(_a), b(_b), c(_c) { } }; // Point -> Line | Line -> Point void points_make_line(Point w, Point z, Line *line) { line->a = z.y - w.y; line->b = w.x - z.x; line->c = -(line->a * w.x + line->b * w.y); } bool lines_make_point(Line w, Line z, Point *point) { double tmp = (w.a * z.b - w.b * z.a); if (sgn(tmp) == 0) return false; point->x = (w.b * z.c - w.c * z.b) / tmp; point->y = (w.c * z.a - w.a * z.c) / tmp; return true; } // Calculate the distance between two points double sqr_dist(Point a, Point b) { return sqr(a.x-b.x) + sqr(a.y-b.y); } double dist(Point a, Point b) { return sqrt(sqr(a.x-b.x) + sqr(a.y-b.y)); } // Calculate the det/dot of two vector double mult(Point a, Point b) { return a.x*b.y - a.y*b.x; } double mult(Point z, Point a, Point b) { return mult(a-z, b-z); } double dot(Point a, Point b) { return a.x*b.x + a.y*b.y; } double dot(Point z, Point a, Point b) { return dot(a-z, b-z); } // Rotate a vector Point rotate(Point p, double sinA, double cosA) { return Point(p.x*cosA - p.y*sinA, p.x*sinA + p.y*cosA); } Point rotate(Point p, double angle) { return rotate(p, sin(angle), cos(angle)); }
C
// Snipe event handling. Free and open source. See licence.txt. // TODO: detect shift-click for select, ctrl-click for add cursor // TODO: touch scroll #include "settings.h" // Event code constants represent keyboard, mouse, window and timer events. // These constants are intended to be independent of the graphics library, and // suitable for user-defined key maps. // The prefixes S_ C_ and SC_ represent Shift, Control or both. On macOS, Cmd is // treated the same as Control. Combinations using Alt are not included, because // they are likely to be bound to system-wide operations. // CLICK and DRAG are mouse button down and up events. They are accompanied by // pixel coordinates, later converted into document row/column coordinates by // the display module. Every CLICK is followed by a DRAG, whether the mouse has // been moved or not - a DRAG event can be discarded later if the row/column // position is the same as the CLICK. // SCROLL events are generated by a mouse scroll wheel, or equivalent touchpad // gesture, accompanied by a scroll amount. A TEXT event is accompanied by a // character, possibly generated by a platform's Unicode input method. The codes // after TEXT are window or timer events. // In combinations with CTRL plus a text character, shift can be problematic, so // is ignored. For C_PLUS, technically you should hold CTRL and SHIFT. For // convenience on the majority of keyboards where + is above = the combination // CTRL and = is interpreted as C_PLUS, and so is CTRL and keypad plus. CTRL and // underscore, and CTRL and keypad minus, are interpreted as C_MINUS. enum event { CLICK, S_CLICK, C_CLICK, SC_CLICK, DRAG, S_DRAG, C_DRAG, SC_DRAG, SCROLL, S_SCROLL, C_SCROLL, SC_SCROLL, ESCAPE, S_ESCAPE, C_ESCAPE, SC_ESCAPE, ENTER, S_ENTER, C_ENTER, SC_ENTER, TAB, S_TAB, C_TAB, SC_TAB, BACKSPACE, S_BACKSPACE, C_BACKSPACE, SC_BACKSPACE, INSERT, S_INSERT, C_INSERT, SC_INSERT, DELETE, S_DELETE, C_DELETE, SC_DELETE, RIGHT, S_RIGHT, C_RIGHT, SC_RIGHT, LEFT, S_LEFT, C_LEFT, SC_LEFT, DOWN, S_DOWN, C_DOWN, SC_DOWN, UP, S_UP, C_UP, SC_UP, PAGE_UP, S_PAGE_UP, C_PAGE_UP, SC_PAGE_UP, PAGE_DOWN, S_PAGE_DOWN, C_PAGE_DOWN, SC_PAGE_DOWN, HOME, S_HOME, C_HOME, SC_HOME, END, S_END, C_END, SC_END, F1, S_F1, C_F1, SC_F1, F2, S_F2, C_F2, SC_F2, F3, S_F3, C_F3, SC_F3, F4, S_F4, C_F4, SC_F4, F5, S_F5, C_F5, SC_F5, F6, S_F6, C_F6, SC_F6, F7, S_F7, C_F7, SC_F7, F8, S_F8, C_F8, SC_F8, F9, S_F9, C_F9, SC_F9, F10, S_F10, C_F10, SC_F10, F11, S_F11, C_F11, SC_F11, F12, S_F12, C_F12, SC_F12, MENU, S_MENU, C_MENU, SC_MENU, C_A, C_B, C_C, C_D, C_E, C_F, C_G, C_H, C_I, C_J, C_K, C_L, C_M, C_N, C_O, C_P, C_Q, C_R, C_S, C_T, C_U, C_V, C_W, C_X, C_Y, C_Z, C_0, C_1, C_2, C_3, C_4, C_5, C_6, C_7, C_8, C_9, C_SPACE, C_PLUS, C_MINUS, TEXT, PASTE, RESIZE, FOCUS, DEFOCUS, FRAME, LOAD, BLINK, SAVE, QUIT, IGNORE }; typedef enum event event; // Get the name of an event constant as a string (including combinations). const char *findEventName(event e); // Find an event from its name (including S_ or C_ or SC_ prefix). event findEvent(char *name); // Print out an event with a given terminating string, e.g. for testing. void printEvent(event e, int r, int c, char const *t, char *end);
C
/* Assignment name : ft_strdup Expected files : ft_strdup.c Allowed functions: malloc -------------------------------------------------------------------------------- Reproduce the behavior of the function strdup (man strdup). Your function must be declared as follows: char *ft_strdup(char *src); */ #include <stdio.h> // #include <string.h> #include <stdlib.h> char *ft_strdup(char *src){ char *result; int i=0; int len = 0; while(src[len] != '\0'){ len++; } result = (char *)malloc(sizeof(*result) * (len +1)); while(i<len){ result[i] = src[i]; i++; } return result; } int main(){ char *str = "My String."; printf("%s", ft_strdup(str)); // printf("%s", strdup(str)); return 0; }
C
/* Ken Sheedlo * Simple circularly linked list implementation */ #include "tuple.h" #include "error_handling.h" struct _ll_t; /*Forward declaration*/ typedef struct _ll_node { void *data; struct _ll_t *list; struct _ll_node *next; struct _ll_node *prev; } node_t; typedef struct _ll_t { node_t *head; size_t length; } list_t; void list_init(list_t *list); void list_addfirst(list_t *list, void *data); void list_addlast(list_t *list, void *data); void list_insertbefore(node_t *node, void *data); void list_insertafter(node_t *node, void *data); void *list_remove(node_t *node); void list_clear(list_t *list, int32_t free_data); int32_t list_match(list_t *lst0, node_t *s0, list_t *lst1, node_t *s1, int32_t (*eq)(const void *, const void *), int32_t count); void list_print(FILE *output, list_t *lst, void (*disp)(FILE *, const void *)); void list_map(list_t *rop, list_t *op, void *(*map)(const void *)); void list_filter(list_t *rop, list_t *op, int32_t (*filt)(const void *)); void *list_reduce(list_t *op, void *(*rfunc)(const void *, const void *), void *start); void list_zip(list_t *rop, list_t *op1, list_t *op2); void list_zipwith(list_t *rop, list_t *op1, list_t *op2, void *(*zip)(const void *, const void *));
C
#include "uchat.h" char *my_itoa(long long number) { char *str = (char *)malloc(21); int count = 0; unsigned long long num; int flag = 0; if(number & 0x8000000000000000) { flag = 1; str[count++] = '-'; num = (number ^ 0xFFFFFFFFFFFFFFFF) + 1; } else num = (unsigned long long) number; if(num == 0) str[count++] = '0'; for(; num != 0; num /= 10) str[count++] = ((num % 10) + '0'); for(int i = 0; (i + flag) < (count + flag) / 2; ++i) { char temp = str[i + flag]; str[i + flag] = str[count - i - 1]; str[count - i - 1] = temp; } str[count] = '\0'; return str; } char *mx_strnew(const int size) { if(size >= 0) { char *strnew = (char *) malloc(size + 1); if(NULL == strnew) return NULL; for(int i = 0; i <= size; ++i) { strnew[i] = '\0'; } return strnew; } return NULL; } char *mx_strdup(const char *str) { char *strcopy = mx_strnew(strlen(str)); return mx_strcpy(strcopy, str); } char *mx_strcpy(char *dst, const char *src) { char *dst_return = dst; while (*src) { *dst = *src; dst++; src++; } *dst = '\0'; return dst_return; } void mx_free(void **ptr) { if (ptr && *ptr) { free(*ptr); *ptr = NULL; } }
C
#include "holberton.h" /** *_memcpy - Copy characters for one array and paste in other, *@dest:Is the array where are going to be paste the characters. *@src:Is the array from is going to be copied, *@n:Mount of characters that are going to be copied. *Return:The array dest. */ char *_memcpy(char *dest, char *src, unsigned int n) { unsigned int ctr; for (ctr = 0; ctr < n; ctr++) { *(dest + ctr) = *(src + ctr); } return (dest); }
C
#include "rpnStack.h" #include "Stack.h" #include "TokenType.h" void initrpnStack(rpnstack* st) { init(&(st->data)); init(&(st->type)); } void rpnpush(int data, etype e, rpnstack* st) { push(data, &(st->data)); push((int)e, &(st->type)); } rpndata rpnpop(rpnstack* st) { rpndata rv; rv.data = pop(&(st->data)); rv.type = (etype)pop(&(st->type)); return rv; }
C
// Copyright (c) 2020, devgo.club // All rights reserved. #include <stdlib.h> #include <unistd.h> #include <stdio.h> #include <stdint.h> #include <errno.h> #include <string.h> #include <pthread.h> void th_cleanup_func(void *arg) { char *msg = (char *)arg; printf("[%ld] cleanup: msg = %s\n", pthread_self(), msg); return; } void *th_start_func(void *arg) { int *code = (int *)arg; printf("[%ld] th_start_func: *code = %d >\n", pthread_self(), *code); pthread_cleanup_push(&th_cleanup_func, "Hello, C!"); pthread_cleanup_push(&th_cleanup_func, "Hello, Linux!"); printf("[%ld] th_start_func: *code = %d >>>\n", pthread_self(), *code); pthread_cleanup_pop(*code); pthread_cleanup_pop(*code); return NULL; } int main(int argc, char const *argv[]) { pthread_t th_id1; int *arg1 = malloc(sizeof(int)); *arg1 = 0; pthread_t th_id2; int *arg2 = malloc(sizeof(int)); *arg2 = 1; pthread_create(&th_id1, NULL, &th_start_func, (void *)arg1); pthread_create(&th_id2, NULL, &th_start_func, (void *)arg2); int *ret1 = NULL; int *ret2 = NULL; pthread_join(th_id1, (void **)&ret1); pthread_join(th_id2, (void **)&ret2); return EXIT_SUCCESS; }
C
#include <stdio.h> void split_time ( long int tot_sec, int *h, int *m, int *s ); int main(void){ int h,m,s,tot_sec; scanf("%d", &tot_sec); split_time(tot_sec, &h, &m, &s); printf("%d sono %d h %d m %d s\n", tot_sec,h,m,s); } void split_time ( long int tot_sec, int *h, int *m, int *s ){ *h = tot_sec/3600; *m = (tot_sec-(*h * 3600))/60; *s = tot_sec-(*h * 3600) -(*m * 60); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rroland <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/11/22 15:18:11 by rroland #+# #+# */ /* Updated: 2020/12/06 15:01:11 by rroland ### ########.fr */ /* */ /* ************************************************************************** */ #include "get_next_line.h" #include <stdio.h> char *recording(char *buff) { int i; i = 0; while (buff[i] != 0) { if (buff[i] == '\n') { buff[i] = '\0'; return (ft_strdup(&buff[i + 1])); } i++; } return (0); } int read_in(int fd, char **rec, char **line) { int num; char *tmp; char *buff; num = 1; if (!(buff = (char *)malloc(BUFFER_SIZE + 1))) return (-1); while (num > 0) { num = read(fd, buff, BUFFER_SIZE); buff[num] = 0; *rec = recording(buff); tmp = *line; *line = ft_strjoin(*line, buff); if (tmp) free(tmp); if (*rec) break ; } free(buff); return (num); } int k(char *str, int num) { if (num == 0 && str == 0) return (0); if (num != 0 && str == 0) return (-1); return (1); } int get_next_line(int fd, char **line) { static char *str; int num; char *rec; if (fd < 0 || line == 0 || BUFFER_SIZE < 1 || (num = read(fd, &num, 0) == -1)) return (-1); *line = 0; rec = 0; if (str) { rec = recording(str); *line = ft_strjoin(*line, str); free(str); str = ft_strdup(rec); free(rec); if (str) return (1); } num = read_in(fd, &rec, line); str = ft_strdup(rec); free(rec); return (k(str, num)); } int main() { char *line; int fd; fd = open("readme.txt", O_RDONLY); while(get_next_line(fd, &line) == 1) printf("%s\n", line); return (0); }
C
int main(void) { int a[100],n; cin >>n; for (int i=0;i<=n-1;i++) { cin >>a[i]; } for (int i=n-1;i>=0;i--) { cout <<a[i]; if (i!=0) cout <<" "; } return 0; }
C
#include<stdio.h> int main(){ int n, rev=0,remainder; printf("Enter an integer:"); scanf("%d",&n); while(n!=0){ remainder = n%10; rev = rev*10+remainder; n=n/10; } printf("Reverse of a number=%d",rev); return 0; }
C
/* ** diff_way.c for main in /home/blanch_p/rendu/Semestre2/Infographie/ ** ** Made by Alexandre Blanchard ** Login <[email protected]> ** ** Started on Wed Apr 13 14:06:34 2016 Alexandre Blanchard ** Last update Sun Apr 17 22:32:26 2016 Alexandre Blanchard */ #include "adventure.h" int check_first(int dep, t_node **nod, int i, int j) { if ((nod[i]->way[j] == nod[dep]->way[0] || nod[i]->way[j] == nod[dep]->way[1] || nod[i]->way[j] == nod[dep]->way[2]) && nod[i]->way[j] > -1) return (1); return (0); } int check_second(int arr, t_node **nod, int i, int j) { if ((nod[i]->way[j] == nod[arr]->way[0] || nod[i]->way[j] == nod[arr]->way[1] || nod[i]->way[j] == nod[arr]->way[2]) && nod[i]->way[j] > -1) return (1); return (0); } int find_node_inter(int dep, int arr, t_node **nod) { int i; int j; int first; int sec; int max; i = -1; max = 0; while (nod[++i] != NULL) { j = 0; first = 0; sec = 0; while (j < 3) { if (check_first(dep, nod, i, j) == 1) first = 1; if (check_second(arr, nod, i, j) == 1) sec = 1; j++; } if (sec == 1 && first == 1 && nod[max]->pos_way <= nod[i]->pos_way) max = i; } return (max); } int find_way_inter(int dep, int arr, t_node **nod) { int i; int j; int first; int sec; int max; i = -1; max = 0; while (nod[++i] != NULL) { j = 0; first = 0; sec = 0; while (j < 3) { if (check_first(dep, nod, i, j) == 1) first = 1; if (check_second(arr, nod, i, j) == 1) sec = 1; j++; } if (sec == 1 && first == 1 && nod[max]->pos_way <= nod[i]->pos_way) max = i; } return (max); } int find_diff_way(int dep, int arr, t_node **nod) { int inter; inter = find_node_inter(dep, arr, nod); return (inter); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: temehenn <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/11/14 08:49:06 by temehenn #+# #+# */ /* Updated: 2018/11/14 09:51:16 by temehenn ### ########.fr */ /* */ /* ************************************************************************** */ #include "get_next_line.h" static int check_str(char **rest, char **line, int ret) { char *end; size_t size; if ((end = ft_strchr(*rest, '\n'))) { size = ft_strlen(end + 1); *line = *rest; *end = '\0'; if (size) { if (!(*rest = ft_strsub(end + 1, 0, size))) return (-1); } else *rest = NULL; return (1); } else if (*rest && !ret) { *line = *rest; *rest = NULL; return (1); } return (0); } int get_next_line(int fd, char **line) { char buff[BUFF_SIZE + 1]; int ret; static char *rest = NULL; int check; char *tmp; if (fd < 0 || !line) return (-1); while ((ret = read(fd, buff, BUFF_SIZE)) > 0) { buff[ret] = '\0'; tmp = rest; if (!(rest = ft_strjoin(rest, buff))) return (-1); free(tmp); if ((check = check_str(&rest, line, ret)) == 1) return (1); else if (check == -1) return (-1); } if (ret == -1) return (-1); if (rest) return (check_str(&rest, line, ret)); return (0); }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> int main() { int n, i,r, min_elem_ind = 0, max_elem_ind = 0 ; printf("Enter the length of massive\n"); scanf("%d", &n); int a[n]; for (i = 0; i<n; i++){ scanf("%d", &a[i]); } for (i = 0; i<n; i++){ printf("%d ", a[i]); } for (i = 0; i<n; i++){ if (a[i] > a[max_elem_ind]) { max_elem_ind = i; } } for (i = 0; i<n; i++){ if (a[i] < min_elem_ind) { min_elem_ind = i; } } r = a[min_elem_ind]; a[min_elem_ind] = a[max_elem_ind]; a[max_elem_ind] = r; //printf("Best approximate value is: %d\n", approx_elem); printf("\n"); for (i = 0; i<n; i++){ printf("%d ", a[i]); } return 0; }
C
#include <stdio.h> #include <math.h> #include "cs50.h" int main(void) { float change; int coin = 0, converted; //user's input do { printf("How much change do you have?\n"); change = GetFloat(); } while (change < 0); //convertation into cents change *= 100.0; converted = (int) round(change); //quarters loop while (converted >= 25) { coin++; converted -= 25; } //dimes loop while (converted >= 10) { coin++; converted -= 10; } //nickels loop while (converted >= 5) { coin++; converted -= 5; } //pennies loop while (converted >= 1) { coin++; converted -= 1; } //output if (coin == 1) { printf("You've got 1 coin\n"); } else printf("You've got %i coins\n", coin); }
C
#include <stdio.h> #include <stdlib.h> #include <libgen.h> #include <dirent.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <ctype.h> #include <locale.h> #include <wchar.h> #include <wctype.h> #include <x86_64-linux-gnu/sys/types.h> #include <x86_64-linux-gnu/sys/stat.h> #include <x86_64-linux-gnu/sys/wait.h> #define ARGS_COUNT 3 #define BUFFER_SIZE (16 * 1024) typedef struct { int bytes_amount; int words_amount; } file_content; char *prog_name; int max_working_processes_amount; int working_processes_amount; void print_error(char *prog_name, char *error_message, char *error_file) { fprintf(stderr, "%s: %s %s\n", prog_name, error_message, error_file ? error_file : ""); } void print_results(int pid, char *full_path, int bytes_amount, int words_amount) { printf("%d %s %d %d\n", pid, full_path, bytes_amount, words_amount); } void process_data_in_buffer(int *is_word, const char *current_char, ssize_t bytes_read, int *words_amount) { ssize_t byte_size; int is_error = 0; wchar_t wide_char = 0; mbstate_t state = {}; do { byte_size = (ssize_t)mbrtowc(&wide_char, current_char, (size_t)bytes_read, &state); if (byte_size == (size_t) - 2) is_error = 1; else if (byte_size == (size_t) - 1) { current_char++; bytes_read--; } else if (bytes_read > 0) { if (byte_size == 0) { wide_char = 0; byte_size = 1; } current_char += byte_size; bytes_read -= byte_size; if (*is_word) { if (iswspace((wint_t)wide_char) || (wide_char == L' ')) *is_word = 0; } else if (iswprint((wint_t)wide_char) && (wide_char != L' ')) { *words_amount += 1; *is_word = 1; } } } while (!is_error && (bytes_read > 0)); } file_content *get_words_amount(char *file_name, int size) { ssize_t bytes_read; char buf[BUFFER_SIZE]; int words_amount = 0; file_content *content = malloc(sizeof(file_content)); content->words_amount = 0; content->bytes_amount = 0; int f = open(file_name, O_RDONLY); if (f == -1) { print_error(prog_name, strerror(errno), file_name); return NULL; } int is_data_readed; int is_word = 0; do { bytes_read = read(f, buf, BUFFER_SIZE); is_data_readed = bytes_read > 0; if (is_data_readed) { content->bytes_amount += (int)bytes_read; process_data_in_buffer(&is_word, buf, bytes_read, &words_amount); } } while (is_data_readed); content->words_amount = words_amount; if (close(f) == -1) { print_error(prog_name, "Error closing file ", file_name); return NULL; } return content; } void count_files_words(char *dir_name) { DIR *directory = opendir(dir_name); if (!directory) { print_error(prog_name, strerror(errno), dir_name); return; } struct dirent *dir_entry; errno = 0; while ((dir_entry = readdir(directory)) != NULL) { struct stat file_info; char *file_name = (char *)malloc((strlen(dir_entry->d_name) + 1) * sizeof(char)); strcpy(file_name, dir_entry->d_name); char *full_path = malloc((strlen(dir_name) + strlen(file_name) + 2) * sizeof(char)); if (strcmp(file_name, ".") == 0 || strcmp(file_name, "..") == 0) continue; strcpy(full_path, dir_name); strcat(full_path, "/"); strcat(full_path, file_name); if (lstat(full_path, &file_info) == -1) { print_error(prog_name, strerror(errno), file_name); continue; } if (S_ISDIR(file_info.st_mode)) { count_files_words(full_path); } else if (S_ISREG(file_info.st_mode)) { if (working_processes_amount >= max_working_processes_amount) { wait(NULL); working_processes_amount -= 1; } pid_t pid = fork(); if (pid == 0) { if (get_words_amount(full_path, (int)file_info.st_size)!= NULL) print_results(getpid(), full_path, get_words_amount(full_path, (int)file_info.st_size)->bytes_amount, get_words_amount(full_path, (int)file_info.st_size)->words_amount); exit(0); } else if (pid < 0) { print_error(prog_name, "Error creating process", NULL); exit(1); } working_processes_amount += 1; } } if (errno) { print_error(prog_name, strerror(errno), dir_name); } if (closedir(directory) == -1) { print_error(prog_name, strerror(errno), dir_name); } } int main(int argc, char *argv[]) { setlocale(LC_ALL, ""); prog_name = basename(argv[0]); max_working_processes_amount = atoi(argv[2]); if (argc != ARGS_COUNT) { print_error(prog_name, "Wrong args amount", NULL); return 1; } if (max_working_processes_amount == 0 || max_working_processes_amount == 1) { print_error(prog_name, "Incorrect second arg value", NULL); return 1; } char *dir_name = realpath(argv[1], NULL); if (dir_name == NULL) { print_error(prog_name, strerror(errno), argv[1]); return 1; } working_processes_amount = 1; count_files_words(dir_name); while (wait(NULL) > 0) {} return 0; }
C
/* * idshow.c * * Created on: May 16, 2021 * Author: cory */ #include "../lib/9_hdr.h" #include <unistd.h> #include <sys/fsuid.h> #include <limits.h> #include "8_hdr.h" #include "tlpi_hdr.h" #define SG_SIZE (NGROUPS_MAX + 1) #define DISPLAY_USERNAME(user) user == NULL ? "???" : user #define DISPLAY_GROUPNAME(group) DISPLAY_USERNAME(group) void __id_show() { uid_t ruid, euid, suid, fsuid; gid_t rgid, egid, sgid, fsgid; gid_t suppGroups[SG_SIZE]; int numGroups, j; char *p; if(getresuid(&ruid, &euid, &suid) == -1) errExit("getresuid"); if(getresgid(&rgid, &egid, &sgid) == -1) errExit("getresgid"); /* Attemps to thcnage the file-system IDs are always ignored * for unpriviledged processes, but even so, the following * calls return the current file-system IDs */ fsuid = setfsuid(0); fsgid = setfsgid(0); printf("UID: "); p = userNameFromId(ruid); printf("real=%s (%ld); ", DISPLAY_USERNAME(p), (long)ruid); p = userNameFromId(euid); printf("effective=%s (%ld); ", DISPLAY_USERNAME(p), (long)ruid); p = userNameFromId(suid); printf("stored=%s (%ld); ", DISPLAY_USERNAME(p), (long)suid); p = userNameFromId(fsuid); printf("fs=%s (%ld); ", DISPLAY_USERNAME(p), (long)suid); printf("\n"); printf("GID: "); p = groupNameFromid(rgid); printf("real=%s (%ld); ", DISPLAY_GROUPNAME(p), (long)rgid); p = groupNameFromid(egid); printf("effective=%s (%ld); ", DISPLAY_GROUPNAME(p), (long)egid); p = groupNameFromid(sgid); printf("stored=%s (%ld)", DISPLAY_GROUPNAME(p), (long)sgid); p = groupNameFromid(fsgid); printf("fs=%s (%ld); ", DISPLAY_GROUPNAME(p), (long)fsgid); printf("\n"); numGroups = getgroups(SG_SIZE, suppGroups); if(numGroups == -1) errExit("getgroups"); printf("Supplementary Groups(%d): ", numGroups); for(j = 0; j < numGroups; j++) { p = groupNameFromid(suppGroups[j]); printf("%s (%ld) ", DISPLAY_GROUPNAME(p), (long)suppGroups[j]); } printf("\n"); //exit(EXIT_SUCCESS); }
C
#include <msp430.h> #include <Output.h> #include <Authenticator.h> //output #define MOTOR BIT2 //input #define BUTTON BIT3 /* *Our driver. * */ void setup(){ WDTCTL = WDTPW | WDTHOLD; // stop watchdog timer setupOutput((MOTOR)); //Declare OUTPUTS setupInput(BUTTON); //Declare INPUTS setOutput((MOTOR),ON); //MAKE PIN0&6 HIGH INITIALLY setupAuthenticator(); } void loop(){ while(1){ if(isPasswordValid()){ setOutput(MOTOR,ON); }else{ setOutput(MOTOR,OFF); } } } /** * main.c */ int main(void) { setup(); loop(); return 0; }
C
/* * 此程序演示算术运算符的使用 * 作者:豫让 日期:20190525 */ #include <stdio.h> int main() { double A=18; // 定义变量A,赋值18 double B=5; // 定义变量B,赋值5 printf("A的值是:%lf\n",A); printf("B的值是:%lf\n",B); printf("A+B的值是:%lf\n",A+B); printf("A-B的值是:%lf\n",A-B); printf("A*B的值是:%lf\n",A*B); printf("A/B的值是:%lf\n",A/B); //printf("A除B的余数是:%lf\n",A%B); A++; // 自增1 printf("A自增后的值是:%lf\n",A); B--; // 自减1 printf("B自减后的值是:%lf\n",B); return 0; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> int main() { char data[] = "D2BCD2BCD2BCD2BCD2BCD2BCD2BCD2BCD2BCD2BCD2BCD2BCB7A1B7A1B7A1B7A1B7A1B7A1B7A1B7A1B7A1B7A1B7A1B7A1C8FEC8FEC8FEC8FEC8FEC8FEC8FEC8FEC8FEC8FEC8FEC8FECBC1CBC1CBC1CBC1CBC1CBC1CBC1CBC1CBC1CBC1CBC1CBC1CEE9CEE9CEE9CEE9CEE9CEE9CEE9CEE9CEE9CEE9CEE9CEE9"; int len = strlen(data); int i; for(i = 0; i < len; i++) { if(i%2 == 0) printf(" ,0x"); printf("%c", data[i]); } printf("\n"); printf("len = %d\n", len/2); return 0; }
C
//--------------------------- // Name: Natalie Petrosian // UserID: npetrosi // Assignment: PA2 //--------------------------- #include "List.h" #define UNVISITED 0 #define INPROGRESS 1 #define ALLDONE 2 #define FOUND 3 #define NOTFOUND 4 #define MAX_ARRAY_SIZE 256 typedef struct GraphObj { int numVertices; int numEdges; Node adjacencyList[MAX_ARRAY_SIZE]; int visitStatus[MAX_ARRAY_SIZE]; } GraphObj; // GraphObj typedef struct GraphObj* Graph; Graph newGraph(int numVertices); void freeGraph(Graph* pG); int getOrder(Graph G); int getSize(Graph G); int getNeighborCount(Graph G, int v); List getNeighbors(Graph G, int v); int addEdge(Graph G, int u, int v); void unvisitAll(Graph G); int getMark(Graph G, int u); void setMark(Graph G, int u, int theMark); int PathExistsRecursive(Graph G, int w, int v); void printGraph(FILE* out, Graph G);
C
/* Define a student structure with University Seat Number (USN), name (FirstName, LastName), and marks in 3 subjects as members of that structure with nesting. Write a C program to read the information for one student and print the same. */ #include <stdio.h> #include <string.h> #include <stdlib.h> typedef struct marks { char name[30]; int marks; } marks; typedef struct student { char first_name[20]; char last_name[20]; marks studmarks[3]; } student; int main() { student stud; printf("Enter the name of student first name, last name : "); scanf("%s %s", stud.first_name, stud.last_name); for (int i = 0; i < 3; i++) { char arraytemp[30]; printf("\nEnter the name of %d subject : ", i + 1); scanf("%s", arraytemp); strcpy(stud.studmarks[i].name, arraytemp); printf("\nEnter the marks of %d subject : ", i + 1); scanf("%d", &stud.studmarks[i].marks); } printf("The name of the student is %s %s\n", stud.first_name, stud.last_name); printf("The marks in each subject are \n"); for (int i = 0; i < 3; i++) printf("%s : %d\n", stud.studmarks[i].name, stud.studmarks[i].marks); return 0; }
C
#include <stdio.h> #include <unistd.h> #include <pthread.h> //线程函数 /* 线程除了自己私有的堆栈和寄存器以外其他的都是共享的! */ void* pthreadone(void *num) { //将本线程设置为分离线程 pthread_detach(pthread_self()); printf("I am pthread one!\n"); pthread_exit("exit"); } void* pthreadtwo(void *num) { //创建的线程默认为绑定线程 printf("I am pthread two!\n"); } int main() { pthread_t fdo; char* num = "传递线程的数据!\n"; pthread_create( &fdo,//线程ID 0,//线程默认属性 pthreadone,//线程代码函数 (void*)num//线程参数 ); pthread_t fdt; pthread_create( &fdt,// 0,// pthreadtwo,// (void*)num // ); char re[100]; pthread_join(fdt, (void**)&re); printf("%s\n", re); } /* 线程分类: 1.非分离线程(pthreadtwo) 非分离线程必须进行join回收该线程所拥有的资源(线程ID等)。 2.绑定线程(pthreadone) 分离线程是不需要进行join的,分离线程结束的时候就会将所占有的资源进行释放。 */ /* Thread attributes:() Detach state = PTHREAD_CREATE_JOINABLE 设置分离状态 Scope = PTHREAD_SCOPE_SYSTEM 设置范围 Inherit scheduler = PTHREAD_INHERIT_SCHED 设置继承的调度策略 Scheduling policy = SCHED_OTHER 设置调度策略 Scheduling priority = 0 设置优先级 Guard size = 4096 bytes 线程栈末尾的警戒缓冲区大小 Stack address = 0x40196000 线程堆栈的地址 Stack size = 0x201000 bytes 线程堆栈的大小 */
C
#include <stdio.h> #include <pthread.h> #include <stdlib.h> #include <semaphore.h> #define LIMIT 1000 sem_t sem1,sem2; void* function1(void *p) { int expected = *(int *)p; while(expected < LIMIT) { sem_wait(&sem1);{ printf("Even %d\n", expected); expected += 2; } sem_post(&sem2); } exit(0); } void* function2(void *p) { int expected = *(int *)p; while(expected < LIMIT) { sem_wait(&sem2); { printf("Odd %d\n", expected); expected += 2; } sem_post(&sem1); } exit(0); } int main(int argc, char *argv[]) { pthread_t thread1, thread2; int counter = 0; int expected_0 = 0, expected_1 = 1; sem_init(&sem1, 0, 1); sem_init(&sem2, 0, 0); pthread_create(&thread1, NULL, function1, (void *)&expected_0); pthread_create(&thread2, NULL, function2, (void *)&expected_1); pthread_join(thread1, NULL); pthread_join(thread2, NULL); return 0; }
C
#include <stdio.h> #include <assert.h> // f(n + 1) = f(n) + f(n - 1) int fibo_loop(int index){ if(index < 2){ return 1; } else { int value = 1, value_before = 1; //define f(0) and f(1) int tmp = 0; while(index > 1){ tmp = value; value += value_before; value_before = tmp; index--; } return value; } } int fibo_rec(int index, int a, int b){ if(index < 2){ return a; } else { return fibo_rec(index - 1, a + b, a); } } int main(void){ int index = 0; printf("Input the index?:"); scanf("%d", &index); assert(index >= 0); printf("(loop) f(%d) = %d\n", index, fibo_loop(index)); printf("(recursion) f(%d) = %d\n", index, fibo_rec(index, 1, 1)); return 0; }
C
#ifndef __LAB8_GLOBAL__ #define __LAB8_GLOBAL__ enum{ //32 terminals //ս1ʼʷķֵͻ IF=1, ELSE, WHILE, DO, BREAK, TRUE, FALSE, INT, BOOL, AND, OR, NOT, EQ, NE, GT, GE, LT, LE, SET, ADD, SUB, MUL, DIV, SC, LP, RP, LB, RB, LSB, RSB, ID, NUM }; enum{ // non-terminals & auxiliaries PRO, BLO, DECLS, DECL, TYP, TYPP, BASIC, STMTS, STMT, LOC, LOCP, BEXP, BEXPP, JOIN, JOINP, EQU, EQUP, REL, RELP, AEXP, AEXPP, TERM, TERMP, UNY, FAC, EPS, END }; enum{ // Operator opASSIGN, opADD, opSUB, opMUL, opDIV, opARRGETLEFT, opARRGETRIGHT, opAND, opOR, opNOT, opLT, opEQ, opNE, opGT, opLE, opGE, opJMP, opJNE, opJE, opJZ, opJNZ, opJL, opJG, opJLE, opJGE }; //opARRGETLEFT -> arr[index] = n.place opARRGETRIGHT -> n.place = arr[index] enum{ // NONE, IMMEDIATE, VARIABLE, ADDRESS }; #endif
C
/* ** my_putnbr_base.c for my_putnbr_base in /home/lblanchard/PSU_2016_my_printf ** ** Made by Leandre Blanchard ** Login <[email protected]> ** ** Started on Wed Nov 9 11:32:20 2016 Leandre Blanchard ** Last update Sun Apr 30 17:16:24 2017 Léandre Blanchard */ #include "my_printf.h" int part_of_base(char c, char *base) { long i; i = 0; while (base[i] != 0) { if (c == base[i]) return (0); i = i + 1; } return (84); } int my_put_pointer(long long nbr) { char *base; char *result; unsigned long long i; unsigned long long j; j = 0; i = nbr; if ((result = malloc(sizeof (char) * 100)) == NULL) return (-1); if ((base = my_strdup("0123456789abcedf")) == NULL) return (-1); while (i) { result[j] = base[i % 16]; i = i / 16; j = j + 1; } my_putstr(my_revstr(result)); return (0); } int my_putnbr_base(long long nbr, char *base) { unsigned long long basex; unsigned long long i; char *result; unsigned long long j; j = 0; i = nbr; basex = my_strlen(base); if ((result = malloc(sizeof (char) * 100)) == NULL) return (-1); while (i) { result[j] = base[i % basex]; i = i / basex; j = j + 1; } while (nbr) { if (part_of_base(result[nbr], base) == 0) my_putchar(result[nbr]); nbr = nbr - 1; } if (part_of_base(result[nbr], base) == 0) my_putchar(result[nbr]); return (0); } void my_nputnbr_base(long long nbr, char *base, int n) { my_putnbr_base(nbr, base); }
C
/* * @Brief: * This file is for extracting picture from mp3 file. * @References: * http://blog.csdn.net/ydtbk/article/details/9258651 * http://magiclen.org/mp3-tag/ */ #include <stdio.h> #include <stdlib.h> #include <memory.h> #include "extractPic.h" // id3v2 header tag structure typedef struct { char identi[3]; char version; char revision; char flags; unsigned char size[4]; } ID3V2Header; // frame header structure typedef struct { char frameId[4]; unsigned char size[4]; char flags[2]; } ID3V2Frameheader; unsigned char Mp3ToPic_GetHeaderInfo(FILE *fp, int *len) { ID3V2Header mp3ID3V2; // pointer to the mp3 at the beginning fseek(fp, 0, SEEK_SET); // load header tag memset(&mp3ID3V2, 0, 10); fread(&mp3ID3V2, 10, 1, fp); if (strncmp(mp3ID3V2.identi, "ID3", 3) != 0) { printf("[mp3_pic] Error: no ID3V2 tag!\n"); return 0; } // calculate header tag size *len= ((mp3ID3V2.size[0]&0x7f) << 21) + ((mp3ID3V2.size[1]&0x7f) << 14) + ((mp3ID3V2.size[2]&0x7f) << 7) + (mp3ID3V2.size[3]&0x7f); return 1; } int Mp3ToPic_GetPicSize(FILE *fp, int len) { ID3V2Frameheader pFrameBuf; char image_tag[7] = {"0"}; char pic_type[5] = {"0"}; int frame_size = 0; int skip_data = 0; int i = 0; memset(&pFrameBuf, 0, 10); fread(&pFrameBuf, 10, 1, fp); // find pic tag location while (strncmp(pFrameBuf.frameId, "APIC", 4) != 0) { if (ftell(fp) > len) { printf("[mp3_pic] Error: no APIC tag!\n\n"); return 0; } frame_size = (pFrameBuf.size[0] << 24) + (pFrameBuf.size[1] << 16) + (pFrameBuf.size[2] << 8) + pFrameBuf.size[3]; fseek(fp, frame_size, SEEK_CUR); memset(&pFrameBuf, 0, 10); fread(&pFrameBuf, 10, 1, fp); } // calculate pic tag size frame_size = (pFrameBuf.size[0] << 24) + (pFrameBuf.size[1] << 16) + (pFrameBuf.size[2] << 8) + pFrameBuf.size[3]; // check pic format fread(image_tag, 6, 1, fp); while (1) { if (i > frame_size) { printf("[mp3_pic] Error: cannot find image tag!\n"); fclose(fp); return 0; } if (strcmp(image_tag, "image/") == 0) { skip_data += 6; fread(pic_type, 4, 1, fp); if (strncmp(pic_type, "jpeg", 4) == 0) { skip_data += 4; break; } else if (strncmp(pic_type, "png", 3) == 0) { skip_data += 3; fseek(fp, -1, SEEK_CUR); break; } else { printf("[mp3_pic] Error: unsupported image format!\n"); return 0; } } else { i++; fseek(fp, -5, SEEK_CUR); fread(image_tag, 6, 1, fp); skip_data += 1; continue; } } // need to shift 3 bytes but don't know why fseek(fp, 3, SEEK_CUR); skip_data += 3; return (frame_size - skip_data); } int Mp3ToPic(FILE *fp) { int tag_size = 0; if (Mp3ToPic_GetHeaderInfo(fp, &tag_size) == 0) return 0; return Mp3ToPic_GetPicSize(fp, tag_size); }
C
#ifndef GAME_FONT_H #define GAME_FONT_H #include "Texture.h" struct Font { Texture texture; int charWidth[256]; int startChar; int fontHeight; int cellWidth; int cellHeight; int imageWidth; int imageHeight; int numRows; int numCols; }; /** * Loads a font file. */ int Font_Load(Font& font, const char* fileName); /** * Begins drawing with the specified font. */ void Font_BeginDrawing(const Font& font); /** * Finishes drawing with a font. */ void Font_EndDrawing(); /** * Draws text on the screen at the specified location. */ int Font_DrawText(const char* text, int x, int y); /** * Returns the width (in pixels) of the text when rendered. */ int Font_GetTextWidth(const Font& font, const char* text); /** * Returns the height (in pixels) of the text when rendered. */ int Font_GetTextHeight(const Font& font); #endif
C
/* * This file is part of the OpenMV project. * * Copyright (c) 2013-2021 Ibrahim Abdelkader <[email protected]> * Copyright (c) 2013-2021 Kwabena W. Agyeman <[email protected]> * * This work is licensed under the MIT license, see the file LICENSE for details. * * Common data structures. */ #include "imlib.h" #define CHAR_BITS (sizeof(char) * 8) #define CHAR_MASK (CHAR_BITS - 1) #define CHAR_SHIFT IM_LOG2(CHAR_MASK) //////////// // bitmap // //////////// void bitmap_alloc(bitmap_t *ptr, size_t size) { ptr->size = size; ptr->data = (char *) fb_alloc0(((size + CHAR_MASK) >> CHAR_SHIFT) * sizeof(char), FB_ALLOC_NO_HINT); } void bitmap_free(bitmap_t *ptr) { if (ptr->data) { fb_free(); } } void bitmap_clear(bitmap_t *ptr) { memset(ptr->data, 0, ((ptr->size + CHAR_MASK) >> CHAR_SHIFT) * sizeof(char)); } void bitmap_bit_set(bitmap_t *ptr, size_t index) { ptr->data[index >> CHAR_SHIFT] |= 1 << (index & CHAR_MASK); } bool bitmap_bit_get(bitmap_t *ptr, size_t index) { return (ptr->data[index >> CHAR_SHIFT] >> (index & CHAR_MASK)) & 1; } ////////// // lifo // ////////// void lifo_alloc(lifo_t *ptr, size_t size, size_t data_len) { ptr->len = 0; ptr->size = size; ptr->data_len = data_len; ptr->data = (char *) fb_alloc(size * data_len, FB_ALLOC_NO_HINT); } void lifo_alloc_all(lifo_t *ptr, size_t *size, size_t data_len) { uint32_t tmp_size; ptr->data = (char *) fb_alloc_all(&tmp_size, FB_ALLOC_NO_HINT); ptr->data_len = data_len; ptr->size = tmp_size / data_len; ptr->len = 0; *size = ptr->size; } void lifo_free(lifo_t *ptr) { if (ptr->data) { fb_free(); } } void lifo_clear(lifo_t *ptr) { ptr->len = 0; } size_t lifo_size(lifo_t *ptr) { return ptr->len; } bool lifo_is_not_empty(lifo_t *ptr) { return ptr->len; } bool lifo_is_not_full(lifo_t *ptr) { return ptr->len != ptr->size; } void lifo_enqueue(lifo_t *ptr, void *data) { memcpy(ptr->data + (ptr->len * ptr->data_len), data, ptr->data_len); ptr->len += 1; } void lifo_dequeue(lifo_t *ptr, void *data) { if (data) { memcpy(data, ptr->data + ((ptr->len - 1) * ptr->data_len), ptr->data_len); } ptr->len -= 1; } void lifo_poke(lifo_t *ptr, void *data) { memcpy(ptr->data + (ptr->len * ptr->data_len), data, ptr->data_len); } void lifo_peek(lifo_t *ptr, void *data) { memcpy(data, ptr->data + ((ptr->len - 1) * ptr->data_len), ptr->data_len); } ////////// // fifo // ////////// void fifo_alloc(fifo_t *ptr, size_t size, size_t data_len) { ptr->head_ptr = 0; ptr->tail_ptr = 0; ptr->len = 0; ptr->size = size; ptr->data_len = data_len; ptr->data = (char *) fb_alloc(size * data_len, FB_ALLOC_NO_HINT); } void fifo_alloc_all(fifo_t *ptr, size_t *size, size_t data_len) { uint32_t tmp_size; ptr->data = (char *) fb_alloc_all(&tmp_size, FB_ALLOC_NO_HINT); ptr->data_len = data_len; ptr->size = tmp_size / data_len; ptr->len = 0; ptr->tail_ptr = 0; ptr->head_ptr = 0; *size = ptr->size; } void fifo_free(fifo_t *ptr) { if (ptr->data) { fb_free(); } } void fifo_clear(fifo_t *ptr) { ptr->head_ptr = 0; ptr->tail_ptr = 0; ptr->len = 0; } size_t fifo_size(fifo_t *ptr) { return ptr->len; } bool fifo_is_not_empty(fifo_t *ptr) { return ptr->len; } bool fifo_is_not_full(fifo_t *ptr) { return ptr->len != ptr->size; } void fifo_enqueue(fifo_t *ptr, void *data) { memcpy(ptr->data + (ptr->head_ptr * ptr->data_len), data, ptr->data_len); size_t temp = ptr->head_ptr + 1; if (temp == ptr->size) { temp = 0; } ptr->head_ptr = temp; ptr->len += 1; } void fifo_dequeue(fifo_t *ptr, void *data) { if (data) { memcpy(data, ptr->data + (ptr->tail_ptr * ptr->data_len), ptr->data_len); } size_t temp = ptr->tail_ptr + 1; if (temp == ptr->size) { temp = 0; } ptr->tail_ptr = temp; ptr->len -= 1; } void fifo_poke(fifo_t *ptr, void *data) { memcpy(ptr->data + (ptr->head_ptr * ptr->data_len), data, ptr->data_len); } void fifo_peek(fifo_t *ptr, void *data) { memcpy(data, ptr->data + (ptr->tail_ptr * ptr->data_len), ptr->data_len); } ////////// // list // ////////// void list_init(list_t *ptr, size_t data_len) { ptr->head_ptr = NULL; ptr->tail_ptr = NULL; ptr->size = 0; ptr->data_len = data_len; } void list_copy(list_t *dst, list_t *src) { memcpy(dst, src, sizeof(list_t)); } void list_free(list_t *ptr) { for (list_lnk_t *i = ptr->head_ptr; i; ) { list_lnk_t *j = i->next_ptr; xfree(i); i = j; } } void list_clear(list_t *ptr) { list_free(ptr); ptr->head_ptr = NULL; ptr->tail_ptr = NULL; ptr->size = 0; } size_t list_size(list_t *ptr) { return ptr->size; } void list_push_front(list_t *ptr, void *data) { list_lnk_t *tmp = (list_lnk_t *) xalloc(sizeof(list_lnk_t) + ptr->data_len); memcpy(tmp->data, data, ptr->data_len); if (ptr->size++) { tmp->next_ptr = ptr->head_ptr; tmp->prev_ptr = NULL; ptr->head_ptr->prev_ptr = tmp; ptr->head_ptr = tmp; } else { tmp->next_ptr = NULL; tmp->prev_ptr = NULL; ptr->head_ptr = tmp; ptr->tail_ptr = tmp; } } void list_push_back(list_t *ptr, void *data) { list_lnk_t *tmp = (list_lnk_t *) xalloc(sizeof(list_lnk_t) + ptr->data_len); memcpy(tmp->data, data, ptr->data_len); if (ptr->size++) { tmp->next_ptr = NULL; tmp->prev_ptr = ptr->tail_ptr; ptr->tail_ptr->next_ptr = tmp; ptr->tail_ptr = tmp; } else { tmp->next_ptr = NULL; tmp->prev_ptr = NULL; ptr->head_ptr = tmp; ptr->tail_ptr = tmp; } } void list_pop_front(list_t *ptr, void *data) { list_lnk_t *tmp = ptr->head_ptr; if (data) { memcpy(data, tmp->data, ptr->data_len); } if (tmp->next_ptr) { tmp->next_ptr->prev_ptr = NULL; } ptr->head_ptr = tmp->next_ptr; ptr->size -= 1; xfree(tmp); } void list_pop_back(list_t *ptr, void *data) { list_lnk_t *tmp = ptr->tail_ptr; if (data) { memcpy(data, tmp->data, ptr->data_len); } tmp->prev_ptr->next_ptr = NULL; ptr->tail_ptr = tmp->prev_ptr; ptr->size -= 1; xfree(tmp); } void list_get_front(list_t *ptr, void *data) { memcpy(data, ptr->head_ptr->data, ptr->data_len); } void list_get_back(list_t *ptr, void *data) { memcpy(data, ptr->tail_ptr->data, ptr->data_len); } void list_set_front(list_t *ptr, void *data) { memcpy(ptr->head_ptr->data, data, ptr->data_len); } void list_set_back(list_t *ptr, void *data) { memcpy(ptr->tail_ptr->data, data, ptr->data_len); } void list_insert(list_t *ptr, void *data, size_t index) { if (index == 0) { list_push_front(ptr, data); } else if (index >= ptr->size) { list_push_back(ptr, data); } else if (index < (ptr->size >> 1)) { list_lnk_t *i = ptr->head_ptr; while (index) { i = i->next_ptr; index -= 1; } list_lnk_t *tmp = (list_lnk_t *) xalloc(sizeof(list_lnk_t) + ptr->data_len); memcpy(tmp->data, data, ptr->data_len); tmp->next_ptr = i; tmp->prev_ptr = i->prev_ptr; i->prev_ptr->next_ptr = tmp; i->prev_ptr = tmp; ptr->size += 1; } else { list_lnk_t *i = ptr->tail_ptr; index = ptr->size - index - 1; while (index) { i = i->prev_ptr; index -= 1; } list_lnk_t *tmp = (list_lnk_t *) xalloc(sizeof(list_lnk_t) + ptr->data_len); memcpy(tmp->data, data, ptr->data_len); tmp->next_ptr = i; tmp->prev_ptr = i->prev_ptr; i->prev_ptr->next_ptr = tmp; i->prev_ptr = tmp; ptr->size += 1; } } void list_remove(list_t *ptr, void *data, size_t index) { if (index == 0) { list_pop_front(ptr, data); } else if (index >= (ptr->size - 1)) { list_pop_back(ptr, data); } else if (index < (ptr->size >> 1)) { list_lnk_t *i = ptr->head_ptr; while (index) { i = i->next_ptr; index -= 1; } if (data) { memcpy(data, i->data, ptr->data_len); } i->prev_ptr->next_ptr = i->next_ptr; i->next_ptr->prev_ptr = i->prev_ptr; ptr->size -= 1; xfree(i); } else { list_lnk_t *i = ptr->tail_ptr; index = ptr->size - index - 1; while (index) { i = i->prev_ptr; index -= 1; } if (data) { memcpy(data, i->data, ptr->data_len); } i->prev_ptr->next_ptr = i->next_ptr; i->next_ptr->prev_ptr = i->prev_ptr; ptr->size -= 1; xfree(i); } } void list_get(list_t *ptr, void *data, size_t index) { if (index == 0) { list_get_front(ptr, data); } else if (index >= (ptr->size - 1)) { list_get_back(ptr, data); } else if (index < (ptr->size >> 1)) { list_lnk_t *i = ptr->head_ptr; while (index) { i = i->next_ptr; index -= 1; } memcpy(data, i->data, ptr->data_len); } else { list_lnk_t *i = ptr->tail_ptr; index = ptr->size - index - 1; while (index) { i = i->prev_ptr; index -= 1; } memcpy(data, i->data, ptr->data_len); } } void list_set(list_t *ptr, void *data, size_t index) { if (index == 0) { list_set_front(ptr, data); } else if (index >= (ptr->size - 1)) { list_set_back(ptr, data); } else if (index < (ptr->size >> 1)) { list_lnk_t *i = ptr->head_ptr; while (index) { i = i->next_ptr; index -= 1; } memcpy(i->data, data, ptr->data_len); } else { list_lnk_t *i = ptr->tail_ptr; index = ptr->size - index - 1; while (index) { i = i->prev_ptr; index -= 1; } memcpy(i->data, data, ptr->data_len); } } ////////////// // iterator // ////////////// list_lnk_t *iterator_start_from_head(list_t *ptr) { return ptr->head_ptr; } list_lnk_t *iterator_start_from_tail(list_t *ptr) { return ptr->tail_ptr; } list_lnk_t *iterator_next(list_lnk_t *lnk) { return lnk->next_ptr; } list_lnk_t *iterator_prev(list_lnk_t *lnk) { return lnk->prev_ptr; } void iterator_get(list_t *ptr, list_lnk_t *lnk, void *data) { memcpy(data, lnk->data, ptr->data_len); } void iterator_set(list_t *ptr, list_lnk_t *lnk, void *data) { memcpy(lnk->data, data, ptr->data_len); }
C
/** * \addtogroup apps * @{ */ /** * \defgroup special_server Special webserver * @{ * * This example shows a simplified webserver that always responds with the same information. */ /** * \file * Implementation of the HTTP client. * \author Eñaut Muxika <[email protected]> */ #include <stdlib.h> #include <string.h> #include <uip/uip.h> #include <uip/uiplib.h> #include "special_server.h" #include "network_state.h" /************************************************/ /* Constants */ /************************************************/ #define SPECIAL_SERVER_TIMEOUT 20 /************************************************/ /* Global variables */ /************************************************/ char* specserver_resp_data; int specserver_resp_data_len; frame_stats_t specserver_stats; /************************************************/ /* Prototypes */ /************************************************/ /************************************************/ /* Function implementations */ /************************************************/ /*-----------------------------------------------------------------------------------*/ void specserver_app_init(void) { uip_listen( HTONS( SPECIAL_SERVER_PORT ) ); specserver_stats.recv = specserver_stats.sent = 0; } /*-----------------------------------------------------------------------------------*/ void specserver_appcall(void) { static uint8_t reqs = 0; static char *data; if( uip_conn->lport != HTONS( SPECIAL_SERVER_PORT ) ) return; specserver_stats.frames++; if( uip_connected() ) { reqs = 0; } if( uip_newdata() ) { specserver_stats.recv++; char *p; // Process response data = (char*)uip_appdata; p = strchr( data, '\r' ); if( p != NULL ) *p = 0; p = strchr( data, '\n' ); if( p != NULL ) *p = 0; data[50] = 0; // Limit max size to one line or 50 char, whicever is smaller reqs++; } if( uip_acked() ) { } if( uip_rexmit() || uip_newdata() || uip_acked()) { // Send response if( reqs > 0 ) { reqs--; uip_send( specserver_resp_data, specserver_resp_data_len ); }else{ uip_close(); } } else if(uip_poll()) { uip_close(); } } /*-----------------------------------------------------------------------------------*/ char *i2dec(char *buf, int num, int width) { char c; int i = width; int ndig = 0; int sgn = 0; if( i == 0 ) i = 10; // all digits if( i < 0 ) i = -i; // justify left if( num < 0 ) { num = -num; sgn = 1; } buf[i] = 0; while( i > 0 && num > 0 ) { c = (num%10) + '0'; num /= 10; i--; buf[i] = c; ndig++; } if( ndig == 0 && num == 0 ) { i--; buf[i] = '0'; ndig++; } if( sgn && i > 0 ) { i--; buf[i] = '-'; ndig++; sgn = 0; } if( num > 0 || sgn ) { // Not enough space if( sgn ) buf[0] = '<'; else buf[0] = '>'; } if( i > 0 ) { if( width == 0 ) { // memcpy( buf, buf + i, ndig + 1 ); }else if( width > 0 ) { // Justify right memset( buf, ' ', i ); ndig += i; }else{ // Justify left memcpy( buf, buf + i, ndig ); memset( buf + ndig, ' ', i ); ndig += i; } } return (buf+ndig); } char *i2hex(char *buf, uint32_t num, int width) { char c; int i = width; int ndig = 0; if( i <= 0 ) i = 8; // all digits buf[i] = 0; while( i >= 0 ) { c = (num & 0xF) + '0'; num >>= 4; if( c > '9' ) c += ('A' - '0' - 10); i--; buf[i] = c; ndig++; } return (buf+ndig); } /** @} */ /** @} */
C
#include <stdio.h> //printf #include <sys/socket.h> #include <netdb.h> //hostent #include <arpa/inet.h> #include <string.h> //#include "hle_url_prase.h" typedef struct _url_info_t { char*protocol; //协议 char*host; //域名 char*port; //端口 char*path; //路径 char*query; //询问 char*fragment; //片段 }url_info_t; /************************************************************************** URL info 结构的释放 参数: url_info:url_prase函数 解析后的url结构体指针 ***************************************************************************/ int free_url_info(url_info_t*url_info) { if(NULL == url_info) return -1; free((void*)url_info->protocol); free((void*)url_info->host); free((void*)url_info->port); free((void*)url_info->path); free((void*)url_info->query); free((void*)url_info->fragment); return 0; } /************************************************************************** URL解析函数,精简版 参数: url(入):url字符串指针 url_info_ret(返回):解析后的url结构体指针 注意,使用完后需要释放(free)url_info_ret的每一个成员,不然会产生内存泄漏。 return: success:0 error:-1 //url示例: http://www.baidu.com:80/cig-bin/index.html?sdkfj#283sjkdf ***************************************************************************/ int url_prase(const char*url,url_info_t*url_info_ret) { if(NULL == url) return -1; char *parseptr1; char *parseptr2; int len; int i; /*************解析协议*********************************/ parseptr2 = strdup(url); char *free_pst = parseptr2; parseptr1 = strchr(parseptr2, ':');//在parseptr2中找“ :”的位置,由parseptr1指向它开始的位置 if ( NULL == parseptr1 ) { printf("URL error!\n"); free(parseptr2); return -1; } len = parseptr1 - parseptr2; //地址做差,得出 “ :”之前字符串长度(字节数),即协议的长度 for ( i = 0; i < len; i++ ) { if ( !isalpha(parseptr2[i]) ) //判断字符ch是否为英文字母a-z A-Z ,是则返回非零值 { printf("URL error!\n"); free(parseptr2); return -1; } } /* printf("protocol: "); for(i=0;i<len;i++) printf("%c",parseptr2[i]); */ url_info_ret->protocol = (char*)calloc(len+1,sizeof(char)); strncpy(url_info_ret->protocol,parseptr2,len); //url_info_ret->protocol = strndup(parseptr2,len); /*************解析host*********************************/ printf("\n"); parseptr1++; //指向 “ :”的下一个字符,跳过“//” parseptr2 = parseptr1; for ( i = 0; i < 2; i++ ) { if ( '/' != *parseptr2 ) { printf("URL error!\n"); free(parseptr2); free(url_info_ret->protocol); return -1; } parseptr2++; } parseptr1 = strchr(parseptr2, ':'); if ( NULL == parseptr1 )//判断有无端口号 { parseptr1 = strchr(parseptr2, '/'); //无端口号的 host解析 if ( NULL == parseptr1 ) { printf("URL error!\n"); free(parseptr2); free(url_info_ret->protocol); return -1; } len = parseptr1 - parseptr2;//host长度 /*printf("host: "); for(i=0;i<len;i++) printf("%c",parseptr2[i]); printf("\n");//解析主机 */ //url_info_ret->host = strndup(parseptr2,len); url_info_ret->host = (char*)calloc(len+1,sizeof(char)); strncpy(url_info_ret->host,parseptr2,len); } else//有端口号 { len = parseptr1 - parseptr2; /*printf("host: "); for(i=0;i<len;i++) printf("%c",parseptr2[i]); printf("\n"); */ // url_info_ret->host = strndup(parseptr2,len); url_info_ret->host = (char*)calloc(len+1,sizeof(char)); strncpy(url_info_ret->host,parseptr2,len); /*************解析port*********************************/ parseptr1++; //跳过端口前的 “ :” parseptr2 = parseptr1;//基准位置从端口开始 parseptr1 = strchr(parseptr2, '/'); if ( NULL == parseptr1 ) { printf("URL error!\n"); free(parseptr2); free(url_info_ret->protocol); free(url_info_ret->host); return -1; } len = parseptr1 - parseptr2; /* printf("port: "); for(i=0;i<len;i++) printf("%d",(parseptr2[i]-48)); printf("\n");//解析端口 */ //url_info_ret->port = strndup(parseptr2,len); url_info_ret->port = (char*)calloc(len+1,sizeof(char)); strncpy(url_info_ret->port,parseptr2,len); } /*************解析path*********************************/ parseptr1++; //跳过端口后边的“/” parseptr2 = parseptr1;//基准位置重新调整 while ( '\0' != *parseptr1 && '?' != *parseptr1 && '#' != *parseptr1 ) { parseptr1++; } len = parseptr1 - parseptr2; /* printf("path: "); for(i=0;i<len;i++) printf("%c",parseptr2[i]); printf("\n");//解析路径 */ //url_info_ret->path = strndup(parseptr2,len); url_info_ret->path = (char*)calloc(len+1,sizeof(char)); strncpy(url_info_ret->path,parseptr2,len); /*************解析query*********************************/ parseptr2=parseptr1; if ( '?' == *parseptr1 ) { parseptr2++; parseptr1 = parseptr2; while ( '\0' != *parseptr1 && '#' != *parseptr1 ) { parseptr1++; } len = parseptr1 - parseptr2; /* printf("query: "); for(i=0;i<len;i++) printf("%c",parseptr2[i]);//判断有无询问并解析 printf("\n"); */ //url_info_ret->query = strndup(parseptr2,len); url_info_ret->query = (char*)calloc(len+1,sizeof(char)); strncpy(url_info_ret->query,parseptr2,len); } /*************解析fragment*********************************/ parseptr2=parseptr1; if ( '#' == *parseptr1 ) { parseptr2++; parseptr1 = parseptr2; while ( '\0' != *parseptr1 ) { parseptr1++; } len = parseptr1 - parseptr2; /* printf("fragment: "); for(i=0;i<len;i++) printf("%c",parseptr2[i]); printf("\n");//判断有无片段并解析 */ //url_info_ret->fragment = strndup(parseptr2,len); url_info_ret->fragment = (char*)calloc(len+1,sizeof(char)); strncpy(url_info_ret->fragment,parseptr2,len); } free(free_pst);//释放备份url return 0; } /************************************************************************** Get ip from domain name 依据域名解析ip地址。 参数: hostname(入):域名字符串指针 ip(返回):返回ip字符串指针 (需提前申请空间,再传地址) ***************************************************************************/ #include<netdb.h> //hostent #include<arpa/inet.h> int hostname_to_ip(char * hostname , char* ip) { struct hostent *he; struct in_addr **addr_list; int i; printf("hostname_to_ip:hostname = %s\n",hostname); if ( (he = gethostbyname( hostname ) ) == NULL) { // get the host info perror("gethostbyname"); return 1; } addr_list = (struct in_addr **) he->h_addr_list; for(i = 0; addr_list[i] != NULL; i++) { //Return the first one; strcpy(ip , inet_ntoa(*addr_list[i]) ); return 0; } return 1; } /************************************************************************** hle Get ip from url 依据域名解析ip地址。 参数: url(入):域名字符串指针 ip(返回):返回ip字符串指针 (需提前申请空间,再传地址) port:port ***************************************************************************/ char hle_ip[20]; char hle_port[10]; int hle_url_to_ip_port(char * url,char*ip,char*port) { if(NULL == url||NULL == ip) return -1; url_info_t url_info_ret = {0}; int ret = url_prase(url,&url_info_ret); if(ret < 0) perror("url_prase failed!\n"); hostname_to_ip(url_info_ret.host,ip); if(url_info_ret.port != NULL) { strcpy(port,url_info_ret.port); } printf("the url = %s \nprase ip = %s\n",url,ip); strcpy(hle_ip,ip); strcpy(hle_port,port); return 0; }
C
/* Lab 1 CSE 2320 - Lab 1 Created By Atafo Abure 1001442575 This program is going to help you predict the outcome of a mergesort using binary search. It will required the inputs for the two arrays and the number of probes Feb 6 2018 How to run To compile and run use the following commands gcc lab1.c a.out < inputFile.txt inputFile.txt would be the name of the input file you want to work with. Note the inputFile has to be in the same directory as the lab1.c file */ #include <stdio.h> #include <stdlib.h> void binarySearch(int *a,int *b, int low, int high, int rank); //main function int main(){ int m, n, p; scanf("%d",&m); scanf("%d",&n); scanf("%d",&p); int k, *a = 0, *b = 0, rank = 0, smallestSize = 0, biggestSize = 0; int high, low; int x,y; //dynamic allocation for arrays a = (int *)malloc((m+2) * sizeof(int)); b = (int *)malloc((n+2) * sizeof(int)); for(x = 1; x < m+1; x++) { scanf("%d",&a[x]); } a[0] = -99999999; a[m+1] = 99999999; for(y = 1; y < n+1; y++) { scanf("%d",&b[y]); } b[0] = -99999999; b[n+1] = 99999999; // Test case to account for the number of probes being larger than the size of both arrays if(p > m || p > n) { printf("Number of probes given are larger than the sizes of every array"); free(a); free(b); return 0; // quits the program } // run the binary search function for the given number of ranks for(k = 0; k < p; k++) { scanf("%d",&rank); //if statement to find which array is the larger array if(m > n) { smallestSize = n; biggestSize = m; } else { smallestSize = m; biggestSize = n; } // if rank is greater than the size of the smallest array then high value should be set to the smallest array and m has to be greater than or equal to n if(rank > smallestSize && m <= n) high = smallestSize; else high = rank; low = rank - biggestSize; // low should be the rank minus the biggestSize if the value is negative your lowest value should be 0 if(low < 0) low = 0; binarySearch(a, b, low, high, rank); // call binary search function and predict the merge sort } //free dynamically allocated arrays free(a); free(b); return 0; } //binary search function used to predict the outcome of a mergesort void binarySearch(int *a,int *b, int low, int high, int rank) { int i, j; int mid; while (low<=high) { i = (low+high)/2; j = rank - i; printf("Low is: %d High is: %d ",low, high); printf("i is: %d j is: %d ",i,j); printf("a[%d] is: %d b[%d] is: %d\n",i,a[i],j,b[j]); mid=(low+high)/2; //mid splits the array in half for the purpose of binary search if(i + j == rank) { if(b[j] < a[i]) { if(a[i] <= b[j+1]) { printf("a[%d] = %d has rank %d\n",i,a[i],rank); // the given rank is in arrayA at position i break; } else { high = mid - 1; // reset high value to mid - 1 } } else if(a[i] <= b[j]) { if(b[j] < a[i+1]) { printf("b[%d] = %d has rank %d\n",j,b[j],rank); // the given rank is in arrayB at position j break; } else { low = mid+1; // reset low value to mid + 1 } } } } }
C
#include <limits.h> #include <stdio.h> #include <string.h> #include <errno.h> #include "error.h" #include "log.h" int main(int argc, char* args[]) { int status; if (log_init(args[0])) { perror("log_init()"); status = 1; } else { ErrorObj* err; (void)log_set_level(LOG_LEVEL_DEBUG); err = ERR_NEW(0, NULL, "Simple message"); err_log(err, ERR_ERROR); err_free(err); err = ERR_NEW( 0, ERR_NEW(1, NULL, "Nested message 2"), "Nested message 1"); err_log(err, ERR_ERROR); err_free(err); err = ERR_NEW( 0, ERR_NEW1( 1, ERR_NEW1(2, NULL, "Nested message 3: %s", strerror(ENOMEM)), "Nested message 2: %d", INT_MAX), "Nested message 1"); err_log(err, ERR_DEBUG); err_free(err); status = 0; } return status; }
C
#include <stdio.h> #include <string.h> #include <assert.h> //递归,字符串的全排列 void Swap(char *s1,char *s2) { char tmp = *s1; *s1 = *s2; *s2 = tmp; } int IsSwap(char *begin,char *end) { assert(begin != NULL && end != NULL); char *p = begin; for(p; p < end; p++) { if(*p == *end) { return 0; } } return 1; } void Permutation(char *str,char *begin) { if(*begin == '\0') { printf("%s\n",str); } else { char *pchr = begin; for(pchr = begin; *pchr != '\0'; pchr++) { if(IsSwap(begin,pchr) == 1) //去除重复 { Swap(begin,pchr); Permutation(str,begin+1); Swap(begin,pchr); } } } } /* void Permutation1(char *str,char *begin) { } */ //非递归 void Permutation1(char *str) { assert(str != NULL); int len = strlen(str); int i = 0; int j = 0; int k = 0; } int main() { char str[] = "abcd"; Permutation(str,str); return 0; }
C
#include<stdio.h> void main() { float a, b; clrscr(); a = 10; b = 3; printf("%f", a/b); getch(); }
C
// $Id: nsort.c,v 1.1 2011-04-29 19:46:42-07 - - $ #include <assert.h> #include <libgen.h> #include <stdio.h> #include <stdio_ext.h> #include <stdlib.h> #include <stdbool.h> #include <unistd.h> #include <string.h> #define OPTION "d" typedef struct node node; struct node { double item; node *link; }; int exit_status = EXIT_SUCCESS; char *programName; _Bool debugFlag = false; node *head = NULL; void optionsCheck (int num, char** str) { for(;;) { int opts = getopt(num, str, OPTION); if (opts == EOF) break; switch (opts) { case 'd': debugFlag = true; break; default: printf("%s: -%c: invalid option\n", programName, opts); abort(); } } } void sortList (/*node *head*/FILE *fp) { for(;;) { double number; // FILE *fp; int sc=fgetc(fp); // int sc = scanf("%lg\n", &number); if (sc == EOF || sc != 1) break; if (head == NULL) { node *tmp = malloc (sizeof (struct node)); assert (tmp != NULL); tmp->item = number; tmp->link = head; head = tmp; } else { node *tmp = malloc (sizeof (struct node)); assert (tmp != NULL); tmp->item = number; node *previous = NULL; for(node *curr = head; curr != NULL; curr = curr->link) { if (number < curr->item && previous == NULL) { tmp->link = head; head = tmp; break; } else if (number < curr->item) { tmp->link = curr; previous->link = tmp; break; } else if (number >= curr->item && curr->link == NULL) { curr->link = tmp; tmp->link = NULL; break; } previous = curr; } } }while(getchar() != '\n'); } void printList (/*node *head*/) { if(debugFlag) { for(node *curr = head; curr != NULL; curr = curr->link){ printf("Node pointer[%p] : item->%g\n", curr, curr->item); } } else{ for(node *curr = head; curr != NULL; curr = curr->link){ printf("%24.15g\n", curr->item); } } } void destroyNodes (/*node *head*/){ while(head != NULL){ node *old = head; head = head->link; free(old); } } int main (int argc, char** argv) { programName = basename(argv[0]); if(argc > 2) { printf("Too Many Arguments"); exit_status = EXIT_FAILURE; } else { if(argc == 2) { optionsCheck(argc, argv); } if(strcmp(argv[0], "-d") == 0) { printf("&head= %p\n", &head); printf("head= %p\n", head); for(node *curr = head; curr != NULL; curr = curr->link) { printf("%p -> struct node {item = %.15g. link = %p}\n", curr, curr->item, curr->link); } printf("NULL= %p\n", NULL); } else { sortList(/*head*/programName); printList(/*head*/); destroyNodes(/*head*/); } } return(exit_status); }
C
/* * This program finds the lowest common ancester in a BST * * Author: @pyav */ #include <stdio.h> #include <stdlib.h> #define SUCCESS 0 #define FAILURE 1 /* Node structure */ struct node { int data; struct node *left; struct node *right; }; /* Create a new node */ struct node *new_node(int data) { struct node *one_node = NULL; one_node = (struct node *) malloc(sizeof (struct node)); if (one_node != NULL) { one_node->data = data; one_node->left = NULL; one_node->right = NULL; } return one_node; } /* Insert a new node */ struct node *insert_node(struct node *node, int data) { if (node == NULL) return new_node(data); if (data < node->data) node->left = insert_node(node->left, data); else if (data > node->data) node->right = insert_node(node->right, data); return node; } /* Print tree inorder */ void print_tree_inorder(struct node *node) { if (node != NULL) { print_tree_inorder(node->left); printf("%d ", node->data); print_tree_inorder(node->right); } } /* Function to return lowest common ancester */ struct node *lca(struct node *node, int n1, int n2) { if (node == NULL) return node; if (node->data > n1 && node->data > n2) return lca(node->left, n1, n2); if (node->data < n1 && node->data < n2) return lca(node->right, n1, n2); return node; } /* Free all nodes of the BST */ void free_all(struct node **node) { if (*node == NULL) return; free_all(&(*node)->left); free_all(&(*node)->right); free (*node); *node = NULL; } /* Main driver code */ int main(void) { int n1 = 0; int n2 = 0; struct node *t = NULL; /* structure to hold the lca */ /* Create the tree */ struct node *root = NULL; root = insert_node(root, 20); insert_node(root, 8); insert_node(root, 22); insert_node(root, 4); insert_node(root, 12); insert_node(root, 10); insert_node(root, 14); /* Print the tree */ print_tree_inorder(root); printf("\n"); /* Now check for lowest common ancester */ n1 = 10; n2 = 14; t = lca(root, n1, n2); printf("LCA of %d and %d is %d \n", n1, n2, t->data); n1 = 14; n2 = 8; t = lca(root, n1, n2); printf("LCA of %d and %d is %d \n", n1, n2, t->data); n1 = 10; n2 = 22; t = lca(root, n1, n2); printf("LCA of %d and %d is %d \n", n1, n2, t->data); /* Cleanup */ free_all(&root); return SUCCESS; } /* End of main driver */
C
\\program to print the arrangemet of the string... when repitation is not allowed in the program #include <stdio.h> void recursion(int arr[], int data[], int start, int end, int index, int r) { if (index == r) { if(data[0]+data[1]+data[2]==0) { for (int j=0; j<r; j++) printf("%d ", data[j]); printf("\n"); } return; } for (int i=start; i<=end && end-i+1 >= r-index; i++) { data[index] = arr[i]; recursion(arr, data, i+1, end, index+1, r); } } int main() { int arr[6]; for(int i=0;i<6;i++) scanf("%d",&arr[i]); int r = 3; int n = 6; int aa[3]; recursion(arr,aa,0, n-1,0, r); }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> /** *Finite Machine Matcher Preprocess */ //character set is a-z //character mapping function int charvalue(char c){ return c-'a'; } //check a is b suffix int is_suffix(char *a, char *b,int length_a,int length_b){ if (length_a > length_b){ return 0; } int i = length_a-1; int j = length_b-1; while(i>=0 && a[i] == b[j]){ --i; --j; } return i<0; } //transform result array int *transform; void print_arrayv(int *transform,int x,int y); //preprocess the transform function void preprocess(char *p, char *charset){ int m = strlen(p)+1; int e = strlen(charset); transform = (int *)malloc(sizeof(int)*m*e); int q = 0; int length = 0; char pqa[m]; int i = 0; for (q = 0; q < m; ++q){ length = q+1; memcpy(pqa,p,q); for( i = 0; i < e; ++i){ pqa[length-1]=charset[i]; int k = length; while(k>0 && !is_suffix(p,pqa,k,length)){ --k; } *(transform+q*e+charvalue(charset[i])) = k ; } } print_arrayv(transform,m,e); } /*fsm-matcher * find p in t first place */ int fsm_matcher(char *t, char *p,char *charset){ preprocess(p,charset); int m = strlen(p) + 1; int e = strlen(charset); int length_t = strlen(t); int i = 0; int q = 0; for ( i=0 ; i<length_t; ++i){ q = transform[q*e+charvalue(t[i])]; if (q==m-1){ printf("result is %d\n", i - m +2); } } return -1; } void print_arrayv(int *transform,int x,int y){ int i = 0; int j = 0; for(i=0; i < x ; ++i){ for(j=0; j<y; ++j){ printf("%d ",*(transform+i*y+j)); } printf("\n"); } } int main(int argc,char *argv[]){ char *charset="abcdefghijklmnopqrstuvwxyz"; fsm_matcher("asdfaabcdeabcdefg","abcde",charset); return 0; }
C
#include <map> #include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <string> #include <bitset> #include <cstdio> #include <limits> #include <vector> #include <climits> #include <cstring> #include <cstdlib> #include <fstream> #include <numeric> #include <sstream> #include <iostream> #include <algorithm> #include <unordered_map> using namespace std; int main(){ int n; int k; int q; cin >> n >> k >> q; vector<int> a(n); for(int a_i = 0;a_i < n;a_i++){ cin >> a[a_i]; } while(k>0) { int temp; a.erase(a.begin()+0); a.push_back(temp); --k; } for(int a0 = 0; a0 < q; a0++){ int m; cin >> m; cout<<a[m]<<endl; } return 0; }
C
#include<stdio.h> void main() { int n,i,j,temp; printf("enter the number of values"); scanf("%d",&n); int a[n]; for(i=0;i<n;i++) scanf("%d",&a[i]); for(i=0;i<n;i++) { temp=a[i]; for(j=i;j>0;j--) { if(a[j-1]>temp) { a[j]=a[j-1]; a[j-1]=temp; } } } for(i=0;i<n;i++) printf("%d\n",a[i]); }
C
#include <assert.h> #include "grid.h" #define SIZE_X 3231 #define SIZE_Y 1234 int main() { grid_t* grid1 = grid_create(SIZE_X, SIZE_Y, 0); assert(grid1 != NULL); assert(grid1->data != NULL); assert(grid1->width == SIZE_X); assert(grid1->height == SIZE_Y); assert(grid1->padding == 0); assert(grid1->width_padded == SIZE_X); assert(grid1->height_padded == SIZE_Y); for (int j = 0; j < SIZE_Y; j++) { for (int i = 0; i < SIZE_X; i++) { *grid_get_cell(grid1, i, j) = i + j * SIZE_X; } } grid_t* grid2 = grid_clone(grid1); assert(grid2 != NULL); assert(grid2->data != NULL); assert(grid2->width == SIZE_X); assert(grid2->height == SIZE_Y); assert(grid2->padding == 0); assert(grid2->width_padded == SIZE_X); assert(grid2->height_padded == SIZE_Y); for (int j = 0; j < SIZE_Y; j++) { for (int i = 0; i < SIZE_X; i++) { assert(*grid_get_cell(grid2, i, j) == i + j * SIZE_X); } } grid_t* grid3 = grid_clone_with_padding(grid2, 1); assert(grid3 != NULL); assert(grid3->data != NULL); assert(grid3->width == SIZE_X); assert(grid3->height == SIZE_Y); assert(grid3->padding == 1); assert(grid3->width_padded == SIZE_X + 2); assert(grid3->height_padded == SIZE_Y + 2); for (int j = 0; j < SIZE_Y; j++) { for (int i = 0; i < SIZE_X; i++) { assert(*grid_get_cell(grid3, i, j) == i + j * SIZE_X); } } grid_t* grid4 = grid_create(SIZE_X / 2, SIZE_Y / 2, 1); assert(grid4 != NULL); assert(grid4->data != NULL); assert(grid4->width == SIZE_X / 2); assert(grid4->height == SIZE_Y / 2); assert(grid4->padding == 1); assert(grid4->width_padded == SIZE_X / 2 + 2); assert(grid4->height_padded == SIZE_Y / 2 + 2); assert(grid_copy_block(grid3, 0, 0, SIZE_X / 2, SIZE_Y / 2, grid4, 0, 0) == 0); for (int j = 0; j < SIZE_Y / 2; j++) { for (int i = 0; i < SIZE_X / 2; i++) { assert(*grid_get_cell(grid4, i, j) == i + j * SIZE_X); } } assert(grid_set(grid4, 1420.0) == 0); for (int j = 0; j < SIZE_Y / 2 + 2; j++) { for (int i = 0; i < SIZE_X / 2 + 2; i++) { assert(*grid_get_cell_padded(grid4, i, j) == 1420.0); } } for (int j = 0; j < SIZE_Y / 2; j++) { for (int i = 0; i < SIZE_X / 2; i++) { *grid_get_cell(grid4, i, j) = 420.0; } } *grid_get_cell_padded(grid4, 0, 0) = 420.0; *grid_get_cell_padded(grid4, SIZE_X / 2 + 1, 0) = 420.0; *grid_get_cell_padded(grid4, SIZE_X / 2 + 1, SIZE_Y / 2 + 1) = 420.0; *grid_get_cell_padded(grid4, 0, SIZE_Y / 2 + 1) = 420.0; assert(grid_set_padding_from_inner_bound(grid4) == 0); for (int j = 0; j < SIZE_Y / 2 + 2; j++) { for (int i = 0; i < SIZE_X / 2 + 2; i++) { assert(*grid_get_cell_padded(grid4, i, j) == 420.0); } } assert(grid_multiply(grid4, 2.0) == 0); for (int j = 0; j < SIZE_Y / 2 + 2; j++) { for (int i = 0; i < SIZE_X / 2 + 2; i++) { assert(*grid_get_cell_padded(grid4, i, j) == 420.0 * 2.0); } } *grid_get_cell(grid4, SIZE_X / 4, SIZE_Y / 4) = 2000.0; assert(grid_max(grid4) == 2000.0); /* TODO: test `grid_copy_inner_border` */ grid_destroy(grid1); grid_destroy(grid2); grid_destroy(grid3); grid_destroy(grid4); }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #include <linux/stat.h> #include <fcntl.h> #include <string.h> #define SERWERFIFO "serwerfifo" #define KLIENTFIFO "klientfifo" #define PERM 0777 int main(int argc, char const *argv[]) { FILE *input; int output, licz=20; char liczba[70]; char *home = getenv("HOME"),tekst[100], bufor[70]; int i=0; if(argc != 2){ printf("Brak parametru!\n"); exit(1); } strcat(tekst, argv[1]); strcat(tekst, home); while (tekst[i]!='\0') { i+=1; } if((output = open(SERWERFIFO, O_WRONLY|O_CREAT|O_TRUNC, PERM)) == -1) { return(-2); } sprintf(liczba, "%d%s", i, tekst); write(output, liczba, licz); close(output); input = fopen(KLIENTFIFO, "r"); fgets(bufor, 70, input); fclose(input); printf("%s\n", bufor); return 0; }
C
#include "main.h" void main() { getNumber(); printFib(); getch(); } void getNumber() { printf("Enter your number: "); scanf_s("%d", &number); } int calcFib(int count) { if (count < 2) return 1; else return calcFib(count - 1) + calcFib(count - 2); } void printFib() { printf("%d Fibonacci number is %d", number, calcFib(number)); }
C
#include <stdlib.h> #include <stdio.h> #include <assert.h> #include "mtree.h" #include "cursor.h" #include "error.h" #include "utils.h" #include "_tree.h" #define CHILD(tree, depth, node, i) _TREE_CHILD(tree, depth, node, i, MTreeNode) #define ROOT(tree) _TREE_ROOT(tree, MTreeNode) #define TREE(node) _TREE_TREE(node) static inline const MTree* node_get_tree(const MTree* tree, MTreeNode* node) { return tree->compressed ? (MTree*)_TREE_TREE(node) : tree; } MTreeNode* node_create(MTree* tree, unsigned int depth){ return (MTreeNode*)_tree_node_create((_Tree*)tree, depth); } MTreeNode* node_copy(MTree* tree, MTreeNode* base, unsigned int depth){ return (MTreeNode*)_tree_node_copy((_Tree*)tree, (_TreeNode*)base, depth); } void node_delete(MTree* tree, MTreeNode* node, unsigned int depth) { if (node == NULL || node_get_tree(tree, node) != tree) { return; } if (depth != 0) { for(unsigned int i = 0; i < tree->order; i++) { node_delete(tree, CHILD(tree, depth, node, i), depth - 1); } } free(node); } size_t node_size(MTree* tree, MTreeNode* node, unsigned int depth) { if(node == NULL || node_get_tree(tree, node) != tree){ return 0; } if (depth == 0) { return sizeof(MTreeNode) + (tree->leaf_order - 1) * sizeof(void*); } size_t size = sizeof(*node); for(unsigned int i = 0; i < tree->order; i++) { size += node_size(tree, CHILD(tree, depth, node, i), depth - 1); } return size; } void node_dump(const MTree* tree, MTreeNode* node, unsigned int depth, unsigned int indent){ for(int i = 0; i < indent; i++){ printf(" "); } if(node == NULL){ printf("NULL\n"); return; } if(depth == 0){ printf("<%p> ", node); for(int i = 0; i < tree->leaf_order; i++){ void* value = CHILD(tree, depth, node, i); if (value == NULL){ printf("-, "); } else{ printf("%lu, ", (uintptr_t)value); } } printf("\n"); } else{ printf("<%p> tree=%p\n", node, node_get_tree(tree, node)); for(unsigned int i = 0; i < tree->order; i++) { node_dump(tree, CHILD(tree, depth, node, i), depth - 1, indent + 1); } } } MTree* mtree_create(size_t order, size_t leaf_order, bool compressed, MTree* base) { assert(compressed || base == NULL); //printf("mtree_create()\n"); MTree* tree = malloc(sizeof(*tree)); tree->order = order; tree->leaf_order = leaf_order; tree->compressed = compressed; tree->log_order = log2i(order); tree->log_leaf_order = log2i(leaf_order); tree->data_size = compressed ? sizeof(MTree*) : 0; tree->leaf_data_size = tree->data_size; assert(tree->order == (1 << tree->log_order)); assert(tree->leaf_order == (1 << tree->log_leaf_order)); if (base != NULL) { ROOT(tree) = node_copy(tree, ROOT(base), 0); tree->depth = base->depth; } else{ ROOT(tree) = node_create(tree, 0); tree->depth = 1; } return tree; } size_t mtree_capacity(MTree* tree){ return tree->order * (1 << tree->depth); } unsigned int get_child_index(MTree* tree, uintptr_t x, int depth) { const uintptr_t mask = (1 << tree->log_order) - 1; size_t i = tree->log_order * depth; return (x & (mask << i)) >> i; } void mtree_insert(MTree* tree, uintptr_t key, const void* value) { //printf("mtree_insert()\n"); size_t capacity = mtree_capacity(tree); while(key >= capacity){ MTreeNode* new_root = node_create(tree, tree->depth); CHILD(tree, tree->depth, new_root, 0) = ROOT(tree); ROOT(tree) = new_root; tree->depth += 1; capacity *= tree->order; } uintptr_t x = (key - 1) / tree->leaf_order; MTreeNode* node = ROOT(tree); for(int i = tree->depth - 1; i >= 0; i--) { unsigned int child_index = get_child_index(tree, x, i); MTreeNode* child = CHILD(tree, i, node, child_index); if (child == NULL){ child = node_create(tree, i); CHILD(tree, i, node, child_index) = child; } if (node_get_tree(tree, child) != tree) { child = node_copy(tree, child, i); CHILD(tree, i, node, child_index) = child; } node = child; } CHILD(tree, 0, node, (key - 1) % tree->leaf_order) = (MTreeNode*)value; } ice_t mtree_get(MTree* tree, uintptr_t key, void** value){ //printf("mtree_get()\n"); if (key > mtree_capacity(tree)){ *value = NULL; return ICE_DOCUMENT_DOES_NOT_EXIST; } MTreeNode* node = ROOT(tree); uintptr_t x = (key - 1) / tree->leaf_order; for(int i = tree->depth - 1; i >= 0; i--) { unsigned int child_index = get_child_index(tree, x, i); MTreeNode* child = CHILD(tree, i, node, child_index); if (child == NULL){ return ICE_DOCUMENT_DOES_NOT_EXIST; } node = child; } *value = CHILD(tree, 0, node, (key - 1) % tree->leaf_order); return ICE_OK; } void mtree_delete(MTree* tree) { node_delete(tree, ROOT(tree), tree->depth); free(tree); } size_t mtree_size(MTree* tree) { return sizeof(*tree) + node_size(tree, ROOT(tree), tree->depth); } void mtree_dump(MTree* tree){ node_dump(tree, ROOT(tree), tree->depth, 0); } void mtree_walk(MTree* tree, TreeWalkCallback callback) { _tree_walk((_Tree*)tree, callback); } Cursor* mtree_cursor(MTree* tree) { return _tree_cursor((_Tree*)tree); }
C
/******************* Problem definition **********************************/ /* Implement a program that it shows the message "Hello World" on screen. */ /*************************************************************************/ /* Here, you must include the required libraries */ #include <stdio.h> void main( ){ int x=3,y=2,z=5; int r; r=x+y+z; printf("The sum of 3, 2 and 5 is %d", r); }
C
#include <stdio.h> #include <stdlib.h> const int RED = 0; const int BLACK = 1; typedef struct rb_node rb_node; struct rb_node{ rb_node* lchild, *rchild, *parent; int key, colour; }; rb_node* root; rb_node* get_node(rb_node* parent, int key); void rb_insert(int key); rb_node* rb_search(int key); void rb_delete(int key); rb_node* clock_wise(rb_node* node); rb_node* counter_clock_wise(rb_node* node); void show_rb_tree(rb_node* node); rb_node* get_node(rb_node* parent, int key){ rb_node *tmp = (rb_node*)malloc(sizeof(rb_node)); tmp->key = key; tmp->colour = RED; tmp->parent = parent; tmp->lchild = tmp->rchild = NULL; return tmp; } rb_node* clock_wise(rb_node* node){ if(node == NULL || node->lchild == NULL) return NULL; rb_node *rb_1=node, *rb_2=node->lchild, *rb_3=node->lchild->rchild; if(rb_1->parent != NULL){ if(rb_1->parent->lchild == rb_1) rb_1->parent->lchild = rb_2; else rb_1->parent->rchild = rb_2; }else if(rb_1 == root){ root = rb_2; } rb_2->parent = rb_1->parent; rb_1->parent = rb_2; rb_2->rchild = rb_1; rb_1->lchild = rb_3; if(rb_3 != NULL)rb_3->parent = rb_1; return rb_2; } rb_node* counter_clock_wise(rb_node* node){ if(node == NULL || node->rchild == NULL) return NULL; rb_node *rb_1=node, *rb_2=node->rchild, *rb_3=node->rchild->lchild; if(rb_1->parent != NULL){ if(rb_1->parent->lchild == rb_1) rb_1->parent->lchild = rb_2; else rb_1->parent->rchild = rb_2; } else if(rb_1 == root){ root = rb_2; } rb_2->parent = rb_1->parent; rb_1->parent = rb_2; rb_2->lchild = rb_1; rb_1->rchild = rb_3; if(rb_3 != NULL)rb_3->parent = rb_1; return rb_2; } rb_node* rb_search(int key){ rb_node *p = root; while(p != NULL){ if(key < p->key) p = p->lchild; else if(key > p->key) p = p->rchild; else break; } return p; } void rb_insert(int key){ rb_node *p=root, *q=NULL; if(root == NULL){ root = get_node(NULL, key); root->colour = BLACK; return; } while(p != NULL){ q = p; if(key < p->key) p = p->lchild; else if(key > p->key) p = p->rchild; else return; } if(key < q->key) q->lchild = get_node(q, key); else q->rchild = get_node(q, key); while(q != NULL && q->colour == RED){ p = q->parent;//p won't null, or BUG. if(p->lchild == q){ if(q->rchild != NULL && q->rchild->colour == RED) counter_clock_wise(q); q = clock_wise(p); q->lchild->colour = BLACK; } else{ if(q->lchild != NULL && q->lchild->colour == RED) clock_wise(q); q = counter_clock_wise(p); q->rchild->colour = BLACK; } q = q->parent; } root->colour = BLACK; } void show_rb_tree(rb_node* node){ if(node == NULL) return; printf("(%d,%d)\n", node->key, node->colour); if(node->lchild != NULL){ printf("[-1]\n"); show_rb_tree(node->lchild); } if(node->rchild != NULL){ printf("[1]\n"); show_rb_tree(node->rchild); } printf("[0]\n"); } void rb_delete(int key){ rb_node *v = rb_search(key), *u, *p, *c, *b; int tmp; //ûҵɾڵ㣬ֱӷ if(v == NULL) return; u = v; //ڵҽڵ㶼ڣҵ滻ڵu if(v->lchild != NULL && v->rchild != NULL){ u = v->rchild; while(u->lchild != NULL){ u = u->lchild; } tmp = u->key; u->key = v->key;//뱻ɾڵݽʹתΪɾ滻ڵ case3תΪcase2 v->key = tmp; } //u is the node to free. if(u->lchild != NULL) c = u->lchild; // ɾڵӴʱc= else c = u->rchild; //c = Ҷ p = u->parent;//ȡɾڵĸڵ if(p != NULL){ //remove u from rb_tree. if(p->lchild == u) p->lchild = c; else p->rchild = c; } else{ //u is root. root = c; free((void*)u); return; } //u is not root and u is RED, this will not unbalance. if(u->colour == RED){ free((void*)u); return; } free((void*)u); u = c; //u is the first node to balance. while(u != root){ if(u != NULL && u->colour == RED){ //if u is RED, change it to BLACK can finsh. u->colour = BLACK; return; } if(u == p->lchild) b = p->rchild; else b = p->lchild; printf("%d\n", b->key); //b is borther of u. b can't be null, or the rb_tree is must not balance. if(b->colour == BLACK){ //If b's son is RED, rotate the node. if(b->lchild != NULL && b->lchild->colour == RED){ if(u == p->lchild){ b = clock_wise(b); b->colour = BLACK; b->rchild->colour = RED; p = counter_clock_wise(p); p->colour = p->lchild->colour; p->lchild->colour = BLACK; p->rchild->colour = BLACK; } else{ p = clock_wise(p); p->colour = p->rchild->colour; p->rchild->colour = BLACK; p->lchild->colour = BLACK; } return; } else if(b->rchild != NULL && b->rchild->colour == RED){ if(u == p->rchild){ b = counter_clock_wise(b); b->colour = BLACK; b->lchild->colour = RED; p = clock_wise(p); p->colour = p->rchild->colour; p->rchild->colour = BLACK; p->lchild->colour = BLACK; } else{ p = counter_clock_wise(p); p->colour = p->lchild->colour; p->lchild->colour = BLACK; p->rchild->colour = BLACK; } return; } else{//if b's sons are BLACK, make b RED and move up u. b->colour = RED; u = p; p = u->parent; continue; } } else{ if(u == p->lchild){ p = counter_clock_wise(p); p->colour = BLACK; p->lchild->colour = RED; p = p->lchild; } else{ p = clock_wise(p); p->colour = BLACK; p->rchild->colour = RED; p = p->rchild; } } } root->colour = BLACK; } int main(){ int i; root = NULL; for(i = 1; i <= 10; i++){ rb_insert(i); } rb_delete(9); rb_delete(3); rb_delete(7); show_rb_tree(root); printf("\n"); return 0; }
C
/* * EEPROM_INT.c * * Created: 28/04/2020 23:37:28 * Author: sony */ #include "EEPROM_INT.h" #include "EEPROM_INT_CFG.h" #include "avr/io.h" #define IDLE 1 #define BUSY 2 #define DONE_WR 3 #define DONE_RD 4 static uint8_t EEINT_SM1; static uint8_t EEINT_SM2; void EEINT_Init(void) { EEINT_SM1 = IDLE; EEINT_SM2 = IDLE; } void EEPROM_WriteByte(uint16_t au16_EEPROM_Address, uint8_t au8_EEPROM_Data) { while (EECR & (1 << EEWE)) ; // Wait Until The Last Write Operation IS Complete EEAR = au16_EEPROM_Address; EEDR = au8_EEPROM_Data; EECR |= (1 << EEMWE); // EEPROM Master Write Enable EECR |= (1 << EEWE); // Start eeprom write by setting EEWE } uint8_t EEPROM_ReadByte(uint16_t au16_EEPROM_Address) { while (EECR & (1 << EEWE)) ; // Wait Until The Last Operation IS Complete EEAR = au16_EEPROM_Address; EECR |= (1 << EERE); // start EEPROM read by setting EERE return EEDR; // Return data from the memory location } static void EEPROM_WriteBytes(uint16_t au16_EEPROM_Address, uint8_t *u8ptr_Data, uint16_t u16_DataLength) { while (u16_DataLength != 0) { EEPROM_WriteByte(au16_EEPROM_Address, *u8ptr_Data); au16_EEPROM_Address++; u8ptr_Data++; u16_DataLength--; } } static void EEPROM_ReadBytes(uint16_t au16_EEPROM_Address, uint8_t *u8ptr_Data, uint16_t u16_DataLength) { while (u16_DataLength != 0) { *u8ptr_Data = EEPROM_ReadByte(au16_EEPROM_Address); //Read a byte from EEPROM to RAM au16_EEPROM_Address++; //Increment the EEPROM Address u8ptr_Data++; //Increment the RAM Address u16_DataLength--; //Decrement NoOfBytes after Reading each Byte } } EEINT_CheckType EEINT_ReqWrite(unsigned char StartAddress, const unsigned char *DataPtr, unsigned char Length) { EEINT_CheckType EEINT_Status = EEINT_BUSY; EEINT_SM1 = BUSY; if (DataPtr != ((void *)0)) { if (Length < EEINT_MAX_SIZE) { // Continuously Write The Data Bytes EEPROM_WriteBytes(StartAddress, (unsigned char *)DataPtr, Length); EEINT_Status = EEINT_OK; EEINT_SM1 = DONE_WR; } else { // Memory Size Limit Exceeded EEINT_Status = EEINT_NOK; } } else { // Non-Valid Data Pointer Is Passed EEINT_Status = EEINT_NOK; } return EEINT_Status; } EEINT_CheckType EEINT_ReqRead(unsigned char StartAddress, unsigned char *DataPtr, unsigned char Length) { EEINT_CheckType EEINT_Status = EEINT_BUSY; EEINT_SM2 = BUSY; if (DataPtr != ((void *)0)) { if (Length < EEINT_MAX_SIZE) { // Continuously Read The Data Bytes EEPROM_ReadBytes(StartAddress, DataPtr, Length); EEINT_Status = EEINT_OK; EEINT_SM2 = DONE_RD; } else { // Memory Size Limit Exceeded EEINT_Status = EEINT_NOK; } } else { // Non-Valid Data Pointer Is Passed EEINT_Status = EEINT_NOK; } return EEINT_Status; } void EEINT_Main(void) { // Done Writing State if (EEINT_SM1 == DONE_WR) { EEINT_SM1 = IDLE; EEINT_ConfigParam.WriteDoneCbkPtr(); } else if (EEINT_SM1 == EEINT_NOK) { EEINT_ConfigParam.WriteDoneCbkPtr(); } // Done Reading State if (EEINT_SM2 == DONE_RD) { EEINT_SM1 = IDLE; EEINT_ConfigParam.ReadDoneCbkPtr(); } else if (EEINT_SM2 == EEINT_NOK) { EEINT_ConfigParam.ReadDoneCbkPtr(); } }
C
#define F_CPU 8000000 #include <avr/io.h> #include <util/delay.h> #include <avr/interrupt.h> #define sbi(x,y) x |= _BV(y) //set bit #define cbi(x,y) x &= ~(_BV(y)) //clear bit #define tbi(x,y) x ^= _BV(y) //toggle bit #define is_high(x,y) ((x & _BV(y)) == _BV(y)) typedef struct { unsigned char data; unsigned int delay ; } PATTERN_STRUCT; // 7 seg // PORTD dp G F E D C B A // y y y y x x x x PATTERN_STRUCT pattern[] = { {0b00000001, 150}, {0b00000010, 150}, {0b00000100, 150}, {0b00001000, 150}, {0b00010000, 150}, {0b00100000, 150}, {0b00000001, 50}, {0b00000010, 50}, {0b00000100, 50}, {0b00001000, 50}, {0b00010000, 50}, {0b00100000, 50}, {0b00000001, 300}, {0b00000010, 300}, {0b00000100, 300}, {0b00001000, 300}, {0b00010000, 300}, {0b00100000, 300}, {0b00000001, 50}, {0b00000010, 50}, {0b00000100, 50}, {0b00001000, 50}, {0b00010000, 50}, {0b00100000, 50}, {0x0, 0} }; // A b c d e f g dp const unsigned char digits[17] = { 0b00111111, // 0 0b00000110, // 1 0b01011011, // 2 0b01001111, // 3 0b01100110, // 4 0b01101101, // 5 0b01111101, // 6 0b00000111, // 7 0b01111111, // 8 0b01101111, // 9 0b01110111, // A 0b01111100, // B 0b00111001, // C 0b01011110, // D 0b01111001, // E 0b01110001, // F 0b11111001 // Error }; /******************************************************************/ void wait( int ms ) /* short: Busy wait number of millisecs inputs: int ms (Number of millisecs to busy wait) outputs: notes: Busy wait, not very accurate. Make sure (external) clock value is set. This is used by _delay_ms inside util/delay.h Version : DMK, Initial code *******************************************************************/ { for (int i=0; i<ms; i++) { _delay_ms( 1 ); // library function (max 30 ms at 8MHz) } } void display(int digit) { if(digit > 16) { PORTD = digits[16]; } else { PORTC = digits[digit]; } } int count = 0; ISR( INT0_vect ) { } ISR( INT1_vect ) { } /******************************************************************/ int main( void ) /* short: main() loop, entry point of executable inputs: outputs: notes: Version : DMK, Initial code *******************************************************************/ { DDRC = 0xFF; DDRD = 0xF0; EICRA |= 0x0B; // INT1 falling edge, INT0 rising edge EIMSK |= 0x03; // Enable INT1 & INT0 sei(); while (1) { int index = 0; while( pattern[index].delay != 0 ) { PORTC = pattern[index].data; wait(pattern[index].delay); index++; } } }
C
#include <stdio.h> #include <stdlib.h> int ordemCrescente_PAR(int N); int main (){ int N = 10; ordemCrescente_PAR (N); } int ordemCrescente_PAR(int N){ if ( N < 0 ){ return 0; } else { ordemCrescente_PAR( N - 1 ); printf("%d\n", N); } return 0; }
C
// SPDX-License-Identifier: BSD-2-Clause-Views /* * Copyright (c) 2023 The Regents of the University of California */ #include "mqnic.h" #include <stdio.h> #include <stdlib.h> struct mqnic_res *mqnic_res_open(unsigned int count, volatile uint8_t *base, unsigned int stride) { struct mqnic_res *res = calloc(1, sizeof(struct mqnic_res)); if (!res) return NULL; res->count = count; res->base = base; res->stride = stride; return res; } void mqnic_res_close(struct mqnic_res *res) { if (!res) return; free(res); } unsigned int mqnic_res_get_count(struct mqnic_res *res) { return res->count; } volatile uint8_t *mqnic_res_get_addr(struct mqnic_res *res, int index) { if (index < 0 || index >= res->count) return NULL; return res->base + index * res->stride; }
C
#include<stdio.h> void main(){ int x,y; printf("Enter amount:"); scanf("%d", &x); y= x/500; printf("500: %d\n", y); x = x - (y*500); y = x/100; printf("100: %d\n", y); x = x - (y*100); y= x/50; printf("50: %d\n", y); x = x - (y*50); y = x/20; printf("20: %d\n", y); x = x - (y*20); y= x/10; printf("10: %d\n", y); x = x - (y*10); y = x/5; printf("5: %d\n", y); x = x - (y*5); y = x/2; printf("2: %d\n", y); x = x - (y*2); y = x/1; printf("1: %d\n", y); }
C
/* ˻Ʈ α׷(ҽ) */ #include <stdio.h> #include <stdlib.h> #include "Member.h" #include "BinTree.h" /*--- ˻ ---*/ BinNode* Search(BinNode* p, const Member* x); /*--- ---*/ BinNode* Add(BinNode* p, const Member* x); /*--- ---*/ int Remove(BinNode** root, const Member* x); /*--- 带 ---*/ void PrintTree(const BinNode* p); /*--- ---*/ void FreeTree(BinNode* p);
C
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/msg.h> #include <fcntl.h> #include <signal.h> #include <errno.h> #include "structs.h" #include "parser.h" ServerEnv serverEnv; int loadFromFile() { int i; ServerEnv* env = &serverEnv; FILE* file = NULL; if ((file = fopen(USER_LIST_FILENAME, "r")) == NULL) { perror("Error Raised.\n"); exit(EXIT_FAILURE); } fread(&(env->userCount), sizeof(int), 1, file); fread(env->userList, sizeof(User), env->userCount, file); fclose(file); return 1; } int saveToFile() { FILE* file = NULL; ServerEnv* env = &serverEnv; if ((file = fopen(USER_LIST_FILENAME, "w+")) == NULL) { perror("Error Raised.\n"); exit(EXIT_FAILURE); } fwrite(&(env->userCount), sizeof(int), 1, file); fwrite(env->userList, sizeof(User), env->userCount, file); fclose(file); return 1; } void beforeExit(int sig) { saveToFile(); exit(sig); } int main(int argc, char * argv[]) { pid_t pid; pid = fork(); if (pid < 0) { perror("Fork\n"); exit(EXIT_FAILURE); } if (pid != 0) { exit(0); } pid = setsid(); if (pid < -1) { perror("Setsid\n"); exit(EXIT_FAILURE); } int dev_fd = open("/dev/null", O_RDWR, 0); if (dev_fd == -1) { dup2(dev_fd, STDIN_FILENO); dup2(dev_fd, STDOUT_FILENO); dup2(dev_fd, STDERR_FILENO); if (dev_fd > 2) { close(dev_fd); } } umask(0000); int res, client_fd; Protocol protocol; protocol.msg_type = MSG_TYPE_COMMON; Response* response; serverEnv.userCount = 0; loadFromFile(); signal(SIGKILL, beforeExit); signal(SIGINT, beforeExit); signal(SIGTERM, beforeExit); serverEnv.serverMSGID = msgget((key_t) SERVER_MSGID, 0666 | IPC_CREAT); if (serverEnv.serverMSGID == -1) { fprintf(stderr, "Msgget(server) failed with errno: %d\n", errno); exit(EXIT_FAILURE); } printf("\nServer is runing!\n"); while(1) { if (msgrcv(serverEnv.serverMSGID, (void*)&protocol, SIZE_OF_PROTOCOL, MSG_TYPE_COMMON, 0) == -1) { fprintf(stderr, "msgrcv failed with errno: %d\n", errno); exit(EXIT_FAILURE); } else { printf("Protocol: %d - %s", protocol.pid, protocol.msg); response = parse(&serverEnv, &protocol); int msgid = msgget((key_t) protocol.pid, 0666); if (msgsnd(msgid, (void*)response, SIZE_OF_RESPONSE, 0) == -1) { fprintf(stderr, "MSGSND failed\n"); exit(EXIT_FAILURE); } free(response); } } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* push_swap.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: smignard <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/01/24 14:46:26 by smignard #+# #+# */ /* Updated: 2015/02/26 16:24:28 by smignard ### ########.fr */ /* */ /* ************************************************************************** */ #include "push_swap.h" t_chain *ft_create_elem(char *data) { t_chain *new; if (new = (t_chain *)malloc(sizeof(t_chain))) { new->data = data; new->next = NULL; } return (new); } void ft_tri(t_chain *chaine_a, t_chain *chaine_b, begin_list) { int i; int midd; int poss; i = 0; midd = 0; while(chain = chaine->next) { // chercher chiffre le plus grand //if (chain > chain->next) // poss = chain; //chain = chain->next; i++; chain = chain->next; } begin_list = chain; while(midd < (i / 2)) { midd++; chain = chain->next; } } void ft_remplissage(char *str, t_chain *pile_a) { t_chain *pile_a; static t_chain *begin_list_a; if (pile_a = ft_create_elem(str)) { if (begin_list_a == NULL) begin_list_a = pile_a; else while (pile_a->next != NULL) { pile_a->next = pile_a; pile_a = pile_a->next; } ft_tri(begin_list_a); } } int main(int argc, char **argv) { int i; t_chain *pile_a; i = 0; t_chain = NULL while (i++ < argc) ft_remplissage(argv[i], pile_a); return (0); }
C
#include <stdio.h> #include <stdlib.h> #include <conio.h> #include <math.h> int punto1(); int punto2(); int punto3(); int punto4(); int punto5(); int punto6(); int punto7(); int punto8(); int punto9(); int punto10(); int punto11(); int punto12(); int punto13(); int main(int argc, char const *argv[]) { punto13(); return 0; } int punto1(){ int val1, val2; printf("ingrese el primer valor: "); scanf("%d", &val1); printf("ingrese el segundo valor: "); scanf("%d", &val2); val1 == val2? printf("son iguales"): printf("son distintos") ; return 0; } int punto2(){ int val; printf("ingrese el valor: "); scanf("%d", &val); if(val == 0){ printf("el valor es 0"); }else if (val > 0){ printf("es mayor a 0"); } else { printf("es menor a 0"); } return 0; } int punto3(){ int val1,val2; printf("ingrese el valor 1: "); scanf("%d", &val1); printf("ingrese el valor 2: "); scanf("%d", &val2); if(val1 > val2){ printf("el producto es: %d", val1*val2 ); }else if(val1 ==val2){ printf("Los valores son iguales"); } return 0; } int punto4(){ int val1,val2; printf("ingrese el valor 1: "); scanf("%d", &val1); printf("ingrese el valor 2: "); scanf("%d", &val2); val1 > val2? printf("%d", val1-val2): printf("%d", val2-val1) ; return 0; } int punto5(){ int a,b,c; printf("ingrese el lado a: "); scanf("%d", &a); printf("ingrese el lado b: "); scanf("%d", &b); printf("ingrese el lado c: "); scanf("%d", &c); if(!((a+b)>c && (a+c)> b && (c+b)>a)){ printf("no es un triangulo"); } if (a == b && a == c ){ printf("El triangulo es equilatero"); } else if (a != b && a != c && b != c) { printf("El triangulo es escaleno"); } else { printf("El triangulo es isoceles"); } return 0; } int punto6(){ int val1,val2,val3,promedio; printf("ingrese el valor 1: "); scanf("%d", &val1); printf("ingrese el valor 2: "); scanf("%d", &val2); printf("ingrese el valor 3: "); scanf("%d", &val3); promedio=(val1 + val2 + val3)/3; if (val1 > promedio) { printf("el valor mayor al promedio es: %d",val1); } else if (val2 > promedio){ printf("el valor mayor al promedio es: %d",val2); } else { printf("el valor mayor al promedio es: %d",val3); } return 0; } int punto7(){ int val1,val2,val3,val4; printf("ingrese el valor 1: "); scanf("%d", &val1); printf("ingrese el valor 2: "); scanf("%d", &val2); printf("ingrese el valor 3: "); scanf("%d", &val3); printf("ingrese el valor 4: "); scanf("%d", &val4); if ((val1+val2) > (val3 + val4)) { printf("la suma de los primeros 2 numeros es mayor"); }else{ printf("la suma de los segundos 2 numeros es mayor"); } return 0; } int punto8(){ int edad1, edad2; float altura1, altura2; printf("la edad de la primer persona: "); scanf("%d", &edad1); printf("ingrese la altura de la primer persona: "); scanf("%f", &altura1); printf("la edad de la segunda persona: "); scanf("%d", &edad2); printf("ingrese la altura de la segunda persona: "); scanf("%f", &altura2); if (edad1 > edad2) { printf("la persona con mayor edad mide: %.2f", altura1); }else{ printf("la persona con mayor edad mide: %.2f", altura2); } return 0; } int punto9(){ int hs,valorPorHora; printf("Ingrese lass horas trabajadas: "); scanf("%d", &hs); printf("ingrese el precio por hora: "); scanf("%f", &valorPorHora); if (hs > 50 && hs < 150) { printf("El sueldo es %d", (hs * valorPorHora)+ 100); } else if (hs > 150){ printf("El sueldo es %d", (hs * valorPorHora)+ 200); }else { printf("El sueldo es %d", hs * valorPorHora); } return 0; } int punto10(){ int dia,mes,anio; printf("Ingrese el dia: "); scanf("%d", &dia); printf("ingrese el mes: "); scanf("%d", &mes); printf("ingrese el anio: "); scanf("%d", &anio); if ((mes == 1 ||mes == 3 || mes == 5 || mes == 7 || mes == 8 || mes == 10 || mes == 12) && (dia > 0 && dia <= 31)) { printf("valido"); } else if((mes == 4 ||mes == 6 || mes == 9 ||mes == 11) && (dia > 0 && dia <= 30)){ printf("valido"); } else if(((mes == 2) && (anio % 4 == 0) && (dia > 0 && dia <= 29)) || ((mes == 2) && (anio % 4 != 0) && (dia > 0 && dia <= 28))){ printf("valido"); }else{ printf("invalido"); } return 0; } int punto11(){ int sueldo,categoria, antiguedad; printf("Ingrese el sueldo: "); scanf("%d", &sueldo); printf("Ingrese el categoria: "); scanf("%d", &categoria); printf("Ingrese el antiguedad: "); scanf("%d", &antiguedad); if(categoria== 1){ sueldo= sueldo + (antiguedad*50); } printf("%d", sueldo); return 0; } int punto12(){ int sueldo,categoria, antiguedad; printf("Ingrese el sueldo: "); scanf("%d", &sueldo); printf("Ingrese el categoria: "); scanf("%d", &categoria); printf("Ingrese el antiguedad: "); scanf("%d", &antiguedad); if(categoria== 1){ sueldo= sueldo + (antiguedad*50); } if (antiguedad > 5) { printf("%d", sueldo); } return 0; } int punto13(){ int horas,categoria; printf("Ingrese las horas: "); scanf("%d", &horas); printf("Ingrese el categoria: "); scanf("%d", &categoria); if(categoria== 1){ printf("el sueldo es %d", horas* 50); }else if(categoria== 2){ printf("el sueldo es %d", horas* 70); } else if(categoria== 3){ printf("el sueldo es %d", horas* 80); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "queue.h" //构建一个队列 bool init_queue(s_queue *queue, int ele_size, void (*free_data)(), void (*visit_data)()) { if (queue == null) { return false; } queue->ele_size = ele_size; queue->free_data = free_data; queue->visit_data = visit_data; queue->header = null; queue->footer = null; return true; } //销毁队列 bool destroy_queue(s_queue *queue) { if (queue == null) { return false; } if (queue->header == null) { return true; } clear_queue(queue); return true; } //清空队列中所有元素 bool clear_queue(s_queue *queue) { if (queue == null) { return false; } //从头节点开始释放 s_node *p = queue->header; while (p != null) { //释放内存 if (queue->free_data != null) { queue->free_data(p->data); } s_node *t = p; p = p->next; free(t); } queue->header = null; queue->footer = null; return true; } //在队列尾追加一个元素 bool queue_in(s_queue *queue, void *e) { if (queue == null || e == null) { return false; } //申请新节点内存 s_node *p_new = (s_node *) malloc(sizeof(s_node)); p_new->data = e; p_new->next = null; if (queue->footer == null) { queue->header = p_new; queue->footer = p_new; return true; } queue->footer->next = p_new; queue->footer = p_new; return true; } //在队列头删除一个元素 bool queue_out(s_queue *queue, void **e) { if (queue == null || queue->header == null) { return false; } s_node *p_del = queue->header; queue->header = queue->header->next; if (queue->footer == p_del) { queue->footer = queue->header->next; } *e = p_del->data; if (queue->free_data != null) { queue->free_data(p_del); } return true; } //对每个元素执行visit操作 bool queue_visit(s_queue *queue) { if (queue == null || queue->header == null) { return false; } if (queue->visit_data == null) { return false; } //顺序访问每一个元素 s_node *p = queue->header; while (p != null) { queue->visit_data(p->data); p = p->next; } return true; }
C
/* * Challenge 111 * Find the binary tree min depth */ #include <stdio.h> int main(int argc, char const *argv[]) { /*Solution */ /* Definition for a binary tree node.*/ struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; }; int minDepth(struct TreeNode* root){ if (root == NULL){ return 0; } if (root->left == NULL){ return minDepth(root->right)+1; } if (root->right == NULL){ return minDepth(root->left)+1; } int left = minDepth(root->left); int right = minDepth(root->right); return (left < right ? left : right) + 1; } return 0; }
C
#include <stdlib.h> #include <stdio.h> #include "binary_trees.h" /** * binary_tree_leaves - counts the leaves of a binary tree * @tree: is a pointer to the root node of the tree * Return: the leaves count of tree, otherwise 0 */ size_t binary_tree_leaves(const binary_tree_t *tree) { size_t lleft = 0, lright = 0; if (tree == NULL) return (0); if (tree->left == NULL && tree->right == NULL) return (1); lleft = binary_tree_leaves(tree->left); lright = binary_tree_leaves(tree->right); return (lleft + lright); }
C
#include <stdio.h> int ok() { // ok if (0) { goto ONE; goto ONE; } printf("did not go to one\n"); return 0; ONE: printf("went to one\n"); return 1; } int main(int argc, char *argv[]) { // ruleid:double_goto if (0) goto ONE; goto ONE; printf("did not go to one\n"); return 0; ONE: printf("went to one\n"); return 1; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* parsing_objects3.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: zjamali <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/11/24 14:29:17 by zjamali #+# #+# */ /* Updated: 2020/11/24 14:30:13 by zjamali ### ########.fr */ /* */ /* ************************************************************************** */ #include "minirt.h" t_obj_properties ft_parsing_sphere_properties(char **sph, t_scene *scene) { t_obj_properties obj; if (sph[1] == NULL || sph[2] == NULL || sph[3] == NULL || sph[4] != NULL) { ft_print_error(scene, "you have to specify just the sphere center \ coordination point,diameter and color."); } obj.origin = ft_split(sph[1], ','); obj.color = ft_split(sph[3], ','); obj.diameter = ft_atod(sph[2]); return (obj); } void parsing_sphere(char **sph, t_scene *scene) { t_obj_properties obj; t_sphere *sphere; t_object *new_object; obj = ft_parsing_sphere_properties(sph, scene); ft_check_sphere(scene, obj); if (!(sphere = (t_sphere*)malloc(sizeof(t_sphere)))) ft_print_error(scene, "alloction error"); ft_memset((void*)sphere, 0, sizeof(t_sphere)); sphere->radius = obj.diameter / 2.0; sphere->origin = ft_parse_coord(obj.origin); sphere->color = ft_parse_color(obj.color); if (!(new_object = (t_object*)malloc(sizeof(t_object)))) ft_print_error(scene, "allocation error"); ft_memset((void*)new_object, 0, sizeof(t_object)); new_object->object_type = 's'; new_object->object = sphere; new_object->origin = sphere->origin; new_object->color = sphere->color; new_object->radius = sphere->radius; new_object->next = NULL; ft_lstadd_back(&scene->objects, new_object); ft_element_can_transforme(scene, 's', new_object); }