text:
Q: opencl is giving wrong results for double data type? I am very new to OpenCl.
Problem: i am initializing an array of 10 elements with value of -1 in Host. I am passing the same array as input to device and incrementing each element and then receiving back the array as output through Buffer. Then again, sending back the same output array as input to host and receiving back incremented output buffer. This is done in loop.
Issue: When i am having the data type of array as float/int, Program is working fine. But when i am making the datatype as double of the array it is not giving me the desired results.
Please suggest where i am missing? Any help/suggestion/keywords will be a great help. Thanks in advance.
Code for float data type of array:
#include <stdio.h>
#include <stdlib.h>
#ifdef __APPLE__
#include <OpenCL/opencl.h>
#else
#include <CL/cl.h>
#endif

#define MEM_SIZE (10)
#define MAX_SOURCE_SIZE (0x100000)

int main() {
    float input[MEM_SIZE], output[MEM_SIZE];
    int go, i;
    for (i = 0; i < MEM_SIZE; i++) {
        input[i] = -1.0;
        output[i] = -1.0;
    }
    FILE *fp;
    cl_device_id device_id = NULL;
    cl_context context = NULL;
    cl_command_queue command_queue = NULL;
    cl_program program = NULL;
    cl_kernel kernel = NULL;
    cl_platform_id platform_id = NULL;
    cl_uint ret_num_devices;
    cl_uint ret_num_platforms;
    cl_int ret;
    size_t source_size;
    char *source_str;
    fp = fopen("calc_float.cl", "r");
    if (!fp) {
        fprintf(stderr, "Failed to load kernel.\n");
        exit(1);
    }
    source_str = (char*)malloc(MAX_SOURCE_SIZE);
    source_size = fread(source_str, 1, MAX_SOURCE_SIZE, fp);
    fclose(fp);

    /*Initialization*/
    /* Get Platform and Device Info */
    ret = clGetPlatformIDs(1, &platform_id, &ret_num_platforms);
    ret = clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_DEFAULT, 1, &device_id, &ret_num_devices);

    /* Create OpenCL context */
    context = clCreateContext(NULL, 1, &device_id, NULL, NULL, &ret);

    /* Create Command Queue */
    command_queue = clCreateCommandQueue(context, device_id, 0, &ret);

    /*Initialization complete*/

    cl_mem inputBuffer = clCreateBuffer(context, CL_MEM_READ_ONLY|CL_MEM_COPY_HOST_PTR, MEM_SIZE * sizeof(float),(void *) input, NULL);
    cl_mem outputBuffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY , MEM_SIZE * sizeof(float), NULL, NULL);

    /* Create Kernel Program from the source */
    program = clCreateProgramWithSource(context, 1, (const char **)&source_str,(const size_t *)&source_size, &ret);

    /* Build Kernel Program */
    ret = clBuildProgram(program, 1, &device_id, NULL, NULL, NULL);

    /* Create OpenCL Kernel */
    kernel = clCreateKernel(program, "calc", &ret);

    /* Set OpenCL Kernel Parameters */
    ret = clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&inputBuffer);
    ret = clSetKernelArg(kernel, 1, sizeof(cl_mem), (void *)&outputBuffer);

    /* Execute OpenCL Kernel */
    ret = clEnqueueTask(command_queue, kernel, 0, NULL,NULL);
    double x = 10, io;
    size_t global_work_size[1] = {MEM_SIZE};
    for (io = 0; io < x; io++) {
        inputBuffer = clCreateBuffer(context, CL_MEM_READ_ONLY|CL_MEM_COPY_HOST_PTR, MEM_SIZE * sizeof(float),(void *) output, NULL);
        ret = clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&inputBuffer);
        ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, global_work_size, NULL, 0, NULL, NULL);

        ret = clEnqueueReadBuffer(command_queue, outputBuffer, CL_TRUE, 0, MEM_SIZE * sizeof(float), output, 0, NULL, NULL);
        for (go = 0; go < MEM_SIZE; go++) {
            printf("output[%d] = %f\n",io, go, output[go]);
        }
        printf("\n\n");

    }

    /* Finalization */
    ret = clFlush(command_queue);
    ret = clFinish(command_queue);
    ret = clReleaseKernel(kernel);
    ret = clReleaseProgram(program);
    ret = clReleaseMemObject(inputBuffer);
    ret = clReleaseMemObject(outputBuffer);
    ret = clReleaseCommandQueue(command_queue);
    ret = clReleaseContext(context);

    return 1;
}

calc_float.cl file for above code:
__kernel void calc(__global float* in, __global float* out)
{
    int i;
    for (i = 0; i < 10; i++) {
        out[i] = in[i] + 1;
    }
}

Code for double data type of array:
#include <stdio.h>
#include <stdlib.h>
#ifdef __APPLE__
#include <OpenCL/opencl.h>
#else
#include <CL/cl.h>
#endif

#define MEM_SIZE (10)
#define MAX_SOURCE_SIZE (0x100000)

int main() {
    double input[MEM_SIZE], output[MEM_SIZE];
    int go, i;
    for (i = 0; i < MEM_SIZE; i++) {
        input[i] = -1.0;
        output[i] = -1.0;
    }
    FILE *fp;
    cl_device_id device_id = NULL;
    cl_context context = NULL;
    cl_command_queue command_queue = NULL;
    cl_program program = NULL;
    cl_kernel kernel = NULL;
    cl_platform_id platform_id = NULL;
    cl_uint ret_num_devices;
    cl_uint ret_num_platforms;
    cl_int ret;
    size_t source_size;
    char *source_str;
    fp = fopen("calc_double.cl", "r");
    if (!fp) {
        fprintf(stderr, "Failed to load kernel.\n");
        exit(1);
    }
    source_str = (char*)malloc(MAX_SOURCE_SIZE);
    source_size = fread(source_str, 1, MAX_SOURCE_SIZE, fp);
    fclose(fp);

    /*Initialization*/
    /* Get Platform and Device Info */
    ret = clGetPlatformIDs(1, &platform_id, &ret_num_platforms);
    ret = clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_DEFAULT, 1, &device_id, &ret_num_devices);

    /* Create OpenCL context */
    context = clCreateContext(NULL, 1, &device_id, NULL, NULL, &ret);

    /* Create Command Queue */
    command_queue = clCreateCommandQueue(context, device_id, 0, &ret);

    /*Initialization complete*/

    cl_mem inputBuffer = clCreateBuffer(context, CL_MEM_READ_ONLY|CL_MEM_COPY_HOST_PTR, MEM_SIZE * sizeof(double),(void *) input, NULL);
    cl_mem outputBuffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY , MEM_SIZE * sizeof(double), NULL, NULL);

    /* Create Kernel Program from the source */
    program = clCreateProgramWithSource(context, 1, (const char **)&source_str,(const size_t *)&source_size, &ret);

    /* Build Kernel Program */
    ret = clBuildProgram(program, 1, &device_id, NULL, NULL, NULL);

    /* Create OpenCL Kernel */
    kernel = clCreateKernel(program, "calc", &ret);

    /* Set OpenCL Kernel Parameters */
    ret = clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&inputBuffer);
    ret = clSetKernelArg(kernel, 1, sizeof(cl_mem), (void *)&outputBuffer);

    /* Execute OpenCL Kernel */
    ret = clEnqueueTask(command_queue, kernel, 0, NULL,NULL);
    double x = 10, io;
    size_t global_work_size[1] = {MEM_SIZE};
    for (io = 0; io < x; io++) {
        inputBuffer = clCreateBuffer(context, CL_MEM_READ_ONLY|CL_MEM_COPY_HOST_PTR, MEM_SIZE * sizeof(double),(void *) output, NULL);
        ret = clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&inputBuffer);
        ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, global_work_size, NULL, 0, NULL, NULL);

        ret = clEnqueueReadBuffer(command_queue, outputBuffer, CL_TRUE, 0, MEM_SIZE * sizeof(double), output, 0, NULL, NULL);
        for (go = 0; go < MEM_SIZE; go++) {
            printf("output[%d] = %lf\n",io, go, output[go]);
        }
        printf("\n\n");

    }

    /* Finalization */
    ret = clFlush(command_queue);
    ret = clFinish(command_queue);
    ret = clReleaseKernel(kernel);
    ret = clReleaseProgram(program);
    ret = clReleaseMemObject(inputBuffer);
    ret = clReleaseMemObject(outputBuffer);
    ret = clReleaseCommandQueue(command_queue);
    ret = clReleaseContext(context);

    return 1;
}

calc_double.cl file for above code:
__kernel void calc(__global double* in, __global double* out)
{
    int i;
    for (i = 0; i < 10; i++) {
        out[i] = in[i] + 1;
    }
}

compilation of program:
gcc program.c -o doublesimulation -l OpenCL -I /usr/local/test/AMD-APP-SDK-v2.9-RC-lnx32/include/ -L /usr/local/test/AMD-APP-SDK-v2.9-RC-lnx32/lib/x86

i also tried adding following checks, but it didn't help:
#ifdef cl_khr_fp64
    #pragma OPENCL EXTENSION cl_khr_fp64 : enable
#elif defined(cl_amd_fp64)
    #pragma OPENCL EXTENSION cl_amd_fp64 : enable
#else
    #error "Double precision floating point not supported by OpenCL implementation."
#endif

Operating System: Centos5 32bit with AMD graphics card

A: Check that your GPU supports double precision:
cl_uint native_double_width;
clGetDeviceInfo(device_id, CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE, sizeof(cl_uint), &native_double_width, NULL);

if(native_double_width == 0){
    printf("No double precision support.\n");
}

If native double vector width is equal to 0, double precision isn't supported (clGetDeviceInfo description)


text:
Q: Tests coverage not displayed in SonarQube report I try to display the tests coverage in SonarQube of my Android Kotlin app of the code in my app module. I can generate the jacoco coverage results and display SonarQube qualymetrics but the problem is that the tests coverage is not displayed in SonarQube :
https://imgur.com/a/xOjxLl1
in my build.gradle of my project I have :
...
dependencies {
    classpath 'org.jacoco:org.jacoco.core:0.8.3'
}
...

