Q: Is it possible to show blog view counter with information Google Analytics I have a static blog using Jekyll hosted on GitHub. I have set up Google Analytics for it and works well enough.
Now I want to show how many people viewed each post in my blog. I found Google Analytics JavaScript API to get the information. But it seems that this API uses OAuth for data access. So I think this might not be the API I needed.
Is it possible to do so with Google Analytics? I don't have any server since it's hosted on GitHub.

A: I finally solved this problem by Google Analytics superProxy as suggested in the comment of @EikePierstorff.
I wrote a blog on it.
Here's the main idea.
I first build a project on Google App Engile, with which I authenticate for the access of my Google Analytics. Then a URL of query (which can be pageview of certain pages) is generated in JSON format. I can set the refresh rate on this GAE project so that the JSON file can be updated from Google Analytic.
Sounds almost perfect to me. Thank you all guys for help!

A: You can't query the Google Analytics API without authorization by someone, that's the most important thing to remember.
It's certainly possible to display Google Analytics data on your website to users who don't have access to your account, but in order to do that, someone with access to the account needs to authorize and get an access token in order to run queries.
Normally this is done server side, and once you have a valid access token you can query the API client side (to display charts and graph, etc.). Access tokens are typically valid for 1 hour, so if you want to have your website up all the time, you'll also have to deal with refreshing the access token once it expires.
Now, since you're using Github Pages and don't have a back end, which means all the authorization will need to happen client side. While it's technically possible to do the same thing client side as server side, it's generally not a good idea because private data like your client secret, refresh token, etc. will be visible in the source code.
Applications that do auth client side typically don't authorize on behalf of a user. They require the users themselves to go through an auth flow for security reasons (as I just explained), but that would mean those users 1) have to log in, and 2) can only see the analytics data they have access to, which probably isn't what you want.
--
What you can do is run reports periodically yourself and export that data to a Google Spreadsheet. Google Spreadsheets allow you to embed charts and graphs of data as an <iframe> in external pages, so that might be an option.
At the end of the day, if you can't authorize server side you'll have to come up with some kind of workaround to make this happen.
Here are a few possibly helpful links that might point you in the right direction:
https://developers.google.com/analytics/solutions/google-analytics-spreadsheet-add-on
https://developers.google.com/analytics/devguides/reporting/embed
https://developers.google.com/analytics/solutions/report-automation-magic


Q: Not able to invoke a spark application using a java class on cluster Below is my project's structure:
spark-application:

scala1.scala // I am calling the java class from this class.
java.java // this will submit another spark application to the yarn cluster.

The spark-application that is being triggered by java class:

scala2.scala

My reference tutorial is here
When I run my java class from scala1.scala via spark-submit in the local mode the second spark application scala2.scala is getting triggered and working as expected.
But, when I run the same application via spark-submit in yarn cluster it is showing the below error!
Error: Could not find or load main class
org.apache.spark.deploy.yarn.ApplicationMaster

 Application application_1493671618562_0072 failed 5 times due to AM Container for appattempt_1493671618562_0072_000005 exited with exitCode: 1
 For more detailed output, check the application tracking page: http://headnode.internal.cloudapp.net:8088/cluster/app/application_1493671618562_0072 Then click on links to logs of each attempt.
 Diagnostics: Exception from container-launch.
 Container id: container_e02_1493671618562_0072_05_000001
 Exit code: 1
 Exception message: /mnt/resource/hadoop/yarn/local/usercache/helixuser/appcache/application_1493671618562_0072/container_e02_1493671618562_0072_05_000001/launch_container.sh: line 26: $PWD:$PWD/spark_conf:$PWD/spark.jar:$HADOOP_CONF_DIR:/usr/hdp/current/hadoop-client/:/usr/hdp/current/hadoop-client/lib/:/usr/hdp/current/hadoop-hdfs-client/:/usr/hdp/current/hadoop-hdfs-client/lib/:/usr/hdp/current/hadoop-yarn-client/:/usr/hdp/current/hadoop-yarn-client/lib/:$PWD/mr-framework/hadoop/share/hadoop/mapreduce/:$PWD/mr-framework/hadoop/share/hadoop/mapreduce/lib/:$PWD/mr-framework/hadoop/share/hadoop/common/:$PWD/mr-framework/hadoop/share/hadoop/common/lib/:$PWD/mr-framework/hadoop/share/hadoop/yarn/:$PWD/mr-framework/hadoop/share/hadoop/yarn/lib/:$PWD/mr-framework/hadoop/share/hadoop/hdfs/:$PWD/mr-framework/hadoop/share/hadoop/hdfs/lib/:$PWD/mr-framework/hadoop/share/hadoop/tools/lib/:/usr/hdp/${hdp.version}/hadoop/lib/hadoop-lzo-0.6.0.${hdp.version}.jar:/etc/hadoop/conf/secure: bad substitution
 Stack trace: ExitCodeException exitCode=1: /mnt/resource/hadoop/yarn/local/usercache/helixuser/appcache/application_1493671618562_0072/container_e02_1493671618562_0072_05_000001/launch_container.sh: line 26: $PWD:$PWD/spark_conf:$PWD/spark.jar:$HADOOP_CONF_DIR:/usr/hdp/current/hadoop-client/:/usr/hdp/current/hadoop-client/lib/:/usr/hdp/current/hadoop-hdfs-client/:/usr/hdp/current/hadoop-hdfs-client/lib/:/usr/hdp/current/hadoop-yarn-client/:/usr/hdp/current/hadoop-yarn-client/lib/:$PWD/mr-framework/hadoop/share/hadoop/mapreduce/:$PWD/mr-framework/hadoop/share/hadoop/mapreduce/lib/:$PWD/mr-framework/hadoop/share/hadoop/common/:$PWD/mr-framework/hadoop/share/hadoop/common/lib/:$PWD/mr-framework/hadoop/share/hadoop/yarn/:$PWD/mr-framework/hadoop/share/hadoop/yarn/lib/:$PWD/mr-framework/hadoop/share/hadoop/hdfs/:$PWD/mr-framework/hadoop/share/hadoop/hdfs/lib/:$PWD/mr-framework/hadoop/share/hadoop/tools/lib/:/usr/hdp/${hdp.version}/hadoop/lib/hadoop-lzo-0.6.0.${hdp.version}.jar:/etc/hadoop/conf/secure: bad substitution
 at org.apache.hadoop.util.Shell.runCommand(Shell.java:933)
 at org.apache.hadoop.util.Shell.run(Shell.java:844)
 at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:1123)
 at org.apache.hadoop.yarn.server.nodemanager.DefaultContainerExecutor.launchContainer(DefaultContainerExecutor.java:225)
 at org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call(ContainerLaunch.java:317)
 at org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call(ContainerLaunch.java:83)
 at java.util.concurrent.FutureTask.run(FutureTask.java:266)
 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
 at java.lang.Thread.run(Thread.java:745)
 Container exited with a non-zero exit code 1
 Failing this attempt. Failing the application.

My project's directory structure is given below:
lrwxrwxrwx 1 yarn hadoop   95 May  5 06:03 __app__.jar -> /mnt/resource/hadoop/yarn/local/filecache/10/sparkfiller-1.0-SNAPSHOT-jar-with-dependencies.jar
-rw-r--r-- 1 yarn hadoop   74 May  5 06:03 container_tokens
-rwx------ 1 yarn hadoop  710 May  5 06:03 default_container_executor_session.sh
-rwx------ 1 yarn hadoop  764 May  5 06:03 default_container_executor.sh
-rwx------ 1 yarn hadoop 6433 May  5 06:03 launch_container.sh
lrwxrwxrwx 1 yarn hadoop  102 May  5 06:03 __spark_conf__ -> /mnt/resource/hadoop/yarn/local/usercache/helixuser/filecache/80/__spark_conf__6125877397366945561.zip
lrwxrwxrwx 1 yarn hadoop  125 May  5 06:03 __spark__.jar -> /mnt/resource/hadoop/yarn/local/usercache/helixuser/filecache/81/spark-assembly-1.6.3.2.5.4.0-121-hadoop2.7.3.2.5.4.0-121.jar
drwx--x--- 2 yarn hadoop 4096 May  5 06:03 tmp
find -L . -maxdepth 5 -ls:
3933556      4 drwx--x---   3 yarn     hadoop       4096 May  5 06:03 .
3933558      4 drwx--x---   2 yarn     hadoop       4096 May  5 06:03 ./tmp
3933562      4 -rw-r--r--   1 yarn     hadoop         60 May  5 06:03 ./.launch_container.sh.crc
3933517 185944 -r-x------   1 yarn     hadoop   190402950 May  5 06:03 ./__spark__.jar
3933564      4 -rw-r--r--   1 yarn     hadoop          16 May  5 06:03 ./.default_container_executor_session.sh.crc
3933518      4 drwx------   2 yarn     hadoop        4096 May  5 06:03 ./__spark_conf__
3933548      4 -r-x------   1 yarn     hadoop         945 May  5 06:03 ./__spark_conf__/taskcontroller.cfg
3933543      4 -r-x------   1 yarn     hadoop         249 May  5 06:03 ./__spark_conf__/slaves
3933541      4 -r-x------   1 yarn     hadoop        2316 May  5 06:03 ./__spark_conf__/ssl-client.xml.example
3933520      4 -r-x------   1 yarn     hadoop        1734 May  5 06:03 ./__spark_conf__/log4j.properties
3933526      4 -r-x------   1 yarn     hadoop         265 May  5 06:03 ./__spark_conf__/hadoop-metrics2-azure-file-system.properties
3933536      4 -r-x------   1 yarn     hadoop        1045 May  5 06:03 ./__spark_conf__/container-executor.cfg
3933519      8 -r-x------   1 yarn     hadoop        5685 May  5 06:03 ./__spark_conf__/hadoop-env.sh
3933531      4 -r-x------   1 yarn     hadoop        2358 May  5 06:03 ./__spark_conf__/topology_script.py
3933547      8 -r-x------   1 yarn     hadoop        4113 May  5 06:03 ./__spark_conf__/mapred-queues.xml.template
3933528      4 -r-x------   1 yarn     hadoop         744 May  5 06:03 ./__spark_conf__/ssl-client.xml
3933544      4 -r-x------   1 yarn     hadoop         417 May  5 06:03 ./__spark_conf__/topology_mappings.data
3933549      4 -r-x------   1 yarn     hadoop         342 May  5 06:03 ./__spark_conf__/__spark_conf__.properties
3933523      4 -r-x------   1 yarn     hadoop         247 May  5 06:03 ./__spark_conf__/hadoop-metrics2-adl-file-system.properties
3933535      4 -r-x------   1 yarn     hadoop        1020 May  5 06:03 ./__spark_conf__/commons-logging.properties
3933525     24 -r-x------   1 yarn     hadoop       22138 May  5 06:03 ./__spark_conf__/yarn-site.xml
3933529      4 -r-x------   1 yarn     hadoop        2450 May  5 06:03 ./__spark_conf__/capacity-scheduler.xml
3933538      4 -r-x------   1 yarn     hadoop        2490 May  5 06:03 ./__spark_conf__/hadoop-metrics.properties
 3933534     12 -r-x------   1 yarn     hadoop        8754 May  5 06:03 ./__spark_conf__/hdfs-site.xml
 3933533      8 -r-x------   1 yarn     hadoop        4261 May  5 06:03 ./__spark_conf__/yarn-env.sh
 3933532      4 -r-x------   1 yarn     hadoop        1335 May  5 06:03 ./__spark_conf__/configuration.xsl
 3933530      4 -r-x------   1 yarn     hadoop         758 May  5 06:03 ./__spark_conf__/mapred-site.xml.template
 3933545      4 -r-x------   1 yarn     hadoop        1000 May  5 06:03 ./__spark_conf__/ssl-server.xml
 3933527      8 -r-x------   1 yarn     hadoop        4680 May  5 06:03 ./__spark_conf__/core-site.xml
 3933522      8 -r-x------   1 yarn     hadoop        5783 May  5 06:03 ./__spark_conf__/hadoop-metrics2.properties
 3933542      4 -r-x------   1 yarn     hadoop        1308 May  5 06:03 ./__spark_conf__/hadoop-policy.xml
 3933540      4 -r-x------   1 yarn     hadoop        1602 May  5 06:03 ./__spark_conf__/health_check
 3933537      8 -r-x------   1 yarn     hadoop        4221 May  5 06:03 ./__spark_conf__/task-log4j.properties
 3933521      8 -r-x------   1 yarn     hadoop        7596 May  5 06:03 ./__spark_conf__/mapred-site.xml
 3933546      4 -r-x------   1 yarn     hadoop        2697 May  5 06:03 ./__spark_conf__/ssl-server.xml.example
 3933539      4 -r-x------   1 yarn     hadoop         752 May  5 06:03 ./__spark_conf__/mapred-env.sh
 3932820 135852 -r-xr-xr-x   1 yarn     hadoop   139105807 May  4 22:53 ./__app__.jar
 3933566      4 -rw-r--r--   1 yarn     hadoop          16 May  5 06:03 ./.default_container_executor.sh.crc
 3933563      4 -rwx------   1 yarn     hadoop         710 May  5 06:03 ./default_container_executor_session.sh
 3933559      4 -rw-r--r--   1 yarn     hadoop          74 May  5 06:03 ./container_tokens
