text:
Q: Spark-Vertica access issue (connects, prints schema, count but not able to get the records) I am able to connect to Vertica through EMR (Spark), count and print schema but not able to read the data. Able to telnet from EMR.
My Vertica version
Vertica Database
09.02.0104
vertica.jar
09.01.0100

Spark-shell command
spark-shell --jars /home/hadoop/vertica-9.0.1_spark2.1_scala2.11.jar,/home/hadoop/vertica-
jdbc-9.0.1-7.jar

Query to read the Vertica table
val source = spark.read.format("com.vertica.spark.datasource.DefaultSource").option("host",
"verticaHost").option("port", "port").option("db", "DataBase?ssl=true").option("dbschema",
"Schemna").option("user", "user").option("password", "password").option("table",
"table").option("numPartitions", "1").option("queryTimeout", "500").load()

I also added .option("query", "select * from schema.table limit 100") and counted but it gave full count of the table instead of 100.
Output
source.printSchema() --> works, gets the schema information
source.count() --> works, gets the count.
source.show() --> Throws below error.

Error
java.sql.SQLNonTransientConnectionException: [Vertica][VJDBC](100176) Failed to connect to host xxxxxx on port xxxx. Reason: Failed to establish a connection to the primary server or any backup address.
at com.vertica.io.ProtocolStream.<init>(Unknown Source)
at com.vertica.core.VConnection.tryConnect(Unknown Source)
at com.vertica.core.VConnection.connect(Unknown Source)
at com.vertica.jdbc.common.BaseConnectionFactory.doConnect(Unknown Source)
at com.vertica.jdbc.common.AbstractDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:208)
at com.vertica.spark.datasource.VerticaDataSourceRDD$.getConnector(VerticaRDD.scala:176)
at com.vertica.spark.datasource.VerticaDataSourceRDD$$anonfun$scanTable$1.apply(VerticaRDD.scala:205)
at com.vertica.spark.datasource.VerticaDataSourceRDD$$anonfun$scanTable$1.apply(VerticaRDD.scala:205)
at com.vertica.spark.datasource.VerticaDataSourceRDD$$anon$1.<init>(VerticaRDD.scala:338)
at com.vertica.spark.datasource.VerticaDataSourceRDD.compute(VerticaRDD.scala:330)
at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
at org.apache.spark.scheduler.Task.run(Task.scala:121)
at org.apache.spark.executor.Executor$TaskRunner$$anonfun$10.apply(Executor.scala:402)
at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:408)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: com.vertica.support.exceptions.NonTransientConnectionException: [Vertica][VJDBC](100176) Failed to connect to host xxxxxx on port xxxx. Reason: Failed to establish a connection to the primary server or any backup address.
... 31 more
Caused by: java.io.IOException: Failed to establish a connection to the primary server or any backup address.
at com.vertica.io.VStream.establishConnection(Unknown Source)
at com.vertica.io.VStream.<init>(Unknown Source)
... 31 more
Caused by: java.net.ConnectException: Connection timed out (Connection timed out)
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
... 33 more

How can it count and print schema but not read it. Thanks in advance!


text:
Q: How does a for loop work, specifically for(;;)? Looking through some old company code, I came across a for loop that looks like this:
for (;;) {
    //Some stuff
}

I tried Google but couldn't find any answers. Did I fall asleep in a programming class or is this an unusual loop?

A: This loop has no guard and acts as a while(true) loop. It will loop infinitely until a break.

A: This is the same as:
while(true) {
  //Some Stuff
}

Basically, an alternate syntax for an infinite loop.

A: It's an infinite loop.  Not exactly good coding because it isn't intuitive that is would actually compile or not throw a runtime error.  Rewriting as while(true) { /* code */ } would be much more readable to indicate a infinite loop.

A: It's an infinite loop. The initialization, condition, and increment statements are all optional, so without any of them, this will always loop again (unless a break is hit or some other construct interacts with it).
Although I'm unsure about Java, this question explains how in .Net your empty for and a while (true) will be compiled to exactly the same thing. I would not be surprised if Java does as well.

A: These are all infinite loops
for(;;) {
   // endlessly
}

while(true) {
   // endlessly
}

do {
   // endlessly
} while(true);

A: A for loop in java has the following structure -
for (initialization statement; condition check; update)
    loop body;

As you can see, there are four statements here -

*

*Initialization statement: This statement is executed only once, when the loop is entered for the first time. This is an optional statement, meaning you can choose keep this field blank. It is generally used for some initialization purpose.

*Conditional check: This statement is probably the most important one. It checks to verify whether or not certain expression evaluates to true. If it is, then the loop execution continues. You can choose to keep this field empty, which will be evaluated to true.

*Update: This statement list is executed from left to right, typically used to increment/decrement some variable.

*loop body: The body of the loop, which will be executed again and again based on the conditional check's truth value.

Basically this is how the execution follows - first, when the loop is entered for the first time, the initialization statement is executed once. Then the conditional check is executed to see if it evaluated to true. If it is, then the the loop body is executed, otherwise the loop execution is finished. After that, the Update statement(s) is(are) executed. Next, the conditional check is executed again, and if it evaluates to true, then again the loop body is executed, then update statement is executed, then again the conditional check....you get the picture.
Now about your for( ; ; ) syntax. It has no initialization statement, so nothing will be executed. Its conditional check statement is also empty, which means it evaluates to true after that the loop body is executed. Next, since the update statement is empty, nothing is executed. Then the conditional check is performed again which will again evaluates to true and then this whole process will again repeat.
So you see, this is basically an infinite loop which has no initialization statement, whose conditional check will always evaluates to true, and which has no update statement. This is equivalent to -
while(true)
{
    .....
}

which is another popular loop construct in java.
When you use an infinite loop like this, it's important pay attention to the breaking condition as in most cases you can't let a loop to run indefinitely. To break out of these kinds of loops, you can use the break statement. The structure is as follows -
if(some_condition_is_true)
    break;        // This will cause execution to break out of its nearest loop

or
if(some_condition_is_false)
    break;

redpajama_set_name: RedPajamaStackExchange


text:
Q: regex to check string is certain length I am trying to write a regex to match pairs of cards (AA, KK, QQ ... 22) and I have the regex ([AKQJT2-9])\1. The problem I have is that this regex will match AA as well as AAbc etc. Is there a way to write the regex such that I can specify I want to match ([AKQJT2-9])\1 and only that (i.e. no more characters after).

A: Enclose the regex in ^ and $:
^([AKQJT2-9])\1$

^ is the "start-of-string" anchor, and $ is the "end-of-string" anchor. If your regex flavor supports it, \A and \Z might be an even better choice since ^ and $ can also match start/end of a line in a multiline string, depending on your regex engine and configuration.

A: You mean, like this ?
^([AKQJT2-9])\1$

It will only match if the string is "AA", "KK", …
If you want to capture both characters, but not the rest of the string, you'll have to use another parenthesis
($match,$unused) = $string ~= (([AKQJT2-9])\2); # in perl


text:
Q: After a cancelled rebase in progress, I cannot update my branch from master branch? I have a separate branch with many additions on my local and I used to rebase with master branch to keep up with the core development. Last time, since it took too long I cancelled the rebase as it was progressing. After that point, whenever I ask for rebase, git says "Already up-to-date" but I am sure that it is not. In that case, how should I diagnoise the problem and solve it without damaging my local copy?