in my build.gradle of my app module
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'org.sonarqube'
apply plugin: 'jacoco'

jacoco {
    toolVersion = '0.8.3'
}

tasks.withType(Test) {
    jacoco.includeNoLocationClasses = true
}
android {
   ...
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            testCoverageEnabled true
        }
        debug {
            testCoverageEnabled true
        }
     testOptions {
        animationsDisabled true
        unitTests {
            returnDefaultValues = true
            includeAndroidResources = true
        }
    }
task jacocoTestReport(type: JacocoReport, dependsOn: ['testDebugUnitTest', 'createDebugCoverageReport']) {

    reports {
        xml.enabled = true
        html.enabled = true
    }

    def fileFilter = [ '**/R.class', '**/R$*.class', '**/BuildConfig.*', '**/Manifest*.*', '**/*Test*.*', 'android/**/*.*' ]
    def debugTree = fileTree(dir: "$project.buildDir/tmp/kotlin-classes/debug", excludes: fileFilter)
    def mainSrc = "$project.projectDir/src/main/java"

    sourceDirectories = files([mainSrc])
    classDirectories = files([debugTree])
    executionData = fileTree(dir: project.buildDir, includes: [
            'jacoco/testDebugUnitTest.exec', 'outputs/code-coverage/connected/*coverage.ec'
    ])
}

sonarqube {
    properties {
        property 'sonar.projectKey', 'mySonarKey'
        property 'sonar.projectName', 'myProjectName'
        property "sonar.host.url", "http://localhost:9000" // local sonar address

        property "sonar.java.binaries", 'target/classes,app/build/tmp/kotlin-classes'
        property "sonar.sources", 'src/main/java'
        property "sonar.tests", 'src/androidTest/java'

        property "sonar.java.coveragePlugin", "jacoco"
        property "sonar.coverage.jacoco.xmlReportPaths", "./build/reports/jacoco/jacocoTestReport/jacocoTestReport.xml" //link to xml file that generated by jacoco
    }
}
...