3933565      4 -rwx------   1 yarn     hadoop         764 May  5 06:03 ./default_container_executor.sh
3933560      4 -rw-r--r--   1 yarn     hadoop          12 May  5 06:03 ./.container_tokens.crc
3933561      8 -rwx------   1 yarn     hadoop        6433 May  5 06:03 ./launch_container.sh
broken symlinks(find -L . -maxdepth 5 -type l -ls):

Below is the java code that invokes the second Spark application:
import org.apache.spark.deploy.yarn.Client;
import org.apache.spark.deploy.yarn.ClientArguments;
import org.apache.hadoop.conf.Configuration;
import org.apache.spark.SparkConf;
import org.apache.spark.SparkException;

public class CallingSparkJob {

        public void submitJob(String latestreceivedpitrL,String newPtr) throws Exception {
           System.out.println("In submit job method");
            try{
            System.out.println("Building a spark command");

   // prepare arguments to be passed to
   // org.apache.spark.deploy.yarn.Client object
   String[] args = new String[] {
       // the name of your application
"--name",
"name",
// "--master",
    // "yarn",
      //    "--deploy-mode",
    //  "cluster",

          //       "--conf", "spark.yarn.executor.memoryOverhead=600", "--conf",
        "spark.yarn.submit.waitAppCompletion=false",

       // memory for driver (optional)
       "--driver-memory",
       "1000M",

       "--num-executors",
       "2",
       "--executor-cores",
       "2",

       // path to your application's JAR file
       // required in yarn-cluster mode
       "--jar",
   "wasb://storage_account_container@storageaccount.blob.core.windows.net/user/ankushuser/sparkfiller/sparkfiller-1.0-SNAPSHOT-jar-with-dependencies.jar",
       // name of your application's main class (required)
       "--class",
       "com.test.SparkFiller",

       // comma separated list of local jars that want
       // SparkContext.addJar to work with
      // "--addJars",
      // "/Users/mparsian/zmp/github/data-algorithms-book/lib/spark-assembly-1.5.2-hadoop2.6.0.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/log4j-1.2.17.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/junit-4.12-beta-2.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/jsch-0.1.42.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/JeraAntTasks.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/jedis-2.5.1.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/jblas-1.2.3.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/hamcrest-all-1.3.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/guava-18.0.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/commons-math3-3.0.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/commons-math-2.2.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/commons-logging-1.1.1.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/commons-lang3-3.4.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/commons-lang-2.6.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/commons-io-2.1.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/commons-httpclient-3.0.1.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/commons-daemon-1.0.5.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/commons-configuration-1.6.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/commons-collections-3.2.1.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/commons-cli-1.2.jar,/Users/mparsian/zmp/github/data-algorithms-book/lib/cloud9-1.3.2.jar",

       // argument 1 for latestreceivedpitrL
    "--arg",
       latestreceivedpitrL,

       // argument 2 for newPtr
     "--arg",
       newPtr,

"--arg",
"yarn-cluster"

   };

  System.out.println("create a Hadoop Configuration object");

// create a Hadoop Configuration object
   Configuration config = new Configuration();

   // identify that you will be using Spark as YARN mode
  System.setProperty("SPARK_YARN_MODE", "true");

   // create an instance of SparkConf object
   SparkConf sparkConf = new SparkConf();
sparkConf.setSparkHome("/usr/hdp/current/spark-client");
    // sparkConf.setMaster("yarn");
    sparkConf.setMaster("yarn-cluster");

   // sparkConf.setAppName("spark-yarn");
   //  sparkConf.set("master", "yarn");

    // sparkConf.set("spark.submit.deployMode", "cluster"); // worked

   // create ClientArguments, which will be passed to Client
   // ClientArguments cArgs = new ClientArguments(args);
   ClientArguments cArgs = new ClientArguments(args, sparkConf);

   // create an instance of yarn Client client
   Client client = new Client(cArgs, config, sparkConf);

   // submit Spark job to YARN
   client.run();
   }catch(Exception e){

       System.out.println("Error submitting spark Job");

       System.out.println(e.getMessage());
   }

  }

 }

The spark-submit command used to run the first spark application locally:

spark-submit --class scala1 --master yarn --deploy-mode cluster --num-executors 2 --executor-cores 2 --conf spark.yarn.executor.memoryOverhead=600 --conf spark.yarn.submit.waitAppCompletion=false /home/ankushuser/kafka_retry/kafka_retry_test/sparkflightaware/target/sparkflightaware-0.0.1-SNAPSHOT-jar-with-dependencies.jar

If I run this spark-submit command locally it is invoking the java class and the spark-submit command for the second scala2 application is working fine.
If I run it in yarn mode, then I am facing the issue.
Thank you for your help.

A: Since there's a bounty, I'll repost this as a reply as well -- but in reality I would like to flag this as a duplicate, since the actual Exception is the one covered in another question, and answered:
It is caused by hdp.version not getting substituted correctly. You have to set hdp.version in the file java-opts under $SPARK_HOME/conf.
Alternatively, use
--driver-java-options="-Dhdp.version=INSERT_VERSION_STRING_HERE"  --conf "spark.executor.extraJavaOptions=-Dhdp.version=INSERT_VERSION_STRING_HERE" in your spark-submit and make sure to use the correct version string, as in the subdirectory of /usr/hdp.
If you want to stick with calling client.submit from your code, then you need to put those lines into the --arg you build in your code.


Q: Why there is no output to the framebuffer's textures? Here is the code:
int main(){
    //init gl environment
    //...

    //create textures for pass 1

    GLuint normal_color_output;
    glCreateTextures(GL_TEXTURE_2D_MULTISAMPLE, 1, &normal_color_output);
    glTextureStorage2DMultisample(normal_color_output, 8, GL_RGBA32F, 1000, 800, GL_TRUE);
    GLuint high_color_output;
    glCreateTextures(GL_TEXTURE_2D_MULTISAMPLE, 1, &high_color_output);
    glTextureStorage2DMultisample(high_color_output,8, GL_R11F_G11F_B10F, 1000, 800,GL_TRUE);

    //init framebuffer

    GLuint render_buffer;
    glCreateRenderbuffers(1, &render_buffer);
    glNamedRenderbufferStorageMultisample(render_buffer, 8, GL_DEPTH24_STENCIL8, 1000, 800);
    GLuint framebuffer;
    glCreateFramebuffers(1, &framebuffer);
    glNamedFramebufferTexture(framebuffer, GL_COLOR_ATTACHMENT0, normal_color_output,0);
    glNamedFramebufferTexture(framebuffer, GL_COLOR_ATTACHMENT1, high_color_output, 0);
    glNamedFramebufferRenderbuffer(framebuffer, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, render_buffer);
    const GLenum drawbuffers[] = {GL_COLOR_ATTACHMENT0,GL_COLOR_ATTACHMENT1};
    glNamedFramebufferDrawBuffers(framebuffer, 2, drawbuffers);
    glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);

    //init another framebuffer
    //What I want to do is trying to achieve implementing my own msaa color resolve solution.

    GLuint mix_framebuffer;
    glCreateFramebuffers(1, &mix_framebuffer);
    GLuint mix_renderbuffer;
    glCreateRenderbuffers(1, &mix_renderbuffer);
    glNamedRenderbufferStorage(mix_renderbuffer, GL_DEPTH24_STENCIL8, 1000, 800);
    GLuint normal_antialiasing_texture, hdr_antialiasing_texture;
    glCreateTextures(GL_TEXTURE_2D, 1, &normal_antialiasing_texture);
    glTextureStorage2D(normal_antialiasing_texture, 1, GL_RGBA32F, 1000, 800);
    glCreateTextures(GL_TEXTURE_2D, 1, &hdr_antialiasing_texture);
    glTextureStorage2D(hdr_antialiasing_texture, 1, GL_RGBA32F, 1000, 800);
    glNamedFramebufferTexture(mix_framebuffer, GL_COLOR_ATTACHMENT0, normal_antialiasing_texture, 0);
    glNamedFramebufferTexture(mix_framebuffer, GL_COLOR_ATTACHMENT1, hdr_antialiasing_texture, 0);
    glNamedFramebufferDrawBuffers(mix_framebuffer,2, drawbuffers);
    glNamedFramebufferRenderbuffer(mix_framebuffer, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, mix_renderbuffer);
    glBindFramebuffer(GL_FRAMEBUFFER, mix_framebuffer);

    //....
    //draw commands
    while (!glfwWindowShouldClose(window)) {
        // pass 1
        glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
        glUseProgram(program);
        glUniformMatrix4fv(3, 1, GL_FALSE, glm::value_ptr(camera.GetViewMat()));
        model.Render(program);
        glPointSize(20.f);
        glUseProgram(light_shader);// I draw a point to show the light's position
        glUniformMatrix4fv(0, 1, GL_FALSE, glm::value_ptr(camera.GetViewMat()));
        glDrawArrays(GL_POINTS, 0, 1);

        //pass 2
        glBindFramebuffer(GL_FRAMEBUFFER, mix_framebuffer);
        glUseProgram(mix_program);
        glBindTextureUnit(0, normal_color_output);
        glBindTextureUnit(1, high_color_output);
        glClear(GL_COLOR_BUFFER_BIT);
        glNamedFramebufferDrawBuffers(mix_framebuffer, 2, drawbuffers);
        glDrawArrays(GL_POINTS, 0, 1);
        //...
    }
}

I use geometry shader to model a square, here is the code:
//mix_gs.glsl
#version 450 core

layout(points) in;
layout(triangle_strip) out;
layout(max_vertices = 4) out;

void main(){
    gl_Position = vec4(-1,1,-1,1);
    EmitVertex();
    gl_Position = vec4(-1,-1,-1,1);
    EmitVertex();
    gl_Position = vec4(1,1,-1,1);
    EmitVertex();
    gl_Position = vec4(1,-1,-1,1);
    EmitVertex();
    EndPrimitive();
}

here is the mix_fs.glsl:
#version 450 core

layout(location = 0)out vec4 color;
layout(location = 1)out vec4 hdr_color;
layout(binding = 0) uniform sampler2DMS color_sdms;
layout(binding = 1) uniform sampler2DMS hdr_sdms;
void main(){
/*
    for(int i=0;i<8;i++){
        color += texelFetch(color_sdms,ivec2(gl_FragCoord.xy),i);
        hdr_color += vec4(texelFetch(hdr_sdms,ivec2(gl_FragCoord.xy),i).xyz,1);
    }
    */
    color = vec4(1,0,0,1);//I just output a color
    hdr_color = vec4(0,1,0,1);
}