A: Once some rebase starts in git repo, it creates .git/rebase-merge/* folder and it will be present till rebase operation is completed.
In your case, if cancel the rebase operation, it will not remove any .git/rebase-merge/ folder automatically, which means that process is still active.
So, its always better to choose either below options:

*

*
git rebase --abort
{To abort the rebase operation (the perfect way to cancel the operation)

*
git rebase --continue
{To finish the rebase operation}


text:
Q: Why does this example iron code seem to block? I'm running this hello world example code from the http://ironframework.io homepage:
extern crate iron;

use iron::prelude::*;
use iron::status;

fn main() {
    fn hello_world(_: &mut Request) -> IronResult<Response> {
        Ok(Response::with((status::Ok, "Hello World!")))
    }

    Iron::new(hello_world).http("localhost:3000").unwrap();
    println!("On 3000");
}

I expected to see "On 3000" appear on standard out, but it never appears. My guess is that the main thread is being blocked before it executes the println. Why is that happening?
If I use a temporary and call unwrap afterwards, I get the expected output:
fn main() {
    fn hello_world(_: &mut Request) -> IronResult<Response> {
        Ok(Response::with((status::Ok, "Hello World!")))
    }

    let result = Iron::new(hello_world).http("localhost:3000");
    println!("On 3000");
    result.unwrap();
}

Why is it that the behavior changes when unwrap is called on the return value?
I'm running rust 1.1.0 and iron 0.1.20.

A: The answer occurred to me after I wrote the question.
The http function returns an HttpResult<Listening> The Listening type has a destructor that calls join on a thread, which blocks.
In the first case, the returned object's lifetime is complete after the unwrap call, so the destructor gets called which joins the thread. If I assign it to a variable, the destructor doesn't get invoked until after unwrap is called.


text:
Q: How to give width and height programatically for collection view cell in ios, swift 3 I tried to give the height and width for collectionViewCell , programatically. I used following method:
 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let viewWidth = self.deviceWidth/3 - 5
        let viewHeight = viewWidth

        return CGSize(width :100,height: 100)
    }

This didn't work. even this method didn't show as a hint. Help me with this. Is there any other delegate method to set the cell width and height programmatically in Swift 3?

A: Method collectionView(_:layout:sizeForItemAt:) is UICollectionViewDelegateFlowLayout protocol's method, so setting delegate and datasource of collectionView is not enough, you need to implement UICollectionViewDelegateFlowLayout with your custom class where you have added collectionView to call UICollectionViewDelegateFlowLayout protocol's methods. So implement UICollectionViewDelegateFlowLayout like below example:
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

A: Pls sure your class must implement UICollectionViewDelegateFlowLayout like this:
class ViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate, UICollectionViewDelegateFlowLayout
{
    ...
}

And then write this delegate method in your class:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
    return CGSize(width: 100, height: 100) // The size of one cell
}

Hope it will help you...

A: This methods always work. Please first ensure that this method is executed ot not. If not, the write delegate UICollectionViewDelegateFlowLayout like this:
class MyViewController: UIViewController , UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource{
   :
   :
}

And dont forget to bind the delegate and datasource of UICollectionView either from storyboard or by code collectionView.delegate = self and collectionView.datasource = self


text:
Q: sudo in expect script How to use sudo with an expect script ? Like I want to do
spawn sudo apt-get install wine
expect "*?assword: "
send "$passwd\r"
interact

But it does not send password. How can I resolve this ?

A: You can set user as sudoer, it can skip password validation.


text:
Q: VLC: Restart need after changing settings I'm trying to use VLC to take a number of screenshots from a number of videos... The location for the resulting screenshots varies slightly for each video, as does the naming convention. Both of these settings are configured in Tools > Peferences > Video > Video Snapshots.
However, I've found that after making changes to these settings they are not being recognised....until VLC is restarted.
I assume that this is a 'feature' common to everyone, and not just a bug with my version.
It's not the end of the world, but it's very annoying to have to restart the app after each change. And there doesn't seem to be any good justification for it - I can't see why it would be required; I assume it is just an oversight.
Is this a common experience? Is there any way around it... any way to coax the app into accepting modified settings without a restart?

A: Yes, this is a common experience. I have had the same behaviour with all versions of vlc I have used (that's a lot, I have been using vlc for many years) on both linux and windows operating systems.
Feature? Bug? Dunno.


text:
Q: How to avoid duplicate string in a spinner? I have a spinner and an edittext, I want the edittext to get the spinner text when pressed, but the result is that the text will be doubled a lot.
private EditText etTormenta2;
Spinner spnTormentaIni2;

String tormentaColumna1[]={"0","1","2","3","4","5","6","7","8"};

spnTormentaIni2=(Spinner)findViewById(R.id.spnTormentaIni2);

ArrayAdapter<CharSequence>adapter21=ArrayAdapter.createFromResource(this,
                R.array.combos_tormentaarena,android.R.layout.simple_spinner_item);

        spnTormentaIni2.setAdapter(adapter21);

        spnTormentaIni2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                int start =etTormenta2.getSelectionStart();
                final String str2 ="\"ColumnStart\": "+tormentaColumna1[i]+",";
                etTormenta2.getText().insert(start, str2);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });


text:
Q: Add HTTP message handler to all HTTP clients I have an HTTP message handler named AddHeadersHandler, which extends System.Net.Http.DelegatingHandler and I need it to be added to all current and future HttpClient instances, including typed, named and non-named clients.
I know I can add a handler using .AddHttpMessageHandler<AddHeadersHandler>() for a specific client, but how do I add it to all clients?
// AddHeadersHandler.cs
public class AddHeadersHandler: DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        request.Headers.TryAddWithoutValidation("X-Correlation-Id", Guid.NewGuid.ToString());

        return base.SendAsync(request, cancellationToken);
    }
}

// Startup.cs
services
    .AddHttpContextAccessor()
    .AddTransient<AddHeadersHandler>();
services
    .AddHttpClient<MyClient>()
    .AddHttpMessageHandler<AddHeadersHandler>(); // I don't want to specify this for each client.

// MyClient.cs
public class MyClient
{
    public HttpClient HttpClient { get; }

    public MyClient(HttpClient httpClient)
    {
        HttpClient = httpClient;
    }

    public async Task GetTest()
    {
        await HttpClient.GetAsync("https://localhost:5001/test"); // This should have headers attached.
    }
}

A: It can be done by configuring HttpClientFactoryOptions for all named options. We need to provide a delegate in HttpMessageHandlerBuilderActions, which will include your handler to AdditionalHandlers property list.
There are multiple ways of doing this using the Options pattern.
1. Using .AddSingleton() ❌
If your handler has any dependencies (ex. IHttpContextAccessor to get current correlation id), we would like to use dependency injection to resolve it.
We could use OptionsBuilder API to get a required handler using dependency injection. Unfortunately, OptionsBuilder API does not provide a method to configure options for all named instances like .ConfigureAll does.
Luckily, we can get what we need by registering a factory method for IConfigureOptions<HttpClientFactoryOptions> like so:
// Startup.cs
services.AddSingleton<IConfigureOptions<HttpClientFactoryOptions>>(provider =>
{
    // When name is null, it will be used for all configurations.
    return new ConfigureNamedOptions<HttpClientFactoryOptions>(name: null, options =>
    {
        options.HttpMessageHandlerBuilderActions.Add(builder =>
        {
            // Here we have access to ServiceProvider to get an instance of the handler.
            builder.AdditionalHandlers.Add(provider.GetRequiredService<AddHeadersHandler>());
        });
    });
});

2. Using .ConfigureAll() ✔
The following improved answer was inspired by LostInComputer.
Add .ConfigureAll in your Startup.cs and use IServiceProvider through builder object like so:
services.ConfigureAll<HttpClientFactoryOptions>(options =>
{
    options.HttpMessageHandlerBuilderActions.Add(builder =>
    {
        builder.AdditionalHandlers.Add(builder.Services.GetRequiredService<AddHeadersHandler>());
    });
});


text:
Q: Xcode shows same device twice in device selection list
Details :
Xcode version :  5.0 and 5.0.1
Devices : happens on all devices
Base SDK : I have two SDKs 6.1 and 7.0 doesn't matter which SDK i set as base.
What happens when i click on one of them and tried to run :
Selecting one cell compiles app using SDKs 6.1 and selecting other cell compiles app using SDKs 7.0
Both cells show same device name and setting base SDK to any of 6.1 / 7.0 doesn't affect.
First thing why Xcode shows device name twice ?
Any one face similar problem ? Is there any way to show sdk version along with device name ?


text:
Q: How to get the complete URL address most efficiently? I'm using a Java program to get expanded URLs from short URLs. Given a Java URLConnection, among the two approaches, which one is better to get the desired result?
Connection.getHeaderField("Location");

vs
Connection.getURL();

I guess both of them give the same output. The first approach did not give me the best results, only 1 out of 7 were resolved. Can the efficiency be increased by the second approach?
Can we use any other better approach?

A: I'd use the following:
@Test
public void testLocation() throws Exception {
    final String link = "http://bit.ly/4Agih5";

    final URL url = new URL(link);
    final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setInstanceFollowRedirects(false);

    final String location = urlConnection.getHeaderField("location");
    assertEquals("http://stackoverflow.com/", location);
    assertEquals(link, urlConnection.getURL().toString());
}

With setInstanceFollowRedirects(false) the HttpURLConnection does not follow redirects and the destination page (stackoverflow.com in the above example) will not be downloaded just the redirect page from bit.ly.
One drawback is that when a resolved bit.ly URL points to another short URL for example on tinyurl.com you will get a tinyurl.com link, not what the tinyurl.com redirects to.
Edit:
To see the reponse of bit.ly use curl:
$ curl --dump-header /tmp/headers http://bit.ly/4Agih5

<title>bit.ly</title>

moved here

As you can see bit.ly sends only a short redirect page. Then check the HTTP headers:
$ cat /tmp/headers
HTTP/1.0 301 Moved Permanently
Server: nginx
Date: Wed, 06 Nov 2013 08:48:59 GMT
Content-Type: text/html; charset=utf-8
Cache-Control: private; max-age=90
Location: http://stackoverflow.com/
Mime-Version: 1.0
Content-Length: 117
X-Cache: MISS from cam
X-Cache-Lookup: MISS from cam:3128
Via: 1.1 cam:3128 (squid/2.7.STABLE7)
Connection: close

It sends a 301 Moved Permanently response with a Location header (which points to http://stackoverflow.com/). Modern browsers don't show you the HTML page above. Instead they automatically redirect you to the URL in the Location header.

A: The above link contains a more complete method along the same line as the previous post
https://github.com/cpdomina/WebUtils/blob/master/src/net/cpdomina/webutils/URLUnshortener.java


text:
Q: WebGL: How to Use Integer Attributes in GLSL Is it possible to use integer attributes in WebGL vertex shaders? My vertex data contains integers and I want to define the vertex attributes like this:
attribute vec3 POSITION;
attribute int INDEX[8];
attribute float WEIGHT[8];

If this is possible, how would I pass the mixed vertex data to the shader from js using gl.bufferData?
If this is not possible, what is the best way to achieve the same results (pass indices from CPU to shader and use them as integers in the shader)?

A: WebGL does not support integer attributes. With some exceptions listed in the spec (https://www.khronos.org/registry/webgl/specs/1.0/), WebGL uses mostly the same GLSL feature set as OpenGL ES 2.0.
The spec document for the OpenGL ES Shading Language 1.00 (which is the GLSL version used for ES 2.0)says on page 30, in section "4.3.3 Attribute":

The attribute qualifier can be used only with the data types float, vec2, vec3, vec4, mat2, mat3, and mat4. Attribute variables cannot be declared as arrays or structures.

The best you can do is probably to simply use floats that do not have a fractional part. The range of values that can be represented exactly will be more limited than an integer using the same storage space. For example a 16-bit float (half float) has 11 bits of precision, and can exactly represent integers from 0 to 2048.


text:
Q: Creating a context menu with Rg.Plugins.Popup in Xamarin.Forms Is it possible to create a context menu using Rg.Plugin.Popup?
Basically, I would like to know if it is possible to do the following 2 things:

*

*Disable the dimming effect around the pop-up

*Place the pop-up adjacent to the button that is tapped in order to open it, above or bellow it.


text:
Q: How to move label's text right to left,when a character hides in left it shows on right? Here is my key code:
using System;
using System.Windows.Forms;
namespace Scroller
{
    public partial class Form1 : Form
    {
        int i, j;
        bool k = false;
        public Form1()
        {
            InitializeComponent();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            label1.Text = "Time:"+ System.DateTime.Now.ToString();
            i--;
            j = i + this.Width;
            if (i < this.Width && i > 0)
            {
                label1.Left = i;
            }
            else
            if (i < 0 && k == false)
            {
                label1.Left = i;
                k = true;
            }
            else
            if (i < 0 && k == true)
            {
                label1.Left = j;
                k = false;
            }

            if (i < 0 - label1.Width)
            {
                i = this.Width - label1.Width;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            label1.Text = "Time:"+  System.DateTime.Now.ToString();
            i = this.Width - label1.Width;
            label1.Left = i;
        }
    }
}

The effect that I want to make is the whole time string move right to left. When a pixel of the text disappear on the left side (because it is out of the form's left border),the pixel will shows on the right side.
In other words, the effect can't be make by delete the first character of string and append it to the last.
I knew that it will be easier to use two label to do it. Set one's location in the form and hide the other right by the form. Move them in the same time.
When the first label hit the left border of the form, the second hit the right border of the form. And the first one move out, the second move in. Until the second totally move in, reset their x location.
But I just want to use one label. So I chose to quickly switch the label's location, and try to "cheat" user's eye. The problem is when the label switch between left and right, it flash very obviously. Even though I set timer's interval below 20,the problem still exist.
Could you help me dissolve the flash problem or enlighten me other ways which can just use one label and one timer to make the effect I need?
Thanks. If I didn't describer my problem clear enough or need more code, please let me know.

A: I don't think you can work out the flashing problem changing the label's location in a windows form.
Another solution would be to set the label width the same size as the form width, make the label text fill all the width using spaces and make the timer always get the last character and put it on the beginning of the string.
Sample code below.
private void timer1_Tick(object sender, EventArgs e)
{
    label1.Text = label1.Text.Substring(label1.Text.Length - 1) + label1.Text.Remove(label1.Text.Length - 1);
}

private void Form1_Load(object sender, EventArgs e)
{
    // The total spaces required to fill the form vary from form.width and the initial label.text.width
    // Width | Spaces
    //  177  |   13
    //  228  |   30
    //  297  |   53
    //  318  |   60

    // The spacesEnd = 60 work for a form with width 319
    int spacesBegin = 0, spacesEnd = 60;

    label1.Text = "Time:" + System.DateTime.Now.ToString();
    label1.AutoSize = false;
    label1.Left = -3;
    label1.Width = this.Width - 1;
    label1.Height = 15;
    label1.BorderStyle = BorderStyle.FixedSingle;

    for (int i = 0; i < spacesBegin; i++)
        label1.Text = " " + label1.Text;
    for (int i = 0; i < spacesEnd; i++)
        label1.Text += " ";

    Timer timer = new Timer();
    timer.Tick += timer1_Tick;
    timer.Interval = 50;
    timer.Start();
}


text:
Q: Can I use variables in Nginx server block for SSL Cert and Key file? I'm using Nginx Apache Reverse Proxy, I have multiple VHOSTS and I want to serve them all in a single nginx vhost file with support for SSL.
My server block is
    server {
    listen 80;
    server_name _;

    root   /var/www/$host/web;

    access_log  /var/log/mylogs/httpd/$host/access.log;

    location / {
        try_files $uri $uri/ /index.php;
    }

    location ~ \.php$ {
        proxy_pass http://SERVERIP:8090;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location ~ /\. {
        deny all;
    }

}

This is working well without SSL for all sites BUT
when I do the same for SSL support below:
    server {
    listen 80;
    server_name _;

    ssl on;
    ssl_certificate /var/www/$host/ssl/$host-le.crt;
    ssl_certificate_key /var/www/$host/ssl/$host-le.key;
    root   /var/www/$host/web;

    access_log  /var/log/mylogs/httpd/$host/access.log;

    location / {
        try_files $uri $uri/ /index.php;
    }

    location ~ \.php$ {
        proxy_pass http://MYIP:8090;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location ~ /\. {
        deny all;
    }

}

I got errors something like this
ssl_certificate /var/www/$host/ssl/$host-le.crt not found
nginx config test failed

My vhost web files are in this format
/var/www/domain1.com/web
/var/www/domain2.com/web
/var/www/domain3.com/web
and their ssl cert and keys are in
/var/www/domain1.com/ssl
/var/www/domain2.com/ssl
/var/www/domain3.com/ssl
Please help me, I'm noob and still learning....

A: Use $ssl_server_name variable instead of $host.
It can be used since Nginx 1.15.9 and OpenSSL 1.0.2 version.
http://nginx.org/ru/docs/http/ngx_http_ssl_module.html
ssl_certificate     $ssl_server_name.crt;
ssl_certificate_key $ssl_server_name.key;


text:
Q: Algorithm for solving decimal exponents without fractions Could someone explain the steps involved in solving something like 2^2.2 if fractions couldn't be used, such as in an infinite precision calculation?

A: In the general case  a^b where ^ is exponentiation (not XOR), and a and b are real numbers:
pow(a,b) = exp( b * log(a) )
exp(x)   = sum[n = 0->inf]  x^n / n!
ln(x)    = sum[n = 1->inf]  (x-1)^n / n
x^n      = n == 0  ? 1   // unless x == 0
          (n%2==0) ? x^(n/2) * x^(n/2)
          othewrwise x*x^(n-1)
          // faster than loop for large n,

This requries two series that you need to terminate at a certain precision, but the exponentiation is only with natural numbers.
You also have to deal with sign of a and b (a^-b = 1/(a^b)), zero values etc.

A: A typical implementation of pow(x,y) (i.e. x^y) involves computing exp(y*log(x)).  No fractions involved.


text:
Q: Jinga used to automate adding HTML elements I have asked this question a few times and sorry to be annoying but I have added a bit more info so that you can hopefully help.
I have a database table called "country" with fields: country_code and country_name. e.g. country_code = AF country_name = Afghanistan I will need to make a drop-down with all the countries and add it to the HTML. Instead of adding the radio buttons manually, I want to try and do it using jinga.
This is what the model of the country table looks like in sqlalchemy:
class Country(db.Model):
country_code = db.Column(db.String(3), primary_key=True)
country_name = db.Column(db.String(150), unique=True)

With the below code, It is supposed to get the country name and set label as the countries name and then the id= to the country code and the for= to the country code as well. I'm not getting any errors, but it hasn't added any countries to the coutries drop down menu. I might not be understanding this correctly but jinga can do this right? I may be missing something so I have attached the javascript behind opening and closing the drop down.
{% extends "base.html" %} {% block title %}Your Countries{% endblock %}
{% block countriespage %}

Your Countries

        <input type="radio" class="radio" id="AF" name="countries"/>
        Afghanistan

    {% for country in country %}

                <input type="radio" class="radio" id="{{ country.country_code }}" name="countries"/>
                {{ country.name }}

    {% endfor %}

        <input type="radio" class="radio" id="AL" name="countries" />
        Albania

Javascript:
const selected = document.querySelector(".selected");
const optionsContainer = document.querySelector(".options-container");

const optionsList = document.querySelectorAll(".option");

// When clicked...
selected.addEventListener("click", () => {
  // it will toggle the countries dropdown by adding the class 'active' to it
  optionsContainer.classList.toggle("active");
});

// For each element in the list referencing every element with variable 'o'
optionsList.forEach(o => {
  // adds an event listener for when each element ('o') is clicked
    o.addEventListener("click", () => {
        // changes the element which has 'selected' to have the label of the clicked element (i.e. changes the top part of select box to clicked country)
        selected.innerHTML = o.querySelector("label").innerHTML;
        // closes the dropdown
        optionsContainer.classList.remove("active");
    });
});

I have a notes page which reads the notes a user has from sql and uses a for loop with jinga to show the notes. This is what the note code for adding the notes to the page is:

Notes

{% for note in user.notes %}

{{ note.data }}

    <button type="button" note-id={{ note.id }} class="close deleteNoteButton">
        ×
    </button>

{% endfor %}

I've tried many things but I'm not sure what's going wrong. Any help would be appreciated. Thanks


text:
Q: Wordpress Apache Adjust SSL Hello i have a site on my own computer hosting. I setup wordpress and apache on it. Got a domain name and registered it on cloudflare. They also offer a free certificate which i got and put into folder .crt and .key files. Here is my configuration for ssl and non-ssl for apache
HTTPS
<VirtualHost *:443>
    ServerName hascelin.fun
    ServerAdmin hascelin@gmail.com
    DocumentRoot /var/www/html/hascelin.fun/
    ServerAlias www.hascelin.fun

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
    <Directory /var/www/html/hascelin.fun/>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride All
            Order allow,deny
            allow from all
    </Directory>

    #RewriteEngine on
    #RewriteCond %{SERVER_NAME} =www.hascelin.fun [OR]
    #RewriteCond %{SERVER_NAME} =hascelin.fun
    #RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
    SSLEngine      on
    SSLCertificateFile        /home/orest/cert/hascelin.crt
    SSLCertificateKeyFile     /home/orest/cert/hascelin.key
</VirtualHost>

HTTP
<VirtualHost *:80>
    ServerName hascelin.fun
    ServerAdmin hascelin@gmail.com
    DocumentRoot /var/www/html/hascelin.fun/
    ServerAlias www.hascelin.fun

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
    <Directory /var/www/html/hascelin.fun/>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride All
            Order allow,deny
            allow from all
    </Directory>

    #RewriteEngine on
    #RewriteCond %{SERVER_NAME} =www.hascelin.fun [OR]
    #RewriteCond %{SERVER_NAME} =hascelin.fun
    #RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
    #SSLEngine      on
    #SSLCertificateFile        /home/orest/cert/hascelin.crt
    #SSLCertificateKeyFile     /home/orest/cert/hascelin.key

Media files are loading from http


text:
Q: Concatenar con JS Hola soy nuevo aqui y desearia que me ayudaran en un código de como concatenar html con javascript, este es mi codigo:

objeto1

objeto2

objeto3

objeto4

y necestio concatenar los li con un array en js como el siguiente
var frutas = [
      {
        'nombre'     : 'manzana',
        'indice' : 2
      },
      {
        'nombre'     : 'pera',
        'indice' : 4
      },
      {
        'nombre'     : 'durazno',
        'indice' : 1
      },
      {
        'nombre'     : 'fresa',
        'indice' : 3
      }
];

para que me muestre el indice mayor y el segundo mayor concatenado con los li de la lista, ejemplo:

*Objeto 1, pera

*Objeto 2, fresa
Espero que me puedan ayudar y de haberme explicado bien

A: Puedes usar Array.prototype.sort para ordenar el array, ya que es un array de objetos, vamos a ordenarlo dándole al método un callback, luego de ordenarlo, solo lo revertimos con Array.prototype.reverse, definimos una variable que irá aumentando, para poner el índice actual

let frutas = [
      {
        'nombre'     : 'manzana',
        'indice' : 2
      },
      {
        'nombre'     : 'pera',
        'indice' : 4
      },
      {
        'nombre'     : 'durazno',
        'indice' : 1
      },
      {
        'nombre'     : 'fresa',
        'indice' : 3
      }
];

function orderUl(items) {
  items = (items.sort((a, b) => {
    if (a.indice > b.indice) {
      return 1;
    }
    if (a.indice  ((a.indice  b.indice) ? 1 : 0))).reverse();

  let i = 1;
  items.forEach(el => {
    exampleUl.innerHTML += `<li>Objeto ${i}, ${el.nombre}</li>`;
    i++;
  });
}

orderUl(frutas);


text:
Q: program reading in file erroneously Alright, I'm about to do something I hate, because my issue is requiring me to post my code unadulterated.
This is for a homework assignment. ALL I need to do for this half of the project is read in data from a file, store it, and print the data back out. The data (found here: www.gamefaqs.com/ps2/459841-final-fantasy-xii/faqs/42703 just incase I've missed something about the data) is just a list of rare spawns from Final Fantasy 12. There's s series of entries, which I have a set of loops in place to take apart and cobble into a pair of arrays.
The problem is that several of the entries are giving me issues with either printing data it's not supposed to, or putting data in the wrong spots. Several of the entries, where a series of asterisks denotes the difficulty of the monsters is supposed to be converted into a numerical format based on the size of a temporary variable that the asterisks are put into, are instead reading a DIFFERENT variable (not all of them, just some of them). Further, entries 51 and 65 aren't trashing everything they are supposed to, and instead kicking back stuff I DON'T want printed.
All it's supposed to do is take in vital stats about the mobs (Name, HP, XP, LP, it's weakness, what drops when it dies, what can be stolen, what is gotten from a Poach attempt, the original sprite used, how tough it is[scale of 1-5], and where it spawns at). Everything else is supposed to be thrown out. After that, it's supposed to print the stats I've told it to, and in the order I specified. It works for /most/ of them.
I've gone through the code a dozen times with the Debugger, and I'm still not even sure exactly where it's buggering up. Even so much as a simple "look at this part of the loop" would help tremendously.
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>

using namespace std;

void readFile(int numericData[80] [4], string textData[80] [7]);
void printData(int numericData[80] [4], string textData[80] [7]);

int main()
{

    string trash;
    string textData [80] [7];
    /* columns: 0 = name 1 = Weakness 2 = drops
    3 = stealables 4 = poach item
    5 = appearnce type 6 = location */

    int numericData [80] [4];
    // columns: 0 = HP 1 = XP 2 = LP 3 = diff rank
    // used 2 multi-dimensional parallel arrays to avoid 10 parallel arrays

    readFile(numericData, textData);
    printData(numericData, textData);

    return 0;
}