I generate my jacoco report with :
gradlew clean jacocoTestReport
And generate my sonarqube analysis with :
gradlew sonarqube
the jacoco report is generated myAppName\app\build\reports\jacoco\jacocoTestReport\jacocoTestReport.xml
I also have an html folder next to the report where I can see that my test coverage generated with the right coverage.
So the question is what can I change to display my generated jacoco coverage in SonarQube ?
(I'm not sure about the sonarqube.properties that I add in my app module build.gradle)

A: I had the same issue for a long time and the solution is to change your path in the build.gradle :
def debugTree = fileTree(dir: "$project.buildDir/tmp/kotlin-classes/debug", excludes: fileFilter)

To :
def debugTree = fileTree(dir: "$project.buildDir/tmp/kotlin-classes/snapshot", excludes: fileFilter)

Otherwise, the .xml generated won't include the coverage for your whole source code and sonarqube will display 0% coverage as a result
Note : my target folder was called 'snapshot' but it might be different for you

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting a lot of Mariadb log-error message with WSREP: cleanup transaction for LOCAL_STATE I have setup Mariadb Galera cluster with 3 Node and recently after checking the
mysql error-log file I got surprised to see (string like below) is repeating.
I am confused why it is repeating so many time the same [Note] and
should I be concern for this.
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
2018-06-24 12:57:34 140400686594816 [Note] WSREP: cleanup transaction for LOCAL_STATE
Kindly help.


text:
Q: Connect to MongoDB on Appfog from localhost I'm trying to run my application on my local pc. Everything looks perfectly fine on the cloud, it works and connects to MongoDB with the code below:
    $services_json = json_decode(getenv("VCAP_SERVICES"),true);
$mongo_config = $services_json["mongodb-1.8"][0]["credentials"];

// Generally will be localhost if you're querying from the machine that Mongo is installed on
$config['mongo_host'] = $mongo_config["hostname"];

// Generally will be 27017 unless you've configured Mongo otherwise
$config['mongo_port'] = $mongo_config["port"];

// The database you want to work from (required)
$config['mongo_db'] = $mongo_config["db"];

// Leave blank if Mongo is not running in auth mode
$config['mongo_user'] = $mongo_config["username"];
$config['mongo_pass'] = $mongo_config["password"];

But since I cannot get the vcap_services from my local pc, I'm using constant values for the connection to connect my app to the remote mongo server on appfog:
    // Generally will be localhost if you're querying from the machine that Mongo is installed on
$config['mongo_host'] = "***";

// Generally will be 27017 unless you've configured Mongo otherwise
$config['mongo_port'] = "***";

// The database you want to work from (required)
$config['mongo_db'] = "db";

// Leave blank if Mongo is not running in auth mode
$config['mongo_user'] = "***";
$config['mongo_pass'] = "***";

But when I try to execute the app through http://localhost/my-app, it gave me this error:
Unable to connect to MongoDB: Failed to connect to: ***: Connection timed out

What can be the problem?
* values are deleted for the privacy.

A: Did you try connecting without the VCAP variables not on localhost but the actual server? AppFog may not give authorization to connect without VCAP variables or something may be wrong on the values you manually get.
I believe this is an authorization problem. Try another cloud service if you cannot handle with it. This is not the only solution.


text:
Q: jQuery Chosen not rendering correctly with Bootstrap 3 I am seeing an issue with jQuery Chosen plugin when used with Bootstrap 3, at least when there is more than one select atop another. The height of the select (multiple) is about half the size required, and the text is cut off (and therefore unreadable).
Does anyone know why this might be, or if there are any good examples of chosen being used with Bootstrap 3 (like select2 provides).

A: The solution I found was editing the bootstrap.css file, and commenting out
*,
*:before,
*:after {
 -webkit-box-sizing: border-box;
 -moz-box-sizing: border-box;
      box-sizing: border-box;

}
This was the css styling that was breaking mine.  I am not sure where it is require in bootstrap but it fixed the issue for me and the styling still looked correct to me.


text:
Q: Switcheroo gone after last update since the last kernel update for Ubuntu 13.04, the folder /sys/kernel/debug/vgaswitcheroo/switch is gone on my Laptop, an Acer Aspire 3820TG.
Checking the output of grep -i /boot/config-* tells me that my kernel supports switcheroo however, the file is gone (and yes, I checked that as root).
Can anybody please give me a hint? I almost checked the whole internet for an appropriate answer but nobody seems to have the same problem.

A: I had the same problem, and I also looked everywhere, tried everything.
Finally I got it working installing the next packages:
i965-va-driver intel-gpu-tools xserver-xorg-video-intel-dbg xserver-xorg-video-radeon-dbg xserver-xorg-video-r128-dbg xserver-xorg-video-ati-dbg

note: using kernel 3.8.0-31-generic
I am not sure what did the trick but it worked, now I can see the /sys/kernel/debug/vgaswitcheroo/switch.
Good luck,
Regards
Giri


text:
Q: manipulating text file in c# I am assigned a project that requires a c# console application that will be used to manipulate a text file. The text file is a bcp table dump. The program should be able to:

*

*Split the file into multiple file(s) based on a column given by the user

*Include or exclude the split column from the output

Currently, I am reading in the file as such:
var groupQuery = from name in File.ReadAllLines(fileName)
                                .Skip(skipHeaderRow)
                             let n = name.Split(delimiterChars)
                             group name by n[index] into g
                             // orderby g.Key
                             select g;

I am afraid I might run into memory issues since some of the files can have over 2 million reacords and each row is about 2617 bytes

A: If you are confident that you program will only need to sequentially access... the bcp dump file, use StreamReader class to read the file. This class is optimized for sequential access and it opens the file as a stream, therefore memory issues should not bother you. Further, you can increase the buffer size of your stream by initializing from a different constructor of this class to have a larger chunk in memory to work with.

If you want to have random access to your file in pieces... go for Memory Mapped Files. make sure to create view accessor over a limited section of the file. The example code given at the link of MMFs explains how to create a small view over a large file.

Edit: I had the code for using MMFs in my answer but I have removed it now as I realized... Even though in reality group by is lazy, it is also a non-streaming LINQ operator. Therefore, it will have to read the entire bcp dump of yours to finally give you the results. This implies:

*

*StreamReader is a clearly a better approach for you. Make sure you increase the buffer to max possible;

*Your LINQ will take some time when it will hit the group by operator and will only come back to life after entire file read has been finished.

A: Try using Buffered Streams to read/write files without completely loading them into memory.
using (FileStream fs = File.Open(inputFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
        using (StreamReader sr = new StreamReader(fs)) {
            string line = sr.ReadLine();
            string lineA = null;
            string lineB = null;
            while ((line != null)) {
                // Split your line here into lineA and lineB
                // and write using buffered writer.
                line = sr.ReadLine();
            }
        }
}

(from here)
The idea is to read the file line by line without loading the entire thing in your memory, split it however way you want and then write the splitted lines, line by line into your output files.

A: Don't reinvent the wheel. Consider using a library like FileHelpers.
http://www.filehelpers.net/example/QuickStart/ReadWriteRecordByRecord/
var engine = new FileHelperAsyncEngine<Customer>();

using(engine.BeginReadFile(fileName))
{
    var groupQuery =
        from o in engine
        group name by o.CustomerId into g
        // orderby g.Key
        select g;

    foreach(Customer cust in engine)
    {
        Console.WriteLine(cust.Name);
    }
}

You will still run into memory problems with your group and order functions because all records need to be in memory to be grouped and ordered.


text:
Q: Function signature doesn't match called function, difference between const char[] and char*? I am using PubSubClient.h, as defined here: https://pubsubclient.knolleary.net/api.html
The instance is created as the following:
WiFiClientSecure secureCl;
PubSubClient mqttCl(secureCl);

PubSubClient has method called setCallBack, which takes in the parameter callback.

PubSubClient setCallback (callback)
callback : a pointer to a message callback function called when a message arrives for a subscription created by this client.

The following signature is given for function callback:
void callback(const char[] topic, byte* payload, unsigned int length)

But, within the example code I were given, inside setup the callback function used is the receivedCallback function:
mqttCl.setCallback(receivedCallback); //called inside setup()

And the function is given as:
void receivedCallback(char* topic, byte* payload, unsigned int length) {
//some code here

}

Now, I can see that it has char* topic, instead of const char[] and I can't get my head around how it is not const char[], as defined by the signature. Could someone explain in simple terms why is it like that?

A: It seems a bug, in this context the problem is given by the const attribute e not by the [] or the *. In fact const char[] and const char* are equal, also char[] and char* are equal, but const char[] and char* can create something that is incompatible.

A: The difference is in the missing const of your callback.
Basically char* topic as an argument means that you are allowed to manipulate the content of topic as in topic[0] = 'A';.
On the other side const char* or const char[] guarantees that there will not be a change to the underlying string and so a pointer to an string from the read-only memory could be given.
mqttCl could for example do the following:
byte payload[10];
callback("test-topic", payload, 10);

And your recievedCallback is allowed to do:
topic[0] = 'b';

The compiler is allowed to store "test-topic" in the read-only memory of the process in which case the program would crash. To prevent this the const part in type signatures must match.


text:
Q: Docker busybox tar broken pipe When executing
docker run --rm -v ldaps_ldap-config:/volume -v /tmp/tmp.VznAcI3PTA:/backup busybox tar c -Jvf /backup/ldap-config.tar /volume

I always get the following output:
BusyBox v1.31.0 (2019-07-16 01:13:11 UTC) multi-call binary.

Usage: xz -d [-cfk] [FILE]...

Decompress FILE (or stdin)

    -d  Decompress
    -c  Write to stdout
    -f  Force
    -k  Keep input files
tar: write error: Broken pipe

I use the following versions:
Docker version 18.06.3-ce, build d7080c1
BusyBox v1.31.0 (2019-07-16 01:13:11 UTC) multi-call binary.

Is this because of busybox or am I doing something wrong?
How can I fix this?

A: The Busybox container only has the Busybox version of xz, which can only decompress.
The simplest option here is to use another compressor; the safest best is -z instead of -J (gzip).


text:
Q: Return list of items to a controller method I have these tables in my database, Presses, Paper, and PressPaperSpeeds:
Presses
----------------
PressID (PK)
Name

Paper
----------------
PaperID (PK)
Name

PressPaperSpeeds
----------------
PressPaperSpeedID (PK)
PressID (FK)
PaperID (FK)
Speed

When I'm adding a Press, I'd like to have a table to add PressPaperSpeeds. In one column, it contains all the Papers, and in another column, a textbox to enter the Speed. Here's what I have on my view page to create a Press:

    <% foreach(Paper paper in Model.Papers) { %>

            <%: paper.Name %>
            <input type="text" />

    <% } %>

My view model contains Papers, which is just a collection of all Papers from the database.
Here's my controller method:
[HttpPost]
public ActionResult Create(PressesViewModel viewModel)
{
    Press press = new Press();
    TryUpdateModel(press);

    if (ModelState.IsValid)
    {
        //somehow get all values for Press Paper Speeds and save them here
        DBRepository.SavePress(press);
        return RedirectToAction("Details", new { id = press.PressID });
    }
    return View(viewModel);
}

How can I get the PaperID and Speed value from the textbox for that table of speeds, and return it to my controller?

A: ok then i will create my viewmodel like
public class PressViewModel
{
public int PressID{get;set;}
public string Name{get;set;}
public IEnumerable<VMPressPaperSpeed> PressPaperSpeeds{get;set;}
}

public class VMPressPaperSpeed{
public int PressPaperSpeedID{get;set;}
public int PressID{get;set;}
public int PaperID{get;set;}
public string PaperName{get;set;}// for view purpose
public int Speed{get;set;}//change data type for speed accordingly
}

My controller would look like
[HttpGet]
public ActionResult Create()
{
  var model = new PressViewModel();
  model.PressPaperSpeeds = _SomeRepository.PopulatePaperDataLeavingIDsUntouched();
  // after this line i will have all paper information inside my viewmodel's property that will be passed to view and user will enter corresponding speeds for current press
}

My view will look like
    <%:Html.LabelFor(x=>x.Name)>
    <%:Html.TextBoxFor(x=>x.Name)>
    <%:Html.HiddenFor(x=>x.ID)%>

    <%for(int i=0;i<Model.PressPaperSpeeds.Count;i++){%>
    <%:Html.PaperName%>
    <%:Html.Hidden("Model.PressPaperSpeeds["+i+"].PressPaperID" Model.PressPaperSpeeds[i].PressPaperSpeedID)%>
<%:Html.Hidden("Model.PressPaperSpeeds["+i+"].PressID" Model.PressPaperSpeeds[i].PressID)%>
<%:Html.Hidden("Model.PressPaperSpeeds["+i+"].PaperID" Model.PressPaperSpeeds[i].PaperID)%>
<%:Html.TextBox("Model.PressPaperSpeeds["+i+"].Speed" Model.PressPaperSpeeds[i].Speed)%>
<%:Html.Hidden("Model.PressPaperSpeeds["+i+"].PaperName" Model.PressPaperSpeeds[i].PaperName)%>

put everything in form fill it out and press submit button. go to post action method put a break point and see things will be populated in your viewModel and tryUpdate Model should also work as well but you have to name properties in your viewmodel exactly the way they are in model. Don't miss EntitySet property name.


text:
Q: Swift 3 - Send make synchronous http request I have the following code:
func completeLoadAction(urlString:String) -> Int {
    let url = URL(string:urlString.trimmingCharacters(in: .whitespaces))
    let request = URLRequest(url: url!)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {                                                 // check for fundamental networking error
            print("error=\(error)")
            let ac = UIAlertController(title: "Unable to complete", message: "The load has been added to the completion queue. This will be processed once there is a connection.", preferredStyle: .alert)
            ac.addAction(UIAlertAction(title: "OK", style: .default))
            self.present(ac, animated:  true)
            return
        }

    let httpStatus = response as? HTTPURLResponse
        var httpStatusCode:Int = (httpStatus?.statusCode)!

        let responseString = String(data: data, encoding: .utf8)
        print("responseString = \(responseString)")
        let ac = UIAlertController(title: "Completed Successfully", message: "The "+coldel+" has been completed successfully", preferredStyle: .alert)
        ac.addAction(UIAlertAction(title:"Continue", style: .default, handler:  { action in self.performSegue(withIdentifier: "segueConfirmedLoad", sender: self) }))

        self.present(ac, animated: true)

    }
    task.resume()
    return httpStatusCode
}

I need to be able to call this and at the same time check the return value as it is the http status code, it will let me know if the call was successful or not.
Problem is because it's in a dataTask I can't access the responses status code here
var httpStatusCode:Int = (httpStatus?.statusCode)!

Because the task doesn't start until Task.Resume() is called and the task is asynchronous so it will never work.
Are there any ways around this?

A: To make it synchronous and wait you can use semaphores such as below
struct Login {

    static func execute() -> Bool {
        let request = NSURLRequest....

        var success = false
        let semaphore = DispatchSemaphore(value: 0)
        let task = URLSession.shared.dataTask(with: request, completionHandler: { _, response, error in
            if let error = error {
                print("Error while trying to re-authenticate the user: \(error)")
            } else if let response = response as? HTTPURLResponse,
                300..<600 ~= response.statusCode {
                    print("Error while trying to re-authenticate the user, statusCode: \(response.statusCode)")
            } else {
                success = true
            }
            semaphore.signal()
        })

        task.resume()
        _ = semaphore.wait(timeout: DispatchTime.distantFuture)
        return success
    }
}

A: You can use DispatchGroup for sync network calls. More thread safe.
        let group = DispatchGroup()
        for i in 0...100 {
          group.enter()
          URLSession.shared.dataTask(with: NSURL(string: "___URL_STRING___")! as URL, completionHandler: { (data, response, error) -> Void in
                defer { group.leave() }
                print("json:\(i)")
          }).resume()
          group.wait()
        }

A: There is always a way to use the asynchronous pattern.
To make the function asynchronous add a completion block
func completeLoadAction(urlString:String, completion: (Int) -> ()) {
   let url = URL(string:urlString.trimmingCharacters(in: .whitespaces))
   let request = URLRequest(url: url!)
   let task = URLSession.shared.dataTask(with: request) { data, response, error in
      guard let data = data, error == nil else {                                                 // check for fundamental networking error
         print("error=\(error)")
         DispatchQueue.main.async {
            let ac = UIAlertController(title: "Unable to complete", message: "The load has been added to the completion queue. This will be processed once there is a connection.", preferredStyle: .alert)
            ac.addAction(UIAlertAction(title: "OK", style: .default))
            self.present(ac, animated:  true)
         }
         completion(0) // or return an error code
         return
      }

      let httpStatus = response as? HTTPURLResponse
      var httpStatusCode:Int = (httpStatus?.statusCode)!

      let responseString = String(data: data, encoding: .utf8)
      print("responseString = \(responseString)")
      DispatchQueue.main.async {
         let ac = UIAlertController(title: "Completed Successfully", message: "The "+coldel+" has been completed successfully", preferredStyle: .alert)
         ac.addAction(UIAlertAction(title:"Continue", style: .default, handler:  { action in self.performSegue(withIdentifier: "segueConfirmedLoad", sender: self) }))
         self.present(ac, animated: true)
      }
      completion(httpStatusCode)
   }
   task.resume()

}

and call it thusly
completeLoadAction(urlString: "www.something.com") { code in
   print(code)
}

A: This won't work in all situations.   Suppose you are implementing a shared extension.  And you are overriding the isContentValid() method that returns a boolean (true if the content is valid)... but in order to test if the content is valid, you want to verify that the server is running (this is a contrived example).  If you make an asynchronous http call--completion block or not--you cannot return the proper value of the boolean; the only way to accomplish this is to do a synchronous call and return true/false based on the return value.
The answer that posted the semaphore pattern is the proper one to use in this case.

A: Complementary things to @darren102 answer using Semaphore:
If you find the solution using DispatchSemaphore  as the right fit for you (for whatever reason) keep in mind that you can end up in deadlock (your signal will never be called) if the the wait and signal are called on the same thread, e.g. main queue, or some other serial queue. This can easily happen without you noticing it looking at your code. Therefore alsways add some timeout for your request so your app does not freeze, lets say 5 seconds.
_ = semaphore.wait(timeout: 5)

Also if you happen to call this custom made Semaphore syncronous function inside some closure of asychronous URL request, you can end up with signal not called (either by dispatching to the same queue or by going out of threads with thread explosion, so basically your system will wait on the same thread to be realeased, but this never happens). You will spot this problem by your semaphore waiting , and proceeding after timeout. If you want to avoid this kind of situation, call the execute() function on concurrent queue (e.g. global() ) , here is example:
func logout(_ completion: @escaping () -> ()) {
    sendUrlRequest() { [weak self] (response, error) -> () in

        //do some stuff
        completion()
    }
}

func hideLoading() {
    DispatchQueue.main.async {
        //does hide loading
    }
}

func execute() -> Bool {
        let request = NSURLRequest....

        var success = false
        let semaphore = DispatchSemaphore(value: 0)
        let task = URLSession.shared.dataTask(with: request, completionHandler: { _, response, error in
            if let error = error {
                print("Error while trying to re-authenticate the user: \(error)")
            } else if let response = response as? HTTPURLResponse,
                300..<600 ~= response.statusCode {
                    print("Error while trying to re-authenticate the user, statusCode: \(response.statusCode)")
            } else {
                success = true
            }
            semaphore.signal()
        })

        task.resume()
        _ = semaphore.wait(timeout: 5)
        return success
    }

Calling execute() on concurrent queue alongside other stuff:
 logout { [weak self] in
    DispatchQueue.global().async { //calling the whole logout scope on concurrent queue
        _ = self?.execute()
            self?.hideLoading()
    }
}

Hopefully this has been at least a bit helpfull as a complementary answer. However above all my biggest recommendation is not using such semaphore synchronous code and stick to old fashioned completion in closure (as Apple recommends) and is written in this answer


text:
Q: How to save result in separate column in excel using shell script I am saving the executed output in the excel sheet, the results will show in the new row like below
I do have the request like this,
db.cassandra.contactPoints     10.11.12.13
db.cassandra.port                8080
server.host                10.10.10.10:9443
server2.host             10.12.12.12:9001
sftp.host             abcdiefgh.unix.hes2000.org
sftp.port                     22

Expected output

filename                   hostname          Port
db.cassandra.contactPoints  10.11.12.13        8080
server.host                 10.10.10.10        9443
server2.host                10.12.12.12        9001
sftp.host          abcdiefgh.unix.hes2000.org   22

I have used below script
grep -P '((?<=[^0-9.]|^)[1-9][0-9]{0,2}(\.([0-9]{0,3})){3}(?=[^0-9.]|$)|(http|ftp|https|ftps|sftp)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?|\.port|\.host|contact-points|\.uri)' $filename | awk 'BEGIN {print "Column_A\tColumn_B"}NR%2 {if(next = "%port%"){printf "%s \t",$0;next;}}1' | grep '^[^#]' | awk '{split($0,a,"="); print a[1],","a[2]}'

Thank you in advance for your suggestions

A: Could you please try following.
awk '
BEGIN{
  print "Filename hostname port"
}
/:[0-9]+/{
  sub(/:/,"\t")
  print;
  next
}
NF==2{
  if($NF~/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/ || $NF~/[a-zA-Z]+\..*\.[a-zA-Z]+$/){
    val=$0
  }
  else{
    if(val){
      print val,$NF
      val=""
    }
  }
}
' Input_file | column -t

Explanation: Adding detailed explanation for above code here.
awk '                                                                             ##Starting awk program from here.
BEGIN{                                                                            ##Starting BEGIN section of this program here.
  print "Filename hostname port"                                                  ##Printing header for output here.
}
/:[0-9]+/{                                                                        ##Checking condition if line has colon digits then do following.
  sub(/:/,"\t")                                                                   ##Substitute colon with TAB here in line.
  print;                                                                          ##Printing the current line here.
  next                                                                            ##next will skip all further statements from here.
}
NF==2{                                                                            ##Checking condition if number of fields in a Line are 2 then do following.
  if($NF~/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/ || $NF~/[a-zA-Z]+\..*\.[a-zA-Z]+$/){    ##If a line is in ip format or domain format then do following.
    val=$0                                                                        ##Creating variable val which has current line value in it.
  }
  else{                                                                           ##Mentioning else here.
    if(val){                                                                      ##Checking condition if variable val is NOT NULL then do following.
      print val,$NF                                                               ##Printing variable val and last field of line here.
      val=""                                                                      ##Nullifying variable val here.
    }
  }
}
'  Input_file | column -t                                                              ##Mentioning Input_file name here and passing whole output to column command.


text:
Q: Runtime Error encountered while taking Screenshot in iMacros While taking screenshot of a webpage via iMacros,RuntimeError: SAVEAS requires File IO interface installed is displayed.How to overcome it.

A: You should use SCREENSHOT funcionality instead of SAVEAS. Use SAVEAS to create a HTML file.
(http://wiki.imacros.net/SCREENSHOT)
I use palemoon version 25.0.0, which can be obtained on (ftp://archive:get@archive.palemoon.org/Pale_Moon/25.x/25.0.0/Palemoon-Portable-25.0.0.win64.exe) - Don't forget to hinder browser ability to auto-update.
Firefox recent versions can´t access file system.


text:
Q: No sound or networking So yesterday I broke my sudo when I changed the permissions of the /usr folder. But late into the night I was able to restore it.
Now my sound and networking do not work. Videos also do not play because the sound doesn't work. It also doesn't show me the battery meter. apt-get -f install, dpkg --configure -a, and, sudo apt-get update && sudo apt-get install upgrade don't help, the last one because there isn't any internet connection.
Please help me. Thanks in advance.

A: is a jungle there....
all in the /usr is under the root user so i guess that a
chown root:root usr
chown root:root usr/*
chown root:root usr//
chown root:root usr///*
should do the trick....
the problem is that
root@ubuntu:/usr/include# ll sound/
total 144
drwxr-xr-x  2 root root  4096 Jul  6 01:27 ./
drwxr-xr-x 53 root root 20480 Jul  6 01:27 ../
-rw-r--r--  1 root root 22029 Jun 18 21:35 asequencer.h
-rw-r--r--  1 root root  4313 Jun 18 21:35 asound_fm.h
-rw-r--r--  1 root root 39635 Jun 18 21:35 asound.h
-rw-r--r--  1 root root 16843 Jun 18 21:35 emu10k1.h
-rw-r--r--  1 root root  3076 Jun 18 21:35 hdsp.h
-rw-r--r--  1 root root  5464 Jun 18 21:35 hdspm.h
-rw-r--r--  1 root root  4238 Jun 18 21:35 sb16_csp.h
-rw-r--r--  1 root root  7430 Jun 18 21:35 sfnt_info.h
the folder has the drwxr-xr-x permissions and the files -rw-r--r-- and that is translated in chmod 777 or 644 .. or other permission....
so if you have modified with the chmod command is a jungle to make every file back as they was...  http://en.wikipedia.org/wiki/Chmod


text:
Q: Multiple font sizes in a single QML Text element I've been trying to get a Text element to display text of varying size via some rich text formatting:
  Text {
    font.pointSize: 30
    text: 'T' +
          'T' +
          'T' +
          'T' +
          'T' +
          'T' +
          'T' +
          'T' +
          'T' +
          'T' +
          'T' +
          'T' +
          'T' +
          'T' +
          'T' +
          'T' +
          'T' +
          'T' +
          'T' +
          'T' +
          'T' +
          'T'
  }

Unfortunately, as made evident by the end result, it seems that only size 1 to 7 and -1 to -2 works as expected, everything else has zero effect.

What I want in particular is text that is significantly smaller than the set value of 30pts, around 10 or so would be ideal, however I cannot get that low using any of the few options that worked.
Edit: I was able to get the desired size difference by changing the base size and using size 7 for the "normal" and size -2 for the small text, but nonetheless, I will leave the question in the event someone has a generic solution to get arbitrary sizing.

A: You trying to use the Text.RichText style text, so need do like this:
Text {
    textFormat: Text.RichText
    text: "

T

T

T

T

            "
}

I think your HTML text shall be detected as Text.StyledText, that is in the style of HTML 3.2. it supports limited font-size property of HTML tag:

Text.RichText supports a larger subset of HTML 4, as described on the
  Supported HTML Subset page.

The HTML 4 supports the CSS property in below:

font-size
  [ small | medium | large | x-large | xx-large ] | pt | px


text:
Q: Calculations based on series of previous rows I am new to SQL (only have done a course online so I am familiar with basics). I think the best way to describe my problem is by showing it through the table shown below:

I am trying to calculate the entries in col1.
What should I do?
THE CODE I AM USING IS:
SELECT *,SUM((col2)*POWER(1-col3,[ROW]-1)) OVER (ORDER BY [ROW] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) FROM [bak].[table]
BUT WHAT THIS DOES FOR EXAMPLE TO 4 IS: (1-C)^2*B1+(1-C)^2*B2+(1-C)^2*B3 INSTEAD OF (1-C)^2*B1+(1-C)*B2+B3

A: Hmmm . . . You need to raise values to a certain power, based on how far back they go.  Then you have a sum().
You can do this by assigning a sequential number and doing the cumulative sum with power().  But then you divide out the current row.
Without sample data, it is tricky to be sure this is exactly right, but the idea is:
select t.*,
       (sum(b * power(1 - c, seqnum)) over (order by id rows between unbounded preceding and 1 preceding) /
        power(1 - c, seqnum + 1)
       )
from (select t.*, row_number() over (order by id desc) as seqnum
      from t
     ) t;


text:
Q: Using inner join and group by I have a restaurants. So I have a "menu" table and an "orders" table. I want to find when a given dish was most recently ordered. So I know I have to use group by dishId at some point, but everything I try returns an error. The following query works, but it returns duplicates. I only want the most recent instance for each dish. Note that my "orders" table contains customer information that I am not presently interested in.
select o.timestamp, m.*
from orders o
inner join menu m
on (o.dishId = m.dishId);

A: I think the problem your having here is you need to include each of the columns you want to group by
select m.dishId, MAX(o.timestamp)
    from orders o
    inner join menu m
    on (o.dishId = m.dishId)
group by m.dishId;

If you want to group by more columns you have to add them in both places. Example:
select m.dishId, m.dishName, MAX(o.timestamp)
    from orders o
    inner join menu m
    on (o.dishId = m.dishId)
group by m.dishId, m.dishName;


text:
Q: What is a better solution to have a duplicate site with some different content? My client has got a corporate site and some dealer sites. He would like to have his dealer sites pretty much the same as the corporate site except having different contact information and a different team member page. Here is the question, is there a way that if he updates the corporate site, it updates all the dealer sites as well? Because the content is the same, he does not want to login to every site, copy and paste the content again and again. Any suggestions? I thought about using iframe, but is it good for seo if 95% of the site is iframe?

A: One method you could use is a singular CMS service that houses all the content for all the sites.
Once the user browses to the site you can provide a host header look up to determine which dealer site (or corporate) the user is browsing to. From this information it should be relatively easy to load different contact information.
As you haven't provided many other details such as web server, programming language we can really only help you with theoretical answers.
Hope this helps.


text:
Q: Random down voting of questions on Stack Overflow I posted a question on Stack Overflow and got a down vote.
What I don't understand is the reason for down vote.
Here is my post:
Figuring out the complexity of the code
Does random down voting with out a justification help the community at all?

A: No, random downvoting without a justification does not help the community at all. However, we do not know the downvoter had no justification, merely that we are not privy to it.
Any rules against "random" downvoting would be virtually unenforceable, so the best advice I can give you here would be to shrug and move on.

A: Down (and up) voting is how the community expresses their opinion on the quality of the question.  While it's nice to leave a comment, it's certainly not mandatory or even necessary for learning.
Look at the questions that are similar but have more upvotes than downvotes, and see how they are different from yours.


text:
Q: Google DriveService C# leaking HttpConnection objects I have an application that utilizes Google's Drive service using the C# SDK.  I am using Service Account credentials, with impersonation to specify the user I am acting on behalf of.
The issue I'm having is that I need to create a new DriveService for each impersonated user, and each of those DriveService isntances creates 2 HttpConnection objects that are NOT cleaned up when I Dispose() the DriveService.  I have repro'd this in a unit test.  I create the DriveService in this method:
public DriveService GetDriveService(string email)
    {
        var serviceAccountEmail = "service account email";
        var privateKey = "private key";

        var serviceAcctCreds =  new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
        {
            User = email,
            Scopes = "scopes" }),
        }.FromPrivateKey(privateKey));

        var driveService = new DriveService(new BaseClientService.Initializer
        {
            HttpClientInitializer = serviceAcctCreds,
            ApplicationName = "app name",
        });

        return driveService;
    }

Then use it as so:
public async Task DoTheGDriveMemoryTest()
        {
            var userEmails = new List<string>
            {
                 "email1@example.com", "email2@example.com"
            };
            var i = 1;
            while (true)
            {
                foreach (var email in userEmails)
                {
                    //recommend using Fiddler Autoresponders here
                    using (var service = GetDriveService(email))
                    {
                        var request = service.Changes.List("delta id");
                        try
                        {
                            var result = await request.ExecuteAsync();
                        }
                        catch (Exception e)
                        {
                            //do nothing
                        }
                    }
                }
            }
        }

This results in an ever-increasing number of HttpConnection objects held in memory, that are not cleaned up with Garbage Collection.

A: If DriveService is using HttpClient under the covers, you may be running into dispose not working on a shared object, or connections being held until a timeout.

But HttpClient is different. Although it implements the IDisposable interface it is actually a shared object.

See https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/

A: As Mike M has stated, this is a known problem with HttpClient in that its Dispose() method doesn't really dispose of the instance.
Unfortunately because the way the Google.Apis.Auth library ties together the HttpClient and the credentials, I can't see a nice workaround for this.
Here is a very hacky workaround, that allows you to share one HttpClient between all the RPCs.
Define a custom IHttpClientFactory:
class SharedHttpClientFactory : IHttpClientFactory
{
    public SharedHttpClientFactory()
    {
        _handler = new ConfigurableMessageHandler(new HttpClientHandler());
        _client = new ConfigurableHttpClient(_handler);
    }

    private readonly ConfigurableMessageHandler _handler;
    private readonly ConfigurableHttpClient _client;
    private Action _clearHandlers = null;

    public ConfigurableHttpClient CreateHttpClient(CreateHttpClientArgs args)
    {
        _clearHandlers?.Invoke();
        var executeInterceptors = args.Initializers.OfType<IHttpExecuteInterceptor>().ToList();
        var unsuccessfulResponseHandlers = args.Initializers.OfType<IHttpUnsuccessfulResponseHandler>().ToList();
        _clearHandlers = () =>
        {
            foreach (var executeInterceptor in executeInterceptors)
            {
                _handler.RemoveExecuteInterceptor(executeInterceptor);
            }
            foreach (var unsuccssfulResponseHandler in unsuccessfulResponseHandlers)
            {
                _handler.RemoveUnsuccessfulResponseHandler(unsuccssfulResponseHandler);
            }
        };
        foreach (var executeInterceptor in executeInterceptors)
        {
            _handler.AddExecuteInterceptor(executeInterceptor);
        }
        foreach (var unsuccssfulResponseHandler in unsuccessfulResponseHandlers)
        {
            _handler.AddUnsuccessfulResponseHandler(unsuccssfulResponseHandler);
        }
        _handler.ApplicationName = args.ApplicationName;
        return _client;
    }
}

Create a single instance of this factory:
var factory = new SharedHttpClientFactory();

Then create every DriveService using this factory:
var client = new StorageService(new Google.Apis.Services.BaseClientService.Initializer
{
    HttpClientFactory = factory,
    HttpClientInitializer = serviceAcctCreds
});

Caveats abound:

*

*Do not dispose of the DriveService as this will dispose of the underlying shared HttpClient.

*All the DriveService instances share the same credentials; these credentials are changed each time a new DriveService is instantiated. This means that all previous instances also have their credentials updated.

*The credential passed into the initializer HttpClientInitializer property must be a ServiceCredential instance (as it is in your code). This won't work if it's a GoogleCredential instance.

*This whole thing isn't really advised, is definitely a nasty hack, but I can't see a better/simpler workaround.


text:
Q: Подскажите сборщики html для gulp Подскажите, как можно подключать html файлы один в другой в определённом месте и как их сжимать в gulp?

A: Добрый день. Касательно импорта html в html есть вот такие варианты
http://www.webmasters.by/articles/html-coding/3288-html5-imports.html
https://habrahabr.ru/post/230751/
Что касается импорта в pug, то тут возможно воспользоваться подгрузкой блока через AJAX


text:
Q: Creating a Function That Sets a Variable to a Random Integer I am writing a shell script on my Linux machine, and I'm trying to figure out a good way to write a function that I could call that would set a variable, let's call it $variable, to a random number between 1 and 466,550.  Of course I could write;
shuf -i 1-466550 -n 1

And it'll do the trick, but how could I write this in a function to have it set my variable, $variable, to that random number (until the function is called again, at which case it picks another random integer from 1-466,550)?

A: I would highly recommend reading through a bash scripting guide.
I usually recommend Bash Scripting for Beginners and Advanced Bash-Scripting Guide, though they have not been updated for a couple of years...
With that said, here's an example of how it could be done.
#!/usr/bin/env bash

generate_random() {
    shuf -i 1-466550 -n 1
}

variable="$(generate_random)"
echo "random number: ${variable}"
variable="$(generate_random)"
echo "another random number: ${variable}"

A: Generating a random number with bash $RANDOM variable:
#!/bin/bash

f(){
    echo $(((RANDOM * RANDOM) % 466550 + 1))
}
x=$(f)
echo $x


text:
Q: compare string with list and print only matched keywords in python frontvar="risk management system application tracking system digital signature computer systems "

listvar = ['c','computer system','tracking','management',etc]

matchedkeys =[i for i in listvar if i in frontvar]

output :['c',
 'ca',
 'com',
 'computer systems',
 'eme',
 'git',
 'io',
 'man',
 'management',
 'nat',
 'om',
 'ppl',
 'r',
 're',
 'tal',
 'track',
 'tracking']

the list(listvar) is very big
i want to print exactly matched words like computer,computer system,risk management system etc.. it should not print junk values like('nat',
 'om',
 'ppl',
 'r',
 're',
 'tal',
 'track')

A: You're checking for substring match, not word match.
Just change:
matchedkeys = [i for i in listvar if i in frontvar]

To:
matchedkeys = [i for i in listvar if i in frontvar.split()]

Splitting the frontvar string into a list will match against the words in frontvar instead of the characters in the string.

A: To match just a single word from frontvar, just change
matchedkeys = [i for i in listvar if i in frontvar]
to
matchedkeys = [i for i in listvar if i in frontvar.split()] as @mVChr suggested.
To match multiple words, I'd suggest either using a tuple as mVChr suggested (not sure why that wasn't working for you, you'd have to post an update), or to do as follows:
matchedkeys = [i for i in listvar if all([j in frontvar.split() for j in i.split()])]
This will get anything in listvar if every word in listvar is also a word in frontvar. (I use "word" here to describe substrings separated by whitespace.)
I'm not sure if this is actually what you want, your question is slightly unclear to me and I don't have enough reputation to comment. If you're doing something a bit more complicated, a regex might also be appropriate.


text:
Q: How to run a command in unix shell and then get the output back from/to java application I know how to execute a shell command from my java app.  It should be something like:
String command = "java -version";
Process proc = null;
try {
  proc = Runtime.getRuntime().exec(command);
}
catch (IOException e) {
System.out.print(e);
}

I want to get the output of this command back to my java app, without printing the output to some temporary file which I then read from my app.  Is this possible?

A: You need to use ProcessBuilder
Process process = new ProcessBuilder(
"C:\\PathToExe\\exe.exe","param1","param2").start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;

System.out.printf("Output of running %s is:", Arrays.toString(args));

while ((line = br.readLine()) != null) {
  System.out.println(line);
}

code that is already found on stackoverflow Execute external program in java


text: Q: Valuative criterion over non-locally Noetherian base Let $X$ be an irreducible scheme and $f:X\rightarrow S$ be a morphism of finite type. Let $\eta$ be the generic point of $X$. Assume that for any (not necessarily discrete) valuation ring $A \subset K=k(\eta)$ with $\mathrm{Frac}(A)=K$ and any diagram such that $\mathrm{Spec}\,K\rightarrow X$ is the inclusion of generic point there exists a unique dotted arrow. Is $f$ necessarily proper?


text:
Q: number of distinct de Bruijn sequences B(n,k) I am trying to find out where does the formula for finding the number of all distinct de Bruijn sequences come from.
Wikipedia page
:https://en.wikipedia.org/wiki/De_Bruijn_sequence
here is the formula part:B(n,k)
p.s: This is not homework! I'm just self-studying Graph Theory.


text:
Q: How-to carry out a set of operations on a large set of three-dimensional vectors in most efficient manner? Problem description
Essentially, I am trying to carry out a set of operations on a significantly large set of coordinate data. The coordinates in the data set represent a uniformly distributed set of points within some complex geometry on per geometry entity basis. I know how to carry out some operations necessary to achieve what, ideally, would be my objective. However, I ran into difficulties putting different components of the algorithm together. This can be described by insufficient knowledge of programming in Mathematica at current time.
Below is a narrowed down example of what I am trying to achieve:
Input data [example]
origins = {{-2.87985, 0.27489, 1.2342}, {-2.8102, 0.2323,
    1.1111}, {-3.2728, -0.1247, 0.0023}, {-3.1846, -0.2364,
    1.2206}, {-3.0209, -0.2992, 0.6696}};
destinations = {{6.2662, 16.3095, 0.8657}, {4.2532, 14.7594,
    3.5271}, {5.5305, 5.35983, 3.61508}, {4.48381, 15.74443,
    0.3802}, {6.6048, 10.1849, 1.4391}};
offset = {#[[1]], #[[2]]+6, #[[3]]} & /@ origins;

Output [incomplete]
Graphics3D[{
    (*Origin*)
    Cylinder[{{-3, 0, 0}, {-3, 0, 2}}, 0.3],
    {PointSize[0.1], Red, Point@#1},
    (*Offset*)
    {PointSize[0.05], Green, Point@#2},
    (*Rotation*)
    Tooltip[{PointSize[0.05], Blue,
      GeometricTransformation[Point@#2,
       RotationTransform[Pi/2, {0, 0, 1}, #1]]}, "Rotation: \[Pi]"]
    },
   Axes -> True,
   AxesLabel -> {"x", "y", "z"}] &[origins[[1]], offset[[1]]]

Following is a set of steps which I would like to be able to carry out on the above data set:

*

*Offset each vectors 'y' coordinate value by some number;

*Rotate the offset products around their associated origins in {Pi/2, Pi, 3 Pi/2, 2 Pi}

*Upon each rotation of the offset components, calculate the distance between the new coordinates of the associated vector and ALL coordinates in the destinations set.

Issues
In the above output example, I have applied the GeometricTransformation in a form of RotationTransformation and I was able to rotate the Point around the origin as it was intended. However, in this example, I have specified the rotation axes manually. Given that I am working with a complex geometry, would there be a way how to achieve the axe selection automatically?
It is my current understanding in order to achieve the distance calculation I could use inbuild functions such as Outer and EuclideanDistance. What I strugle with is formulating the algorithm to carry out all of the above in the most efficient manner.
I would appreciate any input on the subject matter and hope to learn from this activity.
EDIT 1: Clarification
In order to visualize the relation between the origin and the offset coordinates, please see table below:

Additionally, the rotation axis must be {0,1,0} for vertically positioned cylinders and {0,0,1} for horizontally positioned Cylinder.
I have also found a flow in my initial design. The flow is releted to the offset coordinates. As with rotation axis, the offset must commence based on Cylinder position (vertical -> {0,1,0}, horizontal -> {0,0,1})


text:
Q: Get characters of a string starting from last part of string up to a period I have an array with such strings as:
filename.pdf
filename.xls
filename.txt
filename.ppt

How can I grab the string, start at last part of the string and work my way up to the immediate period, so that I can determine .pdf and '.xlsand.ppt` and so on?

A: You can use split, which uses explode in the background and return the last element,
data
data:
    - filename.pdf
    - filename.xls
    - filename.txt
    - filename.ppt

twig
{% for file in data %}
    {{ file | split('.') | last }}
{% endfor %}

demo


text:
Q: Powershell delete MSMQ remotely I was wondering if it was possible to delete queues remotely via PowerShell? I have the following script:
cls

[Reflection.Assembly]::LoadWithPartialName("System.Messaging")

$computers = @("comp1","comp2","comp3");

foreach($computer in $computers) {

    $messageQueues = [System.Messaging.MessageQueue]::GetPrivateQueuesByMachine($computer);

    foreach ($queue in $messageQueues) {
        $endpoint = [string]::Format("FormatName:DIRECT=OS:{0}\{1}", $computer, $queue.QueueName);

        Write-Host $endpoint
        [System.Messaging.MessageQueue]::Delete($endpoint);
    }
}

This works fine, if I was running it on the machine whose queues I want to delete however when I run this remotely I get the error:
The specified format name does not support the requested operation. For example, a direct queue format name cannot be deleted.

Any ideas if this can be done?
EDIT
Oddly, I have figured I can remote onto the machine via PowerShell and execute a script block. However, I don't understand the difference between doing:
THIS:
$endpoint = [string]::Format("FormatName:DIRECT=OS:{0}\{1}", $computer, $queue.QueueName);
Invoke-Command -ComputerName $computer -ScriptBlock { [Reflection.Assembly]::LoadWithPartialName("System.Messaging"); [System.Messaging.MessageQueue]::Delete($endpoint) };

AND THIS:
Invoke-Command -ComputerName $computer -ScriptBlock { [Reflection.Assembly]::LoadWithPartialName("System.Messaging"); [System.Messaging.MessageQueue]::Delete("FormatName:DIRECT=OS:MY_SERVER\some.endpoint") };

The value of $endpoint is the same however, for some odd reason it doesn't like the variable approach though both values are identical. I tested this by setting $endpoint then calling delete. I get the error:
Exception calling "Delete" with "1" argument(s): "Invalid value  for parameter path."

What I'm trying to say is if I hard code the value as part of the argument it works but assign it to a variable then invoke the method I get an error

A: For historic purposes if anyone else is experiencing this issue or is wondering how to delete queues remotely then please see below.

*

*How do I delete private queues on a remote computer? It is possible to delete queues remotely. This can be achieved using the command Enable-PSRemoting -Force. Without this, you encounter the issue @JohnBreakWell indicated (see his link to MSDN).

*The scope of variables when using Invoke-Command? The problem I found was the variables I declared were simply out of scope (script block was unable to see it). To rectify this, I simply did the following:
The important bit being the argument list and the use of param.
 $computers = @("comp1","comp2");

    foreach($computer in $computers) {
        [Reflection.Assembly]::LoadWithPartialName("System.Messaging");

        $messageQueues = [System.Messaging.MessageQueue]::GetPrivateQueuesByMachine($computer);

        foreach ($queue in $messageQueues) {
            $endpoint = [string]::Format("FormatName:DIRECT=OS:{0}\{1}", $computer, $queue.QueueName);

            Enable-PSRemoting -Force
            Invoke-Command -ComputerName $computer -ScriptBlock {
                param ($computer, $endpoint)
                [Reflection.Assembly]::LoadWithPartialName("System.Messaging");
                [System.Messaging.MessageQueue]::Delete($endpoint)
            }

        } -ArgumentList $computer, $endpoint

    }

A: You cannot delete a remote private queue.
You need to perform the operation locally to the queue.
From MQDeleteQueue:
Remarks
(2nd paragraph)
"Private queues registered on a remote computer ... cannot be deleted."

A: As Dr. Schizo mentioned, you'll need to execute
Enable-PSRemoting -Force

on the remote machine, but then, assuming you're using Server 2012 r2, it's as simple as:
Invoke-Command -ComputerName COMPUTERNAME { Get-MsmqQueue -Name QUEUENAME | Remove-MsmqQueue }


text:
Q: can't show the encrypted text on Logcat main func to try encrypt and show on logcat
aes = new ofxLibcrypto();
// start
unsigned char *key = (unsigned char *)"qwertyuiqwertyuiqwertyuiqwertyui";
unsigned char *iv = (unsigned char *)"qwertyuiqwertyui";
unsigned char *plaintext = (unsigned char *)"The quick brown fox jumps over the lazy dog";
unsigned char *ciphertext;
unsigned char decryptedtext[128];
int ciphertext_len, decryptedtext_len;
ciphertext_len = aes->encrypt(plaintext, strlen((char*)plaintext), key, iv, ciphertext);

ofLogNotice("IDB") << "Encrpyted: " << ciphertext;

decryptedtext_len = aes->decrypt(ciphertext, ciphertext_len, key, iv, decryptedtext);
decryptedtext[decryptedtext_len] = (unsigned char) "\0";
ofLogNotice("IDB") << "Decrypted: " << decryptedtext;
// end

Program encrypts successfully but when I try to show the ciphertext, it shows only first char. When I try to show char by char in a loop, it shows all chars as encrypted. I examined many codes to fix it but they do it this way and I can't fix it. Since encrypting and decrypting functions works fine, I didn't attach them but if needed I will attach.
Thanks already who will help.

A:
can't show the encrypted text

Your encrypted text(ciphertext) is a binary blob. It may have some printable characters such as A or ? or something, but is also going to have characters that are not printable for e.g characters with ASCII value 1, 2, 3 or even 0.
Consider this sequence of characters in a binary blob:
unsigned char data[] = {0x41, 0x00, 0x42, 0x43};
                     // 'A',  '\0', 'B',  'C'

data contains characters 'A', '\0'(null byte), 'B', 'C'. If you try to print data, you will only see A, because the next character is a null byte and it will stop printing immediately when it encounters that.
So then, how do you display a binary blob? The usual way to do it is by encoding the binary data as either base16 or some other base.
Here's a simple function to encode your data in base16:
template <typename T>
std::string toBase16(const T itbegin, const T itend)
{
    std::string rv;
    static const char hexmap[16] = { '0', '1', '2', '3', '4', '5', '6', '7',
        '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
    rv.reserve(std::distance(itbegin, itend) * 2);
    for (T it = itbegin; it < itend; ++it) {
        unsigned char val = (unsigned char)(*it);
        rv.push_back(hexmap[val >> 4]);
        rv.push_back(hexmap[val & 15]);
    }
    return rv;
}

Usage:
int ciphertext_len, decryptedtext_len;
ciphertext_len = aes->encrypt(plaintext, strlen((char*)plaintext), key, iv, ciphertext);

ofLogNotice("IDB") << "Encrpyted: " << toBase16(ciphertext, ciphertext + ciphertext_len);

Another way is to cast every byte to int and then display its decimal value:
unsigned char data[] = {0x41, 0x00, 0x42, 0x43};
                     // 'A',  '\0', 'B',  'C'
for (int i = 0; i < 4; ++i)
{
    cout << static_cast<int>(data[i]) << ' ';
}
//Output: 65 0 66 67


text:
Q: state hooks is not updating state on change I am building a simple blog app and I am trying to update title of the blog But it is not updating, it is just showing the current state.
I have tried many times by changing the method of setting state but it is still showing that error.
App.js
function BlogDetail() {
    const [blogName, setBlogName] = useState("");

    axios.get("/api/blog_detail/70/").then(res => {

       setBlogName(res.data[0].blog_name)
    })

  const handleChange = (e) => {
    console.log(e.target.value)
    setBlogName({
      ...blogName,
      [e.target.name]: e.target.value
    })
  }

  const saveBlog = (e) => {
   // sending to API
   console.log(blogName)
  }

   return (

       <form>

       {blogName}

       <input type="text" name="blogName" value={blogName} onChange={e => handleChange} />

       <button type="submit" onClick={e => saveBlog(e)}>Save</button>

       <form>

   )
}

And When I update on change instead of updating on submit
onChange=(e => setBlogName(e.target.value))

Then it is showing

A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined

I have tried many times but it is still not working.

A: input requires a string as a value, but you are trying to pass an object:
setBlogName({
  ...blogName,
  [e.target.name]: e.target.value
})

instead pass a string:
setBlogName(e.target.value)

Also, you need to execute handleChange function and pass the event param.
onChange={e => handleChange(e)}

Edit:
Looked at it second time and it should be like this:

function BlogDetail() {
    const [blogName, setBlogName] = useState("");

    // without this you override state every time you press a key
    useEffect(() => {
      axios.get("/api/blog_detail/70/").then(res => {

         setBlogName(res.data[0].blog_name)
      })
    }, [])

  const handleChange = (e) => {
    // just use value here
    setBlogName(e.target.value)
  }

  const saveBlog = (e) => {
   // sending to API
   console.log(blogName)
  }

   return (

       <form>

       {blogName}

       { /* remember to run the function */ }
       <input type="text" name="blogName" value={blogName} onChange={e => handleChange()} />

       <button type="submit" onClick={e => saveBlog(e)}>Save</button>

       <form>

   )
}

A: Besides the problem that within handleChange you need to pass an an string value to setBlogName you also need to wrap your axios fetch call in a useEffect.
The problem is that everytime you trigger a rerender while calling setBlogName you are calling your API point again and set the value back to the fetched value.
You should prevent that by doing the following ->
useEffect(() => {
  axios.get("/api/blog_detail/70/").then(res => {
     setBlogName(res.data[0].blog_name)
  }), [])

Don't forget to install { useEffect } from 'react'.
And well of course update handleChange ->
const handleChange = (e) => {
    const newBlogPostName = e.target.value
    console.log(newBlogPostName)
    setBlogName(newBlogPostName)
  }

A: you have not any action in this method. where is the update state?
const saveBlog = (e) => {
   // sending to API
   console.log(blogName)

  }

and in this method you change the string to an object
const handleChange = (e) => {
    console.log(e.target.value)
    setBlogName({
      ...blogName,
      [e.target.name]: e.target.value
    })
  }

A: so the problem is that your function updates your state to an object and then you want to display that object(not a string property of that object) in the DOM. its wrong because you cant display objects in the DOM in react. in this case, you even get an error because you cant use spread operator on strings. you cant do something like this: ...("test")
  const handleChange = (e) => {
    console.log(e.target.value)
    //the state value will be an object. its wrong. you even get an error
    because of using spread operator on a string
    setBlogName({
      ...blogName //this is a string at the init time,
      [e.target.name]: e.target.value
    })
  }

so whats the solution?
you should update your state to a string or use a string property of the object.
something like this:
      const handleChange = (e) => {
        console.log(e.target.value)

        setBlogName("string")
      }

      return (<>{blogName}</>)

thats it.


text:
Q: Lipschitz Continuous $\Rightarrow$ Uniformly Continuous The Question: Prove that if a function $f$ defined on $S \subseteq \mathbb R$ is Lipschitz continuous then $f$ is uniformly continuous on $S$.

Definition. A function $f$ defined on a set $S \subseteq \mathbb R$ is said to be Lipschitz continuous on $S$ if there exists an $M$ so that $$\frac{|f(x) - f(c)|}{|x - c|} \le M$$ for all $x$ and $c$ in $S$ such that $x \ne c$.

My Heuristic Interpretation: if $f$ is Lipschitz continuous then the "absolute slope" of $f$ is never unbounded i.e. no asymptotes.

Definition. A continuous function $f$ defined on $\mathrm{Dom}\, (f)$ is said to be uniformly continuous if for each $\varepsilon > 0 \ \exists \ \delta > 0$ s.t. $\forall \ x, c \in \mathrm{Dom}\, (f)$ $$ |x - c| \le \delta \ \Rightarrow \ |f(x) - f(c)| \le \varepsilon$$

Proof:
$f$ Lipschitz continuous $\Rightarrow$ $|f(x) - f(c)| \le M|x - c|$. Since we suppose $|x - c| \le \delta$ for uniform continuity, we have $x$ within $\delta$ of $c$, so $|x| \le |c| + \delta$. So taking $\delta = \varepsilon/M$
\begin{align*}
|f(x) - f(c)| &\le M|x - c| \\
& \le M\delta \\
& = \varepsilon
\end{align*}
My Question: Is my proof valid with the assumptions taken?

A: It's not very well organized, and it has some extraneous clutter, but it also has the core of the argument. You want to show that for each $\epsilon>0$ there is a $\delta>0$ such that $|f(x)-f(c)|<\epsilon$ whenever $x,c\in\operatorname{dom}f$ and $|x-c|<\delta$, so in a polished version of the argument your first step should be:

Suppose that $f$ is Lipschitz continuous on some set $S$ with Lipschitz constant $M$, and fix $\epsilon>0$.

You've already worked out that $\epsilon/M$ will work for $\delta$, so you can even start out with:

Fix $\epsilon>0$ and let $\delta=\frac\epsilon{M}$.

Now you want to show that this choice of $\delta$ does the job.

Clearly $\delta>0$. Suppose that $x,c\in S$ and $|x-c|<\delta$. Then by the Lipschitz continuity of $f$ we have $|f(x)-f(c)|\le M|x-c|<M\delta=\epsilon$, so $f$ is uniformly continuous on $S$. $\dashv$

Added: Your heuristic interpretation of Lipschitz continuity is inaccurate enough that it may well lead you astray at some point. Consider the function
$$f(x)=\begin{cases}
x\sin\frac1x,&\text{if }x\ne0\\
0,&\text{if }x=0\;.
\end{cases}$$
This function has no vertical asymptotes, but it's not Lipschitz continuous: for $n\in\Bbb Z^+\setminus\{0\}$ we have
$$\begin{align*}
\left|\frac{f\left(\frac1{2n\pi}\right)-f\left(\frac1{2n\pi+\frac{\pi}2}\right)}{\frac1{2n\pi}-\frac1{2n\pi+\frac{\pi}2}}\right|&=\left|\frac{\frac1{2n\pi+\frac{\pi}2}}{\frac1{2n\pi}-\frac1{2n\pi+\frac{\pi}2}}\right|\\
&=\left|\frac1{\frac{2n\pi+\frac{\pi}2}{2n\pi}-1}\right|\\
&=\left|\frac{2n\pi}{\pi/2}\right|\\
&=4|n|\,,
\end{align*}$$
which can be made as large as you want. This function has very, very steep bits, but they're also very, very short.

A: I suppose one small detail to add to Brian's answer is that in the argument we assumed $M\neq 0$. But the case for $M=0$ is trivial enough as that means $f$ is constant, which is clearly uniformly continuous (setting $\delta=\epsilon$).
$\textbf{Edit:}$
Suppose $f:S\to\mathbb{R}$ is Lipchitz continuous, then we have some $M\geq 0$ such that for all $x,y\in S$,
$$|f(x)-f(y)|\leq M|x-y|$$
Suppose $M>0$. Then, given some $\epsilon>0$, we set $\delta=\frac{\epsilon}{M}$. Then for all $x,y\in S$, we have
$$|x-y|<\delta\implies |f(x)-f(y)|\leq M|x-y|<M\cdot \frac{\epsilon}{M}=\epsilon$$
Hence $f$ is uniformly continuous.
If $M=0$, then it is easy to see $f(x)=f(y)$ for all $x,y\in S$, i.e. $f$ is constant. One can check easily that this is uniformly continuous (setting $\delta=\epsilon$).
Note, however, that the converse is not true. For instance, one can check that the function $f:[0,\infty)\to\mathbb{R}$ given by $f(x)=\sqrt{x}$ is uniformly continuous but not Lipschitz continuous.


text:
Q: Element is not clickable in selenium java (chrome driver) I am getting exceptions, when i am trying to click on Edit Criteria. Please someone can help me as
public void selectCriteriaFromWorklistsOptions() {
        waitABit(Constants.medium);
        for (int i = 0; i < 3; i++) {
            try {
                WebElement dropDown = getDriver().findElement(By.cssSelector(div.nav-menu__group > ul:nth-child(2) > li:nth-child(1) > button:nth-child(1)));
                dropDown.click();
                break;
            } catch (Exception e) {
                logger.debug((e.getMessage()));
            }
        }
    }

Also, I tried this also -
 WebElement element = waitForCondition().until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(text(),'Edit criteria')])")));
 element.click();

