text
stringlengths
54
60.6k
<commit_before>9101adbf-2d14-11e5-af21-0401358ea401<commit_msg>9101adc0-2d14-11e5-af21-0401358ea401<commit_after>9101adc0-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>#include <stdio.h> #include <mpi.h> #include <boost/regex.hpp> #include <regex> #include <iostream> #include <string> #include <map> #include <set> #include <algorithm> typedef std::map<std::string, std::set<std::string>> LinkMap; int g_world_size; int g_my_rank; std::string g_filename = "enwiki-20160305-pages-articles.xml"; void parse_file(MPI_File *infile); void regex_test(); void find_links(std::string section, std::string current_title, LinkMap &links); int main(int argc, char** argv) { // Initialize the MPI environment MPI_Init(NULL, NULL); // Get the number of processes MPI_Comm_size(MPI_COMM_WORLD, &g_world_size); // Get the rank of the process MPI_Comm_rank(MPI_COMM_WORLD, &g_my_rank); // Print off a hello world message printf("Hello world from rank %d out of %d processors\n", g_my_rank, g_world_size); // Open up the wikipedia xml file MPI_File infile; MPI_File_open(MPI_COMM_WORLD, (char *)g_filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &infile); // Parse the file parse_file(&infile); if (g_my_rank == 0){ //regex_test(); } // Close the file MPI_File_close(&infile); // Finalize the MPI environment. MPI_Finalize(); return 0; } // Parse the input file: pull out page titles and any links from a page to another void parse_file(MPI_File *infile){ //get file size MPI_Offset filesize; MPI_File_get_size(*infile, &filesize); // the size of each chunk that will be read in at a time // TODO: find an optimal setting for this so that we aren't producing too many read reqeusts int chunk_size = 1000; //get size of the chunk this rank will handle long long int max_size = filesize / g_world_size; // where this rank will stop reading the file (aka where the next rank will start reading) long long int stopping_point = max_size * (g_my_rank + 1); //get the start point for this rank in the file: // subtract chunk_size from the 'logical' start point to make sure // that each node has a title for the links that it finds MPI_Offset offset = std::max(max_size * g_my_rank, max_size * g_my_rank - chunk_size); printf("Rank %d ==> start point: %lld\n", g_my_rank, offset); // the regex to find a tile in the file boost::regex title_regex("<title[^>]*>([^<]+)</title>"); // declare some variables char * chunk; std::string current_title = ""; LinkMap links; // keep going until the offset is in the next ranks group while (offset < stopping_point && links.size() < 100){ // allocate a chunk to read in from the file chunk = (char *)malloc( (chunk_size + 1)*sizeof(char)); // read it in MPI_File_read_at(*infile, offset, chunk, chunk_size, MPI_CHAR, MPI_STATUS_IGNORE); // end the string chunk[chunk_size] = '\0'; // make it a c++ string for convenience std::string chunk_string(chunk); // free the allocated space free(chunk); //std::cout << "reading" << std::endl; //std::cout << chunk_string << std::endl; boost::smatch title_match; // keep looping while there is another title in the the current chunk while (boost::regex_search(chunk_string, title_match, title_regex)){ // if we've already found at least one title, search the first part of the chunk for any links if (current_title != ""){ find_links(title_match.prefix(), current_title, links); } // overwrite current_title with the new one current_title = title_match[1].str(); // initilize the new title's spot in the links map with an empty set links[current_title] = std::set<std::string>(); printf("title %lu: %s\n", links.size(), current_title.c_str()); //std::cout << title_match[0] << std::endl; // set the chunk_string to be everything after the title chunk_string = title_match.suffix(); } // do one last search through the remainder of the chunk for any links if (current_title != ""){ find_links(chunk_string, current_title, links); } offset += chunk_size; } //output the contents of the links map after parsing std::cout << links.size() << std::endl; for (const auto &key : links) { std::cout << key.first << " " << key.second.size() << std::endl; /*for (const auto &val: key.second){ std::cout << " " << val << std::endl; }*/ } } void find_links(std::string section, std::string current_title, LinkMap &links){ //links[current_title].push_back("test"); //std::cout << section << std::endl; boost::regex link_regex("\\[\\[([^\\[\\]]*)\\]\\]"); boost::smatch link_match; while (boost::regex_search(section, link_match, link_regex)){ boost::ssub_match sub_match = link_match[1]; std::string piece = sub_match.str(); //std::cout << piece << '\n'; links[current_title].insert(piece); //std::cout << current_title << " > " << piece << std::endl; section = link_match.suffix().str(); } } void regex_test(){ std::string s ("this <title>abc test def</title> has a submarine as <title>another title</title> subsequence"); boost::smatch m; boost::regex e ("<title[^>]*>([^<]+)</title>"); // matches words beginning by "sub" std::cout << "The following matches and submatches were found:" << std::endl; while (boost::regex_search (s,m,e)) { for (auto x:m) std::cout << x << "\n"; std::cout << std::endl; s = m.suffix().str(); } } <commit_msg>starting to remove regex<commit_after>#include <stdio.h> #include <mpi.h> #include <boost/regex.hpp> #include <regex> #include <iostream> #include <string> #include <map> #include <set> #include <algorithm> typedef std::map<std::string, std::set<std::string>> LinkMap; int g_world_size; int g_my_rank; std::string g_filename = "enwiki-20160305-pages-articles.xml"; void parse_file(MPI_File *infile); void regex_test(); void find_links(std::string section, std::string current_title, LinkMap &links); int main(int argc, char** argv) { // Initialize the MPI environment MPI_Init(NULL, NULL); // Get the number of processes MPI_Comm_size(MPI_COMM_WORLD, &g_world_size); // Get the rank of the process MPI_Comm_rank(MPI_COMM_WORLD, &g_my_rank); // Print off a hello world message printf("Hello world from rank %d out of %d processors\n", g_my_rank, g_world_size); // Open up the wikipedia xml file MPI_File infile; MPI_File_open(MPI_COMM_WORLD, (char *)g_filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &infile); // Parse the file //parse_file(&infile); if (g_my_rank == 0){ regex_test(); } // Close the file MPI_File_close(&infile); // Finalize the MPI environment. MPI_Finalize(); return 0; } // Parse the input file: pull out page titles and any links from a page to another void parse_file(MPI_File *infile){ //get file size MPI_Offset filesize; MPI_File_get_size(*infile, &filesize); // the size of each chunk that will be read in at a time // TODO: find an optimal setting for this so that we aren't producing too many read reqeusts int chunk_size = 1000; //get size of the chunk this rank will handle long long int max_size = filesize / g_world_size; // where this rank will stop reading the file (aka where the next rank will start reading) long long int stopping_point = max_size * (g_my_rank + 1); //get the start point for this rank in the file: // subtract chunk_size from the 'logical' start point to make sure // that each node has a title for the links that it finds MPI_Offset offset = std::max(max_size * g_my_rank, max_size * g_my_rank - chunk_size); printf("Rank %d ==> start point: %lld\n", g_my_rank, offset); // the regex to find a tile in the file boost::regex title_regex("<title[^>]*>([^<]+)</title>"); // declare some variables char * chunk; std::string current_title = ""; LinkMap links; // keep going until the offset is in the next ranks group while (offset < stopping_point && links.size() < 100){ // allocate a chunk to read in from the file chunk = (char *)malloc( (chunk_size + 1)*sizeof(char)); // read it in MPI_File_read_at(*infile, offset, chunk, chunk_size, MPI_CHAR, MPI_STATUS_IGNORE); // end the string chunk[chunk_size] = '\0'; // make it a c++ string for convenience std::string chunk_string(chunk); // free the allocated space free(chunk); //std::cout << "reading" << std::endl; //std::cout << chunk_string << std::endl; boost::smatch title_match; // keep looping while there is another title in the the current chunk while (boost::regex_search(chunk_string, title_match, title_regex)){ // if we've already found at least one title, search the first part of the chunk for any links if (current_title != ""){ find_links(title_match.prefix(), current_title, links); } // overwrite current_title with the new one current_title = title_match[1].str(); // initilize the new title's spot in the links map with an empty set links[current_title] = std::set<std::string>(); printf("title %lu: %s\n", links.size(), current_title.c_str()); //std::cout << title_match[0] << std::endl; // set the chunk_string to be everything after the title chunk_string = title_match.suffix(); } // do one last search through the remainder of the chunk for any links if (current_title != ""){ find_links(chunk_string, current_title, links); } offset += chunk_size; } //output the contents of the links map after parsing std::cout << links.size() << std::endl; for (const auto &key : links) { std::cout << key.first << " " << key.second.size() << std::endl; /*for (const auto &val: key.second){ std::cout << " " << val << std::endl; }*/ } } void find_links(std::string section, std::string current_title, LinkMap &links){ //links[current_title].push_back("test"); //std::cout << section << std::endl; boost::regex link_regex("\\[\\[([^\\[\\]]*)\\]\\]"); boost::smatch link_match; while (boost::regex_search(section, link_match, link_regex)){ boost::ssub_match sub_match = link_match[1]; std::string piece = sub_match.str(); //std::cout << piece << '\n'; links[current_title].insert(piece); //std::cout << current_title << " > " << piece << std::endl; section = link_match.suffix().str(); } } void regex_test(){ std::string chunk_string ("this <title>abc test def</title><title>banana</title>has a submarine as <title>another title</title> subsequence"); /*std::cout << chunk_string << std::endl; std::size_t found_start = chunk_string.find("<title>"); std::size_t found_end = chunk_string.find("</title>"); std::string title = chunk_string.substr(found_start+7, found_end-found_start-7); std::cout << found_start << std::endl; std::cout << found_end << std::endl; std::cout << title << std::endl;;*/ int found_begin, found_end; found_begin = chunk_string.find("<title>"); found_end = chunk_string.find("</title>"); while(found_begin != std::string::npos && found_end != std::string::npos){ std::string new_title = chunk_string.substr(found_begin+7, found_end-found_begin-7); std::cout << "new title: " << new_title << std::endl; std::cout << found_begin - 1 << std::endl; std::string prefix = chunk_string.substr(0, std::max(0, found_begin - 1)); std::cout << "prefix: " << prefix << std::endl; chunk_string = chunk_string.substr(found_end+8); std::cout << "new search string: " << chunk_string << std::endl; std::cout << std::endl; found_begin = chunk_string.find("<title>"); found_end = chunk_string.find("</title>"); } } <|endoftext|>
<commit_before>cb796091-2e4e-11e5-9322-28cfe91dbc4b<commit_msg>cb81a6ee-2e4e-11e5-bec2-28cfe91dbc4b<commit_after>cb81a6ee-2e4e-11e5-bec2-28cfe91dbc4b<|endoftext|>
<commit_before>5c0da9ac-2e3a-11e5-809f-c03896053bdd<commit_msg>5c20bfec-2e3a-11e5-a6ce-c03896053bdd<commit_after>5c20bfec-2e3a-11e5-a6ce-c03896053bdd<|endoftext|>
<commit_before>7e79196b-2d15-11e5-af21-0401358ea401<commit_msg>7e79196c-2d15-11e5-af21-0401358ea401<commit_after>7e79196c-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>f5dd6f0f-2e4e-11e5-8057-28cfe91dbc4b<commit_msg>f5e5938a-2e4e-11e5-b82d-28cfe91dbc4b<commit_after>f5e5938a-2e4e-11e5-b82d-28cfe91dbc4b<|endoftext|>
<commit_before>901729c2-ad5b-11e7-b201-ac87a332f658<commit_msg>new flies<commit_after>90965257-ad5b-11e7-b26d-ac87a332f658<|endoftext|>
<commit_before>5c7d4cf0-2748-11e6-8f61-e0f84713e7b8<commit_msg>GOD DAMNED IT!<commit_after>5c87aec7-2748-11e6-9ff7-e0f84713e7b8<|endoftext|>
<commit_before>d4ebf99c-585a-11e5-9fb2-6c40088e03e4<commit_msg>d4f56482-585a-11e5-bc26-6c40088e03e4<commit_after>d4f56482-585a-11e5-bc26-6c40088e03e4<|endoftext|>
<commit_before>#include <iostream.h> #include <conio.h> #include "quiz.h" void main() { clrscr(); init_ques(); init_ui(); cout << questions[0][1][2].q; getch(); } <commit_msg>Fixed error that was to be fixed earlier<commit_after>#include <iostream.h> #include <conio.h> #include "quiz.h" extern question questions[3][3][3]; void main() { clrscr(); init_ques(); init_ui(); getch(); } <|endoftext|>
<commit_before>/* * AED - 2015 * * Autor: Ferreyra, Maximiliano Gastn. * * Legajjo: 155911-4. * * Fecha: 20150411 */ #include <iostream> using namespace std; int main(){ /* * Declaramos variables que vamos a utilizar durante el programa. */ int num1 = 37; int num2 = 4; float num3 = 35.7; float num4 = 9.4; double num5 = 38.99; double num6 = 21.65; cout << "===============================================================================\n" << endl; cout << "| Trabajo Practico No 1 AED |" << endl; cout << "| \"Tipos de Datos y sus Operaciones Basicas\" |" << endl; cout << "| Alumno: Ferreyra, Maximiliano Gaston || Legajo: 155911-4 |" << endl; cout << "===============================================================================" << endl; cout << "_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n" << endl; // Tipo de datos INT cout << "Tipo de dato: Int" << endl; cout << "_________________\n" << endl; cout << "Suma (num1 + num2): " << num1 + num2 << endl; cout << "Resta (num1 - num2): " << num1 - num2 << endl; cout << "Multiplicacion (num1 * num2): " << num1 * num2 << endl; cout << "Division (num1 / num2): " << num1 / num2 << endl; cout << "Resto de Division Entera (num1 % num2): " << num1 % num2 << "\n" << endl; // Tipo de datos Float cout << "Tipo de dato: Float" << endl; cout << "_________________\n" << endl; cout << "Suma (num3 + num4): " << num3 + num4 << endl; cout << "Resta (num3 - num4): " << num3 - num4 << endl; cout << "Multiplicacion (num3 * num4): " << num3 * num4 << endl; cout << "Division (num3 / num4): " << num3 / num4 << endl; // No se puede obtener un resto de una divisin de datos del tipo Float. // Tipo de datos Double cout << "Tipo de dato: Double" << endl; cout << "_________________\n" << endl; cout << "Suma (num5 + num6): " << num5 + num6 << endl; cout << "Resta (num5 - num6): " << num5 - num6 << endl; cout << "Multiplicacion (num5 * num6): " << num5 * num6 << endl; cout << "Division (num5 / num6): " << num5 / num6 << endl; // No se puede obtener un resto de una divisin de datos del tipo Double. } <commit_msg>Se elimina tipo de datos Float, ya que no se pedía en el enunciado<commit_after>/* * AED - 2015 * * Autor: Ferreyra, Maximiliano Gastn. * * Legajjo: 155911-4. * * Fecha: 20150411 */ #include <iostream> using namespace std; int main(){ /* * Declaramos variables que vamos a utilizar durante el programa. */ int num1 = 37; int num2 = 4; float num3 = 35.7; float num4 = 9.4; double num5 = 38.99; double num6 = 21.65; cout << "===============================================================================\n" << endl; cout << "| Trabajo Practico No 1 AED |" << endl; cout << "| \"Tipos de Datos y sus Operaciones Basicas\" |" << endl; cout << "| Alumno: Ferreyra, Maximiliano Gaston || Legajo: 155911-4 |" << endl; cout << "===============================================================================" << endl; cout << "_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n" << endl; // Tipo de datos INT cout << "Tipo de dato: Int" << endl; cout << "_________________\n" << endl; cout << "Suma (num1 + num2): " << num1 + num2 << endl; cout << "Resta (num1 - num2): " << num1 - num2 << endl; cout << "Multiplicacion (num1 * num2): " << num1 * num2 << endl; cout << "Division (num1 / num2): " << num1 / num2 << endl; cout << "Resto de Division Entera (num1 % num2): " << num1 % num2 << "\n" << endl; // Tipo de datos Double cout << "Tipo de dato: Double" << endl; cout << "_________________\n" << endl; cout << "Suma (num5 + num6): " << num5 + num6 << endl; cout << "Resta (num5 - num6): " << num5 - num6 << endl; cout << "Multiplicacion (num5 * num6): " << num5 * num6 << endl; cout << "Division (num5 / num6): " << num5 / num6 << endl; // No se puede obtener un resto de una divisin de datos del tipo Double. } <|endoftext|>
<commit_before>ab3eaaa1-327f-11e5-89c3-9cf387a8033e<commit_msg>ab447beb-327f-11e5-93f6-9cf387a8033e<commit_after>ab447beb-327f-11e5-93f6-9cf387a8033e<|endoftext|>
<commit_before>555cdcc7-2e4f-11e5-abe0-28cfe91dbc4b<commit_msg>5564ee7a-2e4f-11e5-b418-28cfe91dbc4b<commit_after>5564ee7a-2e4f-11e5-b418-28cfe91dbc4b<|endoftext|>
<commit_before>#include <immintrin.h> #include <iostream> #include <iomanip> #include <malloc.h> #ifdef _MSC_VER extern "C" { #include <stdlib.h> } #define alignedMalloc(size,align) _aligned_malloc(size,align) #else #define alignedMalloc(size,align) memalign(align,size) #endif const int ALIGN=32; // alignment step for SSE const int cWidth = 256; const int cHeight = cWidth; const int cSize = cHeight * cWidth; void float2half(float* floats, short* halfs) { __m256 float_vector = _mm256_load_ps(floats); __m128i half_vector = _mm256_cvtps_ph(float_vector, 0); *(__m128i*)halfs = half_vector; } int main() { unsigned char* image =reinterpret_cast<unsigned char*>(alignedMalloc(cSize,ALIGN)); short* gain =reinterpret_cast<short*>(alignedMalloc(cSize*2,ALIGN)); float* gainOriginal = reinterpret_cast<float*>(alignedMalloc(cSize*4,ALIGN)); for (unsigned int i = 0;i < cSize;i++) { gainOriginal[i] = 1.0f; } for(unsigned int i = 0;i < cSize/8;i++) { float2half(&gainOriginal[i*8], &gain[i*8]); } for (unsigned int i = 0; i < cSize; i++) { if ((i & 7) == 0) { std::cout << std::dec << std::setfill(' ') << std::setw(5) << i; } std::cout << " 0x" << std::hex << gain[i]; if ((i & 7) == 7) { std::cout << std::endl; } } return 0; } <commit_msg>check compiler more strictly * only gcc and Visual Studio is accepted to compile this source<commit_after>#include <immintrin.h> #include <iostream> #include <iomanip> #include <malloc.h> #ifdef _MSC_VER extern "C" { #include <stdlib.h> } #define alignedMalloc(size,align) _aligned_malloc(size,align) #elif defined (__GNUC__) #define alignedMalloc(size,align) memalign(align,size) #endif const int ALIGN=32; // alignment step for SSE const int cWidth = 256; const int cHeight = cWidth; const int cSize = cHeight * cWidth; void float2half(float* floats, short* halfs) { __m256 float_vector = _mm256_load_ps(floats); __m128i half_vector = _mm256_cvtps_ph(float_vector, 0); *(__m128i*)halfs = half_vector; } int main() { unsigned char* image =reinterpret_cast<unsigned char*>(alignedMalloc(cSize,ALIGN)); short* gain =reinterpret_cast<short*>(alignedMalloc(cSize*2,ALIGN)); float* gainOriginal = reinterpret_cast<float*>(alignedMalloc(cSize*4,ALIGN)); for (unsigned int i = 0;i < cSize;i++) { gainOriginal[i] = 1.0f; } for(unsigned int i = 0;i < cSize/8;i++) { float2half(&gainOriginal[i*8], &gain[i*8]); } for (unsigned int i = 0; i < cSize; i++) { if ((i & 7) == 0) { std::cout << std::dec << std::setfill(' ') << std::setw(5) << i; } std::cout << " 0x" << std::hex << gain[i]; if ((i & 7) == 7) { std::cout << std::endl; } } return 0; } <|endoftext|>
<commit_before>822befcc-2d3e-11e5-8f90-c82a142b6f9b<commit_msg>82baa62e-2d3e-11e5-bd6c-c82a142b6f9b<commit_after>82baa62e-2d3e-11e5-bd6c-c82a142b6f9b<|endoftext|>
<commit_before>16b0c492-2f67-11e5-a983-6c40088e03e4<commit_msg>16b7f776-2f67-11e5-a84a-6c40088e03e4<commit_after>16b7f776-2f67-11e5-a84a-6c40088e03e4<|endoftext|>
<commit_before>08fa709e-2e4f-11e5-af70-28cfe91dbc4b<commit_msg>08ffd0e8-2e4f-11e5-b72c-28cfe91dbc4b<commit_after>08ffd0e8-2e4f-11e5-b72c-28cfe91dbc4b<|endoftext|>
<commit_before>#include <iostream> using namespace std; typedef union { size_t st; float f; } ieee754Union; int main(int argc, char* argv[]) { if (argc < 2) { cerr << "Please supply a float as the first argument." << endl; return EXIT_FAILURE; } ieee754Union u; if(sscanf(argv[1], "%f", &u.f) == 0) { cerr << "Please supply a float as the first argument." << endl; return EXIT_FAILURE; } string bitString = bitset<32>(u.st).to_string().insert(9, ":").insert(1, ":"); cout << argv[1] << " (base 10 argument)" << endl; cout << u.f << " (base 10 internal float)" << endl; cout << hex << (((1 << 31) - 1) & u.st) << " (ieee754 hexadecimal)" << endl; cout << bitString << " (ieee754 sign:exponent:mantisa)" << endl; return EXIT_SUCCESS; }<commit_msg>mantisa -> mantissa<commit_after>#include <iostream> using namespace std; typedef union { size_t st; float f; } ieee754Union; int main(int argc, char* argv[]) { if (argc < 2) { cerr << "Please supply a float as the first argument." << endl; return EXIT_FAILURE; } ieee754Union u; if(sscanf(argv[1], "%f", &u.f) == 0) { cerr << "Please supply a float as the first argument." << endl; return EXIT_FAILURE; } string bitString = bitset<32>(u.st).to_string().insert(9, ":").insert(1, ":"); cout << argv[1] << " (base 10 argument)" << endl; cout << u.f << " (base 10 internal float)" << endl; cout << hex << (((1 << 31) - 1) & u.st) << " (ieee754 hexadecimal)" << endl; cout << bitString << " (ieee754 sign:exponent:mantissa)" << endl; return EXIT_SUCCESS; }<|endoftext|>
<commit_before>92323b64-2d14-11e5-af21-0401358ea401<commit_msg>92323b65-2d14-11e5-af21-0401358ea401<commit_after>92323b65-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>dab93f51-313a-11e5-9e77-3c15c2e10482<commit_msg>dac6abcc-313a-11e5-8b79-3c15c2e10482<commit_after>dac6abcc-313a-11e5-8b79-3c15c2e10482<|endoftext|>
<commit_before>#include <omp.h> #include "evaluate_circuit.h" // Input: ./qflex.x I J K fidelity circuit_filename ordering_filename \ // grid_filename [initial_conf] [final_conf] // // Example: // $ ./qflex.x 11 12 2 0.005 ./circuits/ben_11_16_0.txt \ // ./ordering/bristlecone_48.txt ./grid/bristlecone_48.txt int main(int argc, char** argv) { // Reading input. if (argc < 8) throw std::logic_error("ERROR: Not enough arguments."); int current_arg = 1; qflex::QflexInput input; input.I = atoi(argv[current_arg++]); input.J = atoi(argv[current_arg++]); input.K = atoi(argv[current_arg++]); input.fidelity = atof(argv[current_arg++]); // Creating streams for input files. auto circuit_data = std::ifstream(std::string(argv[current_arg++])); if (!circuit_data.good()) { std::cout << "Cannot open circuit data file: " << std::string(argv[current_arg++]) << std::endl; assert(circuit_data.good()); } input.circuit_data = &circuit_data; auto ordering_data = std::ifstream(std::string(argv[current_arg++])); if (!ordering_data.good()) { std::cout << "Cannot open ordering data file: " << std::string(argv[current_arg++]) << std::endl; assert(ordering_data.good()); } input.ordering_data = &ordering_data; auto grid_data = std::ifstream(std::string(argv[current_arg++])); if (!grid_data.good()) { std::cout << "Cannot open grid data file: " << std::string(argv[current_arg++]) << std::endl; assert(grid_data.good()); } input.grid_data = &grid_data; // Setting initial and final circuit states. if (argc > current_arg) { input.initial_state = std::string(argv[current_arg++]); } if (argc > current_arg) { input.final_state_A = std::string(argv[current_arg++]); } // Evaluating circuit. std::vector<std::pair<std::string, std::complex<double>>> amplitudes = qflex::EvaluateCircuit(&input); // Printing output. for (int c = 0; c < amplitudes.size(); ++c) { const auto& state = amplitudes[c].first; const auto& amplitude = amplitudes[c].second; std::cout << input.initial_state << " --> " << state << ": " << std::real(amplitude) << " " << std::imag(amplitude) << std::endl; } return 0; } <commit_msg>small fixes<commit_after>#include <omp.h> #include "evaluate_circuit.h" // Input: ./qflex.x I J K fidelity circuit_filename ordering_filename \ // grid_filename [initial_conf] [final_conf] // // Example: // $ ./qflex.x 11 12 2 0.005 ./circuits/ben_11_16_0.txt \ // ./ordering/bristlecone_48.txt ./grid/bristlecone_48.txt int main(int argc, char** argv) { // Reading input. if (argc < 8) throw std::logic_error("ERROR: Not enough arguments."); int current_arg = 1; qflex::QflexInput input; input.I = atoi(argv[current_arg++]); input.J = atoi(argv[current_arg++]); input.K = atoi(argv[current_arg++]); input.fidelity = atof(argv[current_arg++]); // Creating streams for input files. auto circuit_data = std::ifstream(std::string(argv[current_arg++])); if (!circuit_data.good()) { std::cout << "Cannot open circuit data file: " << std::string(argv[current_arg]) << std::endl; assert(circuit_data.good()); } input.circuit_data = &circuit_data; auto ordering_data = std::ifstream(std::string(argv[current_arg++])); if (!ordering_data.good()) { std::cout << "Cannot open ordering data file: " << std::string(argv[current_arg]) << std::endl; assert(ordering_data.good()); } input.ordering_data = &ordering_data; auto grid_data = std::ifstream(std::string(argv[current_arg++])); if (!grid_data.good()) { std::cout << "Cannot open grid data file: " << std::string(argv[current_arg]) << std::endl; assert(grid_data.good()); } input.grid_data = &grid_data; // Setting initial and final circuit states. if (argc > current_arg) { input.initial_state = std::string(argv[current_arg++]); } if (argc > current_arg) { input.final_state_A = std::string(argv[current_arg++]); } // Evaluating circuit. std::vector<std::pair<std::string, std::complex<double>>> amplitudes = qflex::EvaluateCircuit(&input); // Printing output. for (int c = 0; c < amplitudes.size(); ++c) { const auto& state = amplitudes[c].first; const auto& amplitude = amplitudes[c].second; std::cout << input.initial_state << " --> " << state << ": " << std::real(amplitude) << " " << std::imag(amplitude) << std::endl; } return 0; } <|endoftext|>
<commit_before>0e9fcdda-585b-11e5-8234-6c40088e03e4<commit_msg>0ea7ae8a-585b-11e5-91c3-6c40088e03e4<commit_after>0ea7ae8a-585b-11e5-91c3-6c40088e03e4<|endoftext|>
<commit_before>#include <iostream> using namespace std; /* f G H g b C I h c a D J i d e K j k l a b-B b+B c-C c+C ... Instead of sampling b, B, c, C... I sample b-B, b+B, c-C, c+C... to make the nn insensitive to direction. */ class Pet{ protected: const int numLayers = 4; // Arbitrary const int layerSize = 10; // Arbitrary const int numInputPositions = 19; // All positions within 2 steps. const int numInputChannels = 6; // Other pets rgb, Scent rgb const int numOutputDirections = 6; // All directions const int numDirectionalOutputChannels = 3; // Move, Fight, Mate const int numGeneralOutputChannels = 3; // Null, Scent const int numInputNeurons = numInputPositions*numInputChannels; const int numProcessingNeurons = numLayers*layerSize; const int numOutputNeurons = numOutputDirections*numDirectionalOutputChannels + numGeneralOutputChannels; const int numInputConnections = numInputPositions*numInputChannels*layerSize; const int numProcessingConnections = (numLayers-1)*layerSize*layerSize; const int numOutputConnections = (numOutputDirections*numDirectionalOutputChannels + numGeneralOutputChannels)*layerSize; float inputNeurons[numInputNeurons]; float processingNeurons[numProcessingNeurons]; float outputNeurons[numOutputNeurons]; float inputConnections[numinputConnections]; float processingConnections[numProcessingConnections]; float outputConnections[numOutputConnections]; void collectInput(WorldCell environment[]){ for(int i=0; i<) } void processInput(){ // First layer takes input directly from input neurons. for(int write=0; write<layerSize; ++write){ processingNeurons[write] = 0; for(int read=0; read<numInputNeurons; ++read) processingNeurons[write] = inputNeurons[read] * inputConnections[write*layerSize + read]; } // Propagate through the rest of the processing layers. for(int layer=1; layer<numLayers; ++layer) for(int write=0; write<layerSize; ++write){ processingNeurons[layer*layerSize + write] = 0; for(int read=0; read<layerSize; ++read) processingNeurons[layer*layerSize + write] += processingNeurons[(layer-1)*layerSize + read] * processingConnections[write*layerSize + read]; } // Output neurons read from the last layer. for(int write=0; write<numOutputNeurons; ++write){ outputNeurons[write] = 0; for(int read=0; read<layerSize; ++read) outputNeurons[write] = processingNeurons[(numLayers-1)*layerSize + read] * outputConnections[read*layerSize + write]; } } void respondToInput(){ for(int i=0; i<) } const float breedingEnergy = 0.2; int direction; int position; float energy; float color[3]; public: void live(){ collectInput(); processInput(); respondToInput(); } } int main() { cout << "Hello world!" << endl; return 0; } <commit_msg>Begun implementing the movement.<commit_after>#include <iostream> using namespace std; /* f G H g b C I h c a D J i d e K j k l a b-B b+B c-C c+C ... Instead of sampling b, B, c, C... I sample b-B, b+B, c-C, c+C... to make the nn insensitive to direction. HANDLED BY Environment::Sample. */ enum Directions { none, forward, forwardLeft, forwardRight, backward, backwardLeft, backwardRight, numDirections }; class Pet{ protected: const int numLayers = 1; // Arbitrary const int layerSize = 4; // Arbitrary const int numInputPositions = 7; // All positions within 1 steps. const int numInputChannels = 3; // Other pets mate-abillity, nutricient, danger. const int numOutputPositions = 7; // All positions within 1 steps. const int numGeneralOutputs = 2; // Mate, scent. const int numInputNeurons = numInputPositions*numInputChannels; const int numProcessingNeurons = numLayers*layerSize; const int numOutputNeurons = numOutputPositions + numGeneralOutputs; const int numInputConnections = numInputPositions*numInputChannels*layerSize; const int numProcessingConnections = (numLayers-1)*layerSize*layerSize; const int numOutputConnections = (numOutputPositions + numGeneralOutputs)*layerSize; float inputNeurons[numInputNeurons]; float processingNeurons[numProcessingNeurons]; float outputNeurons[numOutputNeurons]; float inputConnections[numinputConnections]; float processingConnections[numProcessingConnections]; float outputConnections[numOutputConnections]; Environment& environment; int position; Direction facingDirection; void collectInput(){ for(Channels channel = 0; i<numChannels; ++i) for(Directions direction = 0; i<numDirections; ++i) inputNeurons[channel*numDirections + direction] = environment.sample(position, facingDirection, direction, channel); } void processInput(){ // First layer takes input directly from input neurons. for(int write=0; write<layerSize; ++write){ processingNeurons[write] = 0; for(int read=0; read<numInputNeurons; ++read) processingNeurons[write] = inputNeurons[read] * inputConnections[write*layerSize + read]; } // Propagate through the rest of the processing layers. for(int layer=1; layer<numLayers; ++layer) for(int write=0; write<layerSize; ++write){ processingNeurons[layer*layerSize + write] = 0; for(int read=0; read<layerSize; ++read) processingNeurons[layer*layerSize + write] += processingNeurons[(layer-1)*layerSize + read] * processingConnections[write*layerSize + read]; } // Output neurons read from the last layer. for(int write=0; write<numOutputNeurons; ++write){ outputNeurons[write] = 0; for(int read=0; read<layerSize; ++read) outputNeurons[write] = processingNeurons[(numLayers-1)*layerSize + read] * outputConnections[read*layerSize + write]; } } void respondToInput(){ for(int i=0; i<) } const float breedingEnergy = 0.2; int direction; int position; float energy; float color[3]; public: void live(){ collectInput(); processInput(); respondToInput(); } } int main() { cout << "Hello world!" << endl; return 0; } <|endoftext|>
<commit_before>58ebb811-2e4f-11e5-823f-28cfe91dbc4b<commit_msg>58f29db3-2e4f-11e5-875d-28cfe91dbc4b<commit_after>58f29db3-2e4f-11e5-875d-28cfe91dbc4b<|endoftext|>
<commit_before>b88f04ae-2e4f-11e5-a9ec-28cfe91dbc4b<commit_msg>b895a321-2e4f-11e5-a23e-28cfe91dbc4b<commit_after>b895a321-2e4f-11e5-a23e-28cfe91dbc4b<|endoftext|>
<commit_before>e7889151-ad58-11e7-b703-ac87a332f658<commit_msg>Typical bobby<commit_after>e7fbefb0-ad58-11e7-96d1-ac87a332f658<|endoftext|>
<commit_before>5d286628-2d16-11e5-af21-0401358ea401<commit_msg>5d286629-2d16-11e5-af21-0401358ea401<commit_after>5d286629-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>7f6cf58e-2d15-11e5-af21-0401358ea401<commit_msg>7f6cf58f-2d15-11e5-af21-0401358ea401<commit_after>7f6cf58f-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>8fd2dfe8-4b02-11e5-80a9-28cfe9171a43<commit_msg>Made changes so it will hopefully compile by the next commit<commit_after>8fdfbca3-4b02-11e5-8249-28cfe9171a43<|endoftext|>
<commit_before>8f156b4a-35ca-11e5-b6d1-6c40088e03e4<commit_msg>8f1c604c-35ca-11e5-86e7-6c40088e03e4<commit_after>8f1c604c-35ca-11e5-86e7-6c40088e03e4<|endoftext|>
<commit_before>/* * Copyright (C) 2004-2008 See the AUTHORS file for details. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. */ #include "znc.h" #include <getopt.h> static struct option g_LongOpts[] = { { "help", no_argument, 0, 'h' }, { "version", no_argument, 0, 'v' }, { "no-color", no_argument, 0, 'n' }, { "makeconf", no_argument, 0, 'c' }, { "makepass", no_argument, 0, 's' }, #ifdef HAVE_LIBSSL { "makepem", no_argument, 0, 'p' }, { "encrypt-pem", no_argument, 0, 'e' }, #endif /* HAVE_LIBSSL */ { "datadir", required_argument, 0, 'd' }, { 0, 0, 0, 0 } }; static void GenerateHelp(const char *appname) { CUtils::PrintMessage("USAGE: " + CString(appname) + " [options] [config]"); CUtils::PrintMessage("Options are:"); CUtils::PrintMessage("\t-h, --help List available command line options (this page)"); CUtils::PrintMessage("\t-v, --version Output version information and exit"); CUtils::PrintMessage("\t-n, --no-color Don't use escape sequences in the output"); CUtils::PrintMessage("\t-c, --makeconf Interactively create a new config"); CUtils::PrintMessage("\t-s, --makepass Generates a password for use in config"); #ifdef HAVE_LIBSSL CUtils::PrintMessage("\t-p, --makepem Generates a pemfile for use with SSL"); CUtils::PrintMessage("\t-e, --encrypt-pem when used along with --makepem, encrypts the private key in the pemfile"); #endif /* HAVE_LIBSSL */ CUtils::PrintMessage("\t-d, --datadir Set a different znc repository (default is ~/.znc)"); } static void die(int sig) { signal(SIGSEGV, SIG_DFL); signal(SIGABRT, SIG_DFL); signal(SIGPIPE, SIG_DFL); #ifdef _DEBUG CUtils::PrintMessage("Exiting on SIG [" + CString(sig) + "]"); if ((sig == SIGABRT) || (sig == SIGSEGV)) { abort(); } #endif /* _DEBUG */ delete &CZNC::Get(); exit(sig); } static void rehash(int sig) { CZNC::Get().SetNeedRehash(true); } int main(int argc, char** argv) { CString sConfig; CString sDataDir = ""; srand(time(NULL)); CUtils::SetStdoutIsTTY(isatty(1)); #ifdef HAVE_LIBSSL InitSSL(); #endif /* HAVE_LIBSSL */ int iArg, iOptIndex = -1; bool bMakeConf = false; bool bMakePass = false; #ifdef HAVE_LIBSSL bool bMakePem = false; bool bEncPem = false; while ((iArg = getopt_long(argc, argv, "hvncsped:", g_LongOpts, &iOptIndex)) != -1) { #else while ((iArg = getopt_long(argc, argv, "hvncsd:", g_LongOpts, &iOptIndex)) != -1) { #endif /* HAVE_LIBSSL */ switch (iArg) { case 'h': GenerateHelp(argv[0]); return 0; case 'v': cout << CZNC::GetTag() << endl; return 0; case 'n': CUtils::SetStdoutIsTTY(false); break; case 'c': bMakeConf = true; break; case 's': bMakePass = true; break; #ifdef HAVE_LIBSSL case 'p': bMakePem = true; break; case 'e': bEncPem = true; break; #endif /* HAVE_LIBSSL */ case 'd': sDataDir = CString(optarg); break; case '?': default: GenerateHelp(argv[0]); return 1; } } if (optind < argc) { sConfig = argv[optind]; } else { sConfig = "znc.conf"; } if (bMakeConf) { CZNC& ZNC = CZNC::Get(); ZNC.InitDirs("", sDataDir); if (ZNC.WriteNewConfig(sConfig)) { char const* args[5]; if (argc > 2) { args[0] = argv[0]; if (!sDataDir.empty()) { args[1] = "--datadir"; args[2] = strdup(sDataDir.c_str()); args[3] = argv[optind]; args[4] = NULL; } else { args[1] = argv[optind]; args[2] = NULL; } } else if (argc > 1) { args[0] = argv[0]; if (!sDataDir.empty()) { args[1] = "--datadir"; args[2] = strdup(sDataDir.c_str()); args[3] = NULL; } else { args[1] = NULL; } } else { CUtils::PrintError("Unable to launch znc [Try manually restarting]"); return 1; } if ((chdir(ZNC.GetCurPath().c_str()) == -1) || (execv(*argv, (char *const*)args) == -1)) { CUtils::PrintError("Unable to launch znc [" + CString(strerror(errno)) + "]"); return 1; } } return 0; } #ifdef HAVE_LIBSSL if (bMakePem) { CZNC* pZNC = &CZNC::Get(); pZNC->InitDirs("", sDataDir); pZNC->WritePemFile(bEncPem); delete pZNC; return 0; } if (bEncPem && !bMakePem) { CUtils::PrintError("--encrypt-pem should be used along with --makepem."); return 1; } #endif /* HAVE_LIBSSL */ if (bMakePass) { CString sHash = CUtils::GetHashPass(); CUtils::PrintMessage("Use this in the <User> section of your config:"); CUtils::PrintMessage("Pass = " + sHash + " -"); return 0; } CZNC* pZNC = &CZNC::Get(); pZNC->InitDirs(((argc) ? argv[0] : ""), sDataDir); if (!pZNC->ParseConfig(sConfig)) { CUtils::PrintError("Unrecoverable config error."); delete pZNC; return 1; } if (!pZNC->OnBoot()) { CUtils::PrintError("Exiting due to module boot errors."); delete pZNC; return 1; } #ifdef _DEBUG int iPid = getpid(); CUtils::PrintMessage("Staying open for debugging [pid: " + CString(iPid) + "]"); pZNC->WritePidFile(iPid); #else CUtils::PrintAction("Forking into the background"); int iPid = fork(); if (iPid == -1) { CUtils::PrintStatus(false, strerror(errno)); delete pZNC; exit(1); } if (iPid > 0) { CUtils::PrintStatus(true, "[pid: " + CString(iPid) + "]"); pZNC->WritePidFile(iPid); CUtils::PrintMessage(CZNC::GetTag(false)); exit(0); } // Redirect std in/out/err to /dev/null close(0); open("/dev/null", O_RDONLY); close(1); open("/dev/null", O_WRONLY); close(2); open("/dev/null", O_WRONLY); CUtils::SetStdoutIsTTY(false); #endif struct sigaction sa; sa.sa_flags = 0; sigemptyset(&sa.sa_mask); sa.sa_handler = SIG_IGN; sigaction(SIGPIPE, &sa, (struct sigaction*) NULL); sa.sa_handler = die; sigaction(SIGINT, &sa, (struct sigaction*) NULL); sigaction(SIGILL, &sa, (struct sigaction*) NULL); sigaction(SIGQUIT, &sa, (struct sigaction*) NULL); sigaction(SIGBUS, &sa, (struct sigaction*) NULL); sigaction(SIGSEGV, &sa, (struct sigaction*) NULL); sigaction(SIGTERM, &sa, (struct sigaction*) NULL); sa.sa_handler = rehash; sigaction(SIGHUP, &sa, (struct sigaction*) NULL); int iRet = 0; try { iRet = pZNC->Loop(); } catch (CException e) { // EX_Shutdown is thrown to exit switch (e.GetType()) { case CException::EX_Shutdown: iRet = 0; default: iRet = 1; } } delete pZNC; return iRet; } <commit_msg>Call setsid() after forking<commit_after>/* * Copyright (C) 2004-2008 See the AUTHORS file for details. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. */ #include "znc.h" #include <getopt.h> static struct option g_LongOpts[] = { { "help", no_argument, 0, 'h' }, { "version", no_argument, 0, 'v' }, { "no-color", no_argument, 0, 'n' }, { "makeconf", no_argument, 0, 'c' }, { "makepass", no_argument, 0, 's' }, #ifdef HAVE_LIBSSL { "makepem", no_argument, 0, 'p' }, { "encrypt-pem", no_argument, 0, 'e' }, #endif /* HAVE_LIBSSL */ { "datadir", required_argument, 0, 'd' }, { 0, 0, 0, 0 } }; static void GenerateHelp(const char *appname) { CUtils::PrintMessage("USAGE: " + CString(appname) + " [options] [config]"); CUtils::PrintMessage("Options are:"); CUtils::PrintMessage("\t-h, --help List available command line options (this page)"); CUtils::PrintMessage("\t-v, --version Output version information and exit"); CUtils::PrintMessage("\t-n, --no-color Don't use escape sequences in the output"); CUtils::PrintMessage("\t-c, --makeconf Interactively create a new config"); CUtils::PrintMessage("\t-s, --makepass Generates a password for use in config"); #ifdef HAVE_LIBSSL CUtils::PrintMessage("\t-p, --makepem Generates a pemfile for use with SSL"); CUtils::PrintMessage("\t-e, --encrypt-pem when used along with --makepem, encrypts the private key in the pemfile"); #endif /* HAVE_LIBSSL */ CUtils::PrintMessage("\t-d, --datadir Set a different znc repository (default is ~/.znc)"); } static void die(int sig) { signal(SIGSEGV, SIG_DFL); signal(SIGABRT, SIG_DFL); signal(SIGPIPE, SIG_DFL); #ifdef _DEBUG CUtils::PrintMessage("Exiting on SIG [" + CString(sig) + "]"); if ((sig == SIGABRT) || (sig == SIGSEGV)) { abort(); } #endif /* _DEBUG */ delete &CZNC::Get(); exit(sig); } static void rehash(int sig) { CZNC::Get().SetNeedRehash(true); } int main(int argc, char** argv) { CString sConfig; CString sDataDir = ""; srand(time(NULL)); CUtils::SetStdoutIsTTY(isatty(1)); #ifdef HAVE_LIBSSL InitSSL(); #endif /* HAVE_LIBSSL */ int iArg, iOptIndex = -1; bool bMakeConf = false; bool bMakePass = false; #ifdef HAVE_LIBSSL bool bMakePem = false; bool bEncPem = false; while ((iArg = getopt_long(argc, argv, "hvncsped:", g_LongOpts, &iOptIndex)) != -1) { #else while ((iArg = getopt_long(argc, argv, "hvncsd:", g_LongOpts, &iOptIndex)) != -1) { #endif /* HAVE_LIBSSL */ switch (iArg) { case 'h': GenerateHelp(argv[0]); return 0; case 'v': cout << CZNC::GetTag() << endl; return 0; case 'n': CUtils::SetStdoutIsTTY(false); break; case 'c': bMakeConf = true; break; case 's': bMakePass = true; break; #ifdef HAVE_LIBSSL case 'p': bMakePem = true; break; case 'e': bEncPem = true; break; #endif /* HAVE_LIBSSL */ case 'd': sDataDir = CString(optarg); break; case '?': default: GenerateHelp(argv[0]); return 1; } } if (optind < argc) { sConfig = argv[optind]; } else { sConfig = "znc.conf"; } if (bMakeConf) { CZNC& ZNC = CZNC::Get(); ZNC.InitDirs("", sDataDir); if (ZNC.WriteNewConfig(sConfig)) { char const* args[5]; if (argc > 2) { args[0] = argv[0]; if (!sDataDir.empty()) { args[1] = "--datadir"; args[2] = strdup(sDataDir.c_str()); args[3] = argv[optind]; args[4] = NULL; } else { args[1] = argv[optind]; args[2] = NULL; } } else if (argc > 1) { args[0] = argv[0]; if (!sDataDir.empty()) { args[1] = "--datadir"; args[2] = strdup(sDataDir.c_str()); args[3] = NULL; } else { args[1] = NULL; } } else { CUtils::PrintError("Unable to launch znc [Try manually restarting]"); return 1; } if ((chdir(ZNC.GetCurPath().c_str()) == -1) || (execv(*argv, (char *const*)args) == -1)) { CUtils::PrintError("Unable to launch znc [" + CString(strerror(errno)) + "]"); return 1; } } return 0; } #ifdef HAVE_LIBSSL if (bMakePem) { CZNC* pZNC = &CZNC::Get(); pZNC->InitDirs("", sDataDir); pZNC->WritePemFile(bEncPem); delete pZNC; return 0; } if (bEncPem && !bMakePem) { CUtils::PrintError("--encrypt-pem should be used along with --makepem."); return 1; } #endif /* HAVE_LIBSSL */ if (bMakePass) { CString sHash = CUtils::GetHashPass(); CUtils::PrintMessage("Use this in the <User> section of your config:"); CUtils::PrintMessage("Pass = " + sHash + " -"); return 0; } CZNC* pZNC = &CZNC::Get(); pZNC->InitDirs(((argc) ? argv[0] : ""), sDataDir); if (!pZNC->ParseConfig(sConfig)) { CUtils::PrintError("Unrecoverable config error."); delete pZNC; return 1; } if (!pZNC->OnBoot()) { CUtils::PrintError("Exiting due to module boot errors."); delete pZNC; return 1; } #ifdef _DEBUG int iPid = getpid(); CUtils::PrintMessage("Staying open for debugging [pid: " + CString(iPid) + "]"); pZNC->WritePidFile(iPid); #else CUtils::PrintAction("Forking into the background"); int iPid = fork(); if (iPid == -1) { CUtils::PrintStatus(false, strerror(errno)); delete pZNC; exit(1); } if (iPid > 0) { // We are the parent. We are done and will go to bed. CUtils::PrintStatus(true, "[pid: " + CString(iPid) + "]"); pZNC->WritePidFile(iPid); CUtils::PrintMessage(CZNC::GetTag(false)); exit(0); } // Redirect std in/out/err to /dev/null close(0); open("/dev/null", O_RDONLY); close(1); open("/dev/null", O_WRONLY); close(2); open("/dev/null", O_WRONLY); CUtils::SetStdoutIsTTY(false); // We are the child. There is no way we can be a process group // leader, thus setsid() must succeed. setsid(); // Now we are in our own process group and session (no controlling // terminal). We are independent! #endif struct sigaction sa; sa.sa_flags = 0; sigemptyset(&sa.sa_mask); sa.sa_handler = SIG_IGN; sigaction(SIGPIPE, &sa, (struct sigaction*) NULL); sa.sa_handler = die; sigaction(SIGINT, &sa, (struct sigaction*) NULL); sigaction(SIGILL, &sa, (struct sigaction*) NULL); sigaction(SIGQUIT, &sa, (struct sigaction*) NULL); sigaction(SIGBUS, &sa, (struct sigaction*) NULL); sigaction(SIGSEGV, &sa, (struct sigaction*) NULL); sigaction(SIGTERM, &sa, (struct sigaction*) NULL); sa.sa_handler = rehash; sigaction(SIGHUP, &sa, (struct sigaction*) NULL); int iRet = 0; try { iRet = pZNC->Loop(); } catch (CException e) { // EX_Shutdown is thrown to exit switch (e.GetType()) { case CException::EX_Shutdown: iRet = 0; default: iRet = 1; } } delete pZNC; return iRet; } <|endoftext|>
<commit_before>/* * main.cpp * * Created on: 8 Oct 2016 * Author: muttley */ #include <iostream> #include <gtkmm.h> #include <string> #include <vector> #include <fstream> #include <cstdlib> #include <cstring> #include <algorithm> #include <regex> #include <sys/types.h> #include <dirent.h> #include <sys/stat.h> #include "VDF.h" #include "Filesystem.h" #include "Settings.h" #include "Utils.h" #include "Logger.h" #include "MainWindow.h" #ifdef __APPLE__ #include <mach-o/dyld.h> #endif using namespace std; int main(int argc, char *argv[]) { //Checking parameters for --verbose or -v for (int i = 0; i < argc; i++) { if (strcmp(argv[i], "--verbose") == 0 || strcmp(argv[i], "-v") == 0) LogLevel = 0; } LOG(1, "ArmA 3 Unix Launcher started"); //~/.config/a3unixlauncher if (!Filesystem::DirectoryExists(Filesystem::HomeDirectory + Filesystem::LauncherSettingsDirectory)) { bool result = Filesystem::CreateDirectory(Filesystem::HomeDirectory + Filesystem::LauncherSettingsDirectory); if (!result) return 1; } if (!Filesystem::FileExists(Filesystem::HomeDirectory + Filesystem::LauncherSettingsDirectory + Filesystem::LauncherSettingsFilename)) { Settings::Save(Filesystem::HomeDirectory + Filesystem::LauncherSettingsDirectory + Filesystem::LauncherSettingsFilename); } Settings::Load(Filesystem::HomeDirectory + Filesystem::LauncherSettingsDirectory + Filesystem::LauncherSettingsFilename); if (Settings::ArmaPath == Filesystem::DIR_NOT_FOUND) Settings::ArmaPath = Filesystem::GetDirectory(DirectoryToFind::ArmaInstall); if (Settings::WorkshopPath == Filesystem::DIR_NOT_FOUND) Settings::WorkshopPath = Filesystem::GetDirectory(DirectoryToFind::WorkshopMods); for (int i = 0; i < argc; i++) { if (strcmp(argv[i], "--purge") == 0) { if (Settings::ArmaPath != Filesystem::DIR_NOT_FOUND) { string removeWorkshop = "rm -rf " + Utils::BashAdaptPath(Settings::ArmaPath + Filesystem::ArmaDirWorkshop); string removeCustom = "rm -rf " + Utils::BashAdaptPath(Settings::ArmaPath + Filesystem::ArmaDirCustom); system(removeWorkshop.c_str()); system(removeCustom.c_str()); } string removeConfig = "rm -rf \"" + Filesystem::HomeDirectory + Filesystem::LauncherSettingsDirectory + "\""; system(removeConfig.c_str()); LOG(1, "Purged config file, !workshop, !custom directories"); exit(0); } } //Dirty fix to Gtk::Application trying to parse arguments on its own argc = 0; Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "muttley.a3unixlauncher"); #ifdef __APPLE__ //apple path is like: /Applications/arma3-unix-launcher.app/Contents/MacOS/./arma3-unix-launcher char* path = new char[4096]; unsigned int pathLength = 4095; _NSGetExecutablePath(path, &pathLength); string currentPath = path; delete[] path; string MainFormPath = Utils::RemoveLastElement(currentPath, false) + "MainForm.glade"; #else string MainFormPath = "/usr/share/arma3-unix-launcher/MainForm.glade"; if (!Filesystem::FileExists(MainFormPath)) MainFormPath = "MainForm.glade"; if (!Filesystem::FileExists(MainFormPath)) { string binaryPath = Filesystem::GetSymlinkTarget("/proc/" + to_string(getpid()) + "/exe"); MainFormPath = Utils::RemoveLastElement(binaryPath, false, 2) + "MainForm.glade"; } #endif Glib::RefPtr<Gtk::Builder> builder = Gtk::Builder::create_from_file(MainFormPath); cout << "GTK+ version: " << gtk_major_version << "." << gtk_minor_version << "." << gtk_micro_version << endl << "Glib version: " << glib_major_version << "." << glib_minor_version << "." << glib_micro_version << endl; //if autodetection fails while (Settings::ArmaPath == Filesystem::DIR_NOT_FOUND) { string Message = string("Launcher couldn't detect ArmA 3 installation directory") + "\nClick 'Yes' to select appropriate directory" + "\nClick 'No' to close the program"; Gtk::MessageDialog msg(Message, false, Gtk::MESSAGE_INFO, Gtk::BUTTONS_YES_NO); int result = msg.run(); if (result == Gtk::RESPONSE_NO) exit(2); Gtk::FileChooserDialog fcDialog("Select ArmA 3 install directory", Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER); fcDialog.add_button("_Open", 1); result = fcDialog.run(); if (result == 1) { string currentFolder = fcDialog.get_current_folder(); if (Filesystem::FileExists(currentFolder + "/arma3.i386")) Settings::ArmaPath = currentFolder; currentFolder = fcDialog.get_filename(); if (Filesystem::FileExists(currentFolder + "/arma3.i386")) Settings::ArmaPath = currentFolder; if (Settings::ArmaPath == Filesystem::DIR_NOT_FOUND) { string Message2 = string("Selected directory seems incorrect") + "\n" + currentFolder + "/arma3.i386 doesn't exist"; Gtk::MessageDialog msg2(Message2); msg2.run(); } } } MainWindow* mainWindow = NULL; builder->get_widget_derived("MainForm", mainWindow); if (mainWindow) app->run(*mainWindow); delete mainWindow; return 0; } <commit_msg>Quick & dirty fix for ArmA 3 detection on Mac OS X<commit_after>/* * main.cpp * * Created on: 8 Oct 2016 * Author: muttley */ #include <iostream> #include <gtkmm.h> #include <string> #include <vector> #include <fstream> #include <cstdlib> #include <cstring> #include <algorithm> #include <regex> #include <sys/types.h> #include <dirent.h> #include <sys/stat.h> #include "VDF.h" #include "Filesystem.h" #include "Settings.h" #include "Utils.h" #include "Logger.h" #include "MainWindow.h" #ifdef __APPLE__ #include <mach-o/dyld.h> #endif using namespace std; int main(int argc, char *argv[]) { //Checking parameters for --verbose or -v for (int i = 0; i < argc; i++) { if (strcmp(argv[i], "--verbose") == 0 || strcmp(argv[i], "-v") == 0) LogLevel = 0; } LOG(1, "ArmA 3 Unix Launcher started"); //~/.config/a3unixlauncher if (!Filesystem::DirectoryExists(Filesystem::HomeDirectory + Filesystem::LauncherSettingsDirectory)) { bool result = Filesystem::CreateDirectory(Filesystem::HomeDirectory + Filesystem::LauncherSettingsDirectory); if (!result) return 1; } if (!Filesystem::FileExists(Filesystem::HomeDirectory + Filesystem::LauncherSettingsDirectory + Filesystem::LauncherSettingsFilename)) { Settings::Save(Filesystem::HomeDirectory + Filesystem::LauncherSettingsDirectory + Filesystem::LauncherSettingsFilename); } Settings::Load(Filesystem::HomeDirectory + Filesystem::LauncherSettingsDirectory + Filesystem::LauncherSettingsFilename); if (Settings::ArmaPath == Filesystem::DIR_NOT_FOUND) Settings::ArmaPath = Filesystem::GetDirectory(DirectoryToFind::ArmaInstall); if (Settings::WorkshopPath == Filesystem::DIR_NOT_FOUND) Settings::WorkshopPath = Filesystem::GetDirectory(DirectoryToFind::WorkshopMods); for (int i = 0; i < argc; i++) { if (strcmp(argv[i], "--purge") == 0) { if (Settings::ArmaPath != Filesystem::DIR_NOT_FOUND) { string removeWorkshop = "rm -rf " + Utils::BashAdaptPath(Settings::ArmaPath + Filesystem::ArmaDirWorkshop); string removeCustom = "rm -rf " + Utils::BashAdaptPath(Settings::ArmaPath + Filesystem::ArmaDirCustom); system(removeWorkshop.c_str()); system(removeCustom.c_str()); } string removeConfig = "rm -rf \"" + Filesystem::HomeDirectory + Filesystem::LauncherSettingsDirectory + "\""; system(removeConfig.c_str()); LOG(1, "Purged config file, !workshop, !custom directories"); exit(0); } } //Dirty fix to Gtk::Application trying to parse arguments on its own argc = 0; Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "muttley.a3unixlauncher"); #ifdef __APPLE__ //apple path is like: /Applications/arma3-unix-launcher.app/Contents/MacOS/./arma3-unix-launcher char* path = new char[4096]; unsigned int pathLength = 4095; _NSGetExecutablePath(path, &pathLength); string currentPath = path; delete[] path; string MainFormPath = Utils::RemoveLastElement(currentPath, false) + "MainForm.glade"; #else string MainFormPath = "/usr/share/arma3-unix-launcher/MainForm.glade"; if (!Filesystem::FileExists(MainFormPath)) MainFormPath = "MainForm.glade"; if (!Filesystem::FileExists(MainFormPath)) { string binaryPath = Filesystem::GetSymlinkTarget("/proc/" + to_string(getpid()) + "/exe"); MainFormPath = Utils::RemoveLastElement(binaryPath, false, 2) + "MainForm.glade"; } #endif Glib::RefPtr<Gtk::Builder> builder = Gtk::Builder::create_from_file(MainFormPath); cout << "GTK+ version: " << gtk_major_version << "." << gtk_minor_version << "." << gtk_micro_version << endl << "Glib version: " << glib_major_version << "." << glib_minor_version << "." << glib_micro_version << endl; //if autodetection fails while (Settings::ArmaPath == Filesystem::DIR_NOT_FOUND) { string Message = string("Launcher couldn't detect ArmA 3 installation directory") + "\nClick 'Yes' to select appropriate directory" + "\nClick 'No' to close the program"; Gtk::MessageDialog msg(Message, false, Gtk::MESSAGE_INFO, Gtk::BUTTONS_YES_NO); int result = msg.run(); if (result == Gtk::RESPONSE_NO) exit(2); Gtk::FileChooserDialog fcDialog("Select ArmA 3 install directory", Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER); fcDialog.add_button("_Open", 1); result = fcDialog.run(); if (result == 1) { string currentFolder = fcDialog.get_current_folder(); if (Filesystem::FileExists(currentFolder + "/arma3.i386") || Filesystem::FileExists(currentFolder + "/ArmA3.app") || Filesystem::DirectoryExists(currentFolder + "/ArmA3.app")) Settings::ArmaPath = currentFolder; currentFolder = fcDialog.get_filename(); if (Filesystem::FileExists(currentFolder + "/arma3.i386") || Filesystem::FileExists(currentFolder + "/ArmA3.app") || Filesystem::DirectoryExists(currentFolder + "/ArmA3.app")) Settings::ArmaPath = currentFolder; if (Settings::ArmaPath == Filesystem::DIR_NOT_FOUND) { string Message2 = string("Selected directory seems incorrect") + "\n" + currentFolder + "/arma3.i386 doesn't exist" "\n" + currentFolder + "/ArmA3.app doesn't exist"; Gtk::MessageDialog msg2(Message2); msg2.run(); } } } MainWindow* mainWindow = NULL; builder->get_widget_derived("MainForm", mainWindow); if (mainWindow) app->run(*mainWindow); delete mainWindow; return 0; } <|endoftext|>
<commit_before>f278e24c-2747-11e6-b3cd-e0f84713e7b8<commit_msg>( ͡° ͜ʖ ͡°)<commit_after>f290b245-2747-11e6-b5ed-e0f84713e7b8<|endoftext|>
<commit_before>eece5170-585a-11e5-b999-6c40088e03e4<commit_msg>eed57766-585a-11e5-82af-6c40088e03e4<commit_after>eed57766-585a-11e5-82af-6c40088e03e4<|endoftext|>
<commit_before>8d6fbe80-2e4f-11e5-af7a-28cfe91dbc4b<commit_msg>8d76b102-2e4f-11e5-bebe-28cfe91dbc4b<commit_after>8d76b102-2e4f-11e5-bebe-28cfe91dbc4b<|endoftext|>
<commit_before>993e835c-4b02-11e5-95bd-28cfe9171a43<commit_msg>GOD DAMNED IT!<commit_after>994be09c-4b02-11e5-bacd-28cfe9171a43<|endoftext|>
<commit_before>a25053fa-2e4f-11e5-896d-28cfe91dbc4b<commit_msg>a2579cc0-2e4f-11e5-b581-28cfe91dbc4b<commit_after>a2579cc0-2e4f-11e5-b581-28cfe91dbc4b<|endoftext|>
<commit_before>65e877b3-2749-11e6-a9f5-e0f84713e7b8<commit_msg>For ashok to integrate at some point<commit_after>65f67dc0-2749-11e6-b097-e0f84713e7b8<|endoftext|>
<commit_before>ce8f7efd-2d3d-11e5-98ad-c82a142b6f9b<commit_msg>cee632d9-2d3d-11e5-bda6-c82a142b6f9b<commit_after>cee632d9-2d3d-11e5-bda6-c82a142b6f9b<|endoftext|>
<commit_before>d99edf59-4b02-11e5-9957-28cfe9171a43<commit_msg>Gapjgjchguagdmg<commit_after>d9adf682-4b02-11e5-80a4-28cfe9171a43<|endoftext|>
<commit_before>a6bfcab8-ad5c-11e7-b6b1-ac87a332f658<commit_msg>Boyaaah!<commit_after>a74fe72e-ad5c-11e7-8fc4-ac87a332f658<|endoftext|>
<commit_before>#include <assert.h> #include <stdio.h> #include <stdlib.h> #include <netcdf.h> #include <cudpp.h> #include <cutil.h> #include "cuda_test.h" #include "cpu_test.h" #include "cuda_defs.h" #define DEBUG 1 #define ERRCODE 2 #define ERR(e) {printf("Error: %s\n", nc_strerror(e)); exit(ERRCODE);} #define TIME 1 #define LAT 190 #define LON 384 #define VARNAME "TMP_2maboveground" #define DMIN 205 #define DMAX 320 #define MONTHS 12 void unpack_data(char *filename, float *data_in, char *varname); int main(int argc, char *argv[]){ int dmin, dmax, nSamples, dim; float *dataT=NULL; if (!DEBUG){ int start = 1985; int end = 1986; //int end = 2009; int tsamples = ((end-start) + 1)*MONTHS; dim = 9; //num forecasts dmin = DMIN; dmax = DMAX; nSamples = tsamples * LAT * LON; int foffset, yoffset, moffset; char filename[23]; float *data = NULL; CPUMALLOC((void**)&data, sizeof(float)*nSamples*dim); CPUMALLOC((void**)&dataT, sizeof(float)*nSamples*dim); printf("%d\n", nSamples*dim); char ffilename[25]; int zcount=0; for (int f = 1; f<=9; f++){ foffset = nSamples*(f-1); for (int y =start; y<=end; y++){ yoffset = (LAT*LON*12) * (y-start); for (int m = 1; m<=MONTHS; m++){ sprintf(ffilename, "../data/TMP_%d%02d_f%02d.nc", y, m, f); moffset = LAT*LON*(m-1); unpack_data(ffilename, (data+(foffset+yoffset+moffset)), VARNAME); } } } assert((foffset+yoffset+moffset+LAT*LON)==(dim*nSamples)); //Transpose //http://stackoverflow.com/a/16743203/1267531 for(unsigned int n=0; n<(nSamples*dim); n++){ dataT[n] = data[nSamples*(n%dim) +(n/dim)]; } CPUFREE(data); }else{ //Fake data, rows of all 0s...4s char *sfilename = "../data/simple.nc"; char *varname = "data"; dmin=0; dmax=4; nSamples = 100; dim = 5; CPUMALLOC((void**)&dataT, sizeof(float)*nSamples*dim); unpack_data(sfilename, dataT, varname); /** for (int i=0; i<nSamples; i++){ for(int j=0; j<dim; j++){ printf("%1.0f ",dataT[(i*dim)+j]); } printf("\n"); }**/ } /* Allocate enough space.. */ unsigned int LSH = 0; unsigned int BS = 0; unsigned int RESULT = 0; unsigned int KNN = 0; if (argc>1){LSH = atoi(argv[1]);} if (argc>2){BS = atoi(argv[2]);} if (argc>3){RESULT = atoi(argv[3]);} if (argc>4){KNN = atoi(argv[4]);} testall(dataT, nSamples, dim, dmin, dmax, LSH, BS, RESULT); if(KNN){ test_kdtree(dataT, nSamples, dim); } CPUFREE(dataT); return 0; } void unpack_data(char *filename, float *data_in, char *varname){ //netCDF fileit and data var int ncid, varid; //loop inds and error_handling int ld, la, ln, retval; /** Open the file. NC_NOWRITE tells netCDF we want read-only access to the file.*/ if((retval = nc_open(filename, NC_NOWRITE, &ncid))) ERR(retval); /** Get the varid of the data variable, based on its name. */ if ((retval = nc_inq_varid(ncid, varname, &varid))) ERR(retval); /* Read the data. */ if ((retval = nc_get_var_float(ncid, varid, data_in))) ERR(retval); /* Close the file, freeing all resources. */ if ((retval = nc_close(ncid))) ERR(retval); //printf("*** SUCCESS reading %s!\n", filename); } <commit_msg>removed char filename[32] 'cause unused<commit_after>#include <assert.h> #include <stdio.h> #include <stdlib.h> #include <netcdf.h> #include <cudpp.h> #include <cutil.h> #include "cuda_test.h" #include "cpu_test.h" #include "cuda_defs.h" #define DEBUG 1 #define ERRCODE 2 #define ERR(e) {printf("Error: %s\n", nc_strerror(e)); exit(ERRCODE);} #define TIME 1 #define LAT 190 #define LON 384 #define VARNAME "TMP_2maboveground" #define DMIN 205 #define DMAX 320 #define MONTHS 12 void unpack_data(char *filename, float *data_in, char *varname); int main(int argc, char *argv[]){ int dmin, dmax, nSamples, dim; float *dataT=NULL; if (!DEBUG){ int start = 1985; int end = 1986; //int end = 2009; int tsamples = ((end-start) + 1)*MONTHS; dim = 9; //num forecasts dmin = DMIN; dmax = DMAX; nSamples = tsamples * LAT * LON; int foffset, yoffset, moffset; float *data = NULL; CPUMALLOC((void**)&data, sizeof(float)*nSamples*dim); CPUMALLOC((void**)&dataT, sizeof(float)*nSamples*dim); printf("%d\n", nSamples*dim); char ffilename[25]; int zcount=0; for (int f = 1; f<=9; f++){ foffset = nSamples*(f-1); for (int y =start; y<=end; y++){ yoffset = (LAT*LON*12) * (y-start); for (int m = 1; m<=MONTHS; m++){ sprintf(ffilename, "../data/TMP_%d%02d_f%02d.nc", y, m, f); moffset = LAT*LON*(m-1); unpack_data(ffilename, (data+(foffset+yoffset+moffset)), VARNAME); } } } assert((foffset+yoffset+moffset+LAT*LON)==(dim*nSamples)); //Transpose //http://stackoverflow.com/a/16743203/1267531 for(unsigned int n=0; n<(nSamples*dim); n++){ dataT[n] = data[nSamples*(n%dim) +(n/dim)]; } CPUFREE(data); }else{ //Fake data, rows of all 0s...4s char *sfilename = "../data/simple.nc"; char *varname = "data"; dmin=0; dmax=4; nSamples = 100; dim = 5; CPUMALLOC((void**)&dataT, sizeof(float)*nSamples*dim); unpack_data(sfilename, dataT, varname); /** for (int i=0; i<nSamples; i++){ for(int j=0; j<dim; j++){ printf("%1.0f ",dataT[(i*dim)+j]); } printf("\n"); }**/ } /* Allocate enough space.. */ unsigned int LSH = 0; unsigned int BS = 0; unsigned int RESULT = 0; unsigned int KNN = 0; if (argc>1){LSH = atoi(argv[1]);} if (argc>2){BS = atoi(argv[2]);} if (argc>3){RESULT = atoi(argv[3]);} if (argc>4){KNN = atoi(argv[4]);} testall(dataT, nSamples, dim, dmin, dmax, LSH, BS, RESULT); if(KNN){ test_kdtree(dataT, nSamples, dim); } CPUFREE(dataT); return 0; } void unpack_data(char *filename, float *data_in, char *varname){ //netCDF fileit and data var int ncid, varid; //loop inds and error_handling int ld, la, ln, retval; /** Open the file. NC_NOWRITE tells netCDF we want read-only access to the file.*/ if((retval = nc_open(filename, NC_NOWRITE, &ncid))) ERR(retval); /** Get the varid of the data variable, based on its name. */ if ((retval = nc_inq_varid(ncid, varname, &varid))) ERR(retval); /* Read the data. */ if ((retval = nc_get_var_float(ncid, varid, data_in))) ERR(retval); /* Close the file, freeing all resources. */ if ((retval = nc_close(ncid))) ERR(retval); //printf("*** SUCCESS reading %s!\n", filename); } <|endoftext|>
<commit_before>30f44098-5216-11e5-8497-6c40088e03e4<commit_msg>30fbe530-5216-11e5-9b35-6c40088e03e4<commit_after>30fbe530-5216-11e5-9b35-6c40088e03e4<|endoftext|>
<commit_before>7430cbc0-ad59-11e7-9082-ac87a332f658<commit_msg>Finished?<commit_after>74b50f73-ad59-11e7-b9db-ac87a332f658<|endoftext|>
<commit_before>8b332542-2d14-11e5-af21-0401358ea401<commit_msg>8b332543-2d14-11e5-af21-0401358ea401<commit_after>8b332543-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>8431fc83-2d15-11e5-af21-0401358ea401<commit_msg>8431fc84-2d15-11e5-af21-0401358ea401<commit_after>8431fc84-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>#include <cctype> #include <cmath> #include <cstdlib> #include <cstring> #include <fstream> #include <iostream> #include <sstream> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> #include "linearizer.hpp" #include "parser.hpp" #include "utils.hpp" using namespace std; void output_vector_to_file(vector<double> vec_write, ofstream &myfile) { for (auto i = 0; i < int(vec_write.size()) - 1; ++i) { myfile << vec_write[i] << ','; } myfile << vec_write[int(vec_write.size()) - 1] << endl; return; } int main() { string user_input = //"f(x)=-1.3*Ln[x]+5+3.5*x^2-2.6*Exp[x]-35,Range=0.0:10.0,Mesh=20"; //"f(x)=Exp[x],Range=0.0:10.0,Mesh=20"; "f(x)=x,Range=0.0:10.0,Mesh=20"; size_t pos = user_input.find(","); string f = user_input.substr(0, int(pos)); // first string, function cout << "Function: " << f << endl; vector<elementaryFunctionLib> terms; vector<double> coeff; parser(f, terms, coeff); for (int i = 0; i < int(terms.size()); ++i) { cout << coeff[i] << ' ' << terms[i] << endl; } string str2 = user_input.substr(int(pos) + 1); pos = str2.find(","); string range = str2.substr(0, int(pos)); // second useful string, range string mesh = str2.substr(int(pos) + 1); // third useful string, mesh vector<double> range_vec = Range_vec(range); cout << "range " << range_vec[0] << ':' << range_vec[1] << endl; int Mesh_val = get_Mesh(mesh); cout << "Mesh: " << Mesh_val << endl; // aAll, bAll of size mesh intervals are accumulated 0th and 1st moments. int meshPts = Mesh_val; vector<double> aAll(meshPts, 0.0); vector<double> bAll(meshPts, 0.0); vector<double> aCurrent(meshPts, 0.0); vector<double> bCurrent(meshPts, 0.0); double lb = range_vec[0]; double ub = range_vec[1]; for (int iTerm = 0; iTerm < int(terms.size()); iTerm++) { linearizeCurrent(terms[iTerm], lb, ub, meshPts, aCurrent, bCurrent); for (int iMesh = 0; iMesh < meshPts; iMesh++) { aAll[iMesh] += aCurrent[iMesh] * coeff[iTerm]; bAll[iMesh] += bCurrent[iMesh] * coeff[iTerm]; } } // Output aAll & bAll for debugging purposes std::cout << "first moments of the linearization" << std::endl; for(auto &i:aAll) { std::cout << i << std::endl; } std::cout << std::endl; std::cout << "zeroth moments of the linearization" << std::endl; for(auto &i:bAll) { std::cout << i << std::endl; } // Output test.txt for use in a python plotter script ofstream myfile; myfile.open("test.txt"); myfile << user_input << endl; output_vector_to_file(aAll, myfile); output_vector_to_file(bAll, myfile); myfile.close(); return 0; } <commit_msg>exhcanged aAll bAll<commit_after>#include <cctype> #include <cmath> #include <cstdlib> #include <cstring> #include <fstream> #include <iostream> #include <sstream> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> #include "linearizer.hpp" #include "parser.hpp" #include "utils.hpp" using namespace std; void output_vector_to_file(vector<double> vec_write, ofstream &myfile) { for (auto i = 0; i < int(vec_write.size()) - 1; ++i) { myfile << vec_write[i] << ','; } myfile << vec_write[int(vec_write.size()) - 1] << endl; return; } int main() { string user_input = //"f(x)=-1.3*Ln[x]+5+3.5*x^2-2.6*Exp[x]-35,Range=0.0:10.0,Mesh=20" //"f(x)=Exp[x],Range=0.0:10.0,Mesh=20" //"f(x)=x,Range=0.0:10.0,Mesh=20" //"f(x)=x^2,Range=0.0:10.0,Mesh=20" "f(x)=Sin(x),Range=0.0:10.0,Mesh=20" ; size_t pos = user_input.find(","); string f = user_input.substr(0, int(pos)); // first string, function cout << "Function: " << f << endl; vector<elementaryFunctionLib> terms; vector<double> coeff; parser(f, terms, coeff); for (int i = 0; i < int(terms.size()); ++i) { cout << coeff[i] << ' ' << terms[i] << endl; } string str2 = user_input.substr(int(pos) + 1); pos = str2.find(","); string range = str2.substr(0, int(pos)); // second useful string, range string mesh = str2.substr(int(pos) + 1); // third useful string, mesh vector<double> range_vec = Range_vec(range); cout << "range " << range_vec[0] << ':' << range_vec[1] << endl; int Mesh_val = get_Mesh(mesh); cout << "Mesh: " << Mesh_val << endl; // aAll, bAll of size mesh intervals are accumulated 0th and 1st moments. int meshPts = Mesh_val; vector<double> aAll(meshPts, 0.0); vector<double> bAll(meshPts, 0.0); vector<double> aCurrent(meshPts, 0.0); vector<double> bCurrent(meshPts, 0.0); double lb = range_vec[0]; double ub = range_vec[1]; for (int iTerm = 0; iTerm < int(terms.size()); iTerm++) { linearizeCurrent(terms[iTerm], lb, ub, meshPts, aCurrent, bCurrent); for (int iMesh = 0; iMesh < meshPts; iMesh++) { aAll[iMesh] += aCurrent[iMesh] * coeff[iTerm]; bAll[iMesh] += bCurrent[iMesh] * coeff[iTerm]; } } // Output aAll & bAll for debugging purposes std::cout << "first moments of the linearization" << std::endl; for(auto &i:aAll) { std::cout << i << std::endl; } std::cout << std::endl; std::cout << "zeroth moments of the linearization" << std::endl; for(auto &i:bAll) { std::cout << i << std::endl; } // Output test.txt for use in a python plotter script ofstream myfile; myfile.open("test.txt"); myfile << user_input << endl; output_vector_to_file(bAll, myfile); output_vector_to_file(aAll, myfile); myfile.close(); return 0; } <|endoftext|>
<commit_before>b97fbd4a-35ca-11e5-bf02-6c40088e03e4<commit_msg>b9864c8a-35ca-11e5-9757-6c40088e03e4<commit_after>b9864c8a-35ca-11e5-9757-6c40088e03e4<|endoftext|>
<commit_before>#include <string> #include <errno.h> #include <getopt.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <limits.h> #include <stdlib.h> #include "shared.h" #include "run.h" #define OPTION_NOT (1<<16) #define OPTION_FS_ALLOW 0x101 static const char optionstring[] = "+hd"; #define OPTION_BOOL(longopt, value) \ { longopt, 0, 0, value }, \ { "no-" longopt, 0, 0, value|OPTION_NOT } static const struct option options[] = { { "help", 0, 0, 'h' }, { "debug", 0, 0, 'd' }, { "none", 0, 0, 'N' }, { "fs-allow", 1, 0, OPTION_FS_ALLOW }, OPTION_BOOL("net", 'n'), OPTION_BOOL("pid", 'p'), OPTION_BOOL("ipc", 'i'), OPTION_BOOL("mount", 'm'), OPTION_BOOL("fs", 'f'), { 0, 0, 0, 0 } }; void usage(FILE* stream, int exitcode) { fprintf(stream, "Usage: sandbox [options] [--] command [args]\n\n" "Run a command in a sandbox.\n\n" "Options:\n" " --help, -h Show this message\n" " --debug, -d Enable debugging messages\n" "\n" "Sandbox features:\n" " All of the following sandbox features are enabled by default.\n" " `--no-<feature>' disables a feature.\n" "\n" " --none\n" " Disable all sandbox features.\n" " May be followed by additional options to turn on selected features.\n" "\n" " --net, --no-net\n" " Network isolation; prevents connections to any host (including\n" " localhost).\n" "\n" " --pid, --no-pid\n" " PID isolation; prevents sending signals to any process outside of\n" " the sandbox.\n" "\n" " --mount, --no-mount\n" " Mount isolation; prevents mounting or unmounting any mounts outside\n" " of the sandbox.\n" "\n" " --ipc, --no-ipc\n" " IPC isolation; prevents access to any SysV IPC resources outside of\n" " the sandbox.\n" "\n" " --fs, --no-fs\n" " Filesystem isolation; prevents modification of files outside of the\n" " sandbox.\n" "\n" "Filesystem options:\n" "\n" " --fs-allow <PATH> [ --fs-allow <PATH2> ... ]\n" " Allow writes to the specified path(s).\n" " <PATH> may contain a single relative or absolute path, or\n" " several paths separated with the : character.\n" ); exit(exitcode); } std::string realpath(std::string const& path) { char* resolved = realpath(path.c_str(), 0); if (!resolved) { fprintf(stderr, "Could not resolve %s: %s\n", path.c_str(), strerror(errno)); exit(4); } std::string out{resolved}; free(resolved); return out; } void parse_fs_allow(Context* ctx, const char* arg) { int backslash = 0; std::string current_arg; while (*arg) { if (backslash) { current_arg.append(1, *arg); backslash = 0; } else if (*arg == '\\') { backslash = 1; } else if (*arg == ':') { ctx->fuse_writable_paths.push_back(realpath(current_arg)); current_arg.clear(); } else { current_arg.append(1, *arg); } ++arg; } ctx->fuse_writable_paths.push_back(realpath(current_arg)); } void parse_arguments(Context* ctx, int argc, char** argv) { int gotopt; while ((gotopt = getopt_long(argc, argv, optionstring, options, 0))) { if (gotopt == -1) { break; } debug("gotopt 0x%x\n", gotopt); int enable = !(gotopt&OPTION_NOT); gotopt &= 0xffff; switch (gotopt) { case 'h': usage(stdout, 0); case '?': usage(stderr, 3); case 'd': ++Global::debug_mode; break; case 'N': ctx->netns = 0; ctx->pidns = 0; ctx->mountns = 0; ctx->ipcns = 0; ctx->fs = 0; break; case 'n': ctx->netns = enable; break; case 'p': ctx->pidns = enable; break; case 'i': ctx->ipcns = enable; break; case 'm': ctx->mountns = enable; break; case 'f': ctx->fs = enable; break; case OPTION_FS_ALLOW: parse_fs_allow(ctx, optarg); break; } } debug("optind %d\n", optind); ctx->child_argv = &argv[optind]; if (!ctx->child_argv[0]) { fprintf(stderr, "Not enough arguments\n"); usage(stderr, 3); } if (ctx->fs && !ctx->mountns) { fprintf(stderr, "error: filesystem sandbox requires mount sandbox.\n" "Try adding --mount to the sandbox arguments.\n"); exit(3); } ctx->mount_proc = ctx->mountns && ctx->pidns; /* If using fuse and pidns, create a pid namespace and mount namespace for the fuse layer only; this ensures the sandbox fuse process won't be visible within the sandbox, and killing the top-level sandbox process is guaranteed to kill the fuse process. */ ctx->clone_for_fuse = ctx->fs && ctx->pidns; } static char* mountpoint = 0; void remove_mountpoint() { if (rmdir(mountpoint)) { if (errno != ENOENT) { fprintf(stderr, "warning: could not remove sandbox fuse mount point %s: " "%s\n", mountpoint, strerror(errno)); } } } void setup_fuse_context(Context* ctx) { const char* tempdir = getenv("TMPDIR"); if (!tempdir) { tempdir = "/tmp"; } std::string tmpl(tempdir); tmpl += "/sandbox-fuse-XXXXXX"; char* c_mountpoint = strdup(tmpl.c_str()); if (!mkdtemp(c_mountpoint)) { perror("Can't create mount point for FUSE"); exit(3); } ctx->fuse_mountpoint = c_mountpoint; mountpoint = c_mountpoint; atexit(remove_mountpoint); } int main(int argc, char** argv) { Context ctx = { .netns = 1, .pidns = 1, .mountns = 1, .ipcns = 1, .fs = 1 }; parse_arguments(&ctx, argc, argv); if (ctx.fs) { setup_fuse_context(&ctx); } return run(&ctx); } <commit_msg>Add note about --net and unix domain sockets<commit_after>#include <string> #include <errno.h> #include <getopt.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <limits.h> #include <stdlib.h> #include "shared.h" #include "run.h" #define OPTION_NOT (1<<16) #define OPTION_FS_ALLOW 0x101 static const char optionstring[] = "+hd"; #define OPTION_BOOL(longopt, value) \ { longopt, 0, 0, value }, \ { "no-" longopt, 0, 0, value|OPTION_NOT } static const struct option options[] = { { "help", 0, 0, 'h' }, { "debug", 0, 0, 'd' }, { "none", 0, 0, 'N' }, { "fs-allow", 1, 0, OPTION_FS_ALLOW }, OPTION_BOOL("net", 'n'), OPTION_BOOL("pid", 'p'), OPTION_BOOL("ipc", 'i'), OPTION_BOOL("mount", 'm'), OPTION_BOOL("fs", 'f'), { 0, 0, 0, 0 } }; void usage(FILE* stream, int exitcode) { fprintf(stream, "Usage: sandbox [options] [--] command [args]\n\n" "Run a command in a sandbox.\n\n" "Options:\n" " --help, -h Show this message\n" " --debug, -d Enable debugging messages\n" "\n" "Sandbox features:\n" " All of the following sandbox features are enabled by default.\n" " `--no-<feature>' disables a feature.\n" "\n" " --none\n" " Disable all sandbox features.\n" " May be followed by additional options to turn on selected features.\n" "\n" " --net, --no-net\n" " Network isolation; prevents connections to any host (including\n" " localhost). This includes Unix domain socket connections.\n" "\n" " --pid, --no-pid\n" " PID isolation; prevents sending signals to any process outside of\n" " the sandbox.\n" "\n" " --mount, --no-mount\n" " Mount isolation; prevents mounting or unmounting any mounts outside\n" " of the sandbox.\n" "\n" " --ipc, --no-ipc\n" " IPC isolation; prevents access to any SysV IPC resources outside of\n" " the sandbox.\n" "\n" " --fs, --no-fs\n" " Filesystem isolation; prevents modification of files outside of the\n" " sandbox.\n" "\n" "Filesystem options:\n" "\n" " --fs-allow <PATH> [ --fs-allow <PATH2> ... ]\n" " Allow writes to the specified path(s).\n" " <PATH> may contain a single relative or absolute path, or\n" " several paths separated with the : character.\n" ); exit(exitcode); } std::string realpath(std::string const& path) { char* resolved = realpath(path.c_str(), 0); if (!resolved) { fprintf(stderr, "Could not resolve %s: %s\n", path.c_str(), strerror(errno)); exit(4); } std::string out{resolved}; free(resolved); return out; } void parse_fs_allow(Context* ctx, const char* arg) { int backslash = 0; std::string current_arg; while (*arg) { if (backslash) { current_arg.append(1, *arg); backslash = 0; } else if (*arg == '\\') { backslash = 1; } else if (*arg == ':') { ctx->fuse_writable_paths.push_back(realpath(current_arg)); current_arg.clear(); } else { current_arg.append(1, *arg); } ++arg; } ctx->fuse_writable_paths.push_back(realpath(current_arg)); } void parse_arguments(Context* ctx, int argc, char** argv) { int gotopt; while ((gotopt = getopt_long(argc, argv, optionstring, options, 0))) { if (gotopt == -1) { break; } debug("gotopt 0x%x\n", gotopt); int enable = !(gotopt&OPTION_NOT); gotopt &= 0xffff; switch (gotopt) { case 'h': usage(stdout, 0); case '?': usage(stderr, 3); case 'd': ++Global::debug_mode; break; case 'N': ctx->netns = 0; ctx->pidns = 0; ctx->mountns = 0; ctx->ipcns = 0; ctx->fs = 0; break; case 'n': ctx->netns = enable; break; case 'p': ctx->pidns = enable; break; case 'i': ctx->ipcns = enable; break; case 'm': ctx->mountns = enable; break; case 'f': ctx->fs = enable; break; case OPTION_FS_ALLOW: parse_fs_allow(ctx, optarg); break; } } debug("optind %d\n", optind); ctx->child_argv = &argv[optind]; if (!ctx->child_argv[0]) { fprintf(stderr, "Not enough arguments\n"); usage(stderr, 3); } if (ctx->fs && !ctx->mountns) { fprintf(stderr, "error: filesystem sandbox requires mount sandbox.\n" "Try adding --mount to the sandbox arguments.\n"); exit(3); } ctx->mount_proc = ctx->mountns && ctx->pidns; /* If using fuse and pidns, create a pid namespace and mount namespace for the fuse layer only; this ensures the sandbox fuse process won't be visible within the sandbox, and killing the top-level sandbox process is guaranteed to kill the fuse process. */ ctx->clone_for_fuse = ctx->fs && ctx->pidns; } static char* mountpoint = 0; void remove_mountpoint() { if (rmdir(mountpoint)) { if (errno != ENOENT) { fprintf(stderr, "warning: could not remove sandbox fuse mount point %s: " "%s\n", mountpoint, strerror(errno)); } } } void setup_fuse_context(Context* ctx) { const char* tempdir = getenv("TMPDIR"); if (!tempdir) { tempdir = "/tmp"; } std::string tmpl(tempdir); tmpl += "/sandbox-fuse-XXXXXX"; char* c_mountpoint = strdup(tmpl.c_str()); if (!mkdtemp(c_mountpoint)) { perror("Can't create mount point for FUSE"); exit(3); } ctx->fuse_mountpoint = c_mountpoint; mountpoint = c_mountpoint; atexit(remove_mountpoint); } int main(int argc, char** argv) { Context ctx = { .netns = 1, .pidns = 1, .mountns = 1, .ipcns = 1, .fs = 1 }; parse_arguments(&ctx, argc, argv); if (ctx.fs) { setup_fuse_context(&ctx); } return run(&ctx); } <|endoftext|>
<commit_before>71e22e80-5216-11e5-8bb8-6c40088e03e4<commit_msg>71ea85a6-5216-11e5-8602-6c40088e03e4<commit_after>71ea85a6-5216-11e5-8602-6c40088e03e4<|endoftext|>
<commit_before>45c20ce2-5216-11e5-8bca-6c40088e03e4<commit_msg>45c8df86-5216-11e5-85de-6c40088e03e4<commit_after>45c8df86-5216-11e5-85de-6c40088e03e4<|endoftext|>
<commit_before>#include "gameloop.hpp" #include "glhead.hpp" #include "input.hpp" #include "glresource.hpp" #include "spinner/vector.hpp" #include "gpu.hpp" #include "glx.hpp" #include "camera.hpp" #include "font.hpp" #include "updator.hpp" #include "scene.hpp" #include "sound.hpp" using namespace rs; using namespace spn; // MainThread と DrawThread 間のデータ置き場 // リソースハンドルはメインスレッド struct Mth_DthData { rs::HLInput hlIk, hlIm; rs::HLAct actQuit, actButton, actLeft, actRight, actUp, actDown, actMoveX, actMoveY, actPress; rs::HLCam hlCam; rs::SPWindow spWin; }; #define shared (Mth_Dth::_ref()) class Mth_Dth : public spn::Singleton<Mth_Dth>, public rs::SpinLock<Mth_DthData> {}; class MyDraw : public rs::IDrawProc { rs::HLFx _hlFx; rs::HLVb _hlVb; rs::HLIb _hlIb; rs::HLTex _hlTex; rs::HLText _hlText; spn::Size _size; bool _bPress; GLint _passView, _passText; public: MyDraw() { _bPress = false; struct TmpV { spn::Vec3 pos; spn::Vec4 tex; }; TmpV tmpV[] = { { spn::Vec3{-1,-1,0}, spn::Vec4{0,1,0,0} }, { spn::Vec3{-1,1,0}, spn::Vec4{0,0,0,0} }, { spn::Vec3{1,1,0}, spn::Vec4{1,0,0,0} }, { spn::Vec3{1,-1,0}, spn::Vec4{1,1,0,0} } }; // インデックス定義 GLubyte tmpI[] = { 0,1,2, 2,3,0 }; mgr_rw.addUriHandler(rs::SPUriHandler(new rs::UriH_File(u8"/"))); _hlVb = mgr_gl.makeVBuffer(GL_STATIC_DRAW); _hlVb.ref()->use()->initData(tmpV, countof(tmpV), sizeof(TmpV)); _hlIb = mgr_gl.makeIBuffer(GL_STATIC_DRAW); _hlIb.ref()->use()->initData(tmpI, countof(tmpI)); _hlTex = mgr_gl.loadTexture(spn::URI("file:///home/slice/test.png")); _hlTex.ref()->use()->setFilter(rs::IGLTexture::MipmapLinear, true,true); rs::CCoreID cid = mgr_text.makeCoreID("MS Gothic", rs::CCoreID(0, 15, CCoreID::CharFlag_AA, false, 1, CCoreID::SizeType_Point)); _hlText = mgr_text.createText(cid, U"おお_ゆうしゃよ\nなんということじゃ\nつるぎの もちかたが ちがうぞ"); rs::GPUInfo info; info.onDeviceReset(); std::cout << info; _hlFx = mgr_gl.loadEffect(spn::URI("file:///home/slice/test.glx")); auto& pFx = *_hlFx.ref(); GLint techID = pFx.getTechID("TheTech"); pFx.setTechnique(techID, true); _passView = pFx.getPassID("P0"); _passText = pFx.getPassID("P1"); // pFx.setUniform(spn::Vec4{1,2,3,4}, pFx.getUniformID("lowVal")); rs::SetSwapInterval(1); _size *= 0; auto lk = shared.lock(); auto& cd = lk->hlCam.ref(); cd.setFOV(spn::DEGtoRAD(60)); cd.setZPlane(0.01f, 500.f); } bool runU(uint64_t accum) override { glClearColor(0,0,1,1); glClearDepth(1.0f); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); auto lk = shared.lock(); auto& cd = lk->hlCam.ref(); auto sz = lk->spWin->getSize(); if(sz != _size) { _size = sz; cd.setAspect(float(_size.width)/_size.height); glViewport(0,0,_size.width, _size.height); } auto& fx = *_hlFx.ref(); fx.setPass(_passView); GLint id = fx.getUniformID("mTrans"); auto btn = mgr_input.isKeyPressing(lk->actPress); if(btn ^ _bPress) { lk->hlIm.ref()->setMouseMode((!_bPress) ? rs::MouseMode::Relative : rs::MouseMode::Absolute); _bPress = btn; } constexpr float speed = 0.25f; float mvF=0, mvS=0; if(mgr_input.isKeyPressing(lk->actUp)) mvF += speed; if(mgr_input.isKeyPressing(lk->actDown)) mvF -= speed; if(mgr_input.isKeyPressing(lk->actLeft)) mvS -= speed; if(mgr_input.isKeyPressing(lk->actRight)) mvS += speed; cd.moveFwd3D(mvF); cd.moveSide3D(mvS); if(_bPress) { float xv = mgr_input.getKeyValue(lk->actMoveX)/4.f, yv = mgr_input.getKeyValue(lk->actMoveY)/4.f; cd.addRot(spn::Quat::RotationY(spn::DEGtoRAD(-xv))); cd.addRot(spn::Quat::RotationX(spn::DEGtoRAD(-yv))); } fx.setUniform(cd.getViewProjMatrix().convert44(), id); id = fx.getUniformID("tDiffuse"); fx.setUniform(_hlTex, id); // 頂点フォーマット定義 rs::SPVDecl decl(new rs::VDecl{ {0,0, GL_FLOAT, GL_FALSE, 3, (GLuint)rs::VSem::POSITION}, {0,12, GL_FLOAT, GL_FALSE, 4, (GLuint)rs::VSem::TEXCOORD0} }); fx.setVDecl(std::move(decl)); fx.setVStream(_hlVb.get(), 0); fx.setIStream(_hlIb.get()); fx.drawIndexed(GL_TRIANGLES, 6, 0); fx.setPass(_passText); id = fx.getUniformID("mText"); auto fn = [](int x, int y, float r) { float rx = Rcp22Bit(512), ry = Rcp22Bit(384); return Mat33(rx*r, 0, 0, 0, ry*r, 0, -1.f+x*rx, 1.f-y*ry, 1); }; fx.setUniform(fn(0,0,1), id); _hlText.ref().draw(&fx); return true; } }; class TestObj : public ObjectT<TestObj> { class MySt : public State { public: MySt(StateID id): State(id) {} void onUpdate(TestObj& self) { // self.destroy(); } }; public: TestObj() { LogOutput("TestObj::ctor"); setStateNew<MySt>(128); } ~TestObj() { LogOutput("TestObj::dtor"); } void onDestroy() override { LogOutput("TestObj::onDestroy"); } }; class TScene2 : public Scene<TScene2> { class MySt : public State { public: MySt(): State(0) {} void onUpdate(TScene2& self) override { auto lk = shared.lock(); if(mgr_input.isKeyPressed(lk->actRight)) mgr_scene.setPopScene(1); } }; public: TScene2() { setStateNew<MySt>(); LogOutput("TScene2::ctor"); } ~TScene2() { LogOutput("TScene2::dtor"); } }; class TScene : public Scene<TScene> { HLAb _hlAb; HLSs _hlSs; class MySt : public State { public: MySt(StateID id): State(id) {} void onEnter(TScene& self, StateID prevID) override { self._hlAb = mgr_sound.loadOggStream(mgr_rw.fromFile("/home/slice/test.ogg", RWops::Read, false)); self._hlSs = mgr_sound.createSource(); self._hlSs.ref().setBuffer(self._hlAb, 0); } void onUpdate(TScene& self) override { HGbj hGbj(rep_gobj.getObj(c_id)); if(!hGbj.valid()) self.destroy(); auto lk = shared.lock(); if(mgr_input.isKeyPressed(lk->actLeft)) mgr_scene.setPushScene(mgr_gobj.emplace(new TScene2())); if(mgr_input.isKeyPressed(lk->actQuit)) mgr_scene.setPopScene(1); } void onDown(TScene& self, ObjTypeID prevID, const Variant& arg) override { LogOutput("TScene::onDown"); auto& s = self._hlSs.ref(); s.stop(); s.setFadeOut(std::chrono::seconds(5)); s.play(); } void onPause(TScene& self) override { LogOutput("TScene::onPause"); } void onResume(TScene& self) override { LogOutput("TScene::onResume"); } void onStop(TScene& self) override { LogOutput("TScene::onStop"); } void onReStart(TScene& self) override { LogOutput("TScene::onReStart"); } }; public: const static ObjID c_id; TScene(): Scene(0) { setStateNew<MySt>(256); LogOutput("TScene::ctor"); HLGbj hg = mgr_gobj.emplace(new TestObj()); rep_gobj.setObj(c_id, hg.weak()); _update.addObj(0, hg); hg.release(); } void onDestroy() override { LogOutput("TScene::onDestroy"); } ~TScene() { LogOutput("TScene::dtor"); } }; const ObjID TScene::c_id = rep_gobj.RegID("Player"); class MyMain : public rs::IMainProc { Mth_Dth _mth; public: MyMain(const rs::SPWindow& sp) { auto lk = shared.lock(); lk->hlIk = rs::Keyboard::OpenKeyboard(); lk->spWin = sp; lk->actQuit = mgr_input.addAction("quit"); mgr_input.link(lk->actQuit, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_ESCAPE)); lk->actButton = mgr_input.addAction("button"); mgr_input.link(lk->actButton, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_LSHIFT)); lk->actLeft = mgr_input.addAction("left"); lk->actRight = mgr_input.addAction("right"); lk->actUp = mgr_input.addAction("up"); lk->actDown = mgr_input.addAction("down"); lk->actMoveX = mgr_input.addAction("moveX"); lk->actMoveY = mgr_input.addAction("moveY"); lk->actPress = mgr_input.addAction("press"); mgr_input.link(lk->actLeft, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_A)); mgr_input.link(lk->actRight, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_D)); mgr_input.link(lk->actUp, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_W)); mgr_input.link(lk->actDown, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_S)); lk->hlIm = rs::Mouse::OpenMouse(0); lk->hlIm.ref()->setMouseMode(rs::MouseMode::Absolute); lk->hlIm.ref()->setDeadZone(0, 1.f, 0.f); lk->hlIm.ref()->setDeadZone(1, 1.f, 0.f); mgr_input.link(lk->actMoveX, rs::InF::AsAxis(lk->hlIm, 0)); mgr_input.link(lk->actMoveY, rs::InF::AsAxis(lk->hlIm, 1)); mgr_input.link(lk->actPress, rs::InF::AsButton(lk->hlIm, 0)); lk->hlCam = mgr_cam.emplace(); rs::CamData& cd = lk->hlCam.ref(); cd.setOfs(0,0,-3); mgr_scene.setPushScene(mgr_gobj.emplace(new TScene())); } bool runU() override { mgr_sound.update(); return !mgr_scene.onUpdate(); } void onPause() override { mgr_scene.onPause(); } void onResume() override { mgr_scene.onResume(); } void onStop() override { mgr_scene.onStop(); } void onReStart() override { mgr_scene.onReStart(); } rs::IDrawProc* initDraw() override { return new MyDraw; } }; int main(int argc, char **argv) { GameLoop gloop([](const rs::SPWindow& sp){ return new MyMain(sp); }); return gloop.run("HelloSDL2", 1024, 768, SDL_WINDOW_SHOWN, 2,0,24); } <commit_msg>テストコード: AGroup<commit_after>#include "gameloop.hpp" #include "glhead.hpp" #include "input.hpp" #include "glresource.hpp" #include "spinner/vector.hpp" #include "gpu.hpp" #include "glx.hpp" #include "camera.hpp" #include "font.hpp" #include "updator.hpp" #include "scene.hpp" #include "sound.hpp" using namespace rs; using namespace spn; // MainThread と DrawThread 間のデータ置き場 // リソースハンドルはメインスレッド struct Mth_DthData { rs::HLInput hlIk, hlIm; rs::HLAct actQuit, actButton, actLeft, actRight, actUp, actDown, actMoveX, actMoveY, actPress; rs::HLCam hlCam; rs::SPWindow spWin; }; #define shared (Mth_Dth::_ref()) class Mth_Dth : public spn::Singleton<Mth_Dth>, public rs::SpinLock<Mth_DthData> {}; class MyDraw : public rs::IDrawProc { rs::HLFx _hlFx; rs::HLVb _hlVb; rs::HLIb _hlIb; rs::HLTex _hlTex; rs::HLText _hlText; spn::Size _size; bool _bPress; GLint _passView, _passText; public: MyDraw() { _bPress = false; struct TmpV { spn::Vec3 pos; spn::Vec4 tex; }; TmpV tmpV[] = { { spn::Vec3{-1,-1,0}, spn::Vec4{0,1,0,0} }, { spn::Vec3{-1,1,0}, spn::Vec4{0,0,0,0} }, { spn::Vec3{1,1,0}, spn::Vec4{1,0,0,0} }, { spn::Vec3{1,-1,0}, spn::Vec4{1,1,0,0} } }; // インデックス定義 GLubyte tmpI[] = { 0,1,2, 2,3,0 }; mgr_rw.addUriHandler(rs::SPUriHandler(new rs::UriH_File(u8"/"))); _hlVb = mgr_gl.makeVBuffer(GL_STATIC_DRAW); _hlVb.ref()->use()->initData(tmpV, countof(tmpV), sizeof(TmpV)); _hlIb = mgr_gl.makeIBuffer(GL_STATIC_DRAW); _hlIb.ref()->use()->initData(tmpI, countof(tmpI)); _hlTex = mgr_gl.loadTexture(spn::URI("file:///home/slice/test.png")); _hlTex.ref()->use()->setFilter(rs::IGLTexture::MipmapLinear, true,true); rs::CCoreID cid = mgr_text.makeCoreID("MS Gothic", rs::CCoreID(0, 15, CCoreID::CharFlag_AA, false, 1, CCoreID::SizeType_Point)); _hlText = mgr_text.createText(cid, U"おお_ゆうしゃよ\nなんということじゃ\nつるぎの もちかたが ちがうぞ"); rs::GPUInfo info; info.onDeviceReset(); std::cout << info; _hlFx = mgr_gl.loadEffect(spn::URI("file:///home/slice/test.glx")); auto& pFx = *_hlFx.ref(); GLint techID = pFx.getTechID("TheTech"); pFx.setTechnique(techID, true); _passView = pFx.getPassID("P0"); _passText = pFx.getPassID("P1"); // pFx.setUniform(spn::Vec4{1,2,3,4}, pFx.getUniformID("lowVal")); rs::SetSwapInterval(1); _size *= 0; auto lk = shared.lock(); auto& cd = lk->hlCam.ref(); cd.setFOV(spn::DEGtoRAD(60)); cd.setZPlane(0.01f, 500.f); } bool runU(uint64_t accum) override { glClearColor(0,0,1,1); glClearDepth(1.0f); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); auto lk = shared.lock(); auto& cd = lk->hlCam.ref(); auto sz = lk->spWin->getSize(); if(sz != _size) { _size = sz; cd.setAspect(float(_size.width)/_size.height); glViewport(0,0,_size.width, _size.height); } auto& fx = *_hlFx.ref(); fx.setPass(_passView); GLint id = fx.getUniformID("mTrans"); auto btn = mgr_input.isKeyPressing(lk->actPress); if(btn ^ _bPress) { lk->hlIm.ref()->setMouseMode((!_bPress) ? rs::MouseMode::Relative : rs::MouseMode::Absolute); _bPress = btn; } constexpr float speed = 0.25f; float mvF=0, mvS=0; if(mgr_input.isKeyPressing(lk->actUp)) mvF += speed; if(mgr_input.isKeyPressing(lk->actDown)) mvF -= speed; if(mgr_input.isKeyPressing(lk->actLeft)) mvS -= speed; if(mgr_input.isKeyPressing(lk->actRight)) mvS += speed; cd.moveFwd3D(mvF); cd.moveSide3D(mvS); if(_bPress) { float xv = mgr_input.getKeyValue(lk->actMoveX)/4.f, yv = mgr_input.getKeyValue(lk->actMoveY)/4.f; cd.addRot(spn::Quat::RotationY(spn::DEGtoRAD(-xv))); cd.addRot(spn::Quat::RotationX(spn::DEGtoRAD(-yv))); } fx.setUniform(cd.getViewProjMatrix().convert44(), id); id = fx.getUniformID("tDiffuse"); fx.setUniform(_hlTex, id); // 頂点フォーマット定義 rs::SPVDecl decl(new rs::VDecl{ {0,0, GL_FLOAT, GL_FALSE, 3, (GLuint)rs::VSem::POSITION}, {0,12, GL_FLOAT, GL_FALSE, 4, (GLuint)rs::VSem::TEXCOORD0} }); fx.setVDecl(std::move(decl)); fx.setVStream(_hlVb.get(), 0); fx.setIStream(_hlIb.get()); fx.drawIndexed(GL_TRIANGLES, 6, 0); fx.setPass(_passText); id = fx.getUniformID("mText"); auto fn = [](int x, int y, float r) { float rx = Rcp22Bit(512), ry = Rcp22Bit(384); return Mat33(rx*r, 0, 0, 0, ry*r, 0, -1.f+x*rx, 1.f-y*ry, 1); }; fx.setUniform(fn(0,0,1), id); _hlText.ref().draw(&fx); return true; } }; class TestObj : public ObjectT<TestObj> { class MySt : public State { public: MySt(StateID id): State(id) {} void onUpdate(TestObj& self) { // self.destroy(); } }; public: TestObj() { LogOutput("TestObj::ctor"); setStateNew<MySt>(128); } ~TestObj() { LogOutput("TestObj::dtor"); } void onDestroy() override { LogOutput("TestObj::onDestroy"); } }; class TScene2 : public Scene<TScene2> { class MySt : public State { public: MySt(): State(0) {} void onUpdate(TScene2& self) override { auto lk = shared.lock(); if(mgr_input.isKeyPressed(lk->actRight)) mgr_scene.setPopScene(1); } }; public: TScene2() { setStateNew<MySt>(); LogOutput("TScene2::ctor"); } ~TScene2() { LogOutput("TScene2::dtor"); } }; class TScene : public Scene<TScene> { HLAb _hlAb; HLSg _hlSg; class MySt : public State { public: MySt(StateID id): State(id) {} void onEnter(TScene& self, StateID prevID) override { self._hlAb = mgr_sound.loadOggStream(mgr_rw.fromFile("/home/slice/test.ogg", RWops::Read, false)); self._hlSg = mgr_sound.createSourceGroup(1); } void onUpdate(TScene& self) override { HGbj hGbj(rep_gobj.getObj(c_id)); if(!hGbj.valid()) self.destroy(); auto lk = shared.lock(); if(mgr_input.isKeyPressed(lk->actLeft)) mgr_scene.setPushScene(mgr_gobj.emplace(new TScene2())); if(mgr_input.isKeyPressed(lk->actQuit)) mgr_scene.setPopScene(1); } void onDown(TScene& self, ObjTypeID prevID, const Variant& arg) override { LogOutput("TScene::onDown"); auto& s = self._hlSg.ref(); s.clear(); s.play(self._hlAb, 0); } void onPause(TScene& self) override { LogOutput("TScene::onPause"); } void onResume(TScene& self) override { LogOutput("TScene::onResume"); } void onStop(TScene& self) override { LogOutput("TScene::onStop"); } void onReStart(TScene& self) override { LogOutput("TScene::onReStart"); } }; public: const static ObjID c_id; TScene(): Scene(0) { setStateNew<MySt>(256); LogOutput("TScene::ctor"); HLGbj hg = mgr_gobj.emplace(new TestObj()); rep_gobj.setObj(c_id, hg.weak()); _update.addObj(0, hg); hg.release(); } void onDestroy() override { LogOutput("TScene::onDestroy"); } ~TScene() { LogOutput("TScene::dtor"); } }; const ObjID TScene::c_id = rep_gobj.RegID("Player"); class MyMain : public rs::IMainProc { Mth_Dth _mth; public: MyMain(const rs::SPWindow& sp) { auto lk = shared.lock(); lk->hlIk = rs::Keyboard::OpenKeyboard(); lk->spWin = sp; lk->actQuit = mgr_input.addAction("quit"); mgr_input.link(lk->actQuit, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_ESCAPE)); lk->actButton = mgr_input.addAction("button"); mgr_input.link(lk->actButton, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_LSHIFT)); lk->actLeft = mgr_input.addAction("left"); lk->actRight = mgr_input.addAction("right"); lk->actUp = mgr_input.addAction("up"); lk->actDown = mgr_input.addAction("down"); lk->actMoveX = mgr_input.addAction("moveX"); lk->actMoveY = mgr_input.addAction("moveY"); lk->actPress = mgr_input.addAction("press"); mgr_input.link(lk->actLeft, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_A)); mgr_input.link(lk->actRight, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_D)); mgr_input.link(lk->actUp, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_W)); mgr_input.link(lk->actDown, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_S)); lk->hlIm = rs::Mouse::OpenMouse(0); lk->hlIm.ref()->setMouseMode(rs::MouseMode::Absolute); lk->hlIm.ref()->setDeadZone(0, 1.f, 0.f); lk->hlIm.ref()->setDeadZone(1, 1.f, 0.f); mgr_input.link(lk->actMoveX, rs::InF::AsAxis(lk->hlIm, 0)); mgr_input.link(lk->actMoveY, rs::InF::AsAxis(lk->hlIm, 1)); mgr_input.link(lk->actPress, rs::InF::AsButton(lk->hlIm, 0)); lk->hlCam = mgr_cam.emplace(); rs::CamData& cd = lk->hlCam.ref(); cd.setOfs(0,0,-3); mgr_scene.setPushScene(mgr_gobj.emplace(new TScene())); } bool runU() override { mgr_sound.update(); return !mgr_scene.onUpdate(); } void onPause() override { mgr_scene.onPause(); } void onResume() override { mgr_scene.onResume(); } void onStop() override { mgr_scene.onStop(); } void onReStart() override { mgr_scene.onReStart(); } rs::IDrawProc* initDraw() override { return new MyDraw; } }; int main(int argc, char **argv) { GameLoop gloop([](const rs::SPWindow& sp){ return new MyMain(sp); }); return gloop.run("HelloSDL2", 1024, 768, SDL_WINDOW_SHOWN, 2,0,24); } <|endoftext|>
<commit_before>// // Copyright (C) 2003-2008 by Warren Woodford // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include <QApplication> #include <QTranslator> #include <QLocale> #include "mainwindow.h" #include <unistd.h> int main( int argc, char ** argv ) { QApplication app(argc, argv); app.setWindowIcon(QIcon::fromTheme("mx-user")); QTranslator qtTran; qtTran.load(QString("qt_") + QLocale::system().name()); app.installTranslator(&qtTran); QTranslator appTran; appTran.load(QString("mx-user_") + QLocale::system().name(), "/usr/share/mx-user/locale"); app.installTranslator(&appTran); if (getuid() == 0) { MainWindow mw; mw.show(); return app.exec(); } else { QApplication::beep(); QMessageBox::critical(nullptr, QString::null, QApplication::tr("You must run this program as root.")); return EXIT_FAILURE; } } <commit_msg>restart as root<commit_after>// // Copyright (C) 2003-2008 by Warren Woodford // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include <QApplication> #include <QTranslator> #include <QLocale> #include "mainwindow.h" #include <unistd.h> int main( int argc, char ** argv ) { QApplication app(argc, argv); app.setWindowIcon(QIcon::fromTheme("mx-user")); QTranslator qtTran; qtTran.load(QString("qt_") + QLocale::system().name()); app.installTranslator(&qtTran); QTranslator appTran; appTran.load(QString("mx-user_") + QLocale::system().name(), "/usr/share/mx-user/locale"); app.installTranslator(&appTran); if (getuid() == 0) { MainWindow mw; mw.show(); return app.exec(); } else { system("su-to-root -X -c " + QCoreApplication::applicationFilePath().toUtf8() + "&"); // QApplication::beep(); // QMessageBox::critical(nullptr, QString::null, // QApplication::tr("You must run this program as root.")); // return EXIT_FAILURE; } } <|endoftext|>
<commit_before>9226e764-35ca-11e5-ba1d-6c40088e03e4<commit_msg>922d4640-35ca-11e5-b88e-6c40088e03e4<commit_after>922d4640-35ca-11e5-b88e-6c40088e03e4<|endoftext|>
<commit_before>3990ac6e-2d3e-11e5-ad75-c82a142b6f9b<commit_msg>39ebd7f8-2d3e-11e5-84ac-c82a142b6f9b<commit_after>39ebd7f8-2d3e-11e5-84ac-c82a142b6f9b<|endoftext|>
<commit_before>b79173c0-2e4f-11e5-9ae5-28cfe91dbc4b<commit_msg>b7985168-2e4f-11e5-9c0e-28cfe91dbc4b<commit_after>b7985168-2e4f-11e5-9c0e-28cfe91dbc4b<|endoftext|>
<commit_before>9668fd26-2e4f-11e5-8aa8-28cfe91dbc4b<commit_msg>967104f8-2e4f-11e5-b001-28cfe91dbc4b<commit_after>967104f8-2e4f-11e5-b001-28cfe91dbc4b<|endoftext|>
<commit_before>67aac44c-2e4f-11e5-bbfa-28cfe91dbc4b<commit_msg>67b1675c-2e4f-11e5-9de5-28cfe91dbc4b<commit_after>67b1675c-2e4f-11e5-9de5-28cfe91dbc4b<|endoftext|>
<commit_before>5c8bf208-2e3a-11e5-8e9e-c03896053bdd<commit_msg>5c9ac1ca-2e3a-11e5-aa47-c03896053bdd<commit_after>5c9ac1ca-2e3a-11e5-aa47-c03896053bdd<|endoftext|>
<commit_before>#include "base.h" #include "camera_list.h" #include "camera.h" using namespace dslr; #if 0 EdsError GetCurrentDevice(EdsCameraRef camera, EdsUInt32* device) { // Get current device setting return EdsGetPropertyData(camera, kEdsPropID_Evf_OutputDevice, 0, sizeof(*device), device); } EdsError SetDevice(EdsCameraRef camera, EdsUInt32 device) { return SetProperty<kEdsPropID_Evf_OutputDevice>(camera, device); } EdsError StartLiveView(EdsCameraRef camera) { #if 0 EdsError err; EdsUInt32 device; err = GetCurrentDevice(camera, &device); if (EDS_ERR_OK != err) { return err; } std::cout << "Device = " << device << std::endl; device |= kEdsEvfOutputDevice_PC; #endif return SetDevice(camera, kEdsEvfOutputDevice_PC); } EdsError EndLiveView(EdsCameraRef camera) { #if 0 EdsError err; EdsUInt32 device; err = GetCurrentDevice(camera, &device); if (EDS_ERR_OK != err) { return err; } device &= ~kEdsEvfOutputDevice_TFT; #endif return SetDevice(camera, 0); } #endif int main() { EdsError err; err = EdsInitializeSDK(); if (EDS_ERR_OK != err) { throw err; } CameraList cameraList; std::cout << "There are " << cameraList.Count() << " cameras connected.\n"; if (cameraList.Count() > 0) { Camera camera = cameraList.get(0); camera.SetProperty(kEdsPropID_SaveTo, kEdsSaveTo_Host); } EdsTerminateSDK(); return 0; } <commit_msg>Removing old live view stuff.<commit_after>#include "base.h" #include "camera_list.h" #include "camera.h" using namespace dslr; int main() { EdsError err; err = EdsInitializeSDK(); if (EDS_ERR_OK != err) { throw err; } CameraList cameraList; std::cout << "There are " << cameraList.Count() << " cameras connected.\n"; if (cameraList.Count() > 0) { Camera camera = cameraList.get(0); camera.SetProperty(kEdsPropID_SaveTo, kEdsSaveTo_Host); } EdsTerminateSDK(); return 0; } <|endoftext|>
<commit_before>0ae174ae-2f67-11e5-8901-6c40088e03e4<commit_msg>0ae83958-2f67-11e5-b5eb-6c40088e03e4<commit_after>0ae83958-2f67-11e5-b5eb-6c40088e03e4<|endoftext|>
<commit_before>6c44b664-2fa5-11e5-9bd7-00012e3d3f12<commit_msg>6c468b24-2fa5-11e5-8796-00012e3d3f12<commit_after>6c468b24-2fa5-11e5-8796-00012e3d3f12<|endoftext|>
<commit_before>e9ac25d4-2e4e-11e5-b059-28cfe91dbc4b<commit_msg>e9b2bedc-2e4e-11e5-a6ea-28cfe91dbc4b<commit_after>e9b2bedc-2e4e-11e5-a6ea-28cfe91dbc4b<|endoftext|>
<commit_before>809e9198-2d15-11e5-af21-0401358ea401<commit_msg>809e9199-2d15-11e5-af21-0401358ea401<commit_after>809e9199-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>b6e6d74c-327f-11e5-9366-9cf387a8033e<commit_msg>b6ece0b0-327f-11e5-bb61-9cf387a8033e<commit_after>b6ece0b0-327f-11e5-bb61-9cf387a8033e<|endoftext|>
<commit_before>aa096e2e-2e4f-11e5-acc3-28cfe91dbc4b<commit_msg>aa106b1e-2e4f-11e5-b70a-28cfe91dbc4b<commit_after>aa106b1e-2e4f-11e5-b70a-28cfe91dbc4b<|endoftext|>
<commit_before>bec43e1e-2d3c-11e5-a467-c82a142b6f9b<commit_msg>bf1853fd-2d3c-11e5-8ac4-c82a142b6f9b<commit_after>bf1853fd-2d3c-11e5-8ac4-c82a142b6f9b<|endoftext|>
<commit_before>072f5ea2-2f67-11e5-a0e8-6c40088e03e4<commit_msg>07377edc-2f67-11e5-8e68-6c40088e03e4<commit_after>07377edc-2f67-11e5-8e68-6c40088e03e4<|endoftext|>
<commit_before>11b7a426-2d3d-11e5-8eb2-c82a142b6f9b<commit_msg>1217b70a-2d3d-11e5-8e76-c82a142b6f9b<commit_after>1217b70a-2d3d-11e5-8e76-c82a142b6f9b<|endoftext|>
<commit_before>f1539294-327f-11e5-815b-9cf387a8033e<commit_msg>f15990ae-327f-11e5-95ce-9cf387a8033e<commit_after>f15990ae-327f-11e5-95ce-9cf387a8033e<|endoftext|>
<commit_before>ea526b94-2e4e-11e5-81c2-28cfe91dbc4b<commit_msg>ea594e26-2e4e-11e5-8a95-28cfe91dbc4b<commit_after>ea594e26-2e4e-11e5-8a95-28cfe91dbc4b<|endoftext|>
<commit_before>43e94135-2d3f-11e5-a0e8-c82a142b6f9b<commit_msg>4454ba2b-2d3f-11e5-8fc4-c82a142b6f9b<commit_after>4454ba2b-2d3f-11e5-8fc4-c82a142b6f9b<|endoftext|>
<commit_before>2ee65136-5216-11e5-8eb5-6c40088e03e4<commit_msg>2ef08dc2-5216-11e5-bd63-6c40088e03e4<commit_after>2ef08dc2-5216-11e5-bd63-6c40088e03e4<|endoftext|>
<commit_before>#include <vector> #include <tuple> #include <fstream> #include "Windows.h" #include <psapi.h> using namespace std; namespace { typedef void(*callable)(void*); typedef tuple<void*, size_t> MyTuple; constexpr DWORD invocation_interval_ms = 15 * 1000; constexpr size_t stack_size = 0x10000; struct SetupConfiguration { uint32_t initialized; void* setup_address; uint32_t setup_length; void* VirtualProtectEx; void* WaitForSingleObjectEx; void* CreateWaitableTimer; void* SetWaitableTimer; void* MessageBox; void* tramp_addr; void* sleep_handle; uint32_t interval; void* target; uint8_t shadow[8]; }; struct StackTrampoline { void* VirtualProtectEx; void* return_address; void* current_process; void* address; uint32_t size; uint32_t protections; void* old_protections_ptr; uint32_t old_protections; void* setup_config; }; struct Workspace { SetupConfiguration config; uint8_t stack[stack_size]; StackTrampoline tramp; }; } Workspace& allocate_workspace() { auto result = VirtualAllocEx(GetCurrentProcess(), nullptr, sizeof(Workspace), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); if (!result) throw runtime_error("[-] Couldn't VirtualAllocEx: " + GetLastError()); RtlSecureZeroMemory(result, sizeof(Workspace)); return *static_cast<Workspace*>(result); } MyTuple allocate_pic(const string& filename) { fstream file_stream{ filename, fstream::in | fstream::ate | fstream::binary }; if (!file_stream) throw runtime_error("[-] Couldn't open " + filename); auto pic_size = static_cast<size_t>(file_stream.tellg()); file_stream.seekg(0, fstream::beg); auto pic = VirtualAllocEx(GetCurrentProcess(), nullptr, pic_size, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); if (!pic) throw runtime_error("[-] Couldn't VirtualAllocEx: " + GetLastError()); file_stream.read(static_cast<char*>(pic), pic_size); file_stream.close(); DWORD old_protection; auto prot_result = VirtualProtectEx(GetCurrentProcess(), pic, pic_size, PAGE_EXECUTE_READ, &old_protection); if (!prot_result) throw runtime_error("[-] Couldn't VirtualProtectEx: " + GetLastError()); return MyTuple((void*) pic, (size_t) pic_size); } void* get_gadget(bool use_mshtml, const string& gadget_pic_path) { if (use_mshtml) { printf("[ ] Loading mshtml.dll.\n"); auto mshtml_base = reinterpret_cast<uint8_t*>(LoadLibraryA("mshtml.dll")); printf("[+] Loaded mshtml.dll into memory at 0x%p.\n", mshtml_base); return mshtml_base + 7165405; } else { printf("[ ] Allocating memory for %s.\n", gadget_pic_path.c_str()); void* memory; size_t size; tie(memory, size) = allocate_pic(gadget_pic_path); printf("[ ] Allocated %u bytes for gadget PIC.\n", size); return memory; } } void launch(const string& setup_pic_path, const string& gadget_pic_path) { printf("[ ] Allocating executable memory for %s.\n", setup_pic_path.c_str()); void* setup_memory; size_t setup_size; tie(setup_memory, setup_size) = allocate_pic(setup_pic_path); printf("[+] Allocated %d bytes for PIC.\n", setup_size); auto use_mshtml{ true }; printf("[ ] Configuring ROP gadget.\n"); auto gadget_memory = get_gadget(use_mshtml, gadget_pic_path); printf("[+] ROP gadget configured.\n"); printf("[ ] Allocating read/write memory for config, stack, and trampoline.\n"); auto& scratch_memory = allocate_workspace(); auto& config = scratch_memory.config; auto& tramp = scratch_memory.tramp; printf("[+] Allocated %u bytes for scratch memory.\n", sizeof(scratch_memory)); printf("[ ] Building stack trampoline.\n"); tramp.old_protections_ptr = &tramp.old_protections; tramp.protections = PAGE_EXECUTE_READ; tramp.current_process = GetCurrentProcess(); tramp.VirtualProtectEx = VirtualProtectEx; tramp.size = static_cast<uint32_t>(setup_size); tramp.address = setup_memory; tramp.return_address = setup_memory; tramp.setup_config = &config; printf("[+] Stack trampoline built.\n"); printf("[ ] Building configuration.\n"); config.setup_address = setup_memory; config.setup_length = static_cast<uint32_t>(setup_size); config.VirtualProtectEx = VirtualProtectEx; config.WaitForSingleObjectEx = WaitForSingleObjectEx; config.CreateWaitableTimer = CreateWaitableTimerW; config.SetWaitableTimer = SetWaitableTimer; config.MessageBox = MessageBoxA; config.tramp_addr = &tramp; config.interval = invocation_interval_ms; config.target = gadget_memory; printf("[+] Configuration built.\n"); printf("[+] Success!\n"); printf(" ================================\n"); printf(" Gargoyle PIC @ -----> 0x%p\n", setup_memory); printf(" ROP gadget @ -------> 0x%p\n", gadget_memory); printf(" Configuration @ ----> 0x%p\n", &scratch_memory.config); printf(" Top of stack @ -----> 0x%p\n", &scratch_memory.stack); printf(" Bottom of stack @ --> 0x%p\n", &scratch_memory.stack[stack_size-1]); printf(" Stack trampoline @ -> 0x%p\n", &scratch_memory.tramp); reinterpret_cast<callable>(setup_memory)(&config); } int main() { try { launch("setup.pic", "gadget.pic"); } catch (exception& e) { printf("%s\n", e.what()); } } <commit_msg>removing unnecessary c-style casts<commit_after>#include <vector> #include <tuple> #include <fstream> #include "Windows.h" #include <psapi.h> using namespace std; namespace { typedef void(*callable)(void*); typedef tuple<void*, size_t> MyTuple; constexpr DWORD invocation_interval_ms = 15 * 1000; constexpr size_t stack_size = 0x10000; struct SetupConfiguration { uint32_t initialized; void* setup_address; uint32_t setup_length; void* VirtualProtectEx; void* WaitForSingleObjectEx; void* CreateWaitableTimer; void* SetWaitableTimer; void* MessageBox; void* tramp_addr; void* sleep_handle; uint32_t interval; void* target; uint8_t shadow[8]; }; struct StackTrampoline { void* VirtualProtectEx; void* return_address; void* current_process; void* address; uint32_t size; uint32_t protections; void* old_protections_ptr; uint32_t old_protections; void* setup_config; }; struct Workspace { SetupConfiguration config; uint8_t stack[stack_size]; StackTrampoline tramp; }; } Workspace& allocate_workspace() { auto result = VirtualAllocEx(GetCurrentProcess(), nullptr, sizeof(Workspace), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); if (!result) throw runtime_error("[-] Couldn't VirtualAllocEx: " + GetLastError()); RtlSecureZeroMemory(result, sizeof(Workspace)); return *static_cast<Workspace*>(result); } MyTuple allocate_pic(const string& filename) { fstream file_stream{ filename, fstream::in | fstream::ate | fstream::binary }; if (!file_stream) throw runtime_error("[-] Couldn't open " + filename); auto pic_size = static_cast<size_t>(file_stream.tellg()); file_stream.seekg(0, fstream::beg); auto pic = VirtualAllocEx(GetCurrentProcess(), nullptr, pic_size, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); if (!pic) throw runtime_error("[-] Couldn't VirtualAllocEx: " + GetLastError()); file_stream.read(static_cast<char*>(pic), pic_size); file_stream.close(); DWORD old_protection; auto prot_result = VirtualProtectEx(GetCurrentProcess(), pic, pic_size, PAGE_EXECUTE_READ, &old_protection); if (!prot_result) throw runtime_error("[-] Couldn't VirtualProtectEx: " + GetLastError()); return MyTuple(pic, pic_size); } void* get_gadget(bool use_mshtml, const string& gadget_pic_path) { if (use_mshtml) { printf("[ ] Loading mshtml.dll.\n"); auto mshtml_base = reinterpret_cast<uint8_t*>(LoadLibraryA("mshtml.dll")); printf("[+] Loaded mshtml.dll into memory at 0x%p.\n", mshtml_base); return mshtml_base + 7165405; } else { printf("[ ] Allocating memory for %s.\n", gadget_pic_path.c_str()); void* memory; size_t size; tie(memory, size) = allocate_pic(gadget_pic_path); printf("[ ] Allocated %u bytes for gadget PIC.\n", size); return memory; } } void launch(const string& setup_pic_path, const string& gadget_pic_path) { printf("[ ] Allocating executable memory for %s.\n", setup_pic_path.c_str()); void* setup_memory; size_t setup_size; tie(setup_memory, setup_size) = allocate_pic(setup_pic_path); printf("[+] Allocated %d bytes for PIC.\n", setup_size); auto use_mshtml{ true }; printf("[ ] Configuring ROP gadget.\n"); auto gadget_memory = get_gadget(use_mshtml, gadget_pic_path); printf("[+] ROP gadget configured.\n"); printf("[ ] Allocating read/write memory for config, stack, and trampoline.\n"); auto& scratch_memory = allocate_workspace(); auto& config = scratch_memory.config; auto& tramp = scratch_memory.tramp; printf("[+] Allocated %u bytes for scratch memory.\n", sizeof(scratch_memory)); printf("[ ] Building stack trampoline.\n"); tramp.old_protections_ptr = &tramp.old_protections; tramp.protections = PAGE_EXECUTE_READ; tramp.current_process = GetCurrentProcess(); tramp.VirtualProtectEx = VirtualProtectEx; tramp.size = static_cast<uint32_t>(setup_size); tramp.address = setup_memory; tramp.return_address = setup_memory; tramp.setup_config = &config; printf("[+] Stack trampoline built.\n"); printf("[ ] Building configuration.\n"); config.setup_address = setup_memory; config.setup_length = static_cast<uint32_t>(setup_size); config.VirtualProtectEx = VirtualProtectEx; config.WaitForSingleObjectEx = WaitForSingleObjectEx; config.CreateWaitableTimer = CreateWaitableTimerW; config.SetWaitableTimer = SetWaitableTimer; config.MessageBox = MessageBoxA; config.tramp_addr = &tramp; config.interval = invocation_interval_ms; config.target = gadget_memory; printf("[+] Configuration built.\n"); printf("[+] Success!\n"); printf(" ================================\n"); printf(" Gargoyle PIC @ -----> 0x%p\n", setup_memory); printf(" ROP gadget @ -------> 0x%p\n", gadget_memory); printf(" Configuration @ ----> 0x%p\n", &scratch_memory.config); printf(" Top of stack @ -----> 0x%p\n", &scratch_memory.stack); printf(" Bottom of stack @ --> 0x%p\n", &scratch_memory.stack[stack_size-1]); printf(" Stack trampoline @ -> 0x%p\n", &scratch_memory.tramp); reinterpret_cast<callable>(setup_memory)(&config); } int main() { try { launch("setup.pic", "gadget.pic"); } catch (exception& e) { printf("%s\n", e.what()); } } <|endoftext|>
<commit_before>daa02090-585a-11e5-b871-6c40088e03e4<commit_msg>daa6b8c2-585a-11e5-8bdc-6c40088e03e4<commit_after>daa6b8c2-585a-11e5-8bdc-6c40088e03e4<|endoftext|>
<commit_before>7e82f978-2e4f-11e5-a578-28cfe91dbc4b<commit_msg>7e89b7b8-2e4f-11e5-ada5-28cfe91dbc4b<commit_after>7e89b7b8-2e4f-11e5-ada5-28cfe91dbc4b<|endoftext|>
<commit_before>48647b00-2e4f-11e5-9676-28cfe91dbc4b<commit_msg>486bd773-2e4f-11e5-a0b4-28cfe91dbc4b<commit_after>486bd773-2e4f-11e5-a0b4-28cfe91dbc4b<|endoftext|>
<commit_before>809e9237-2d15-11e5-af21-0401358ea401<commit_msg>809e9238-2d15-11e5-af21-0401358ea401<commit_after>809e9238-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>788ae7e4-2d53-11e5-baeb-247703a38240<commit_msg>788b6c6e-2d53-11e5-baeb-247703a38240<commit_after>788b6c6e-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>6944bcd4-2fa5-11e5-8191-00012e3d3f12<commit_msg>69466a86-2fa5-11e5-918b-00012e3d3f12<commit_after>69466a86-2fa5-11e5-918b-00012e3d3f12<|endoftext|>
<commit_before>8e9fac34-2d14-11e5-af21-0401358ea401<commit_msg>8e9fac35-2d14-11e5-af21-0401358ea401<commit_after>8e9fac35-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>fff171ca-2e4e-11e5-9a2f-28cfe91dbc4b<commit_msg>fff7fad4-2e4e-11e5-acd0-28cfe91dbc4b<commit_after>fff7fad4-2e4e-11e5-acd0-28cfe91dbc4b<|endoftext|>
<commit_before>d9f4e55c-585a-11e5-bb09-6c40088e03e4<commit_msg>d9fb98e8-585a-11e5-a1dd-6c40088e03e4<commit_after>d9fb98e8-585a-11e5-a1dd-6c40088e03e4<|endoftext|>
<commit_before>d486bc14-2e4e-11e5-b389-28cfe91dbc4b<commit_msg>d48dda5c-2e4e-11e5-a00a-28cfe91dbc4b<commit_after>d48dda5c-2e4e-11e5-a00a-28cfe91dbc4b<|endoftext|>
<commit_before>4c5459b5-ad5b-11e7-a7b4-ac87a332f658<commit_msg>Did ANOTHER thing<commit_after>4cd53763-ad5b-11e7-ba58-ac87a332f658<|endoftext|>
<commit_before>79853672-2d53-11e5-baeb-247703a38240<commit_msg>7985b62e-2d53-11e5-baeb-247703a38240<commit_after>7985b62e-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>8431fc1c-2d15-11e5-af21-0401358ea401<commit_msg>8431fc1d-2d15-11e5-af21-0401358ea401<commit_after>8431fc1d-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>7592591e-2d53-11e5-baeb-247703a38240<commit_msg>7592da6a-2d53-11e5-baeb-247703a38240<commit_after>7592da6a-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>7e7919bc-2d15-11e5-af21-0401358ea401<commit_msg>7e7919bd-2d15-11e5-af21-0401358ea401<commit_after>7e7919bd-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>86b92d1c-ad5a-11e7-aeb1-ac87a332f658<commit_msg>Added that feature we discussed on... Was it monday?<commit_after>873d4fdc-ad5a-11e7-8db2-ac87a332f658<|endoftext|>
<commit_before>d903cb63-313a-11e5-91ef-3c15c2e10482<commit_msg>d9098040-313a-11e5-aaba-3c15c2e10482<commit_after>d9098040-313a-11e5-aaba-3c15c2e10482<|endoftext|>
<commit_before>8b332546-2d14-11e5-af21-0401358ea401<commit_msg>8b332547-2d14-11e5-af21-0401358ea401<commit_after>8b332547-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>f9aa5f70-2e4e-11e5-9e28-28cfe91dbc4b<commit_msg>f9b4339c-2e4e-11e5-9134-28cfe91dbc4b<commit_after>f9b4339c-2e4e-11e5-9134-28cfe91dbc4b<|endoftext|>
<commit_before>d2710438-4b02-11e5-b413-28cfe9171a43<commit_msg>I finished programming, there is nothing left to program<commit_after>d28015fd-4b02-11e5-a789-28cfe9171a43<|endoftext|>
<commit_before>f8591ad8-585a-11e5-bd5a-6c40088e03e4<commit_msg>f85feb2c-585a-11e5-8daf-6c40088e03e4<commit_after>f85feb2c-585a-11e5-8daf-6c40088e03e4<|endoftext|>
<commit_before>ad3eed9c-327f-11e5-91fe-9cf387a8033e<commit_msg>ad468d17-327f-11e5-991e-9cf387a8033e<commit_after>ad468d17-327f-11e5-991e-9cf387a8033e<|endoftext|>
<commit_before>781c604e-2d53-11e5-baeb-247703a38240<commit_msg>781ce05a-2d53-11e5-baeb-247703a38240<commit_after>781ce05a-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>b87f865a-35ca-11e5-9f5d-6c40088e03e4<commit_msg>b88640a6-35ca-11e5-9207-6c40088e03e4<commit_after>b88640a6-35ca-11e5-9207-6c40088e03e4<|endoftext|>
<commit_before>c0a09734-35ca-11e5-a2cc-6c40088e03e4<commit_msg>c0a76390-35ca-11e5-9ac4-6c40088e03e4<commit_after>c0a76390-35ca-11e5-9ac4-6c40088e03e4<|endoftext|>
<commit_before>bb5d957a-4b02-11e5-bfc1-28cfe9171a43<commit_msg>more bug fix<commit_after>bb685f3d-4b02-11e5-8821-28cfe9171a43<|endoftext|>