void readFile(int numericData[80] [4], string textData[80] [7])
{
    ifstream inputFile;
    inputFile.open("80RaresFFXII.txt");

    string trash;
    string rankConverter;
    for (int i = 0; i < 169; i++)
    {
        getline(inputFile, trash);
    }
    //throws out first 169 trash lines, until first usale line.

    for (int rareReader = 0; rareReader < 80; rareReader++)
    {
        getline(inputFile, trash);
        getline(inputFile, trash);
        getline(inputFile, trash);
        // first three lines of EACH entry are trash: empty line,
        // rare number, and empty line

        getline(inputFile, trash, ':');
        getline(inputFile, trash, ' ');
        // reads the portion 'Name : ' and trashes

        getline(inputFile, textData[rareReader][0], '(');
        // stores name of monster

        getline(inputFile, trash);
        // throws away the rest of the Name line
        /* NOTE: this somehow fixed a different problem with
        entry 52 and on some how gumming up the works
        look at cosmetic fixes when they crop up*/

        getline(inputFile, trash);
        // trashes emplty line after name

        getline(inputFile, trash, ':');
        getline(inputFile, trash, ' ');
        inputFile >> numericData[rareReader][0];
        getline(inputFile, trash, ':');
        getline(inputFile, trash, ' ');
        inputFile >> numericData[rareReader][1];
        getline(inputFile, trash, ':');
        getline(inputFile, trash, ' ');
        inputFile >> numericData[rareReader][2];
        // stores HP, XP, and LP values

        getline(inputFile, trash);
        // trashes emplty line after LP

        getline(inputFile, trash, ':');
        if(trash == "\nWeak  ")
        {
        getline(inputFile, trash, ' ');
        getline(inputFile, textData[rareReader][1]);
        getline(inputFile, trash, ':');
        }
        else
        {
            textData[rareReader][1] = "None";
        }
        // one entry has missing line here

        if (trash == "Drops ")
        {
        getline(inputFile, trash, ' ');
        getline(inputFile, textData[rareReader][2]);
        getline(inputFile, trash, ':');
        }
        else
            textData[rareReader][2]= "N/A";

        if(trash == "Steal ")
        {
        getline(inputFile, trash, ' ');
        getline(inputFile, textData[rareReader][3]);
        getline(inputFile, trash, ':');
        }
        else
            textData[rareReader][3] = "N/A";

        if (trash == "Poach :")
        {
            getline(inputFile, trash, ' ');
            getline(inputFile, textData[rareReader][4]);
            getline(inputFile, trash, ':');
        }
        else
        {
            textData[rareReader][4] = "N/A";
        }
        // note: poach exists on only some entries.
        // if/else statement exsists to compensate for variation

        getline(inputFile, trash, ' ');
        getline(inputFile, textData[rareReader][5]);
        /* stores weaknes, drop items, poachable,
         stealable items, and the base sprite
         image used for the rare */

        getline(inputFile, trash, ':');
        getline(inputFile, trash, ' ');
        getline(inputFile, rankConverter);

        numericData[rareReader][3] = rankConverter.size();
        // takes in number of stars in Rare Rank, then coverts
        //the size to numerical form.

        getline(inputFile, trash, ':');
        getline(inputFile, trash, ' ');
        getline(inputFile, textData[rareReader][6]);
        // stores Location of rare

        if(rareReader > 79)
        {
            do
            {
                getline(inputFile, trash);
            }
            while (trash != "-------------------------------------------------------------------------------");
            // throws away the rest of each entry as trash
        }

    }
    inputFile.close();
}