A: Wait for this element to become clickable.
And try using the following css selector:
.bttn-menu"

Or:
.nav-menu_bttn>.bttn-menu

Try 2:
button[bss-bttn-menu]

Try 3:
It should look like this in Java:
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(.nav-menu_bttn>button[bss-bttn-menu]")));

Check the amount of underscores _ by yourself. Probably there are two of them.


text:
Q: Get filename of PDF file open and save as I would like to identify the file name of a PDF file already open and copy the filename in an excel cell. After I would like to save this PDF under a specific folder with the name indicated in the excel cell.
I can do that with a word document but I found many difficulties with a pdf file. Thanks in advance for your help.
Lo


text:
Q: Odd "timeouts" when attempting to execute a MongoDB query from a Sails.js app When I start my Sails application in a localhost environment and load it in a browser, the view will render fine, an async request to another (non-mongo) resource works fine, but any async requests back to Sails that fetch data from Mongo works only within the first few moments of app start.
I can hammer as many requests as I want so long as I get one request in in the first few moments.  Beyond that, if I wait a full 2 or 3 seconds, the call will always stall.
Here's an example of the query using native:
    Item.native(function (error, collection) {
      collection.find().sort({'count': 1}).limit(parseInt(count)).toArray(function(error, data) {
        console.log(error, data);
        return res.send(data);
      });
    });

And another example using Waterline:
Item.find().sort('count ASC').limit(count).exec(function (error, data) {
  console.log(error, data);
  return res.send(data);
});

When it stalls, the callback is never called, so no error ever gets logged to the console.
I've tried stepping through the code and and it seems the flow of logic just bounces around from an internal _dispatch() function, to a couple of bind functions and back and forth and on and on.
I can verify that queries work fine from the Mongo console, and I'm seeding my database using Waterline on app start and that's also working fine.  I can also access the collection fine (the first callback using native executes).  I feel like I'm starting to run out of ideas, so any help would be great.  Thanks for taking a look.
Here's what I'm running for reference:

*

*sails: 0.11.0

*mongo: 2.6.10

*sails-mongo: 0.11.0

A: gconsidine, sails-mongo v0.11.0 and v0.11.1 have a bad connection configs. Check my answer on a previous thread: https://stackoverflow.com/a/29973775/4249576. Try updating sails-mongo to v0.11.2.


text:
Q: {puppetserver ca list --all} default host name and output format While migrating from puppet 5 to 6 (6.20), it was noticed that puppet cert ca list --all  was deprecated with puppetserver ca list --all.  When we execute this command we get an error:

Fatal error when running action 'list'   Error: Failed connecting to
https://puppet:8140/puppet-ca/v1/certificate_statuses/any_key   Root
cause: Failed to open TCP connection to puppet:8140 (getaddrinfo: Name
or service not known)

This error indicates that puppet is looking for a host names puppet whereas the puppetserver host alias in /etc/hosts is puppetserver.
When we add another alias as puppet to /etc/hosts then this command gets executed successfully. I have 2 queries on this

*

*Is there a mechanism to execute this command without modifying /etc/hosts

*What is the output structure of this command. I need to parse this using a script. In version 5 the format was having a prefix of +, - etc, which does not exists now.

A: Concerning 1-st question.
Now days it's due to default hard-coded or configured hostname under the hood.
Name may be defined in puppet.conf and no need to support /etc/hosts
[server]
server = fqdn.fqdn

or
[server]
ca_server = fqdn.fqdn

As described in configuration manual at https://puppet.com/docs/puppet/7/configuration.html#ca-server

ca_server
The server to use for certificate authority requests. It's a separate server because it cannot and does not need to horizontally scale.
Default: $server

However there is life hack:
$ cat /etc/hosts | grep puppet
127.0.0.1 puppetmaster puppet

And puppetserver ca will succeed too in certain cases.


text:
Q: How to calculate AUC with tensorflow? I've built a binary classifier using Tensorflow and now I would like to evaluate the classifier using AUC and accuracy.
As far as accuracy is concerned, I can easily do like this:
X = tf.placeholder('float', [None, n_input])
y = tf.placeholder('float', [None, n_classes])
pred = mlp(X, weights, biases, dropout_keep_prob)
correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

When calculating AUC I use the following:
print(tf.argmax(pred, 1).dtype.name)
print(tf.argmax(pred, 1).dtype.name)

a = tf.cast(tf.argmax(pred, 1),tf.float32)
b = tf.cast(tf.argmax(y,1),tf.float32)

auc = tf.contrib.metrics.streaming_auc(a, b)

and in the training loop:
train_acc = sess.run(accuracy, feed_dict={X: batch_xs, y: batch_ys, dropout_keep_prob:1.})
train_auc = sess.run(auc, feed_dict={X: batch_xs, y: batch_ys, dropout_keep_prob:1.})

which gives me the following output (and error) error:
int64
int64
/usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/array_ops.py:1197: VisibleDeprecationWarning: converting an array with ndim > 0 to an index will result in an error in the future
  result_shape.insert(dim, 1)
Net built successfully...

Starting training...

Epoch: 000/300 cost: 0.618990561
Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 715, in _do_call
    return fn(*args)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 697, in _run_fn
    status, run_metadata)
  File "/usr/lib/python3.5/contextlib.py", line 66, in __exit__
    next(self.gen)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/errors.py", line 450, in raise_exception_on_not_ok_status
    pywrap_tensorflow.TF_GetCode(status))
