text
stringlengths
54
60.6k
<commit_before>#include <jni.h> #include <stdlib.h> #include "SuperpoweredFrequencyDomain.h" #include "SuperpoweredAndroidAudioIO.h" #include "SuperpoweredSimple.h" #include "SuperpoweredRecorder.h" static SuperpoweredAndroidAudioIO *audioIO; static SuperpoweredRecorder *audioRecorder; static SuperpoweredFrequencyDomain *frequencyDomain; static float *magnitudeLeft, *magnitudeRight, *phaseLeft, *phaseRight, *fifoOutput, *inputBufferFloat; static int fifoOutputFirstSample, fifoOutputLastSample, stepSize, fifoCapacity; #define FFT_LOG_SIZE 11 // 2^11 = 2048 // This is called periodically by the media server. static bool audioProcessing(void *clientdata, short int *audioInputOutput, int numberOfSamples, int samplerate) { SuperpoweredShortIntToFloat(audioInputOutput, inputBufferFloat, numberOfSamples); // Converting the 16-bit integer samples to 32-bit floating point. frequencyDomain->addInput(inputBufferFloat, numberOfSamples); // Input goes to the frequency domain. // In the frequency domain we are working with 1024 magnitudes and phases for every channel (left, right), if the fft size is 2048. while (frequencyDomain->timeDomainToFrequencyDomain(magnitudeLeft, magnitudeRight, phaseLeft, phaseRight)) { // You can work with frequency domain data from this point. // This is just a quick example: we remove the magnitude of the first 20 bins, meaning total bass cut between 0-430 Hz. memset(magnitudeLeft, 0, 80); memset(magnitudeRight, 0, 80); // We are done working with frequency domain data. Let's go back to the time domain. // Check if we have enough room in the fifo buffer for the output. If not, move the existing audio data back to the buffer's beginning. if (fifoOutputLastSample + stepSize >= fifoCapacity) { // This will be true for every 100th iteration only, so we save precious memory bandwidth. int samplesInFifo = fifoOutputLastSample - fifoOutputFirstSample; if (samplesInFifo > 0) memmove(fifoOutput, fifoOutput + fifoOutputFirstSample * 2, samplesInFifo * sizeof(float) * 2); fifoOutputFirstSample = 0; fifoOutputLastSample = samplesInFifo; }; // Transforming back to the time domain. frequencyDomain->frequencyDomainToTimeDomain(magnitudeLeft, magnitudeRight, phaseLeft, phaseRight, fifoOutput + fifoOutputLastSample * 2); frequencyDomain->advance(); fifoOutputLastSample += stepSize; }; // If we have enough samples in the fifo output buffer, pass them to the audio output. if (fifoOutputLastSample - fifoOutputFirstSample >= numberOfSamples) { SuperpoweredFloatToShortInt(fifoOutput + fifoOutputFirstSample * 2, audioInputOutput, numberOfSamples); fifoOutputFirstSample += numberOfSamples; return true; } else return false; } // Ugly Java-native bridges - JNI, that is. extern "C" { JNIEXPORT void Java_com_superpowered_frequencydomain_MainActivity_FrequencyDomain(JNIEnv *javaEnvironment, jobject self, jlong samplerate, jlong buffersize); JNIEXPORT void Java_com_superpowered_frequencydomain_MainActivity_StopRecord(JNIEnv *javaEnvironment, jobject self); JNIEXPORT void Java_com_superpowered_frequencydomain_MainActivity_StartRecord(JNIEnv *javaEnvironment, jobject self); } JNIEXPORT void Java_com_superpowered_frequencydomain_MainActivity_FrequencyDomain(JNIEnv *javaEnvironment, jobject self, jlong samplerate, jlong buffersize) { frequencyDomain = new SuperpoweredFrequencyDomain(FFT_LOG_SIZE); // This will do the main "magic". stepSize = frequencyDomain->fftSize / 4; // The default overlap ratio is 4:1, so we will receive this amount of samples from the frequency domain in one step. // Frequency domain data goes into these buffers: magnitudeLeft = (float *)malloc(frequencyDomain->fftSize * sizeof(float)); magnitudeRight = (float *)malloc(frequencyDomain->fftSize * sizeof(float)); phaseLeft = (float *)malloc(frequencyDomain->fftSize * sizeof(float)); phaseRight = (float *)malloc(frequencyDomain->fftSize * sizeof(float)); // Time domain result goes into a FIFO (first-in, first-out) buffer fifoOutputFirstSample = fifoOutputLastSample = 0; fifoCapacity = stepSize * 100; // Let's make the fifo's size 100 times more than the step size, so we save memory bandwidth. fifoOutput = (float *)malloc(fifoCapacity * sizeof(float) * 2 + 128); inputBufferFloat = (float *)malloc(buffersize * sizeof(float) * 2 + 128); audioIO = new SuperpoweredAndroidAudioIO(samplerate, buffersize, true, true, audioProcessing, NULL, buffersize*2); // Start audio input/output. //audioRecorder = new SuperpoweredAudioRecorder(); } JNIEXPORT void Java_com_superpowered_frequencydomain_MainActivity_StopRecord(JNIEnv *javaEnvironment, jobject self){ audioIO->stop(); } JNIEXPORT void Java_com_superpowered_frequencydomain_MainActivity_StartRecord(JNIEnv *javaEnvironment, jobject self){ audioIO->start(); } <commit_msg>JNI functions changed<commit_after>#include <jni.h> #include <stdlib.h> #include "SuperpoweredFrequencyDomain.h" #include "SuperpoweredAndroidAudioIO.h" #include "SuperpoweredSimple.h" #include "SuperpoweredRecorder.h" static SuperpoweredAndroidAudioIO *audioIO; static SuperpoweredRecorder *audioRecorder; static SuperpoweredFrequencyDomain *frequencyDomain; static float *magnitudeLeft, *magnitudeRight, *phaseLeft, *phaseRight, *fifoOutput, *inputBufferFloat; static int fifoOutputFirstSample, fifoOutputLastSample, stepSize, fifoCapacity; #define FFT_LOG_SIZE 11 // 2^11 = 2048 // This is called periodically by the media server. static bool audioProcessing(void *clientdata, short int *audioInputOutput, int numberOfSamples, int samplerate) { SuperpoweredShortIntToFloat(audioInputOutput, inputBufferFloat, numberOfSamples); // Converting the 16-bit integer samples to 32-bit floating point. frequencyDomain->addInput(inputBufferFloat, numberOfSamples); // Input goes to the frequency domain. // In the frequency domain we are working with 1024 magnitudes and phases for every channel (left, right), if the fft size is 2048. while (frequencyDomain->timeDomainToFrequencyDomain(magnitudeLeft, magnitudeRight, phaseLeft, phaseRight)) { // You can work with frequency domain data from this point. // This is just a quick example: we remove the magnitude of the first 20 bins, meaning total bass cut between 0-430 Hz. memset(magnitudeLeft, 0, 80); memset(magnitudeRight, 0, 80); // We are done working with frequency domain data. Let's go back to the time domain. // Check if we have enough room in the fifo buffer for the output. If not, move the existing audio data back to the buffer's beginning. if (fifoOutputLastSample + stepSize >= fifoCapacity) { // This will be true for every 100th iteration only, so we save precious memory bandwidth. int samplesInFifo = fifoOutputLastSample - fifoOutputFirstSample; if (samplesInFifo > 0) memmove(fifoOutput, fifoOutput + fifoOutputFirstSample * 2, samplesInFifo * sizeof(float) * 2); fifoOutputFirstSample = 0; fifoOutputLastSample = samplesInFifo; }; // Transforming back to the time domain. frequencyDomain->frequencyDomainToTimeDomain(magnitudeLeft, magnitudeRight, phaseLeft, phaseRight, fifoOutput + fifoOutputLastSample * 2); frequencyDomain->advance(); fifoOutputLastSample += stepSize; }; // If we have enough samples in the fifo output buffer, pass them to the audio output. if (fifoOutputLastSample - fifoOutputFirstSample >= numberOfSamples) { SuperpoweredFloatToShortInt(fifoOutput + fifoOutputFirstSample * 2, audioInputOutput, numberOfSamples); fifoOutputFirstSample += numberOfSamples; return true; } else return false; } // Ugly Java-native bridges - JNI, that is. extern "C" { JNIEXPORT void Java_com_scorelab_stutterAid_MainActivity_FrequencyDomain(JNIEnv *javaEnvironment, jobject self, jlong samplerate, jlong buffersize); JNIEXPORT void Java_com_scorelab_stutterAid_MainActivity_StopRecord(JNIEnv *javaEnvironment, jobject self); JNIEXPORT void Java_com_scorelab_stutterAid_MainActivity_StartRecord(JNIEnv *javaEnvironment, jobject self); } JNIEXPORT void Java_com_scorelab_stutterAid__MainActivity_FrequencyDomain(JNIEnv *javaEnvironment, jobject self, jlong samplerate, jlong buffersize) { frequencyDomain = new SuperpoweredFrequencyDomain(FFT_LOG_SIZE); // This will do the main "magic". stepSize = frequencyDomain->fftSize / 4; // The default overlap ratio is 4:1, so we will receive this amount of samples from the frequency domain in one step. // Frequency domain data goes into these buffers: magnitudeLeft = (float *)malloc(frequencyDomain->fftSize * sizeof(float)); magnitudeRight = (float *)malloc(frequencyDomain->fftSize * sizeof(float)); phaseLeft = (float *)malloc(frequencyDomain->fftSize * sizeof(float)); phaseRight = (float *)malloc(frequencyDomain->fftSize * sizeof(float)); // Time domain result goes into a FIFO (first-in, first-out) buffer fifoOutputFirstSample = fifoOutputLastSample = 0; fifoCapacity = stepSize * 100; // Let's make the fifo's size 100 times more than the step size, so we save memory bandwidth. fifoOutput = (float *)malloc(fifoCapacity * sizeof(float) * 2 + 128); inputBufferFloat = (float *)malloc(buffersize * sizeof(float) * 2 + 128); audioIO = new SuperpoweredAndroidAudioIO(samplerate, buffersize, true, true, audioProcessing, NULL, buffersize*2); // Start audio input/output. //audioRecorder = new SuperpoweredAudioRecorder(); } JNIEXPORT void Java_com_scorelab_stutterAid_MainActivity_StopRecord(JNIEnv *javaEnvironment, jobject self){ audioIO->stop(); } JNIEXPORT void Java_com_scorelab_stutterAid_MainActivity_StartRecord(JNIEnv *javaEnvironment, jobject self){ audioIO->start(); } <|endoftext|>
<commit_before>1a9b90c8-2f67-11e5-b231-6c40088e03e4<commit_msg>1aa22f98-2f67-11e5-b8da-6c40088e03e4<commit_after>1aa22f98-2f67-11e5-b8da-6c40088e03e4<|endoftext|>
<commit_before>/* Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /* Utility program that encapsulates process creation, monitoring and bulletproof process cleanup Usage: safe_process [options to safe_process] -- progname arg1 ... argn To safeguard mysqld you would invoke safe_process with a few options for safe_process itself followed by a double dash to indicate start of the command line for the program you really want to start $> safe_process --output=output.log -- mysqld --datadir=var/data1 ... This would redirect output to output.log and then start mysqld, once it has done that it will continue to monitor the child as well as the parent. The safe_process then checks the follwing things: 1. Child exits, propagate the childs return code to the parent by exiting with the same return code as the child. 2. Parent dies, immediately kill the child and exit, thus the parent does not need to properly cleanup any child, it is handled automatically. 3. Signal's recieced by the process will trigger same action as 2) 4. The named event "safe_process[pid]" can be signaled and will trigger same action as 2) WARNING! Be careful when using ProcessExplorer, since it will open a handle to each process(and maybe also the Job), the process spawned by safe_process will not be closed off when safe_process is killed. */ #include <windows.h> #include <stdio.h> #include <tlhelp32.h> #include <signal.h> #include <stdlib.h> static int verbose= 0; static char safe_process_name[32]= {0}; static void message(const char* fmt, ...) { if (!verbose) return; va_list args; fprintf(stderr, "%s: ", safe_process_name); va_start(args, fmt); vfprintf(stderr, fmt, args); fprintf(stderr, "\n"); va_end(args); fflush(stderr); } static void die(const char* fmt, ...) { DWORD last_err= GetLastError(); va_list args; fprintf(stderr, "%s: FATAL ERROR, ", safe_process_name); va_start(args, fmt); vfprintf(stderr, fmt, args); fprintf(stderr, "\n"); va_end(args); if (last_err) { char *message_text; if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER |FORMAT_MESSAGE_IGNORE_INSERTS, NULL, last_err , 0, (LPSTR)&message_text, 0, NULL)) { fprintf(stderr,"error: %d, %s\n",last_err, message_text); LocalFree(message_text); } else { /* FormatMessage failed, print error code only */ fprintf(stderr,"error:%d\n", last_err); } } fflush(stderr); exit(1); } DWORD get_parent_pid(DWORD pid) { HANDLE snapshot; DWORD parent_pid= -1; PROCESSENTRY32 pe32; pe32.dwSize= sizeof(PROCESSENTRY32); snapshot= CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (snapshot == INVALID_HANDLE_VALUE) die("CreateToolhelp32Snapshot failed"); if (!Process32First(snapshot, &pe32)) { CloseHandle(snapshot); die("Process32First failed"); } do { if (pe32.th32ProcessID == pid) parent_pid= pe32.th32ParentProcessID; } while(Process32Next( snapshot, &pe32)); CloseHandle(snapshot); if (parent_pid == -1) die("Could not find parent pid"); return parent_pid; } enum { PARENT, CHILD, EVENT, NUM_HANDLES }; HANDLE shutdown_event; void handle_signal (int signal) { message("Got signal: %d", signal); if(SetEvent(shutdown_event) == 0) { /* exit safe_process and (hopefully) kill off the child */ die("Failed to SetEvent"); } } int main(int argc, const char** argv ) { char child_args[4096]= {0}; DWORD pid= GetCurrentProcessId(); DWORD parent_pid= get_parent_pid(pid); HANDLE job_handle; HANDLE wait_handles[NUM_HANDLES]= {0}; PROCESS_INFORMATION process_info= {0}; BOOL nocore= FALSE; sprintf(safe_process_name, "safe_process[%d]", pid); /* Create an event for the signal handler */ if ((shutdown_event= CreateEvent(NULL, TRUE, FALSE, safe_process_name)) == NULL) die("Failed to create shutdown_event"); wait_handles[EVENT]= shutdown_event; signal(SIGINT, handle_signal); signal(SIGBREAK, handle_signal); signal(SIGTERM, handle_signal); message("Started"); /* Parse arguments */ for (int i= 1; i < argc; i++) { const char* arg= argv[i]; char* to= child_args; if (strcmp(arg, "--") == 0 && strlen(arg) == 2) { /* Got the "--" delimiter */ if (i >= argc) die("No real args -> nothing to do"); /* Copy the remaining args to child_arg */ for (int j= i+1; j < argc; j++) { arg= argv[j]; if (strchr (arg, ' ') && arg[0] != '\"' && arg[strlen(arg)] != '\"') { /* Quote arg that contains spaces and are not quoted already */ to+= _snprintf(to, child_args + sizeof(child_args) - to, "\"%s\" ", arg); } else { to+= _snprintf(to, child_args + sizeof(child_args) - to, "%s ", arg); } } break; } else { if (strcmp(arg, "--verbose") == 0) verbose++; else if (strncmp(arg, "--parent-pid", 10) == 0) { /* Override parent_pid with a value provided by user */ const char* start; if ((start= strstr(arg, "=")) == NULL) die("Could not find start of option value in '%s'", arg); start++; /* Step past = */ if ((parent_pid= atoi(start)) == 0) die("Invalid value '%s' passed to --parent-id", start); } else if (strcmp(arg, "--nocore") == 0) { nocore= TRUE; } else if ( strncmp (arg, "--env ", 6) == 0 ) { putenv(strdup(arg+6)); } else die("Unknown option: %s", arg); } } if (*child_args == '\0') die("nothing to do"); /* Open a handle to the parent process */ message("parent_pid: %d", parent_pid); if (parent_pid == pid) die("parent_pid is equal to own pid!"); if ((wait_handles[PARENT]= OpenProcess(SYNCHRONIZE, FALSE, parent_pid)) == NULL) die("Failed to open parent process with pid: %d", parent_pid); /* Create the child process in a job */ JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = { 0 }; STARTUPINFO si = { 0 }; si.cb = sizeof(si); /* Create the job object to make it possible to kill the process and all of it's children in one go */ if ((job_handle= CreateJobObject(NULL, NULL)) == NULL) die("CreateJobObject failed"); /* Make all processes associated with the job terminate when the last handle to the job is closed. */ #ifndef JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE #define JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE 0x00002000 #endif jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; if (SetInformationJobObject(job_handle, JobObjectExtendedLimitInformation, &jeli, sizeof(jeli)) == 0) message("SetInformationJobObject failed, continue anyway..."); /* Avoid popup box */ if (nocore) SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); #if 0 /* Setup stdin, stdout and stderr redirect */ si.dwFlags= STARTF_USESTDHANDLES; si.hStdInput= GetStdHandle(STD_INPUT_HANDLE); si.hStdOutput= GetStdHandle(STD_OUTPUT_HANDLE); si.hStdError= GetStdHandle(STD_ERROR_HANDLE); #endif /* Create the process suspended to make sure it's assigned to the Job before it creates any process of it's own Allow the new process to break away from any job that this process is part of so that it can be assigned to the new JobObject we just created. This is safe since the new JobObject is created with the JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE flag, making sure it will be terminated when the last handle to it is closed(which is owned by this process). If breakaway from job fails on some reason, fallback is to create a new process group. Process groups also allow to kill process and its descedants, subject to some restrictions (processes have to run within the same console,and must not ignore CTRL_BREAK) */ DWORD create_flags[]= {CREATE_BREAKAWAY_FROM_JOB, CREATE_NEW_PROCESS_GROUP, 0}; BOOL process_created= FALSE; BOOL jobobject_assigned= FALSE; for (int i=0; i < sizeof(create_flags)/sizeof(create_flags[0]); i++) { process_created= CreateProcess(NULL, (LPSTR)child_args, NULL, NULL, TRUE, /* inherit handles */ CREATE_SUSPENDED | create_flags[i], NULL, NULL, &si, &process_info); if (process_created) { jobobject_assigned= AssignProcessToJobObject(job_handle, process_info.hProcess); break; } } if (!process_created) { die("CreateProcess failed"); } ResumeThread(process_info.hThread); CloseHandle(process_info.hThread); wait_handles[CHILD]= process_info.hProcess; message("Started child %d", process_info.dwProcessId); /* Monitor loop */ DWORD child_exit_code= 1; DWORD wait_res= WaitForMultipleObjects(NUM_HANDLES, wait_handles, FALSE, INFINITE); switch (wait_res) { case WAIT_OBJECT_0 + PARENT: message("Parent exit"); break; case WAIT_OBJECT_0 + CHILD: if (GetExitCodeProcess(wait_handles[CHILD], &child_exit_code) == 0) message("Child exit: could not get exit_code"); else message("Child exit: exit_code: %d", child_exit_code); break; case WAIT_OBJECT_0 + EVENT: message("Wake up from shutdown_event"); break; default: message("Unexpected result %d from WaitForMultipleObjects", wait_res); break; } message("Exiting, child: %d", process_info.dwProcessId); if (TerminateJobObject(job_handle, 201) == 0) message("TerminateJobObject failed"); CloseHandle(job_handle); message("Job terminated and closed"); if (!jobobject_assigned) { GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, process_info.dwProcessId); TerminateProcess(process_info.hProcess, 202); } if (wait_res != WAIT_OBJECT_0 + CHILD) { /* The child has not yet returned, wait for it */ message("waiting for child to exit"); if ((wait_res= WaitForSingleObject(wait_handles[CHILD], INFINITE)) != WAIT_OBJECT_0) { message("child wait failed: %d", wait_res); } else { message("child wait succeeded"); } /* Child's exit code should now be 201, no need to get it */ } message("Closing handles"); for (int i= 0; i < NUM_HANDLES; i++) CloseHandle(wait_handles[i]); message("Exiting, exit_code: %d", child_exit_code); exit(child_exit_code); } <commit_msg>Fix process handle leak in buildbot. GenerateConsoleCtrlEvent sent to non-existing process will add a process handle to this non-existing process to console host process conhost.exe<commit_after>/* Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /* Utility program that encapsulates process creation, monitoring and bulletproof process cleanup Usage: safe_process [options to safe_process] -- progname arg1 ... argn To safeguard mysqld you would invoke safe_process with a few options for safe_process itself followed by a double dash to indicate start of the command line for the program you really want to start $> safe_process --output=output.log -- mysqld --datadir=var/data1 ... This would redirect output to output.log and then start mysqld, once it has done that it will continue to monitor the child as well as the parent. The safe_process then checks the follwing things: 1. Child exits, propagate the childs return code to the parent by exiting with the same return code as the child. 2. Parent dies, immediately kill the child and exit, thus the parent does not need to properly cleanup any child, it is handled automatically. 3. Signal's recieced by the process will trigger same action as 2) 4. The named event "safe_process[pid]" can be signaled and will trigger same action as 2) WARNING! Be careful when using ProcessExplorer, since it will open a handle to each process(and maybe also the Job), the process spawned by safe_process will not be closed off when safe_process is killed. */ #include <windows.h> #include <stdio.h> #include <tlhelp32.h> #include <signal.h> #include <stdlib.h> static int verbose= 0; static char safe_process_name[32]= {0}; static void message(const char* fmt, ...) { if (!verbose) return; va_list args; fprintf(stderr, "%s: ", safe_process_name); va_start(args, fmt); vfprintf(stderr, fmt, args); fprintf(stderr, "\n"); va_end(args); fflush(stderr); } static void die(const char* fmt, ...) { DWORD last_err= GetLastError(); va_list args; fprintf(stderr, "%s: FATAL ERROR, ", safe_process_name); va_start(args, fmt); vfprintf(stderr, fmt, args); fprintf(stderr, "\n"); va_end(args); if (last_err) { char *message_text; if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER |FORMAT_MESSAGE_IGNORE_INSERTS, NULL, last_err , 0, (LPSTR)&message_text, 0, NULL)) { fprintf(stderr,"error: %d, %s\n",last_err, message_text); LocalFree(message_text); } else { /* FormatMessage failed, print error code only */ fprintf(stderr,"error:%d\n", last_err); } } fflush(stderr); exit(1); } DWORD get_parent_pid(DWORD pid) { HANDLE snapshot; DWORD parent_pid= -1; PROCESSENTRY32 pe32; pe32.dwSize= sizeof(PROCESSENTRY32); snapshot= CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (snapshot == INVALID_HANDLE_VALUE) die("CreateToolhelp32Snapshot failed"); if (!Process32First(snapshot, &pe32)) { CloseHandle(snapshot); die("Process32First failed"); } do { if (pe32.th32ProcessID == pid) parent_pid= pe32.th32ParentProcessID; } while(Process32Next( snapshot, &pe32)); CloseHandle(snapshot); if (parent_pid == -1) die("Could not find parent pid"); return parent_pid; } enum { PARENT, CHILD, EVENT, NUM_HANDLES }; HANDLE shutdown_event; void handle_signal (int signal) { message("Got signal: %d", signal); if(SetEvent(shutdown_event) == 0) { /* exit safe_process and (hopefully) kill off the child */ die("Failed to SetEvent"); } } int main(int argc, const char** argv ) { char child_args[4096]= {0}; DWORD pid= GetCurrentProcessId(); DWORD parent_pid= get_parent_pid(pid); HANDLE job_handle; HANDLE wait_handles[NUM_HANDLES]= {0}; PROCESS_INFORMATION process_info= {0}; BOOL nocore= FALSE; sprintf(safe_process_name, "safe_process[%d]", pid); /* Create an event for the signal handler */ if ((shutdown_event= CreateEvent(NULL, TRUE, FALSE, safe_process_name)) == NULL) die("Failed to create shutdown_event"); wait_handles[EVENT]= shutdown_event; signal(SIGINT, handle_signal); signal(SIGBREAK, handle_signal); signal(SIGTERM, handle_signal); message("Started"); /* Parse arguments */ for (int i= 1; i < argc; i++) { const char* arg= argv[i]; char* to= child_args; if (strcmp(arg, "--") == 0 && strlen(arg) == 2) { /* Got the "--" delimiter */ if (i >= argc) die("No real args -> nothing to do"); /* Copy the remaining args to child_arg */ for (int j= i+1; j < argc; j++) { arg= argv[j]; if (strchr (arg, ' ') && arg[0] != '\"' && arg[strlen(arg)] != '\"') { /* Quote arg that contains spaces and are not quoted already */ to+= _snprintf(to, child_args + sizeof(child_args) - to, "\"%s\" ", arg); } else { to+= _snprintf(to, child_args + sizeof(child_args) - to, "%s ", arg); } } break; } else { if (strcmp(arg, "--verbose") == 0) verbose++; else if (strncmp(arg, "--parent-pid", 10) == 0) { /* Override parent_pid with a value provided by user */ const char* start; if ((start= strstr(arg, "=")) == NULL) die("Could not find start of option value in '%s'", arg); start++; /* Step past = */ if ((parent_pid= atoi(start)) == 0) die("Invalid value '%s' passed to --parent-id", start); } else if (strcmp(arg, "--nocore") == 0) { nocore= TRUE; } else if ( strncmp (arg, "--env ", 6) == 0 ) { putenv(strdup(arg+6)); } else die("Unknown option: %s", arg); } } if (*child_args == '\0') die("nothing to do"); /* Open a handle to the parent process */ message("parent_pid: %d", parent_pid); if (parent_pid == pid) die("parent_pid is equal to own pid!"); if ((wait_handles[PARENT]= OpenProcess(SYNCHRONIZE, FALSE, parent_pid)) == NULL) die("Failed to open parent process with pid: %d", parent_pid); /* Create the child process in a job */ JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = { 0 }; STARTUPINFO si = { 0 }; si.cb = sizeof(si); /* Create the job object to make it possible to kill the process and all of it's children in one go */ if ((job_handle= CreateJobObject(NULL, NULL)) == NULL) die("CreateJobObject failed"); /* Make all processes associated with the job terminate when the last handle to the job is closed. */ #ifndef JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE #define JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE 0x00002000 #endif jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; if (SetInformationJobObject(job_handle, JobObjectExtendedLimitInformation, &jeli, sizeof(jeli)) == 0) message("SetInformationJobObject failed, continue anyway..."); /* Avoid popup box */ if (nocore) SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); #if 0 /* Setup stdin, stdout and stderr redirect */ si.dwFlags= STARTF_USESTDHANDLES; si.hStdInput= GetStdHandle(STD_INPUT_HANDLE); si.hStdOutput= GetStdHandle(STD_OUTPUT_HANDLE); si.hStdError= GetStdHandle(STD_ERROR_HANDLE); #endif /* Create the process suspended to make sure it's assigned to the Job before it creates any process of it's own Allow the new process to break away from any job that this process is part of so that it can be assigned to the new JobObject we just created. This is safe since the new JobObject is created with the JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE flag, making sure it will be terminated when the last handle to it is closed(which is owned by this process). If breakaway from job fails on some reason, fallback is to create a new process group. Process groups also allow to kill process and its descedants, subject to some restrictions (processes have to run within the same console,and must not ignore CTRL_BREAK) */ DWORD create_flags[]= {CREATE_BREAKAWAY_FROM_JOB, CREATE_NEW_PROCESS_GROUP, 0}; BOOL process_created= FALSE; BOOL jobobject_assigned= FALSE; for (int i=0; i < sizeof(create_flags)/sizeof(create_flags[0]); i++) { process_created= CreateProcess(NULL, (LPSTR)child_args, NULL, NULL, TRUE, /* inherit handles */ CREATE_SUSPENDED | create_flags[i], NULL, NULL, &si, &process_info); if (process_created) { jobobject_assigned= AssignProcessToJobObject(job_handle, process_info.hProcess); break; } } if (!process_created) { die("CreateProcess failed"); } ResumeThread(process_info.hThread); CloseHandle(process_info.hThread); wait_handles[CHILD]= process_info.hProcess; message("Started child %d", process_info.dwProcessId); /* Monitor loop */ DWORD child_exit_code= 1; DWORD wait_res= WaitForMultipleObjects(NUM_HANDLES, wait_handles, FALSE, INFINITE); switch (wait_res) { case WAIT_OBJECT_0 + PARENT: message("Parent exit"); break; case WAIT_OBJECT_0 + CHILD: if (GetExitCodeProcess(wait_handles[CHILD], &child_exit_code) == 0) message("Child exit: could not get exit_code"); else message("Child exit: exit_code: %d", child_exit_code); break; case WAIT_OBJECT_0 + EVENT: message("Wake up from shutdown_event"); break; default: message("Unexpected result %d from WaitForMultipleObjects", wait_res); break; } message("Exiting, child: %d", process_info.dwProcessId); if (TerminateJobObject(job_handle, 201) == 0) message("TerminateJobObject failed"); CloseHandle(job_handle); message("Job terminated and closed"); if (wait_res != WAIT_OBJECT_0 + CHILD) { if (!jobobject_assigned) { TerminateProcess(process_info.hProcess, 202); } /* The child has not yet returned, wait for it */ message("waiting for child to exit"); if ((wait_res= WaitForSingleObject(wait_handles[CHILD], INFINITE)) != WAIT_OBJECT_0) { message("child wait failed: %d", wait_res); } else { message("child wait succeeded"); } /* Child's exit code should now be 201, no need to get it */ } message("Closing handles"); for (int i= 0; i < NUM_HANDLES; i++) CloseHandle(wait_handles[i]); message("Exiting, exit_code: %d", child_exit_code); exit(child_exit_code); } <|endoftext|>
<commit_before>#ifndef H_EXTENSIONS_CUTEHMI_SHAREDDATABASE_0_INCLUDE_CUTEHMI_SHAREDDATABASE_DATABASEWORKER_HPP #define H_EXTENSIONS_CUTEHMI_SHAREDDATABASE_0_INCLUDE_CUTEHMI_SHAREDDATABASE_DATABASEWORKER_HPP #include "internal/common.hpp" #include <cutehmi/Worker.hpp> #include <QSqlDatabase> namespace cutehmi { namespace shareddatabase { /** * %Database worker. Convenient worker class that runs tasks in the same thread as where database connection lives. */ class CUTEHMI_SHAREDDATABASE_API DatabaseWorker: public QObject { Q_OBJECT public: /** * Constructor. This constructor employs the worker in the same thread as where database connection denoted by * @a connectionName lives. * @param connectionName database connection name. * @param task task function. See job(). */ explicit DatabaseWorker(const QString & connectionName, std::function<void(QSqlDatabase & db)> task = nullptr); /** * Set task. * @param task task function. See job(). */ void setTask(std::function<void(QSqlDatabase & db)> task); /** * %Worker's job. This function can be reimplemented. Default implementation calls @a task function if it has been set (it * can be passed to the \ref DatabseWorker(const QString & connectionName, std::function<void(QSqlDatabase & db)> task) * "constructor" or set via setTask() function). Default implementation does nothing if @a task has not been set (i.e. * @a task = @p nullptr). * @paragraph db databse connection to be used by the worker. */ virtual void job(QSqlDatabase & db); /** * Wait for the worker. Causes calling thread to wait until worker finishes its job. Function does not block until work() * has been called. It also won't block if worker has already finished its job. * * @threadsafe */ void wait() const; /** * Check if worker is ready. * @return @p true when worker has completed the job, @p false otherwise. * * @threadsafe */ bool isReady() const; /** * Check if worker is working. * @return @p true if worker is processing its job, @p false otherwise. * * @threadsafe */ bool isWorking() const; /** * Do the work. This function tells worker to process the job() in database thread. */ void work(); signals: /** * Work started. This signal is emitted just before worker starts processing the \ref job(QSqlDatabase & db) "job". */ void started(); /** * Results are ready. This signal is emitted when the job() has been completed and the results are ready. */ void ready(); /** * Worker performed strike action. This signal is emitted when worker denied to do the job. */ void striked(const QString & reason); protected: /** * Get database thread. * @return database thread. */ QThread * dbThread() const; /** * Get database connection. * @return database connection. * * @warning database connection lives inside database thread. This means that this function can not be called from a thread * other than database thread, i.e. it should not be used outside the job() scope. */ QSqlDatabase * db(); /** * Get database connection. * @return database connection. * * @warning database connection lives inside database thread. This means that this function can not be called from a thread * other than database thread, i.e. it should not be used outside the job() scope. */ const QSqlDatabase * db() const; private slots: void updateDbThread(const QString & connectionName); private: void instantiateWorker(); struct Members { const QString connectionName; std::function<void(QSqlDatabase & db)> task; std::unique_ptr<Worker> worker; std::unique_ptr<QSqlDatabase> db; }; MPtr<Members> m; }; } } #endif //(c)C: Copyright © 2020, Michał Policht <michal@policht.pl>. All rights reserved. //(c)C: This file is a part of CuteHMI. //(c)C: CuteHMI is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. //(c)C: CuteHMI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. //(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI. If not, see <https://www.gnu.org/licenses/>. <commit_msg>Fix Doxygen parameter command.<commit_after>#ifndef H_EXTENSIONS_CUTEHMI_SHAREDDATABASE_0_INCLUDE_CUTEHMI_SHAREDDATABASE_DATABASEWORKER_HPP #define H_EXTENSIONS_CUTEHMI_SHAREDDATABASE_0_INCLUDE_CUTEHMI_SHAREDDATABASE_DATABASEWORKER_HPP #include "internal/common.hpp" #include <cutehmi/Worker.hpp> #include <QSqlDatabase> namespace cutehmi { namespace shareddatabase { /** * %Database worker. Convenient worker class that runs tasks in the same thread as where database connection lives. */ class CUTEHMI_SHAREDDATABASE_API DatabaseWorker: public QObject { Q_OBJECT public: /** * Constructor. This constructor employs the worker in the same thread as where database connection denoted by * @a connectionName lives. * @param connectionName database connection name. * @param task task function. See job(). */ explicit DatabaseWorker(const QString & connectionName, std::function<void(QSqlDatabase & db)> task = nullptr); /** * Set task. * @param task task function. See job(). */ void setTask(std::function<void(QSqlDatabase & db)> task); /** * %Worker's job. This function can be reimplemented. Default implementation calls @a task function if it has been set (it * can be passed to the \ref DatabseWorker(const QString & connectionName, std::function<void(QSqlDatabase & db)> task) * "constructor" or set via setTask() function). Default implementation does nothing if @a task has not been set (i.e. * @a task = @p nullptr). * @param db databse connection to be used by the worker. */ virtual void job(QSqlDatabase & db); /** * Wait for the worker. Causes calling thread to wait until worker finishes its job. Function does not block until work() * has been called. It also won't block if worker has already finished its job. * * @threadsafe */ void wait() const; /** * Check if worker is ready. * @return @p true when worker has completed the job, @p false otherwise. * * @threadsafe */ bool isReady() const; /** * Check if worker is working. * @return @p true if worker is processing its job, @p false otherwise. * * @threadsafe */ bool isWorking() const; /** * Do the work. This function tells worker to process the job() in database thread. */ void work(); signals: /** * Work started. This signal is emitted just before worker starts processing the \ref job(QSqlDatabase & db) "job". */ void started(); /** * Results are ready. This signal is emitted when the job() has been completed and the results are ready. */ void ready(); /** * Worker performed strike action. This signal is emitted when worker denied to do the job. */ void striked(const QString & reason); protected: /** * Get database thread. * @return database thread. */ QThread * dbThread() const; /** * Get database connection. * @return database connection. * * @warning database connection lives inside database thread. This means that this function can not be called from a thread * other than database thread, i.e. it should not be used outside the job() scope. */ QSqlDatabase * db(); /** * Get database connection. * @return database connection. * * @warning database connection lives inside database thread. This means that this function can not be called from a thread * other than database thread, i.e. it should not be used outside the job() scope. */ const QSqlDatabase * db() const; private slots: void updateDbThread(const QString & connectionName); private: void instantiateWorker(); struct Members { const QString connectionName; std::function<void(QSqlDatabase & db)> task; std::unique_ptr<Worker> worker; std::unique_ptr<QSqlDatabase> db; }; MPtr<Members> m; }; } } #endif //(c)C: Copyright © 2020, Michał Policht <michal@policht.pl>. All rights reserved. //(c)C: This file is a part of CuteHMI. //(c)C: CuteHMI is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. //(c)C: CuteHMI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. //(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI. If not, see <https://www.gnu.org/licenses/>. <|endoftext|>
<commit_before>9612c735-327f-11e5-a33d-9cf387a8033e<commit_msg>96191399-327f-11e5-b785-9cf387a8033e<commit_after>96191399-327f-11e5-b785-9cf387a8033e<|endoftext|>
<commit_before>// // NumberRepr.cpp // Project // // Created by Lennart Oymanns on 03.05.17. // // #include "NumberRepr.hpp" using namespace Equation; NumberRepr::NumberRepr() { value_double = 0.0; isValid = false; rational = Rational_t(0); } NumberRepr::NumberRepr(const std::string &s) { auto dot_pos = s.find_first_of("eE."); if (dot_pos != std::string::npos) { value_double = strtod(s.c_str(), NULL); isFraction = false; } else { rational = Integer_t(s); isFraction = true; } isValid = true; } void NumberRepr::SetFromInt(long num, long denom) { isFraction = true; rational = Rational_t(num, denom); value_double = 0.0; if (denom == 0) { isValid = false; } else { isValid = true; } } NumberRepr &NumberRepr::operator*=(const NumberRepr &rhs) { if (!rhs.isValid) { isValid = false; } if (rhs.isFraction && isFraction) { rational *= rhs.rational; return *this; } SetFromDouble(Double() * rhs.Double()); return *this; } NumberRepr &NumberRepr::operator/=(const NumberRepr &rhs) { if (!rhs.isValid) { isValid = false; } if (isFraction && rhs.isFraction) { if (rhs.rational == Rational_t(0)) { isValid = false; return *this; } rational /= rhs.rational; return *this; } SetFromDouble(Double() / rhs.Double()); return *this; } NumberRepr &NumberRepr::operator+=(const NumberRepr &rhs) { if (!rhs.isValid) { isValid = false; } if (rhs.isFraction && isFraction) { rational += rhs.rational; return *this; } SetFromDouble(Double() + rhs.Double()); return *this; } NumberRepr &NumberRepr::operator-=(const NumberRepr &rhs) { if (!rhs.isValid) { isValid = false; } if (rhs.isFraction && isFraction) { rational -= rhs.rational; return *this; } SetFromDouble(Double() - rhs.Double()); return *this; } std::ostream &operator<<(std::ostream &os, const NumberRepr &obj) { os << obj.String(); return os; } NumberRepr NumberRepr::Pow(const NumberRepr &base, const NumberRepr &exp) { if (!base.isValid || !exp.isValid) { auto inv = NumberRepr(0l); inv.isValid = false; return inv; } if (!base.IsFraction() || !exp.IsFraction()) { double b = base.Double(); double e = exp.Double(); return NumberRepr(pow(b, e)); } if (base.IsFraction() && exp.Denominator() == Integer_t(1)) { auto abs_enum = boost::multiprecision::abs(exp.Numerator()); if (abs_enum > Integer_t( 100)) { // if the exponent is too large, return a invalid number auto inv = NumberRepr(0l); inv.isValid = false; return inv; } unsigned e = abs_enum.convert_to<unsigned>(); auto rat = base.rational; Rational_t result_num = boost::multiprecision::pow(boost::multiprecision::numerator(rat), e); Rational_t result_denom = boost::multiprecision::pow(boost::multiprecision::denominator(rat), e); if (exp.Numerator() >= Integer_t(0)) { Rational_t res = result_num / result_denom; return NumberRepr(res); } Rational_t res = result_denom / result_num; return NumberRepr(res); } auto inv = NumberRepr(pow(base.Double(), exp.Double())); inv.isValid = false; return inv; } double NumberRepr::Double() const { if (isFraction) { return rational.convert_to<double>(); } return value_double; } std::string NumberRepr::String() const { if (!isValid) { return "nan"; } std::stringstream ss; if (isFraction) { ss << Numerator().str(); if (Denominator() != Integer_t(1)) { ss << " / " << Denominator().str(); } return ss.str(); } ss << std::setprecision(17) << Double(); return ss.str(); } bool NumberRepr::operator==(const NumberRepr &n) const { if (!isValid || !n.isValid) { return false; } if (isFraction && n.isFraction) { return rational == n.rational; } if (!isFraction && !n.isFraction) { return Double() == n.Double(); } return false; } void NumberRepr::ToLatex(std::ostream &s) const { if (IsFraction()) { if (Denominator() != Integer_t(1)) { s << "\\frac{" << Numerator() << "}{" << Denominator() << "}"; } else { s << Numerator(); } return; } s << Double(); } bool NumberRepr::operator<(const NumberRepr &n) { if (!isValid || !n.isValid) { return false; } if (isFraction && n.isFraction) { return rational < n.rational; } return Double() < n.Double(); } bool NumberRepr::operator>(const NumberRepr &n) { if (*this < n) { return false; } if (*this == n) { return false; } return true; } <commit_msg>fix issue with old version of boost?<commit_after>// // NumberRepr.cpp // Project // // Created by Lennart Oymanns on 03.05.17. // // #include "NumberRepr.hpp" using namespace Equation; NumberRepr::NumberRepr() { value_double = 0.0; isValid = false; rational = Rational_t(0); } NumberRepr::NumberRepr(const std::string &s) { auto dot_pos = s.find_first_of("eE."); if (dot_pos != std::string::npos) { value_double = strtod(s.c_str(), NULL); isFraction = false; } else { rational = Integer_t(s); isFraction = true; } isValid = true; } void NumberRepr::SetFromInt(long num, long denom) { isFraction = true; rational = Rational_t(num, denom); value_double = 0.0; if (denom == 0) { isValid = false; } else { isValid = true; } } NumberRepr &NumberRepr::operator*=(const NumberRepr &rhs) { if (!rhs.isValid) { isValid = false; } if (rhs.isFraction && isFraction) { rational *= rhs.rational; return *this; } SetFromDouble(Double() * rhs.Double()); return *this; } NumberRepr &NumberRepr::operator/=(const NumberRepr &rhs) { if (!rhs.isValid) { isValid = false; } if (isFraction && rhs.isFraction) { if (rhs.rational == Rational_t(0)) { isValid = false; return *this; } rational /= rhs.rational; return *this; } SetFromDouble(Double() / rhs.Double()); return *this; } NumberRepr &NumberRepr::operator+=(const NumberRepr &rhs) { if (!rhs.isValid) { isValid = false; } if (rhs.isFraction && isFraction) { rational += rhs.rational; return *this; } SetFromDouble(Double() + rhs.Double()); return *this; } NumberRepr &NumberRepr::operator-=(const NumberRepr &rhs) { if (!rhs.isValid) { isValid = false; } if (rhs.isFraction && isFraction) { rational -= rhs.rational; return *this; } SetFromDouble(Double() - rhs.Double()); return *this; } std::ostream &operator<<(std::ostream &os, const NumberRepr &obj) { os << obj.String(); return os; } NumberRepr NumberRepr::Pow(const NumberRepr &base, const NumberRepr &exp) { if (!base.isValid || !exp.isValid) { auto inv = NumberRepr(0l); inv.isValid = false; return inv; } if (!base.IsFraction() || !exp.IsFraction()) { double b = base.Double(); double e = exp.Double(); return NumberRepr(pow(b, e)); } if (base.IsFraction() && exp.Denominator() == Integer_t(1)) { Integer_t abs_enum = boost::multiprecision::abs(exp.Numerator()); if (abs_enum > Integer_t(100)) { // if the exponent is too large, return a invalid number auto inv = NumberRepr(0l); inv.isValid = false; return inv; } unsigned e = abs_enum.convert_to<unsigned>(); auto rat = base.rational; Rational_t result_num = boost::multiprecision::pow(boost::multiprecision::numerator(rat), e); Rational_t result_denom = boost::multiprecision::pow(boost::multiprecision::denominator(rat), e); if (exp.Numerator() >= Integer_t(0)) { Rational_t res = result_num / result_denom; return NumberRepr(res); } Rational_t res = result_denom / result_num; return NumberRepr(res); } auto inv = NumberRepr(pow(base.Double(), exp.Double())); inv.isValid = false; return inv; } double NumberRepr::Double() const { if (isFraction) { return rational.convert_to<double>(); } return value_double; } std::string NumberRepr::String() const { if (!isValid) { return "nan"; } std::stringstream ss; if (isFraction) { ss << Numerator().str(); if (Denominator() != Integer_t(1)) { ss << " / " << Denominator().str(); } return ss.str(); } ss << std::setprecision(17) << Double(); return ss.str(); } bool NumberRepr::operator==(const NumberRepr &n) const { if (!isValid || !n.isValid) { return false; } if (isFraction && n.isFraction) { return rational == n.rational; } if (!isFraction && !n.isFraction) { return Double() == n.Double(); } return false; } void NumberRepr::ToLatex(std::ostream &s) const { if (IsFraction()) { if (Denominator() != Integer_t(1)) { s << "\\frac{" << Numerator() << "}{" << Denominator() << "}"; } else { s << Numerator(); } return; } s << Double(); } bool NumberRepr::operator<(const NumberRepr &n) { if (!isValid || !n.isValid) { return false; } if (isFraction && n.isFraction) { return rational < n.rational; } return Double() < n.Double(); } bool NumberRepr::operator>(const NumberRepr &n) { if (*this < n) { return false; } if (*this == n) { return false; } return true; } <|endoftext|>
<commit_before>#ifndef BUBBLESORT_HPP_ #define BUBBLESORT_HPP_ #include <algorithm> // Bubble Sort Algorithm // Simple and slow algorithm // http://en.wikipedia.org/wiki/Bubble_sort namespace BS { class Solution { public: // Basic algorithm // Best case performance: O(n^2) // Worst case performance: O(n^2) // Worst Case Auxiliary Space Complexity: O(1) // @input: // - container - object of container type with sortable items template<typename T> static void BubbleSort(T& container) { // Why we need to check container emptyness: // container.size() = size_t // size_t - long unsigned int // if size == 0 -> 0 - 1 = max(long unsigned int) if (container.empty()) { return; } for (size_t i = 0; i < container.size() - 1; ++i) { for(size_t j = 0; j < container.size() - i - 1; ++j) { if (container[j + 1] < container[j]) { std::swap(container[j + 1], container[j]); // swap: // int temp = container[j + 1]; // container[j] = container[j + 1]; // container[j + 1] = temp; } } } } // Optimised basic algorithm // Best case performance: O(n) // Worst case performance: O(n^2) // Worst Case Auxiliary Space Complexity: O(1) // @input: // - container - object of container type with sortable items template<typename T> static void BubbleSortOptimised(T& container) { if (container.empty()) { return; } for (size_t i = 0; i < container.size() - 1; ++i) { bool swapUsed = false; for(size_t j = 0; j < container.size() - i - 1; ++j) { if (container[j + 1] < container[j]) { std::swap(container[j + 1], container[j]); swapUsed = true; } } // If we did not swap elements in container, it means that // all elements are sorted and we can exit if (!swapUsed) { return; } } } // Recursive algorithm // Best case performance: O(n) // Worst case performance: O(n^2) // Worst Case Auxiliary Space Complexity: O(1) // @input: // - container - object of container type with sortable items template<typename T> static void BubbleSortRecursive(T& container) { BSRImpl(container, container.size()); } private: template<typename T> static void BSRImpl(T& container, const size_t size) { if (size <= 0) { return; } bool swapUsed = false; for(size_t j = 0; j < size - 1; ++j) { if (container[j + 1] < container[j]) { std::swap(container[j + 1], container[j]); swapUsed = true; } } if (!swapUsed) { return; } BSRImpl(container, size - 1); } }; } #endif /* BUBBLESORT_HPP_ */ <commit_msg>Minor style changes in BubbleSort<commit_after>#ifndef BUBBLESORT_HPP_ #define BUBBLESORT_HPP_ #include <algorithm> // Bubble Sort Algorithm // Simple and slow algorithm // http://en.wikipedia.org/wiki/Bubble_sort namespace BS { class Solution { public: // Basic algorithm // Best case performance: O(n^2) // Worst case performance: O(n^2) // Worst Case Auxiliary Space Complexity: O(1) // @input: // - container - object of container type with sortable items template<typename T> static void BubbleSort(T& container) { // Why we need to check container emptyness: // container.size() = size_t // size_t - long unsigned int // if size == 0 -> 0 - 1 = max(long unsigned int) if (container.empty()) { return; } for (size_t i = 0; i < container.size() - 1; ++i) { for(size_t j = 0; j < container.size() - i - 1; ++j) { if (container[j + 1] < container[j]) { std::swap(container[j + 1], container[j]); // swap: // int temp = container[j + 1]; // container[j] = container[j + 1]; // container[j + 1] = temp; } } } } // Optimised basic algorithm // Best case performance: O(n) // Worst case performance: O(n^2) // Worst Case Auxiliary Space Complexity: O(1) // @input: // - container - object of container type with sortable items template<typename T> static void BubbleSortOptimised(T& container) { if (container.empty()) { return; } for (size_t i = 0; i < container.size() - 1; ++i) { bool swapUsed = false; for(size_t j = 0; j < container.size() - i - 1; ++j) { if (container[j + 1] < container[j]) { std::swap(container[j + 1], container[j]); swapUsed = true; } } // If we did not swap elements in container, it means that // all elements are sorted and we can exit if (!swapUsed) { return; } } } // Recursive algorithm // Best case performance: O(n) // Worst case performance: O(n^2) // Worst Case Auxiliary Space Complexity: O(1) // @input: // - container - object of container type with sortable items template<typename T> static void BubbleSortRecursive(T& container) { BSRImpl(container, container.size()); } private: template<typename T> static void BSRImpl(T& container, const size_t size) { if (size <= 0) { return; } bool swapUsed = false; for(size_t j = 0; j < size - 1; ++j) { if (container[j + 1] < container[j]) { std::swap(container[j + 1], container[j]); swapUsed = true; } } if (!swapUsed) { return; } BSRImpl(container, size - 1); } }; } #endif /* BUBBLESORT_HPP_ */ <|endoftext|>
<commit_before>#include "gamerow.h" #include <QDebug> #include <QPushButton> #include <QLabel> #include <QHBoxLayout> #include <QUrlQuery> #include <QMenu> #include <QAction> #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QNetworkReply> #include <QPixmap> int GameRow::COVER_HEIGHT = 80; GameRow::GameRow(QWidget *parent, Game game, DownloadKey key, AppController* controller) : QWidget(parent), game(game), downloadKey(key), controller(controller) { QHBoxLayout* rowLayout = new QHBoxLayout; downloadButton = new QPushButton("Download"); downloadMenu = new QMenu("Choose download"); downloadButton->setMenu(downloadMenu); connect(downloadMenu, SIGNAL(aboutToShow()), SLOT(onTriggerMenu())); connect(controller->api, SIGNAL(onDownloadKeyUploads(DownloadKey,QList<Upload>)), SLOT(onDownloadKeyUploads(DownloadKey,QList<Upload>))); imageHolder = new QLabel(); double ratio = double(Game::COVER_WIDTH) / Game::COVER_HEIGHT; imageHolder->setFixedWidth(int(COVER_HEIGHT * ratio)); imageHolder->setFixedHeight(COVER_HEIGHT); imageHolder->setScaledContents(true); imageHolder->setObjectName("imageHolder"); downloadProgress = new QProgressBar(); downloadProgress->setMinimum(0); downloadProgress->setMaximum(100); rowLayout->addWidget(imageHolder); QWidget* infoWidget = new QWidget(); QVBoxLayout* infoWidgetLayout = new QVBoxLayout(); infoWidgetLayout->addWidget(new QLabel(game.title)); infoWidgetLayout->addWidget(new QLabel(game.user.nameForDisplay())); infoWidget->setLayout(infoWidgetLayout); rowLayout->addWidget(infoWidget, 1); rowLayout->addWidget(downloadButton, 0); setLayout(rowLayout); // connect(downloadButton, SIGNAL(clicked()), SLOT(onClickDownload())); refreshThumbnail(); } GameRow::~GameRow() { } void GameRow::onClickDownload() { qDebug() << "clicked download" << game.title; layout()->removeWidget(downloadButton); downloadButton->hide(); qobject_cast<QHBoxLayout*>(layout())->addWidget(downloadProgress, 0); downloadProgress->setMaximum(0); } void GameRow::onDownloadThumbnail() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender()); reply->deleteLater(); if (reply->error() != QNetworkReply::NoError) { qDebug() << "Error downloading thumbnail" << reply->errorString(); return; } QByteArray imageData = reply->readAll(); QPixmap pixmap; if (pixmap.loadFromData(imageData)) { imageHolder->setPixmap(pixmap); } } void GameRow::onTriggerMenu() { downloadMenu->clear(); QAction* loaderAction = new QAction("Loading...", downloadMenu); loaderAction->setDisabled(true); downloadMenu->addAction(loaderAction); controller->api->downloadKeyUploads(downloadKey); } void GameRow::onDownloadKeyUploads(DownloadKey key, QList<Upload> uploads) { // need to pass correct download key first // if (key.id != downloadKey.id) { // return; // } downloadMenu->clear(); foreach (Upload upload, uploads) { downloadMenu->addAction(new QAction(upload.filename, downloadMenu)); } } void GameRow::refreshThumbnail() { if (game.coverImageUrl == "") { return; } QNetworkAccessManager* networkManager = new QNetworkAccessManager(this); qDebug() << "Fetching cover" << game.coverImageUrl; QNetworkReply* reply = networkManager->get(QNetworkRequest(QUrl(game.coverImageUrl))); connect(reply, SIGNAL(finished()), this, SLOT(onDownloadThumbnail())); } <commit_msg>show empty file list message<commit_after>#include "gamerow.h" #include <QDebug> #include <QPushButton> #include <QLabel> #include <QHBoxLayout> #include <QUrlQuery> #include <QMenu> #include <QAction> #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QNetworkReply> #include <QPixmap> int GameRow::COVER_HEIGHT = 80; GameRow::GameRow(QWidget *parent, Game game, DownloadKey key, AppController* controller) : QWidget(parent), game(game), downloadKey(key), controller(controller) { QHBoxLayout* rowLayout = new QHBoxLayout; downloadButton = new QPushButton("Download"); downloadMenu = new QMenu("Choose download"); downloadButton->setMenu(downloadMenu); connect(downloadMenu, SIGNAL(aboutToShow()), SLOT(onTriggerMenu())); connect(controller->api, SIGNAL(onDownloadKeyUploads(DownloadKey,QList<Upload>)), SLOT(onDownloadKeyUploads(DownloadKey,QList<Upload>))); imageHolder = new QLabel(); double ratio = double(Game::COVER_WIDTH) / Game::COVER_HEIGHT; imageHolder->setFixedWidth(int(COVER_HEIGHT * ratio)); imageHolder->setFixedHeight(COVER_HEIGHT); imageHolder->setScaledContents(true); imageHolder->setObjectName("imageHolder"); downloadProgress = new QProgressBar(); downloadProgress->setMinimum(0); downloadProgress->setMaximum(100); rowLayout->addWidget(imageHolder); QWidget* infoWidget = new QWidget(); QVBoxLayout* infoWidgetLayout = new QVBoxLayout(); infoWidgetLayout->addWidget(new QLabel(game.title)); infoWidgetLayout->addWidget(new QLabel(game.user.nameForDisplay())); infoWidget->setLayout(infoWidgetLayout); rowLayout->addWidget(infoWidget, 1); rowLayout->addWidget(downloadButton, 0); setLayout(rowLayout); // connect(downloadButton, SIGNAL(clicked()), SLOT(onClickDownload())); refreshThumbnail(); } GameRow::~GameRow() { } void GameRow::onClickDownload() { qDebug() << "clicked download" << game.title; layout()->removeWidget(downloadButton); downloadButton->hide(); qobject_cast<QHBoxLayout*>(layout())->addWidget(downloadProgress, 0); downloadProgress->setMaximum(0); } void GameRow::onDownloadThumbnail() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender()); reply->deleteLater(); if (reply->error() != QNetworkReply::NoError) { qDebug() << "Error downloading thumbnail" << reply->errorString(); return; } QByteArray imageData = reply->readAll(); QPixmap pixmap; if (pixmap.loadFromData(imageData)) { imageHolder->setPixmap(pixmap); } } void GameRow::onTriggerMenu() { downloadMenu->clear(); QAction* loaderAction = new QAction("Loading...", downloadMenu); loaderAction->setDisabled(true); downloadMenu->addAction(loaderAction); controller->api->downloadKeyUploads(downloadKey); } void GameRow::onDownloadKeyUploads(DownloadKey key, QList<Upload> uploads) { // need to pass correct download key first // if (key.id != downloadKey.id) { // return; // } downloadMenu->clear(); if (uploads.count() == 0) { QAction* loaderAction = new QAction("No files", downloadMenu); loaderAction->setDisabled(true); downloadMenu->addAction(loaderAction); return; } foreach (Upload upload, uploads) { downloadMenu->addAction(new QAction(upload.filename, downloadMenu)); } } void GameRow::refreshThumbnail() { if (game.coverImageUrl == "") { return; } QNetworkAccessManager* networkManager = new QNetworkAccessManager(this); qDebug() << "Fetching cover" << game.coverImageUrl; QNetworkReply* reply = networkManager->get(QNetworkRequest(QUrl(game.coverImageUrl))); connect(reply, SIGNAL(finished()), this, SLOT(onDownloadThumbnail())); } <|endoftext|>
<commit_before>//---------------------------------------------------------------------------// /*! * \file tstMCSA.cpp * \author Stuart R. Slattery * \brief Stationary solver tests. */ //---------------------------------------------------------------------------// #include <iostream> #include <vector> #include <cmath> #include <cstdlib> #include <sstream> #include <algorithm> #include <string> #include <cassert> #include <Chimera_LinearSolver.hpp> #include <Chimera_LinearProblem.hpp> #include <Chimera_LinearSolverFactory.hpp> #include <Chimera_MCSA.hpp> #include <Teuchos_UnitTestHarness.hpp> #include <Teuchos_DefaultComm.hpp> #include <Teuchos_CommHelpers.hpp> #include <Teuchos_RCP.hpp> #include <Teuchos_ArrayRCP.hpp> #include <Teuchos_Array.hpp> #include <Teuchos_OpaqueWrapper.hpp> #include <Teuchos_TypeTraits.hpp> #include <Teuchos_Tuple.hpp> #include <Teuchos_ParameterList.hpp> #include <Tpetra_Map.hpp> #include <Tpetra_CrsMatrix.hpp> #include <Tpetra_Vector.hpp> //---------------------------------------------------------------------------// // Tests //---------------------------------------------------------------------------// TEUCHOS_UNIT_TEST( MCSA, mcsa_test ) { // Setup parallel distribution. Teuchos::RCP<const Teuchos::Comm<int> > comm = Teuchos::DefaultComm<int>::getComm(); // Build the linear operator - this is a 2D Transient Diffusion operator. int N = 10; int problem_size = N*N; double dx = 0.01; double dy = 0.01; double dt = 0.05; double alpha = 0.001; Teuchos::RCP<const Tpetra::Map<int> > row_map = Tpetra::createUniformContigMap<int,int>( problem_size, comm ); Teuchos::RCP<Tpetra::CrsMatrix<double,int,int> > A = Tpetra::createCrsMatrix<double,int,int>( row_map, 3 ); Teuchos::Array<double> diag( 1, 1.0 + 2*dt*alpha*( 1/(dx*dx) + 1/(dy*dy) ) ); Teuchos::Array<double> i_minus( 1, -dt*alpha/(dx*dx) ); Teuchos::Array<double> i_plus( 1, -dt*alpha/(dx*dx) ); Teuchos::Array<double> j_minus( 1, -dt*alpha/(dy*dy) ); Teuchos::Array<double> j_plus( 1, -dt*alpha/(dy*dy) ); Teuchos::Array<int> idx(1); Teuchos::Array<int> idx_iminus(1); Teuchos::Array<int> idx_iplus(1); Teuchos::Array<int> idx_jminus(1); Teuchos::Array<int> idx_jplus(1); Teuchos::Array<double> one(1,1.0); // Min X boundary Dirichlet. for ( int j = 1; j < N-1; ++j ) { int i = 0; idx[0] = i + j*N; A->insertGlobalValues( idx[0], idx(), one() ); } // Max X boundary Dirichlet. for ( int j = 1; j < N-1; ++j ) { int i = N-1; idx[0] = i + j*N; A->insertGlobalValues( idx[0], idx(), one() ); } // Min Y boundary Dirichlet. for ( int i = 0; i < N; ++i ) { int j = 0; idx[0] = i + j*N; A->insertGlobalValues( idx[0], idx(), one() ); } // Max Y boundary Dirichlet. for ( int i = 0; i < N; ++i ) { int j = N-1; idx[0] = i + j*N; A->insertGlobalValues( idx[0], idx(), one() ); } // Central grid points. for ( int i = 1; i < N-1; ++i ) { for ( int j = 1; j < N-1; ++j ) { idx[0] = i + j*N; idx_iminus[0] = (i-1) + j*N; idx_iplus[0] = (i+1) + j*N; idx_jminus[0] = i + (j-1)*N; idx_jplus[0] = i + (j+1)*N; A->insertGlobalValues( idx[0], idx_jminus(), j_minus() ); A->insertGlobalValues( idx[0], idx_iminus(), i_minus() ); A->insertGlobalValues( idx[0], idx(), diag() ); A->insertGlobalValues( idx[0], idx_iplus(), i_plus() ); A->insertGlobalValues( idx[0], idx_jplus(), j_plus() ); } } A->fillComplete(); // Build the solution vector. double X_val = 0.0; Teuchos::RCP<Tpetra::Vector<double,int> > X = Tpetra::createVector<double,int>( row_map ); X->putScalar( X_val ); // Build the right hand side. double B_val = 0.0; Teuchos::RCP<Tpetra::Vector<double,int> > B = Tpetra::createVector<double,int>( row_map ); B->putScalar( B_val ); // Set dirichlet boundary conditions. int row; // left for ( int j = 1; j < N-1; ++j ) { int i = 0; row = i + j*N; if ( row_map->isNodeGlobalElement( row ) ) { B->replaceGlobalValue( row, 5.0 ); } } // right for ( int j = 1; j < N-1; ++j ) { int i = N-1; row = i + j*N; if ( row_map->isNodeGlobalElement( row ) ) { B->replaceGlobalValue( row, 5.0 ); } } // bottom for ( int i = 0; i < N; ++i ) { int j = 0; row = i + j*N; if ( row_map->isNodeGlobalElement( row ) ) { B->replaceGlobalValue( row, 0.0 ); } } // top for ( int i = 0; i < N; ++i ) { int j = N-1; row = i + j*N; if ( row_map->isNodeGlobalElement( row ) ) { B->replaceGlobalValue( row, 0.0 ); } } // Build the linear problem. comm->barrier(); Teuchos::RCP<Chimera::LinearProblem<double,int,int> > linear_problem = Teuchos::rcp( new Chimera::LinearProblem<double,int,int>( A, X, B ) ); // Set the solver parameters. Teuchos::RCP<Teuchos::ParameterList> plist = Teuchos::rcp( new Teuchos::ParameterList() ); plist->set<std::string>( "SOLVER TYPE", "MCSA" ); plist->set<std::string>( "RNG TYPE", "MT19937" ); plist->set<double>( "TOLERANCE", 1.0e-8 ); plist->set<int>( "MAX ITERS", 100 ); plist->set<std::string>( "SPLIT TYPE", "JACOBI" ); plist->set<std::string>( "MC TYPE", "ADJOINT" ); plist->set<double>( "WEIGHT CUTOFF", 1.0e-4 ); plist->set<int>( "HISTORIES PER STAGE", 10000 ); Teuchos::RCP<Chimera::LinearSolver<double,int,int> > solver = Chimera::LinearSolverFactory::create( plist, linear_problem ); // Solve. solver->iterate(); // Check the solution vector. Teuchos::ArrayRCP<const double> X_view = linear_problem->getLHS()->get1dView(); std::cout << X_view() << std::endl; } //---------------------------------------------------------------------------// // end tstMCSA.cpp //---------------------------------------------------------------------------// <commit_msg>working on MCSA. still some issues<commit_after>//---------------------------------------------------------------------------// /*! * \file tstMCSA.cpp * \author Stuart R. Slattery * \brief Stationary solver tests. */ //---------------------------------------------------------------------------// #include <iostream> #include <vector> #include <cmath> #include <cstdlib> #include <sstream> #include <algorithm> #include <string> #include <cassert> #include <Chimera_LinearSolver.hpp> #include <Chimera_LinearProblem.hpp> #include <Chimera_LinearSolverFactory.hpp> #include <Chimera_MCSA.hpp> #include <Teuchos_UnitTestHarness.hpp> #include <Teuchos_DefaultComm.hpp> #include <Teuchos_CommHelpers.hpp> #include <Teuchos_RCP.hpp> #include <Teuchos_ArrayRCP.hpp> #include <Teuchos_Array.hpp> #include <Teuchos_OpaqueWrapper.hpp> #include <Teuchos_TypeTraits.hpp> #include <Teuchos_Tuple.hpp> #include <Teuchos_ParameterList.hpp> #include <Tpetra_Map.hpp> #include <Tpetra_CrsMatrix.hpp> #include <Tpetra_Vector.hpp> //---------------------------------------------------------------------------// // Tests //---------------------------------------------------------------------------// TEUCHOS_UNIT_TEST( MCSA, mcsa_test ) { // Setup parallel distribution. Teuchos::RCP<const Teuchos::Comm<int> > comm = Teuchos::DefaultComm<int>::getComm(); // Build the linear operator - this is a 2D Transient Diffusion operator. int N = 10; int problem_size = N*N; double dx = 0.01; double dy = 0.01; double dt = 0.05; double alpha = 0.001; Teuchos::RCP<const Tpetra::Map<int> > row_map = Tpetra::createUniformContigMap<int,int>( problem_size, comm ); Teuchos::RCP<Tpetra::CrsMatrix<double,int,int> > A = Tpetra::createCrsMatrix<double,int,int>( row_map, 3 ); Teuchos::Array<double> diag( 1, 1.0 + 2*dt*alpha*( 1/(dx*dx) + 1/(dy*dy) ) ); Teuchos::Array<double> i_minus( 1, -dt*alpha/(dx*dx) ); Teuchos::Array<double> i_plus( 1, -dt*alpha/(dx*dx) ); Teuchos::Array<double> j_minus( 1, -dt*alpha/(dy*dy) ); Teuchos::Array<double> j_plus( 1, -dt*alpha/(dy*dy) ); Teuchos::Array<int> idx(1); Teuchos::Array<int> idx_iminus(1); Teuchos::Array<int> idx_iplus(1); Teuchos::Array<int> idx_jminus(1); Teuchos::Array<int> idx_jplus(1); Teuchos::Array<double> one(1,1.0); // Min X boundary Dirichlet. for ( int j = 1; j < N-1; ++j ) { int i = 0; idx[0] = i + j*N; A->insertGlobalValues( idx[0], idx(), one() ); } // Max X boundary Dirichlet. for ( int j = 1; j < N-1; ++j ) { int i = N-1; idx[0] = i + j*N; A->insertGlobalValues( idx[0], idx(), one() ); } // Min Y boundary Dirichlet. for ( int i = 0; i < N; ++i ) { int j = 0; idx[0] = i + j*N; A->insertGlobalValues( idx[0], idx(), one() ); } // Max Y boundary Dirichlet. for ( int i = 0; i < N; ++i ) { int j = N-1; idx[0] = i + j*N; A->insertGlobalValues( idx[0], idx(), one() ); } // Central grid points. for ( int i = 1; i < N-1; ++i ) { for ( int j = 1; j < N-1; ++j ) { idx[0] = i + j*N; idx_iminus[0] = (i-1) + j*N; idx_iplus[0] = (i+1) + j*N; idx_jminus[0] = i + (j-1)*N; idx_jplus[0] = i + (j+1)*N; A->insertGlobalValues( idx[0], idx_jminus(), j_minus() ); A->insertGlobalValues( idx[0], idx_iminus(), i_minus() ); A->insertGlobalValues( idx[0], idx(), diag() ); A->insertGlobalValues( idx[0], idx_iplus(), i_plus() ); A->insertGlobalValues( idx[0], idx_jplus(), j_plus() ); } } A->fillComplete(); // Build the solution vector. double X_val = 0.0; Teuchos::RCP<Tpetra::Vector<double,int> > X = Tpetra::createVector<double,int>( row_map ); X->putScalar( X_val ); // Build the right hand side. double B_val = 0.0; Teuchos::RCP<Tpetra::Vector<double,int> > B = Tpetra::createVector<double,int>( row_map ); B->putScalar( B_val ); // Set dirichlet boundary conditions. int row; // left for ( int j = 1; j < N-1; ++j ) { int i = 0; row = i + j*N; if ( row_map->isNodeGlobalElement( row ) ) { B->replaceGlobalValue( row, 5.0 ); } } // right for ( int j = 1; j < N-1; ++j ) { int i = N-1; row = i + j*N; if ( row_map->isNodeGlobalElement( row ) ) { B->replaceGlobalValue( row, 5.0 ); } } // bottom for ( int i = 0; i < N; ++i ) { int j = 0; row = i + j*N; if ( row_map->isNodeGlobalElement( row ) ) { B->replaceGlobalValue( row, 0.0 ); } } // top for ( int i = 0; i < N; ++i ) { int j = N-1; row = i + j*N; if ( row_map->isNodeGlobalElement( row ) ) { B->replaceGlobalValue( row, 0.0 ); } } // Build the linear problem. comm->barrier(); Teuchos::RCP<Chimera::LinearProblem<double,int,int> > linear_problem = Teuchos::rcp( new Chimera::LinearProblem<double,int,int>( A, X, B ) ); // Set the solver parameters. Teuchos::RCP<Teuchos::ParameterList> plist = Teuchos::rcp( new Teuchos::ParameterList() ); plist->set<std::string>( "SOLVER TYPE", "MCSA" ); plist->set<std::string>( "RNG TYPE", "MT19937" ); plist->set<double>( "TOLERANCE", 1.0e-8 ); plist->set<int>( "MAX ITERS", 100 ); plist->set<std::string>( "SPLIT TYPE", "JACOBI" ); plist->set<std::string>( "MC TYPE", "ADJOINT" ); plist->set<double>( "WEIGHT CUTOFF", 1.0e-4 ); plist->set<int>( "HISTORIES PER STAGE", 100 ); Teuchos::RCP<Chimera::LinearSolver<double,int,int> > solver = Chimera::LinearSolverFactory::create( plist, linear_problem ); // Solve. solver->iterate(); // Check the solution vector. Teuchos::ArrayRCP<const double> X_view = linear_problem->getLHS()->get1dView(); std::cout << X_view() << std::endl; } //---------------------------------------------------------------------------// // end tstMCSA.cpp //---------------------------------------------------------------------------// <|endoftext|>
<commit_before>#include "scheduler.h" #include <pthread.h> //for pthread_setschedparam #include <time.h> //for clock_nanosleep #include <signal.h> //for sigaction signal handlers #include <cstdlib> //for atexit #include <algorithm> //for push_heap #include "logging.h" #include "timeutil.h" std::array<std::vector<void(*)()>, SCHED_NUM_EXIT_HANDLER_LEVELS> Scheduler::exitHandlers; std::atomic<bool> Scheduler::isExiting(false); void ctrlCOrZHandler(int s){ printf("Caught signal %d\n",s); exit(1); } void segfaultHandler(int /*signal*/, siginfo_t *si, void */*arg*/) { printf("Caught segfault at address %p\n", si->si_addr); exit(1); } void Scheduler::callExitHandlers() { if (!isExiting.exchange(true)) { //try setting isExiting to true. If it was previously false, then call the exit handlers: LOG("Exiting\n"); for (const std::vector<void(*)()>& level : exitHandlers) { for (void(*handler)() : level) { (*handler)(); } } } } void Scheduler::configureExitHandlers() { std::atexit((void(*)())&Scheduler::callExitHandlers); //listen for ctrl+c, ctrl+z and segfaults. Then try to properly unmount any I/Os (crucial for disabling the heated nozzle) struct sigaction sigIntHandler; sigIntHandler.sa_handler = ctrlCOrZHandler; sigemptyset(&sigIntHandler.sa_mask); sigIntHandler.sa_flags = 0; sigaction(SIGINT, &sigIntHandler, NULL); //register ctrl+c sigaction(SIGTSTP, &sigIntHandler, NULL); //register ctrl+z sigaction(SIGABRT, &sigIntHandler, NULL); //register SIGABRT, which is triggered for critical errors (eg glibc detects double-free) struct sigaction sa; //memset(&sa, 0, sizeof(sigaction)); sigemptyset(&sa.sa_mask); sa.sa_sigaction = segfaultHandler; sa.sa_flags = SA_SIGINFO; sigaction(SIGSEGV, &sa, NULL); //register segfault listener } void Scheduler::registerExitHandler(void (*handler)(), unsigned level) { if (level > exitHandlers.size()) { throw std::runtime_error("Tried to register an exit handler at too high of a level"); } exitHandlers[level].push_back(handler); //std::atexit(handler); } Scheduler::Scheduler() : _lockPushes(mutex, std::defer_lock), _arePushesLocked(false), bufferSize(SCHED_CAPACITY) { //clock_gettime(CLOCK_MONOTONIC, &(this->lastEventHandledTime)); //initialize to current time. } void Scheduler::queue(const Event& evt) { //LOGV("Scheduler::queue\n"); std::unique_lock<std::mutex> lock(this->mutex); while (this->eventQueue.size() >= this->bufferSize) { eventConsumedCond.wait(lock); } //_lockPushes.lock(); //aquire a lock //if (this->eventQueue.size() >= this->bufferSize) { // return; //keep pushes locked. this->orderedInsert(evt); this->nonemptyCond.notify_one(); //notify the consumer thread that a new event is ready. } void Scheduler::orderedInsert(const Event &evt) { this->eventQueue.push_back(evt); if (timespecLt(evt.time(), this->eventQueue.back().time())) { //If not already ordered, we must order it. std::push_heap(this->eventQueue.begin(), this->eventQueue.end()); } } void Scheduler::schedPwm(AxisIdType idx, const PwmInfo &p) { LOGV("Scheduler::schedPwm: %i, %u, %u. Current: %u, %u\n", idx, p.nsHigh, p.nsLow, pwmInfo[idx].nsHigh, pwmInfo[idx].nsLow); if (pwmInfo[idx].nsHigh != 0 || pwmInfo[idx].nsLow != 0) { //already scheduled and running. Just update times. pwmInfo[idx] = p; } else { //have to schedule: LOGV("Scheduler::schedPwm: queueing\n"); pwmInfo[idx] = p; Event evt(timespecNow(), idx, p.nsHigh ? StepForward : StepBackward); //if we have any high-time, then start with forward, else backward. this->queue(evt); } } Event Scheduler::nextEvent(bool doSleep, std::chrono::microseconds timeout) { Event evt; if (!this->_arePushesLocked) { //Lock other threads from pushing to queue, if not done already. _lockPushes.lock(); } while (this->eventQueue.empty()) { //wait for an event to be pushed. //condition_variable.wait() can produce spurious wakeups; need the while loop. //this->nonemptyCond.wait(_lockPushes); //condition_variable.wait() can produce spurious wakeups; need the while loop. if (this->nonemptyCond.wait_for(_lockPushes, timeout) == std::cv_status::timeout) { if (!this->_arePushesLocked) { //if pushes aren't locked, then unlock the physical lock. _lockPushes.unlock(); } return Event(); //return null event } } evt = this->eventQueue.front(); this->eventQueue.pop_front(); //check if event is PWM-based: //if (pwmInfo[evt.stepperId()].nsLow != 0 || pwmInfo[evt.stepperId()].nsHigh != 0) { if (pwmInfo[evt.stepperId()].isNonNull()) { if (evt.direction() == StepForward) { //if (pwmInfo[evt.stepperId()].nsLow != 0) { //do we need to transition to a low time again? If not, then stay here forever. //next event will be StepBackward, or refresh this event if there is no off-duty. Event nextPwm(evt.time(), evt.stepperId(), pwmInfo[evt.stepperId()].nsLow ? StepBackward : StepForward); nextPwm.offsetNano(pwmInfo[evt.stepperId()].nsHigh); this->orderedInsert(nextPwm); //to do: ordered insert //} } else { //if (pwmInfo[evt.stepperId()].nsHigh != 0) { //do we need to transition to a high time again? If not, then stay here forever. //next event will be StepForward, or refresh this event if there is no on-duty. Event nextPwm(evt.time(), evt.stepperId(), pwmInfo[evt.stepperId()].nsHigh ? StepForward : StepBackward); nextPwm.offsetNano(pwmInfo[evt.stepperId()].nsLow); this->orderedInsert(nextPwm); //} } } if (this->eventQueue.size() < bufferSize) { //queue is underfilled; release the lock _lockPushes.unlock(); this->_arePushesLocked = false; eventConsumedCond.notify_one(); } else { //queue is filled; do not release the lock. this->_arePushesLocked = true; } if (doSleep) { this->sleepUntilEvent(evt); /*struct timespec sleepUntil = evt.time(); //struct timespec curTime; //clock_gettime(CLOCK_MONOTONIC, &curTime); //LOGV("Scheduler::nextEvent sleep from %lu.%lu until %lu.%lu\n", curTime.tv_sec, curTime.tv_nsec, sleepUntil.tv_sec, sleepUntil.tv_nsec); clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &sleepUntil, NULL); //sleep to event time. //clock_gettime(CLOCK_MONOTONIC, &(this->lastEventHandledTime)); //in case we fall behind, preserve the relative time between events. //this->lastEventHandledTime = sleepUntil;*/ } return evt; } void Scheduler::sleepUntilEvent(const Event &evt) const { struct timespec sleepUntil = evt.time(); clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &sleepUntil, NULL); //sleep to event time. } void Scheduler::initSchedThread() const { struct sched_param sp; sp.sched_priority=SCHED_PRIORITY; if (int ret = pthread_setschedparam(pthread_self(), SCHED_FIFO, &sp)) { LOGW("Warning: pthread_setschedparam (increase thread priority) at scheduler.cpp returned non-zero: %i\n", ret); } } struct timespec Scheduler::lastSchedTime() const { Event evt; { std::unique_lock<std::mutex> lock(this->mutex); if (this->eventQueue.size()) { evt = this->eventQueue.back(); } else { lock.unlock(); timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return ts; } } return evt.time(); } void Scheduler::setBufferSize(unsigned size) { this->bufferSize = size; LOG("Scheduler buffer size set: %u\n", size); } unsigned Scheduler::getBufferSize() const { return this->bufferSize; } unsigned Scheduler::numActivePwmChannels() const { unsigned r=0; for (const PwmInfo &p : this->pwmInfo) { if (p.isNonNull()) { r += 1; } } return r; } <commit_msg>Scheduler mutexes optimizing<commit_after>#include "scheduler.h" #include <pthread.h> //for pthread_setschedparam #include <time.h> //for clock_nanosleep #include <signal.h> //for sigaction signal handlers #include <cstdlib> //for atexit #include <algorithm> //for push_heap #include "logging.h" #include "timeutil.h" std::array<std::vector<void(*)()>, SCHED_NUM_EXIT_HANDLER_LEVELS> Scheduler::exitHandlers; std::atomic<bool> Scheduler::isExiting(false); void ctrlCOrZHandler(int s){ printf("Caught signal %d\n",s); exit(1); } void segfaultHandler(int /*signal*/, siginfo_t *si, void */*arg*/) { printf("Caught segfault at address %p\n", si->si_addr); exit(1); } void Scheduler::callExitHandlers() { if (!isExiting.exchange(true)) { //try setting isExiting to true. If it was previously false, then call the exit handlers: LOG("Exiting\n"); for (const std::vector<void(*)()>& level : exitHandlers) { for (void(*handler)() : level) { (*handler)(); } } } } void Scheduler::configureExitHandlers() { std::atexit((void(*)())&Scheduler::callExitHandlers); //listen for ctrl+c, ctrl+z and segfaults. Then try to properly unmount any I/Os (crucial for disabling the heated nozzle) struct sigaction sigIntHandler; sigIntHandler.sa_handler = ctrlCOrZHandler; sigemptyset(&sigIntHandler.sa_mask); sigIntHandler.sa_flags = 0; sigaction(SIGINT, &sigIntHandler, NULL); //register ctrl+c sigaction(SIGTSTP, &sigIntHandler, NULL); //register ctrl+z sigaction(SIGABRT, &sigIntHandler, NULL); //register SIGABRT, which is triggered for critical errors (eg glibc detects double-free) struct sigaction sa; //memset(&sa, 0, sizeof(sigaction)); sigemptyset(&sa.sa_mask); sa.sa_sigaction = segfaultHandler; sa.sa_flags = SA_SIGINFO; sigaction(SIGSEGV, &sa, NULL); //register segfault listener } void Scheduler::registerExitHandler(void (*handler)(), unsigned level) { if (level > exitHandlers.size()) { throw std::runtime_error("Tried to register an exit handler at too high of a level"); } exitHandlers[level].push_back(handler); //std::atexit(handler); } Scheduler::Scheduler() : _lockPushes(mutex, std::defer_lock), _arePushesLocked(false), bufferSize(SCHED_CAPACITY) { //clock_gettime(CLOCK_MONOTONIC, &(this->lastEventHandledTime)); //initialize to current time. } void Scheduler::queue(const Event& evt) { //LOGV("Scheduler::queue\n"); std::unique_lock<std::mutex> lock(this->mutex); while (this->eventQueue.size() >= this->bufferSize) { eventConsumedCond.wait(lock); } //_lockPushes.lock(); //aquire a lock //if (this->eventQueue.size() >= this->bufferSize) { // return; //keep pushes locked. this->orderedInsert(evt); this->nonemptyCond.notify_one(); //notify the consumer thread that a new event is ready. } void Scheduler::orderedInsert(const Event &evt) { this->eventQueue.push_back(evt); if (timespecLt(evt.time(), this->eventQueue.back().time())) { //If not already ordered, we must order it. std::push_heap(this->eventQueue.begin(), this->eventQueue.end()); } } void Scheduler::schedPwm(AxisIdType idx, const PwmInfo &p) { LOGV("Scheduler::schedPwm: %i, %u, %u. Current: %u, %u\n", idx, p.nsHigh, p.nsLow, pwmInfo[idx].nsHigh, pwmInfo[idx].nsLow); if (pwmInfo[idx].nsHigh != 0 || pwmInfo[idx].nsLow != 0) { //already scheduled and running. Just update times. pwmInfo[idx] = p; } else { //have to schedule: LOGV("Scheduler::schedPwm: queueing\n"); pwmInfo[idx] = p; Event evt(timespecNow(), idx, p.nsHigh ? StepForward : StepBackward); //if we have any high-time, then start with forward, else backward. this->queue(evt); } } Event Scheduler::nextEvent(bool doSleep, std::chrono::microseconds timeout) { Event evt; { std::unique_lock<std::mutex> lock(this->mutex); while (this->eventQueue.empty()) { //wait for an event to be pushed. //condition_variable.wait() can produce spurious wakeups; need the while loop. //this->nonemptyCond.wait(_lockPushes); //condition_variable.wait() can produce spurious wakeups; need the while loop. if (this->nonemptyCond.wait_for(lock, timeout) == std::cv_status::timeout) { return Event(); //return null event } } evt = this->eventQueue.front(); this->eventQueue.pop_front(); //check if event is PWM-based: //if (pwmInfo[evt.stepperId()].nsLow != 0 || pwmInfo[evt.stepperId()].nsHigh != 0) { if (pwmInfo[evt.stepperId()].isNonNull()) { if (evt.direction() == StepForward) { //next event will be StepBackward, or refresh this event if there is no off-duty. Event nextPwm(evt.time(), evt.stepperId(), pwmInfo[evt.stepperId()].nsLow ? StepBackward : StepForward); nextPwm.offsetNano(pwmInfo[evt.stepperId()].nsHigh); this->orderedInsert(nextPwm); //to do: ordered insert } else { //next event will be StepForward, or refresh this event if there is no on-duty. Event nextPwm(evt.time(), evt.stepperId(), pwmInfo[evt.stepperId()].nsHigh ? StepForward : StepBackward); nextPwm.offsetNano(pwmInfo[evt.stepperId()].nsLow); this->orderedInsert(nextPwm); } } else { //non-pwm event, means the queue size has decreased by 1. lock.unlock(); eventConsumedCond.notify_one(); } } if (doSleep) { this->sleepUntilEvent(evt); /*struct timespec sleepUntil = evt.time(); //struct timespec curTime; //clock_gettime(CLOCK_MONOTONIC, &curTime); //LOGV("Scheduler::nextEvent sleep from %lu.%lu until %lu.%lu\n", curTime.tv_sec, curTime.tv_nsec, sleepUntil.tv_sec, sleepUntil.tv_nsec); clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &sleepUntil, NULL); //sleep to event time. //clock_gettime(CLOCK_MONOTONIC, &(this->lastEventHandledTime)); //in case we fall behind, preserve the relative time between events. //this->lastEventHandledTime = sleepUntil;*/ } return evt; /*Event evt; if (!this->_arePushesLocked) { //Lock other threads from pushing to queue, if not done already. _lockPushes.lock(); } while (this->eventQueue.empty()) { //wait for an event to be pushed. //condition_variable.wait() can produce spurious wakeups; need the while loop. //this->nonemptyCond.wait(_lockPushes); //condition_variable.wait() can produce spurious wakeups; need the while loop. if (this->nonemptyCond.wait_for(_lockPushes, timeout) == std::cv_status::timeout) { if (!this->_arePushesLocked) { //if pushes aren't locked, then unlock the physical lock. _lockPushes.unlock(); } return Event(); //return null event } } evt = this->eventQueue.front(); this->eventQueue.pop_front(); //check if event is PWM-based: //if (pwmInfo[evt.stepperId()].nsLow != 0 || pwmInfo[evt.stepperId()].nsHigh != 0) { if (pwmInfo[evt.stepperId()].isNonNull()) { if (evt.direction() == StepForward) { //if (pwmInfo[evt.stepperId()].nsLow != 0) { //do we need to transition to a low time again? If not, then stay here forever. //next event will be StepBackward, or refresh this event if there is no off-duty. Event nextPwm(evt.time(), evt.stepperId(), pwmInfo[evt.stepperId()].nsLow ? StepBackward : StepForward); nextPwm.offsetNano(pwmInfo[evt.stepperId()].nsHigh); this->orderedInsert(nextPwm); //to do: ordered insert //} } else { //if (pwmInfo[evt.stepperId()].nsHigh != 0) { //do we need to transition to a high time again? If not, then stay here forever. //next event will be StepForward, or refresh this event if there is no on-duty. Event nextPwm(evt.time(), evt.stepperId(), pwmInfo[evt.stepperId()].nsHigh ? StepForward : StepBackward); nextPwm.offsetNano(pwmInfo[evt.stepperId()].nsLow); this->orderedInsert(nextPwm); //} } } if (this->eventQueue.size() < bufferSize) { //queue is underfilled; release the lock _lockPushes.unlock(); this->_arePushesLocked = false; eventConsumedCond.notify_one(); } else { //queue is filled; do not release the lock. this->_arePushesLocked = true; } if (doSleep) { this->sleepUntilEvent(evt); /*struct timespec sleepUntil = evt.time(); //struct timespec curTime; //clock_gettime(CLOCK_MONOTONIC, &curTime); //LOGV("Scheduler::nextEvent sleep from %lu.%lu until %lu.%lu\n", curTime.tv_sec, curTime.tv_nsec, sleepUntil.tv_sec, sleepUntil.tv_nsec); clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &sleepUntil, NULL); //sleep to event time. //clock_gettime(CLOCK_MONOTONIC, &(this->lastEventHandledTime)); //in case we fall behind, preserve the relative time between events. //this->lastEventHandledTime = sleepUntil;*/ //} //return evt; } void Scheduler::sleepUntilEvent(const Event &evt) const { struct timespec sleepUntil = evt.time(); clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &sleepUntil, NULL); //sleep to event time. } void Scheduler::initSchedThread() const { struct sched_param sp; sp.sched_priority=SCHED_PRIORITY; if (int ret = pthread_setschedparam(pthread_self(), SCHED_FIFO, &sp)) { LOGW("Warning: pthread_setschedparam (increase thread priority) at scheduler.cpp returned non-zero: %i\n", ret); } } struct timespec Scheduler::lastSchedTime() const { Event evt; { std::unique_lock<std::mutex> lock(this->mutex); if (this->eventQueue.size()) { evt = this->eventQueue.back(); } else { lock.unlock(); timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return ts; } } return evt.time(); } void Scheduler::setBufferSize(unsigned size) { this->bufferSize = size; LOG("Scheduler buffer size set: %u\n", size); } unsigned Scheduler::getBufferSize() const { return this->bufferSize; } unsigned Scheduler::numActivePwmChannels() const { unsigned r=0; for (const PwmInfo &p : this->pwmInfo) { if (p.isNonNull()) { r += 1; } } return r; } <|endoftext|>
<commit_before>/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016 Vladimír Vondruš <mosra@centrum.cz> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "CubeMap.h" #include <Corrade/Utility/Resource.h> #include <Magnum/Buffer.h> #include <Magnum/CubeMapTexture.h> #include <Magnum/Texture.h> #include <Magnum/TextureFormat.h> #include <Magnum/Math/Functions.h> #include <Magnum/MeshTools/FlipNormals.h> #include <Magnum/MeshTools/Interleave.h> #include <Magnum/MeshTools/CompressIndices.h> #include <Magnum/Primitives/Cube.h> #include <Magnum/SceneGraph/Scene.h> #include <Magnum/SceneGraph/Camera.h> #include <Magnum/Trade/AbstractImporter.h> #include <Magnum/Trade/ImageData.h> #include <Magnum/Trade/MeshData3D.h> #include "CubeMapShader.h" namespace Magnum { namespace Examples { CubeMap::CubeMap(const std::string& prefix, Object3D* parent, SceneGraph::DrawableGroup3D* group): Object3D(parent), SceneGraph::Drawable3D(*this, group) { CubeMapResourceManager& resourceManager = CubeMapResourceManager::instance(); /* Cube mesh */ if(!(_cube = resourceManager.get<Mesh>("cube"))) { Trade::MeshData3D cubeData = Primitives::Cube::solid(); MeshTools::flipFaceWinding(cubeData.indices()); Buffer* buffer = new Buffer; buffer->setData(MeshTools::interleave(cubeData.positions(0)), BufferUsage::StaticDraw); Containers::Array<char> indexData; Mesh::IndexType indexType; UnsignedInt indexStart, indexEnd; std::tie(indexData, indexType, indexStart, indexEnd) = MeshTools::compressIndices(cubeData.indices()); Buffer* indexBuffer = new Buffer; indexBuffer->setData(indexData, BufferUsage::StaticDraw); Mesh* mesh = new Mesh; mesh->setPrimitive(cubeData.primitive()) .setCount(cubeData.indices().size()) .addVertexBuffer(*buffer, 0, CubeMapShader::Position{}) .setIndexBuffer(*indexBuffer, 0, indexType, indexStart, indexEnd); resourceManager.set("cube-buffer", buffer, ResourceDataState::Final, ResourcePolicy::Resident) .set("cube-index-buffer", indexBuffer, ResourceDataState::Final, ResourcePolicy::Resident) .set(_cube.key(), mesh, ResourceDataState::Final, ResourcePolicy::Resident); } /* Cube map texture */ if(!(_texture = resourceManager.get<CubeMapTexture>("texture"))) { CubeMapTexture* cubeMap = new CubeMapTexture; cubeMap->setWrapping(Sampler::Wrapping::ClampToEdge) .setMagnificationFilter(Sampler::Filter::Linear) .setMinificationFilter(Sampler::Filter::Linear, Sampler::Mipmap::Linear); Resource<Trade::AbstractImporter> importer = resourceManager.get<Trade::AbstractImporter>("jpeg-importer"); /* Configure texture storage using size of first image */ importer->openFile(prefix + "+x.jpg"); std::optional<Trade::ImageData2D> image = importer->image2D(0); CORRADE_INTERNAL_ASSERT(image); Vector2i size = image->size(); cubeMap->setStorage(Math::log2(size.min())+1, TextureFormat::RGB8, size) .setSubImage(CubeMapTexture::Coordinate::PositiveX, 0, {}, *image); importer->openFile(prefix + "-x.jpg"); CORRADE_INTERNAL_ASSERT_OUTPUT(image = importer->image2D(0)); cubeMap->setSubImage(CubeMapTexture::Coordinate::NegativeX, 0, {}, *image); importer->openFile(prefix + "+y.jpg"); CORRADE_INTERNAL_ASSERT_OUTPUT(image = importer->image2D(0)); cubeMap->setSubImage(CubeMapTexture::Coordinate::PositiveY, 0, {}, *image); importer->openFile(prefix + "-y.jpg"); CORRADE_INTERNAL_ASSERT_OUTPUT(image = importer->image2D(0)); cubeMap->setSubImage(CubeMapTexture::Coordinate::NegativeY, 0, {}, *image); importer->openFile(prefix + "+z.jpg"); CORRADE_INTERNAL_ASSERT_OUTPUT(image = importer->image2D(0)); cubeMap->setSubImage(CubeMapTexture::Coordinate::PositiveZ, 0, {}, *image); importer->openFile(prefix + "-z.jpg"); CORRADE_INTERNAL_ASSERT_OUTPUT(image = importer->image2D(0)); cubeMap->setSubImage(CubeMapTexture::Coordinate::NegativeZ, 0, {}, *image); cubeMap->generateMipmap(); resourceManager.set(_texture.key(), cubeMap, ResourceDataState::Final, ResourcePolicy::Manual); } /* Shader */ if(!(_shader = resourceManager.get<AbstractShaderProgram, CubeMapShader>("shader"))) resourceManager.set<AbstractShaderProgram>(_shader.key(), new CubeMapShader, ResourceDataState::Final, ResourcePolicy::Manual); } void CubeMap::draw(const Matrix4& transformationMatrix, SceneGraph::Camera3D& camera) { _shader->setTransformationProjectionMatrix(camera.projectionMatrix()*transformationMatrix) .setTexture(*_texture); _cube->draw(*_shader); } }} <commit_msg>cubemap: don't use deprecated functionality.<commit_after>/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016 Vladimír Vondruš <mosra@centrum.cz> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "CubeMap.h" #include <Corrade/Utility/Resource.h> #include <Magnum/Buffer.h> #include <Magnum/CubeMapTexture.h> #include <Magnum/Texture.h> #include <Magnum/TextureFormat.h> #include <Magnum/Math/Functions.h> #include <Magnum/MeshTools/FlipNormals.h> #include <Magnum/MeshTools/Interleave.h> #include <Magnum/MeshTools/CompressIndices.h> #include <Magnum/Primitives/Cube.h> #include <Magnum/SceneGraph/Scene.h> #include <Magnum/SceneGraph/Camera.h> #include <Magnum/Trade/AbstractImporter.h> #include <Magnum/Trade/ImageData.h> #include <Magnum/Trade/MeshData3D.h> #include "CubeMapShader.h" namespace Magnum { namespace Examples { CubeMap::CubeMap(const std::string& prefix, Object3D* parent, SceneGraph::DrawableGroup3D* group): Object3D(parent), SceneGraph::Drawable3D(*this, group) { CubeMapResourceManager& resourceManager = CubeMapResourceManager::instance(); /* Cube mesh */ if(!(_cube = resourceManager.get<Mesh>("cube"))) { Trade::MeshData3D cubeData = Primitives::Cube::solid(); MeshTools::flipFaceWinding(cubeData.indices()); Buffer* buffer = new Buffer; buffer->setData(MeshTools::interleave(cubeData.positions(0)), BufferUsage::StaticDraw); Containers::Array<char> indexData; Mesh::IndexType indexType; UnsignedInt indexStart, indexEnd; std::tie(indexData, indexType, indexStart, indexEnd) = MeshTools::compressIndices(cubeData.indices()); Buffer* indexBuffer = new Buffer; indexBuffer->setData(indexData, BufferUsage::StaticDraw); Mesh* mesh = new Mesh; mesh->setPrimitive(cubeData.primitive()) .setCount(cubeData.indices().size()) .addVertexBuffer(*buffer, 0, CubeMapShader::Position{}) .setIndexBuffer(*indexBuffer, 0, indexType, indexStart, indexEnd); resourceManager.set("cube-buffer", buffer, ResourceDataState::Final, ResourcePolicy::Resident) .set("cube-index-buffer", indexBuffer, ResourceDataState::Final, ResourcePolicy::Resident) .set(_cube.key(), mesh, ResourceDataState::Final, ResourcePolicy::Resident); } /* Cube map texture */ if(!(_texture = resourceManager.get<CubeMapTexture>("texture"))) { CubeMapTexture* cubeMap = new CubeMapTexture; cubeMap->setWrapping(Sampler::Wrapping::ClampToEdge) .setMagnificationFilter(Sampler::Filter::Linear) .setMinificationFilter(Sampler::Filter::Linear, Sampler::Mipmap::Linear); Resource<Trade::AbstractImporter> importer = resourceManager.get<Trade::AbstractImporter>("jpeg-importer"); /* Configure texture storage using size of first image */ importer->openFile(prefix + "+x.jpg"); std::optional<Trade::ImageData2D> image = importer->image2D(0); CORRADE_INTERNAL_ASSERT(image); Vector2i size = image->size(); cubeMap->setStorage(Math::log2(size.min())+1, TextureFormat::RGB8, size) .setSubImage(CubeMapCoordinate::PositiveX, 0, {}, *image); importer->openFile(prefix + "-x.jpg"); CORRADE_INTERNAL_ASSERT_OUTPUT(image = importer->image2D(0)); cubeMap->setSubImage(CubeMapCoordinate::NegativeX, 0, {}, *image); importer->openFile(prefix + "+y.jpg"); CORRADE_INTERNAL_ASSERT_OUTPUT(image = importer->image2D(0)); cubeMap->setSubImage(CubeMapCoordinate::PositiveY, 0, {}, *image); importer->openFile(prefix + "-y.jpg"); CORRADE_INTERNAL_ASSERT_OUTPUT(image = importer->image2D(0)); cubeMap->setSubImage(CubeMapCoordinate::NegativeY, 0, {}, *image); importer->openFile(prefix + "+z.jpg"); CORRADE_INTERNAL_ASSERT_OUTPUT(image = importer->image2D(0)); cubeMap->setSubImage(CubeMapCoordinate::PositiveZ, 0, {}, *image); importer->openFile(prefix + "-z.jpg"); CORRADE_INTERNAL_ASSERT_OUTPUT(image = importer->image2D(0)); cubeMap->setSubImage(CubeMapCoordinate::NegativeZ, 0, {}, *image); cubeMap->generateMipmap(); resourceManager.set(_texture.key(), cubeMap, ResourceDataState::Final, ResourcePolicy::Manual); } /* Shader */ if(!(_shader = resourceManager.get<AbstractShaderProgram, CubeMapShader>("shader"))) resourceManager.set<AbstractShaderProgram>(_shader.key(), new CubeMapShader, ResourceDataState::Final, ResourcePolicy::Manual); } void CubeMap::draw(const Matrix4& transformationMatrix, SceneGraph::Camera3D& camera) { _shader->setTransformationProjectionMatrix(camera.projectionMatrix()*transformationMatrix) .setTexture(*_texture); _cube->draw(*_shader); } }} <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbSuperimpose.h" #include <iostream> #include "otbImageFileReader.h" #include "otbStreamingImageFileWriter.h" #include "otbImage.h" #include "otbVectorImage.h" #include "otbGenericRSResampleImageFilter.h" #include "otbBCOInterpolateImageFunction.h" #include "itkExceptionObject.h" #include "otbStandardWriterWatcher.h" #include "otbSimpleRcsPanSharpeningFusionImageFilter.h" #include "otbHCSPanSharpeningFusionImageFilter.h" #include "otbStreamingStatisticsImageFilter.h" #include "otbStreamingStatisticsVectorImageFilter.h" #include "itkSquareImageFilter.h" #include "itkPixelBuilder.h" #include "init/ossimInit.h" #include "itkFixedArray.h" #include "otbPipelineMemoryPrintCalculator.h" namespace otb { namespace Functor { template <class TInput, class TOutput> class VectorToSquaredNormFunctor { public: inline TOutput operator ()(const TInput& A) { return static_cast<TOutput>(A.GetSquaredNorm()); } itkConceptMacro(OutputShouldNotBeVectorImageCheck, (itk::Concept::Convertible<TOutput, double>)); }; // end namespace Functor } int Superimpose::Describe(ApplicationDescriptor* descriptor) { descriptor->SetName("Superimpose"); descriptor->SetDescription("Using available image metadata, project one image onto another one"); descriptor->AddOption("DEMDirectory","Directory were to find the DEM tiles","dem",1,false,otb::ApplicationDescriptor::DirectoryName); descriptor->AddOption("NumStreamDivisions","Number of streaming divisions (optional)","stream",1,false,otb::ApplicationDescriptor::Integer); descriptor->AddOption("LocMapSpacing","Generate a coarser deformation field with the given spacing.","lmSpacing",1,false,otb::ApplicationDescriptor::Real); descriptor->AddOption("ReferenceInput","The reference input","inR", 1,true,otb::ApplicationDescriptor::InputImage); descriptor->AddOption("MovingInput","The image to reproject","inM", 1,true,otb::ApplicationDescriptor::InputImage); descriptor->AddOutputImage(); return EXIT_SUCCESS; } int Superimpose::Execute(otb::ApplicationOptionsResult* parseResult) { try { typedef unsigned short int PixelType; typedef otb::VectorImage<PixelType, 2> ImageType; typedef otb::ImageFileReader<ImageType> ReaderType; typedef otb::StreamingImageFileWriter<ImageType> WriterType; typedef otb::BCOInterpolateImageFunction<ImageType> InterpolatorType; typedef otb::GenericRSResampleImageFilter<ImageType,ImageType> ResamplerType; // Read input images information ReaderType::Pointer refReader = ReaderType::New(); refReader->SetFileName(parseResult->GetParameterString("ReferenceInput")); refReader->GenerateOutputInformation(); ReaderType::Pointer movingReader = ReaderType::New(); movingReader->SetFileName(parseResult->GetParameterString("MovingInput")); movingReader->GenerateOutputInformation(); // Resample filter ResamplerType::Pointer resampler = ResamplerType::New(); InterpolatorType::Pointer interpolator = InterpolatorType::New(); resampler->SetInterpolator(interpolator); // Add DEM if any if(parseResult->IsOptionPresent("DEMDirectory")) { resampler->SetDEMDirectory(parseResult->GetParameterString("DEMDirectory",0)); } // Set up output image informations ImageType::SpacingType spacing = refReader->GetOutput()->GetSpacing(); ImageType::IndexType start = refReader->GetOutput()->GetLargestPossibleRegion().GetIndex(); ImageType::SizeType size = refReader->GetOutput()->GetLargestPossibleRegion().GetSize(); ImageType::PointType origin = refReader->GetOutput()->GetOrigin(); if(parseResult->IsOptionPresent("LocMapSpacing")) { double defScalarSpacing = parseResult->GetParameterFloat("LocMapSpacing"); std::cout<<"Generating coarse deformation field (spacing="<<defScalarSpacing<<")"<<std::endl; ImageType::SpacingType defSpacing; defSpacing[0] = defScalarSpacing; defSpacing[1] = defScalarSpacing; resampler->SetDeformationFieldSpacing(defSpacing); } else { ImageType::SpacingType defSpacing; defSpacing[0]=10*spacing[0]; defSpacing[1]=10*spacing[1]; resampler->SetDeformationFieldSpacing(defSpacing); } ImageType::PixelType defaultValue; itk::PixelBuilder<ImageType::PixelType>::Zero(defaultValue, movingReader->GetOutput()->GetNumberOfComponentsPerPixel()); resampler->SetInput(movingReader->GetOutput()); resampler->SetOutputOrigin(origin); resampler->SetOutputSpacing(spacing); resampler->SetOutputSize(size); resampler->SetOutputStartIndex(start); resampler->SetOutputKeywordList(refReader->GetOutput()->GetImageKeywordlist()); resampler->SetOutputProjectionRef(refReader->GetOutput()->GetProjectionRef()); resampler->SetEdgePaddingValue(defaultValue); WriterType::Pointer writer = WriterType::New(); writer->SetFileName(parseResult->GetOutputImage()); writer->SetInput(resampler->GetOutput()); writer->SetWriteGeomFile(true); otb::StandardWriterWatcher w4(writer,resampler,"Superimposition"); otb::PipelineMemoryPrintCalculator::Pointer memoryPrintCalculator = otb::PipelineMemoryPrintCalculator::New(); const double byteToMegabyte = 1./vcl_pow(2.0, 20); memoryPrintCalculator->SetDataToWrite(resampler->GetOutput()); memoryPrintCalculator->SetAvailableMemory(256 / byteToMegabyte); if (parseResult->IsOptionPresent("AvailableMemory")) { long long int memory = static_cast <long long int> (parseResult->GetParameterUInt("AvailableMemory")); memoryPrintCalculator->SetAvailableMemory(memory / byteToMegabyte); } memoryPrintCalculator->SetBiasCorrectionFactor(1.27); memoryPrintCalculator->Compute(); writer->SetTilingStreamDivisions(memoryPrintCalculator->GetOptimalNumberOfStreamDivisions()); writer->Update(); } catch ( itk::ExceptionObject & err ) { std::cout << "Exception itk::ExceptionObject raised !" << std::endl; std::cout << err << std::endl; return EXIT_FAILURE; } catch ( std::bad_alloc & err ) { std::cout << "Exception bad_alloc : "<<(char*)err.what()<< std::endl; return EXIT_FAILURE; } catch ( ... ) { std::cout << "Unknown exception raised !" << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } } <commit_msg>COMP: fix Superimpose<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbSuperimpose.h" #include <iostream> #include "otbImageFileReader.h" #include "otbStreamingImageFileWriter.h" #include "otbImage.h" #include "otbVectorImage.h" #include "otbGenericRSResampleImageFilter.h" #include "otbBCOInterpolateImageFunction.h" #include "itkExceptionObject.h" #include "otbStandardWriterWatcher.h" #include "otbPipelineMemoryPrintCalculator.h" namespace otb { int Superimpose::Describe(ApplicationDescriptor* descriptor) { descriptor->SetName("Superimpose"); descriptor->SetDescription("Using available image metadata, project one image onto another one"); descriptor->AddOption("DEMDirectory","Directory were to find the DEM tiles","dem",1,false,otb::ApplicationDescriptor::DirectoryName); descriptor->AddOption("NumStreamDivisions","Number of streaming divisions (optional)","stream",1,false,otb::ApplicationDescriptor::Integer); descriptor->AddOption("LocMapSpacing","Generate a coarser deformation field with the given spacing.","lmSpacing",1,false,otb::ApplicationDescriptor::Real); descriptor->AddOption("ReferenceInput","The reference input","inR", 1,true,otb::ApplicationDescriptor::InputImage); descriptor->AddOption("MovingInput","The image to reproject","inM", 1,true,otb::ApplicationDescriptor::InputImage); descriptor->AddOutputImage(); return EXIT_SUCCESS; } int Superimpose::Execute(otb::ApplicationOptionsResult* parseResult) { try { typedef unsigned short int PixelType; typedef otb::VectorImage<PixelType, 2> ImageType; typedef otb::ImageFileReader<ImageType> ReaderType; typedef otb::StreamingImageFileWriter<ImageType> WriterType; typedef otb::BCOInterpolateImageFunction<ImageType> InterpolatorType; typedef otb::GenericRSResampleImageFilter<ImageType,ImageType> ResamplerType; // Read input images information ReaderType::Pointer refReader = ReaderType::New(); refReader->SetFileName(parseResult->GetParameterString("ReferenceInput")); refReader->GenerateOutputInformation(); ReaderType::Pointer movingReader = ReaderType::New(); movingReader->SetFileName(parseResult->GetParameterString("MovingInput")); movingReader->GenerateOutputInformation(); // Resample filter ResamplerType::Pointer resampler = ResamplerType::New(); InterpolatorType::Pointer interpolator = InterpolatorType::New(); resampler->SetInterpolator(interpolator); // Add DEM if any if(parseResult->IsOptionPresent("DEMDirectory")) { resampler->SetDEMDirectory(parseResult->GetParameterString("DEMDirectory",0)); } // Set up output image informations ImageType::SpacingType spacing = refReader->GetOutput()->GetSpacing(); ImageType::IndexType start = refReader->GetOutput()->GetLargestPossibleRegion().GetIndex(); ImageType::SizeType size = refReader->GetOutput()->GetLargestPossibleRegion().GetSize(); ImageType::PointType origin = refReader->GetOutput()->GetOrigin(); if(parseResult->IsOptionPresent("LocMapSpacing")) { double defScalarSpacing = parseResult->GetParameterFloat("LocMapSpacing"); std::cout<<"Generating coarse deformation field (spacing="<<defScalarSpacing<<")"<<std::endl; ImageType::SpacingType defSpacing; defSpacing[0] = defScalarSpacing; defSpacing[1] = defScalarSpacing; resampler->SetDeformationFieldSpacing(defSpacing); } else { ImageType::SpacingType defSpacing; defSpacing[0]=10*spacing[0]; defSpacing[1]=10*spacing[1]; resampler->SetDeformationFieldSpacing(defSpacing); } ImageType::PixelType defaultValue; itk::PixelBuilder<ImageType::PixelType>::Zero(defaultValue, movingReader->GetOutput()->GetNumberOfComponentsPerPixel()); resampler->SetInput(movingReader->GetOutput()); resampler->SetOutputOrigin(origin); resampler->SetOutputSpacing(spacing); resampler->SetOutputSize(size); resampler->SetOutputStartIndex(start); resampler->SetOutputKeywordList(refReader->GetOutput()->GetImageKeywordlist()); resampler->SetOutputProjectionRef(refReader->GetOutput()->GetProjectionRef()); resampler->SetEdgePaddingValue(defaultValue); WriterType::Pointer writer = WriterType::New(); writer->SetFileName(parseResult->GetOutputImage()); writer->SetInput(resampler->GetOutput()); writer->SetWriteGeomFile(true); otb::StandardWriterWatcher w4(writer,resampler,"Superimposition"); otb::PipelineMemoryPrintCalculator::Pointer memoryPrintCalculator = otb::PipelineMemoryPrintCalculator::New(); const double byteToMegabyte = 1./vcl_pow(2.0, 20); memoryPrintCalculator->SetDataToWrite(resampler->GetOutput()); memoryPrintCalculator->SetAvailableMemory(256 / byteToMegabyte); if (parseResult->IsOptionPresent("AvailableMemory")) { long long int memory = static_cast <long long int> (parseResult->GetParameterUInt("AvailableMemory")); memoryPrintCalculator->SetAvailableMemory(memory / byteToMegabyte); } memoryPrintCalculator->SetBiasCorrectionFactor(1.27); memoryPrintCalculator->Compute(); writer->SetTilingStreamDivisions(memoryPrintCalculator->GetOptimalNumberOfStreamDivisions()); writer->Update(); } catch ( itk::ExceptionObject & err ) { std::cout << "Exception itk::ExceptionObject raised !" << std::endl; std::cout << err << std::endl; return EXIT_FAILURE; } catch ( std::bad_alloc & err ) { std::cout << "Exception bad_alloc : "<<(char*)err.what()<< std::endl; return EXIT_FAILURE; } catch ( ... ) { std::cout << "Unknown exception raised !" << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } } <|endoftext|>
<commit_before>// This file is part of the AliceVision project. // Copyright (c) 2016 AliceVision contributors. // Copyright (c) 2012 openMVG contributors. // This Source Code Form is subject to the terms of the Mozilla Public License, // v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at https://mozilla.org/MPL/2.0/. #pragma once #include <string> namespace aliceVision { namespace sensorDB { /** * @brief The Database structure */ struct Datasheet { Datasheet() {} /** * @brief Datasheet Constructor * @param brand * @param model * @param sensorSize */ Datasheet( const std::string& brand, const std::string& model, const double& sensorSize ): _brand(brand), _model(model), _sensorSize(sensorSize) {} bool operator==(const Datasheet& ds) const; std::string _brand; std::string _model; double _sensorSize; }; } // namespace sensorDB } // namespace aliceVision <commit_msg>[sensor] default constructor init _sensorSize<commit_after>// This file is part of the AliceVision project. // Copyright (c) 2016 AliceVision contributors. // Copyright (c) 2012 openMVG contributors. // This Source Code Form is subject to the terms of the Mozilla Public License, // v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at https://mozilla.org/MPL/2.0/. #pragma once #include <string> namespace aliceVision { namespace sensorDB { /** * @brief The Database structure */ struct Datasheet { Datasheet() = default; /** * @brief Datasheet Constructor * @param brand * @param model * @param sensorSize */ Datasheet( const std::string& brand, const std::string& model, const double& sensorSize ): _brand(brand), _model(model), _sensorSize(sensorSize) {} bool operator==(const Datasheet& ds) const; std::string _brand; std::string _model; double _sensorSize{}; }; } // namespace sensorDB } // namespace aliceVision <|endoftext|>
<commit_before>#ifndef slic3r_ElectronicRoutingGraph_hpp_ #define slic3r_ElectronicRoutingGraph_hpp_ #include "Polygon.hpp" #include "SVG.hpp" #include <boost/graph/adjacency_list.hpp> #include <boost/graph/graph_traits.hpp> #include <boost/graph/graphviz.hpp> #include <boost/graph/astar_search.hpp> #include <boost/geometry.hpp> #include <boost/geometry/geometries/register/point.hpp> // Define translation between Slic3r::Point and boost::geometry::model::point BOOST_GEOMETRY_REGISTER_POINT_2D(Slic3r::Point, coord_t, cs::cartesian, x, y) namespace Slic3r { class ElectronicRoutingGraph; // Define boost graph types struct PointVertex { unsigned int index; // unique index 0..n Point3 point; // the actual point on the layer void* predecessor; // for recording a route boost::default_color_type color = boost::white_color; coord_t cost = INF; coord_t distance = INF; }; typedef boost::property<boost::edge_weight_t, coord_t> edge_weight_property_t; typedef boost::adjacency_list<boost::setS, boost::hash_setS, boost::undirectedS, PointVertex, edge_weight_property_t> routing_graph_t; typedef boost::graph_traits<routing_graph_t>::vertex_descriptor routing_vertex_t; typedef boost::graph_traits<routing_graph_t>::edge_descriptor routing_edge_t; typedef std::unordered_map<Point3, routing_vertex_t> point_index_t; typedef boost::geometry::index::rtree<Point, boost::geometry::index::quadratic<16> > spatial_index_t; typedef std::map<routing_edge_t, Polyline> InterlayerOverlaps; typedef std::map<coord_t, ExPolygonCollection*> ExpolygonsMap; typedef std::map<coord_t, Polylines> PolylinesMap; typedef std::map<coord_t, spatial_index_t> RtreeMap; class ElectronicRoutingGraph { public: ElectronicRoutingGraph(); bool add_vertex(const Point3& p, routing_vertex_t* vertex); bool add_vertex(const Point3& p); bool add_edge(const Line3& l, routing_edge_t* edge, const double& edge_weight_factor); bool add_polygon(const Polygon& p, const double& weight_factor, const coord_t print_z); bool nearest_point(const Point3& dest, Point3* point); bool points_in_boxrange(const Point3& dest, const coord_t range, Points* points); void append_z_position(coord_t z); bool astar_route(const Point3& start_p, const Point3& goal_p, PolylinesMap* result, const double routing_explore_weight_factor, const double routing_interlayer_factor, const double layer_overlap, const double astar_factor); void fill_svg(SVG* svg, const coord_t z, const ExPolygonCollection& s = ExPolygonCollection(), const routing_vertex_t& current_v = NULL) const; void write_svg(const std::string filename, const coord_t z) const; InterlayerOverlaps interlayer_overlaps; ExpolygonsMap infill_surfaces_map; // pointer to infill area polygons for vertex generation in A* private: routing_graph_t graph; // actual boost graph boost::property_map<routing_graph_t, Point3 PointVertex::*>::type vertex_index; // Index Vertex->Point point_index_t point_index; // Index Point->Vertex // boost RTree datastructure for fast range / nearest point access of graph points RtreeMap rtree_index; // spatial index std::vector<coord_t> z_positions; }; // Euclidean distance heuristic for routing graph template <class Graph, class CostType, class LocMap> class distance_heuristic : public boost::astar_heuristic<Graph, CostType> { public: typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex; distance_heuristic(LocMap l, Vertex goal, const double astar_factor) : m_location(l), m_goal(goal), astar_factor(astar_factor) {} CostType operator()(Vertex u) { CostType dx = m_location[m_goal].x - m_location[u].x; CostType dy = m_location[m_goal].y - m_location[u].y; CostType dz = m_location[m_goal].z - m_location[u].z; return ::sqrt(dx * dx + dy * dy + dz * dz)*astar_factor; } private: LocMap m_location; Vertex m_goal; double astar_factor; }; // Visitor that terminates when we find the goal struct found_goal {}; // exception for termination template <class BoostGraph, class Vertex, class Edge, class Graph, class Surfaces> class astar_visitor : public boost::default_astar_visitor { public: astar_visitor(Vertex goal, Graph* graph, Surfaces surfaces, const std::vector<coord_t> &z_positions, InterlayerOverlaps *interlayer_overlaps, const coord_t step_distance, Slic3r::point_index_t* point_index, const double routing_explore_weight_factor, const double routing_interlayer_factor, const double layer_overlap) : m_goal(goal), graph(graph), surfaces(surfaces), z_positions(z_positions), interlayer_overlaps(interlayer_overlaps), step_distance(step_distance), point_index(point_index), routing_explore_weight_factor(routing_explore_weight_factor), routing_interlayer_factor(routing_interlayer_factor), layer_overlap(layer_overlap), debug(true), debug_trigger(true) {} void black_target(Edge e, BoostGraph const& g) { std::cout << "REOPEN VERTEX!!!" << std::endl; std::cout << "a: " << g[boost::source(e, g)].point << std::endl; std::cout << "b: " << g[boost::target(e, g)].point << std::endl; } void examine_vertex(Vertex u, BoostGraph const& g) { typedef typename boost::graph_traits<BoostGraph>::vertex_iterator vertex_iterator; BoostGraph& g_i = const_cast<BoostGraph&>(g); coord_t print_z = g[u].point.z; if(debug || (u == m_goal)) { std::cout << "explore factor: " << this->routing_explore_weight_factor << " interlayer factor: " << this->routing_interlayer_factor << " layer_overlap: " << this->layer_overlap << std::endl; // debug output graph std::ostringstream ss; ss << "graph_visitor_"; ss << print_z; ss << ".svg"; std::string filename = ss.str(); BoundingBox bb = surfaces[print_z]->convex_hull().bounding_box(); bb.offset(scale_(5)); SVG svg_graph(filename.c_str(), bb); this->graph->fill_svg(&svg_graph, print_z, *surfaces[print_z], u); svg_graph.Close(); char ch; char d = 'd'; char c = 'c'; if(debug && debug_trigger) { std::cin >> ch; } if(ch == c) debug_trigger = false; if(ch == d) debug = false; } if(u == m_goal) { throw found_goal(); } // add vertices in 45° steps if they are inside the infill region Point vertex_p = (Point)g[u].point; if(surfaces[print_z]->contains_b(vertex_p)) { // is this point inside infill? Points pts; // generate grid candidates Point spacing(step_distance, step_distance); Point base(0, 0); pts.push_back(Point(vertex_p)); pts.back().translate(step_distance, 0); pts.back().align_to_grid(spacing, base); pts.push_back(Point(vertex_p)); pts.back().translate(step_distance, -step_distance); pts.back().align_to_grid(spacing, base); pts.push_back(Point(vertex_p)); pts.back().translate(0, -step_distance); pts.back().align_to_grid(spacing, base); pts.push_back(Point(vertex_p)); pts.back().translate(-step_distance, -step_distance); pts.back().align_to_grid(spacing, base); pts.push_back(Point(vertex_p)); pts.back().translate(-step_distance, 0); pts.back().align_to_grid(spacing, base); pts.push_back(Point(vertex_p)); pts.back().translate(-step_distance, step_distance); pts.back().align_to_grid(spacing, base); pts.push_back(Point(vertex_p)); pts.back().translate(0, step_distance); pts.back().align_to_grid(spacing, base); pts.push_back(Point(vertex_p)); pts.back().translate(step_distance, step_distance); pts.back().align_to_grid(spacing, base); // check existing points within grid distance Points near_pts; if(this->graph->points_in_boxrange(g[u].point, step_distance, &near_pts)) { pts.insert(pts.end(), near_pts.begin(), near_pts.end()); } // insert vertices and edges to graph for(auto &p : pts) { if(surfaces[print_z]->contains_b(p)) { // is this point inside infill? Vertex v; this->graph->add_vertex(Point3(p, print_z), &v); coord_t distance = vertex_p.distance_to(p) * routing_explore_weight_factor; // avoid self-loops if(u != v) { boost::add_edge(u, v, distance, g_i); } } } } // traverse back (for overlap) and check for matching points in the neighbor-layers boost::property_map<routing_graph_t, boost::edge_weight_t>::const_type EdgeWeightMap = boost::get(boost::edge_weight_t(), g); auto predmap = boost::get(&PointVertex::predecessor, g); coord_t prev_z = -1; coord_t next_z = -1; for (std::vector<coord_t>::const_iterator z = this->z_positions.begin(); z != this->z_positions.end(); ++z) { if(*z == print_z) { if(z != this->z_positions.end()) { ++z; next_z = *z; } break; } prev_z = *z; } coord_t length = 0; double upper_weight = 0; double lower_weight = 0; Point3 last_point = g[u].point; Vertex last_vertex = u; Polyline upper_trace, lower_trace; bool traverse_upper = (next_z > 0); bool traverse_lower = (prev_z >= 0); for(routing_vertex_t v = u;; v = predmap[v]) { if(predmap[v] == v || g[v].point.z != print_z) break; length += g[v].point.distance_to(last_point); if(length > (this->step_distance + this->layer_overlap)) { break; } double w = 0; if(v != u) { // only from the second point routing_edge_t edge = boost::edge(last_vertex,v,g).first; w = boost::get(EdgeWeightMap, edge); } // matching existing points???? if(traverse_upper) { try { Point3 p(((Point)g[v].point), next_z); routing_vertex_t vertex = point_index->at(p); // unordered_map::at throws an out-of-range upper_trace.append((Point)(g[vertex].point)); upper_weight += w; } catch (const std::out_of_range& oor) { traverse_upper = false; } } if(traverse_lower) { try { Point3 p(((Point)g[v].point), prev_z); routing_vertex_t vertex = point_index->at(p); // unordered_map::at throws an out-of-range lower_trace.append((Point)(g[vertex].point)); lower_weight += w; } catch (const std::out_of_range& oor) { traverse_lower = false; } } // can we generate new points inside infill??? { // } // add upper edge connections if(traverse_upper && upper_trace.length() >= this->layer_overlap) { Point3 a(upper_trace.last_point(), print_z); Point3 b_upper((Point)g[u].point, next_z); //coord_t distance = upper_trace.length() * this->routing_interlayer_factor; coord_t distance = upper_weight + scale_(this->routing_interlayer_factor); // we directly add the edge to get the length correct. (not just point-to point distance) routing_edge_t edge = boost::add_edge(point_index->at(a), point_index->at(b_upper), distance, g_i).first; (*this->interlayer_overlaps)[edge] = upper_trace; //std::cout << "upper_trace weight: " << upper_weight << " vs length: " << upper_trace.length() << " vs factor: " << scale_(this->routing_interlayer_factor) << std::endl; } // add lower edge connections if(traverse_lower && lower_trace.length() >= this->layer_overlap) { Point3 a(lower_trace.last_point(), print_z); Point3 b_lower((Point)g[u].point, prev_z); //coord_t distance = lower_trace.length() * this->routing_interlayer_factor; coord_t distance = lower_weight + scale_(this->routing_interlayer_factor); // we directly add the edge to get the length correct. (not just point-to point distance) routing_edge_t edge = boost::add_edge(point_index->at(a), point_index->at(b_lower), distance, g_i).first; (*this->interlayer_overlaps)[edge] = lower_trace; } last_point = g[v].point; last_vertex = v; } } private: Vertex m_goal; Graph* graph; Surfaces surfaces; const std::vector<coord_t> z_positions; InterlayerOverlaps *interlayer_overlaps; const coord_t step_distance; point_index_t* point_index; const double routing_explore_weight_factor; const double routing_interlayer_factor; const double layer_overlap; bool debug; bool debug_trigger; }; } #endif <commit_msg>Generate edges to close vertices outsite infill regions to better contact perimeters<commit_after>#ifndef slic3r_ElectronicRoutingGraph_hpp_ #define slic3r_ElectronicRoutingGraph_hpp_ #include "Polygon.hpp" #include "SVG.hpp" #include <boost/graph/adjacency_list.hpp> #include <boost/graph/graph_traits.hpp> #include <boost/graph/graphviz.hpp> #include <boost/graph/astar_search.hpp> #include <boost/geometry.hpp> #include <boost/geometry/geometries/register/point.hpp> // Define translation between Slic3r::Point and boost::geometry::model::point BOOST_GEOMETRY_REGISTER_POINT_2D(Slic3r::Point, coord_t, cs::cartesian, x, y) namespace Slic3r { class ElectronicRoutingGraph; // Define boost graph types struct PointVertex { unsigned int index; // unique index 0..n Point3 point; // the actual point on the layer void* predecessor; // for recording a route boost::default_color_type color = boost::white_color; coord_t cost = INF; coord_t distance = INF; }; typedef boost::property<boost::edge_weight_t, coord_t> edge_weight_property_t; typedef boost::adjacency_list<boost::setS, boost::hash_setS, boost::undirectedS, PointVertex, edge_weight_property_t> routing_graph_t; typedef boost::graph_traits<routing_graph_t>::vertex_descriptor routing_vertex_t; typedef boost::graph_traits<routing_graph_t>::edge_descriptor routing_edge_t; typedef std::unordered_map<Point3, routing_vertex_t> point_index_t; typedef boost::geometry::index::rtree<Point, boost::geometry::index::quadratic<16> > spatial_index_t; typedef std::map<routing_edge_t, Polyline> InterlayerOverlaps; typedef std::map<coord_t, ExPolygonCollection*> ExpolygonsMap; typedef std::map<coord_t, Polylines> PolylinesMap; typedef std::map<coord_t, spatial_index_t> RtreeMap; class ElectronicRoutingGraph { public: ElectronicRoutingGraph(); bool add_vertex(const Point3& p, routing_vertex_t* vertex); bool add_vertex(const Point3& p); bool add_edge(const Line3& l, routing_edge_t* edge, const double& edge_weight_factor); bool add_polygon(const Polygon& p, const double& weight_factor, const coord_t print_z); bool nearest_point(const Point3& dest, Point3* point); bool points_in_boxrange(const Point3& dest, const coord_t range, Points* points); void append_z_position(coord_t z); bool astar_route(const Point3& start_p, const Point3& goal_p, PolylinesMap* result, const double routing_explore_weight_factor, const double routing_interlayer_factor, const double layer_overlap, const double astar_factor); void fill_svg(SVG* svg, const coord_t z, const ExPolygonCollection& s = ExPolygonCollection(), const routing_vertex_t& current_v = NULL) const; void write_svg(const std::string filename, const coord_t z) const; InterlayerOverlaps interlayer_overlaps; ExpolygonsMap infill_surfaces_map; // pointer to infill area polygons for vertex generation in A* private: routing_graph_t graph; // actual boost graph boost::property_map<routing_graph_t, Point3 PointVertex::*>::type vertex_index; // Index Vertex->Point point_index_t point_index; // Index Point->Vertex // boost RTree datastructure for fast range / nearest point access of graph points RtreeMap rtree_index; // spatial index std::vector<coord_t> z_positions; }; // Euclidean distance heuristic for routing graph template <class Graph, class CostType, class LocMap> class distance_heuristic : public boost::astar_heuristic<Graph, CostType> { public: typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex; distance_heuristic(LocMap l, Vertex goal, const double astar_factor) : m_location(l), m_goal(goal), astar_factor(astar_factor) {} CostType operator()(Vertex u) { CostType dx = m_location[m_goal].x - m_location[u].x; CostType dy = m_location[m_goal].y - m_location[u].y; CostType dz = m_location[m_goal].z - m_location[u].z; return ::sqrt(dx * dx + dy * dy + dz * dz)*astar_factor; } private: LocMap m_location; Vertex m_goal; double astar_factor; }; // Visitor that terminates when we find the goal struct found_goal {}; // exception for termination template <class BoostGraph, class Vertex, class Edge, class Graph, class Surfaces> class astar_visitor : public boost::default_astar_visitor { public: astar_visitor(Vertex goal, Graph* graph, Surfaces surfaces, const std::vector<coord_t> &z_positions, InterlayerOverlaps *interlayer_overlaps, const coord_t step_distance, Slic3r::point_index_t* point_index, const double routing_explore_weight_factor, const double routing_interlayer_factor, const double layer_overlap) : m_goal(goal), graph(graph), surfaces(surfaces), z_positions(z_positions), interlayer_overlaps(interlayer_overlaps), step_distance(step_distance), point_index(point_index), routing_explore_weight_factor(routing_explore_weight_factor), routing_interlayer_factor(routing_interlayer_factor), layer_overlap(layer_overlap), debug(true), debug_trigger(true) {} void black_target(Edge e, BoostGraph const& g) { std::cout << "REOPEN VERTEX!!!" << std::endl; std::cout << "a: " << g[boost::source(e, g)].point << std::endl; std::cout << "b: " << g[boost::target(e, g)].point << std::endl; } void examine_vertex(Vertex u, BoostGraph const& g) { typedef typename boost::graph_traits<BoostGraph>::vertex_iterator vertex_iterator; BoostGraph& g_i = const_cast<BoostGraph&>(g); coord_t print_z = g[u].point.z; if(debug || (u == m_goal)) { std::cout << "explore factor: " << this->routing_explore_weight_factor << " interlayer factor: " << this->routing_interlayer_factor << " layer_overlap: " << this->layer_overlap << std::endl; // debug output graph std::ostringstream ss; ss << "graph_visitor_"; ss << print_z; ss << ".svg"; std::string filename = ss.str(); BoundingBox bb = surfaces[print_z]->convex_hull().bounding_box(); bb.offset(scale_(5)); SVG svg_graph(filename.c_str(), bb); this->graph->fill_svg(&svg_graph, print_z, *surfaces[print_z], u); svg_graph.Close(); char ch; char d = 'd'; char c = 'c'; if(debug && debug_trigger) { std::cin >> ch; } if(ch == c) debug_trigger = false; if(ch == d) debug = false; } if(u == m_goal) { throw found_goal(); } // add vertices in 45° steps if they are inside the infill region Point vertex_p = (Point)g[u].point; Points pts; if(surfaces[print_z]->contains_b(vertex_p)) { // is this point inside infill? // generate grid candidates Point spacing(step_distance, step_distance); Point base(0, 0); pts.push_back(Point(vertex_p)); pts.back().translate(step_distance, 0); pts.back().align_to_grid(spacing, base); if(!surfaces[print_z]->contains_b(pts.back())) pts.pop_back(); pts.push_back(Point(vertex_p)); pts.back().translate(step_distance, -step_distance); pts.back().align_to_grid(spacing, base); if(!surfaces[print_z]->contains_b(pts.back())) pts.pop_back(); pts.push_back(Point(vertex_p)); pts.back().translate(0, -step_distance); pts.back().align_to_grid(spacing, base); if(!surfaces[print_z]->contains_b(pts.back())) pts.pop_back(); pts.push_back(Point(vertex_p)); pts.back().translate(-step_distance, -step_distance); pts.back().align_to_grid(spacing, base); if(!surfaces[print_z]->contains_b(pts.back())) pts.pop_back(); pts.push_back(Point(vertex_p)); pts.back().translate(-step_distance, 0); pts.back().align_to_grid(spacing, base); if(!surfaces[print_z]->contains_b(pts.back())) pts.pop_back(); pts.push_back(Point(vertex_p)); pts.back().translate(-step_distance, step_distance); pts.back().align_to_grid(spacing, base); if(!surfaces[print_z]->contains_b(pts.back())) pts.pop_back(); pts.push_back(Point(vertex_p)); pts.back().translate(0, step_distance); pts.back().align_to_grid(spacing, base); if(!surfaces[print_z]->contains_b(pts.back())) pts.pop_back(); pts.push_back(Point(vertex_p)); pts.back().translate(step_distance, step_distance); pts.back().align_to_grid(spacing, base); if(!surfaces[print_z]->contains_b(pts.back())) pts.pop_back(); } // check existing points within grid distance Points near_pts; if(this->graph->points_in_boxrange(g[u].point, step_distance, &near_pts)) { pts.insert(pts.end(), near_pts.begin(), near_pts.end()); } // insert vertices and edges to graph for(auto &p : pts) { //if(surfaces[print_z]->contains_b(p)) { // is this point inside infill? Vertex v; this->graph->add_vertex(Point3(p, print_z), &v); coord_t distance = vertex_p.distance_to(p) * routing_explore_weight_factor; // avoid self-loops if(u != v) { boost::add_edge(u, v, distance, g_i); } //} } // traverse back (for overlap) and check for matching points in the neighbor-layers boost::property_map<routing_graph_t, boost::edge_weight_t>::const_type EdgeWeightMap = boost::get(boost::edge_weight_t(), g); auto predmap = boost::get(&PointVertex::predecessor, g); coord_t prev_z = -1; coord_t next_z = -1; for (std::vector<coord_t>::const_iterator z = this->z_positions.begin(); z != this->z_positions.end(); ++z) { if(*z == print_z) { if(z != this->z_positions.end()) { ++z; next_z = *z; } break; } prev_z = *z; } coord_t length = 0; double upper_weight = 0; double lower_weight = 0; Point3 last_point = g[u].point; Vertex last_vertex = u; Polyline upper_trace, lower_trace; bool traverse_upper = (next_z > 0); bool traverse_lower = (prev_z >= 0); for(routing_vertex_t v = u;; v = predmap[v]) { if(predmap[v] == v || g[v].point.z != print_z) break; length += g[v].point.distance_to(last_point); if(length > (this->step_distance + this->layer_overlap)) { break; } double w = 0; if(v != u) { // only from the second point routing_edge_t edge = boost::edge(last_vertex,v,g).first; w = boost::get(EdgeWeightMap, edge); } // matching existing points???? if(traverse_upper) { try { Point3 p(((Point)g[v].point), next_z); routing_vertex_t vertex = point_index->at(p); // unordered_map::at throws an out-of-range upper_trace.append((Point)(g[vertex].point)); upper_weight += w; } catch (const std::out_of_range& oor) { traverse_upper = false; } } if(traverse_lower) { try { Point3 p(((Point)g[v].point), prev_z); routing_vertex_t vertex = point_index->at(p); // unordered_map::at throws an out-of-range lower_trace.append((Point)(g[vertex].point)); lower_weight += w; } catch (const std::out_of_range& oor) { traverse_lower = false; } } // can we generate new points inside infill??? { // } // add upper edge connections if(traverse_upper && upper_trace.length() >= this->layer_overlap) { Point3 a(upper_trace.last_point(), print_z); Point3 b_upper((Point)g[u].point, next_z); //coord_t distance = upper_trace.length() * this->routing_interlayer_factor; coord_t distance = upper_weight + scale_(this->routing_interlayer_factor); // we directly add the edge to get the length correct. (not just point-to point distance) routing_edge_t edge = boost::add_edge(point_index->at(a), point_index->at(b_upper), distance, g_i).first; (*this->interlayer_overlaps)[edge] = upper_trace; //std::cout << "upper_trace weight: " << upper_weight << " vs length: " << upper_trace.length() << " vs factor: " << scale_(this->routing_interlayer_factor) << std::endl; } // add lower edge connections if(traverse_lower && lower_trace.length() >= this->layer_overlap) { Point3 a(lower_trace.last_point(), print_z); Point3 b_lower((Point)g[u].point, prev_z); //coord_t distance = lower_trace.length() * this->routing_interlayer_factor; coord_t distance = lower_weight + scale_(this->routing_interlayer_factor); // we directly add the edge to get the length correct. (not just point-to point distance) routing_edge_t edge = boost::add_edge(point_index->at(a), point_index->at(b_lower), distance, g_i).first; (*this->interlayer_overlaps)[edge] = lower_trace; } last_point = g[v].point; last_vertex = v; } } private: Vertex m_goal; Graph* graph; Surfaces surfaces; const std::vector<coord_t> z_positions; InterlayerOverlaps *interlayer_overlaps; const coord_t step_distance; point_index_t* point_index; const double routing_explore_weight_factor; const double routing_interlayer_factor; const double layer_overlap; bool debug; bool debug_trigger; }; } #endif <|endoftext|>
<commit_before>//===--- Errors.cpp - Error reporting utilities ---------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Utilities for reporting errors to stderr, system console, and crash logs. // //===----------------------------------------------------------------------===// #if defined(__CYGWIN__) || defined(__ANDROID__) || defined(_MSC_VER) # define SWIFT_SUPPORTS_BACKTRACE_REPORTING 0 #else # define SWIFT_SUPPORTS_BACKTRACE_REPORTING 1 #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #if defined(_MSC_VER) #include <io.h> #else #include <unistd.h> #endif #include <stdarg.h> #include "ImageInspection.h" #include "swift/Runtime/Debug.h" #include "swift/Runtime/Mutex.h" #include "swift/Basic/Demangle.h" #include "swift/Basic/LLVM.h" #include "llvm/ADT/StringRef.h" #if !defined(_MSC_VER) #include <cxxabi.h> #endif #if SWIFT_SUPPORTS_BACKTRACE_REPORTING // execinfo.h is not available on Android. Checks in this file ensure that // fatalError behaves as expected, but without stack traces. #include <execinfo.h> #endif #ifdef __APPLE__ #include <asl.h> #endif namespace FatalErrorFlags { enum: uint32_t { ReportBacktrace = 1 << 0 }; } // end namespace FatalErrorFlags using namespace swift; #if SWIFT_SUPPORTS_BACKTRACE_REPORTING static bool getSymbolNameAddr(llvm::StringRef libraryName, SymbolInfo syminfo, std::string &symbolName, uintptr_t &addrOut) { // If we failed to find a symbol and thus dlinfo->dli_sname is nullptr, we // need to use the hex address. bool hasUnavailableAddress = syminfo.symbolName == nullptr; if (hasUnavailableAddress) { return false; } // Ok, now we know that we have some sort of "real" name. Set the outAddr. addrOut = uintptr_t(syminfo.symbolAddress); // First lets try to demangle using cxxabi. If this fails, we will try to // demangle with swift. We are taking advantage of __cxa_demangle actually // providing failure status instead of just returning the original string like // swift demangle. int status; char *demangled = abi::__cxa_demangle(syminfo.symbolName, 0, 0, &status); if (status == 0) { assert(demangled != nullptr && "If __cxa_demangle succeeds, demangled " "should never be nullptr"); symbolName += demangled; free(demangled); return true; } assert(demangled == nullptr && "If __cxa_demangle fails, demangled should " "be a nullptr"); // Otherwise, try to demangle with swift. If swift fails to demangle, it will // just pass through the original output. symbolName = demangleSymbolAsString( syminfo.symbolName, strlen(syminfo.symbolName), Demangle::DemangleOptions::SimplifiedUIDemangleOptions()); return true; } /// This function dumps one line of a stack trace. It is assumed that \p address /// is the address of the stack frame at index \p index. static void dumpStackTraceEntry(unsigned index, void *framePC) { SymbolInfo syminfo; // 0 is failure for lookupSymbol if (0 == lookupSymbol(framePC, &syminfo)) { return; } // If lookupSymbol succeeded then fileName is non-null. Thus, we find the // library name here. StringRef libraryName = StringRef(syminfo.fileName).rsplit('/').second; // Next we get the symbol name that we are going to use in our backtrace. std::string symbolName; // We initialize symbolAddr to framePC so that if we succeed in finding the // symbol, we get the offset in the function and if we fail to find the symbol // we just get HexAddr + 0. uintptr_t symbolAddr = uintptr_t(framePC); bool foundSymbol = getSymbolNameAddr(libraryName, syminfo, symbolName, symbolAddr); // We do not use %p here for our pointers since the format is implementation // defined. This makes it logically impossible to check the output. Forcing // hexadecimal solves this issue. // If the symbol is not available, we print out <unavailable> + offset // from the base address of where the image containing framePC is mapped. // This gives enough info to reconstruct identical debugging target after // this process terminates. if (foundSymbol) { static const char *backtraceEntryFormat = "%-4u %-34s 0x%0.16lx %s + %td\n"; fprintf(stderr, backtraceEntryFormat, index, libraryName.data(), symbolAddr, symbolName.c_str(), ptrdiff_t(uintptr_t(framePC) - symbolAddr)); } else { static const char *backtraceEntryFormat = "%-4u %-34s 0x%0.16lx " "<unavailable> + %td\n"; fprintf(stderr, backtraceEntryFormat, index, libraryName.data(), uintptr_t(framePC), ptrdiff_t(uintptr_t(framePC) - uintptr_t(syminfo.baseAddress))); } } #endif #ifdef SWIFT_HAVE_CRASHREPORTERCLIENT #include <malloc/malloc.h> // Instead of linking to CrashReporterClient.a (because it complicates the // build system), define the only symbol from that static archive ourselves. // // The layout of this struct is CrashReporter ABI, so there are no ABI concerns // here. extern "C" { CRASH_REPORTER_CLIENT_HIDDEN struct crashreporter_annotations_t gCRAnnotations __attribute__((__section__("__DATA," CRASHREPORTER_ANNOTATIONS_SECTION))) = { CRASHREPORTER_ANNOTATIONS_VERSION, 0, 0, 0, 0, 0, 0, 0}; } // Report a message to any forthcoming crash log. static void reportOnCrash(uint32_t flags, const char *message) { // We must use an "unsafe" mutex in this pathway since the normal "safe" // mutex calls fatalError when an error is detected and fatalError ends up // calling us. In other words we could get infinite recursion if the // mutex errors. static swift::StaticUnsafeMutex crashlogLock; crashlogLock.lock(); char *oldMessage = (char *)CRGetCrashLogMessage(); char *newMessage; if (oldMessage) { asprintf(&newMessage, "%s%s", oldMessage, message); if (malloc_size(oldMessage)) free(oldMessage); } else { newMessage = strdup(message); } CRSetCrashLogMessage(newMessage); crashlogLock.unlock(); } #else static void reportOnCrash(uint32_t flags, const char *message) { // empty } #endif // Report a message to system console and stderr. static void reportNow(uint32_t flags, const char *message) { #if defined(_MSC_VER) #define STDERR_FILENO 2 _write(STDERR_FILENO, message, strlen(message)); #else write(STDERR_FILENO, message, strlen(message)); #endif #ifdef __APPLE__ asl_log(NULL, NULL, ASL_LEVEL_ERR, "%s", message); #endif #if SWIFT_SUPPORTS_BACKTRACE_REPORTING if (flags & FatalErrorFlags::ReportBacktrace) { fputs("Current stack trace:\n", stderr); constexpr unsigned maxSupportedStackDepth = 128; void *addrs[maxSupportedStackDepth]; int symbolCount = backtrace(addrs, maxSupportedStackDepth); for (int i = 0; i < symbolCount; ++i) { dumpStackTraceEntry(i, addrs[i]); } } #endif } /// Report a fatal error to system console, stderr, and crash logs. /// Does not crash by itself. void swift::swift_reportError(uint32_t flags, const char *message) { reportNow(flags, message); reportOnCrash(flags, message); } static int swift_vasprintf(char **strp, const char *fmt, va_list ap) { #if defined(_MSC_VER) int len = _vscprintf(fmt, ap); if (len < 0) return -1; char *buffer = reinterpret_cast<char *>(malloc(len + 1)); if (!buffer) return -1; int result = vsprintf(buffer, fmt, ap); if (result < 0) { free(buffer); return -1; } *strp = buffer; return result; #else return vasprintf(strp, fmt, ap); #endif } // Report a fatal error to system console, stderr, and crash logs, then abort. LLVM_ATTRIBUTE_NORETURN void swift::fatalError(uint32_t flags, const char *format, ...) { va_list args; va_start(args, format); char *log; swift_vasprintf(&log, format, args); swift_reportError(flags, log); abort(); } // Crash when a deleted method is called by accident. SWIFT_RUNTIME_EXPORT LLVM_ATTRIBUTE_NORETURN extern "C" void swift_deletedMethodError() { swift::fatalError(/* flags = */ 0, "fatal error: call of deleted method\n"); } // Define symbols to satisfy LLVM's Config/abi-breaking.h checks. // The Swift runtime uses some header-only content from LLVM's ADT classes, // which pulls in references to one of these symbols. Those symbols are // defined in LLVM's libSupport, but the Swift runtime does not link with // that library. Since the ABI checks are not relevant for the runtime, // define both symbols, essentially disabling the checks. #ifndef _MSC_VER namespace llvm { __attribute__((weak, visibility ("hidden"))) int EnableABIBreakingChecks; __attribute__((weak, visibility ("hidden"))) int DisableABIBreakingChecks; } // end namespace llvm #endif <commit_msg>Revert "Try again to find a good way to deal with LLVM's abi-breaking.h checks."<commit_after>//===--- Errors.cpp - Error reporting utilities ---------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Utilities for reporting errors to stderr, system console, and crash logs. // //===----------------------------------------------------------------------===// #if defined(__CYGWIN__) || defined(__ANDROID__) || defined(_MSC_VER) # define SWIFT_SUPPORTS_BACKTRACE_REPORTING 0 #else # define SWIFT_SUPPORTS_BACKTRACE_REPORTING 1 #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #if defined(_MSC_VER) #include <io.h> #else #include <unistd.h> #endif #include <stdarg.h> #include "ImageInspection.h" #include "swift/Runtime/Debug.h" #include "swift/Runtime/Mutex.h" #include "swift/Basic/Demangle.h" #include "swift/Basic/LLVM.h" #include "llvm/ADT/StringRef.h" #if !defined(_MSC_VER) #include <cxxabi.h> #endif #if SWIFT_SUPPORTS_BACKTRACE_REPORTING // execinfo.h is not available on Android. Checks in this file ensure that // fatalError behaves as expected, but without stack traces. #include <execinfo.h> #endif #ifdef __APPLE__ #include <asl.h> #endif namespace FatalErrorFlags { enum: uint32_t { ReportBacktrace = 1 << 0 }; } // end namespace FatalErrorFlags using namespace swift; #if SWIFT_SUPPORTS_BACKTRACE_REPORTING static bool getSymbolNameAddr(llvm::StringRef libraryName, SymbolInfo syminfo, std::string &symbolName, uintptr_t &addrOut) { // If we failed to find a symbol and thus dlinfo->dli_sname is nullptr, we // need to use the hex address. bool hasUnavailableAddress = syminfo.symbolName == nullptr; if (hasUnavailableAddress) { return false; } // Ok, now we know that we have some sort of "real" name. Set the outAddr. addrOut = uintptr_t(syminfo.symbolAddress); // First lets try to demangle using cxxabi. If this fails, we will try to // demangle with swift. We are taking advantage of __cxa_demangle actually // providing failure status instead of just returning the original string like // swift demangle. int status; char *demangled = abi::__cxa_demangle(syminfo.symbolName, 0, 0, &status); if (status == 0) { assert(demangled != nullptr && "If __cxa_demangle succeeds, demangled " "should never be nullptr"); symbolName += demangled; free(demangled); return true; } assert(demangled == nullptr && "If __cxa_demangle fails, demangled should " "be a nullptr"); // Otherwise, try to demangle with swift. If swift fails to demangle, it will // just pass through the original output. symbolName = demangleSymbolAsString( syminfo.symbolName, strlen(syminfo.symbolName), Demangle::DemangleOptions::SimplifiedUIDemangleOptions()); return true; } /// This function dumps one line of a stack trace. It is assumed that \p address /// is the address of the stack frame at index \p index. static void dumpStackTraceEntry(unsigned index, void *framePC) { SymbolInfo syminfo; // 0 is failure for lookupSymbol if (0 == lookupSymbol(framePC, &syminfo)) { return; } // If lookupSymbol succeeded then fileName is non-null. Thus, we find the // library name here. StringRef libraryName = StringRef(syminfo.fileName).rsplit('/').second; // Next we get the symbol name that we are going to use in our backtrace. std::string symbolName; // We initialize symbolAddr to framePC so that if we succeed in finding the // symbol, we get the offset in the function and if we fail to find the symbol // we just get HexAddr + 0. uintptr_t symbolAddr = uintptr_t(framePC); bool foundSymbol = getSymbolNameAddr(libraryName, syminfo, symbolName, symbolAddr); // We do not use %p here for our pointers since the format is implementation // defined. This makes it logically impossible to check the output. Forcing // hexadecimal solves this issue. // If the symbol is not available, we print out <unavailable> + offset // from the base address of where the image containing framePC is mapped. // This gives enough info to reconstruct identical debugging target after // this process terminates. if (foundSymbol) { static const char *backtraceEntryFormat = "%-4u %-34s 0x%0.16lx %s + %td\n"; fprintf(stderr, backtraceEntryFormat, index, libraryName.data(), symbolAddr, symbolName.c_str(), ptrdiff_t(uintptr_t(framePC) - symbolAddr)); } else { static const char *backtraceEntryFormat = "%-4u %-34s 0x%0.16lx " "<unavailable> + %td\n"; fprintf(stderr, backtraceEntryFormat, index, libraryName.data(), uintptr_t(framePC), ptrdiff_t(uintptr_t(framePC) - uintptr_t(syminfo.baseAddress))); } } #endif #ifdef SWIFT_HAVE_CRASHREPORTERCLIENT #include <malloc/malloc.h> // Instead of linking to CrashReporterClient.a (because it complicates the // build system), define the only symbol from that static archive ourselves. // // The layout of this struct is CrashReporter ABI, so there are no ABI concerns // here. extern "C" { CRASH_REPORTER_CLIENT_HIDDEN struct crashreporter_annotations_t gCRAnnotations __attribute__((__section__("__DATA," CRASHREPORTER_ANNOTATIONS_SECTION))) = { CRASHREPORTER_ANNOTATIONS_VERSION, 0, 0, 0, 0, 0, 0, 0}; } // Report a message to any forthcoming crash log. static void reportOnCrash(uint32_t flags, const char *message) { // We must use an "unsafe" mutex in this pathway since the normal "safe" // mutex calls fatalError when an error is detected and fatalError ends up // calling us. In other words we could get infinite recursion if the // mutex errors. static swift::StaticUnsafeMutex crashlogLock; crashlogLock.lock(); char *oldMessage = (char *)CRGetCrashLogMessage(); char *newMessage; if (oldMessage) { asprintf(&newMessage, "%s%s", oldMessage, message); if (malloc_size(oldMessage)) free(oldMessage); } else { newMessage = strdup(message); } CRSetCrashLogMessage(newMessage); crashlogLock.unlock(); } #else static void reportOnCrash(uint32_t flags, const char *message) { // empty } #endif // Report a message to system console and stderr. static void reportNow(uint32_t flags, const char *message) { #if defined(_MSC_VER) #define STDERR_FILENO 2 _write(STDERR_FILENO, message, strlen(message)); #else write(STDERR_FILENO, message, strlen(message)); #endif #ifdef __APPLE__ asl_log(NULL, NULL, ASL_LEVEL_ERR, "%s", message); #endif #if SWIFT_SUPPORTS_BACKTRACE_REPORTING if (flags & FatalErrorFlags::ReportBacktrace) { fputs("Current stack trace:\n", stderr); constexpr unsigned maxSupportedStackDepth = 128; void *addrs[maxSupportedStackDepth]; int symbolCount = backtrace(addrs, maxSupportedStackDepth); for (int i = 0; i < symbolCount; ++i) { dumpStackTraceEntry(i, addrs[i]); } } #endif } /// Report a fatal error to system console, stderr, and crash logs. /// Does not crash by itself. void swift::swift_reportError(uint32_t flags, const char *message) { reportNow(flags, message); reportOnCrash(flags, message); } static int swift_vasprintf(char **strp, const char *fmt, va_list ap) { #if defined(_MSC_VER) int len = _vscprintf(fmt, ap); if (len < 0) return -1; char *buffer = reinterpret_cast<char *>(malloc(len + 1)); if (!buffer) return -1; int result = vsprintf(buffer, fmt, ap); if (result < 0) { free(buffer); return -1; } *strp = buffer; return result; #else return vasprintf(strp, fmt, ap); #endif } // Report a fatal error to system console, stderr, and crash logs, then abort. LLVM_ATTRIBUTE_NORETURN void swift::fatalError(uint32_t flags, const char *format, ...) { va_list args; va_start(args, format); char *log; swift_vasprintf(&log, format, args); swift_reportError(flags, log); abort(); } // Crash when a deleted method is called by accident. SWIFT_RUNTIME_EXPORT LLVM_ATTRIBUTE_NORETURN extern "C" void swift_deletedMethodError() { swift::fatalError(/* flags = */ 0, "fatal error: call of deleted method\n"); } <|endoftext|>
<commit_before>#include <cstdint> #include <iostream> typedef std::uint64_t u64; u64 mulmod(u64 a, u64 b, u64 m) { u64 r = 0; u64 s = 0; while (b > 0) { s = ((m - r) > a) ? r + a : r + a - m; r = (b & 1) * s + (1 - (b & 1)) * r; b >>= 1; a = ((m - a) > a) ? a + a : a + a - m; } return r; } u64 powmod(u64 a, u64 e, u64 m) { u64 r = 1; while (e > 0) { r = (e & 1) * mulmod(r, a, m) + (1 - (e & 1)) * r; e >>= 1; a = mulmod(a, a, m); } return r; } const u64 prime = 12200160415121876909; const u64 sqrt5 = 833731445503647576; int main() { u64 a, b; std::cin >> a; std::cin >> b; std::cout << mulmod(a, b, prime); return 0; } <commit_msg>fibonacci function done<commit_after>#include <cstdint> #include <iostream> typedef std::uint64_t u64; u64 mulmod(u64 a, u64 b, u64 m) { u64 r = 0; u64 s = 0; while (b > 0) { s = ((m - r) > a) ? r + a : r + a - m; r = (b & 1) * s + (1 - (b & 1)) * r; b >>= 1; a = ((m - a) > a) ? a + a : a + a - m; } return r; } u64 powmod(u64 a, u64 e, u64 m) { u64 r = 1; while (e > 0) { r = (e & 1) * mulmod(r, a, m) + (1 - (e & 1)) * r; e >>= 1; a = mulmod(a, a, m); } return r; } u64 fib(u64 n) { const u64 prime = 12200160415121876909; const u64 sqrt5 = 833731445503647576; const u64 sqrt5inv = 2606778372125104897; n %= prime; // It overflows long before this happens, has no real use ... u64 a = powmod(1 + sqrt5, n, prime); u64 b = powmod(prime + 1 - sqrt5, n, prime); u64 invpow2 = powmod(2, prime - 1 - n, prime); u64 phin_minus_psin = (a > b) ? a - b : (prime - b) + a; u64 factor = mulmod(sqrt5inv, invpow2, prime); return mulmod(phin_minus_psin, factor, prime); } int main() { u64 n; std::cin >> n; std::cout << fib(n); return 0; } <|endoftext|>
<commit_before>#include "hash_impl.h" #include "cryptopp_impl.h" namespace multihash { hash::impl::impl(hash_code code) : hash_code_(code) { init(); } void hash::impl::init() { switch (hash_code_) { case hash_code::SHA1: case hash_code::SHA2_256: case hash_code::SHA2_512: algorithm_ = std::make_unique<cryptopp_impl>(hash_code_); break; case hash_code::SHA3: case hash_code::IDENTITY: std::string msg = "No hash function for code " + std::to_string(static_cast<char>(hash_code_)); throw std::out_of_range(msg); } } bool hash::operator==(const hash& rhs) const { return code() == rhs.code(); } multihash hash::impl::operator()(std::istream& input) { if (!input.good()) { throw std::invalid_argument("hash input is not good"); } init(); auto buffer = std::string(algorithm_->block_size(), ' '); auto begin = buffer.begin(); auto end = buffer.end(); while (!input.eof()) { input.read(const_cast<char*>(buffer.data()), buffer.size()); if (!input.eof()) { // filled the buffer so update the hash algorithm_->update(buffer); } } // final update to hash with partially filled vector auto chars_read(input.gcount()); std::advance(begin, chars_read); buffer.erase(begin, end); algorithm_->update(buffer); return digest(); } multihash hash::impl::operator()(std::string_view input) { init(); auto block_size = algorithm_->block_size(); auto begin = input.begin(); auto size = std::min(input.size(), block_size); auto remaining = input.size(); auto end = begin; while (size > 0) { std::advance(end, size); auto buffer = std::string_view(begin, size); algorithm_->update(buffer); begin = end; remaining -= size; size = std::min(remaining, block_size); } return digest(); } multihash hash::impl::digest() { auto digest = algorithm_->digest(); auto view = std::string_view(digest.data(), digest.size()); return multihash(hash_code_, view); } } // namespace multihash <commit_msg>Use VS-compatible string view constructor<commit_after>#include "hash_impl.h" #include "cryptopp_impl.h" namespace multihash { hash::impl::impl(hash_code code) : hash_code_(code) { init(); } void hash::impl::init() { switch (hash_code_) { case hash_code::SHA1: case hash_code::SHA2_256: case hash_code::SHA2_512: algorithm_ = std::make_unique<cryptopp_impl>(hash_code_); break; case hash_code::SHA3: case hash_code::IDENTITY: std::string msg = "No hash function for code " + std::to_string(static_cast<char>(hash_code_)); throw std::out_of_range(msg); } } bool hash::operator==(const hash& rhs) const { return code() == rhs.code(); } multihash hash::impl::operator()(std::istream& input) { if (!input.good()) { throw std::invalid_argument("hash input is not good"); } init(); auto buffer = std::string(algorithm_->block_size(), ' '); auto begin = buffer.begin(); auto end = buffer.end(); while (!input.eof()) { input.read(const_cast<char*>(buffer.data()), buffer.size()); if (!input.eof()) { // filled the buffer so update the hash algorithm_->update(buffer); } } // final update to hash with partially filled vector auto chars_read(input.gcount()); std::advance(begin, chars_read); buffer.erase(begin, end); algorithm_->update(buffer); return digest(); } multihash hash::impl::operator()(std::string_view input) { init(); auto block_size = algorithm_->block_size(); auto begin = input.begin(); auto size = std::min(input.size(), block_size); auto remaining = input.size(); auto end = begin; while (size > 0) { std::advance(end, size); auto buffer = std::string_view(input.data(), size); algorithm_->update(buffer); begin = end; remaining -= size; size = std::min(remaining, block_size); } return digest(); } multihash hash::impl::digest() { auto digest = algorithm_->digest(); auto view = std::string_view(digest.data(), digest.size()); return multihash(hash_code_, view); } } // namespace multihash <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <cstring> #include <vector> #include <queue> #include <map> #include <cassert> #include "node.hpp" using namespace std; typedef unsigned char uchar; // Made this struct so we could pair a character with it's frequency // and define proper operators so our implementation is simplified. struct Cpair{ char first; int second; Cpair(char c, int v): first(c), second(v){} bool operator < ( const Cpair& b ) const { return second < b.second; } bool operator > ( const Cpair& b ) const { return second > b.second; } }; // This function defines operator for printing our data ostream& operator<<(std::ostream &os, const Cpair& m) { return os << "char: " << m.first << " frequency: " << m.second ; } // Takes two characters bit representation and cast it // to an unsigned short: // i.e: uchar bits[2] = {168,2} becomes 680 // i.e: uchar bits[2] = {0,2} becomes 520 // i.e: uchar bits[2] = {168,0} becomes 168 // We simply interpret the array of two chars as // if they were a short (which, bitwise, may be same as // unsigned short) unsigned short bit2short( uchar* bytes ){ return (unsigned short) (((short)bytes[1]) << 8) | bytes[0]; } // Gets the tree and map each char to its string binary representation void mapChar(map<uchar,string>& m, Node<Cpair>* root, uchar c, string key = ""){ if (root->data.first == c){ m[c] = key; return ; } else{ if (root->left != NULL) mapChar(m, root->left, c, key+'0'); if (root->right!= NULL) mapChar(m, root->right, c, key+'1'); } } // Gets a string of ones and zeroes and returns a // byte (a char)) uchar byte2char ( const string& byte ){ char aux = 0; for (int i = 7 ; i >= 0 ; --i){ aux = aux | ((byte[7-i]-'0') << i); } return aux; } // Does the same thing as previous function but the // other way around (takes byte and returns string) string char2byte (uchar c){ string aux; for ( int i = 7 ; i >= 0 ; --i ){ aux += ((1 << i) & c) ? '1' : '0'; } return aux; } // With the Huffman's tree's root and vector of pairs, we can generate the mappings // of each character to its Huffman's code. That's what this function does. map<uchar, string> getMap (Node<Cpair>* root, const vector<Cpair>& f){ map<uchar, string> code; for (auto v : f){ mapChar(code, root, v.first); } return code; } // Gets the char => binary string mapping and text compressed string // (from only text code info on, without tree building protocol part) // and returns the unzipped text. string unZip( const string& bits, const map<uchar,string>& code){ string aux; string unzip; for (size_t i = 0 ; i < bits.size() ; ++i){ aux += bits[i]; for (auto it = code.begin() ; it!= code.end() ; ++it){ if (it->second == aux){ unzip += it->first; aux.clear(); break; } } } return unzip; } // Accordingly to our protocol, we use this function to get a // frequency list out of the bit string representation of the // zipped file. vector<Cpair> parseFrequencies(const string& bits){ vector<Cpair> aux; int n = (int) bits[0]; uchar buf[2]; for (int i = 2; i < 3*n+2; i+=3){ buf[0] = bits[i+1]; buf[1] = bits[i+2]; aux.push_back(Cpair(bits[i], bit2short(buf))); } return aux; } // Function for generating the tree, return it's node solely. // And the node is all we need to know everything about the tree. Node<Cpair>* buildTree (const vector<Cpair>& list){ Node<Cpair>* root; priority_queue <Node<Cpair>, vector<Node<Cpair> >, greater<Node<Cpair>> > f_list; for (auto v : list){ f_list.push(Node<Cpair>(v)); } while (f_list.size() != 1){ auto first = f_list.top(); f_list.pop(); auto second = f_list.top(); f_list.pop(); Cpair r('*', first.data.second+second.data.second); root = new Node<Cpair> (r); root->left = new Node<Cpair> (first); root->right = new Node<Cpair> (second); f_list.push(*root); } return root; } // For debugging purposes, this function takes a tree root and // prints it in preorder. void printTree(const Node<Cpair>* r){ cout << r->data << endl; if (r->left != NULL) printTree(r->left); if (r->right != NULL) printTree(r->right); } // Simply cuts off the whole bit string representation of zipped file // the part related to the text. string getTextBits( const string& bytes ){ int n = (int) bytes[0]; unsigned int rem = (int) bytes[1]; string aux = bytes.substr(3*n+2); string txt; for (size_t i = 0 ; i < aux.size(); ++i){ txt += char2byte(aux[i]); } return txt.substr(0,txt.size()-rem); } int main (int argc, char* argv[]){ if (argc == 1){ cerr << "No argument given. \n" << "Usage: \n" << "For help, run ./topzip.out -h \n" << "Aborting. \n"; exit(-1); } bool zip = true; for (int i = 1 ; i < argc ; ++i){ if (!strcmp(argv[i], "-h") or !strcmp(argv[i], "--help")){ cout << "Need help ? Here is how to use it:"<< endl; cout << "\t~ ./topzip.out <flags> <path-to-text>\n"<< endl; cout << "flags = -u or --unzip for unzipping mode"<< endl; cout << "flags = -h or --help for help"<< endl; return 0; } if (!strcmp(argv[i], "-u") or !strcmp(argv[i], "--unzip")){ zip = false; } } string file (argv[argc-1]); if (file.size() >= 4){ if (file.substr(file.size()-4) == ".top" && zip){ cerr << "You requested to zip a .top file... That is not cool." << endl; cerr << "I'll abort the program before you blow everything up." << endl; cerr << "If you want to unzip, use the -u or --unzip flag on execution, i.e:" << endl; cerr << "~ ./topzip.out --unzip <awesome-file>.top" << endl; exit(-1); } } ifstream in (file); ofstream out; if (zip) file+=".top"; else file= file.substr(0,file.size()-4); out.open(file); if (!in.is_open() || !out.is_open()){ cerr << "Could not open file. Aborting" << endl; cerr << "(maybe you mispelled it ?)" << endl; exit (-1); } if (zip){ cout << "Entered in zipping mode..." << endl; string stream; int frequency[256]; vector<Cpair> frequencies; memset (frequency, 0, sizeof frequency); char c; char n = 0 ; // reading each character of file while (in.get(c)){ uchar aux = c; frequency[aux] ++; // trick so v[c] is frequency of c; stream += c; } for (int i = 0 ; i < 256 ; ++i){ if ( frequency [i] != 0 ){ n++; frequencies.push_back((Cpair((uchar) i, frequency[i]))); } } // Building tree // We turn first 2 elements of the priority queue sorted in increasing // order of frequency into leafes of a root element with frequency // as the sum of both. Then we push this root to the priority queue // and repeat the process untill we are left with only one element. Node<Cpair>* root = buildTree(frequencies); // Map chars to its string of 1's and 0's map<uchar,string> code = getMap(root, frequencies); // Generating binary stream of digits string bitstream; for (uchar c : stream){ bitstream += code[c]; } // bitstream is the text's binary code. Now we need to pack // the frequency list information into our binary .top file, // so we can build the tree back again and hence read the // zipped file. // This binary code will follow the preceding protocol: // a char n : 1 byte for the number of nonzero frequencies // a char rem : 1 byte for the number of forgotten last bits // (3 bits would be enough, but that's too less for a variable) // preceding n*3 chars (bytes) : // for each 3 bytes: // first byte: related character // next 2 bytes: the 2 bytes corresponding to the short // binary representation of the character's // representation. // First we complete final bits char rem = 0; for (size_t i = 0 ; i < bitstream.size()%8 ; ++i){ rem ++; bitstream += '0'; } // Packing prefix for rebuilding the tree on unzipping string prefix, postfix; prefix += n; prefix += rem; for (auto f: frequencies){ uchar buf[2]; unsigned short aux = (short) f.second; buf[1] = (char) (aux>> 8); buf[0] = (char) (aux); prefix += f.first; prefix += buf[0]; prefix += buf[1]; } for (size_t i = 0; i < bitstream.size() ; i+=8){ postfix += byte2char(bitstream.substr(i,i+8)); } bitstream = prefix+postfix; out << bitstream; string txt = getTextBits(bitstream); string unzip = unZip(txt, code); cout << "Number of chars in text:" << root->data.second << endl; cout << "Number of chars in zipped file:" << (bitstream.size() >> 3) << endl; cout << unzip ; } else { cout << "Entered in unzipping mode..." << endl; string stream; char c; while (in.get(c)){ stream += c; } // Get frequency list vector<Cpair> frequencies = parseFrequencies(stream); // Get text side string txt = getTextBits(stream); // Build Huffman's tree from frequency list Node<Cpair>* root = buildTree(frequencies); // Get mappings from tree map<uchar,string> code = getMap(root, frequencies); // Unzip the hell out of text!! string unzip = unZip(txt, code); cout << "Unzipped text:\n" << unzip; out << unzip; } return 0; } <commit_msg>Added a simple header mark<commit_after>///////////////////////////////////////////////////////////////// // _____ _ // //|_ _| (_) // // | | ___ _ __ _____ _ __ // // | |/ _ \| '_ \_ / | '_ \ // // | | (_) | |_) / /| | |_) | // // \_/\___/| .__/___|_| .__/ // // | | | | // // |_| |_| // // // //*For instructions on how to use topzip, see README.md // //*For information on this project's license, see LICENSE.md // ///////////////////////////////////////////////////////////////// #include <iostream> #include <fstream> #include <cstring> #include <vector> #include <queue> #include <map> #include <cassert> #include "node.hpp" using namespace std; typedef unsigned char uchar; // Made this struct so we could pair a character with it's frequency // and define proper operators so our implementation is simplified. struct Cpair{ char first; int second; Cpair(char c, int v): first(c), second(v){} bool operator < ( const Cpair& b ) const { return second < b.second; } bool operator > ( const Cpair& b ) const { return second > b.second; } }; // This function defines operator for printing our data ostream& operator<<(std::ostream &os, const Cpair& m) { return os << "char: " << m.first << " frequency: " << m.second ; } // Takes two characters bit representation and cast it // to an unsigned short: // i.e: uchar bits[2] = {168,2} becomes 680 // i.e: uchar bits[2] = {0,2} becomes 520 // i.e: uchar bits[2] = {168,0} becomes 168 // We simply interpret the array of two chars as // if they were a short (which, bitwise, may be same as // unsigned short) unsigned short bit2short( uchar* bytes ){ return (unsigned short) (((short)bytes[1]) << 8) | bytes[0]; } // Gets the tree and map each char to its string binary representation void mapChar(map<uchar,string>& m, Node<Cpair>* root, uchar c, string key = ""){ if (root->data.first == c){ m[c] = key; return ; } else{ if (root->left != NULL) mapChar(m, root->left, c, key+'0'); if (root->right!= NULL) mapChar(m, root->right, c, key+'1'); } } // Gets a string of ones and zeroes and returns a // byte (a char)) uchar byte2char ( const string& byte ){ char aux = 0; for (int i = 7 ; i >= 0 ; --i){ aux = aux | ((byte[7-i]-'0') << i); } return aux; } // Does the same thing as previous function but the // other way around (takes byte and returns string) string char2byte (uchar c){ string aux; for ( int i = 7 ; i >= 0 ; --i ){ aux += ((1 << i) & c) ? '1' : '0'; } return aux; } // With the Huffman's tree's root and vector of pairs, we can generate the mappings // of each character to its Huffman's code. That's what this function does. map<uchar, string> getMap (Node<Cpair>* root, const vector<Cpair>& f){ map<uchar, string> code; for (auto v : f){ mapChar(code, root, v.first); } return code; } // Gets the char => binary string mapping and text compressed string // (from only text code info on, without tree building protocol part) // and returns the unzipped text. string unZip( const string& bits, const map<uchar,string>& code){ string aux; string unzip; for (size_t i = 0 ; i < bits.size() ; ++i){ aux += bits[i]; for (auto it = code.begin() ; it!= code.end() ; ++it){ if (it->second == aux){ unzip += it->first; aux.clear(); break; } } } return unzip; } // Accordingly to our protocol, we use this function to get a // frequency list out of the bit string representation of the // zipped file. vector<Cpair> parseFrequencies(const string& bits){ vector<Cpair> aux; int n = (int) bits[0]; uchar buf[2]; for (int i = 2; i < 3*n+2; i+=3){ buf[0] = bits[i+1]; buf[1] = bits[i+2]; aux.push_back(Cpair(bits[i], bit2short(buf))); } return aux; } // Function for generating the tree, return it's node solely. // And the node is all we need to know everything about the tree. Node<Cpair>* buildTree (const vector<Cpair>& list){ Node<Cpair>* root; priority_queue <Node<Cpair>, vector<Node<Cpair> >, greater<Node<Cpair>> > f_list; for (auto v : list){ f_list.push(Node<Cpair>(v)); } while (f_list.size() != 1){ auto first = f_list.top(); f_list.pop(); auto second = f_list.top(); f_list.pop(); Cpair r('*', first.data.second+second.data.second); root = new Node<Cpair> (r); root->left = new Node<Cpair> (first); root->right = new Node<Cpair> (second); f_list.push(*root); } return root; } // For debugging purposes, this function takes a tree root and // prints it in preorder. void printTree(const Node<Cpair>* r){ cout << r->data << endl; if (r->left != NULL) printTree(r->left); if (r->right != NULL) printTree(r->right); } // Simply cuts off the whole bit string representation of zipped file // the part related to the text. string getTextBits( const string& bytes ){ int n = (int) bytes[0]; unsigned int rem = (int) bytes[1]; string aux = bytes.substr(3*n+2); string txt; for (size_t i = 0 ; i < aux.size(); ++i){ txt += char2byte(aux[i]); } return txt.substr(0,txt.size()-rem); } int main (int argc, char* argv[]){ if (argc == 1){ cerr << "No argument given. \n" << "Usage: \n" << "For help, run ./topzip.out -h \n" << "Aborting. \n"; exit(-1); } bool zip = true; for (int i = 1 ; i < argc ; ++i){ if (!strcmp(argv[i], "-h") or !strcmp(argv[i], "--help")){ cout << "Need help ? Here is how to use it:"<< endl; cout << "\t~ ./topzip.out <flags> <path-to-text>\n"<< endl; cout << "flags = -u or --unzip for unzipping mode"<< endl; cout << "flags = -h or --help for help"<< endl; return 0; } if (!strcmp(argv[i], "-u") or !strcmp(argv[i], "--unzip")){ zip = false; } } string file (argv[argc-1]); if (file.size() >= 4){ if (file.substr(file.size()-4) == ".top" && zip){ cerr << "You requested to zip a .top file... That is not cool." << endl; cerr << "I'll abort the program before you blow everything up." << endl; cerr << "If you want to unzip, use the -u or --unzip flag on execution, i.e:" << endl; cerr << "~ ./topzip.out --unzip <awesome-file>.top" << endl; exit(-1); } } ifstream in (file); ofstream out; if (zip) file+=".top"; else file= file.substr(0,file.size()-4); out.open(file); if (!in.is_open() || !out.is_open()){ cerr << "Could not open file. Aborting" << endl; cerr << "(maybe you mispelled it ?)" << endl; exit (-1); } if (zip){ cout << "Entered in zipping mode..." << endl; string stream; int frequency[256]; vector<Cpair> frequencies; memset (frequency, 0, sizeof frequency); char c; char n = 0 ; // reading each character of file while (in.get(c)){ uchar aux = c; frequency[aux] ++; // trick so v[c] is frequency of c; stream += c; } for (int i = 0 ; i < 256 ; ++i){ if ( frequency [i] != 0 ){ n++; frequencies.push_back((Cpair((uchar) i, frequency[i]))); } } // Building tree // We turn first 2 elements of the priority queue sorted in increasing // order of frequency into leafes of a root element with frequency // as the sum of both. Then we push this root to the priority queue // and repeat the process untill we are left with only one element. Node<Cpair>* root = buildTree(frequencies); // Map chars to its string of 1's and 0's map<uchar,string> code = getMap(root, frequencies); // Generating binary stream of digits string bitstream; for (uchar c : stream){ bitstream += code[c]; } // bitstream is the text's binary code. Now we need to pack // the frequency list information into our binary .top file, // so we can build the tree back again and hence read the // zipped file. // This binary code will follow the preceding protocol: // a char n : 1 byte for the number of nonzero frequencies // a char rem : 1 byte for the number of forgotten last bits // (3 bits would be enough, but that's too less for a variable) // preceding n*3 chars (bytes) : // for each 3 bytes: // first byte: related character // next 2 bytes: the 2 bytes corresponding to the short // binary representation of the character's // representation. // First we complete final bits char rem = 0; for (size_t i = 0 ; i < bitstream.size()%8 ; ++i){ rem ++; bitstream += '0'; } // Packing prefix for rebuilding the tree on unzipping string prefix, postfix; prefix += n; prefix += rem; for (auto f: frequencies){ uchar buf[2]; unsigned short aux = (short) f.second; buf[1] = (char) (aux>> 8); buf[0] = (char) (aux); prefix += f.first; prefix += buf[0]; prefix += buf[1]; } for (size_t i = 0; i < bitstream.size() ; i+=8){ postfix += byte2char(bitstream.substr(i,i+8)); } bitstream = prefix+postfix; out << bitstream; string txt = getTextBits(bitstream); string unzip = unZip(txt, code); cout << "Number of chars in text:" << root->data.second << endl; cout << "Number of chars in zipped file:" << (bitstream.size() >> 3) << endl; cout << unzip ; } else { cout << "Entered in unzipping mode..." << endl; string stream; char c; while (in.get(c)){ stream += c; } // Get frequency list vector<Cpair> frequencies = parseFrequencies(stream); // Get text side string txt = getTextBits(stream); // Build Huffman's tree from frequency list Node<Cpair>* root = buildTree(frequencies); // Get mappings from tree map<uchar,string> code = getMap(root, frequencies); // Unzip the hell out of text!! string unzip = unZip(txt, code); cout << "Unzipped text:\n" << unzip; out << unzip; } return 0; } <|endoftext|>
<commit_before>7829f448-2d53-11e5-baeb-247703a38240<commit_msg>782a799a-2d53-11e5-baeb-247703a38240<commit_after>782a799a-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>be2bbb30-2e4f-11e5-ace6-28cfe91dbc4b<commit_msg>be329f9c-2e4f-11e5-9c18-28cfe91dbc4b<commit_after>be329f9c-2e4f-11e5-9c18-28cfe91dbc4b<|endoftext|>
<commit_before>eab17099-2d3c-11e5-b47b-c82a142b6f9b<commit_msg>eb164c51-2d3c-11e5-8203-c82a142b6f9b<commit_after>eb164c51-2d3c-11e5-8203-c82a142b6f9b<|endoftext|>
<commit_before>#include "sgct.h" #include "ParticleSystem.h" #include "Snow.h" #include "World.h" #include "HelperFunctions.h" #include "Field.h" #include "DebugField.h" #include "Gravity.h" #include "Wind.h" #include "ObjSystem.h" #include "SoapBubble.h" #include "Vortex.h" #include <iostream> #include "SimplexNoise.h" //our beautiful global variables sgct::Engine* gEngine; Snow* gParticles; World* gWorld; Object* road; Object* tree; SoapBubble* gBubble; Wind* gWind; Gravity* gGrav; Vortex* gTurbine; bool gDisplayInfo; bool gStatsGraph; bool gWireframe; sgct::SharedDouble curr_time(0.0); sgct::SharedDouble sizeFactorX(0.0); sgct::SharedDouble sizeFactorY(0.0); sgct::SharedDouble sizeFactorZ(0.0); sgct::SharedDouble vortFactorX(0.0); sgct::SharedDouble vortFactorY(0.0); sgct::SharedDouble vortFactorZ(0.0); sgct::SharedDouble positionX(0.0); sgct::SharedDouble positionZ(0.0); sgct::SharedDouble radius(0.0); sgct::SharedDouble fadeDistance(0.0); void initialize(); void draw(); void myPreSyncFun(); void statsDrawFun(); void myEncodeFun(); void myDecodeFun(); void externalControlCallback(const char * receivedChars, int size, int clientId); void sendMessageToExternalControl(void * data, int length); int main(int argc, char *argv[]) { initRandom(); gEngine = new sgct::Engine(argc, argv); gEngine->setInitOGLFunction(initialize); gEngine->setDrawFunction(draw); gEngine->setPreSyncFunction(myPreSyncFun); gEngine->setPostSyncPreDrawFunction(statsDrawFun); gEngine->setExternalControlCallback(externalControlCallback); sgct::SharedData::instance()->setEncodeFunction(myEncodeFun); sgct::SharedData::instance()->setDecodeFunction(myDecodeFun); gParticles = new Snow(gEngine); gWorld = new World(gEngine); gBubble = new SoapBubble(gEngine); road = new Object(gEngine); tree = new Object(gEngine); gGrav = new Gravity(); gGrav->init(-9.81f); gParticles->addField(gGrav); gWind = new Wind(); //wind->init(getRandom(-0.2, 0.2), 0.0f, getRandom(-0.2, 0.2)); gWind->setAcceleration(getRandom(-0.2, 0.2), 0.0f, getRandom(-0.2, 0.2)); //gParticles->addField(gWind); gTurbine = new Vortex(); gTurbine->init(0.0f, 0.0f, 0.0f); // gParticles->addField(gTurbine); if(!gEngine->init(sgct::Engine::OpenGL_3_3_Core_Profile)) { delete gEngine; return EXIT_FAILURE; } //Not working yet... :( SimplexNoise* noise = new SimplexNoise(); noise->init(glm::vec3(0), glm::vec3(0), gEngine->getTime()); // gParticles->addField(noise); cout << "---- Fields active on gParticles ----" << endl; gParticles->printFields(); cout << "---------------" << endl << endl; gEngine->render(); gParticles->destroy(); road->deleteObject(); delete road; delete gEngine; delete gParticles; delete gWorld; delete gBubble; delete gWind; delete gTurbine; exit(EXIT_SUCCESS); } void initialize() { if(!gParticles->initialize()) { std::cout << "Error Initialzing Particle System:" << std::endl; exit(EXIT_FAILURE); } gWorld->initializeWorld(); road->loadObj("road/road.obj", "road/road.png"); road->scale(0.2f,0.2f,0.2f); road->translate(0.0f, -2.0f, 5.0f); tree->loadObj("road/tree.obj","road/tree.png"); tree->scale(0.05f,0.05f,0.05f); tree->translate(0.0f, -1.0f, -6.0f); gBubble->createSphere(1.5f, 100); gDisplayInfo = false; gStatsGraph = false; gWireframe = false; } void draw() { double delta = gEngine->getDt(); gWorld->drawWorld(); gBubble->drawBubble(); road->draw(); tree->draw(); gParticles->move(delta); gParticles->draw(delta); } //Checking the time since the program started, not sure if we need this either. void myPreSyncFun() { //Checks so the gEnginenode is actually the master. if( gEngine->isMaster() ) { //Sets the current time since the program started curr_time.setVal(sgct::Engine::getTime()); } } void myEncodeFun() { sgct::SharedData::instance()->writeDouble(&curr_time); sgct::SharedData::instance()->writeDouble(&sizeFactorX); sgct::SharedData::instance()->writeDouble(&sizeFactorY); sgct::SharedData::instance()->writeDouble(&sizeFactorZ); sgct::SharedData::instance()->writeDouble(&vortFactorX); sgct::SharedData::instance()->writeDouble(&vortFactorY); sgct::SharedData::instance()->writeDouble(&vortFactorZ); sgct::SharedData::instance()->writeDouble(&positionX); sgct::SharedData::instance()->writeDouble(&positionZ); sgct::SharedData::instance()->writeDouble(&radius); sgct::SharedData::instance()->writeDouble(&fadeDistance); } void myDecodeFun() { sgct::SharedData::instance()->readDouble(&curr_time); sgct::SharedData::instance()->readDouble(&sizeFactorX); sgct::SharedData::instance()->readDouble(&sizeFactorY); sgct::SharedData::instance()->readDouble(&sizeFactorZ); sgct::SharedData::instance()->readDouble(&vortFactorX); sgct::SharedData::instance()->readDouble(&vortFactorY); sgct::SharedData::instance()->readDouble(&vortFactorZ); sgct::SharedData::instance()->readDouble(&positionX); sgct::SharedData::instance()->readDouble(&positionZ); sgct::SharedData::instance()->readDouble(&radius); sgct::SharedData::instance()->readDouble(&fadeDistance); } //Shows stats and graph depending on if the variables are true or not. Dont know if we need this? Currently set to false. void statsDrawFun() { gEngine->setDisplayInfoVisibility(gDisplayInfo); gEngine->setStatsGraphVisibility(gStatsGraph); gEngine->setWireframe(gWireframe); } //Used to alter certain values when sent from GUI. This way we can alter the fields or change gravity in realtime! void externalControlCallback(const char * receivedChars, int size, int clientId) { //Checks so the gEnginenode is actually the master. if(gEngine->isMaster()) { if(size >= 6 && strncmp(receivedChars, "winX", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); sizeFactorX.setVal(tmpVal); gWind->setAcceleration((sizeFactorX.getVal()*0.01f), (sizeFactorY.getVal()*0.01f), (sizeFactorZ.getVal()*0.01f)); } else if(size >= 6 && strncmp(receivedChars, "winY", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); sizeFactorY.setVal(tmpVal); gWind->setAcceleration((sizeFactorX.getVal()*0.01f), (sizeFactorY.getVal()*0.01f), (sizeFactorZ.getVal()*0.01f)); } else if(size >= 6 && strncmp(receivedChars, "winZ", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); sizeFactorZ.setVal(tmpVal); gWind->setAcceleration((sizeFactorX.getVal()*0.01f), (sizeFactorY.getVal()*0.01f), (sizeFactorZ.getVal()*0.01f)); } else if(size >= 6 && strncmp(receivedChars, "vorX", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); gTurbine->setForce((tmpVal*0.01f), (tmpVal*0.01f), (tmpVal*0.01f)); } else if(size >= 6 && strncmp(receivedChars, "vorY", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); vortFactorY.setVal(tmpVal); gTurbine->setForce((vortFactorX.getVal()*0.01f), (vortFactorY.getVal()*0.01f), (vortFactorZ.getVal()*0.01f)); } else if(size >= 6 && strncmp(receivedChars, "vorZ", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); vortFactorZ.setVal(tmpVal); gTurbine->setForce((vortFactorX.getVal()*0.01f), (vortFactorY.getVal()*0.01f), (vortFactorZ.getVal()*0.01f)); } else if(size >= 6 && strncmp(receivedChars, "posX", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); positionX.setVal(tmpVal); gTurbine->setPosition((positionX.getVal()*0.01f),(positionZ.getVal()*0.01f)); } else if(size >= 6 && strncmp(receivedChars, "posZ", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); positionZ.setVal(tmpVal); gTurbine->setPosition((positionX.getVal()*0.01f),(positionZ.getVal()*0.01f)); } else if(size >= 6 && strcmp(receivedChars, "radius") != 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); radius.setVal(tmpVal); gTurbine->setRadius(radius.getVal()); } else if(size >= 6 && strcmp(receivedChars, "pause") != 0) { gParticles->togglePause(); } else if(size >= 6 && strncmp(receivedChars, "grav", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); gGrav->init(-tmpVal); } else if(strcmp(receivedChars, "fadeDistance") != 0) { float tmpVal = atof(receivedChars + 5); fadeDistance.setVal(tmpVal); gParticles->setFadeDistance(fadeDistance.getVal()); } else if(size >= 6 && strcmp(receivedChars, "display") != 0) { gDisplayInfo = !gDisplayInfo; } else if(size >= 6 && strcmp(receivedChars, "stats") != 0) { gStatsGraph = !gStatsGraph; } else if(size >= 6 && strcmp(receivedChars, "wire") != 0) { gWireframe = !gWireframe; } } } <commit_msg>Fixed the guiproblem, but we still cant use negative values<commit_after>#include "sgct.h" #include "ParticleSystem.h" #include "Snow.h" #include "World.h" #include "HelperFunctions.h" #include "Field.h" #include "DebugField.h" #include "Gravity.h" #include "Wind.h" #include "ObjSystem.h" #include "SoapBubble.h" #include "Vortex.h" #include <iostream> #include "SimplexNoise.h" //our beautiful global variables sgct::Engine* gEngine; Snow* gParticles; World* gWorld; Object* road; Object* tree; SoapBubble* gBubble; Wind* gWind; Gravity* gGrav; Vortex* gTurbine; bool gDisplayInfo; bool gStatsGraph; bool gWireframe; sgct::SharedDouble curr_time(0.0); sgct::SharedDouble sizeFactorX(0.0); sgct::SharedDouble sizeFactorY(0.0); sgct::SharedDouble sizeFactorZ(0.0); sgct::SharedDouble vortFactorX(0.0); sgct::SharedDouble vortFactorY(0.0); sgct::SharedDouble vortFactorZ(0.0); sgct::SharedDouble positionX(0.0); sgct::SharedDouble positionZ(0.0); sgct::SharedDouble radius(0.0); sgct::SharedDouble fadeDistance(0.0); void initialize(); void draw(); void myPreSyncFun(); void statsDrawFun(); void myEncodeFun(); void myDecodeFun(); void externalControlCallback(const char * receivedChars, int size, int clientId); void sendMessageToExternalControl(void * data, int length); int main(int argc, char *argv[]) { initRandom(); gEngine = new sgct::Engine(argc, argv); gEngine->setInitOGLFunction(initialize); gEngine->setDrawFunction(draw); gEngine->setPreSyncFunction(myPreSyncFun); gEngine->setPostSyncPreDrawFunction(statsDrawFun); gEngine->setExternalControlCallback(externalControlCallback); sgct::SharedData::instance()->setEncodeFunction(myEncodeFun); sgct::SharedData::instance()->setDecodeFunction(myDecodeFun); gParticles = new Snow(gEngine); gWorld = new World(gEngine); gBubble = new SoapBubble(gEngine); road = new Object(gEngine); tree = new Object(gEngine); gGrav = new Gravity(); gGrav->init(-9.81f); gParticles->addField(gGrav); gWind = new Wind(); //wind->init(getRandom(-0.2, 0.2), 0.0f, getRandom(-0.2, 0.2)); gWind->setAcceleration(getRandom(-0.2, 0.2), 0.0f, getRandom(-0.2, 0.2)); //gParticles->addField(gWind); gTurbine = new Vortex(); gTurbine->init(0.0f, 0.0f, 0.0f); // gParticles->addField(gTurbine); if(!gEngine->init(sgct::Engine::OpenGL_3_3_Core_Profile)) { delete gEngine; return EXIT_FAILURE; } //Not working yet... :( SimplexNoise* noise = new SimplexNoise(); noise->init(glm::vec3(0), glm::vec3(0), gEngine->getTime()); // gParticles->addField(noise); cout << "---- Fields active on gParticles ----" << endl; gParticles->printFields(); cout << "---------------" << endl << endl; gEngine->render(); gParticles->destroy(); road->deleteObject(); delete road; delete gEngine; delete gParticles; delete gWorld; delete gBubble; delete gWind; delete gTurbine; exit(EXIT_SUCCESS); } void initialize() { if(!gParticles->initialize()) { std::cout << "Error Initialzing Particle System:" << std::endl; exit(EXIT_FAILURE); } gWorld->initializeWorld(); road->loadObj("road/road.obj", "road/road.png"); road->scale(0.2f,0.2f,0.2f); road->translate(0.0f, -2.0f, 5.0f); tree->loadObj("road/tree.obj","road/tree.png"); tree->scale(0.05f,0.05f,0.05f); tree->translate(0.0f, -1.0f, -6.0f); gBubble->createSphere(1.5f, 100); gDisplayInfo = false; gStatsGraph = false; gWireframe = false; } void draw() { double delta = gEngine->getDt(); gWorld->drawWorld(); gBubble->drawBubble(); road->draw(); tree->draw(); gParticles->move(delta); gParticles->draw(delta); //if(gEngine->isExternalControlConnected()) // cout << "Connectad is very nice"; } //Checking the time since the program started, not sure if we need this either. void myPreSyncFun() { //Checks so the gEnginenode is actually the master. if( gEngine->isMaster() ) { //Sets the current time since the program started curr_time.setVal(sgct::Engine::getTime()); } } void myEncodeFun() { sgct::SharedData::instance()->writeDouble(&curr_time); sgct::SharedData::instance()->writeDouble(&sizeFactorX); sgct::SharedData::instance()->writeDouble(&sizeFactorY); sgct::SharedData::instance()->writeDouble(&sizeFactorZ); sgct::SharedData::instance()->writeDouble(&vortFactorX); sgct::SharedData::instance()->writeDouble(&vortFactorY); sgct::SharedData::instance()->writeDouble(&vortFactorZ); sgct::SharedData::instance()->writeDouble(&positionX); sgct::SharedData::instance()->writeDouble(&positionZ); sgct::SharedData::instance()->writeDouble(&radius); sgct::SharedData::instance()->writeDouble(&fadeDistance); } void myDecodeFun() { sgct::SharedData::instance()->readDouble(&curr_time); sgct::SharedData::instance()->readDouble(&sizeFactorX); sgct::SharedData::instance()->readDouble(&sizeFactorY); sgct::SharedData::instance()->readDouble(&sizeFactorZ); sgct::SharedData::instance()->readDouble(&vortFactorX); sgct::SharedData::instance()->readDouble(&vortFactorY); sgct::SharedData::instance()->readDouble(&vortFactorZ); sgct::SharedData::instance()->readDouble(&positionX); sgct::SharedData::instance()->readDouble(&positionZ); sgct::SharedData::instance()->readDouble(&radius); sgct::SharedData::instance()->readDouble(&fadeDistance); } //Shows stats and graph depending on if the variables are true or not. Dont know if we need this? Currently set to false. void statsDrawFun() { gEngine->setDisplayInfoVisibility(gDisplayInfo); gEngine->setStatsGraphVisibility(gStatsGraph); gEngine->setWireframe(gWireframe); } //Used to alter certain values when sent from GUI. This way we can alter the fields or change gravity in realtime! void externalControlCallback(const char * receivedChars, int size, int clientId) { //Checks so the gEnginenode is actually the master. if(gEngine->isMaster()) { if(size >= 6 && strncmp(receivedChars, "winX", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); sizeFactorX.setVal(tmpVal); gWind->setAcceleration((sizeFactorX.getVal()*0.01f), (sizeFactorY.getVal()*0.01f), (sizeFactorZ.getVal()*0.01f)); } else if(size >= 6 && strncmp(receivedChars, "winY", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); sizeFactorY.setVal(tmpVal); gWind->setAcceleration((sizeFactorX.getVal()*0.01f), (sizeFactorY.getVal()*0.01f), (sizeFactorZ.getVal()*0.01f)); } else if(size >= 6 && strncmp(receivedChars, "winZ", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); sizeFactorZ.setVal(tmpVal); gWind->setAcceleration((sizeFactorX.getVal()*0.01f), (sizeFactorY.getVal()*0.01f), (sizeFactorZ.getVal()*0.01f)); } else if(size >= 6 && strncmp(receivedChars, "vorX", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); gTurbine->setForce((tmpVal*0.01f), (tmpVal*0.01f), (tmpVal*0.01f)); } else if(size >= 6 && strncmp(receivedChars, "vorY", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); vortFactorY.setVal(tmpVal); gTurbine->setForce((vortFactorX.getVal()*0.01f), (vortFactorY.getVal()*0.01f), (vortFactorZ.getVal()*0.01f)); } else if(size >= 6 && strncmp(receivedChars, "vorZ", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); vortFactorZ.setVal(tmpVal); gTurbine->setForce((vortFactorX.getVal()*0.01f), (vortFactorY.getVal()*0.01f), (vortFactorZ.getVal()*0.01f)); } else if(size >= 6 && strncmp(receivedChars, "posX", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); positionX.setVal(tmpVal); gTurbine->setPosition((positionX.getVal()*0.01f),(positionZ.getVal()*0.01f)); } else if(size >= 6 && strncmp(receivedChars, "posZ", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); positionZ.setVal(tmpVal); gTurbine->setPosition((positionX.getVal()*0.01f),(positionZ.getVal()*0.01f)); } else if(size >= 6 && strncmp(receivedChars, "radi", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); radius.setVal(tmpVal); gTurbine->setRadius(radius.getVal()); } else if(size >= 6 && strncmp(receivedChars, "paus", 4) == 0) { gParticles->togglePause(); } else if(size >= 6 && strncmp(receivedChars, "grav", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); gGrav->init(-tmpVal); } else if(strncmp(receivedChars, "fade", 1) == 0) { float tmpVal = atof(receivedChars + 5); fadeDistance.setVal(tmpVal); gParticles->setFadeDistance(fadeDistance.getVal()); } else if(size >= 6 && strncmp(receivedChars, "disp", 4) == 0) { //gDisplayInfo = !gDisplayInfo; } else if(size >= 6 && strncmp(receivedChars, "stat", 4) == 0) { //gStatsGraph = !gStatsGraph; } else if(size >= 6 && strncmp(receivedChars, "wire", 4) == 0) { //gWireframe = !gWireframe; } } } <|endoftext|>
<commit_before>a3a82351-2e4f-11e5-93af-28cfe91dbc4b<commit_msg>a3b2afb8-2e4f-11e5-8bd6-28cfe91dbc4b<commit_after>a3b2afb8-2e4f-11e5-8bd6-28cfe91dbc4b<|endoftext|>
<commit_before>/******************************* Copyright (C) 2013-2014 grégoire ANGERAND This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. **********************************/ #include <n/core/String.h> #include <n/test/TestTemplate.h> #include <n/test/Test.h> namespace n { namespace test { class StringTest : public TestTemplate<StringTest> { public: StringTest() : TestTemplate<StringTest>() { } bool run() override { basicTests(); return true; } private: void basicTests() { core::String str = "floup, flup, flap, flip"; test(str.replaced(",", ""), "floup flup flap flip", "Replaced test"); test(str.replaced("p", "w"), "flouw, fluw, flaw, fliw", "Replaced test 2"); test(str.replaced("floup", "flip"), "flip, flup, flap, flip", "Replaced test 3"); str.replace(",", ""); core::String s = str; test(s.toChar(), str.toChar(), "Sharing test"); str.replace("p ", "_"); str.replace("flou", "flew"); test(str == "flew_flu_fla_flip" && s == "floup flup flap flip", true, "Replace test"); str.clear(); test(str == "" && s == "floup flup flap flip", true, "Clear test"); str = s; test(s.toChar(), str.toChar(), "Sharing 2 test"); test(str == "floup flup flap flip" && s == "floup flup flap flip", true, "Affectation test"); char const *cp = str.toChar(); str.detach(); test(str.toChar() != cp, true, "detach test"); test(str, "floup flup flap flip", "detach test"); test(str.size(), 20, "detach test"); test(str.size(), strlen(str.toChar()), "detach test"); str.map([](char c) { return c == 'f' ? 'F' : c; }); test(str, "Floup Flup Flap Flip", "Map test"); test(s, "floup flup flap flip", "Map test"); test(s.mapped([](char c) { return c == 'f' ? 'F' : c; }), str, "Mapped test"); str.filter([](char c) { return c != ' '; }); test(str.endWith("pFlapFlip"), true, "endWith test"); test(str.endWith("Flap"), false, "endWith test 2"); test(str.beginWith("gn ?"), false, "beginWith test"); test(str.beginWith("Floup"), true, "beginWith test 2"); test(str.endWith(""), true, "endWith \"\" test"); test(str, "FloupFlupFlapFlip", "Filter test"); test(s, "floup flup flap flip", "Filter test"); test(s.mapped([](char c) { return c == 'f' ? 'F' : c; }).filtered([](char c) { return c != ' '; }), str, "Filtered test"); core::String a; test(str.endWith(""), true, "\"\".endWith test"); test(a.size(), 0, "Lenght test"); core::String b = a; a = a + 'c'; test(a.isShared(), false, "Shared test"); test(b.size(), 0, "CoW test"); b = a; test(a.isShared() && b.isShared(), true, "Shared test 2"); a += a; test(a.isShared() || b.isShared(), false, "Shared test 3"); test(b.size(), 1, "CoW test 2"); test(a, "cc", "CoW test 3"); test(a + 3, "cc3", "Int concat test"); test(core::String("") + 9.5f, "9.5", "Float contructor test"); test(core::String("a") + 9.5f, "a9.5", "Float concat test"); test(9.5f + core::String("f"), "9.5f", "Float concat test 2"); } }; } //test } //n <commit_msg>Fixed tests messages<commit_after>/******************************* Copyright (C) 2013-2014 grégoire ANGERAND This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. **********************************/ #include <n/core/String.h> #include <n/test/TestTemplate.h> #include <n/test/Test.h> namespace n { namespace test { class StringTest : public TestTemplate<StringTest> { public: StringTest() : TestTemplate<StringTest>() { } bool run() override { basicTests(); return true; } private: void basicTests() { core::String str = "floup, flup, flap, flip"; test(str.replaced(",", ""), "floup flup flap flip", "Replaced test failed"); test(str.replaced("p", "w"), "flouw, fluw, flaw, fliw", "Replaced test 2"); test(str.replaced("floup", "flip"), "flip, flup, flap, flip", "Replaced test 3"); str.replace(",", ""); core::String s = str; test(s.toChar(), str.toChar(), "Sharing test failed"); str.replace("p ", "_"); str.replace("flou", "flew"); test(str == "flew_flu_fla_flip" && s == "floup flup flap flip", true, "Replace test failed"); str.clear(); test(str == "" && s == "floup flup flap flip", true, "Clear test failed"); str = s; test(s.toChar(), str.toChar(), "Sharing 2 test failed"); test(str == "floup flup flap flip" && s == "floup flup flap flip", true, "Affectation test failed"); char const *cp = str.toChar(); str.detach(); test(str.toChar() != cp, true, "detach test failed"); test(str, "floup flup flap flip", "detach test failed"); test(str.size(), 20, "detach test failed"); test(str.size(), strlen(str.toChar()), "detach test failed"); str.map([](char c) { return c == 'f' ? 'F' : c; }); test(str, "Floup Flup Flap Flip", "Map test failed"); test(s, "floup flup flap flip", "Map test failed"); test(s.mapped([](char c) { return c == 'f' ? 'F' : c; }), str, "Mapped test failed"); str.filter([](char c) { return c != ' '; }); test(str.endWith("pFlapFlip"), true, "endWith test failed"); test(str.endWith("Flap"), false, "endWith test 2"); test(str.beginWith("gn ?"), false, "beginWith test failed"); test(str.beginWith("Floup"), true, "beginWith test 2"); test(str.endWith(""), true, "endWith \"\" test failed"); test(str, "FloupFlupFlapFlip", "Filter test failed"); test(s, "floup flup flap flip", "Filter test failed"); test(s.mapped([](char c) { return c == 'f' ? 'F' : c; }).filtered([](char c) { return c != ' '; }), str, "Filtered test failed"); core::String a; test(str.endWith(""), true, "\"\".endWith test failed"); test(a.size(), 0, "Lenght test failed"); core::String b = a; a = a + 'c'; test(a.isShared(), false, "Shared test failed"); test(b.size(), 0, "CoW test failed"); b = a; test(a.isShared() && b.isShared(), true, "Shared test 2"); a += a; test(a.isShared() || b.isShared(), false, "Shared test 3"); test(b.size(), 1, "CoW test 2"); test(a, "cc", "CoW test 3"); test(a + 3, "cc3", "Int concat test failed"); test(core::String("") + 9.5f, "9.5", "Float contructor test failed"); test(core::String("a") + 9.5f, "a9.5", "Float concat test failed"); test(9.5f + core::String("f"), "9.5f", "Float concat test 2"); } }; } //test } //n <|endoftext|>
<commit_before>65581954-2fa5-11e5-ba76-00012e3d3f12<commit_msg>655a1524-2fa5-11e5-84bb-00012e3d3f12<commit_after>655a1524-2fa5-11e5-84bb-00012e3d3f12<|endoftext|>
<commit_before>9721158c-2e4f-11e5-a971-28cfe91dbc4b<commit_msg>972897d9-2e4f-11e5-818f-28cfe91dbc4b<commit_after>972897d9-2e4f-11e5-818f-28cfe91dbc4b<|endoftext|>
<commit_before>c3ae11c0-4b02-11e5-81be-28cfe9171a43<commit_msg>lets try again<commit_after>c3bc8aa1-4b02-11e5-b309-28cfe9171a43<|endoftext|>
<commit_before>7e7919ae-2d15-11e5-af21-0401358ea401<commit_msg>7e7919af-2d15-11e5-af21-0401358ea401<commit_after>7e7919af-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>0dc8cb68-2f67-11e5-a94b-6c40088e03e4<commit_msg>0dcfc834-2f67-11e5-8d28-6c40088e03e4<commit_after>0dcfc834-2f67-11e5-8d28-6c40088e03e4<|endoftext|>
<commit_before>b41de50a-327f-11e5-80ad-9cf387a8033e<commit_msg>b42401d7-327f-11e5-b92b-9cf387a8033e<commit_after>b42401d7-327f-11e5-b92b-9cf387a8033e<|endoftext|>
<commit_before>d48f73ee-313a-11e5-ad4c-3c15c2e10482<commit_msg>d4952d40-313a-11e5-8f3f-3c15c2e10482<commit_after>d4952d40-313a-11e5-8f3f-3c15c2e10482<|endoftext|>
<commit_before>d59ab370-35ca-11e5-a5ec-6c40088e03e4<commit_msg>d5a15918-35ca-11e5-b89d-6c40088e03e4<commit_after>d5a15918-35ca-11e5-b89d-6c40088e03e4<|endoftext|>
<commit_before>8d6dfce8-2d14-11e5-af21-0401358ea401<commit_msg>8d6dfce9-2d14-11e5-af21-0401358ea401<commit_after>8d6dfce9-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>81cf0d85-2d15-11e5-af21-0401358ea401<commit_msg>81cf0d86-2d15-11e5-af21-0401358ea401<commit_after>81cf0d86-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>f6bfe68c-585a-11e5-b809-6c40088e03e4<commit_msg>f6c6e824-585a-11e5-ab58-6c40088e03e4<commit_after>f6c6e824-585a-11e5-ab58-6c40088e03e4<|endoftext|>
<commit_before>#include "Data/Field.h" #include <iostream> int main(int argc, char** argv) { if (argc < 2) { std::cerr << "Specify field to load on the command line" << std::endl; getchar(); return 1; } // Load the field std::cout << "Loading field..." << std::endl; PropertySpace::Field *field = PropertySpace::Field::Load(argv[1]); if (!field) { std::cerr << "Error loading field" << std::endl; getchar(); return 1; } // Do PCA field->DoPCA(); // Transform extended field to normalized PCA basis field->Transform(); // Save transformed field as volumes field->Save("D:\\Temp\\TestField", 6); // Clean up delete field; // Keep the console window open for testing std::cout << "Press any enter to exit" << std::endl; getchar(); return 0; } <commit_msg>Only wait before exit in debug builds.<commit_after>#include "Data/Field.h" #include <iostream> int main(int argc, char** argv) { if (argc < 2) { std::cerr << "Specify field to load on the command line" << std::endl; return 1; } // Load the field std::cout << "Loading field..." << std::endl; PropertySpace::Field *field = PropertySpace::Field::Load(argv[1]); if (!field) { std::cerr << "Error loading field" << std::endl; return 1; } // Do PCA field->DoPCA(); // Transform extended field to normalized PCA basis field->Transform(); // Save transformed field as volumes field->Save("D:\\Temp\\TestField", 6); // Clean up delete field; #ifndef NDEBUG // Keep the console window open for testing std::cout << "Press any enter to exit" << std::endl; getchar(); #endif return 0; } <|endoftext|>
<commit_before>34b11b5a-5216-11e5-9059-6c40088e03e4<commit_msg>34b7dc1a-5216-11e5-9e4b-6c40088e03e4<commit_after>34b7dc1a-5216-11e5-9e4b-6c40088e03e4<|endoftext|>
<commit_before>e46bc007-327f-11e5-af01-9cf387a8033e<commit_msg>e472687a-327f-11e5-bcb6-9cf387a8033e<commit_after>e472687a-327f-11e5-bcb6-9cf387a8033e<|endoftext|>
<commit_before>3c1859c8-2e3a-11e5-afcf-c03896053bdd<commit_msg>3c2777c8-2e3a-11e5-9780-c03896053bdd<commit_after>3c2777c8-2e3a-11e5-9780-c03896053bdd<|endoftext|>
<commit_before>de9dfa1e-2e4e-11e5-9198-28cfe91dbc4b<commit_msg>dea45794-2e4e-11e5-b983-28cfe91dbc4b<commit_after>dea45794-2e4e-11e5-b983-28cfe91dbc4b<|endoftext|>
<commit_before>e73d87e6-585a-11e5-9125-6c40088e03e4<commit_msg>e7442a68-585a-11e5-a5ba-6c40088e03e4<commit_after>e7442a68-585a-11e5-a5ba-6c40088e03e4<|endoftext|>
<commit_before>e3d35a00-313a-11e5-b86f-3c15c2e10482<commit_msg>e3d9635c-313a-11e5-9a83-3c15c2e10482<commit_after>e3d9635c-313a-11e5-9a83-3c15c2e10482<|endoftext|>
<commit_before>6752ad8a-5216-11e5-a22e-6c40088e03e4<commit_msg>67591abe-5216-11e5-b1da-6c40088e03e4<commit_after>67591abe-5216-11e5-b1da-6c40088e03e4<|endoftext|>
<commit_before>bfa192e8-35ca-11e5-a106-6c40088e03e4<commit_msg>bfa90f50-35ca-11e5-9d41-6c40088e03e4<commit_after>bfa90f50-35ca-11e5-9d41-6c40088e03e4<|endoftext|>
<commit_before>d20a97fa-2e4e-11e5-978a-28cfe91dbc4b<commit_msg>d2118e8c-2e4e-11e5-b6e3-28cfe91dbc4b<commit_after>d2118e8c-2e4e-11e5-b6e3-28cfe91dbc4b<|endoftext|>
<commit_before>c344ad4a-35ca-11e5-81d1-6c40088e03e4<commit_msg>c34b7314-35ca-11e5-85bb-6c40088e03e4<commit_after>c34b7314-35ca-11e5-85bb-6c40088e03e4<|endoftext|>
<commit_before>809e9265-2d15-11e5-af21-0401358ea401<commit_msg>809e9266-2d15-11e5-af21-0401358ea401<commit_after>809e9266-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>37c88a8a-5216-11e5-8234-6c40088e03e4<commit_msg>37cf33b0-5216-11e5-95b8-6c40088e03e4<commit_after>37cf33b0-5216-11e5-95b8-6c40088e03e4<|endoftext|>
<commit_before>0a2d5197-2748-11e6-befe-e0f84713e7b8<commit_msg>Did a thing<commit_after>0a3f155e-2748-11e6-b260-e0f84713e7b8<|endoftext|>
<commit_before>#include <iostream> using namespace std; int main() { cout << "Hey Mel!"; return 0; } <commit_msg>Initial changes to triangle meme<commit_after>#include <iostream> using namespace std; int main() { int size; char character; cout << "Enter a size for your triangle"; cin >> size; cout << "Enter a character: "; cin >> character; for(int i = 0; i < size; i++) { for(int j = size; j > i; j--) { cout << character; } cout << endl; } return 0; } <|endoftext|>
<commit_before>552fcea8-5216-11e5-8c00-6c40088e03e4<commit_msg>5537d238-5216-11e5-8245-6c40088e03e4<commit_after>5537d238-5216-11e5-8245-6c40088e03e4<|endoftext|>
<commit_before>9101ada4-2d14-11e5-af21-0401358ea401<commit_msg>9101ada5-2d14-11e5-af21-0401358ea401<commit_after>9101ada5-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>#include <algorithm> #include <iostream> #include <vector> #include <assert.h> using namespace std; class Posibles { vector<bool> _b; public: Posibles() : _b(9, true) {} bool activo(int v) const { return _b[v-1]; } void elimina(int v) { _b[v-1] = false; } int num_activos() const { return count(_b.begin(), _b.end(), true); } int val() const { vector<bool>::const_iterator it = find(_b.begin(), _b.end(), true); return 1 + (it - _b.begin()); } string str(int ancho) const; }; string Posibles::str(int ancho) const { string s(ancho, ' '); int j = 0; for (int i = 1; i <= 9; ++i) { if(activo(i)) s[j++] = ('0' + i); } return s; } class Sudoku { vector<Posibles> _celdas; static vector< vector<int> > _grupos, _grupos_de, _vecinos; public: Sudoku(string s); static void inicializa(); Posibles posibles(int k) const { return _celdas[k]; } bool resuelto() const; void asigna(int k, int val); void elimina(int k, int val); void escribe(ostream& o) const; }; bool Sudoku::resuelto() const { for(int k = 0; k < _celdas.size(); k++) { if(_celdas[k].num_activos() != 1) { return false; } } return true; } void Sudoku::asigna(int k, int val) { for(int i = 1; i <= 9; i++) { if(i != val) { elimina(k, i); } } } void Sudoku::elimina(int k, int val) { _celdas[k].elimina(val); } void Sudoku::escribe(ostream& o) const { int ancho = 2; for(int k = 0; k < _celdas.size(); k++) { ancho = max(ancho, 1 + _celdas[k].num_activos()); } string sep(3 * ancho, '-'); for(int i = 0; i < 9; i++) { if(i == 3 || i == 6) { cout << sep << "+-" << sep << "+-" << sep << endl; } for (int j = 0; j < 9; j++) { const int k = i*9 + j; if(j == 3 || j == 6) { cout << "| "; } cout << _celdas[k].str(ancho); } cout << endl; } } Sudoku::Sudoku(string s) :_celdas(81) { int k = 0; for(int i = 0; i < s.size(); i++) { if (s[i] >= '1' && s[i] <= '9') { asigna(i, s[i] - '0'); k++; }else if(s[i] == '0' || s[i] == '.') { k++; } } assert(k == 81); } vector< vector<int> > Sudoku::_grupos(27), Sudoku::_grupos_de(81), Sudoku::_vecinos(81); void Sudoku::inicializa() { for(int i=0; i < 9; i++) { for(int j=0; j < 0; j++) { const int k = i*9 + j; const int g[3] = { i, 9 + j, 18 + (i/3)*3 + j/3}; for(int x = 0; x < 3; x++) { _grupos[g[x]].push_back(k); _grupos_de[k].push_back(g[k]); } } } for (int k = 0; k < 81; ++k) { for (int x = 0; x < 3; ++x) { const int g = _grupos_de[k] [x]; for (int i = 0; i < 9; ++i) { const int k2 = _grupos[g][i]; if(k2 != k) { _vecinos[k].push_back(k2); } } } } } int main() { Sudoku::inicializa(); Sudoku S("4.....8.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......"); S.escribe(cout); // Posibles p; // p.elimina(3); // cout << p.str() << endl; // cout << p.activo(2) << endl; // cout << p.num_activos() << endl; }<commit_msg>the methods 'Elimina' and 'asigna' are modified.<commit_after>#include <algorithm> #include <iostream> #include <vector> #include <assert.h> using namespace std; class Posibles { vector<bool> _b; public: Posibles() : _b(9, true) {} bool activo(int v) const { return _b[v-1]; } void elimina(int v) { _b[v-1] = false; } int num_activos() const { return count(_b.begin(), _b.end(), true); } int val() const { vector<bool>::const_iterator it = find(_b.begin(), _b.end(), true); return 1 + (it - _b.begin()); } string str(int ancho) const; }; string Posibles::str(int ancho) const { string s(ancho, ' '); int j = 0; for (int i = 1; i <= 9; ++i) { if(activo(i)) s[j++] = ('0' + i); } return s; } class Sudoku { vector<Posibles> _celdas; static vector< vector<int> > _grupos, _grupos_de, _vecinos; public: Sudoku(string s); static void inicializa(); Posibles posibles(int k) const { return _celdas[k]; } bool resuelto() const; bool asigna(int k, int val); bool elimina(int k, int val); void escribe(ostream& o) const; }; bool Sudoku::resuelto() const { for(int k = 0; k < _celdas.size(); k++) { if(_celdas[k].num_activos() != 1) { return false; } } return true; } void Sudoku::asigna(int k, int val) { for(int i = 1; i <= 9; i++) { if(i != val) { if(!elimina(k, i)) { return false; } } } } void Sudoku::elimina(int k, int val) { if(!_celdas[k].activo(val)) { return true; } _celdas[k].elimina(val); const int N = _celdas[k].num_activos(); if (N==0) { return false; }else if (N == 1) { const int v2 = _celdas[k].val(); for(int kp = 0; kp < _vecinos[k].size(); kp++) { if(!elimina(kp, v2)) return false; } } for(int x = 0; x < 3; x++) { const int g = _grupos_de[k][x]; int n = 0; k2; for(int i = 0; i < 9; i++) { const int kp = _grupos[g][i]; if(_celdas[kp].activo(val)) { n++, k2 = kp; } } if (n == 0) { return false; }else if (n == 1) { if (!asigna(k2, val)) return false; } } return true; } void Sudoku::escribe(ostream& o) const { int ancho = 2; for(int k = 0; k < _celdas.size(); k++) { ancho = max(ancho, 1 + _celdas[k].num_activos()); } string sep(3 * ancho, '-'); for(int i = 0; i < 9; i++) { if(i == 3 || i == 6) { cout << sep << "+-" << sep << "+-" << sep << endl; } for (int j = 0; j < 9; j++) { const int k = i*9 + j; if(j == 3 || j == 6) { cout << "| "; } cout << _celdas[k].str(ancho); } cout << endl; } } Sudoku::Sudoku(string s) :_celdas(81) { int k = 0; for(int i = 0; i < s.size(); i++) { if (s[i] >= '1' && s[i] <= '9') { asigna(i, s[i] - '0'); k++; }else if(s[i] == '0' || s[i] == '.') { k++; } } assert(k == 81); } vector< vector<int> > Sudoku::_grupos(27), Sudoku::_grupos_de(81), Sudoku::_vecinos(81); void Sudoku::inicializa() { for(int i=0; i < 9; i++) { for(int j=0; j < 0; j++) { const int k = i*9 + j; const int g[3] = { i, 9 + j, 18 + (i/3)*3 + j/3}; for(int x = 0; x < 3; x++) { _grupos[g[x]].push_back(k); _grupos_de[k].push_back(g[k]); } } } for (int k = 0; k < 81; ++k) { for (int x = 0; x < 3; ++x) { const int g = _grupos_de[k] [x]; for (int i = 0; i < 9; ++i) { const int k2 = _grupos[g][i]; if(k2 != k) { _vecinos[k].push_back(k2); } } } } } int main() { Sudoku::inicializa(); Sudoku S("4.....8.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......"); S.escribe(cout); // Posibles p; // p.elimina(3); // cout << p.str() << endl; // cout << p.activo(2) << endl; // cout << p.num_activos() << endl; }<|endoftext|>
<commit_before>b938d9a1-2e4f-11e5-914d-28cfe91dbc4b<commit_msg>b93f9b3d-2e4f-11e5-bb8a-28cfe91dbc4b<commit_after>b93f9b3d-2e4f-11e5-bb8a-28cfe91dbc4b<|endoftext|>
<commit_before>20ccd11e-ad58-11e7-8ba4-ac87a332f658<commit_msg>Made changes so it will hopefully compile by the next commit<commit_after>214cd397-ad58-11e7-aeff-ac87a332f658<|endoftext|>
<commit_before>261a7f2e-2e4f-11e5-a07b-28cfe91dbc4b<commit_msg>2622c633-2e4f-11e5-9b37-28cfe91dbc4b<commit_after>2622c633-2e4f-11e5-9b37-28cfe91dbc4b<|endoftext|>
<commit_before>92323ada-2d14-11e5-af21-0401358ea401<commit_msg>92323adb-2d14-11e5-af21-0401358ea401<commit_after>92323adb-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>8cd6bee3-2e4f-11e5-8fdd-28cfe91dbc4b<commit_msg>8cdd2cfa-2e4f-11e5-bd30-28cfe91dbc4b<commit_after>8cdd2cfa-2e4f-11e5-bd30-28cfe91dbc4b<|endoftext|>
<commit_before>ce76b07d-2e4e-11e5-8dea-28cfe91dbc4b<commit_msg>ce7d57cf-2e4e-11e5-9923-28cfe91dbc4b<commit_after>ce7d57cf-2e4e-11e5-9923-28cfe91dbc4b<|endoftext|>
<commit_before>74615bd4-2e3a-11e5-bfb5-c03896053bdd<commit_msg>74700558-2e3a-11e5-b795-c03896053bdd<commit_after>74700558-2e3a-11e5-b795-c03896053bdd<|endoftext|>
<commit_before>// // Copyright (c) 2008-2013 the Urho3D project. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include "Precompiled.h" #include "Plane.h" namespace Urho3D { // Static initialization order can not be relied on, so do not use Vector3 constants const Plane Plane::UP(Vector3(0.0f, 1.0f, 0.0f), Vector3(0.0f, 0.0f, 0.0f)); void Plane::Transform(const Matrix3& transform) { *this = Transformed(transform); } void Plane::Transform(const Matrix3x4& transform) { *this = Transformed(transform); } void Plane::Transform(const Matrix4& transform) { *this = Transformed(transform); } Matrix3x4 Plane::ReflectionMatrix() const { float negIntercept = -intercept_; return Matrix3x4( -2.0f * normal_.x_ * normal_.x_ + 1.0f, -2.0f * normal_.x_ * normal_.y_, -2.0f * normal_.x_ * normal_.z_, -2.0f * normal_.x_ * negIntercept, -2.0f * normal_.y_ * normal_.x_ , -2.0f * normal_.y_ * normal_.y_ + 1.0f, -2.0f * normal_.y_ * normal_.z_, -2.0f * normal_.y_ * negIntercept, -2.0f * normal_.z_ * normal_.x_, -2.0f * normal_.z_ * normal_.y_, -2.0f * normal_.z_ * normal_.z_ + 1.0f, -2.0f * normal_.z_ * negIntercept ); } Plane Plane::Transformed(const Matrix3& transform) const { Vector3 newNormal = (transform * normal_).Normalized(); Vector3 newPoint = newNormal * intercept_; return Plane(newNormal, newPoint); } Plane Plane::Transformed(const Matrix3x4& transform) const { Vector3 newNormal = (transform * normal_).Normalized(); Vector3 newPoint = transform * (normal_ * intercept_); return Plane(newNormal, newPoint); } Plane Plane::Transformed(const Matrix4& transform) const { return Plane(transform.Inverse().Transpose() * ToVector4()); } } <commit_msg>Perform all plane transforms through Matrix4 multiply to ensure correctness.<commit_after>// // Copyright (c) 2008-2013 the Urho3D project. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include "Precompiled.h" #include "Plane.h" namespace Urho3D { // Static initialization order can not be relied on, so do not use Vector3 constants const Plane Plane::UP(Vector3(0.0f, 1.0f, 0.0f), Vector3(0.0f, 0.0f, 0.0f)); void Plane::Transform(const Matrix3& transform) { *this = Transformed(transform); } void Plane::Transform(const Matrix3x4& transform) { *this = Transformed(transform); } void Plane::Transform(const Matrix4& transform) { *this = Transformed(transform); } Matrix3x4 Plane::ReflectionMatrix() const { float negIntercept = -intercept_; return Matrix3x4( -2.0f * normal_.x_ * normal_.x_ + 1.0f, -2.0f * normal_.x_ * normal_.y_, -2.0f * normal_.x_ * normal_.z_, -2.0f * normal_.x_ * negIntercept, -2.0f * normal_.y_ * normal_.x_ , -2.0f * normal_.y_ * normal_.y_ + 1.0f, -2.0f * normal_.y_ * normal_.z_, -2.0f * normal_.y_ * negIntercept, -2.0f * normal_.z_ * normal_.x_, -2.0f * normal_.z_ * normal_.y_, -2.0f * normal_.z_ * normal_.z_ + 1.0f, -2.0f * normal_.z_ * negIntercept ); } Plane Plane::Transformed(const Matrix3& transform) const { return Plane(Matrix4(transform).Inverse().Transpose() * ToVector4()); } Plane Plane::Transformed(const Matrix3x4& transform) const { return Plane(transform.ToMatrix4().Inverse().Transpose() * ToVector4()); } Plane Plane::Transformed(const Matrix4& transform) const { return Plane(transform.Inverse().Transpose() * ToVector4()); } } <|endoftext|>
<commit_before>6795d454-2fa5-11e5-8282-00012e3d3f12<commit_msg>6797f734-2fa5-11e5-bffc-00012e3d3f12<commit_after>6797f734-2fa5-11e5-bffc-00012e3d3f12<|endoftext|>
<commit_before>bef6e966-327f-11e5-b8a8-9cf387a8033e<commit_msg>befd3821-327f-11e5-a94d-9cf387a8033e<commit_after>befd3821-327f-11e5-a94d-9cf387a8033e<|endoftext|>
<commit_before>952827f0-2e4f-11e5-8cad-28cfe91dbc4b<commit_msg>952f0391-2e4f-11e5-93c1-28cfe91dbc4b<commit_after>952f0391-2e4f-11e5-93c1-28cfe91dbc4b<|endoftext|>
<commit_before>e6eb1263-313a-11e5-b35a-3c15c2e10482<commit_msg>e6f0f705-313a-11e5-8d00-3c15c2e10482<commit_after>e6f0f705-313a-11e5-8d00-3c15c2e10482<|endoftext|>
<commit_before>5bf67344-2d16-11e5-af21-0401358ea401<commit_msg>5bf67345-2d16-11e5-af21-0401358ea401<commit_after>5bf67345-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>16c5cde3-2e4f-11e5-a81a-28cfe91dbc4b<commit_msg>16cc9942-2e4f-11e5-83b4-28cfe91dbc4b<commit_after>16cc9942-2e4f-11e5-83b4-28cfe91dbc4b<|endoftext|>
<commit_before>#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <stdarg.h> #include <getopt.h> #include <ctype.h> #include <limits.h> #include <archive.h> #include <archive_entry.h> #include "main.h" static int LogLevel = Message; static const char *arg0 = 0; unsigned int opt_verbosity = 0; enum { RESET = 0, BOLD = 1, BLACK = 30, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, GRAY, WHITE = GRAY }; void log(int level, const char *msg, ...) { if (level < LogLevel) return; FILE *out = (level <= Message) ? stdout : stderr; if (level == Message) { if (isatty(fileno(out))) { fprintf(out, "\033[%d;%dm***\033[0;0m ", BOLD, GREEN); } else fprintf(out, "*** "); } va_list ap; va_start(ap, msg); vfprintf(out, msg, ap); va_end(ap); } static struct option long_opts[] = { { "help", no_argument, 0, 'h' }, { "version", no_argument, 0, -'v' }, { "db", required_argument, 0, 'd' }, { "install", no_argument, 0, 'i' }, { "dry", no_argument, 0, -'d' }, { "remove", no_argument, 0, 'r' }, { "info", no_argument, 0, 'I' }, { "list", no_argument, 0, 'L' }, { "missing", no_argument, 0, 'M' }, { "found", no_argument, 0, 'F' }, { "pkgs", no_argument, 0, 'P' }, { "verbose", no_argument, 0, 'v' }, { "rename", required_argument, 0, 'n' }, { "ld-append", required_argument, 0, -'A' }, { "ld-prepend", required_argument, 0, -'P' }, { "ld-delete", required_argument, 0, -'D' }, { "ld-insert", required_argument, 0, -'I' }, { "ld-clear", no_argument, 0, -'C' }, { "relink", no_argument, 0, -'R' }, { "json", no_argument, 0, -'J' }, { "fixpaths", no_argument, 0, -'F' }, { 0, 0, 0, 0 } }; static void help(int x) { FILE *out = x ? stderr : stdout; fprintf(out, "usage: %s [options] packages...\n", arg0); fprintf(out, "options:\n" " -h, --help show this message\n" " --version show version info\n" " -v, --verbose print more information\n" ); fprintf(out, "db management options:\n" " -d, --db=FILE set the database file to commit to\n" " -i, --install install packages to a dependency db\n" " -r, --remove remove packages from the database\n" " --dry do not commit the changes to the db\n" " --fixpaths fix up path entries as older dbs didn't handle\n" " ../ in paths (includes --relink)\n" ); fprintf(out, "db query options:\n" " -I, --info show general information about the db\n" " -L, --list list object files\n" " -M, --missing show the 'missing' table\n" " -F, --found show the 'found' table\n" " -P, --pkgs show the installed packages (and -v their files)\n" " -n, --rename=NAME rename the database\n" ); fprintf(out, "db library path options: (run --relink after these changes)\n" " --ld-prepend=DIR add or move a directory to the\n" " top of the trusted library path\n" " --ld-append=DIR add or move a directory to the\n" " bottom of the trusted library path\n" " --ld-delete=DIR remove a library path\n" " --ld-insert=N:DIR add or move a directro to position N\n" " of the trusted library path\n" " --ld-clear remove all library paths\n" " --relink relink all objects\n" ); exit(x); } static void version(int x) { printf("pkgdepdb " FULL_VERSION_STRING "\n"); exit(x); } // don't ask class ArgArg { public: bool on; bool *mode; std::vector<std::string> arg; ArgArg(bool *om) { mode = om; on = false; } operator bool() const { return on; } inline bool operator!() const { return !on; } inline void operator=(bool on) { this->on = on; } inline void operator=(const char *arg) { on = true; this->arg.push_back(arg); } inline void operator=(std::string &&arg) { on = true; this->arg.push_back(std::move(arg)); } }; bool db_store_json(DB *db, const std::string& filename); int main(int argc, char **argv) { arg0 = argv[0]; if (argc < 2) help(1); std::string dbfile, newname; bool do_install = false; bool do_delete = false; bool has_db = false; bool modified = false; bool show_info = false; bool show_list = false; bool show_missing = false; bool show_found = false; bool show_packages = false; bool do_rename = false; bool do_relink = false; bool do_fixpaths = false; bool dryrun = false; bool use_json = false; bool oldmode = true; // library path options ArgArg ld_append (&oldmode), ld_prepend(&oldmode), ld_delete (&oldmode), ld_clear (&oldmode); std::vector<std::tuple<std::string,size_t>> ld_insert; for (;;) { int opt_index = 0; int c = getopt_long(argc, argv, "hird:ILMFPvn:", long_opts, &opt_index); if (c == -1) break; switch (c) { case 'h': help(0); break; case -'v': version(0); break; case 'd': oldmode = false; has_db = true; dbfile = optarg; break; case 'n': oldmode = false; do_rename = true; newname = optarg; break; case -'d': dryrun = true; break; case 'v': ++opt_verbosity; break; case 'i': oldmode = false; do_install = true; break; case 'r': oldmode = false; do_delete = true; break; case 'I': oldmode = false; show_info = true; break; case 'L': oldmode = false; show_list = true; break; case 'M': oldmode = false; show_missing = true; break; case 'F': oldmode = false; show_found = true; break; case 'P': oldmode = false; show_packages = true; break; case -'R': oldmode = false; do_relink = true; break; case -'F': oldmode = false; do_fixpaths = true; break; case -'A': ld_append = optarg; break; case -'P': ld_prepend = optarg; break; case -'D': ld_delete = optarg; break; case -'C': ld_clear = true; break; case -'I': { oldmode = false; std::string str(optarg); if (!isdigit(str[0])) { log(Error, "--ld-insert format wrong: has to start with a number\n"); help(1); return 1; } size_t colon = str.find_first_of(':'); if (std::string::npos == colon) { log(Error, "--ld-insert format wrong, no colon found\n"); help(1); return 1; } ld_insert.push_back(std::make_tuple(std::move(str.substr(colon+1)), strtoul(str.c_str(), nullptr, 0))); break; } case -'J': use_json = true; break; case ':': case '?': help(1); break; } } if (do_fixpaths) do_relink = true; if (do_install && do_delete) { log(Error, "--install and --remove are mutually exclusive\n"); help(1); } if (do_delete && optind >= argc) { log(Error, "--remove requires a list of package names\n"); help(1); } if (do_install && optind >= argc) { log(Error, "--install requires a list of package archive files\n"); help(1); } std::vector<Package*> packages; if (oldmode) { // non-database mode! while (optind < argc) { Package *package = Package::open(argv[optind++]); for (auto &obj : package->objects) { const char *objdir = obj->dirname.c_str(); const char *objname = obj->basename.c_str(); for (auto &need : obj->needed) { printf("%s : %s/%s NEEDS %s\n", package->name.c_str(), objdir, objname, need.c_str()); } } delete package; } return 0; } if (!do_delete && optind < argc) { if (do_install) log(Message, "loading packages...\n"); while (optind < argc) { if (do_install) log(Print, " %s\n", argv[optind]); Package *package = Package::open(argv[optind]); if (!package) log(Error, "error reading package %s\n", argv[optind]); else { if (do_install) packages.push_back(package); else { package->show_needed(); delete package; } } ++optind; } if (do_install) log(Message, "packages loaded...\n"); } std::unique_ptr<DB> db(new DB); if (has_db) { if (!db->read(dbfile)) { log(Error, "failed to read database\n"); return 1; } } if (do_rename) { modified = true; db->name = newname; } if (ld_append) { for (auto &dir : ld_append.arg) modified = db->ld_append(dir) || modified; } if (ld_prepend) { for (auto &dir : ld_prepend.arg) modified = db->ld_prepend(dir) || modified; } if (ld_delete) { for (auto &dir : ld_delete.arg) modified = db->ld_delete(dir) || modified; } for (auto &ins : ld_insert) { modified = db->ld_insert(std::get<0>(ins), std::get<1>(ins)) || modified; } if (ld_clear) modified = db->ld_clear() || modified; if (do_fixpaths) { modified = true; log(Message, "fixing up path entries\n"); db->fix_paths(); } if (do_install && packages.size()) { log(Message, "installing packages\n"); for (auto pkg : packages) { modified = true; if (!db->install_package(std::move(pkg))) { printf("failed to commit package %s to database\n", pkg->name.c_str()); break; } } } if (do_delete) { while (optind < argc) { log(Message, "uninstalling: %s\n", argv[optind]); modified = true; if (!db->delete_package(argv[optind])) { log(Error, "error uninstalling package: %s\n", argv[optind]); return 1; } ++optind; } } if (do_relink) { modified = true; log(Message, "relinking everything\n"); db->relink_all(); } if (show_info) db->show_info(); if (show_packages) db->show_packages(); if (show_list) db->show_objects(); if (show_missing) db->show_missing(); if (show_found) db->show_found(); if (!dryrun && modified && has_db) { if (use_json) db_store_json(db.get(), dbfile); else if (!db->store(dbfile)) log(Error, "failed to write to the database\n"); } return 0; } <commit_msg>better wording...<commit_after>#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <stdarg.h> #include <getopt.h> #include <ctype.h> #include <limits.h> #include <archive.h> #include <archive_entry.h> #include "main.h" static int LogLevel = Message; static const char *arg0 = 0; unsigned int opt_verbosity = 0; enum { RESET = 0, BOLD = 1, BLACK = 30, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, GRAY, WHITE = GRAY }; void log(int level, const char *msg, ...) { if (level < LogLevel) return; FILE *out = (level <= Message) ? stdout : stderr; if (level == Message) { if (isatty(fileno(out))) { fprintf(out, "\033[%d;%dm***\033[0;0m ", BOLD, GREEN); } else fprintf(out, "*** "); } va_list ap; va_start(ap, msg); vfprintf(out, msg, ap); va_end(ap); } static struct option long_opts[] = { { "help", no_argument, 0, 'h' }, { "version", no_argument, 0, -'v' }, { "db", required_argument, 0, 'd' }, { "install", no_argument, 0, 'i' }, { "dry", no_argument, 0, -'d' }, { "remove", no_argument, 0, 'r' }, { "info", no_argument, 0, 'I' }, { "list", no_argument, 0, 'L' }, { "missing", no_argument, 0, 'M' }, { "found", no_argument, 0, 'F' }, { "pkgs", no_argument, 0, 'P' }, { "verbose", no_argument, 0, 'v' }, { "rename", required_argument, 0, 'n' }, { "ld-append", required_argument, 0, -'A' }, { "ld-prepend", required_argument, 0, -'P' }, { "ld-delete", required_argument, 0, -'D' }, { "ld-insert", required_argument, 0, -'I' }, { "ld-clear", no_argument, 0, -'C' }, { "relink", no_argument, 0, -'R' }, { "json", no_argument, 0, -'J' }, { "fixpaths", no_argument, 0, -'F' }, { 0, 0, 0, 0 } }; static void help(int x) { FILE *out = x ? stderr : stdout; fprintf(out, "usage: %s [options] packages...\n", arg0); fprintf(out, "options:\n" " -h, --help show this message\n" " --version show version info\n" " -v, --verbose print more information\n" ); fprintf(out, "db management options:\n" " -d, --db=FILE set the database file to commit to\n" " -i, --install install packages to a dependency db\n" " -r, --remove remove packages from the database\n" " --dry do not commit the changes to the db\n" " --fixpaths fix up path entries as older versions didn't\n" " handle ../ in paths (includes --relink)\n" ); fprintf(out, "db query options:\n" " -I, --info show general information about the db\n" " -L, --list list object files\n" " -M, --missing show the 'missing' table\n" " -F, --found show the 'found' table\n" " -P, --pkgs show the installed packages (and -v their files)\n" " -n, --rename=NAME rename the database\n" ); fprintf(out, "db library path options: (run --relink after these changes)\n" " --ld-prepend=DIR add or move a directory to the\n" " top of the trusted library path\n" " --ld-append=DIR add or move a directory to the\n" " bottom of the trusted library path\n" " --ld-delete=DIR remove a library path\n" " --ld-insert=N:DIR add or move a directro to position N\n" " of the trusted library path\n" " --ld-clear remove all library paths\n" " --relink relink all objects\n" ); exit(x); } static void version(int x) { printf("pkgdepdb " FULL_VERSION_STRING "\n"); exit(x); } // don't ask class ArgArg { public: bool on; bool *mode; std::vector<std::string> arg; ArgArg(bool *om) { mode = om; on = false; } operator bool() const { return on; } inline bool operator!() const { return !on; } inline void operator=(bool on) { this->on = on; } inline void operator=(const char *arg) { on = true; this->arg.push_back(arg); } inline void operator=(std::string &&arg) { on = true; this->arg.push_back(std::move(arg)); } }; bool db_store_json(DB *db, const std::string& filename); int main(int argc, char **argv) { arg0 = argv[0]; if (argc < 2) help(1); std::string dbfile, newname; bool do_install = false; bool do_delete = false; bool has_db = false; bool modified = false; bool show_info = false; bool show_list = false; bool show_missing = false; bool show_found = false; bool show_packages = false; bool do_rename = false; bool do_relink = false; bool do_fixpaths = false; bool dryrun = false; bool use_json = false; bool oldmode = true; // library path options ArgArg ld_append (&oldmode), ld_prepend(&oldmode), ld_delete (&oldmode), ld_clear (&oldmode); std::vector<std::tuple<std::string,size_t>> ld_insert; for (;;) { int opt_index = 0; int c = getopt_long(argc, argv, "hird:ILMFPvn:", long_opts, &opt_index); if (c == -1) break; switch (c) { case 'h': help(0); break; case -'v': version(0); break; case 'd': oldmode = false; has_db = true; dbfile = optarg; break; case 'n': oldmode = false; do_rename = true; newname = optarg; break; case -'d': dryrun = true; break; case 'v': ++opt_verbosity; break; case 'i': oldmode = false; do_install = true; break; case 'r': oldmode = false; do_delete = true; break; case 'I': oldmode = false; show_info = true; break; case 'L': oldmode = false; show_list = true; break; case 'M': oldmode = false; show_missing = true; break; case 'F': oldmode = false; show_found = true; break; case 'P': oldmode = false; show_packages = true; break; case -'R': oldmode = false; do_relink = true; break; case -'F': oldmode = false; do_fixpaths = true; break; case -'A': ld_append = optarg; break; case -'P': ld_prepend = optarg; break; case -'D': ld_delete = optarg; break; case -'C': ld_clear = true; break; case -'I': { oldmode = false; std::string str(optarg); if (!isdigit(str[0])) { log(Error, "--ld-insert format wrong: has to start with a number\n"); help(1); return 1; } size_t colon = str.find_first_of(':'); if (std::string::npos == colon) { log(Error, "--ld-insert format wrong, no colon found\n"); help(1); return 1; } ld_insert.push_back(std::make_tuple(std::move(str.substr(colon+1)), strtoul(str.c_str(), nullptr, 0))); break; } case -'J': use_json = true; break; case ':': case '?': help(1); break; } } if (do_fixpaths) do_relink = true; if (do_install && do_delete) { log(Error, "--install and --remove are mutually exclusive\n"); help(1); } if (do_delete && optind >= argc) { log(Error, "--remove requires a list of package names\n"); help(1); } if (do_install && optind >= argc) { log(Error, "--install requires a list of package archive files\n"); help(1); } std::vector<Package*> packages; if (oldmode) { // non-database mode! while (optind < argc) { Package *package = Package::open(argv[optind++]); for (auto &obj : package->objects) { const char *objdir = obj->dirname.c_str(); const char *objname = obj->basename.c_str(); for (auto &need : obj->needed) { printf("%s : %s/%s NEEDS %s\n", package->name.c_str(), objdir, objname, need.c_str()); } } delete package; } return 0; } if (!do_delete && optind < argc) { if (do_install) log(Message, "loading packages...\n"); while (optind < argc) { if (do_install) log(Print, " %s\n", argv[optind]); Package *package = Package::open(argv[optind]); if (!package) log(Error, "error reading package %s\n", argv[optind]); else { if (do_install) packages.push_back(package); else { package->show_needed(); delete package; } } ++optind; } if (do_install) log(Message, "packages loaded...\n"); } std::unique_ptr<DB> db(new DB); if (has_db) { if (!db->read(dbfile)) { log(Error, "failed to read database\n"); return 1; } } if (do_rename) { modified = true; db->name = newname; } if (ld_append) { for (auto &dir : ld_append.arg) modified = db->ld_append(dir) || modified; } if (ld_prepend) { for (auto &dir : ld_prepend.arg) modified = db->ld_prepend(dir) || modified; } if (ld_delete) { for (auto &dir : ld_delete.arg) modified = db->ld_delete(dir) || modified; } for (auto &ins : ld_insert) { modified = db->ld_insert(std::get<0>(ins), std::get<1>(ins)) || modified; } if (ld_clear) modified = db->ld_clear() || modified; if (do_fixpaths) { modified = true; log(Message, "fixing up path entries\n"); db->fix_paths(); } if (do_install && packages.size()) { log(Message, "installing packages\n"); for (auto pkg : packages) { modified = true; if (!db->install_package(std::move(pkg))) { printf("failed to commit package %s to database\n", pkg->name.c_str()); break; } } } if (do_delete) { while (optind < argc) { log(Message, "uninstalling: %s\n", argv[optind]); modified = true; if (!db->delete_package(argv[optind])) { log(Error, "error uninstalling package: %s\n", argv[optind]); return 1; } ++optind; } } if (do_relink) { modified = true; log(Message, "relinking everything\n"); db->relink_all(); } if (show_info) db->show_info(); if (show_packages) db->show_packages(); if (show_list) db->show_objects(); if (show_missing) db->show_missing(); if (show_found) db->show_found(); if (!dryrun && modified && has_db) { if (use_json) db_store_json(db.get(), dbfile); else if (!db->store(dbfile)) log(Error, "failed to write to the database\n"); } return 0; } <|endoftext|>
<commit_before>2c22bcca-2e4f-11e5-9600-28cfe91dbc4b<commit_msg>2c2a472e-2e4f-11e5-b296-28cfe91dbc4b<commit_after>2c2a472e-2e4f-11e5-b296-28cfe91dbc4b<|endoftext|>
<commit_before>6c6208f5-2e4f-11e5-8f96-28cfe91dbc4b<commit_msg>6c68ae19-2e4f-11e5-b0fd-28cfe91dbc4b<commit_after>6c68ae19-2e4f-11e5-b0fd-28cfe91dbc4b<|endoftext|>
<commit_before>#include "chip8.h" chip8 Chip8; SDL_Window *window = nullptr; SDL_Renderer *renderer = nullptr; static const uint8_t SCREEN_WIDTH = 64; static const uint8_t SCREEN_HEIGHT = 32; static const uint8_t PIXEL_SIZE = 12; // Temporary pixel buffer uint32_t pixels[2048]; // Chip8 Keypad uint8_t keymap[16] = { SDLK_x, SDLK_1, SDLK_2, SDLK_3, SDLK_q, SDLK_w, SDLK_e, SDLK_a, SDLK_s, SDLK_d, SDLK_z, SDLK_c, SDLK_4, SDLK_r, SDLK_f, SDLK_v, }; void init_SDL() { //Initialize all SDL subsystems SDL_Init(SDL_INIT_VIDEO); window = SDL_CreateWindow("Chip8 Emulator", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 512, 256, NULL); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED); } int main(int argc, char **argv) { if (argc < 2) { printf("Usage: Chip8.exe chip8application\n\n"); return 1; } init_SDL(); // Load game load: if (!Chip8.loadApplication(argv[1])) return 1; SDL_Event e; bool running = true; // Emulation loop while (running) { // Process SDL events while (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) exit(0); // Process keydown events if (e.type == SDL_KEYDOWN) { if (e.key.keysym.sym == SDLK_ESCAPE) exit(0); if (e.key.keysym.sym == SDLK_F1) goto load; // *gasp*, a goto statement! // Used to reset/reload ROM for (int i = 0; i < 16; ++i) { if (e.key.keysym.sym == keymap[i]) { Chip8.key[i] = 1; } } } // Process keyup events if (e.type == SDL_KEYUP) { for (int i = 0; i < 16; ++i) { if (e.key.keysym.sym == keymap[i]) { Chip8.key[i] = 0; } } } } Chip8.emulateCycle(); // If draw occurred, redraw SDL screen if (Chip8.drawFlag) { // Clear screen SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); SDL_RenderClear(renderer); // Draw screen SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); SDL_Rect *destRect = new SDL_Rect; destRect->x = 0; destRect->y = 0; destRect->w = 8; destRect->h = 8; for (int y = 0; y < 32; y++) { for (int x = 0; x < 64; x++) { if (Chip8.gfx[(y * 64) + x] == 1) { destRect->x = x * 8; destRect->y = y * 8; SDL_RenderFillRect(renderer, destRect); } } } delete destRect; SDL_RenderPresent(renderer); Chip8.drawFlag = false; } // Sleep to slow down emulation speed std::this_thread::sleep_for(std::chrono::microseconds(1200)); } SDL_Quit(); }<commit_msg>Delete main.cpp<commit_after><|endoftext|>
<commit_before>8fd04950-2d14-11e5-af21-0401358ea401<commit_msg>8fd04951-2d14-11e5-af21-0401358ea401<commit_after>8fd04951-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>decceca3-313a-11e5-be43-3c15c2e10482<commit_msg>ded2f114-313a-11e5-ab99-3c15c2e10482<commit_after>ded2f114-313a-11e5-ab99-3c15c2e10482<|endoftext|>
<commit_before>5c9216e4-5216-11e5-afda-6c40088e03e4<commit_msg>5c98e924-5216-11e5-a0fd-6c40088e03e4<commit_after>5c98e924-5216-11e5-a0fd-6c40088e03e4<|endoftext|>
<commit_before>2650d4ee-2e3a-11e5-92b8-c03896053bdd<commit_msg>265f7d94-2e3a-11e5-92de-c03896053bdd<commit_after>265f7d94-2e3a-11e5-92de-c03896053bdd<|endoftext|>
<commit_before>a56927c6-35ca-11e5-a089-6c40088e03e4<commit_msg>a56ffebe-35ca-11e5-8fad-6c40088e03e4<commit_after>a56ffebe-35ca-11e5-8fad-6c40088e03e4<|endoftext|>
<commit_before>0f1eac73-2748-11e6-b1cb-e0f84713e7b8<commit_msg>I hope I am done<commit_after>0f2a29b5-2748-11e6-95f2-e0f84713e7b8<|endoftext|>
<commit_before>/* Copyright (C) 2003 MySQL AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "NdbImpl.hpp" #include <NdbReceiver.hpp> #include "NdbDictionaryImpl.hpp" #include <NdbRecAttr.hpp> #include <AttributeHeader.hpp> #include <NdbConnection.hpp> NdbReceiver::NdbReceiver(Ndb *aNdb) : theMagicNumber(0), m_ndb(aNdb), m_id(NdbObjectIdMap::InvalidId), m_type(NDB_UNINITIALIZED), m_owner(0) { theCurrentRecAttr = theFirstRecAttr = 0; } void NdbReceiver::init(ReceiverType type, void* owner, bool keyInfo) { theMagicNumber = 0x11223344; m_type = type; m_owner = owner; if (m_id == NdbObjectIdMap::InvalidId) { if (m_ndb) m_id = m_ndb->theNdbObjectIdMap->map(this); } theFirstRecAttr = NULL; theCurrentRecAttr = NULL; m_key_info = (keyInfo ? 1 : 0); m_defined_rows = 0; } void NdbReceiver::release(){ NdbRecAttr* tRecAttr = theFirstRecAttr; while (tRecAttr != NULL) { NdbRecAttr* tSaveRecAttr = tRecAttr; tRecAttr = tRecAttr->next(); m_ndb->releaseRecAttr(tSaveRecAttr); } theFirstRecAttr = NULL; theCurrentRecAttr = NULL; } NdbReceiver::~NdbReceiver() { if (m_id != NdbObjectIdMap::InvalidId) { m_ndb->theNdbObjectIdMap->unmap(m_id, this); } } NdbRecAttr * NdbReceiver::getValue(const NdbColumnImpl* tAttrInfo, char * user_dst_ptr){ NdbRecAttr* tRecAttr = m_ndb->getRecAttr(); if(tRecAttr && !tRecAttr->setup(tAttrInfo, user_dst_ptr)){ if (theFirstRecAttr == NULL) theFirstRecAttr = tRecAttr; else theCurrentRecAttr->next(tRecAttr); theCurrentRecAttr = tRecAttr; tRecAttr->next(NULL); return tRecAttr; } if(tRecAttr){ m_ndb->releaseRecAttr(tRecAttr); } return 0; } #define KEY_ATTR_ID (~0) void NdbReceiver::do_get_value(NdbReceiver * org, Uint32 rows, Uint32 key_size){ m_defined_rows = rows; m_rows = new NdbRecAttr*[rows + 1]; m_rows[rows] = 0; NdbColumnImpl key; if(key_size){ key.m_attrId = KEY_ATTR_ID; key.m_arraySize = key_size+1; key.m_attrSize = 4; key.m_nullable = true; // So that receive works w.r.t KEYINFO20 } for(Uint32 i = 0; i<rows; i++){ NdbRecAttr * prev = theCurrentRecAttr; // Put key-recAttr fir on each row if(key_size && !getValue(&key, (char*)0)){ abort(); return ; // -1 } NdbRecAttr* tRecAttr = org->theFirstRecAttr; while(tRecAttr != 0){ if(getValue(&NdbColumnImpl::getImpl(*tRecAttr->m_column), (char*)0)) tRecAttr = tRecAttr->next(); else break; } if(tRecAttr){ abort(); return ;// -1; } // Store first recAttr for each row in m_rows[i] if(prev){ m_rows[i] = prev->next(); } else { m_rows[i] = theFirstRecAttr; } } prepareSend(); return ; //0; } void NdbReceiver::copyout(NdbReceiver & dstRec){ NdbRecAttr* src = m_rows[m_current_row++]; NdbRecAttr* dst = dstRec.theFirstRecAttr; Uint32 tmp = m_key_info; if(tmp > 0){ src = src->next(); } while(dst){ Uint32 len = ((src->theAttrSize * src->theArraySize)+3)/4; dst->receive_data((Uint32*)src->aRef(), len); src = src->next(); dst = dst->next(); } } int NdbReceiver::execTRANSID_AI(const Uint32* aDataPtr, Uint32 aLength) { bool ok = true; NdbRecAttr* currRecAttr = theCurrentRecAttr; NdbRecAttr* prevRecAttr = currRecAttr; for (Uint32 used = 0; used < aLength ; used++){ AttributeHeader ah(* aDataPtr++); const Uint32 tAttrId = ah.getAttributeId(); const Uint32 tAttrSize = ah.getDataSize(); /** * Set all results to NULL if not found... */ while(currRecAttr && currRecAttr->attrId() != tAttrId){ ok &= currRecAttr->setNULL(); prevRecAttr = currRecAttr; currRecAttr = currRecAttr->next(); } if(ok && currRecAttr && currRecAttr->receive_data(aDataPtr, tAttrSize)){ used += tAttrSize; aDataPtr += tAttrSize; prevRecAttr = currRecAttr; currRecAttr = currRecAttr->next(); } else { ndbout_c("%p: ok: %d tAttrId: %d currRecAttr: %p", this,ok, tAttrId, currRecAttr); abort(); return -1; } } theCurrentRecAttr = currRecAttr; /** * Update m_received_result_length */ Uint32 tmp = m_received_result_length + aLength; m_received_result_length = tmp; return (tmp == m_expected_result_length ? 1 : 0); } int NdbReceiver::execKEYINFO20(Uint32 info, const Uint32* aDataPtr, Uint32 aLength) { NdbRecAttr* currRecAttr = m_rows[m_current_row++]; assert(currRecAttr->attrId() == KEY_ATTR_ID); currRecAttr->receive_data(aDataPtr, aLength + 1); /** * Save scanInfo in the end of keyinfo */ ((Uint32*)currRecAttr->aRef())[aLength] = info; Uint32 tmp = m_received_result_length + aLength; m_received_result_length = tmp; return (tmp == m_expected_result_length ? 1 : 0); } <commit_msg>wl1671 - bug fix, null with scans<commit_after>/* Copyright (C) 2003 MySQL AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "NdbImpl.hpp" #include <NdbReceiver.hpp> #include "NdbDictionaryImpl.hpp" #include <NdbRecAttr.hpp> #include <AttributeHeader.hpp> #include <NdbConnection.hpp> NdbReceiver::NdbReceiver(Ndb *aNdb) : theMagicNumber(0), m_ndb(aNdb), m_id(NdbObjectIdMap::InvalidId), m_type(NDB_UNINITIALIZED), m_owner(0) { theCurrentRecAttr = theFirstRecAttr = 0; } void NdbReceiver::init(ReceiverType type, void* owner, bool keyInfo) { theMagicNumber = 0x11223344; m_type = type; m_owner = owner; if (m_id == NdbObjectIdMap::InvalidId) { if (m_ndb) m_id = m_ndb->theNdbObjectIdMap->map(this); } theFirstRecAttr = NULL; theCurrentRecAttr = NULL; m_key_info = (keyInfo ? 1 : 0); m_defined_rows = 0; } void NdbReceiver::release(){ NdbRecAttr* tRecAttr = theFirstRecAttr; while (tRecAttr != NULL) { NdbRecAttr* tSaveRecAttr = tRecAttr; tRecAttr = tRecAttr->next(); m_ndb->releaseRecAttr(tSaveRecAttr); } theFirstRecAttr = NULL; theCurrentRecAttr = NULL; } NdbReceiver::~NdbReceiver() { if (m_id != NdbObjectIdMap::InvalidId) { m_ndb->theNdbObjectIdMap->unmap(m_id, this); } } NdbRecAttr * NdbReceiver::getValue(const NdbColumnImpl* tAttrInfo, char * user_dst_ptr){ NdbRecAttr* tRecAttr = m_ndb->getRecAttr(); if(tRecAttr && !tRecAttr->setup(tAttrInfo, user_dst_ptr)){ if (theFirstRecAttr == NULL) theFirstRecAttr = tRecAttr; else theCurrentRecAttr->next(tRecAttr); theCurrentRecAttr = tRecAttr; tRecAttr->next(NULL); return tRecAttr; } if(tRecAttr){ m_ndb->releaseRecAttr(tRecAttr); } return 0; } #define KEY_ATTR_ID (~0) void NdbReceiver::do_get_value(NdbReceiver * org, Uint32 rows, Uint32 key_size){ m_defined_rows = rows; m_rows = new NdbRecAttr*[rows + 1]; m_rows[rows] = 0; NdbColumnImpl key; if(key_size){ key.m_attrId = KEY_ATTR_ID; key.m_arraySize = key_size+1; key.m_attrSize = 4; key.m_nullable = true; // So that receive works w.r.t KEYINFO20 } for(Uint32 i = 0; i<rows; i++){ NdbRecAttr * prev = theCurrentRecAttr; // Put key-recAttr fir on each row if(key_size && !getValue(&key, (char*)0)){ abort(); return ; // -1 } NdbRecAttr* tRecAttr = org->theFirstRecAttr; while(tRecAttr != 0){ if(getValue(&NdbColumnImpl::getImpl(*tRecAttr->m_column), (char*)0)) tRecAttr = tRecAttr->next(); else break; } if(tRecAttr){ abort(); return ;// -1; } // Store first recAttr for each row in m_rows[i] if(prev){ m_rows[i] = prev->next(); } else { m_rows[i] = theFirstRecAttr; } } prepareSend(); return ; //0; } void NdbReceiver::copyout(NdbReceiver & dstRec){ NdbRecAttr* src = m_rows[m_current_row++]; NdbRecAttr* dst = dstRec.theFirstRecAttr; Uint32 tmp = m_key_info; if(tmp > 0){ src = src->next(); } while(dst){ Uint32 len = ((src->theAttrSize * src->theArraySize)+3)/4; dst->receive_data((Uint32*)src->aRef(), src->isNULL() ? 0 : len); src = src->next(); dst = dst->next(); } } int NdbReceiver::execTRANSID_AI(const Uint32* aDataPtr, Uint32 aLength) { bool ok = true; NdbRecAttr* currRecAttr = theCurrentRecAttr; NdbRecAttr* prevRecAttr = currRecAttr; for (Uint32 used = 0; used < aLength ; used++){ AttributeHeader ah(* aDataPtr++); const Uint32 tAttrId = ah.getAttributeId(); const Uint32 tAttrSize = ah.getDataSize(); /** * Set all results to NULL if not found... */ while(currRecAttr && currRecAttr->attrId() != tAttrId){ ok &= currRecAttr->setNULL(); prevRecAttr = currRecAttr; currRecAttr = currRecAttr->next(); } if(ok && currRecAttr && currRecAttr->receive_data(aDataPtr, tAttrSize)){ used += tAttrSize; aDataPtr += tAttrSize; prevRecAttr = currRecAttr; currRecAttr = currRecAttr->next(); } else { ndbout_c("%p: ok: %d tAttrId: %d currRecAttr: %p", this,ok, tAttrId, currRecAttr); abort(); return -1; } } theCurrentRecAttr = currRecAttr; /** * Update m_received_result_length */ Uint32 tmp = m_received_result_length + aLength; m_received_result_length = tmp; return (tmp == m_expected_result_length ? 1 : 0); } int NdbReceiver::execKEYINFO20(Uint32 info, const Uint32* aDataPtr, Uint32 aLength) { NdbRecAttr* currRecAttr = m_rows[m_current_row++]; assert(currRecAttr->attrId() == KEY_ATTR_ID); currRecAttr->receive_data(aDataPtr, aLength + 1); /** * Save scanInfo in the end of keyinfo */ ((Uint32*)currRecAttr->aRef())[aLength] = info; Uint32 tmp = m_received_result_length + aLength; m_received_result_length = tmp; return (tmp == m_expected_result_length ? 1 : 0); } <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <map> #include <fstream> #include <string> #include <iterator> #include <functional> #include <algorithm> #include <sstream> std::string trim_begin(const std::string& str) { auto alpha = std::find_if_not(str.begin(), str.end(), ::isspace); return str.substr(std::distance(str.begin(), alpha)); } std::string trim_end(const std::string& str) { auto alpha = std::find_if_not(str.rbegin(), str.rend(), ::isspace).base(); return str.substr(0, std::distance(str.begin(), alpha)); } std::vector<std::string> extract_words(const std::string& str) { std::vector<std::string> words; std::istringstream is(str); std::copy( std::istream_iterator<std::string>(is), std::istream_iterator<std::string>(), std::back_inserter(words)); return words; } class sentence_file_reader { std::ifstream ifs; static const size_t BUFFER_SIZE = 16 * 1024; char buff[BUFFER_SIZE]; public: sentence_file_reader(const char *filename) : ifs(filename, std::ios::in) {} ~sentence_file_reader() { ifs.close(); } std::string get_next_sentence() { ifs.getline(buff, BUFFER_SIZE, '.'); return trim_begin(trim_end(buff)); } bool has_more() { return ifs.good(); } }; struct word_node { word_node(const std::string& name) : word_name(name) {} std::string word_name; std::vector<word_node*> lefts; std::vector<word_node*> rights; }; struct word_graph { std::map<std::string, word_node*> word_nodes; word_node *head; word_node *get_or_create(std::string name) { auto name_exists = word_nodes.equal_range(name); if (name_exists.first == name_exists.second) { word_node *name_node = new word_node(name); return word_nodes.insert(name_exists.second, std::make_pair(name, name_node))->second; } return name_exists.first->second; } void make_link(const std::string& a, const std::string& b) { word_node *a_node = get_or_create(a); word_node *b_node = get_or_create(b); a_node->rights.push_back(b_node); b_node->lefts.push_back(a_node); } }; int main() { std::ios::ios_base::sync_with_stdio(false); std::cout << "Hello World!\n"; word_graph graph; sentence_file_reader cfr("test.txt"); std::string str; while (cfr.has_more()) { std::string sentence = cfr.get_next_sentence(); std::vector<std::string> words = extract_words(sentence); if (words.size() > 1) { graph.make_link(words[0], words[1]); for (size_t i = 1, j = 2; j < words.size(); ++j) { graph.make_link(words[i], words[j]); } } } for (auto &kv : graph.word_nodes) { std::cout << kv.first << "\n- left: "; for (auto &w_node : kv.second->lefts) { std::cout << w_node->word_name << " "; } std::cout << "\n- right: "; for (auto &w_node : kv.second->rights) { std::cout << w_node->word_name << " "; } std::cout << std::endl; } return 0; } <commit_msg>Graph building fix<commit_after>#include <iostream> #include <vector> #include <map> #include <fstream> #include <string> #include <iterator> #include <functional> #include <algorithm> #include <sstream> std::string trim_begin(const std::string& str) { auto alpha = std::find_if_not(str.begin(), str.end(), ::isspace); return str.substr(std::distance(str.begin(), alpha)); } std::string trim_end(const std::string& str) { auto alpha = std::find_if_not(str.rbegin(), str.rend(), ::isspace).base(); return str.substr(0, std::distance(str.begin(), alpha)); } std::vector<std::string> extract_words(const std::string& str) { std::vector<std::string> words; std::istringstream is(str); std::copy( std::istream_iterator<std::string>(is), std::istream_iterator<std::string>(), std::back_inserter(words)); return words; } class sentence_file_reader { std::ifstream ifs; static const size_t BUFFER_SIZE = 16 * 1024; char buff[BUFFER_SIZE]; public: sentence_file_reader(const char *filename) : ifs(filename, std::ios::in) {} ~sentence_file_reader() { ifs.close(); } std::string get_next_sentence() { ifs.getline(buff, BUFFER_SIZE, '.'); return trim_begin(trim_end(buff)); } bool has_more() { return ifs.good(); } }; struct word_node { word_node(const std::string& name) : word_name(name) {} std::string word_name; std::map<word_node*, size_t> lefts; std::map<word_node*, size_t> rights; }; struct word_graph { std::map<std::string, word_node*> word_nodes; word_node *head; word_node *get_or_create(std::string name) { auto name_exists = word_nodes.equal_range(name); if (name_exists.first == name_exists.second) { word_node *name_node = new word_node(name); return word_nodes.insert(name_exists.second, std::make_pair(name, name_node))->second; } return name_exists.first->second; } void make_link(const std::string& a, const std::string& b) { word_node *a_node = get_or_create(a); word_node *b_node = get_or_create(b); a_node->rights[b_node]++; b_node->lefts[a_node]++; } }; int main() { std::ios::ios_base::sync_with_stdio(false); std::cout << "Hello World!\n"; word_graph graph; sentence_file_reader cfr("test.txt"); std::string str; while (cfr.has_more()) { std::string sentence = cfr.get_next_sentence(); std::vector<std::string> words = extract_words(sentence); if (words.size() > 1) { graph.make_link(words[0], words[1]); for (size_t i = 1, j = 2; j < words.size(); ++i, ++j) { graph.make_link(words[i], words[j]); } } } for (auto &kv : graph.word_nodes) { std::cout << kv.first << "\n- left: "; for (auto &w_node_cnt : kv.second->lefts) { std::cout << w_node_cnt.first->word_name << ":" << w_node_cnt.second << " "; } std::cout << "\n- right: "; for (auto &w_node_cnt : kv.second->rights) { std::cout << w_node_cnt.first->word_name << ":" << w_node_cnt.second << " "; } std::cout << std::endl; } return 0; }<|endoftext|>
<commit_before>b00978b3-2e4f-11e5-a1fc-28cfe91dbc4b<commit_msg>b0118c3d-2e4f-11e5-963c-28cfe91dbc4b<commit_after>b0118c3d-2e4f-11e5-963c-28cfe91dbc4b<|endoftext|>
<commit_before>8d6dfdaa-2d14-11e5-af21-0401358ea401<commit_msg>8d6dfdab-2d14-11e5-af21-0401358ea401<commit_after>8d6dfdab-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>5f2135dc-ad5b-11e7-ad93-ac87a332f658<commit_msg>my cat is cute<commit_after>5fa325e8-ad5b-11e7-b20e-ac87a332f658<|endoftext|>
<commit_before>f83d067a-585a-11e5-9898-6c40088e03e4<commit_msg>f8439466-585a-11e5-8798-6c40088e03e4<commit_after>f8439466-585a-11e5-8798-6c40088e03e4<|endoftext|>
<commit_before>afd85d70-327f-11e5-93c1-9cf387a8033e<commit_msg>afdf7bfd-327f-11e5-ab27-9cf387a8033e<commit_after>afdf7bfd-327f-11e5-ab27-9cf387a8033e<|endoftext|>
<commit_before>9d2d2491-2747-11e6-b62e-e0f84713e7b8<commit_msg>new flies<commit_after>9d3d72c0-2747-11e6-b023-e0f84713e7b8<|endoftext|>
<commit_before>227508d0-2f67-11e5-ae70-6c40088e03e4<commit_msg>227e3a14-2f67-11e5-a6d9-6c40088e03e4<commit_after>227e3a14-2f67-11e5-a6d9-6c40088e03e4<|endoftext|>
<commit_before>#include <QCoreApplication> #include <QObject> #include <QThread> #include <QEventLoop> #include <QDebug> #include "settings.h" #include "authorize_update_name.h" #include "updatenamemain.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); Settings settings; UpdateNameMain m; if(settings.consumerKey().isEmpty() || settings.consumerSecret().isEmpty() || settings.accessToken().isEmpty() || settings.accessTokenSecret().isEmpty()) { authorize(); } m.exec(); return a.exec(); } <commit_msg>Qtライブラリのパスを追加<commit_after>#include <QCoreApplication> #include <QObject> #include <QThread> #include <QEventLoop> #include <QDir> #include <QDebug> #include "settings.h" #include "authorize_update_name.h" #include "updatenamemain.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QDir library_path; library_path.cd(QCoreApplication::applicationDirPath()); library_path.cd("./lib"); QCoreApplication::addLibraryPath(library_path.path()); Settings settings; if(settings.consumerKey().isEmpty() || settings.consumerSecret().isEmpty() || settings.accessToken().isEmpty() || settings.accessTokenSecret().isEmpty()) { authorize(); } UpdateNameMain m; m.exec(); return a.exec(); } <|endoftext|>
<commit_before>be7f70c5-2e4f-11e5-83da-28cfe91dbc4b<commit_msg>be860e33-2e4f-11e5-bf81-28cfe91dbc4b<commit_after>be860e33-2e4f-11e5-bf81-28cfe91dbc4b<|endoftext|>
<commit_before>eb477c9c-313a-11e5-bf07-3c15c2e10482<commit_msg>eb4d9ce6-313a-11e5-95a3-3c15c2e10482<commit_after>eb4d9ce6-313a-11e5-95a3-3c15c2e10482<|endoftext|>
<commit_before>7f6cf62a-2d15-11e5-af21-0401358ea401<commit_msg>7f6cf62b-2d15-11e5-af21-0401358ea401<commit_after>7f6cf62b-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>84bf3b2e-2e4f-11e5-a797-28cfe91dbc4b<commit_msg>84c5a240-2e4f-11e5-9439-28cfe91dbc4b<commit_after>84c5a240-2e4f-11e5-9439-28cfe91dbc4b<|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Christian <c@ethdev.com> * @date 2014 * Solidity commandline compiler. */ #include <string> #include <iostream> #include <libdevcore/Common.h> #include <libdevcore/CommonData.h> #include <libdevcore/CommonIO.h> #include <libsolidity/Scanner.h> #include <libsolidity/Parser.h> #include <libsolidity/ASTPrinter.h> #include <libsolidity/NameAndTypeResolver.h> #include <libsolidity/Exceptions.h> #include <libsolidity/Compiler.h> #include <libsolidity/SourceReferenceFormatter.h> using namespace std; using namespace dev; using namespace solidity; void help() { cout << "Usage solc [OPTIONS] <file>" << endl << "Options:" << endl << " -h,--help Show this help message and exit." << endl << " -V,--version Show the version and exit." << endl; exit(0); } void version() { cout << "solc, the solidity complier commandline interface " << dev::Version << endl << " by Christian <c@ethdev.com>, (c) 2014." << endl << "Build: " << DEV_QUOTED(ETH_BUILD_PLATFORM) << "/" << DEV_QUOTED(ETH_BUILD_TYPE) << endl; exit(0); } int main(int argc, char** argv) { string infile; for (int i = 1; i < argc; ++i) { string arg = argv[i]; if (arg == "-h" || arg == "--help") help(); else if (arg == "-V" || arg == "--version") version(); else infile = argv[i]; } string sourceCode; if (infile.empty()) { string s; while (!cin.eof()) { getline(cin, s); sourceCode.append(s); } } else sourceCode = asString(dev::contents(infile)); ASTPointer<ContractDefinition> ast; shared_ptr<Scanner> scanner = make_shared<Scanner>(CharStream(sourceCode)); Parser parser; try { ast = parser.parse(scanner); } catch (ParserError const& exception) { SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Parser error", *scanner); return -1; } NameAndTypeResolver resolver; try { resolver.resolveNamesAndTypes(*ast.get()); } catch (DeclarationError const& exception) { SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Declaration error", *scanner); return -1; } catch (TypeError const& exception) { SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Type error", *scanner); return -1; } cout << "Syntax tree for the contract:" << endl; dev::solidity::ASTPrinter printer(ast, sourceCode); printer.print(cout); bytes instructions; Compiler compiler; try { compiler.compileContract(*ast); instructions = compiler.getAssembledBytecode(); } catch (CompilerError const& exception) { SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Compiler error", *scanner); return -1; } cout << "EVM assembly:" << endl; compiler.streamAssembly(cout); cout << "Opcodes:" << endl; cout << eth::disassemble(instructions) << endl; cout << "Binary: " << toHex(instructions) << endl; return 0; } <commit_msg>Converted all asserts to exceptions.<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Christian <c@ethdev.com> * @date 2014 * Solidity commandline compiler. */ #include <string> #include <iostream> #include <libdevcore/Common.h> #include <libdevcore/CommonData.h> #include <libdevcore/CommonIO.h> #include <libsolidity/Scanner.h> #include <libsolidity/Parser.h> #include <libsolidity/ASTPrinter.h> #include <libsolidity/NameAndTypeResolver.h> #include <libsolidity/Exceptions.h> #include <libsolidity/Compiler.h> #include <libsolidity/SourceReferenceFormatter.h> using namespace std; using namespace dev; using namespace solidity; void help() { cout << "Usage solc [OPTIONS] <file>" << endl << "Options:" << endl << " -h,--help Show this help message and exit." << endl << " -V,--version Show the version and exit." << endl; exit(0); } void version() { cout << "solc, the solidity complier commandline interface " << dev::Version << endl << " by Christian <c@ethdev.com>, (c) 2014." << endl << "Build: " << DEV_QUOTED(ETH_BUILD_PLATFORM) << "/" << DEV_QUOTED(ETH_BUILD_TYPE) << endl; exit(0); } int main(int argc, char** argv) { string infile; for (int i = 1; i < argc; ++i) { string arg = argv[i]; if (arg == "-h" || arg == "--help") help(); else if (arg == "-V" || arg == "--version") version(); else infile = argv[i]; } string sourceCode; if (infile.empty()) { string s; while (!cin.eof()) { getline(cin, s); sourceCode.append(s); } } else sourceCode = asString(dev::contents(infile)); ASTPointer<ContractDefinition> ast; shared_ptr<Scanner> scanner = make_shared<Scanner>(CharStream(sourceCode)); Parser parser; bytes instructions; Compiler compiler; try { ast = parser.parse(scanner); NameAndTypeResolver resolver; resolver.resolveNamesAndTypes(*ast.get()); cout << "Syntax tree for the contract:" << endl; dev::solidity::ASTPrinter printer(ast, sourceCode); printer.print(cout); compiler.compileContract(*ast); instructions = compiler.getAssembledBytecode(); } catch (ParserError const& exception) { SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Parser error", *scanner); return -1; } catch (DeclarationError const& exception) { SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Declaration error", *scanner); return -1; } catch (TypeError const& exception) { SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Type error", *scanner); return -1; } catch (CompilerError const& exception) { SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Compiler error", *scanner); return -1; } catch (InternalCompilerError const& exception) { cerr << "Internal compiler error: " << boost::diagnostic_information(exception) << endl; return -1; } catch (Exception const& exception) { cerr << "Exception during compilation: " << boost::diagnostic_information(exception) << endl; return -1; } catch (...) { cerr << "Unknown exception during compilation." << endl; return -1; } cout << "EVM assembly:" << endl; compiler.streamAssembly(cout); cout << "Opcodes:" << endl; cout << eth::disassemble(instructions) << endl; cout << "Binary: " << toHex(instructions) << endl; return 0; } <|endoftext|>
<commit_before>3611805e-2748-11e6-8097-e0f84713e7b8<commit_msg>add file<commit_after>361f1a33-2748-11e6-9637-e0f84713e7b8<|endoftext|>
<commit_before>#include <stdio.h> int main(int argc, char** argv) { // Done. return 0; } <commit_msg>first merge<commit_after>#include <stdio.h> int main(int argc, char** argv) { int l_Ret = EXIT_SUCCESS; // Done. return 0; } <|endoftext|>
<commit_before>#define FUSE_USE_VERSION 30 #include <fuse.h> // POSIX #include <sys/types.h> #include <sys/stat.h> // mode info #include <pwd.h> // user id #include <grp.h> // group id #include <unistd.h> #include <time.h> #include <limits.h> // PATH_MAX // STL #include <map> #include <set> #include <string> #include <system_error> // C++ #include <cstdint> #include <cassert> #include <cstring> namespace posix { constexpr int success = 0; constexpr int errorcode(std::errc err) { return 0 - int(err); } } namespace circlefs { enum class Epath { root, directory, file, }; struct file_entry_t { bool operator < (const file_entry_t& other) const noexcept // for locating files by name { return name < other.name; } std::string name; pid_t pid; struct stat stat; }; static std::map<uid_t, std::set<file_entry_t>> files; static struct timespec inittime; void deconstruct_path(const char* path, Epath& type, passwd*& pw_ent, std::string& filename) noexcept { const char* dir_pos = std::strchr(path, '/') + 1; const char* file_pos = std::strchr(dir_pos, '/'); std::string dir; if(path[1] == '\0') { type = Epath::root; pw_ent = nullptr; filename.clear(); } else { if(file_pos == nullptr) { dir = dir_pos; filename.clear(); type = Epath::directory; } else { dir = std::string(dir_pos, file_pos - dir_pos); filename = file_pos + 1; type = Epath::file; } pw_ent = ::getpwnam(dir.c_str()); } } void clean_set(std::set<file_entry_t>& dir_set) noexcept { char path[PATH_MAX + 1]; struct stat info; auto pos = dir_set.begin(); while(pos != dir_set.end()) { // Linux only sprintf(path, "/proc/%d", pos->pid); if(stat( path, &info ) != posix::success || !(info.st_mode & S_IFDIR)) // if process pos = dir_set.erase(pos); else ++pos; } } /* struct timespec get_oldest(std::set<file_entry_t>& dir_set) { struct timespec oldest = dir_set.begin()->stat.st_atim; auto pos = dir_set.begin(); while(pos != dir_set.end()) { if(pos->stat.st_atim.tv_sec < oldest.tv_sec) oldest.tv_sec = pos->stat.st_atim.tv_sec; } return oldest; } */ int readdir(const char* path, void* buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info* fileInfo) noexcept { (void)fileInfo; filler(buf, "." , nullptr, 0); filler(buf, "..", nullptr, 0); Epath type; passwd* pw_ent; std::string filename; deconstruct_path(path, type, pw_ent, filename); switch(type) { case Epath::root: // root directory (fill with usernames in use) { auto pos = files.begin(); while(pos != files.end()) { clean_set(pos->second); if(pos->second.empty()) pos = files.erase(pos); else { filler(buf, ::getpwuid(pos->first)->pw_name, nullptr, offset); ++pos; } } break; } case Epath::directory: // list files in directory (based on username) { auto pos = files.find(pw_ent->pw_uid); if(pos == files.end()) // username has no files return posix::errorcode(std::errc::no_such_file_or_directory); clean_set(pos->second); for(const file_entry_t& entry : pos->second) filler(buf, entry.name.c_str(), &entry.stat, offset); break; } case Epath::file: // there must have been a parsing error (impossible situation) assert(false); } return posix::success; } int mknod(const char* path, mode_t mode, dev_t rdev) noexcept { (void)rdev; if(!(mode & S_IFSOCK) || mode & (S_ISUID | S_ISGID)) // if not a socket or execution flag is set return posix::errorcode(std::errc::permission_denied); Epath type; passwd* pw_ent = nullptr; std::string filename; struct stat stat = {}; struct timespec time; clock_gettime(CLOCK_REALTIME, &time); deconstruct_path(path, type, pw_ent, filename); if(pw_ent->pw_uid != fuse_get_context()->uid) return posix::errorcode(std::errc::invalid_argument); switch(type) { case Epath::root: // root directory - cannot make root! case Epath::directory: // directory (based on username) - cannot make directory! return posix::errorcode(std::errc::permission_denied); case Epath::file: // create a node file! fuse_context* ctx = fuse_get_context(); auto& dir = files[pw_ent->pw_uid]; auto entry = dir.find({ filename, 0, stat }); if(entry != dir.end()) dir.erase(entry); stat.st_uid = pw_ent->pw_uid; stat.st_gid = pw_ent->pw_gid; stat.st_mode = mode; stat.st_ctim = stat.st_mtim = stat.st_atim = time; dir.insert({ filename, ctx->pid, stat }); break; } return posix::success; } int getattr(const char* path, struct stat* statbuf) noexcept { Epath type; passwd* pw_ent = nullptr; std::string filename; deconstruct_path(path, type, pw_ent, filename); statbuf->st_size = 0; switch(type) { case Epath::root: // root directory (always exists) statbuf->st_atim = statbuf->st_ctim = statbuf->st_mtim = inittime; statbuf->st_mode = S_IFDIR | S_IRUSR | S_IRGRP | S_IROTH | S_IXUSR | S_IXGRP | S_IXOTH; break; case Epath::directory: // username (exists if username exists) statbuf->st_mode = S_IFDIR | S_IRUSR | S_IRGRP | S_IROTH | S_IXUSR | S_IXGRP | S_IXOTH; if(pw_ent == nullptr) return posix::errorcode(std::errc::no_such_file_or_directory); break; case Epath::file: auto pos = files.find(pw_ent->pw_uid); if(pos == files.end()) // username not registered return posix::errorcode(std::errc::no_such_file_or_directory); clean_set(pos->second); for(const file_entry_t& entry : pos->second) // check every file { if(entry.name == filename) { *statbuf = entry.stat; return posix::success; } } return posix::errorcode(std::errc::no_such_file_or_directory); // no file matched } return posix::success; } } int main(int argc, char *argv[]) { static struct fuse_operations ops; clock_gettime(CLOCK_REALTIME, &circlefs::inittime); ops.readdir = circlefs::readdir; ops.mknod = circlefs::mknod; ops.getattr = circlefs::getattr; return fuse_main(argc, argv, &ops, nullptr); } <commit_msg>allow root to make anything<commit_after>#define FUSE_USE_VERSION 30 #include <fuse.h> // POSIX #include <sys/types.h> #include <sys/stat.h> // mode info #include <pwd.h> // user id #include <grp.h> // group id #include <unistd.h> #include <time.h> #include <limits.h> // PATH_MAX // STL #include <map> #include <set> #include <string> #include <system_error> // C++ #include <cstdint> #include <cassert> #include <cstring> namespace posix { constexpr int success = 0; constexpr int errorcode(std::errc err) { return 0 - int(err); } } namespace circlefs { enum class Epath { root, directory, file, }; struct file_entry_t { bool operator < (const file_entry_t& other) const noexcept // for locating files by name { return name < other.name; } std::string name; pid_t pid; struct stat stat; }; static std::map<uid_t, std::set<file_entry_t>> files; static struct timespec inittime; void deconstruct_path(const char* path, Epath& type, passwd*& pw_ent, std::string& filename) noexcept { const char* dir_pos = std::strchr(path, '/') + 1; const char* file_pos = std::strchr(dir_pos, '/'); std::string dir; if(path[1] == '\0') { type = Epath::root; pw_ent = nullptr; filename.clear(); } else { if(file_pos == nullptr) { dir = dir_pos; filename.clear(); type = Epath::directory; } else { dir = std::string(dir_pos, file_pos - dir_pos); filename = file_pos + 1; type = Epath::file; } pw_ent = ::getpwnam(dir.c_str()); } } void clean_set(std::set<file_entry_t>& dir_set) noexcept { char path[PATH_MAX + 1]; struct stat info; auto pos = dir_set.begin(); while(pos != dir_set.end()) { // ::procstat() // Linux only sprintf(path, "/proc/%d", pos->pid); if(stat( path, &info ) != posix::success || !(info.st_mode & S_IFDIR)) // if process pos = dir_set.erase(pos); else ++pos; } } /* struct timespec get_oldest(std::set<file_entry_t>& dir_set) { struct timespec oldest = dir_set.begin()->stat.st_atim; auto pos = dir_set.begin(); while(pos != dir_set.end()) { if(pos->stat.st_atim.tv_sec < oldest.tv_sec) oldest.tv_sec = pos->stat.st_atim.tv_sec; } return oldest; } */ int readdir(const char* path, void* buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info* fileInfo) noexcept { (void)fileInfo; filler(buf, "." , nullptr, 0); filler(buf, "..", nullptr, 0); Epath type; passwd* pw_ent; std::string filename; deconstruct_path(path, type, pw_ent, filename); switch(type) { case Epath::root: // root directory (fill with usernames in use) { auto pos = files.begin(); while(pos != files.end()) { clean_set(pos->second); if(pos->second.empty()) pos = files.erase(pos); else { filler(buf, ::getpwuid(pos->first)->pw_name, nullptr, offset); ++pos; } } break; } case Epath::directory: // list files in directory (based on username) { auto pos = files.find(pw_ent->pw_uid); if(pos == files.end()) // username has no files return posix::errorcode(std::errc::no_such_file_or_directory); clean_set(pos->second); for(const file_entry_t& entry : pos->second) filler(buf, entry.name.c_str(), &entry.stat, offset); break; } case Epath::file: // there must have been a parsing error (impossible situation) assert(false); } return posix::success; } int mknod(const char* path, mode_t mode, dev_t rdev) noexcept { (void)rdev; if(!(mode & S_IFSOCK) || mode & (S_ISUID | S_ISGID)) // if not a socket or execution flag is set return posix::errorcode(std::errc::permission_denied); Epath type; passwd* pw_ent = nullptr; std::string filename; struct stat stat = {}; struct timespec time; clock_gettime(CLOCK_REALTIME, &time); deconstruct_path(path, type, pw_ent, filename); if(fuse_get_context()->uid && // if NOT root AND pw_ent->pw_uid != fuse_get_context()->uid) // UID doesn't match return posix::errorcode(std::errc::invalid_argument); switch(type) { case Epath::root: // root directory - cannot make root! case Epath::directory: // directory (based on username) - cannot make directory! return posix::errorcode(std::errc::permission_denied); case Epath::file: // create a node file! fuse_context* ctx = fuse_get_context(); auto& dir = files[pw_ent->pw_uid]; auto entry = dir.find({ filename, 0, stat }); if(entry != dir.end()) dir.erase(entry); stat.st_uid = pw_ent->pw_uid; stat.st_gid = pw_ent->pw_gid; stat.st_mode = mode; stat.st_ctim = stat.st_mtim = stat.st_atim = time; dir.insert({ filename, ctx->pid, stat }); break; } return posix::success; } int getattr(const char* path, struct stat* statbuf) noexcept { Epath type; passwd* pw_ent = nullptr; std::string filename; deconstruct_path(path, type, pw_ent, filename); statbuf->st_size = 0; switch(type) { case Epath::root: // root directory (always exists) statbuf->st_atim = statbuf->st_ctim = statbuf->st_mtim = inittime; statbuf->st_mode = S_IFDIR | S_IRUSR | S_IRGRP | S_IROTH | S_IXUSR | S_IXGRP | S_IXOTH; break; case Epath::directory: // username (exists if username exists) statbuf->st_mode = S_IFDIR | S_IRUSR | S_IRGRP | S_IROTH | S_IXUSR | S_IXGRP | S_IXOTH; if(pw_ent == nullptr) return posix::errorcode(std::errc::no_such_file_or_directory); break; case Epath::file: auto pos = files.find(pw_ent->pw_uid); if(pos == files.end()) // username not registered return posix::errorcode(std::errc::no_such_file_or_directory); clean_set(pos->second); for(const file_entry_t& entry : pos->second) // check every file { if(entry.name == filename) { *statbuf = entry.stat; return posix::success; } } return posix::errorcode(std::errc::no_such_file_or_directory); // no file matched } return posix::success; } } int main(int argc, char *argv[]) { static struct fuse_operations ops; clock_gettime(CLOCK_REALTIME, &circlefs::inittime); ops.readdir = circlefs::readdir; ops.mknod = circlefs::mknod; ops.getattr = circlefs::getattr; return fuse_main(argc, argv, &ops, nullptr); } <|endoftext|>
<commit_before>1bc53ce2-2f67-11e5-9525-6c40088e03e4<commit_msg>1bce30f4-2f67-11e5-ae9a-6c40088e03e4<commit_after>1bce30f4-2f67-11e5-ae9a-6c40088e03e4<|endoftext|>
<commit_before>a233d44f-327f-11e5-b64d-9cf387a8033e<commit_msg>a239c6b8-327f-11e5-8d36-9cf387a8033e<commit_after>a239c6b8-327f-11e5-8d36-9cf387a8033e<|endoftext|>
<commit_before>/* FILE INFORMATION File: main.cpp Authors: Matthew Cole <mcole8@binghamton.edu> Brian Gracin <bgracin1@binghamton.edu> Description: Driver for apex-sim. Contains functions controlling simulator high-level behavior. */ #include <iostream> #include <string> #include "code.h" #include "cpu.h" #include "data.h" #include "register.h" #include "apex.h" #define VERBOSE 1 using namespace std; //Simulator variables with external linkage int cycle = 0; //simulator cycle current value int pc = 4000; //program counter current value static const char* instFile; //instruction input file //Display an interface help message void help() { cout << "[i] Initialize the simulator state" << endl; cout << "[s n] Simulate <n> number of cycles" << endl; cout << "[d n] Display the simulator internal state" << endl; cout << "[q] Quit the simulator" << endl; cout << "[h] Display a help message" << endl; } // Initialize the simulator to a known state. void initialize(CPU &mycpu, Registers &myregisters, Data &mydata) { if (VERBOSE) cout << "Initializing ... " << endl; //Reset simulator state variables cycle = 0; pc = 4000; //Initialize each of the instances by delegating to member functions mycpu.initialize(); myregisters.initialize(); mydata.initialize(); } // Display the simulator internal state. void display(CPU &mycpu, Registers &myregisters, Data &mydata) { if (VERBOSE) cout << "Displaying simulator state ... " << endl; //Print simulator state variables //Display each of the instances by delegating to member functions //TODO Call to cpu::display() //TODO Call to registers::display() //TODO Call to data::display() } // Simulate the operation of the system for <num_cycles>, or until a HALT //instruction is encountered, or until an error occurs in simulation. //Return the current cycle number after simulation pauses or halts. int simulate(int num_cycles, CPU &apexCPU, Code &apexCode, Registers &apexRF, Data &apexData) { for (int c = cycle; c < cycle + num_cycles; c++) { //Perform one cycle of simulation if (VERBOSE) cout << "Simulating cycle " << cycle << " ..." << endl; //cpu::simulate() returns 0 if execution should not continue //(EOF, HALT or exception encountered) if(!(apexCPU.simulate(apexCode, apexRF, apexData))) break; //TODO Call quit function //Cycle complete, increment the global cycle counter cycle++; } return cycle; } int main(int argc, char** argv) { //Command line program options handling //Check if user needs a usage message if (argc != 2) { cout << "USAGE: apex-sim <instructions file>" << endl; exit(0); } else { //User didn't need a usage message. Capture filenames instFile = (const char*) argv[1]; } //Instantiate Simulator classes Code *apexCode = new Code(instFile); Registers *apexRF = new Registers(); Data *apexData = new Data(); CPU *apexCPU = new CPU(*apexCode, *apexRF, *apexData); //Perform first initialization initialize(*apexCPU, *apexRF, *apexData); //Set up simulator command interface string command = "h"; //interface switch statement selector int n = 1; // number of cycles or addresses modifier /****** USER INTERFACE ******/ while (command != "q") { //On first execution of the interface, display the help message if (cycle == 0) help(); //Get the next command. If command takes the n parameter, ingest it also cin >> command; if (command == "s") cin >> n; //Perform appropriate action based on the command / parameter switch (command[0]) { case 'i': initialize(*apexCPU, *apexRF, *apexData); break; case 's': simulate(n, *apexCPU, *apexCode, *apexRF, *apexData); break; case 'd': display(*apexCPU, *apexRF, *apexData); break; case 'q': //quitting causes no action except to conclude this function break; case 'h': //Falls through to default (which prints the help message) default: //Input wasn't recognized help(); break; } } // End User Interface //TODO Perform any exiting actions? return 0; } <commit_msg>Added quit() functionality<commit_after>/* FILE INFORMATION File: main.cpp Authors: Matthew Cole <mcole8@binghamton.edu> Brian Gracin <bgracin1@binghamton.edu> Description: Driver for apex-sim. Contains functions controlling simulator high-level behavior. */ #include <iostream> #include <string> #include "code.h" #include "cpu.h" #include "data.h" #include "register.h" #include "apex.h" #define VERBOSE 1 using namespace std; //Simulator variables with external linkage int cycle = 0; //simulator cycle current value int pc = 4000; //program counter current value static const char* instFile; //instruction input file //Display an interface help message void help() { cout << "[i] Initialize the simulator state" << endl; cout << "[s n] Simulate <n> number of cycles" << endl; cout << "[d n] Display the simulator internal state" << endl; cout << "[q] Quit the simulator" << endl; cout << "[h] Display a help message" << endl; } //Quit the simulator void quit(CPU &mycpu, Registers &myregisters, Data &mydata){ if (VERBOSE) cout << "Displaying final state and quitting simulator ..." << endl; display(mycpu, myregisters, mydata); return 0; } // Initialize the simulator to a known state. void initialize(CPU &mycpu, Registers &myregisters, Data &mydata) { if (VERBOSE) cout << "Initializing ... " << endl; //Reset simulator state variables cycle = 0; pc = 4000; //Initialize each of the instances by delegating to member functions mycpu.initialize(); myregisters.initialize(); mydata.initialize(); } // Display the simulator internal state. void display(CPU &mycpu, Registers &myregisters, Data &mydata) { if (VERBOSE) cout << "Displaying simulator state ... " << endl; //Print simulator state variables //Display each of the instances by delegating to member functions mycpu.display(); myregisters.display(); mydata.display(); } // Simulate the operation of the system for <num_cycles>, or until a HALT //instruction is encountered, or until an error occurs in simulation. //Return the current cycle number after simulation pauses or halts. int simulate(int num_cycles, CPU &apexCPU, Code &apexCode, Registers &apexRF, Data &apexData) { for (int c = cycle; c < cycle + num_cycles; c++) { //Perform one cycle of simulation if (VERBOSE) cout << "Simulating cycle " << cycle << " ..." << endl; //cpu::simulate() returns 0 if execution should not continue //(EOF, HALT or exception encountered) if(!(apexCPU.simulate(apexCode, apexRF, apexData))){ cout << "Simulator HALT encounted on cycle " << cycle << endl; quit(apexCPU, apexRF, apexData); return 0; } //Cycle complete, increment the global cycle counter cycle++; } return cycle; } int main(int argc, char** argv) { //Command line program options handling //Check if user needs a usage message if (argc != 2) { cout << "USAGE: apex-sim <instructions file>" << endl; exit(0); } else { //User didn't need a usage message. Capture filenames instFile = (const char*) argv[1]; } //Instantiate Simulator classes Code *apexCode = new Code(instFile); Registers *apexRF = new Registers(); Data *apexData = new Data(); CPU *apexCPU = new CPU(*apexCode, *apexRF, *apexData); //Perform first initialization initialize(*apexCPU, *apexRF, *apexData); //Set up simulator command interface string command = "h"; //interface switch statement selector int n = 1; // number of cycles or addresses modifier /******************************************************************************/ /**************************USER INTERFACE *************************************/ /******************************************************************************/ while (command != "q") { //On first execution of the interface, display the help message if (cycle == 0) help(); //Get the next command. If command takes the n parameter, ingest it also cin >> command; if (command == "s") cin >> n; //Perform appropriate action based on the command / parameter switch (command[0]) { case 'i': initialize(*apexCPU, *apexRF, *apexData); break; case 's': simulate(n, *apexCPU, *apexCode, *apexRF, *apexData); break; case 'd': display(*apexCPU, *apexRF, *apexData); break; case 'q': //simulator can quit by user selection or encountering HALT quit(*apexCPU, *apexRF, *apexData); break; case 'h': //Falls through to default (which prints the help message) default: //Input wasn't recognized help(); break; } } // End User Interface quit(*apexCPU, *apexRF, *apexData); return 0; } <|endoftext|>
<commit_before>d93a8d99-4b02-11e5-b288-28cfe9171a43<commit_msg>OKAY this time it should work<commit_after>d945f1f5-4b02-11e5-8d76-28cfe9171a43<|endoftext|>
<commit_before>ae9adeb3-327f-11e5-8823-9cf387a8033e<commit_msg>aea1d059-327f-11e5-88a8-9cf387a8033e<commit_after>aea1d059-327f-11e5-88a8-9cf387a8033e<|endoftext|>