void printData(int numericData[80] [4], string textData[80] [7])
{
    cout << setw(20) << "Name";
    cout << setw(10) << "HP";
    cout << setw(10) << "XP";
    cout << setw(10) << "LP";
    cout << setw(6) << "Rank";
    cout << setw(10) << "Weakness";
    cout << setw(10) << "Sprite\n";
    /*cout << setw(10) << "Poach\n";
        cout << setw(20) << "Drop";
    cout << setw(20) << "Steals";
    cout << setw(20) << "Location \n\n";*/

    for (int printCount = 0; printCount < 80; printCount++)
    {
        cout << setw(20) << textData[printCount][0];
        cout << setw(10) << numericData[printCount][0];
        cout << setw(10) << numericData[printCount][1];
        cout << setw(10) << numericData[printCount][2];
        cout << setw(6) << numericData[printCount][3];
        cout << setw(10) << textData[printCount][1] << endl;
        cout << setw(10) << textData[printCount][5];
        cout << setw(10) << textData[printCount][4];
        cout << setw(20) << textData[printCount][2] << endl;
        cout << setw(20) << textData[printCount][3];
        cout << setw(20) << textData[printCount][6] << endl;

        /* columns: 0 = name 1 = Weakness 2 = drops
        3 = stealables 4 = poach item
        5 = appearnce type 6 = location */
        //copy of note for convenience in reading
    }
}


text:
Q: What is the default size of the buffer used by FileWriter? What is the default size of buffer used by FileWriter ? Till I close the file as :
writer.close()

the buffer doesn't get flushed. So,what is the limit of my doing :
writer.write(string)

A: Please check https://stackoverflow.com/a/6976933/2231632
The file writer uses a default buffer size of 1024 bytes. That thread also provided enough discussion for starters as to what are the limitations of a FileWriter.


text:
Q: jquery get img tag's height I am trying to find out the width and height of img tag. There's two cases:
If the image is NOT in cache, then this works fine:
            img.onload = function() {
                console.log('LOADED');
                var photoWidth = $photo.width();
                console.log("photo width: " + photoWidth);
            };
            img.src = $photo.get(0).src;

It properly logs the width of the img tag. Notice that I don't want the dimensions of the image, but the img tag.
The problem arsies if the image is already in the cache. Then the above code outputs photo width: 0.
This is because onload is called faster than the img tag is inserted into the DOM. (I think).
What are my alternatives?
Thanks

A: You can use the element's offsetWidth and offsetHeight.
See this fiddle.


text:
Q: Are Bearer token hidden over https calls to a REST endpoint So I'm working on a application where a access tokens(JWT,Using spring security) is used authenticate a user the tokens are encrypted and stored in a httponly cookie (ngx-cookie) and the access token has validity of 24hrs and a new token is issued if expired ,currently I'm working on localhost and the bearer token is visible in the headers in the network tab whenever I make an api call. My question is when the application is live and over https(SSL) will the headers and the payload data will be still visible  or hidden/encrypted ?
Currently new to programming so any guidance will be very helpful.
Bearer tokens are shown only for failed api calls not sure how and why