tensorflow.python.framework.errors.FailedPreconditionError: Attempting to use uninitialized value auc/false_positives
     [[Node: auc/false_positives/read = Identity[T=DT_FLOAT, _class=["loc:@auc/false_positives"], _device="/job:localhost/replica:0/task:0/cpu:0"](auc/false_positives)]]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "./mlp_.py", line 152, in <module>
    train_auc = sess.run(auc, feed_dict={X: batch_xs, y: batch_ys, dropout_keep_prob:1.})
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 372, in run
    run_metadata_ptr)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 636, in _run
    feed_dict_string, options, run_metadata)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 708, in _do_run
    target_list, options, run_metadata)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 728, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors.FailedPreconditionError: Attempting to use uninitialized value auc/false_positives
     [[Node: auc/false_positives/read = Identity[T=DT_FLOAT, _class=["loc:@auc/false_positives"], _device="/job:localhost/replica:0/task:0/cpu:0"](auc/false_positives)]]
Caused by op 'auc/false_positives/read', defined at:
  File "./mlp_.py", line 121, in <module>
    auc = tf.contrib.metrics.streaming_auc(a, b)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/contrib/metrics/python/ops/metric_ops.py", line 718, in streaming_auc
    predictions, labels, thresholds, ignore_mask)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/contrib/metrics/python/ops/metric_ops.py", line 603, in _tp_fn_tn_fp
    false_positives = _create_local('false_positives', shape=[num_thresholds])
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/contrib/metrics/python/ops/metric_ops.py", line 75, in _create_local
    collections=collections)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/variables.py", line 211, in __init__
    dtype=dtype)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/variables.py", line 319, in _init_from_args
    self._snapshot = array_ops.identity(self._variable, name="read")
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/gen_array_ops.py", line 831, in identity
    result = _op_def_lib.apply_op("Identity", input=input, name=name)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/op_def_library.py", line 704, in apply_op
    op_def=op_def)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/ops.py", line 2260, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/ops.py", line 1230, in __init__
    self._traceback = _extract_stack()

I don't understand what I am doing wrong and why when using accuracy only the code runs fine but when using AUC it throws this error.
Could you please hint me in the right direction to understand how to fix this?
My objective is to calculate AUC and ROC for better evaluating the binary classifier performances.

A: I've found the same issue on github. At the moment, it seems that you also need to run sess.run(tf.initialize_local_variables()) in order to make tf.contrib.metrics.streaming_auc() work. They're working on it.
Here you have an example demonstrating how you can solve this issue:
import tensorflow as tf

a = tf.Variable([0.1, 0.5])
b = tf.Variable([0.2, 0.6])

auc = tf.contrib.metrics.streaming_auc(a, b)

sess = tf.Session()
sess.run(tf.initialize_all_variables())
sess.run(tf.initialize_local_variables()) # try commenting this line and you'll get the error
train_auc = sess.run(auc)

print(train_auc)