I encount a problem that I find during the draw pass 2, gl cannot outout any color to textures bind to mix_framebuffer.
Here is the debugging info in RenderDoc:
draw pass 1 texture output:

draw pass 2's geometry output:

draw pass 2 texture input:

draw pass 2 texture output:

You can see, draw-pass 1's output was passed to draw-pass2's pipeline successfully, but there is no output to draw-pass2's textures. I don't know why.

A: If you don't see even the plain color, the first I'd recommend to check how it was discarded. There are no so many options:

*

*glColorMask. Highly likely it's not your case, since pass 1 works;

*Wrong face culling and polygon winding order (CW, CCW). By your geometry shader, it looks like CW;

*Blending options;

*Depth-stencil state. I see you use glNamedRenderbufferStorage(mix_renderbuffer, GL_DEPTH24_STENCIL8, 1000, 800); What are depth-stencil settings?

If everything above looks good, any glGetError messages? If it's ok, try to remove MRT for a debugging purposes and output the only color in the second pass. If it would work, probably some error in MRT + Depth buffer setup.


Q: how to draw a line in html 30pt from either side I have a footer div that is 100% wide and 200pt high.  I want to draw a white line that starts 30pt in from both the left and the right 25pt from the bottom.
I have playing about with a div 1px high and positioning it with the following but to now avail.
    #HPFooterlinebreak{
    position:absolute;
    bottom:25pt;
    right:30pt;
    left:30pt;
    background-color:#EFF1EF;
    height:1px;
    width:100%;
}

Just to be clear the div above is not the one 200pt high.
Thanks

A: Why not use a positioned pseudo element with a suitably applied border?

pseudo-elements are added to selectors but instead of describing a
  special state, they allow you to style certain parts of a document

You may also want to use the semantic footer element (if appropriate)

footer {
  background: black;
  height: 200pt;
  position: relative;
}
footer:after {
  content: '';
  position: absolute;
  left: 30pt;
  right: 30pt;
  bottom: 25pt;
  border-top: 1px solid white;
}

A: You're almost there. You don't need the width. Also, if you use position: absolute to position the element inside its parent, then you must also add position: relative or position: absolute to the parent itself.
By the way, if this white line is just for show, you might as well use a pseudo-element for it and keep the HTML simple. But if you like to, you might as well change .footer:before back to #HPFooterlinebreak.

.footer {
    background-color: blue;
    position: relative;
    height: 200px;
}
.footer:before{
    content: "";
    position:absolute;
    bottom:25pt;
    right:30pt;
    left:30pt;
    background-color:#EFF1EF;
    height:1px;
}

  Yo


Q: How to prevent Mocha from preserving require cache between test files? I am running my integration test cases in separate files for each API.
Before it begins I start the server along with all services, like databases. When it ends, I close all connections. I use Before and After hooks for that purpose. It is important to know that my application depends on an enterprise framework where most "core work" is written and I install it as a dependency of my application.
I run the tests with Mocha.
When the first file runs, I see no problems. When the second file runs I get a lot of errors related to database connections. I tried to fix it in many different ways, most of them failed because of the limitations the Framework imposed me.
Debugging I found out that Mocha actually loads all files first, that means that all code written before the hooks and the describe calls is executed. So when the second file is loaded, the require.cache is already full of modules. Only after that the suite executes the tests sequentially.
That has a huge impact in this Framework because many objects are actually Singletons, so if in a after hook it closes a connection with a database, it closes the connection inside the Singleton. The way the Framework was built makes it very hard to give a workaround to this problem, like reconnecting to all services in the before hook.
I wrote a very ugly code that helps me before I can refactor the Framework. This goes in each test file I want to invalidate the cache.
function clearRequireCache() {
    Object.keys(require.cache).forEach(function (key) {
        delete require.cache[key];
    });
}

before(() => {
    clearRequireCache();
})