A: TLS (Transport layer security, earlier SSL) is the protocol responsible for handling HTTPS. In OSI reference model, TLS protocol applies to transport layer (layer 4), while HTTP protocol is an application layer (layer 7) protocol (headers are part of HTTP protocol).
Note: OSI model is a reference model while the actual implementation is the IP model which is a simplified version of the OSI mode.
In communication, data from a given layer is encapsulated/wrapped by the layer below that before sending (read more about the OSI reference model). Therefore, your HTTP data (data + headers) will always be encrypted by the transport layer with the TLS protocol when HTTPS is enabled. Therefore, your application data, including HTTP headers/body will always be encrypted before it's sent over the network. Therefore, no need to worry.


text:
Q: Java GUI calculator textfield Trying to make a java calculator but the text field isn't displaying right. I want to show the equation and answer on the same text field rather than the equation then the answer. Want to be able to show "1+1=2" on the same line. How the code is now if I do it it will show "1+1" then 2 on the next line.
//global = global.concat(num1);

If i remove the // the calculator will do "1+1=" but the answer wont show.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Scanner;
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

//import java.util.ActionEvent;
public class gui implements ActionListener {
    public gui() {
    }

    public void actionPerformed(ActionEvent ae) {
        // JOptionPane.showMessageDialog(ìHello is pressedî);
    }

    public static void main(String[] args) {
        JFrame j = new JFrame("Calculator");
        Container c = j.getContentPane();
        // c.setLayout(new BorderLayout());
        JPanel p1 = new JPanel();
        p1.setLayout(new BorderLayout());
        p1.setLayout(new GridLayout(4, 4, 4, 4));
        final JTextField t = new JTextField(100);
        Font myFontSize = t.getFont().deriveFont(Font.BOLD, 50f);
        t.setFont(myFontSize);
        c.add(t, BorderLayout.NORTH);
        final JButton n1 = new JButton("1");
        n1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String num1 = n1.getText();
                String global = t.getText();
                global = global.concat(num1);
                t.setText(global);
            }
        });
        final JButton n2 = new JButton("2");
        n2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String num1 = n2.getText();
                String global = t.getText();
                global = global.concat(num1);
                t.setText(global);
            }
        });
        final JButton n3 = new JButton("3");
        n3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String num1 = n3.getText();
                String global = t.getText();
                global = global.concat(num1);
                t.setText(global);
            }
        });
        final JButton n4 = new JButton("4");
        n4.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String num1 = n4.getText();
                String global = t.getText();
                global = global.concat(num1);
                t.setText(global);
            }
        });
        final JButton n5 = new JButton("5");
        n5.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String num1 = n5.getText();
                String global = t.getText();
                global = global.concat(num1);
                t.setText(global);
            }
        });
        final JButton n6 = new JButton("6");
        n6.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String num1 = n6.getText();
                String global = t.getText();
                global = global.concat(num1);
                t.setText(global);
            }
        });
        final JButton n7 = new JButton("7");
        n7.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String num1 = n7.getText();
                String global = t.getText();
                global = global.concat(num1);
                t.setText(global);
            }
        });
        final JButton n8 = new JButton("8");
        n8.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String num1 = n8.getText();
                String global = t.getText();
                global = global.concat(num1);
                t.setText(global);
            }
        });
        final JButton n9 = new JButton("9");
        n9.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String num1 = n9.getText();
                String global = t.getText();
                global = global.concat(num1);
                t.setText(global);
            }
        });
        final JButton n10 = new JButton("0");
        n10.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String num1 = n10.getText();
                String global = t.getText();
                global = global.concat(num1);
                t.setText(global);
            }
        });
        final JButton n11 = new JButton("+");
        n11.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String num1 = n11.getText();
                String global = t.getText();
                global = global.concat(num1);
                t.setText(global);
            }
        });
        final JButton n12 = new JButton("-");
        n12.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String num1 = n12.getText();
                String global = t.getText();
                global = global.concat(num1);
                t.setText(global);
            }
        });
        final JButton n13 = new JButton("*");
        n13.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String num1 = n13.getText();
                String global = t.getText();
                global = global.concat(num1);
                t.setText(global);
            }
        });
        final JButton n14 = new JButton("/");
        n14.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String num1 = n14.getText();
                String global = t.getText();
                global = global.concat(num1);
                t.setText(global);
            }
        });
        final JButton n15 = new JButton("=");
        n15.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String num1 = n15.getText();
                String global = t.getText();
                // global = global.concat(num1);
                t.setText(global);
                ScriptEngineManager mgr = new ScriptEngineManager();
                ScriptEngine engine = mgr.getEngineByName("JavaScript");
                try {
                    String s = engine.eval(global).toString();
                    t.setText(s);
                } catch (ScriptException e1) {
                    e1.printStackTrace();
                }
            }
        });
        final JButton n16 = new JButton("C");
        n16.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // String num1 = n16.getText();
                String global = t.getText();
                global = null;
                t.setText(global);
            }
        });
        p1.add(n1);
        p1.add(n2);
        p1.add(n3);
        p1.add(n4);
        p1.add(n5);
        p1.add(n6);
        p1.add(n7);
        p1.add(n8);
        p1.add(n9);
        p1.add(n10);
        p1.add(n11);
        p1.add(n12);
        p1.add(n13);
        p1.add(n14);
        p1.add(n15);
        p1.add(n16);
        c.add(p1, BorderLayout.CENTER);
        j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        j.setSize(350, 350);
        j.setVisible(true);
    }
}

A: When = is pressed, simply concatenate the current text with the result, something like...
    final JButton n15 = new JButton("=");
    n15.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String num1 = n15.getText();
            String global = t.getText();
            t.setText(global);
            ScriptEngineManager mgr = new ScriptEngineManager();
            ScriptEngine engine = mgr.getEngineByName("JavaScript");
            try {
                String s = global + " = " +engine.eval(global).toString();
                t.setText(s);
            } catch (ScriptException e1) {
                e1.printStackTrace();
            }
        }
    });


text:
Q: Reduce y ticks spacing for histograms in matplotlib I am using matplotlib to plot a histogram where each bin contains 1 value. Here's a sample:
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator

def image():
    # Generate a bunch of random data, here's an example
    TYPE1 = [128, 129, 132, 6, 136, 139, 12, 13, 142, 140]
    TYPE2 = [18, 147, 148, 23, 152, 26, 154, 156, 157, 158]
    TYPE3 = [159, 161, 165, 42, 44, 172, 176, 182, 188, 62]
    TYPE4 = [190, 193, 198, 199, 72, 77, 80, 82, 215, 216]
    TYPE5 = [218, 223, 95, 226, 101, 106, 108, 109, 113, 127]

    fig, ax = plt.subplots(1, 1)
    ax = plt.figure().gca()
    ax.yaxis.set_major_locator(MaxNLocator(integer=True))
    ax.hist([TYPE1, TYPE2, TYPE3, TYPE4, TYPE5],
            color=['white', 'white', '0.8', 'green', 'black'],
            label=['TYPE1', 'TYPE2', 'TYPE3', 'TYPE4', 'TYPE5'],
            stacked=True,
            bins=250)

    ax.legend(loc='upper right', bbox_to_anchor=(1, -0.15), fancybox=True)
    plt.tight_layout()
    plt.show()

How do I reduce the spacing on the y axis between 0 and 1 to be say a quarter of the actual height to make it look like something as follows with a reduced height of the axis?

A: You can define the figure size where you can use a smaller height. Moreover, you do not need to define the ax again. I have commented out the redundant line. I would also use a 2 column format for the legends using the keyword ncol=2. It looks better.
fig, ax = plt.subplots(1, 1, figsize=(6, 2.5))
#     ax = plt.figure().gca()
ax.yaxis.set_major_locator(MaxNLocator(integer=True))

ax.legend(loc='upper right', bbox_to_anchor=(1, -0.15), fancybox=True, ncol=2)


text:
Q: tasklist vs. task manager memory Hi and thanks in advance.
What is the difference between the memory in the tasklist ( which you run in the cmd) and that GUI task manager. I noticed for browser processes, that the memory is off by a great deal. Which is more accurate of the process's memory.

A: Task Manager has lots of memory counters see View menu - Select Columns.
The standard one shown is private working set. This is a/ private - so only bytes in memory specific to this program (so no shell32 common code is counted) and b/ working set - the amount of memory mapped and present in that processes address space.
Even memory not present in address space may be in physical memory as on the standby list or in the file cache or being used by another program. It only requires flicking a bit to make it available to the process. Run two copies of notepad, notepad in now in the file cache (and being small) in two processes. But the code is only in memory once not three times.
If you want to make your own tasklist.
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")

Set colItems = objWMIService.ExecQuery("Select * From Win32_Process")

For Each objItem in colItems
'   If objitem.Name = "mspaint.exe" Then
        wscript.echo objitem.name & " PID=" & objItem.ProcessID & " SessionID=" & objitem.sessionid
'       objitem.terminate
'   End If
Next

Lines starting with a ' are commented out.
To use in a command prompt
cscript //nologo c:\path\script.vbs

These are the properties
Property                Type            Operation
========                ====            =========
CSName                              N/A                     N/A
CommandLine                         N/A                     N/A
Description                         N/A                     N/A
ExecutablePath                      N/A                     N/A
ExecutionState                      N/A                     N/A
Handle                              N/A                     N/A
HandleCount                         N/A                     N/A
InstallDate                         N/A                     N/A
KernelModeTime                      N/A                     N/A
MaximumWorkingSetSize               N/A                     N/A
MinimumWorkingSetSize               N/A                     N/A
Name                                N/A                     N/A
OSName                              N/A                     N/A
OtherOperationCount                 N/A                     N/A
OtherTransferCount                  N/A                     N/A
PageFaults                          N/A                     N/A
PageFileUsage                       N/A                     N/A
ParentProcessId                     N/A                     N/A
PeakPageFileUsage                   N/A                     N/A
PeakVirtualSize                     N/A                     N/A
PeakWorkingSetSize                  N/A                     N/A
Priority                            N/A                     N/A
PrivatePageCount                    N/A                     N/A
ProcessId                           N/A                     N/A
QuotaNonPagedPoolUsage              N/A                     N/A
QuotaPagedPoolUsage                 N/A                     N/A
QuotaPeakNonPagedPoolUsage          N/A                     N/A
QuotaPeakPagedPoolUsage             N/A                     N/A
ReadOperationCount                  N/A                     N/A
ReadTransferCount                   N/A                     N/A
SessionId                           N/A                     N/A
Status                              N/A                     N/A
TerminationDate                     N/A                     N/A
ThreadCount                         N/A                     N/A
UserModeTime                        N/A                     N/A
VirtualSize                         N/A                     N/A
WindowsVersion                      N/A                     N/A
WorkingSetSize                      N/A                     N/A
WriteOperationCount                 N/A                     N/A
WriteTransferCount                  N/A                     N/A

And the methods
Call            [ In/Out ]Params&type           Status
====            =====================           ======
AttachDebugger                              (null)
Create                  [IN ]CommandLine(STRING)                (null)
            [IN ]CurrentDirectory(STRING)
            [IN ]ProcessStartupInformation(OBJECT)
            [OUT]ProcessId(UINT32)
GetOwner                [OUT]Domain(STRING)                     (null)
            [OUT]User(STRING)
GetOwnerSid             [OUT]Sid(STRING)                        (null)
SetPriority             [IN ]Priority(SINT32)                   (null)
Terminate               [IN ]Reason(UINT32)                     (null)

Which is the same as
wmic process where name='notepad.exe' get /format:list

Further reading
https://msdn.microsoft.com/en-us/library/ms810627.aspx
https://www.labri.fr/perso/betrema/winnt/ntvmm.html (this no longer appears on the MSDN)


text:
Q: Is my PowerShell execution environment subtly corrupted? I don't expect an answer, but I'm hoping for a direction.
Sometimes, PowerShell ISE seems to just act, well, weird. The weirdness seems to come out of nowhere. I haven't found a way to reproduce the behavior.
Three days ago, I was writing code that operated on the CERT:\ drive, and Intellisense showed me the parameters for the filesystem provider (-File and -Directory) instead of the certificate provider (-ExpiringInDays).
Today, this code raised an exception.
Invoke-Command -ComputerName OneServer -Credential $admin `
    -ScriptBlock {Get-ChildItem -Path CERT:\ -Recurse -ExpiringInDays 366}

The system cannot open the device or file specified
    + CategoryInfo          : NotSpecified: (:) [Get-ChildItem], Win32Exception
    + FullyQualifiedErrorId : System.ComponentModel.Win32Exception,Microsoft.PowerShell.Commands.GetChildItemCommand
    + PSComputerName        : oneserver

Running this snippet of it on my local machine in the same PowerShell session raised the same exception.
Get-ChildItem -Path CERT:\ -Recurse -ExpiringInDays 366

Same exception for CERT:, CERT:\, and CERT:\*.
If I went one directory deeper, using -Path CERT:\LocalMachine, it ran without raising an exception, but it returned certificates that expire several years (more than 366 days) from now.
I switched to a different PowerShell session, pasted in both those snippets, and both ran fine. The variable $admin is set correctly in both sessions. To me, this seems to point at something going wrong in the execution environment. But just above, Invoke-Command and a local command raised the same error. I don't understand that.
The PowerShell event logs (under Microsoft/Windows/PowerShell/Operational) don't show an error for that exception, but they do show an "Access is denied" error related to Invoke-Command.

WSMan reported an error with error code: 5.
 Error message: Connecting to remote server oneserver failed with the following error message : Access is denied.

I think this is related to the execution environment. Running identical code in a different PowerShell session worked fine.
Other things that might be relevant

*

*I shutdown, logout, or restart only when Windows forces me to.

*I usually have more than one PowerShell ISE window open. They might stay open for days. During that time, they appear to work fine. (But, would I really know?)

*Sometimes, code with no variables will fail or produce strange output in one window, but will work as expected in another. I don't always notice that the output is strange. (PowerShell tells me that no certificates will expire before 2020. Is that right, or is it strange? I don't always know.)

*Weird IntelliSense behavior (above).

*Pester unit tests run against all my production code every time I open the ISE. Once in a great while, a bunch of them will fail. If I run them again manually, they succeed. Open a new ISE window, and they succeed.

How do I isolate this kind of problem?

PS > $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.15063.413
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.15063.413
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.

Remote servers are similar: automated jobs run Invoke-Command scripts against all our production servers every day without error. Probably. Maybe.


text:
Q: Git reset not changing workspace I would firstly like to apologise for my naivety but I am still very new to this and I'm in need of some help!
I've really done a number on my project and am trying to revert to a previous commit, in which the site works fine and all my tests pass. I have tried git reset --hard (commit#), git checkout, plus a few others. Each time the console tells me that the HEAD has changed to the right commit, however my workspace is still exactly the same as I left it.
How can I revert back to the way the workspace was originally, so that all my files are removed/updated to their previous state?
Thank you so much for your help!

A: Ah, I have worked it out! I needed to do a git clean to remove the untracked files and directories from the workspace.


text:
Q: Column 'Book.ISBN' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause When I execute the following query I receive the error:
Column 'Book.ISBN' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
select Book.ISBN, Book.A, Book.P, Book.Title, Book._Type, A.number
from Book,
    (select  count(*) as number, Book.ISBN, Book._Type
     from Book inner join Borrowed
            on Book.ISBN = Borrowed.ISBN
     group by Book.ISBN, Book._Type) A
where Book.ISBN = A.ISBN
group by Book._Type

A: In your query you don't need the Group By clause because you are not grouping by any attribute. So in theory this would be sufficient:
select Book.ISBN, Book.A, Book.P, Book.Title, Book._Type, A.number
from Book,
    (select count(*) as number, Book.ISBN, Book._Type
     from Book inner join Borrowed
            on Book.ISBN = Borrowed.ISBN
     group by Book.ISBN, Book._Type) A
where Book.ISBN = A.ISBN

However, to answer your question, you are getting this error because you need to group all the attributes in the SELECT statement. So you need to either remove the GROUP BY completely or else add all attributes in the SELECT to the GROUP BY.
As a rule, you need to only use grouping when you are aggregating in your SELECT statement. So in simple terms, when you are using functions such as MIN, MAX, SUM, COUNT etc. A list of all the common functions can be accessed here.

A: You got this exception just the first time; when  you use group by, you mus include all the columns you want to show in the group by, or, use aggregate functions like sum, max, min etc. because the group need just one value for each group.


text:
Q: .toggle is not a function In my website I have a lot of buttons. When the page loads, I need the first button to be clicked.
I tried getting the first button and then using the function .toggle('click').
var $btn = $('.btn-personalizar-tamanho')[0];
if($btn != undefined) $btn.toggle('click');
The console says .toggle it's not a function.

A: Try it
document.querySelector(selector).classList.toggle('classname');

A: The [0] returns a single DOM element from the jQuery collection. Remove it.
Use the jQuery result directly, fill-in as appropriate. eg:
$(selector).toggle()

(Note that toggle belongs to the jQuery object itself.)
There is no need to check for existence of elements. The selector will have to be adapted for "first" as appropriate.

A: First [0] returns the DOM element and a DOM element does not have a toggle method hence why you are getting the error message. Second, jQuery's toggle() shows and hides an element, that is not triggering the click event.
If you want to trigger the click event then you use click() or trigger('click'). to get the first element you can use first() or :first or eq(0) to get the element.
$('.btn-personalizar-tamanho').first().click()

or
$('.btn-personalizar-tamanho').first().trigger('click')

There is also no need to check if the element exists with jQuery because it does it under the hood when you chain methods.

A: Just do this if the button exists it will click it.
$('.btn-personalizar-tamanho').click();

If you need the first item specifically then add the "first" method
$('.btn-personalizar-tamanho').first().click();

also your solution will work if you wrap the result in another jquery selector and change the toggle method to trigger
$btn = $('.btn-personalizar-tamanho')[0];
if($btn != undefined) $($btn).trigger('click');


text:
Q: Setting up Subversion repo using LDAP groups in svn_access_file If I was doing this from scratch, I would have made this two separate repositories. Unfortunately, I have to make do with what is there.
Our repository looks like this:
/trunk
/tags
/branches
/secret/trunk
/secret/tags
/secret/branches

I have my SVN configuration setup like this:
<Location /gorp>
    DAV svn
    SVNPath /mnt/svn/repositories/gorp
    AuthType basic
    AuthName "Vegicorp Repostitory"
    AuthBasicProvider ldap
    AuthzLDAPAuthoritative off
    AuthLDAPUrl "ldap://ldap.vegicorp.net:389/DC=vegicorp,DC=NET?sAMAccountName" NONE
    AuthLDAPBindDN "CN=ldap-read,,OU=Users,OU=vegicorp,DC=vegicorp,DC=net"
    AuthLDAPBindPassword swordfish
    Require ldap-group CN=Development,OU=Groups,OU=vegicorp,DC=vegicorp,DC=net
    AuthzSVNAccessFile /opt/CollabNet_Subversion/repos_path_access/gorp
</Location>

This works great. All users in the LDAP group Development has access to our repository. However, not all developers should be able to even see the secret directory. Instead, I only want users in the cabal LDAP group to be able to access it.
And, I have my file gorp under the above repos_path_access access directory look like this:
[/]
* = r

[/trunk]
* = rw

[/branches]
* = rw

[/tags]
* = rw

[/secret]
dvadar = rw
cpalpatine = rw
glucas = rw
* =

So far, so good. My cabal group users, dvadar, cpalpatine, and glucas, have access to the /secret directory in my repository, and no one else even sees it. However, as people come and go, I have to manually change this path based access file. What I would like to do is have my path-based access give everyone in cabal access and hide it for everyone else:
[/]
* = r

[/trunk]
* = rw

[/branches]
* = rw

[/tags]
* = rw

[/secret]
@cabal = rw
* =

This does not work. Instead, I see this in my logs:
Tue Sep 03 11:30:50 2013] [error] [client 10.55.9.217] \
Failed to load the AuthzSVNAccessFile: An authz rule refers to group '@cabal'

What is the best way to give my cabal group access to secret without the rest of my developers seeing this directory?

A: Obvious way:
Define cabal group members in AuthzSVNAccessFile.

*

*You can do it by hand (edit members every time, when membership change)

*You can find and use LDAP-to-Authz sync-script (mentioned here, on SO somewhere) for updating @cabal when CN=cabal changed in LDAP

Tricky way

*

*You can add additional <Location /gorp/secret> with changed Require ldap-group directive and maintain group entirely in LDAP

A: I didn't find any of the current projects for syncing SVN authz with LDAP working satisfactory so I created a new one.
It's available here:
https://github.com/rbw0/authzync
And yes, I'm aware this is an old post. But users searching for a solution to this are likely to end up here.

A: I have something very similar to your question which should fully answer it:
@ZTE_OHSAS_administrators = rw
~@ZTE_OHSAS_administrators =

That one should work
¡Cheers!


text:
Q: Group by combining rows I have a table like this
ID | COUNTRY | AMOUNT
1  | USA     | 100
2  | USA     | 100
3  | USA     | 100
4  | FRA     | 100
5  | ITA     | 100
6  | ITA     | 100
7  | FRA     | 100

It is posible to use group by and combine certain values to get as a result a table like this?
ID | COUNTRY | AMOUNT
1  | USA     | 300
2  | EUR     | 400

A: Use group by with conditional
select (case when country = 'USA' then 'USA' else 'EUR' end) COUNTRY,
        sum(AMOUNT) AMOUNT, MONTH
from table t
group by (case when country = 'USA' then 'USA' else 'EUR' end), MONTH ;


text:
Q: Django - ImageField save to user folder fails I can successfully upload a file but I can not state the folder as the logged in username.  I have tried the following:
def user_directory_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
    return 'user_{0}/{1}'.format(instance.user.id, filename)

class Document(models.Model):
    user = models.OneToOneField(User)
    document = models.ImageField(upload_to=user_directory_path)
    uploaded_at = models.DateTimeField(auto_now_add=True)

but receive the following error:
Django Version: 1.9.6
Exception Type: RelatedObjectDoesNotExist
Exception Value: Document has no user.

The form is as follows:
class DocumentForm(forms.ModelForm):
    class Meta:
        model = Document
        fields = ('document', )

With the view as follows:
@login_required
def profile(request, extra_context={}):
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('profile')
    else:
        form = DocumentForm()
    return render(request, 'meta/profile.html', {
                  'form': form
                  })

Any advice would be appreciated, Alan.
Full trace below:
Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/profile/

Django Version: 1.9.6
Python Version: 2.7.10
Installed Applications:
('django.contrib.auth',
 'django.contrib.sites',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.admin',
 'django.contrib.humanize',
 'avatar',
 'mathfilters',
 'smart_selects',
 'tinymce',
 'dbbackup',
 'django_ical',
 'crispy_forms',
 'meta')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'fbf.middleware.QueryCountDebugMiddleware')

Traceback:

    File "/Users/alantingey/virtualenv/fbf/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
      149.                     response = self.process_exception_by_middleware(e, request)

    File "/Users/alantingey/virtualenv/fbf/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
      147.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)

    File "/Users/alantingey/virtualenv/fbf/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
      23.                 return view_func(request, *args, **kwargs)

    File "/Users/alantingey/freebetfriend.com/meta/views.py" in profile
      71.             form.save()

    File "/Users/alantingey/virtualenv/fbf/lib/python2.7/site-packages/django/forms/models.py" in save
      451.             self.instance.save()

    File "/Users/alantingey/virtualenv/fbf/lib/python2.7/site-packages/django/db/models/base.py" in save
      708.                        force_update=force_update, update_fields=update_fields)

    File "/Users/alantingey/virtualenv/fbf/lib/python2.7/site-packages/django/db/models/base.py" in save_base
      736.             updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)

    File "/Users/alantingey/virtualenv/fbf/lib/python2.7/site-packages/django/db/models/base.py" in _save_table
      820.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)

    File "/Users/alantingey/virtualenv/fbf/lib/python2.7/site-packages/django/db/models/base.py" in _do_insert
      859.                                using=using, raw=raw)

    File "/Users/alantingey/virtualenv/fbf/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method
      122.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

    File "/Users/alantingey/virtualenv/fbf/lib/python2.7/site-packages/django/db/models/query.py" in _insert
      1039.         return query.get_compiler(using=using).execute_sql(return_id)

    File "/Users/alantingey/virtualenv/fbf/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
      1059.             for sql, params in self.as_sql():

    File "/Users/alantingey/virtualenv/fbf/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in as_sql
      1019.                 for obj in self.query.objs

    File "/Users/alantingey/virtualenv/fbf/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in pre_save_val
      968.         return field.pre_save(obj, add=True)

    File "/Users/alantingey/virtualenv/fbf/lib/python2.7/site-packages/django/db/models/fields/files.py" in pre_save
      311.             file.save(file.name, file, save=False)

    File "/Users/alantingey/virtualenv/fbf/lib/python2.7/site-packages/django/db/models/fields/files.py" in save
      90.         name = self.field.generate_filename(self.instance, name)

    File "/Users/alantingey/virtualenv/fbf/lib/python2.7/site-packages/django/db/models/fields/files.py" in generate_filename
      328.             directory_name, filename = os.path.split(self.upload_to(instance, filename))

    File "/Users/alantingey/freebetfriend.com/meta/models.py" in user_directory_path
      22.     today_date = datetime.datetime.today().date()

    Exception Type: AttributeError at /profile/
    Exception Value: type object 'datetime.datetime' has no attribute 'datetime'

A: Seems like you have
from datetime import datetime

so either your command should be
today_date = datetime.today().date()

or just update your import statement to
import datetime

A: You are not collecting the logged in user anywhere! Your form only collects the document field.
class DocumentForm(forms.ModelForm):
    class Meta:
        model = Document
        fields = ('document', )

So it's natural that the following code would fail
return 'user_{0}/{1}'.format(instance.user.id, filename)

To fix it change your view to
obj = form.save(commit=False)
obj.user = request.user
obj.save()


text:
Q: Why can't photons cancel each other? The textbook argument against photons canceling each other draws upon the conservation of energy. Does this mean that energy conservation is a "stronger" principle than superposition? Waves in other media than the EM field, e.g., sound or water, do cancel out---presumably by passing on their energy to some other degree of freedom (e.g., heat). Could this imply that EM waves don't have any alternative channel to pass on the destructed energy and thus can't cancel out?

A: You need to careful when you talk about photons as waves because one photon is certainly not an EM wave, which is a superposition of many many photons. Indeed if you are talking about very high energy photons they will produce an electrons positron pair. In other words you can convert the energy of photons into the "mass energy" (think about the famous equation $E = mc^2 \gamma$) of an electron positron pair. This process is called pair production and is entirely quantum mechanical. That's why you don't learn about it in your standard EM course.

A:
The textbook argument against photons cancelling each draws upon conservation of energy.

Our theory of particle physics is called the standard model, and photons are point particles  of zero mass , in the axiomatic table of the model,
and that is what the textbook is using. Yes conservation of energy is a very strict law. (In addition, photon photon interactions, and that is how elementary particles behave,  are rare, for low energy photons, see here )

Does this mean that energy conservation is a "stronger" principle than superposition?

The classical electromagnetic wave when mathematically broken down into photons of energy hν (ν  the frequency of the classical light) emerges in a complicated way from the quantum mechanical "addition" of the complex wave functions of each photon, the photon "wave" is a probability wave for each photon. (see this answer of mine, individual photons behave exactly the same way)

Waves in other media than the EM field, e.g., sound or water, do cancel out---presumably by passing on their energy to some other degree of freedom (e.g., heat).

Classical electromagnetic waves do not need a medium to travel, as the michelson morley experiment showed. But they do interfere in bulk. See this instructive  mit video.

Could this imply that EM waves don't have any alternative channel to pass on the destructed energy and thus can't cancel out?

see above.
Do not confuse classical EM waves with their component photons.A building may be made out of bricks, but a brick is not a building

A: We should be careful to distinguish interaction, correlation, annihilation and interference. Photons do not interfere. Any interference takes place at wave function level, so impacts the probability of finding a number of photons. Photons can annihilate but this requires two photons of a least 511 keV each in order to create an electron-positron pair. Photons can interact (scatter) via transient vacuum charge fluctuations. Finally photons can be correlated by Bose statistics.

A: All waves traveling through a medium don't cancel out. Sound waves, water waves, waves in a rope, etc. pass each other and travel further after they have passed. They don't (or almost not) exchange energy with the medium (like being converted to heat, though there is dampening). Two oppositely traveling waves may seem to vanish for a moment, but the medium contains the kinetic energy of the waves.
The same holds for classical em waves, although they don't travel in a medium. A circular em wave traveling outward from a center and a circular wave moving toward the same center will pass each other and continue their journey, without losing energy because they can't lose energy to the vacuum.
So they don't cancel out (they interact and travel along as if they didn't have encountered each other) because they don't have a channel to lose their energy.

A: It is a curious thing, because in the early days of quantum mechanics it was thought that wave interference effects (which is what I think you mean by cancelling) were only possible for a particle and itself (Dirac said exactly that, although I would have to put in a fair amount of work to find a reference).
This is indeed true for most particles in quantum mechanics. However, since the advent of quantum field theory, it has been recognised that the wave function for a photon does not describe the probability where where the particle may be found, but rather describes the probability for where it might be found that a photon has been annihilated. It actually does not have to be the same photon. Wave interference effects have actually been observed by astronomers for photons originating in different galaxies (sorry I don't have more in the way of details).
What I can say, is that your text book is out of date on this particular topic.


text:
Q: Page in Page View Controller has a sudden dropping down motion I have 2 pages in my app that are transitioned with a UIPageViewController.
The first page loads fine but the second page will have a 'dropping' motion similar to the .gif image below.

This will only occur once when the page is loaded.
I am not really sure what causes this but my suspicions could be the constraints. It seems to be applying the constraints when the page is loaded.
I am currently looking at a solution to pre-load the pages first and if this works, i will expand the solution to pre-load only the previous and next page (if any). If there are any better solutions out there, do share with me.

A: I've had similar issues caused by the navigation controller/navigation bar and the automaticallyAdjustsScrollViewInsets property in code, or the "Adjust Scroll View Insets" property in the storyboard. It looks like your first page does not have it set, and the second page does.

A: I solved the problem by looking at 2 questions that was previously asked in stackoverflow.
The key point to take away was that when setting constraints you had to use the value with respect from the current View. Darryl Bayliss's answer here has a screenshot that gives a better understanding.
To understand more of this, looking at wuc's question and answers will provide some clue too.
For my problem, Darryl Bayliss's solution worked for me.

A: I  fixed this issue (for  Swift, iOS 8.3 ) ,; it is not big things ,  When you add constraints via "Add New Constraints"  ,choose Constraint to margin, (add your constraints without margins).


text:
Q: How to select multiple data in one SQL Query in JAVA JPA Spring Boot I have User entity which holds List of Groups. Each group has two lists: submissionDocumentType and reviewDocumentType. What is the most efficient way to get List of GroupDetails objects for User using as few as possible database calls (see final expected result below)?
User.java
public class User {
@Id
@GeneratedValue(generator ="uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String id;

@ManyToMany(mappedBy = "users")
private Set<UserGroup> userGroups;

UserGroup
public class UserGroup {

@Id
@GeneratedValue(generator ="uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String id;

@ManyToMany(mappedBy = "submissionUserGroups")
private List <DocumentType> submissionDocumentType;

@ManyToMany(mappedBy = "reviewUserGroups")
private List <DocumentType> reviewDocumentType;

GroupDetails.java
public class GroupDetails {

private String groupTitle;
private List<String> reviewDocTypes;
private List<String> submitDocTypes;

Expected response from GET method
[
{
    "groupTitle": "Group one",
    "reviewDocTypes": [
        "Prasymas Eazy",
        "Prasymas Tgwz",
        "Prasymas Gien",
        "Prasymas Docs",
        "Prasymas Ecyd",
        "Prasymas Sjvz"
    ],
    "submitDocTypes": [
        "Prasymas Buor",
        "Prasymas Kzhc",
        "Prasymas Zokx",
        "Prasymas Vvtb",
        "Prasymas Docs",
        "Prasymas Lutj",
        "atostogu prasymas"
    ]
},
{
    "groupTitle": "Group two",
    "reviewDocTypes": [
        "Prasymas Tgwz",
        "Prasymas Gien",
        "Prasymas Kzhc",
        "Prasymas Kblj",
        "Prasymas Docs",
        "Prasymas Ecyd"
    ],
    "submitDocTypes": [
        "Prasymas Tgwz",
        "Prasymas Wmwx",
        "Prasymas Buor",
        "Prasymas Gien",
        "Prasymas Kzhc",
        "Prasymas Kblj",
        "Prasymas Docs",
        "Prasymas Xdau",
        "Prasymas Lutj",
        "Prasymas Ecyd",
        "atostogu prasymas"
    ]
}
]

A: I guess you can do it in one query. As you can see in the reference documentation :

Spring Data allows modeling dedicated return types, to more selectively retrieve partial views of the managed aggregates.The easiest way to limit the result of the queries to only the name attributes is by declaring an interface that exposes accessor methods for the properties to be read

So we can fetch the result using a query method like  this :
interface UserRepository extends Repository<User, String> {
    Collection<GroupDetails> findById(String userId);
}


text:
Q: installation of Ubuntu 16.04 on virtualbox How to install Ubuntu on vmware.
How much ram should I give (if I have 6gb ram) and I have celeron processor

A: A rule of thumb is 'not more than half' of the RAM for the virtual machine. It works for me with 2 GB RAM, but with 6 GB in the computer, you can increase it to 2,5 GB or 3 GB.


text:
Q: When to use or not to use sendfile on/off in Nginx? We have this setting in our nginx.conf for quite a while.
sendfile on;

When we have updated a file e.g. /js/main.js and access from browser https://test.com/js/main.js?newrandomtimestamp, it will still load the older version unless we do a full refresh (clear cache) from our browser.
But when we change the settings from sendfile on; to sendfile off; the browser will load the correct version of the updated file.
For our production web server, should we use sendfile on; or sendfile off;?
If sendfile on; is required (May for the reason of better caching? Faster performance?) then how to solve the problem mentioned above?
Below is the nginx.conf in our production server, and we are using version 1.7.5:
user  nginx;
worker_processes  2;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;
worker_rlimit_nofile 51200;

events {
    use epoll;
    worker_connections  51200;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    client_max_body_size 8m;
    sendfile        on;
    keepalive_timeout  65;

    real_ip_header X-Forwarded-For;
    set_real_ip_from 0.0.0.0/0;
    large_client_header_buffers 4 32k;

    gzip on;
    gzip_min_length 1k;
    gzip_buffers 4 16k;
    gzip_http_version 1.1;
    gzip_comp_level 2;
    gzip_types text/plain application/x-javascript application/javascript text/css application/xml application/json;
    gzip_vary on;

    include /etc/nginx/conf.d/*.conf;
}

A:
... unless we do a full refresh (clear cache) from our browser.

This in itself, a clear manifestation that the "problem" is on the client-side.
sendfile has nothing to do with caching, only how NGINX buffers / reads the file (trying to stuff the contents directly into the network "slot", or buffer its contents first).
The only reasonable explanation is that your specific browser discards ?newrandomtimestamp as a parameter without value, so it's loading the same cached resource for either example.com?blah and example.com?boo.
If you give it a try, then https://example.com/js/main.js?v=newrandomtimestamp scheme, should give newer content every time.

A: There may be a solution to your file caching problem at the application level. It's a well-known problem in the JavaScript development world. The solution is usually called something like "output hashing".
The basic idea is to add a hash of the file contents to the file name so that the file is considered "new" and not found in the cache.
Angular does it at build time (see: --outputHashing).

A: you csn also use a exclude from the caching this file as i do
 location updater/serversettings.xml {
        expires -1;
        add_header 'Cache-Control' 'no-store, no-cache,
 must-revalidate, proxy-revalidate, max-age=0';
    }


text:
Q: Decorating a domain object from multiple data sources. Poor design? I have a primary data source that will return JSON data which I unmarshall to a java POJO.  The secondary data source then uses information from the first Java POJO classes to retrieve additional data from another data source.
My original plan was to have a single POJO that is partially populated by data source one and then completed by data source 2.
But from a purist point this would seem wrong, but I am unsure how you should design the system.
Just for reference, there is no need for this to be done asynchronously.

A: I wouldn't have a single POJO for everything. I would go with the following:

*

*Specific DTO class for the data coming from data source 1;

*Specific DTO class for the data coming from data source 2;

*POJO class for your domain model mapped from the 2 specific DTO classes mentioned above.

With this, you clearly separate data sources and use whatever logic you need to merge them into your domain model. With this, you decouple your domain model from the data sources, making it easier to change any of the classes if needed. You could even add or remove a data source easily.


text:
Q: Blogger Recent Posts Console Error: Cannot read property 'title' of undefined I found this recent Blogger script that will show recent posts of a certain label or tag. The script works fine. However, if I use this script more than once, to show recent posts of a different label, and throws an error of:

Cannot read property 'title' of undefined

Looking at the script, I cannot figure out what is causing this, or how to fix it.

There are a variety of these scripts available, some similar and some not. However, it appears as though they ALL throw this error. Is it possible the error is caused by the feed itself, or is it the script?
Specifically though, the console says the error is with this variable:
var posttitle = entry.title.$t;

A: The error is being caused by the numposts variable value being more than the number of posts present in the specific label
For example , your label might be containing only a single post but if you supplied the numposts's value to be more than 1 , then on the second iteration of the for loop , it will throw the above error as their won't be any post to iterate over
For working demo , check http://jsbin.com/quniyifuna/1/ , here two instances of the above code are working fine without any errors in the console
In the second demo , http://jsbin.com/dosuhi/1/ , I have given numposts a value greater than the posts present in that specific label , therefore in the console you would find the same error as yours

A: I think you didn't change the label name because blogger displays related posts under a specific label only for 1 time. However, you must try to change the blogger label from last line on your JS:

Just change the video label to another one, I'm sure, it'll works...


text:
Q: How to make a link url go through another page when clicked HTML I'm sorry I do not know how to word that title better. I have tried searching google but my terminology isn't helping my results.
Let me explain the context. When you're on a news website or blog and you're on their homepage like: www.homepage.co.uk/ and then you click an article it will go somewhere like this: www.homepage.co.uk/2017/article/ how do they make the 2017 appear? because if you remove the /article/ from the url it takes you to an archive of all the links in that year? I don't understand, is there a process to this?
When I click a link in my website it goes to: www.website.co.uk/link
I want to be able to have that 2017/link/ in the url so they can find the archive of that year just like on their websites?
How do I do this?
I am sorry if I am not explaining this very well.
I understand changing my filenames to : "2017/article.html" might work but I do not believe that is the correct way of doing it?
Thanks a lot for your time and suggestions!

A: You're asking about a couple of things: one is the taxonomy of the site.  Taxonomy, if you don't know, is the "shape" of or how your site is organized.  News sites, for instance, are usually organized by date and perhaps topic (Health and Leisure, Politics, Entertainment, etc.). The other aspect of your question is regarding what you might call RESful "hacking" of URLs.  One of the tenents of REST is that URLS (uri, to be accurate) are supposed to be hackable.  A news site might have /2017/10/10 to display all articles for Oct 10.  Maybe you remove the last "10", and get all the articles for October so far.  If you are not using a site platform that does this for you, you will have to maintain that taxonomy yourself, and manually write all the links.  Systems such as Drupal and Joomla, among others, will translate your taxonomy into automatically-maintained links.  In editing a page on one of these platforms, you typically only refer to the system's internal name of the page (could be a shortened version of the article's title in the above example), and the underlying engine takes care of reconstructing the URL for you (in case the page moves, or its tags/taxonomy changes).
This is a big topic, and I encourage you to do some further reading:
http://searchcontentmanagement.techtarget.com/feature/Building-a-website-taxonomy-in-eight-steps
https://www.drupal.org/docs/7/organizing-content-with-taxonomies/organizing-content-with-taxonomies