It is working, but seems to be very bad practice. And I don`t want this in the code.
As a second idea I was thinking about running Mocha multiple times, one for each "module" (as of my Framework) or file.
"scripts": {
   "test-integration" : "./node_modules/mocha/bin/mocha ./api/modules/module1/test/integration/*.integration.js && ./node_modules/mocha/bin/mocha ./api/modules/module2/test/integration/file1.integration.js && ./node_modules/mocha/bin/mocha ./api/modules/module2/test/integration/file2.integration.js"
}

I was wondering if Mocha provides a solution for this problem so I can get rid of that code and delay the code refacting a bit.


Q: Is it possible to align components horizontally when using WrapLayout/FlowLayout? I use WrapLayout which extends FlowLayout
Now, I have this GUI:

What I want is this:

I tried some things like: label.setVerticalAlignment(JLabel.TOP); but the layout does not seem to respect it. I guess this behavior is inherited from FlowLayout?
Full code:
public class WrapLayoutExample {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(WrapLayoutExample::runGui);
    }

    private static void runGui() {
        JFrame frame = new JFrame("A");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel(new WrapLayout());

        JLabel l = new JLabel("CCC");
        l.setBorder(BorderFactory.createLineBorder(Color.red, 10));
        l.setVerticalAlignment(JLabel.TOP);
        panel.add(l);

        l = new JLabel("BBBB");
        l.setBorder(BorderFactory.createLineBorder(Color.red, 20));
        panel.add(l);

        frame.setLayout(new BorderLayout());
        frame.add(new JScrollPane(panel));

        frame.pack();
        frame.setVisible(true);
    }
}

A: From @camickr's comment in my question:

You should be able to write your own layout manager. Just copy the FlowLayout and replace the logic that centers the component within the row, to position the component at the top.

In FlowLayout, in moveComponents method, there is this line:
cy = y + (height - m.height) / 2;

Changing the line to:
cy = y;

achieves what I want.
It probably breaks the flowLayout.setAlignOnBaseline functionality. But I don't use it anyway.
Layout code (WrapLayout and custom FlowLayout combined):
public class WrapAndAlignHorizontallyTopLayout implements LayoutManager, java.io.Serializable {

    /**
     * This value indicates that each row of components should be left-justified.
     */
    public static final int LEFT = 0;

    /**
     * This value indicates that each row of components should be centered.
     */
    public static final int CENTER = 1;

    /**
     * This value indicates that each row of components should be right-justified.
     */
    public static final int RIGHT = 2;

    /**
     * This value indicates that each row of components should be justified to the
     * leading edge of the container's orientation, for example, to the left in
     * left-to-right orientations.
     *
     * @see java.awt.Component#getComponentOrientation
     * @see java.awt.ComponentOrientation
     * @since 1.2
     */
    public static final int LEADING = 3;

    /**
     * This value indicates that each row of components should be justified to the
     * trailing edge of the container's orientation, for example, to the right in
     * left-to-right orientations.
     *
     * @see java.awt.Component#getComponentOrientation
     * @see java.awt.ComponentOrientation
     * @since 1.2
     */
    public static final int TRAILING = 4;

    /**
     * align is the property that determines how each row distributes
     * empty space. It can be one of the following values:
     *

     *
LEFT
     *
RIGHT
     *
CENTER
     *

     *
     * @serial
     * @see #getAlignment
     * @see #setAlignment
     */
    int align; // This is for 1.1 serialization compatibility

    /**
     * newAlign is the property that determines how each row
     * distributes empty space for the Java 2 platform, v1.2 and greater. It can be
     * one of the following three values:
     *

     *
LEFT
     *
RIGHT
     *
CENTER
     *
LEADING
     *
TRAILING
     *

     *
     * @serial
     * @since 1.2
     * @see #getAlignment
     * @see #setAlignment
     */
    int newAlign; // This is the one we actually use

    /**
     * The flow layout manager allows a seperation of components with gaps. The
     * horizontal gap will specify the space between components and between the
     * components and the borders of the Container.
     *
     * @serial
     * @see #getHgap()
     * @see #setHgap(int)
     */
    int hgap;

    /**
     * The flow layout manager allows a seperation of components with gaps. The
     * vertical gap will specify the space between rows and between the the rows and
     * the borders of the Container.
     *
     * @serial
     * @see #getHgap()
     * @see #setHgap(int)
     */
    int vgap;

    /**
     * If true, components will be aligned on their baseline.
     */
    private boolean alignOnBaseline;

    /*
     * JDK 1.1 serialVersionUID
     */
    private static final long serialVersionUID = -7262534875583282631L;

    /**
     * Constructs a new FlowLayout with a centered alignment and a
     * default 5-unit horizontal and vertical gap.
     */
    public WrapAndAlignHorizontallyTopLayout() {
        this(CENTER, 5, 5);
    }

    /**
     * Constructs a new FlowLayout with the specified alignment and a
     * default 5-unit horizontal and vertical gap. The value of the alignment
     * argument must be one of FlowLayout.LEFT,
     * FlowLayout.RIGHT, FlowLayout.CENTER,
     * FlowLayout.LEADING, or FlowLayout.TRAILING.
     *
     * @param align the alignment value
     */
    public WrapAndAlignHorizontallyTopLayout(int align) {
        this(align, 5, 5);
    }

    /**
     * Creates a new flow layout manager with the indicated alignment and the
     * indicated horizontal and vertical gaps.
     *

     * The value of the alignment argument must be one of
     * FlowLayout.LEFT, FlowLayout.RIGHT,
     * FlowLayout.CENTER, FlowLayout.LEADING, or
     * FlowLayout.TRAILING.
     *
     * @param align the alignment value
     * @param hgap  the horizontal gap between components and between the components
     *              and the borders of the Container
     * @param vgap  the vertical gap between components and between the components
     *              and the borders of the Container
     */
    public WrapAndAlignHorizontallyTopLayout(int align, int hgap, int vgap) {
        this.hgap = hgap;
        this.vgap = vgap;
        setAlignment(align);
    }

    /**
     * Gets the alignment for this layout. Possible values are
     * FlowLayout.LEFT, FlowLayout.RIGHT,
     * FlowLayout.CENTER, FlowLayout.LEADING, or
     * FlowLayout.TRAILING.
     *
     * @return the alignment value for this layout
     * @see java.awt.FlowLayout#setAlignment
     * @since JDK1.1
     */
    public int getAlignment() {
        return newAlign;
    }

    /**
     * Sets the alignment for this layout. Possible values are
     *

     *
FlowLayout.LEFT
     *
FlowLayout.RIGHT
     *
FlowLayout.CENTER
     *
FlowLayout.LEADING
     *
FlowLayout.TRAILING
     *

     *
     * @param align one of the alignment values shown above
     * @see #getAlignment()
     * @since JDK1.1
     */
    public void setAlignment(int align) {
        this.newAlign = align;

        // this.align is used only for serialization compatibility,
        // so set it to a value compatible with the 1.1 version
        // of the class

        switch (align) {
        case LEADING:
            this.align = LEFT;
            break;
        case TRAILING:
            this.align = RIGHT;
            break;
        default:
            this.align = align;
            break;
        }
    }

    /**
     * Gets the horizontal gap between components and between the components and the
     * borders of the Container
     *
     * @return the horizontal gap between components and between the components and
     *         the borders of the Container
     * @see java.awt.FlowLayout#setHgap
     * @since JDK1.1
     */
    public int getHgap() {
        return hgap;
    }

    /**
     * Sets the horizontal gap between components and between the components and the
     * borders of the Container.
     *
     * @param hgap the horizontal gap between components and between the components
     *             and the borders of the Container
     * @see java.awt.FlowLayout#getHgap
     * @since JDK1.1
     */
    public void setHgap(int hgap) {
        this.hgap = hgap;
    }

    /**
     * Gets the vertical gap between components and between the components and the
     * borders of the Container.
     *
     * @return the vertical gap between components and between the components and
     *         the borders of the Container
     * @see java.awt.FlowLayout#setVgap
     * @since JDK1.1
     */
    public int getVgap() {
        return vgap;
    }

    /**
     * Sets the vertical gap between components and between the components and the
     * borders of the Container.
     *
     * @param vgap the vertical gap between components and between the components
     *             and the borders of the Container
     * @see java.awt.FlowLayout#getVgap
     * @since JDK1.1
     */
    public void setVgap(int vgap) {
        this.vgap = vgap;
    }

    /**
     * Sets whether or not components should be vertically aligned along their
     * baseline. Components that do not have a baseline will be centered. The
     * default is false.
     *
     * @param alignOnBaseline whether or not components should be vertically aligned
     *                        on their baseline
     * @since 1.6
     */
    public void setAlignOnBaseline(boolean alignOnBaseline) {
        this.alignOnBaseline = alignOnBaseline;
    }

    /**
     * Returns true if components are to be vertically aligned along their baseline.
     * The default is false.
     *
     * @return true if components are to be vertically aligned along their baseline
     * @since 1.6
     */
    public boolean getAlignOnBaseline() {
        return alignOnBaseline;
    }

    /**
     * Adds the specified component to the layout. Not used by this class.
     *
     * @param name the name of the component
     * @param comp the component to be added
     */
    @Override
    public void addLayoutComponent(String name, Component comp) {
    }

    /**
     * Removes the specified component from the layout. Not used by this class.
     *
     * @param comp the component to remove
     * @see java.awt.Container#removeAll
     */
    @Override
    public void removeLayoutComponent(Component comp) {
    }

    /**
     * Returns the preferred dimensions for this layout given the visible
     * components in the specified target container.
     *
     * @param target the component which needs to be laid out
     * @return the preferred dimensions to lay out the subcomponents of the
     *         specified container
     */
    @Override
    public Dimension preferredLayoutSize(Container target) {
        return layoutSize(target, true);
    }

    /**
     * Returns the minimum dimensions needed to layout the visible components
     * contained in the specified target container.
     *
     * @param target the component which needs to be laid out
     * @return the minimum dimensions to lay out the subcomponents of the specified
     *         container
     */
    @Override
    public Dimension minimumLayoutSize(Container target) {
        Dimension minimum = layoutSize(target, false);
        minimum.width -= (getHgap() + 1);
        return minimum;
    }

    /**
     * Returns the minimum or preferred dimension needed to layout the target
     * container.
     *
     * @param target    target to get layout size for
     * @param preferred should preferred size be calculated
     * @return the dimension to layout the target container
     */
    private Dimension layoutSize(Container target, boolean preferred) {
        synchronized (target.getTreeLock()) {
            // Each row must fit with the width allocated to the containter.
            // When the container width = 0, the preferred width of the container
            // has not yet been calculated so lets ask for the maximum.

            int targetWidth = target.getSize().width;
            Container container = target;

            while (container.getSize().width == 0 && container.getParent() != null) {
                container = container.getParent();
            }

            targetWidth = container.getSize().width;

            if (targetWidth == 0)
                targetWidth = Integer.MAX_VALUE;

            int hgap = getHgap();
            int vgap = getVgap();
            Insets insets = target.getInsets();
            int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2);
            int maxWidth = targetWidth - horizontalInsetsAndGap;

            // Fit components into the allowed width

            Dimension dim = new Dimension(0, 0);
            int rowWidth = 0;
            int rowHeight = 0;

            int nmembers = target.getComponentCount();

            for (int i = 0; i < nmembers; i++) {
                Component m = target.getComponent(i);

                if (m.isVisible()) {
                    Dimension d = preferred ? m.getPreferredSize() : m.getMinimumSize();

                    // Can't add the component to current row. Start a new row.

                    if (rowWidth + d.width > maxWidth) {
                        addRow(dim, rowWidth, rowHeight);
                        rowWidth = 0;
                        rowHeight = 0;
                    }

                    // Add a horizontal gap for all components after the first

                    if (rowWidth != 0) {
                        rowWidth += hgap;
                    }

                    rowWidth += d.width;
                    rowHeight = Math.max(rowHeight, d.height);
                }
            }

            addRow(dim, rowWidth, rowHeight);

            dim.width += horizontalInsetsAndGap;
            dim.height += insets.top + insets.bottom + vgap * 2;

            // When using a scroll pane or the DecoratedLookAndFeel we need to
            // make sure the preferred size is less than the size of the
            // target containter so shrinking the container size works
            // correctly. Removing the horizontal gap is an easy way to do this.

            Container scrollPane = SwingUtilities.getAncestorOfClass(JScrollPane.class, target);

            if (scrollPane != null && target.isValid()) {
                dim.width -= (hgap + 1);
            }

            return dim;
        }
    }

    /*
     * A new row has been completed. Use the dimensions of this row to update the
     * preferred size for the container.
     *
     * @param dim update the width and height when appropriate
     *
     * @param rowWidth the width of the row to add
     *
     * @param rowHeight the height of the row to add
     */
    private void addRow(Dimension dim, int rowWidth, int rowHeight) {
        dim.width = Math.max(dim.width, rowWidth);

        if (dim.height > 0) {
            dim.height += getVgap();
        }

        dim.height += rowHeight;
    }

    /**
     * Centers the elements in the specified row, if there is any slack.
     *
     * @param target      the component which needs to be moved
     * @param x           the x coordinate
     * @param y           the y coordinate
     * @param width       the width dimensions
     * @param height      the height dimensions
     * @param rowStart    the beginning of the row
     * @param rowEnd      the the ending of the row
     * @param useBaseline Whether or not to align on baseline.
     * @param ascent      Ascent for the components. This is only valid if
     *                    useBaseline is true.
     * @param descent     Ascent for the components. This is only valid if
     *                    useBaseline is true.
     * @return actual row height
     */
    private int moveComponents(Container target, int x, int y, int width, int height, int rowStart, int rowEnd,
            boolean ltr, boolean useBaseline, int[] ascent, int[] descent) {
        switch (newAlign) {
        case LEFT:
            x += ltr ? 0 : width;
            break;
        case CENTER:
            x += width / 2;
            break;
        case RIGHT:
            x += ltr ? width : 0;
            break;
        case LEADING:
            break;
        case TRAILING:
            x += width;
            break;
        }
        int maxAscent = 0;
        int nonbaselineHeight = 0;
        int baselineOffset = 0;
        if (useBaseline) {
            int maxDescent = 0;
            for (int i = rowStart; i < rowEnd; i++) {
                Component m = target.getComponent(i);
                if (m.isVisible()) {
                    if (ascent[i] >= 0) {
                        maxAscent = Math.max(maxAscent, ascent[i]);
                        maxDescent = Math.max(maxDescent, descent[i]);
                    } else {
                        nonbaselineHeight = Math.max(m.getHeight(), nonbaselineHeight);
                    }
                }
            }
            height = Math.max(maxAscent + maxDescent, nonbaselineHeight);
            baselineOffset = (height - maxAscent - maxDescent) / 2;
        }
        for (int i = rowStart; i < rowEnd; i++) {
            Component m = target.getComponent(i);
            if (m.isVisible()) {
                int cy;
                if (useBaseline && ascent[i] >= 0) {
                    cy = y + baselineOffset + maxAscent - ascent[i];
                } else {
                    cy = y;
                }
                if (ltr) {
                    m.setLocation(x, cy);
                } else {
                    m.setLocation(target.getWidth() - x - m.getWidth(), cy);
                }
                x += m.getWidth() + hgap;
            }
        }
        return height;
    }

    /**
     * Lays out the container. This method lets each visible component take
     * its preferred size by reshaping the components in the target container in
     * order to satisfy the alignment of this FlowLayout object.
     *
     * @param target the specified component being laid out
     * @see Container
     * @see java.awt.Container#doLayout
     */
    @Override
    public void layoutContainer(Container target) {
        synchronized (target.getTreeLock()) {
            Insets insets = target.getInsets();
            int maxwidth = target.getWidth() - (insets.left + insets.right + hgap * 2);
            int nmembers = target.getComponentCount();
            int x = 0, y = insets.top + vgap;
            int rowh = 0, start = 0;

            boolean ltr = target.getComponentOrientation().isLeftToRight();

            boolean useBaseline = getAlignOnBaseline();
            int[] ascent = null;
            int[] descent = null;

            if (useBaseline) {
                ascent = new int[nmembers];
                descent = new int[nmembers];
            }

            for (int i = 0; i < nmembers; i++) {
                Component m = target.getComponent(i);
                if (m.isVisible()) {
                    Dimension d = m.getPreferredSize();
                    m.setSize(d.width, d.height);

                    if (useBaseline) {
                        int baseline = m.getBaseline(d.width, d.height);
                        if (baseline >= 0) {
                            ascent[i] = baseline;
                            descent[i] = d.height - baseline;
                        } else {
                            ascent[i] = -1;
                        }
                    }
                    if ((x == 0) || ((x + d.width) <= maxwidth)) {
                        if (x > 0) {
                            x += hgap;
                        }
                        x += d.width;
                        rowh = Math.max(rowh, d.height);
                    } else {
                        rowh = moveComponents(target, insets.left + hgap, y, maxwidth - x, rowh, start, i, ltr,
                                useBaseline, ascent, descent);
                        x = d.width;
                        y += vgap + rowh;
                        rowh = d.height;
                        start = i;
                    }
                }
            }
            moveComponents(target, insets.left + hgap, y, maxwidth - x, rowh, start, nmembers, ltr, useBaseline, ascent,
                    descent);
        }
    }

    //
    // the internal serial version which says which version was written
    // - 0 (default) for versions before the Java 2 platform, v1.2
    // - 1 for version >= Java 2 platform v1.2, which includes "newAlign" field
    //
    private static final int currentSerialVersion = 1;
    /**
     * This represent the currentSerialVersion which is bein used. It
     * will be one of two values : 0 versions before Java 2 platform
     * v1.2.. 1 versions after Java 2 platform v1.2..
     *
     * @serial
     * @since 1.2
     */
    private int serialVersionOnStream = currentSerialVersion;

    /**
     * Reads this object out of a serialization stream, handling objects written by
     * older versions of the class that didn't contain all of the fields we use
     * now..
     */
    private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
        stream.defaultReadObject();

        if (serialVersionOnStream < 1) {
            // "newAlign" field wasn't present, so use the old "align" field.
            setAlignment(this.align);
        }
        serialVersionOnStream = currentSerialVersion;
    }

    /**
     * Returns a string representation of this FlowLayout object and
     * its values.
     *
     * @return a string representation of this layout
     */
    @Override
    public String toString() {
        String str = "";
        switch (align) {
        case LEFT:
            str = ",align=left";
            break;
        case CENTER:
            str = ",align=center";
            break;
        case RIGHT:
            str = ",align=right";
            break;
        case LEADING:
            str = ",align=leading";
            break;
        case TRAILING:
            str = ",align=trailing";
            break;
        }
        return getClass().getName() + "[hgap=" + hgap + ",vgap=" + vgap + str + "]";
    }

}

Example code:
public class WrapLayoutExample {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(WrapLayoutExample::runGui);
    }

    private static void runGui() {
        JFrame frame = new JFrame("A");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel(new WrapAndAlignHorizontallyTopLayout());

        JLabel l = new JLabel("CCC");
        l.setBorder(BorderFactory.createLineBorder(Color.red, 10));
        l.setVerticalAlignment(JLabel.TOP);

        panel.add(l);

        for (int i = 0; i < 44; i++) {
            l = new JLabel("BBBB");
            l.setBorder(BorderFactory.createLineBorder(Color.red, (int) (Math.random() * 50)));
            panel.add(l);
        }

        frame.setSize(300, 300);
        frame.setLayout(new BorderLayout());
        frame.add(new JScrollPane(panel));
        frame.setVisible(true);
    }
}

Result:


Q: Bootstrap modals not working I am trying to get modals from bootstrap to work but for some reason it is showing up like this:

This is the default code I used from the bootstrap documentation:

<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Modal title

        ...

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

Thanks in advance!

A: Have you initialized the modal with javascript? All you need is JQuery, the bootstrap CSS file, and the bootstrap JS file.
Then add this code in a


Q: Calculate 3 points of intersection I have a propably quite basic problem, but school is a long time ago and I can't find a way to solve this.
I have the two asymptotic curves through the origin
\begin{equation}
f(x)=20.344\cdot\left(1-\mathrm{e}^{-\mathrm{e}^{-2.583} \cdot x}\right)
\end{equation}
and
\begin{equation}
g(x)=\left(20.344\cdot\left(0.779\cdot\left(1-\mathrm{e}^{-\mathrm{e}^{-1.233} \cdot x}\right)\right)\right) \cdot\left(1-\mathrm{e}^{-\mathrm{e}^{-0.744} \cdot x}\right).
\end{equation}
According to a calculator, they have the three points of intersection (0|0), (0.969|1.436) and (19.797|15.787). Compared to the vizualisation of the curves they are correct. I need the calculation path and the calculator is neither presenting this nor telling the way he used. So I worked the below presented path, but I can't find a method to calculate these three points. The pq formula gives me a wrong result and polynomial division is not applicable. Can someone please tell me how to get to the results?
Thank you very much ahead!
\begin{equation}
\begin{aligned}
&f(x)=g(x)\\
&20.344\cdot\left(1-\mathrm{e}^{-\mathrm{e}^{-2.583} \cdot x}\right)=\left(20.344\cdot\left(0.779\cdot\left(1-\mathrm{e}^{-\mathrm{e}^{-1.233} \cdot x}\right)\right)\right) \cdot\left(1-\mathrm{e}^{-\mathrm{e}^{-0.744} \cdot x}\right)\\
&20.344\cdot\left(1-\mathrm{e}^{-0.076 \mathrm{x}}\right)=\left(20.344\cdot\left(0.779\cdot\left(1-\mathrm{e}^{-\mathrm{e}^{-1.233} \cdot x}\right)\right)\right) \cdot\left(1-\mathrm{e}^{-\mathrm{e}^{-0.744} \cdot x}\right)\\
&-20.344 \cdot e^{-0.076 x}+20.344=\left(20.344\cdot\left(0.779\cdot\left(1-\mathrm{e}^{-\mathrm{e}^{-1.233} \cdot x}\right)\right)\right) \cdot\left(1-\mathrm{e}^{-\mathrm{e}^{-0.744} \cdot x}\right)\\
&-20.344 \cdot e^{-0.076 x}+20.344=\left(20.344\cdot\left(0.779\cdot\left(1-e^{-0.291 x}\right)\right)\right) \cdot\left(1-\mathrm{e}^{-\mathrm{e}^{-0.744} \cdot x}\right)\\
&-20.344 \cdot e^{-0.076 x}+20.344=\left(20.344\cdot\left(-0.779 \cdot e^{-0.291 x}+0.779\right)\right) \cdot\left(1-\mathrm{e}^{-\mathrm{e}^{-0.744} \cdot x}\right)\\
&-20.344 \cdot \mathrm{e}^{-0.076 \mathrm{x}}+20.344=\left(-15.838 \cdot \mathrm{e}^{-0.291 x}+15.838\right) \cdot\left(1-\mathrm{e}^{-\mathrm{e}^{-0.744} \cdot x}\right)\\
&-20.344 \cdot \mathrm{e}^{-0.076 x}+20.344=\left(-15.838 \cdot \mathrm{e}^{-0.291 x}+15.838\right) \cdot\left(1-\mathrm{e}^{-0.475 x}\right)\\
&-20.344 \cdot e^{-0.076 x}+20.344=15.838 \cdot e^{-0.291 x} \cdot e^{-0.475 x}-15.838 \cdot e^{-0.291 x}-15.838 \cdot e^{-0.475 x}+15.838\\
&-20.344 \cdot \mathrm{e}^{-0.076 x}-15.838 \cdot \mathrm{e}^{-0.291 x} \cdot \mathrm{e}^{-0.475 x} \cdot \mathrm{e}^{-0.475 x} \cdot \mathrm{e}^{-0.475 x} \cdot \mathrm{e}^{-0.475 x} \cdot \mathrm{e}^{-0.475 x} \cdot \mathrm{e}^{-0.475 x} \cdot \mathrm{e}^{-0.475 x}+20.344=-15.838 \cdot \mathrm{e}^{-0.291 x}-15.838 \cdot \mathrm{e}^{-0.475 x}+15.838\\
&-20.344 \cdot e^{-0.076 x}-15.838 \cdot e^{-0.291 x} \cdot e^{-0.475 x} \cdot e^{-0.475 x} \cdot e^{-0.475 x} \cdot e^{-0.838 \cdot e^{-0.291 x}+20.344}=-15.838 \cdot e^{-0.475 x}+15.838\\
&-20.344 \cdot e^{-0.076 x}-15.838 \cdot e^{-0.291 x} \cdot e^{-0.475 x} \cdot e^{-0.475 x} \cdot e^{-0.475 x} \cdot e^{-0.291 x}+15.838 \cdot e^{-0.475 x}+20.344=15.838\\
&-20.344 \cdot \mathrm{e}^{-0.076 \mathrm{x}}-15.838 \cdot \mathrm{e}^{-0.291 \mathrm{x}} \cdot \mathrm{e}^{-0.475 \mathrm{x}}+15.838 \cdot \mathrm{e}^{-0.291 \mathrm{x}}+15.838 \cdot \mathrm{e}^{-0.475 \mathrm{x}}=-4.506\\
&-20.344 \cdot \mathrm{e}^{-0.076 \mathrm{x}}-15.838 \cdot \mathrm{e}^{-0.291 \mathrm{x}} \cdot \mathrm{e}^{-0.475 \mathrm{x}}+15.838 \cdot \mathrm{e}^{-0.291 \mathrm{x}}+15.838 \cdot \mathrm{e}^{-0.475 \mathrm{x}}+4.506=0\\
&\text{logarithmise everything:}\\
&-\log(20.344)\cdot (-0.076x)-\log(15.838)\cdot (-0.291x)\cdot (-0.475x)+\log(15.838)\cdot (-0.291x)+\log(15.838)\cdot (-0.475x)+\log(4.506)=0\\
&-3.013\cdot (-0.076x)-2.762\cdot (-0.291x)\cdot (-0.475x)+2.762\cdot (-0.291x)+2.762\cdot (-0.475x)+1.505=0\\
&0.229x-0.382x^2-0.804x-1.312x+1.505=0\\
&-0.382x^2-1.887x+1.505=0\\
&\text{divide by -0.382:}\\
&x^2+4.940x-3.940=0
\end{aligned}
\end{equation}


Q: Multiple for loops to parse XML to CSV not working I want to write a code that can be used on different XML files (all with TEI encoding) to see if specific elements and attributes appear, how often they appear and in what context). To do this I have written the following code:
from logging import root
import xml.etree.ElementTree as ET
import csv

f = open('orestes-elements.csv', 'w', encoding="utf-8")
writer = csv.writer(f)
writer.writerow(["Note Attributes", "Note Text", "Responsibility", "Certainty Element", "Certainty Attributes", "Certainty Text"])

tree = ET.parse(r"C:\Users\noahb\OneDrive\Desktop\Humboldt\Semester 2\Daten\Hausarbeit-TEI\edition-euripides\Orestes.xml")
root = tree.getroot()

try:
    for note in root.findall('.//note'):
        noteat = note.attrib
        notetext = note.text
        print(noteat)
        print(notetext)
    #attribute search
    for responsibility in root.findall(".//*[@resp]"):
        responsibilities = str(responsibility.tag, responsibility.attrib, responsibility.text)
    for certainty in root.findall(".//*[@cert]"):
        certaintytag = certainty.tag
        certaintyat = certainty.attrib
        certaintytext = certainty.text
    writer.writerow([noteat, notetext, responsibilities, certaintytag, certaintyat, certaintytext])
finally:
    f.close()

I get the error "NameError: name 'noteat' is not defined". I can indent writer.writerrow but the information from the other for loop doesnt get added. How do I get the information from the different for loops into my CSV file? Help would be greatly appreciated? (The print() in the for loops gives me the right results and with responsibilities I tried making it all one string but that isnt necessary I am just trying out different solutions - none work until now).
This is an example of my XML file: (some of the elements and attributes will not appear in some of the files - might this be a reason form the errors?)
<?xml version="1.0" encoding="UTF-8"?>

<?oxygen RNGSchema="teiScholiaSchema2021beta.rng" type="xml"?>

<TEI xml:lang="grc">
 <teiHeader>
  <titleStmt>
    <title cert="high">Scholia on Euripides’ Orestes 1–500</title>
    <author><note>Donald J.</note> Mastronarde</author>
   </titleStmt>
</teiHeader>
 <text>
   <div1 type="subdivisionByPlay" xml:id="Orestes">
    <div2 type="hypotheseis" xml:id="hypOrestes">
     Prefatory material (argumenta/hypotheseis) for Orestes

Orestes, pursuing <note cert="low">(vengeance for)</note> the murder of his father, killed Aegisthus and
        Clytemnestra. Having dared to commit matricide he paid the penalty immediately, becoming
        mad. And after Tyndareus, the father of the murdered woman, brought an accusation, the
        Argives were about to issue a public vote about him, concerning what the man who had acted
        impiously should suffer.

    </div2>
   </div1>
 </text>
</TEI>

Example of what CSV should look like:

A: The values in your writer.writerow() will not be defined if an element is missing. You could just define some default values to avoid this.
Try adding the following after the try statement:
noteat, notetext, responsibilities, certaintytag, certaintyat, certaintytext = [''] * 6

You could of course have 'NA' if preferred.


Q: Help debugging 404 on apt-get install apache2 I'm trying to install an apache server on Ubuntu 16.04. I'm following this guide. I therefore ran:
sudo apt-get update
sudo apt-get install apache2

Full traceback below. I also tried with --fix-missing as suggested by the traceback, but I still get 404s. I don't know how to debug this sort of issue. I have checked some of the URLs in a browsers and indeed they don't exist. So I think apt is looking in the wrong place. But that is odd since I just did apt-get update. Any help debugging the issue is appreciated.
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
  apache2-bin apache2-data apache2-utils libaprutil1-dbd-sqlite3 libaprutil1-ldap liblua5.1-0
Suggested packages:
  apache2-doc apache2-suexec-pristine | apache2-suexec-custom
The following NEW packages will be installed:
  apache2 apache2-bin apache2-data apache2-utils libaprutil1-dbd-sqlite3 libaprutil1-ldap liblua5.1-0
0 upgraded, 7 newly installed, 0 to remove and 122 not upgraded.
Need to get 1,383 kB of archives.
After this operation, 5,891 kB of additional disk space will be used.
Do you want to continue? [Y/n] y
Err:1 http://za.archive.ubuntu.com/ubuntu xenial/main amd64 libaprutil1-dbd-sqlite3 amd64 1.5.4-1build1
  404  Not Found [IP: 197.155.77.2 80]
Err:2 http://za.archive.ubuntu.com/ubuntu xenial/main amd64 libaprutil1-ldap amd64 1.5.4-1build1
  404  Not Found [IP: 197.155.77.2 80]
Err:3 http://za.archive.ubuntu.com/ubuntu xenial/main amd64 liblua5.1-0 amd64 5.1.5-8ubuntu1
  404  Not Found [IP: 197.155.77.2 80]
Err:4 http://za.archive.ubuntu.com/ubuntu xenial-updates/main amd64 apache2-bin amd64 2.4.18-2ubuntu3.14
  404  Not Found [IP: 197.155.77.2 80]
Err:5 http://za.archive.ubuntu.com/ubuntu xenial-updates/main amd64 apache2-utils amd64 2.4.18-2ubuntu3.14
  404  Not Found [IP: 197.155.77.2 80]
Ign:6 http://za.archive.ubuntu.com/ubuntu xenial-updates/main i386 apache2-data all 2.4.18-2ubuntu3.14
Err:7 http://za.archive.ubuntu.com/ubuntu xenial-updates/main amd64 apache2 amd64 2.4.18-2ubuntu3.14
  404  Not Found [IP: 197.155.77.2 80]
Err:6 http://za.archive.ubuntu.com/ubuntu xenial-updates/main i386 apache2-data all 2.4.18-2ubuntu3.14
  404  Not Found [IP: 197.155.77.2 80]
E: Failed to fetch http://za.archive.ubuntu.com/ubuntu/pool/main/a/apr-util/libaprutil1-dbd-sqlite3_1.5.4-1build1_amd64.deb  404  Not Found [IP: 197.155.77.2 80]

E: Failed to fetch http://za.archive.ubuntu.com/ubuntu/pool/main/a/apr-util/libaprutil1-ldap_1.5.4-1build1_amd64.deb  404  Not Found [IP: 197.155.77.2 80]

E: Failed to fetch http://za.archive.ubuntu.com/ubuntu/pool/main/l/lua5.1/liblua5.1-0_5.1.5-8ubuntu1_amd64.deb  404  Not Found [IP: 197.155.77.2 80]

E: Failed to fetch http://za.archive.ubuntu.com/ubuntu/pool/main/a/apache2/apache2-bin_2.4.18-2ubuntu3.14_amd64.deb  404  Not Found [IP: 197.155.77.2 80]

E: Failed to fetch http://za.archive.ubuntu.com/ubuntu/pool/main/a/apache2/apache2-utils_2.4.18-2ubuntu3.14_amd64.deb  404  Not Found [IP: 197.155.77.2 80]

E: Failed to fetch http://za.archive.ubuntu.com/ubuntu/pool/main/a/apache2/apache2-data_2.4.18-2ubuntu3.14_all.deb  404  Not Found [IP: 197.155.77.2 80]

E: Failed to fetch http://za.archive.ubuntu.com/ubuntu/pool/main/a/apache2/apache2_2.4.18-2ubuntu3.14_amd64.deb  404  Not Found [IP: 197.155.77.2 80]

E: Unable to fetch some archives, maybe run apt-get update or try with --fix-missing?

A: *

*197.155.77.2 works.

*http://za.archive.ubuntu.com works.

*http://za.archive.ubuntu.com/dists/xenial/ works.

*http://za.archive.ubuntu.com/dists/xenial-updates/ works.

*http://za.archive.ubuntu.com/dists/xenial/main/ works.

Either you are behind a proxy and are blocked from reaching them or their server is having maintenance or is unstable.


Q: Geometry of a Circle Four Tangent circles are centered on the x-axis. The radius of circle A is twice the radius of circle O. The radius of circle C is four times the radius of circle O. All circles have integer radii and the point (63,16) is on the circle. What is the equation of circle A?The questionnaire is here on the link

A: The circle $O$ has radius $r$, centered at 0.
The circle $A$ has radius $2r$, centered at $r+2r=3r$.
The circle $B$ has radius $3r$, centered at $3r+2r+3r=8r$.
The circle $C$ has radius $4r$, centered at $8r+3r+4r=15r$.
The equation of circle $C$ is then
$$(63-15r)^2+16^2=16r^2$$
or
$$209r^2-1890r+4225=0$$
Only one solution is integer, $r=5$. Then the radius of the circle $A$ is 10, and the equation is $$(x-15)^2+y^2=100$$

A: If the circle $O$ is centered at the origin with radius $r$, the center of $C$ is $(41r,0)$ and its radius is $24r$, so you need $(63-41r)^2+16^2=(24r)^2$  This is a quadratic, but the solution are a mess.  We get $r=\frac {2583 \pm8 \sqrt{31301}}{1105}$ with $A$ centered at $(3r,0)$ and having equation $(x-3r)^2+y^2=4r^2$.Both solutions appear acceptable.


Q: I can't pass th:object to controller and mapped to pojo using @ModelAttribute I am trying to retrieve object on my controller that mapped to my POJO
My POJO looks like this
public interface InventoryDetailPOJO {
    String getItem_cd();
}

And this is my form

    <button class="btn btn-block btn-options btn-save">Save</button>

<form action="#"
      th:action="@{/stock-list/inventory-detail}"
      method="post"
      th:object="${inventoryDetail}"
      class="pt-3 form-inventory-detail">

         Item No

         <input type="text" class="form-control form-control-sm w-25"
         th:field="*{item_cd}">

</form>

And for my controller
@RequestMapping(value = "/stock-list/inventory-detail", method = RequestMethod.POST)
public ModelAndView InventoryDetailSubmitPage(ModelAndView modelAndView,
    @ModelAttribute("inventoryDetail") InventoryDetailPOJO inventoryDetail,
        @RequestParam("item_cd") String item_cd) {

    System.err.println("InventoryDetail: " + inventoryDetail);
    System.err.println("item_cd: " + item_cd);

    modelAndView.setViewName("redirect:/stock-list");
    return modelAndView;
}

There're no item on inventoryDetail when I tried to log it, but There's a value on item_cd

A: Remove action="#", like this:
<form th:action="@{/stock-list/inventory-detail}"
      method="post"
      th:object="${inventoryDetail}"
      class="pt-3 form-inventory-detail">


Q: Difference in timing when returning a resolved Promise I have a function that does a bunch of work then returns a resolved Promise. Is there a difference in the timing when each will be resolved?
Option 1
function returnPromise() {
  // do a bunch of stuff
  return Promise.resolve();
}

and this way:
Option 2
function returnPromise() {
  return new Promise((resolve, reject) => {
    //do a bunch of stuff
    resolve();
  });
}

Does Option 1 release control after all the work is done, and Option 2 release control as soon as the function is called? I feel like this has root in the fact I don't fully understand the event loop. Thanks in advance for helping me understand this.

A:
Is there a difference with doing it this way?

No, both your examples do the exact same thing.
Promise.resolve and Promise.reject are simply static methods on the Promise Class that help you avoid constructing a whole Promise when you don't really need to.

A:
Is there a difference in the timing when each will be resolved?

No difference.  The Promise executor (the callback you pass to new Promise()) is called immediately and synchronously.  So, in BOTH cases, you are immediately and synchronously returning an already resolved promise and all the code in your function has already executed.
There should be no meaningful difference in execution timing.  Of course, one might take slightly different number of CPU cycles to execute, but both have the exact same outcome and both immediately return a promise that is already resolved so there should be no difference to the calling code at all.
Promise.resolve() is just meant as a more compact (and probably more efficient) means of creating an already resolved promise.

Does Option 1 release control after all the work is done, and Option 2 release control as soon as the function is called?

They both return when all your work is done and they return an already resolved promise.  This is because the executor callback to new Promise() is called synchronously (before your function returns).

I feel like this has root in the fact I don't fully understand the event loop. Thanks in advance for helping me understand this.

In this particular circumstance, all your code is run synchronously so there is no particular involvement of the event loop.  The returnPromise() function returns (in both cases) when your code in the function is done executing synchronously.  There is no async code here.

The event loop gets involved when you do .then() on the returned promise because even though the promise (in both cases) is already resolved, the .then() handler gets queued in the event queue and does not run until the rest of your Javascript after your .then() handler is done executing.
console.log("1");
returnPromise().then(function() {
    console.log("2");
});
console.log("3");

This will generate identical output results:
1
3
2

with both versions of your returnPromise() function because .then() handlers are queued until the next tick of the event loop (e.g. after the rest of your current Javascript thread of execution is done).


Q: How do I recover a ZIP file in WinRAR that's inside of another RAR file? I tried to use WinRAR to extract an archive, but I couldn't extract all of it because of 1 thing: a file inside the archive was corrupt. I tried using Alt+R, but it tried to do it to the entire archive, which I don't want. It also tried to get me to open another file to fix it. What other file? I am so confused! Please help!

A: Just right click on the winrar archieve and click extract files.Then in the box there will be a miscellaneous option (Keep Broken Files). Just check the box and extract it into your directory..


Q: Strongswan IKEv2 VPN on OS X 10.11 and iOS 10 Clients After many days of searching on Google, through Serverfault, and even on the StrongSwan website, I have been unsuccessful in attempting to get StrongSwan IPSec/IKEv2 VPN working on OS X 10.11.5 and iOS 10. I have been very successful in getting it to work on Windows 10 Pro Insider Preview and Android - neither of which are relevant to my travel arrangements where I will only have a Mac notebook and iOS 10 devices.
I have two StrongSwan VPN Servers setup - one in London and one in San Francisco, both with nearly identical configurations.
Having followed https://raymii.org/s/tutorials/IPSEC_vpn_with_Ubuntu_16.04.html I was able to quickly setup both servers and issue a single client certificate for Windows 10 Pro Insider Preview and Android. However, when I copy the p12s of the two servers over to OS X and iOS to create the VPNs I am presented with questions I didn't get what the other two operating systems.
I can seem to find a definitive answer on what is a "Remote ID" and "Local ID" and how does this pertain to me establishing a certificate based authenticated connection to the SwanStrong VPN Server?
From what little I have been able to find I have learned the following:

*

*Local ID must match the CN or SAN specified in the certificate (i.e. example@example.com)

*Remote ID is required by both OS X and iOS but I have no idea what to put in this input field

*Unlike Windows and Android which connected seamlessly with encryption, OS X and iOS both get stuck at "Connecting" or will quickly cycle to "Disconnecting" perpetually

This is one of the StrongSwan server configurations (the one I have been testing against):
# ipsec.conf - strongSwan IPsec configuration file

config setup
    charondebug="ike 2, knl 2, cfg 2, net 2, esp 2, dmn 2,  mgr 2"

conn %default
    keyexchange=ikev2
    ike=aes128-sha1-modp1024,aes128-sha1-modp1536,aes128-sha1-modp2048,aes128-s$
    esp=aes128-aes256-sha1-sha256-modp2048-modp4096-modp1024,aes128-sha1,aes128$
    dpdaction=clear
    dpddelay=300s
    authby=pubkey
    left=%any
    leftid=subdomain5.subdomain4.subdomain3.subdomain2.subdomain.domain.net
    leftsubnet=0.0.0.0/0
    leftcert=vpnHostCert.der
    leftsendcert=always
    right=%any
    rightsourceip=172.11.22.0/24,2002:25f7:7489:3::/112
    rightdns=8.8.8.8,2001:4860:4860::8888

conn IPSec-IKEv2
    keyexchange=ikev2
    auto=add

How can I correctly provision the VPN Tunnel on OS X 10.11.5 and iOS 10 with the same certificates used by Windows and Android?

A: As it turns out, I needed to use the Apple Configurator to create the VPN Profile so I could set the cryptography to use DH Group 2 and 3DES.
I also had to change the Remote ID to the FQDN of the VPN Server as it is listed in the certificate's Common Name. OS X ignored the Subject Alternative Name (SAN).
However, while I can now establish the connection to the VPN, I cannot traverse traffic over it.
As that question is unrelated to this, I have posted another question at: https://apple.stackexchange.com/questions/253340/sending-all-traffic-over-vpn-tunnel-ikev2-in-os-x-10-11-5


Q: Минималистичный поиск по спискам с дальнейшим его определением Допустим есть два списка:
list_1 = [1, 2, 3]
list_2 = [4, 5, 6]

И значение:
item = 3

Нужно определить в каком списке находится это значение и отправить этот список дальше в метод (напр. any_method(specific_list=...))
P.s. Вроде вопрос простой, но получается километровый код, интересно посмотреть на решение со стороны

A: если списков будет много, то можно сделать так:
arr = [
    [7, 11, 15],
    [1, 2, 3],
    [4, 5, 6],
]
item = 3

any_method(list(filter(lambda obj: item in obj, arr))[0])

правда все равно надо или в исключения заворачивать или учитывать, что ни одного списка может быть не найдено
или так:
any_method(next(filter(lambda obj: item in obj, arr), []))

тут как раз учитывается ситуация, когда ничего не будет найдено и тогда будет возвращен пустой список

A: if item in list_1:
    any_method(specific_list=list_1))
elif item in list_2:
    any_method(specific_list=list_2))

A: any_method(specific_list=list_1 if item in list_1 else list_2)


Q: Jquery Droppable Center Image in Div After Drop Event Hey there,i'm creating a simple inventory using jQuery droppable. For now, it's like :
$(document).ready(function() {

 $( ".weapon, .helmet" ).draggable({ revert: "invalid", cursor: "move" });
 $( "#weapon_spot" ).droppable({accept: ".weapon"});
 $( "#helmet_spot" ).droppable({accept: ".helmet"});

 // make inventory slots droppable as well

 $( ".inv_slot" ).droppable({accept: ".weapon"});

});

I'm kinda new to JQuery and have some trouble setting an image to be aligned inside a certain div. Everything(.weapon, .helmet etc) is a div. Inside them, there can be images. The divs are 70x70 and the images are of that size as well.
The css is like :
.inv_slot, #weapon_spot, #helmet_spot {
    width: 70px;
    padding: 10px;
    height: 70px;
    margin: 10px;
    border: 1px solid black;
    float: left;
    text-align: center;
}

and the image inside a div is like :

My problem is that when i drop an image to another div, it's not aligned in the center of the div, it's not locked and it can be moved inside it. It seems that i can use Drag.Move somehow to do that, but i can't find some good resource explaining that. Could you please help ? :)
EDIT : I have created a demo at http://jsfiddle.net/kzuRn/2/

A: Add a drop callback to the droppables and apply the style changes necessary. Because right now the item is still positioned absolutely it will not recognize your center css.
Something like this: WRONG (see below)
drop: function(ev, ui) {
        $(this).css({position: 'static'})
}

I updated the fiddle. I was wrong before. this is the droppable, and ui.draggable is the draggable.
drop: function(ev, ui) {
    $(this).append(ui.draggable.css('position','static'))
}


Q: How to detect when an EditText is empty using RxTextView (RxBinding) I'm doing validation on an EditText. I want the CharSequence to be invalid if it's empty or it doesn't begin with "https://". I'm also using RxBinding, specifically RxTextView. The problem is that when there is one character left, and I then delete it leaving no characters left in the the CharSequence the map operator doesn't fire off an emission. In other words I want my map operator to return false when the EditText is empty. I'm beginning to think this may not be possible the way I'm doing it. What would be an alternative?
Here is my Observable / Disposable:
val systemIdDisposable = RxTextView.textChanges(binding.etSystemId)
            .skipInitialValue()
            .map { charSeq ->
                if (charSeq.isEmpty()) {
                    false
                } else {
                    viewModel.isSystemIdValid(charSeq.toString())
                }
            }
            .subscribe { isValid ->
                if (!isValid) {
                    binding.systemIdTextInputLayout.isErrorEnabled = true
                    binding.systemIdTextInputLayout.error = viewModel.authErrorFields.value?.systemId
                } else {
                    binding.systemIdTextInputLayout.isErrorEnabled = false
                    binding.systemIdTextInputLayout.error = viewModel.authErrorFields.value?.systemId
                }
            }

And here is a function in my ViewModel that I pass the CharSequence to for validation:
fun isSystemIdValid(systemId: String?): Boolean {

    return if (systemId != null && systemId.isNotEmpty()) {
        _authErrors.value?.systemId = null
        true
    } else {
        _authErrors.value?.systemId =
            getApplication<Application>().resources.getString(R.string.field_empty_error)
        false
    }
}

A: After sleeping on it, I figured it out.
I changed RxTextView.textChanges to RxTextView.textChangeEvents. This allowed me to query the CharSequence's text value (using text() method provided by textChangeEvents) even if it's empty. Due to some other changes (not really relevant to what I was asking in this question) I was also able to reduce some of the conditional code too. I'm just putting that out there in case someone comes across this and is curious about these changes. The takeaway is that you can get that empty emission using RxTextView.textChangeEvents.
Here is my new Observer:
 val systemIdDisposable = RxTextView.textChangeEvents(binding.etSystemId)
            .skipInitialValue()
            .map { charSeq -> viewModel.isSystemIdValid(charSeq.text().toString()) }
            .subscribe {
                binding.systemIdTextInputLayout.error = viewModel.authErrors.value?.systemId
            }

And here is my validation code from the ViewModel:
fun isSystemIdValid(systemId: String?): Boolean {

        val auth = _authErrors.value

        return if (systemId != null && systemId.isNotEmpty()) {
            auth?.systemId = null
            _authErrors.value = auth
            true
        } else {
            auth?.systemId =
                getApplication<Application>().resources.getString(R.string.field_empty_error)
            _authErrors.value = auth
            false
        }
    }

Lastly, if anyone is curious about how I'm using my LiveData / MutableLiveData objects; I create a private MutableLiveData object and only expose an immutable LiveData object that returns the values of the first object. I do this for better encapsulation / data hiding. Here is an example:
private val _authErrors: MutableLiveData<AuthErrorFields> by lazy {
        MutableLiveData<AuthErrorFields>()
    }
    val authErrors: LiveData<AuthErrorFields>
        get() { return _authErrors }

Hope this helps someone!


Q: How to include the query filter in URL (cloudSearch) I am trying to retrieve data from cloudSearch, searching for the word "Person" and adding the following filter:
(prefix field=claimedgalleryid '')

The problem is that I don't know how to create the URL using that exact filter.
Could someone give me a suggestion or some link to Amazon documentation related to this topic?
What I've tried and didn't work:
...search?q=Gallerist&size=10&start=0&fq=(prefix%20field=claimedgalleryid%20%27%27)
...search?q=Gallerist&size=10&start=0&filter=(prefix%20field=claimedgalleryid%20%27%27)

A: You were close with your first attempt--it looks like you forgot to URI encode the = sign as %3D. Try this instead:
&fq=(prefix+field%3Dclaimedgalleryid+'')
I highly recommend using the "test search" feature to work out the kinks in your query syntax.  You can see the results right there, and then use the "View Raw: JSON" link to copy the full request URL and see how characters get escaped and such.


Q: Show depth on the page edge of the book (Turn.js)
https://github.com/blasten/turn.js/issues/260
http://turnjs.com/#samples/steve-jobs

I tried to do the same by keeping the .own-size class on the covers, but the "display" gets set to "none" for the 'cover pages' on navigating through the book. Why is it happening like this?

A: adding 'fixed' class to the cover pages solves the problem


Q: Optional overloaded methods when overriding Case :
I have an abstract class A. It contains two methods

*

*abstract void search(Position p);

*abstract void search(Animal a);
Class B and C extends A. I would like class B to implement search(Position p) only and class C to implement search(Animal a) only. However when I do so it gives an error, telling me to implement both of the method overloads.
How could I solve the problem? Any help is greatly appreciated

A: Here are the rules for classes extending Abstract class

*

*First concrete/non-abstract class must implement all methods

*If abstract class extends Abstract class, it can but need not implement
abstract methods.

Option 1: Interface Segregation
separate search(XXX) into two abstract classes

Option 2: Generics. Make search a Generic Type
public abstract class ClassA {

    public abstract <T> void search(T t);

    public static void main(String ...args){
        ClassA classA = new ClassB();
        classA.search(new Animal());
    }
}

class Animal{

}

class ClassB extends ClassA {

    @Override
    public <Animal> void search(Animal t) {
     System.out.println("called");
    }
}

Option 3: Interface
public class ClassA {
    public static void main(String... args) {
        Searchable classA = new ClassB();
        classA.search(new Animal());
    }
}

interface Searchable {
    public <T> void search(T t);
}

class Animal {
}

class ClassB implements Searchable {
    @Override
    public <Animal> void search(Animal t) {
        System.out.println("called");
    }
}

Option 4: Throw UnsupportedOperationException Exception(Not recomended)
class ClassB extends ClassA {

    @Override
    void search(Position p) {
        throw new UnsupportedOperationException("Not Supported");
    }

    @Override
    void search(Animal a) {

    }
}


Q: How to convert "DATASET POLYDATA" vtk file to "DATASET STRUCTURED_GRID"? I have a vtk file with header like:
# vtk DataFile Version 3.0
vtk output
ASCII
DATASET POLYDATA
POINTS 1000 float

now I need to convert it to a structured vtk file with header like:
# vtk DataFile Version 2.0
VTK from Matlab
ASCII
DATASET STRUCTURED_GRID
DIMENSIONS 32 32 1
POINTS 1000 float

is there a program or script to convert between these two types?


Q: how to create a MySQL / PHP sub query to count the number of records matching a value? I am having trouble querying MySQL. I want to actually get the count of records with the value of the current parent_cat_id. So in this case we want a sub_query that will tell us 4 (because there are 4
id  parent_cat_id   cat_name
6   2   Carrot
8   2   Potatoes
7   2   Lettuce
13  2   Asparagus
4   1   Pears
3   1   Banannas
2   1   Apples

the Main $query which produces what I posted and much more information which I will use....
$menu_query = "SELECT c.id AS id, parent_cat_id, cat_name FROM db.category c JOIN db.parent_category pc ON pc.id = c.parent_cat_id WHERE c.is_active = 1 AND c.is_menu = 1 ORDER BY pc.sort_order, c.sort_order;";

$menu_result = mysql_query($menu_query) or die(mysql_error());

while($menu_row = mysql_fetch_array($menu_result)){
    $menu_name = $menu_row['cat_name'];
    $id = $menu_row['id'];
    $parent_cat_id = $menu_row['parent_cat_id'];
            #echo $parent_cat_id;
    #return from database the $count of  records with the same  ['parent_cat_id'] 's

So I was hoping for a $sub_query of some sort so that I know in my php code to build the next menu's items. The first menu should have 4 and the second menu should have 3.
Thanks.
UPDATE FINAL WORKING SUB QUERY
SELECT c.id AS category_id, c.parent_cat_id, cat_name, d.totalCount
FROM category c
INNER JOIN parent_category pc
ON pc.id = c.parent_cat_id
INNER JOIN(
    SELECT parent_cat_id, COUNT(*) totalCount
    FROM category
    WHERE is_menu = 1
    AND parent_cat_id = 2
    ORDER BY parent_cat_id
) d
ON c.parent_cat_id = d.parent_cat_id
WHERE c.is_active = 1
AND c.is_menu = 1
ORDER BY pc.sort_order, c.sort_order;

Thanks again for your help!!!  I just needed to throw in another WHERE clause in the sub query you taught me.

A: you can have extra subquery to count the values for each parent_cat_id
SELECT  c.id AS id,
        pc.parent_cat_id,
        pc.cat_name,
        d.totalCount
FROM    db.category c
        INNER JOIN db.parent_category pc
            ON pc.id = c.parent_cat_id
        INNER JOIN
        (
            SELECT parent_cat_id, COUNT(*) totalCount
            FROM db.parent_category
            GROUP BY parent_cat_id
        ) d ON c.parent_cat_id = d.parent_cat_id
WHERE   c.is_active = 1 AND
        c.is_menu = 1
ORDER   BY  pc.sort_order,
            c.sort_order


Q: UIDatePicker set minimum and maximum time I've got a UIDatePicker with the time only and I need a possibility to set the minimum and the maximum hour is showed. For example, I need it to start at 6 hours and finish at 15 hrs. Is it possible to perform this with UIDatePicker?

A: 1) Use this function to retrieve the minimum and maximum date
func getTimeIntervalForDate()->(min : Date, max : Date){

let calendar = Calendar.current
var minDateComponent = calendar.dateComponents([.hour], from: Date())
minDateComponent.hour = 09 // Start time

let formatter = DateFormatter()
formatter.dateFormat = "h:mma"
let minDate = calendar.date(from: minDateComponent)
print(" min date : \(formatter.string(from: minDate!))")

var maxDateComponent = calendar.dateComponents([.hour], from: date)
maxDateComponent.hour = 17 //EndTime

let maxDate = calendar.date(from: maxDateComponent)
print(" max date : \(formatter.string(from: maxDate!))")

return (minDate!,maxDate!)
}

2) Assign these dated to your pickerview
func createPickerView(textField : UITextField, pickerView : UIDatePicker){
    pickerView.datePickerMode = .time
    textField.delegate = self
    textField.inputView = pickerView
    let dates = getTimeIntervalForDate()

    pickerView.minimumDate = dates.min
    pickerView.maximumDate = dates.max
    pickerView.minuteInterval = 30
    pickerView.addTarget(self, action: #selector(self.datePickerValueChanged(_:)), for: UIControlEvents.valueChanged)
}

That's it :)

A: Just use this:
datePicker.maximumDate = myMaxDate;
datePicker. minimumDate = myMinDate;

Where myMaxDate and myMinDate are NSDate objects

A: As for my problem, the answer with maximumDate and minimumDate isn't what I am looking for. Maybe my solution is not that clear and right, but it worked great for me.
I have changed the UIDatePicker with UIPickerView, wrote a separate delegate for it:
@interface CHMinutesPickerDelegate () <UIPickerViewDelegate, UIPickerViewDataSource>

@property (nonatomic, strong) NSArray *minutesArray;

@end

@implementation CHMinutesPickerDelegate

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:       (NSInteger)component {
    return [self.minutesArray count];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    return [self.minutesArray objectAtIndex: row];
}

- (NSArray *)minutesArray {
    if (!_minutesArray) {
        NSMutableArray *temporaryMinutesArray = [NSMutableArray array];
        for (int i = 0; i < 6; i++) {
            for (int j = 0; j < 2; j++) {
                [temporaryMinutesArray addObject: [NSString stringWithFormat: @"%i%i", i, j * 5]];
            }
        }
    _minutesArray = temporaryMinutesArray;
}
    return _minutesArray;
}

The minutesArray returns array of: { "05", "10"... etc}. It is an example for custom minutes picker, you can write the same thing for hour or etc, choosing your own maximum and minimum value. This worked nice for me.


Q: Detect text source from accessibility service I'm using an accessibility service to receive text from a view of a specific app. The text can be inserted manually or via voice. Is there any way to check the source? I'd like to change my behavior if the text is inserted manually or not.


Q: Windows 10 boot slow Pre Session Init 40 seconds Aggressive LPM I had an issue where pc starts to boot than pauses for 40 seconds while Windows logo and dots are spinning, no harddrive activity and keyboard and mouse are powered off, after 41 seconds boot proceeds as normal. I used Windows Performance Analyser as per this post.
Investigation in Windows Performance Analyser shows Pre Session Init taking 41 seconds mostly doing idling.

Some process activity was detected at ntoskrnl.exe and ACPI.sys which led me to believe driver initialisation issues.

A: Various attempts to disconnect devices from motherboard pointed at DVD drive, diconnecting it reduced Pre Session Init from 40 to 10 seconds. Next, I attempted to tweak BIOS settings for SATA controller, particularly Aggressive Link Power Management, when it is off then there was no delays in boot. I hope this research would help someone.


Q: Turning a command line app into a Cocoa GUI app on Mac OS X? Is there any tutorials or references, if such thing is possible, to make GUI applications out of command line apps?
What I mean is, having a command line app, wrap it into an app bundle and create a Cocoa GUI app that would have a simple interface to execute the command line app with its flags and parameters.

A: As a matter of fact there are.  Here is the first hit for a Google search:

*

*Cocoa Dev Central: Wrapping UNIX Commands
What you're looking for is the NSTask class.  Check out the documentation for all the information you need.

A: For very simple scripts, I recommend Platypus. For more complicated scenarios, you could try something like Pashua.


Q: get All data vs get partial data Optimization Let's say a client makes a GET call to the server to get all the  followers of some user. now the client shows a list of all the followers but the only data the list needs is:
{"username" : "user", "thumbUrl" : "http:/www.example.com/photo/1", "age" : 78}

now the user can click on one of the followers and he can see more data about the follower he clicked.
My question: should i bring from advance all the followers data from the server (full User Object) vs bring only partial data and then make another call onDemand when the userclicks a follower. And more important is if do i really need to care about such optimizations?
assumptions:

*

*data is throttled (10 Objects per call to followers)

*size of each User Object is around 1kb, partial around 200 bytes

*User usually clicks on 5 followers for each 10 Objects.

Points of Interest:

*

*size saved: about 10kb - 2kb - 5kb = 3kb per bucket of 10 users. is it negligible at this age of the internet? would it matter if the size difference was 30kb?

*bucket size: I gave examples with low bucket size but let's sat my bucket size can get up to 2Mb. Does it matter if my bucket size is 2Mb with the full User data vs 400kb with partial call? Is it slower? (Assuming the User will click enough followers to make the size difference negligible

*Will welcome any other points of interest

A: It depends.
Basically, you have to look at what the expected latency of the connection is, what the bandwidth is, and what responsiveness you want.
As an example: Suppose the round trip latency from client to server is 100 msecs and the bandwidth is 8 mb/s.  If you send the "full" data is 2Mb and the "partial" data is 400kb, then it will take 350 msecs to send the "full" record and 150 msecs to send a "partial" record.  If you send partial records, then each click requires 110 msecs to retrieve results.  Otherwise, each click is instant.  So:

*

*Full - First load: 350 msec, click: instant

*Partial - First load: 150 msecs, click: 110 msecs

The key point is to understand that each call adds overhead.  While it is very tempting to minimize the data transferred, this can actually make things slower, if it causes more round trips.
Of course, this is in and of itself misleading because network calls are variable.  But personally with these numbers I'd be tempted to load up front.
But this is just a very high level analysis.  Other things to consider:

*

*This completely ignores the server side cost.  How fast does it take the "full" data vs. the "partial"?  Can you pull the "full" data, cache it for the future, and return the partial?

*Code that gets the data in one block is likely to be simpler on both client and server, and therefore less buggy.

*If you send partial data, you have to worry about what happens if records change between the first pull and the second.

*To users, a single slow call followed by instant responsiveness feels "faster" than if every single click takes noticeable time.  You want to pay attention to how fast users feel the system is as much as possible at the expensive of concrete measures of how fast the system actually is.

In general, you are better off minimizing the number of network calls rather than minimizing the amount of data transferred overall.  But this cannot be a hard and fast rule because again, it really depends on both the expected bandwidth and the expected latency.  I should note, though, that bandwidth is constantly improving while latency is unlikely to improve significantly over time.

A: You can define the resources and representations in the way that suits your needs. I usually use GET to provide a "summary" view of a collection (like ".../followers") as a resource that provides a list of summaries of the followers, including their ids (or URIs if I'm being good). This is usually sufficient for the client to provide a list that the user can browse, and then drill down into.
However, sometimes the client really does want a list of the complete things. It just depends on your usage. And you can always provide a query string parameter (e.g. "?full=true") to switch back and forth (although an accept header, and content-negotiation, might be a more "correct" but complicated way to do it).
(As for the performance & optimization aspect, it's hard to pin down specific criterion, because that's going to be based on lots of things like your hardware, where it's deployed, middleware in front of your service, etc. Just (obviously) sending back fewer bytes will be faster... beyond that, you can do some performance testing to see what the acceptable thresholds are.)


Q: Divide one CSS column in 2 rows http://jsfiddle.net/9877/6E2pQ/2/
What I want do is have columncontent1 on the left and columncontent2 and columncontent3 stacked on the right side.  see the jsfiddle.  How do I fix the css? I am running out of ideas. Is the error in the css or the way the div placed in the body:

A: There's a lot going on there, I've simplified the HTML and CSS:
CSS:
.leftCol {
float: left;
width: 50%;
background-color: #ccc;
height: 60px;
}
.rightColContainer {
float: left;
width: 50%;
}
.rightCol1 {
background-color: #333;
height: 30px;
}
.rightCol2 {
background-color: #777;
height: 30px;
}

HTML:

columncontent1

columncontent2

columncontent3

You only need to 'contain' the right hand column to stop the 'stacked column' flowing incorrectly.

A: CSS3 actually allows you to make several columns automatically without having to have all those classes. Check out this generator: http://www.generatecss.com/css3/multi-column/
This is however only if you are trying to make your content have multiple columns like a newspaper.


Q: Pathos multiprocessing pool CPickle error When i tried to run the following code:
from pathos.multiprocessing import ProcessingPool as Pool
list1 = [1,2,3,4,5]
list2 = [6,7,8,9,10]
def function1(x,y):
    print x
    print y
if __name__ == '__main__':
    pool = Pool(5)
    pool.map(function1, list1, list2)

It gets the followwing error:
Traceback (most recent call last):
  File "test.py", line 9, in <module>
    pool.map(function1, list1, list2)
  File "C:\Python27\lib\site-packages\pathos\multiprocessing.py", line 136, in map
    return _pool.map(star(f), zip(*args)) # chunksize
  File "C:\Python27\lib\site-packages\multiprocess\pool.py", line 251, in map
    return self.map_async(func, iterable, chunksize).get()
  File "C:\Python27\lib\site-packages\multiprocess\pool.py", line 567, in get
    raise self._value
cPickle.PicklingError: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed

Isn't pathos.multiprocessing is designed to solve this problem?

A: I'm the pathos author.  When I try your code, I don't get an error.  However,  if you are seeing a CPickle.PicklingError, I'm guessing you have an issue with your install of multiprocess.  You are on windows, so do you have a C compiler?  You need one for multiprocess to get a full install of multiprocess.


Q: Why does slice not work directly on arguments? Tested it out on this fiddle after looking at underscore.
This seems like a hack to call slice on arguments when it is not on the prototype chain.
Why is it not on the prototype chain when it obviously works on arguments.
var slice = Array.prototype.slice;
function test () {
    return slice.call(arguments,1);
    // return arguments.slice(1)
}
var foo = test(1,2,3,4);
_.each(foo, function(val){
    console.log(val)
});

A: >>> Object.prototype.toString.call(arguments)
<<< "[object Arguments]"
>>> Array.isArray(arguments) //is not an array
<<< false
>>> arguments instanceof Array //does not inherit from the Array prototype either
<<< false

arguments is not an Array object, that is, it does not inherit from the Array prototype. However, it contains an array-like structure (numeric keys and a length property), thus Array.prototype.slice can be applied to it. This is called duck typing.
Oh and of course, Array.prototype.slice always returns an array, hence it can be used to convert array-like objects / collections to a new Array. (ref: MDN Array slice method - Array-like objects)

A: arguments is not a "real" array.

The arguments object is a local variable available within all
  functions; arguments as a property of Function can no longer be used.
The arguments object is not an Array. It is similar to an Array, but
  does not have any Array properties except length. For example, it does
  not have the pop method. However it can be converted to a real Array.

You could do:
var args = Array.prototype.slice.call(arguments);

A: Arguments is not an Array. It's an Arguments object.
Fortunately, slice only requires an Array-like object, and since Arguments has length and numerically-indexed properties, slice.call(arguments) still works.
It is a hack, but it's safe everywhere.

A: Referring to MDN: »The arguments object is not an Array. It is similar to an Array, but does not have any Array properties except length. For example, it does not have the pop method. However it can be converted to a real Array:«
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments
In order to call slice, you have to get the slicefunction, from the Array-prototype.