Need help creating 1 MySQL query

Question: I'm creating a message board. When a topic gets a reply, the entire topic (all rows that has the topicid) must be bumped to the top of the forum. Pinned topics should always be displayed first, then followed by the topic that has the most recent post date because they are bumped to the top when they get a reply.
This is a pic of the table that contains the posts.
DB Table before query
I need 1 query that will do the following:

group all the topicid together (lets call this "group");
within each group sort the rows by parentid ascending, but NULL always is sorted first;
groups that are "pinned" are displayed first
then groups that have the "latest" post displayed first

The query should give the following results
Results of the query
Answer: I'm afraid I can only answer parts of your question, but I'm giving it a shot and posting it anyway in the hope that it will help you solve your issue.
First, I'd grab the pinned messages (lastest first in this query):
SELECT * FROM messages WHERE pinned = 1 ORDER BY date DESC

Then, you can grab - let's say - the 10 most recent topics:
SELECT MAX(date) AS latest, topicid FROM messages GROUP BY topicid ORDER BY latest DESC LIMIT 10

Now you should know the topicids from which you want to display messages. You could "chain together" the messages with a join:
SELECT * FROM messages AS m1 JOIN messages AS m2 ON m1.postid = m2.parentid WHERE m1.topicid IN <some stuff here> ORDER BY m1.topicid ASC, m1.postid DESC

Sorry for the incomplete answer. Any comments to help me fill the gaps are welcome ;)
Comment: Thanks for the reply. I can do this with multiple queries, but I was wondering if I could do this with only 1 query.
Answer: I think this query will do what you want.
SELECT *
FROM messages m
ORDER BY IF(pinned='yes','9999-12-31 23:59:59', (SELECT MAX(date) FROM messages m2 WHERE m2.topicid = m.topicid)) DESC,
         topicid, IFNULL(parentid, 0)

The first part of the order by ensures that groups that are pinned are ordered first, followed by groups that have the most recent post. It does this by selecting the maximum possible date when the group is pinned, otherwise the latest date for posts in that group and sorts by that value descending. The second part then sorts those posts by topicid, and the final part sorts by parentid. To ensure that posts with a NULL parentid sort first, we use an IFNULL clause on parentid to set the sorting value to 0 when parentid is NULL.
I've created an SQLFiddle to demonstrate this.
Edit This updated query will also sort pinned topics by latest date instead of just by topicid. It does this by adding 1000 years to the date of pinned posts, thus ensuring that pinned posts sort ahead of non-pinned posts while retaining the ordering between pinned posts as well.
SELECT *
FROM messages m
ORDER BY (SELECT MAX(IF(pinned='yes', date + interval 1000 year, date))
          FROM messages m2
          WHERE m2.topicid = m.topicid) DESC,
   topicid, ifnull(parentid, 0)

Here's an updated SQLFiddle to demonstrate.
Comment: Not bad at all! But I also want to sort the pinned topics on the  "latest" post. So within all the pinned topics I want to display the topic that has the latest post first. In your query all pinned topics has latest post "9999-12-31 23:59:59" so the query just orders the pinned topic by the topic id.
Comment: Hi @Farliesz see my edit. This new query will retain ordering on pinned posts too.
Comment: Perfect! Thanks!

Need help creating 1 MySQL query


How to use proximity sensor and audio manager to reduce volume in android device

Question: I would like to implement a functionality in the app such that when user playing audio in his android mobile takes it nearer to his ear, volume should reduce and the audio should play through the earpiece. ( Similar way to what whats app doing when user listens to voice note and moves it near to ear.) Please suggest what is going wrong in the following code? Thanks for the help.
public class SensorActivity extends Activity implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mSensor;
ImageView iv;
Button b;
MediaPlayer player;
private AudioManager mAudioManager;
public boolean isHeadsetOn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sensor);
    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
    iv = (ImageView) findViewById(R.id.image);
    b = (Button) findViewById(R.id.audio);
    mAudioManager = (AudioManager) SensorActivity.this.getSystemService(Context.AUDIO_SERVICE);
    mAudioManager.setMode(AudioManager.STREAM_MUSIC);

    b.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (player != null && player.isPlaying()) {
                player.stop();
                player.release();
            } else {
                AssetFileDescriptor afd;
                try {
                    afd = getAssets().openFd("Kraddy Android Porn.mp3");
                    player = new MediaPlayer();
                    player.setDataSource(afd.getFileDescriptor());
                    player.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
                    player.prepare();

                    player.start();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }
    });
}

protected void onResume() {
    super.onResume();
    mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL);

}

protected void onPause() {
    super.onPause();

    try {
        // unregisterReceiver(mReciever);
        mSensorManager.unregisterListener(this);
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (player != null && player.isPlaying()) {
        player.stop();
        player.release();
    }
}

public void onAccuracyChanged(Sensor sensor, int accuracy) {
}

public void onSensorChanged(SensorEvent event) {
    Log.e("distance", String.valueOf(event.values[0]));
    if (event.values[0] == 0) {
        iv.setImageResource(R.drawable.near);
        mAudioManager.setSpeakerphoneOn(false);
    } else {
        iv.setImageResource(R.drawable.far);
        mAudioManager.setSpeakerphoneOn(true);

    }
}

}
Answer: following code works perfectly fine for the requirement I mentioned in my post.
package com.example.proximitysensordemo;

import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class SensorActivity extends Activity implements SensorEventListener {
    private SensorManager mSensorManager;
    private Sensor mSensor;
    ImageView iv;
    Button b;
    MediaPlayer player;
    private AudioManager mAudioManager;
    public boolean isHeadsetOn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sensor);
    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
    iv = (ImageView) findViewById(R.id.image);
    b = (Button) findViewById(R.id.audio);
    mAudioManager=(AudioManager)getSystemService(Context.AUDIO_SERVICE);

    b.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (player != null && player.isPlaying()) {
                player.pause();
            } else {
                AssetFileDescriptor afd;
                try {
                    if (player == null) {
                        afd = getAssets().openFd("Kraddy Android Porn.mp3");
                        player = new MediaPlayer();
                        player.setDataSource(afd.getFileDescriptor());
                        player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                        player.prepare();
                        player.start();
                    } else {
                        player.start();
                    }

                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }
    });
}

protected void onResume() {
    super.onResume();
    mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_FASTEST);
    mAudioManager.setMode(AudioManager.MODE_IN_CALL);
}

protected void onPause() {
    super.onPause();
    mAudioManager.setMode(AudioManager.MODE_NORMAL);
    try {
        // unregisterReceiver(mReciever);
        mSensorManager.unregisterListener(this);
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (player != null) {
        player.stop();
        player.release();
        player = null;
    }
}

@Override
protected void onStop() {
    // TODO Auto-generated method stub
    super.onStop();
}

public void onAccuracyChanged(Sensor sensor, int accuracy) {
}

public void onSensorChanged(SensorEvent event) {
    Log.e("distance", String.valueOf(event.values[0]));
    Log.e("MaximumRange", String.valueOf(mSensor.getMaximumRange()));

    if (event.values[0] < mSensor.getMaximumRange()) {
        iv.setImageResource(R.drawable.near);
        mAudioManager.setSpeakerphoneOn(false);

    } else {
        iv.setImageResource(R.drawable.far);
        mAudioManager.setSpeakerphoneOn(true);
    }
}

}
Hope this helps. Thanks.
PS: Don't forget to un-register the sensor because android system won't release the sensors automatically after the usage. If you forget to do so music player and other application which uses music player will behave odd.
Comment: Thank you, it works!
For who'll use this code: I just want to remember to add

to your Manifest! Probably you already know it, but I've wasted 4 hours of my life because of this missing permission! D:


How to make a random m3u playlist from all files in subfolders?

Question: I want to create a random playlist for my entire music collection of 90,000 tracks. - i.e.generate a single m3u playlist containing every mp3 in every subfolder of my music folder, and present the list in random order.
Any suggestions for how I can do that?
Answer: First, set up the list (you only need to do this when you add/delete files) :
find Music -type f -print >files.list
wc -l files.list >files.list.nlines

Then, to pick a random one,
line_number=$(echo "$(cat files.list.nlines) * $RANDOM / 32767" | bc -q)
file_to_play="$(sed -n ${line_number}p files.list)"

Comment: Thanks. The first command works well, but generates a  list of all files - how would I adapt it to list just the mp3's? I can't get the 2nd command to work. When I run it I get a ">" prompt. Is there a syntax error?
Comment: @user1175461 Fixed.
Comment: You can use the `shuf` command instead (`shuf -o files.list files.list`).
Comment: Thanks  - wow that shuf command worked unfeasibly quickly!
Comment: How can I adapt the first command to include only mp3 files?
Comment: OK I worked it out - added -name '*.mp3' as a parameter


Ignite Scan Query Throws class org.apache.ignite.binary.BinaryInvalidTypeException

Question: Following Ignite Readme page https://apacheignite.readme.io/docs/cache-queries#section-scan-queries I am trying to run the discussed example code.
IgniteCache<Long, Person> cache = ignite.cache("mycache");

// Find only persons earning more than 1,000.
try (QueryCursor<Cache.Entry<Long, Person>> cursor =
         cache.query(new ScanQuery<Long, Person>((k, p) -> p.getSalary() > 1000))) {
    for (Cache.Entry<Long, Person> entry : cursor)
        System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

I am getting the following exception
Caused by: class org.apache.ignite.binary.BinaryInvalidTypeException: examples.model.Person
    at org.apache.ignite.internal.binary.BinaryContext.descriptorForTypeId(BinaryContext.java:707)
    at org.apache.ignite.internal.binary.BinaryReaderExImpl.deserialize0(BinaryReaderExImpl.java:1757)
    at org.apache.ignite.internal.binary.BinaryReaderExImpl.deserialize(BinaryReaderExImpl.java:1716)
    at org.apache.ignite.internal.binary.BinaryObjectImpl.deserializeValue(BinaryObjectImpl.java:798)
    at org.apache.ignite.internal.binary.BinaryObjectImpl.value(BinaryObjectImpl.java:143)
    at org.apache.ignite.internal.processors.cache.CacheObjectUtils.unwrapBinary(CacheObjectUtils.java:177)
    at org.apache.ignite.internal.processors.cache.CacheObjectUtils.unwrapBinaryIfNeeded(CacheObjectUtils.java:39)
    at org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager$ScanQueryIterator.advance(GridCacheQueryManager.java:3063)
    at org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager$ScanQueryIterator.onHasNext(GridCacheQueryManager.java:2965)
    at org.apache.ignite.internal.util.GridCloseableIteratorAdapter.hasNextX(GridCloseableIteratorAdapter.java:53)
    at org.apache.ignite.internal.util.lang.GridIteratorAdapter.hasNext(GridIteratorAdapter.java:45)
    at org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager.runQuery(GridCacheQueryManager.java:1141)
    at org.apache.ignite.internal.processors.cache.query.GridCacheDistributedQueryManager.processQueryRequest(GridCacheDistributedQueryManager.java:234)
    at org.apache.ignite.internal.processors.cache.query.GridCacheDistributedQueryManager$2.apply(GridCacheDistributedQueryManager.java:109)
    at org.apache.ignite.internal.processors.cache.query.GridCacheDistributedQueryManager$2.apply(GridCacheDistributedQueryManager.java:107)
    at org.apache.ignite.internal.processors.cache.GridCacheIoManager.processMessage(GridCacheIoManager.java:1056)
    at org.apache.ignite.internal.processors.cache.GridCacheIoManager.onMessage0(GridCacheIoManager.java:581)
    at org.apache.ignite.internal.processors.cache.GridCacheIoManager.handleMessage(GridCacheIoManager.java:380)
    at org.apache.ignite.internal.processors.cache.GridCacheIoManager.handleMessage(GridCacheIoManager.java:306)
    at org.apache.ignite.internal.processors.cache.GridCacheIoManager.access$100(GridCacheIoManager.java:101)
    at org.apache.ignite.internal.processors.cache.GridCacheIoManager$1.onMessage(GridCacheIoManager.java:295)
    at org.apache.ignite.internal.managers.communication.GridIoManager.invokeListener(GridIoManager.java:1569)
    at org.apache.ignite.internal.managers.communication.GridIoManager.processRegularMessage0(GridIoManager.java:1197)
    at org.apache.ignite.internal.managers.communication.GridIoManager.access$4200(GridIoManager.java:127)
    at org.apache.ignite.internal.managers.communication.GridIoManager$9.run(GridIoManager.java:1093)
    ... 3 more
Caused by: java.lang.ClassNotFoundException: examples.model.Person
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at org.apache.ignite.internal.util.IgniteUtils.forName(IgniteUtils.java:8771)
    at org.apache.ignite.internal.MarshallerContextImpl.getClass(MarshallerContextImpl.java:349)
    at org.apache.ignite.internal.binary.BinaryContext.descriptorForTypeId(BinaryContext.java:698)

The Person object is taken from the Ingnite example (as well as most of the code, available https://gist.github.com/alexterman/075d7e12f470ce873f99d59478260250 on github ). I am running it on Mac.
Answer: This means you do not have Person class in classpath of your server node(s).
Ignite will not peer class load its Key-Value classes so you need to distribute them to all nodes before running any distributed operations which use those types.
Alternatively you can use withKeepBinary(), work on BinaryObject's. Something along the lines of
cache.withKeepBinary().query(new ScanQuery<Long, BinaryObject>(
    (k, p) -> p.<Integer>getField("salary") > 1000))

Comment: Ignite will not peer class load its Key-Value classes so you need to distribute them to all nodes before running any distributed operations which use those types. @alamar how to achieve using this way, can you give some example or more details


Debugging from a View file

Question: Working on a C# MVC project, I can have multiple files open in Visual Studio. When I press F5 to start debugging, the debugging starts if the currently open file is:

a controller (*.cs);
a model (*.cs);
a stylesheet (*.css);
a config file (*.config);
a partial view (*.cshtml)

However, if the open file is a View (*.cshtml), the browser opens with the "Server Error - URL not found" page.
Additional info: The solution has always been under source control with SVN but at some point, the repository location changed and from then on (I think), this strange error occurs. It didn't happen before, I could debug without thinking if a view file was open or not. The change wasn't performed by me and I lack details on it. I am not sure these things are related either.
Anyone has come across a similar issue? How to solve it?
Answer: I am guessing the problem is your project setup. Do following:

Project right click -> Properties -> Web -> Start action

Most likely it has "Current page" checked, which does not play well with ASP.NET MVC view, it just tries to open the view directly, and not via route. Every other type of file you mentioned is not detected as page, and thus VS does not try to open them as such.
You might want to choose a "Specific URL" there, or just make a habit of switching to a different file before hitting F5.
Comment: That could be it but, I checked "Specific Page" and tried many Views (Home, Main...) but I can't choose any file without getting the server error again
Comment: Again, you are choosing view as a page. This is not going to work for the same reason. Check you browser when you are trying to run the web app - url says "Views/Blah/View.cshtml", right? This is not a proper route in ASP.NET MVC, thus the Not found page. Specifc URL is your best bet here
Comment: But I don't want to specify a URL, debugs occur at localhost, from any machine. I tried leaving it black but it doesn't allow me. Nor something like "/" or "http://" - those don't work
Comment: @chiapa, well, you could try `http://localhost:/`, though this is not an option if you do not have a fixed port yet. I do not have VS at hand to try now, but does "Specific Page" allow you to enter some custom url? You could just enter something like `Home/Index`
Comment: Well, I tried that and it works but I'm not sure that's an optimal solution. Anyway, my main doubt is why this started happening all of a sudden, when before I could debug from any file without problems. I think I'll create a new MVC project to see how it behaves
Comment: OK, the newly created MVC project has "Specific Page" checked with a blank input, and you can run from view, controllers, whatever. Thank you for your effort

Debugging from a View file


creating random numbers that favor smaller numbers

Question: say i generated a set of random numbers and put them into an array, (pre-sorted for simplicity) i'll use javascript to show the math:
var vals = new Array(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,...,10000);

then in a loop, i created a random number to serve as an index:
for(i=0;i<10000;i++){
    var random_index = Math.floor(Math.random() * 10000);
    var result = vals[random_index];
}

if you looked at this output on any kind of graph, the results (with enough iterations through that loop, will look pretty random and balanced)
what I want, is for the results of each access to favor smaller numbers, which incidentally here is array elements with a lower index.
for a visual example, imagine you're trying to plot on a map where the fragments of a firework fell. most of those fragments would fall randomly within a vicinity but have a heavier concentration towards the middle. that's a bit of an over-complicated example since it's taking another dimension into account and uses physics to achieve the result, but it's the same principal.
what operation should i perform on the random_index variable to make it 'favor' smaller numbers?
Comment: If you don't know it already, you'll want to read about the [normal distribution](https://en.wikipedia.org/wiki/Normal_distribution). The position of firework particles on the ground is probably normally distributed.
Comment: On second thought, I agree the normal distribution is a better fit than the exponential.
Comment: possible duplicate of [Random number generator with higher probabilities of giving low values?](http://stackoverflow.com/questions/4420502/random-number-generator-with-higher-probabilities-of-giving-low-values)
Comment: @lhf just noticed this comment. yeah, the modified version of your proposed function in that thread is generally what i was after it seems.
Answer: The usual approach (as explained here, for instance) is to define the distribution function you want and then use one of two approaches to transform a uniformly distributed random variable into a random variable with the desired distribution. Provided your target distribution is simple enough, you can use inverse transform sampling.
If you don't really care what the distribution function is like, just that it favors smaller values, a simple approach might be to generate a uniform r.v. in the range [min2, max2] and then take its square root as your r.v.
Answer: There are any number of things you can do.
For instance:
Math.floor(Math.sqrt(Math.random() * 10000^2));

The real question is, what kind of distribution do you want?
Comment: good question, i think i'd have to see the result visually to determine what 'looks right' for the application i'm using this for. using that function, how can i manipulate the distribution?
Comment: That's right. Cubic root of cube will be more skewed towards small numbers than square root of square, and so on. Similarly you can take the logarithm of exponential, which again gives you a different shape. The possibilities are endless, and they're all fine if you just want a quick, arbitrary distribution that grossly favours small numbers. But if you need something more specific, then you should consider @Ted Hopp's answer.
Comment: This is a wrong answer. Sqrt(R * Max^2) = Sqrt(R) * Sqrt(Max^2) = Sqrt(R) * Max, and since your random seed is less than 1, its square root will be higher, resulting in the opposite of what the OP wants.
I think the approach is correct, if your random number is within the range of [1, Max^2] then its square roott will be what you're looking for, but since you're using Java functions for achieving this then you're getting it wrong.


What is the best approach for (client-side) disabling of a submit button?

Question: Details:

Only disable after user clicks the submit button, but before the posting back to the server
ASP.NET Webforms (.NET 1.1)
Prefer jQuery (if any library at all)
Must be enabled if form reloads (i.e. credit card failed)

This isn't a necessity that I do this, but if there is a simple way to do it without having to change too much, I'll do it. (i.e. if there isn't a simple solution, I probably won't do it, so don't worry about digging too deep)
Answer: For all submit buttons, via JQuery, it'd be:
$('input[type=submit]').click(function() { this.disabled = true; });

Or it might be more useful to do so on form submission:
$('form').submit(function() {
    $('input[type=submit]', this).attr("disabled","disabled");
});

But I think we could give a better answer to your question if we knew a bit more about the context.
If this is an ajax request, then you'll need to make sure you enable submit buttons again on either success or failure.
If this is a standard HTTP form submission (aside from disabling the button with javascript) and you're doing this to safe guard from multiple submissions of the same form, then you ought to have some sort of control in the code that deals with the submitted data, because disabling a button with javascript might not prevent multiple submissions.
Answer: You could do something like this:
$('form').submit(function() {
    $(this)
        .find(":submit,:image")             // get all the submit buttons
        .attr({ disabled : 'disabled' })    // disable them
        .end()                              // go back to this form
        .submit(function() {                // change the onsubmit to always reject.
            return false;
        })
    ;
});

Benefits of this:

It will work with all your forms, with all methods of submission:

clicking a submit element
pressing enter, or
calling form.submit() from some other code

It will disable all submit elements:

<input type="submit"/>
<button type="submit"></button>
<input type="image" />

it's really short.
Answer: I'm guessing that you don't want them to hit the submit button more than once while the submit is processing.
My approach has been to just hide the button entirely and display some sort of status indicator (animated gif, etc) instead.
Here's a very contrived example (it's technically in prototype but I think a jquery version would be very similar):

        <input type="submit" name="submit" id="submit" value="Submit" onclick="handleSubmit();"/>

Comment: +1 was helpful as I needed the submit button value posted through in the request. Disabling the button means the value isn't posted.
Answer: in JQuery:
$('#SubmitButtonID').click(function() { this.disabled = true; });

Answer: On thing to be aware of is that you should not disable the button before the form is submitted. If you disable the button using javascript in the OnClick event you may lose the form submit.
So I would suggest you hide the button using javascript by placing an image above it or by moving the button out of the visible range. That should allow the form submit to proceed normally.
Answer: There are three ways to submit a form that should be covered.  Use both David McLaughlin's and Jimmy's suggestions.  One will disable the submit button form element while the other disables the basic HTML form submit.
For the third, these won't disable Javascript from doing a form.submit().  The OnSubmit="return false" method only applies when a user clicks the submit button or presses Enter in a input form element.  Client side scripting will need to be handled as well.
Answer: How about
Code behind:
btnContinue3.Attributes.Item("onclick") = "disableSubmit()"
Javascript:
function disableSubmit() {
    document.getElementById('btnContinue3').onclick = function() {
        alert('Please only click once on the submit button!'); return false;
    };
}

This doesnt solve the problem of what happens if the postback times out, but other than that it worked for me.


HTML Pages appear differently between browsers bootstrap

Question: Im experiencing different layout in Chrome, IE and FireFox on my bootstrap project.
I suspect it has something to do with the imports.
header:
<!DOCTYPE html>

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>MY WEB</title>
    <link rel="shortcut icon">
    <link href="{{ url_for('static', filename='css/main.min.css') }}" rel="stylesheet">

    <link href="{{ url_for('static', filename='css/style.css') }}" rel="stylesheet">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Bottom of the html page:

Most of the my styling is written inside the html page.
Some of the objects that appear differently (Screenshots are added in the End):

Search form (also - how can I get rid of the arrow and leave only the search glyphicon?)

Button

Show

Navbar

Screenshots of the differences:
Chrome:

Firefox:

IE:
Comment: Please add a working Snippet
Comment: It is because all the browsers do no accept all the css. This is where you should be using vendor prefixing. I would suggest you to inspect the element in Firefox and check which line of CSS is causing the issue and replace with a generic css which is accepted across all the browsers or use vendor prefixes.
Comment: Vishnu which snippet do you mean ? And i've tried to inspect but didn't find the answer there... the reason is my usage of the navigation bar, it makes the redundant arrows as well, but I don't know what to do with it
Answer: As you can see in FF elements inside your buttons are centered. Make sure that you have covered such things. You can always use Can I Use


How to turn all list numbers in a dictionary to zeros

Question: I have the following:
d_out={'000000F|arrow_887067': ['G/G/G/G', '2', '3', '4', '5', '6', 'T/T/G/G', '8', '9', '10', '11', '12', '13', '14', 'G/G/G/G', 'T/T/T/G', '17', '18', 'T/G/G/G', '20', '21', '22', 'T/G/G/G', '24', '25', '26', '27', '28', 'T/G/G/G', '30', '31', '32', '33', 'G/G/G/G', '35', '36', '37', '38', '39', '40'],
       '000000F|arrow_887188': ['CTTTTATTC/CTTTTATTC/CTTTTATTC/CTTTTATTC', '2', '3', '4', '5', '6', 'A/A/A/A', '8', '9', '10', '11', '12', 'G/G/A/A', '14', 'A/A/A/A', '16', '17', '18', '19', '20', '21', '22', 'A/A/A/A', '24', '25', '26', '27', '28', '29', 'A/A/A/A', '31', '32', 'A/A/A/A', '34', '35', '36', '37', '38', '39', '40']}`

I would like the following:
d2_out={'000000F|arrow_887067': ['G/G/G/G', '0', '0', '0', '0', '0', 'T/T/G/G', '0', '0', '0', '0', '0', '0', '0', 'G/G/G/G', 'T/T/T/G', '0', '0', 'T/G/G/G', '0', '0', '0', 'T/G/G/G', '0', '0', '0', '0', '0', 'T/G/G/G', '0', '0', '0', '0', 'G/G/G/G', '0', '0', '0', '0', '0', '0'],
        '000000F|arrow_887188': ['CTTTTATTC/CTTTTATTC/CTTTTATTC/CTTTTATTC', '0', '0', '0', '0', '0', 'A/A/A/A', '0', '0', '0', '0', '0', 'G/G/A/A', '0', 'A/A/A/A', '0', '0', '0', '0', '0', '0', '0', 'A/A/A/A', '0', '0', '0', '0', '0', '0', 'A/A/A/A', '0', '0', 'A/A/A/A', '0', '0', '0', '0', '0', '0', '0']}`

How can I do this?
I have tried:
{key: [value if not isinstance(value, int) else 0 for value in lst]
           for key, lst in d_out.items()}

and
{i:[x if type(x)!=int else 0 for x in d_out[i]] for i in d_out}

Comment: @AdamSmith OK, no problem!
Comment: @Reedinationer I think our edits stomped each other, but mine is somewhat more readable so I rolled back.
Answer: Your first attempt failed because the values are not int objects -- they are strings of only digits. Try instead:
{key: [value if not value.isdigit() else '0' for value in lst]
     for key, lst in d1.items()}

Comment: This didn't work . Python outputs the message: name 'key' is not defined.
Comment: @MandieDriskill sorry: I forgot about that `key` reference by the time I got to the end of the dict comp :)


Partnerships and counting

Question: If there are $2n$ people, then the number of ways to form partnerships of $2$ if order doesn't matter is given by $\frac{(2n)!}{2^n n!}$. I understood the story proof given here Combinatorics: Partnerships Problem Overcounting but I don't understand how to answer it using the combinatorics formula $nC2$. For example, the first thing that comes to my mind to approach this problem is to compute the number of ways to choose $2$ people out of $2n$ which is given by $(2n)C_2$. How to proceed from there? If that is not the right approach, why is it so?
Answer: You want $n$ pairs. For the first, choose $2$ out of $2n$, $\binom{2n}{2}$. For the second, choose $2$ out of remaining $2n-2$, $\binom{2n}{2}$. And so on to obtain n pairs $\binom{2n}{2}\binom{2n-2}{2}...\binom{2}{2}=\frac{(2n)!}{2^{n}}$
and do not forget to divide by $n!$ to cancel out permutation of $n$ pairs, $\frac{(2n)!}{2^{n}n!}$
Comment: Thanks, that helps! I'm wondering how is this problem different from the following problem: 'If there are $2n$ people in the room and each person shakes hand with every other person exactly once, how many handshakes take place?'. These two problems are fundamentally the same and yet for the handshake problem we stop at $(2n)C_2$. Why is that?
Comment: @ForumWhiner You can think of it as choosing only one pair; the pair doing handshake.
Comment: Great. Thanks a ton!
Comment: On an unrelated note, I just came to know that the even moments of a Standard normal distribution is also given by $(2n)!/(2^n n!)$. My mind is blown!

Partnerships and counting


How does a water-heater know when to turn on?

Question: Now that it is getting colder, we have noticed that when we get home from work, our water is not that hot.  It was warm at best after a four-day trip.  The water heater is in an unheated basement, next to the furnace.  It's not freezing by any means.  After a shower or some dishes, it heats up fine and we have hot water.
It's a gas water heater.  My mental image of how it works is that the fire shuts off OK when the water heats the desired temp, but doesn't come back on until new cold water is introduced.  I would have guessed that it would be a normal thermostat.  If it is a thermostat, how do we set the temperature that the water heater that the fire come on at?
Or, can someone explain how this works in reality, and offer advice?
Answer: Yes, it's a thermostat, and there is usually a dial on the side of the tank, near the bottom, to adjust the temperature. More than likely, the water feels colder because it is traveling through uninsulated pipes and is losing much of its heat before it reaches the faucet. You can turn up the temperature of the tank, insulate the pipes (they make foam insulation that just slips over the pipe, just be sure to measure the diameter of your pipes so you get the right one), or both.
You should also consider flushing out any sediment from the bottom of the tank if it's been a while since you last did this. All you need to do is hook up a garden hose to the drain at the bottom of the tank (make sure it can take the warm water), run the other end to a floor drain or utility sink, and open the drain on the bottom of the heater. Make sure the water runs clear for a minute or two before closing the drain. To save on the gas, you can set the thermostat to only run the pilot light while you flush the sediment.
Comment: Insulating the pipes is going to be the biggest gain here. Even turning up the temperature won't help completely -- the water in the pipes is going to be the temperature of the basement, and you have to use all of that up before you can get any hot water at all. Even after that, the pipes will still be quite cold and because copper is an excellent heat conductor, they will absorb a lot of the heat from the water.
Comment: Couple of cautions. Be careful not to turn the temp up too high as scaulding skin can occur, 130f to 140 is usually hot enough. Reducing the diameter of the pipe is not a great idea usually. Codes in USA require min of 1/2 inch in most non-transportable residential housing, 3/4 for some longer/second floor feeds. Insulation pipes is always a good idea, but the same problem will exist after a day or two of non use. Unfortunately the only cure is to run the water a minute or two to purge cool water from the pipe and get to the hot stuff.
Comment: +1, also one way to to address the problem is to use pipes as thin as possible so that less water is stored in them and so the cold water from the pipes is used up faster.
Comment: Should have explained, reducing pipe diameter can reduce volume and pressure at the fixture, especially high volume fixtures like shower heads.
Answer: In addition to insulating your pipes you could install a circulating pump to keep hot water flowing through the pipes. We installed a circulating unit under the sink in our kitchen which is far from my water heater. We installed it after replumbing all the way to the kitchen with 3/4" pipe. We now have plenty of pressure in the kitchen, but without the circulator it can take a long time before hot water comes out of the tap.
Circulators can be run automatically, on a timer, or on demand (push a button). They do not have to run all the time. Ours is on a smart switch and only runs when the kitchen or bathroom lights are on. This way we circulate the water only when we are home and need it.
Answer: There is another system I first saw on TOH. A cross-over valve and pump installed in a nearby lavatory (cabinet) hot water faucet (at the shutoff) forces cold water in the hot line into the adjacent cold line and back to the cold water input on the water heater. That increases "faucet" pressure back in the hot water line, producing hot water near the point of use very quickly. A temp sensor detects when cold water has been purged and hot water only is available for use, and causes the pump to turn off and the crossover valve to return the hot water line to normal flow.
There is no pump power consumption other than when hot water is demanded. There is no loss of fuel for heating up the cold hot-water line. There is no loss or expense of keeping hot water circulating. Energy use is strictly during demand only.


Calculus of variation with discontinuous solutions

Question: I'm thinking of the following question:
Consider a function $f: U\rightarrow\mathbb{R}$ where $U=[0,L_1)\cup(L_1,L]$, and an energy functional $$F=\int_{U}\Big (\frac{\mathrm{d}f}{\mathrm{d}x}\Big)^2\mathrm{d}x.$$ The boundary condition is $f(0)=f(L)=0$. Also, assume $f$ has a jump discontinuity at $x=L_1$, i.e., $f(L_1^-)=-f(L_1^+)=-a$, where $a$ is a constant, and $L_1$ is a variable.
The question is: what is the minimum energy?
Simple answer: the Euler-Lagrange equation on $[0,L_1)$ and $(L_1,L]$ is $$\frac{\mathrm{d}^2 f}{\mathrm{d}x^2}=0,$$ Therefore we have the following solution:  $$f(x) =
\begin{cases}
 -\frac{a}{L_1}x,  & \text{x$\in [0,L_1)$} \\
 -\frac{a}{L-L_1}x+\frac{L}{L-L_1}a, & \text{x$\in (L_1,L]$}
\end{cases}$$ Then the energy function $F(L_1)=\frac{a^2}{L_1}+\frac{a^2}{L-L_1}$. Therefore we have the minimum energy $4a^2/L$ when $L_1=L/2$.
Then I tried Fourier series. The Fourier series for the discontinuous solutions are $$  f(x)=\sum_{k=1}^{\infty}\Big[\frac{4a}{k\pi}\cos\frac{k\pi L_1}{L}+\frac{2aL}{(k\pi)^2}\Big(\frac{1}{L-L_1}-\frac{1}{L_1}\Big)\sin\frac{k\pi L_1}{L}\Big]\sin\Big(\frac{k\pi x}{L}\Big),$$ When we substitute this representation into the energy functional, we get infinite energy. In particular,\begin{align}
F(L_1=L/2) &  =\sum_{k=1}^{\infty}\Big(4a\cos\Big(\frac{k\pi}{2}\Big)\Big)^2\cdot\frac{1}{2L}\\
 & =\sum_{k=1}^{\infty}\frac{4a^2}{L}(1+\cos k\pi)~\mathrm{e}^{-\lambda_1 k} & \text{$\lambda_1\to0^+$}\\
 & \to\frac{4a^2}{L}\cdot\frac{1}{\lambda_1}\\
\end{align}
\begin{align}
F(L_1=L/4) & =\sum_{k=1}^{\infty}\Big(4a\cos\Big(\frac{k\pi}{4}\Big)-\frac{16}{3}\frac{a}{k\pi}\sin\Big(\frac{k\pi}{4}\Big)\Big)^2\cdot\frac{1}{2L}\\
 & =\sum_{k=1}^{\infty}\frac{4a^2}{L}\Big(1+\cos \Big(\frac{k\pi}{2}\Big)\Big)~\mathrm{e}^{-\lambda_2 k}\\& +\sum_{k=1}^{\infty}\Big(\frac{128a^2}{9L}\frac{1}{(k\pi)^2}\sin^2\Big(\frac{k\pi}{4}\Big)-\frac{64a^2}{3L}\frac{1}{k\pi}\sin\Big(\frac{k\pi}{4}\Big)\cos\Big(\frac{k\pi}{4}\Big)\Big)& \text{$\lambda_2\to0^+$}\\
 & \to\frac{4a^2}{L}\cdot\frac{1}{\lambda_2}-\frac{4}{3}\cdot\frac{a^2}{L}\\
\end{align}
It is not surprising that the energies are infinite due to the Gibbs phenomenon. However, it is surprising when we take a look at the energy difference: $$F(L_1=L/4)-F(L_1=L/2)=\Big(\frac{4a^2}{L}\cdot\frac{1}{\lambda_2}-\frac{4a^2}{L}\cdot\frac{1}{\lambda_1}\Big)-\frac{4}{3}\cdot\frac{a^2}{L}$$
While when we use $F(L_1)=\frac{a^2}{L_1}+\frac{a^2}{L-L_1}$, we get $F(L_1=L/4)-F(L_1=L/2)=\frac{4}{3}\cdot\frac{a^2}{L}$. My observation is that when we "ignore" the divergent term, the Fourier series give us the correct absolute value for the energy difference but wrong sign (I have checked for all values of $L_1$). I don't feel like it is a coincidence.
To get the correct value of energy difference, I'm guessing that maybe when we use Fourier series, we introduce a vanishing length scale for the jump discontinuity, and this length scale should be the same whatever the value of $L_1$ is, and somehow $\lambda_1$, $\lambda_2$ are related to it so that $\frac{4a^2}{L}\cdot\frac{1}{\lambda_2}-\frac{4a^2}{L}\cdot\frac{1}{\lambda_1}$ may be some finite number.
My question is whether we can use Fourier series to get the correct value of energy difference.
Comment: It seems to me that you should get the right result if you consider the mollified problem with $f(0)=0,f(L_1-\delta)=-a,f(L_1+\delta)=a,f(L)=0$ and then ultimately send $\delta \to 0$. Euler-Lagrange cannot be derived rigorously on the whole interval in this situation, but it can be in the mollified problem (on each of the three subdomains, of course). The only weird thing here is that you are basically looking at the $L^2$ norm of a non-$L^2$ distribution, which is a somewhat weird thing to do in the first place.
Comment: Do you assume $f$ is continuous on $(L_1-\delta, L_1+\delta)$? I'm not quite sure of how to do it in this way. But I think this problem can be done in separate regions. Then I'm wondering if there is a way to "glue" them. I agree that it is weird.
Comment: Yes, the point is to loosely take into account the jump discontinuity and how it should affect the $L^2$ norm of the derivative, even though the derivative in the real problem isn't $L^2$.
Answer: My attempted answer is:
$F(L_1)=\sum_{k=1}^{\infty}\frac{(b_kk\pi)^2}{2L}=F_1(L_1)+F_2(L_1)+F_3(L_1)$
where
$F_1(L_1)=\frac{1}{2L}\cdot\sum_{k=1}^{\infty}\Big(4a\cos\frac{k\pi L_1}{L}\Big)^2$
$F_2(L_1)=\frac{1}{2L}\cdot\sum_{k=1}^{\infty}\Big[\frac{2aL}{k\pi}\Big(\frac{1}{L-L_1}-\frac{1}{L_1}\Big)\sin\frac{k\pi L_1}{L}\Big]^2=\frac{a^2}{L_1}+\frac{a^2}{L-L_1}-\frac{4a^2}{L}$
$F_3(L_1)=\frac{1}{L}\cdot\sum_{k=1}^{\infty}\Big(4a\cos\frac{k\pi L_1}{L}\Big)\cdot\Big[\frac{2aL}{k\pi}\Big(\frac{1}{L-L_1}-\frac{1}{L_1}\Big)\sin\frac{k\pi L_1}{L}\Big]$
To determine the ground state, we may throw away $F_1(L_1)$ and $F_3(L_1)$, because:
(1) $F_1(L_1)$ contains the fictitious core energy, and we can see this by finding the energy density.
$F(y, L_1)=\int_{0}^{y}(\frac{\mathrm{d}f}{\mathrm{d}x})^2\mathrm{d}x=F_1(y, L_1)+F_2(y, L_1)+F_3(y, L_1)$,
where $F(L,L_1)=F(L_1)$, $F_1(L,L_1)=F_1(L_1)$, $F_2(L,L_1)=F_2(L_1)$, and $F_3(L,L_1)=F_3(L_1)$.
After some calculations, we have
$F_{1}(y, L_1)
=\frac{2a^2y}{L^2}\Big(\frac{\cos\frac{2N\pi L_1}{L}-\cos\frac{2(N+1)\pi L_1}{L}}{1-\cos\frac{2\pi L_1}{L}}-1\Big)-\frac{2a^2}{\pi L}\cdot\frac{\sin\frac{\pi y}{L}}{\cos\frac{\pi L_1}{L}-\cos\frac{\pi y}{L}}+\frac{a^2}{\pi L}\cdot\frac{\cos\frac{(2N+1)\pi L_1}{L}}{\sin\frac{\pi L_1}{L}}\ln\Bigg (\frac{1-\cos\frac{\pi (y-L_1)}{L}}{1-\cos\frac{\pi (y+L_1)}{L}}\Bigg)+\frac{4a^2 y}{L^2}\\ \\ +\begin{cases}
0+\frac{2a^2y}{L^2}\Big(1-\frac{\sin\frac{(2N+1)\pi L_1}{L}}{\sin\frac{\pi L_1}{L}}\Big), & \text{if } 0<y<L_1\\
\frac{4(N-1)a^2}{L}+\frac{2a^2(L-y)}{L^2}\Big(-1+\frac{\sin\frac{(2N+1)\pi L_1}{L}}{\sin\frac{\pi L_1}{L}}\Big), & \text{if } L_1<y<L
\end{cases}\\=-\frac{2a^2}{\pi L}\cdot\frac{\sin\frac{\pi y}{L}}{\cos\frac{\pi L_1}{L}-\cos\frac{\pi y}{L}}+\frac{a^2}{\pi L}\cdot\frac{\cos\frac{\pi L_1}{L}}{\sin\frac{\pi L_1}{L}}\ln\Bigg (\frac{1-\cos\frac{\pi (y-L_1)}{L}}{1-\cos\frac{\pi (y+L_1)}{L}}\Bigg)+\frac{4a^2 y}{L^2}+\begin{cases}
0, & \text{if } 0<y<L_1\\
\frac{4(N-1)a^2}{L}, & \text{if } L_1<y<L
\end{cases}$
where $N\to\infty$. And I assume $N\cdot\frac{L_1}{L}\in \mathbb{Z}$, because that seems to make sure the core size for different $L_1$ and finite $N$ are the same (I don't know a better way to justify it). Now we can see $F_1(L,L_1)=F_1(L_1)$ is infinite but independent of $L_1$. Its energy density profile is
$\mathcal{F}_1(y, L_1)=\frac{4a^2}{L^2}+\frac{a^2}{2L^2}\Big(\csc ^2\frac{\pi (y-L_1)}{2L}+\cos\frac{\pi (y-3L_1)}{2L}-\cos\frac{\pi (y+L_1)}{2L}+\cot\frac{\pi L_1}{L}\csc ^2\frac{\pi (y-L_1)}{2L}\csc\frac{\pi (y+L_1)}{2L}+\csc ^2\frac{\pi (y+L_1)}{2L}\Big)$
We can see that the energy jumps to infinity at $x=L_1$, so $F_1(L_1)$ contains the core energy and the constant energy $\frac{4a^2}{L}$. Also, notice that the size of the core becomes very big, and I think it is due to the Gibbs phenomenon.
(2) I think $F_3(L_1)$ can be regarded as the interaction between the fattened core and the function $f$ on $[0,L_1)\cup (L_1,L]$, so it should be thrown away.
I have posted more about it here https://figshare.com/articles/Some_examples_of_calculus_of_variations_of_discontinuous_functions_and_their_implications_pdf/7379861


C# HtmlAgilityPack behaves differently when running project in Visual Studio debugger or when running a built executable

Question: I'm trying to scrap a web site with HtmlAgilityPack library for C#. More specifically, I'm pulling data from a table which contains crypto-exchanges, it's rates and other data. The problem is: when I launch the project in Visual Studio, all the data is always pulled correctly and there are no errors, however, when I build the project and run it as an executable, one of the table columns is 50% of the time empty (I suppose the Xpath just returns an empty node).
What is more, I have spotted such behavior in another project of mine with HtmlAgilityPack. It is similar web scraping, but with another web site where i first need to log in. Each hour I need to re-login to get fresh cookies from the site, but every 10-12 hours the project fails as it can't find the specified html element in the login page. I launch it 1 time in visual studio, it works just alright and i re-launch the executable and it continues normal behavior for another 10-12 hours until it stumbles again.
Below is the code snippet for the first case:
<code>//Getting the web page
HtmlWeb web = new HtmlWeb();
htmlDoc = web.Load("https://www.bestchange.ru/bitcoin-to-bitcoin-bep20.html", proxies[p].ip, proxies[p].port, proxies[p].login, proxies[p].password);

// parse NAME
if (htmlDoc.DocumentNode != null)
{
    xpath = $"//body/div[3]/div[2]/div/div/div[1]/div[2]/div[6]/div[2]/table/tbody/tr{i}/td[2]/div/div/div";
    HtmlAgilityPack.HtmlNode bodyNode = htmlDoc.DocumentNode.SelectSingleNode(xpath);
    if (bodyNode != null)
    {
        exchange = bodyNode.InnerHtml.ToString();
        Console.WriteLine("Name: " + exchange);
    }
}
//parse PRICE
//This is what gets screwed
if (htmlDoc.DocumentNode != null)
{
    xpath = $"//body/div[3]/div[2]/div/div/div[1]/div[2]/div[6]/div[2]/table/tbody/tr{i}/td[3]/div[1]/text()";
    HtmlAgilityPack.HtmlNode bodyNode = htmlDoc.DocumentNode.SelectSingleNode(xpath);
    if (bodyNode != null)
    {
        Double.TryParse(bodyNode.InnerHtml, out price);
        Console.WriteLine("Price: " + price);
    }
}
</code>
So the price is what is usually pulled wrong (as 0).
I tried to run it on different OS - mac and windows, code it again on another platform, but the result is always the same.
Comment: Does the website return the same htmlcode when running in VS and as executable?
Comment: Please provide enough code so others can better understand or reproduce the problem.
Comment: @cpt.oneeye I actually compared them and they are indeed different, which I wouldn't expect. Why can they be different then?
Comment: @YaroslavKolyada This probably happens on the server which is serving the html. Maybe there is another UserAgent or something else is different at clientside which the website on the server is checking. As a result it sends different html back.
Comment: @cpt.oneeye Thanks for the answer! Any idea how I can fix that?
Comment: @YaroslavKolyada I didn't really worked a lot with HtmlAgilityPack. You could try to make a local website. You call this website with your crawler in VS and in the executable. In your website you try to get some infos how the client looks like and if there are differences (maybe the useragent is different, or there are problems with keeping the login). Maybe there are settings you can define in HtmlAgilityPack so that it is more similar to the VS-Version.
Comment: @YaroslavKolyada Or you check if value is missing. If it does you make a new request until it works (you said it only happens in 50% of the times).
Answer: I finally figured out the problem, it has nothing to do with HtmlAilityPack, instead it was a culture issue. Somehow my Double.TryParse Method was considering doubles only with "," instead of "." (and was outputting the same). I soled it by setting the default thread culture to "en-Us".


Why do people use console-based file managers?

Question: To keep this question specific and on-topic, let me preface this by stating my intent is not to go into pros and cons of using one type of file manager over another.  However, it is clear a significant group of people use console-based file managers, such as Midnight Commander or Ranger.  I'd like to know their reasons for doing so.
Answer: There may be several reasons:

They do not depend on X Window, thus can be used even if there are no desktop environment such as a server.
They are fast and consume less resources (also say above), can be good for old or slow computers.
They can be powerful and flexible, though you need to learn a bit more than Nautilus.
Answer: I'm a Midnight Commander addict, so let me add a few more points:

I find dual pane layout to be very efficient for file operations
Console keyboard managers are more keyboard-friendly, i.e. it is possible to navigate/select files/perform file operations without using mouse. When working in console, switching to mouse is a hindrance
Console keyboard managers are... well, console-friendly, i.e. it is easy to navigate the filesystem and issue commands in console at the same time. Or even assemble commands from file names you see in mc etc.
Muscular memory. Midnight Commander's commands are largely the same as Norton Commander used to have ages ago.


How to loop jQuery animate() in .each() function

Question: I am trying to have several balls make a random displacement in a given div. The code to create and style the balls is almost entirely in jQuery and it works, the problem is trying to make .animate() loop all the time, having the balls moving around in a random direction/speed in each iteration.
The first move works, but not the rest. Here is the link:  https://jsfiddle.net/xpvt214o/19871/
  // Some random colors
  var colors = ["#3CC157", "#2AA7FF", "#1B1B1B", "#FCBC0F", "#F85F36"];
  var numBalls = 50;
  var balls = [];

  function makeNewPosition(){
    // Get viewport dimensions (remove the dimension of the div)
    var h = $('.front-bg').height();
    var w = $('.front-bg').width();
    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);
    return [nh,nw];
  }

  for (i = 0; i < numBalls; i++) {
   $('.front-bg').append('

');
   $('.ball').each(function(index, el) {
    $(this).css('backgroundColor', colors[Math.floor(Math.random() * colors.length)]);
    $(this).css('left', Math.floor(Math.random() * 100) + '%');
    $(this).css('top', Math.floor(Math.random() * 100) + '%');
    $(this).css('transform', 'scale(' + Math.random() + ')');
    var WH = Math.floor(Math.random() * 45) + 4;
    $(this).css({
      width:  WH + 'px',
      height: WH + 'px'
    });
  });
 }

  $('.ball').each(function() {
    var newq = makeNewPosition();
    $(this).animate({
    top: newq[0],
    left: newq[1],
    easing: 'easeInOutQuint',
    complete: function() {
      $(this).animate({
      top: newq[0],
      left: newq[1],
      easing: 'easeInOutQuint',
      }, Math.random() * 10000)
    }
    }, Math.random() * 10000);
  });

Answer: Your answer lies in the statement:

The first move works, but not the rest

You just need to put the moving logic to be repeated in repeating function at certain interval, like setInterval(), or setTimeout()

  // Some random colors
  var colors = ["#3CC157", "#2AA7FF", "#1B1B1B", "#FCBC0F", "#F85F36"];
  var numBalls = 50;
  var balls = [];

  function makeNewPosition(){
    // Get viewport dimensions (remove the dimension of the div)
    var h = $('.front-bg').height();
    var w = $('.front-bg').width();
    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);
    return [nh,nw];
  }

  for (i = 0; i < numBalls; i++) {
   $('.front-bg').append('

');
   $('.ball').each(function(index, el) {
    $(this).css('backgroundColor', colors[Math.floor(Math.random() * colors.length)]);
    $(this).css('left', Math.floor(Math.random() * 100) + '%');
    $(this).css('top', Math.floor(Math.random() * 100) + '%');
    $(this).css('transform', 'scale(' + Math.random() + ')');
    var WH = Math.floor(Math.random() * 45) + 4;
    $(this).css({
      width:  WH + 'px',
      height: WH + 'px'
    });
  });
 }

var first = true;
setInterval(function() {
  $('.ball').each(function() {
    var newq = makeNewPosition();
    $(this).animate({
    top: newq[0],
    left: newq[1],
    easing: 'easeInOutQuint',
    complete: function() {
      $(this).animate({
      top: newq[0],
      left: newq[1],
      easing: 'easeInOutQuint',
      }, Math.random() * 10000)
    }
    }, Math.random() * 10000);
  });
}, (first?0 : 3000));
first = false;
.ball {
  position: absolute;
  border-radius: 100%;
  opacity: 0.7;
}
.front-bg {
  min-height: 400px;
}
#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}


Verifying all text boxes are numbers in JQuery

Question: $('#save').click(function(){
    ($('input[type=text]').each(function () {
        if (isNaN($(this).val())) {
            alert("Some of your values were not entered correctly.");
            return 0;
        }
    });
});

I can't figure out why this isn't working. Any suggestions?
Edit: Sorry for the misleading title--I need to make sure the text boxes contain ONLY numbers.
Comment: Yes: give us any error messages or warnings that you may be getting. Also, in `click(function(){(`, what is the last `(` and its matching `)` in `});` supposed to be doing? I believe those are not supposed to be there.
Comment: They must contain only numbers, or they can contain the number anywhere in the text? Write some sample texts, that's how you can explain regex.
Answer: The isNaN function checks for a specific value called NaN[MDN], which is the result of trying to perform arithmetic operations on non-number objects. It doesn't check if a string is a number. How about a regular expression?
if (!/^\d+$/.test($(this).val())) {
    // Not a number...
}

The above will accept positive integers. If you need to accept negative or floating point numbers, change the regular expression to:
/^-?\d+$/         <-- Accepts positive and negative integers.
/^\d+(\.\d+)?$/   <-- Accepts positive integers and floating point numbers
/^-?\d+(\.\d+)?$/ <-- Accepts positive and negative integers and fpn.

Also, if you return 0 from within each, that stops the loop, but that doesn't prevent the click event from continuing on. You have invalid data, you need to call event.preventDefault() to halt the click event. Something like this will do:
$('#save').click(function(event){
    var badInputs = $('input:text').filter(function() {
        return !$(this).val().match(/^\d+$/);
    };
    if (badInputs.length) {
        alert('Some of your values were not entered correctly.');
        event.preventDefault();
    }
});

Working example: http://jsfiddle.net/FishBasketGordo/ER5Vj/
Comment: Do not use `:text`, because it will be handled by Sizzle. Besides your logic is wrong.
Comment: Corrected the logic mistake. I used the selector `input:text` because it will get inputs without a `type` attribute specified, which are rendered as textboxes.
Comment: @FishBasketGordo: `input[type=text]` elements do not render as checkboxes. I don't get what you are talking about. Also, there is no need to iterate over all elements, the OP had it right with the breaking of the loop.
Comment: @Shef I'm not sure what *you* are talking about. I didn't say anything about checkboxes. As far as not iterating over all the elements, you're right, but in the original loop, the click handler would still proceed with a postback or what have you, when you really want it to stop right there so the user can correct the invalid data. If it means that much to you, set a flag before prematurely exiting the original loop and return false from the handler if it's set. The question is: what are you going to do with that extra half-millisecond you just saved?
Comment: @FishBasketGordo: It's not about the half-millisecond, it's about teaching the right practice. I was talking about the Sizzle engine. An input element without a `type` attribute should not be used in the markup. Anyways, the OP makes the choice so it's up to him to decide what to take on and what not. Over and out. :)
Answer: in this topic a lot of dicussions about checking the numbers in JS. I hope it will help.


Crystal Report Windows Forms Viewer : Object Reference not set to an instance on an object

Question: I am working with a Crystal Reports in Vb.Net Forms application. A huge report that consists of 10-12 Sub-Reports,there are many formulas used in this report, sometimes this report shows "Object Reference not set to an instance on an object" I can't figure out, I have handled exceptions as well. When I click to "Next Page" button it shows below dialog.

I can't figure out why its happening.
read many blogs, some says, its formula error, some says, "Mouse Move" error.
Below is the code I have added, i will check now
<code> Private Sub CrystalReportViewer1_HandleException(ByVal source As _
Object, ByVal e As CrystalDecisions.Windows.Forms.ExceptionEventArgs) _
Handles CrystalReportViewer1.HandleException

'Label1.Text = e.Exception.ToString();
'Here I will trap.

End Sub
</code>
Below is the stack trace I have found by applying above code for exception:
<code>Source:CrystalDecisions.CrystalReports.Engine
Message:Object reference not set to an instance of an object.
ST:   at CrystalDecisions.CrystalReports.Engine.ReportDocument.get_IsLoaded()
at CrystalDecisions.ReportSource.NonHTTPCachedReportSource.GetReport(RequestContext  context, Boolean bAddToCacheWhenCreated)
at CrystalDecisions.ReportSource.LocalReportSourceBase.GetPage(PageRequestContext pageReqContext)
at CrystalDecisions.Windows.Forms.MainReportDocument.GetPage(PageRequestContext context)
</code>
Comment: It should be something to do with the data you're passing. When the data is being manipulated through the CR formulas, it ends up with exception. Try checking the values being passed and for every value that can be NULL,do add some vlaidations
Comment: As soon as I Press Mouse Down or Up key, It pop-up this MessageBox.
Comment: meaning the formula is not being able to execute!
Comment: There was other thing I found today which caused that dialog box to appear, I set my system on standby by left opened that report in report viewer, when I came and hit mouse key, the exception box appeared, seems the object or viewer have lost the reference. anyone could suggest ?
Comment: @Nadeem_MK : Sir, this error I have received from Log. That machine running Windows 7- 32-bit OS.
Answer: I was looking a solution for this,
anyway i found the issue with my problem and so i am posting it here.
My report had a subreport and the its links where not set properly from the main report. In this scenario when i try to set only the parameters of main report and try to load the report, i was getting this object reference error.
So either link the subreport parameters to main report parameter or may be you can try setting the sub report parameters too. I have set the subreport parameters to link to the main report parameters and it works.


Problem with firebase auth providers (HTML and JS)

Question: Hello i have problem to had 2 auth providers and requireDisplayName.
My code :
ui.start('#firebaseui-auth-container', {
 signInOptions: [
   {
     provider: firebase.auth.EmailAuthProvider.PROVIDER_ID, firebase.auth.GoogleAuthProvider.PROVIDER_ID,
     requireDisplayName: false
   }
 ]
});

Thank to help me
Answer: Solved :
ui.start('#firebaseui-auth-container', {
  signInOptions: [
    {
      provider: firebase.auth.EmailAuthProvider.PROVIDER_ID,
      requireDisplayName: false
    },
            firebase.auth.GoogleAuthProvider.PROVIDER_ID,
  ]
});

I'm so dumb xD


How do I find my cars in GTA Online after I accidentally downgraded to a smaller garage?

Question: So I feel really stupid right now, but I recently owned a 6-car garage, and I wanted 2 more cars, but mine was full. I simply thought, "Oh, I'll just buy another 2-car garage and put them in there." (I use an old TV, so reading things is a little difficult, and I mainly skip over things.)
After I bought a 2-car garage, I realized my other one was gone. I am not allowed to buy it back anymore, even though I have enough money. Some cars transferred but not all, and some of the ones that I lost are worth a lot of money.
I can still use my old cars in races, but I can't find them anywhere else. I've searched for answers to this problem, but no one seems to have made the same lame mistake as me.
Comment: I think you mean GTA Online.
Answer:
I use an old tv so reading things are a little difficult and I mainly skip over things.

You should probably stop doing that :)

I am not allowed to buy it back anymore even though I have enough money. Some cars transferred but not all, some that I lost are worth a lot of money.

You haven't lost any cars, you just can't access more than what fits in your current garage. If you buy another 6-car or 10-car garage, you will get access to all the cars again.
Answer: If you transfer from a 10-car garage, for example, down to a six-car garage, you will need to put those six cars into slots 1-6 first. If you forget, go back and buy a 10-car garage, then rearrange. Your cars should still be there.
Answer: The user who posted this Reddit /r/GTAOnline post had a similar predicament to yours: I accidentally hurriedly bought a property and lost a full 10 car garage.
Another user provided a solution that the original poster confirmed resolved their issue (emphasis mine):

You didn't really lose anything. The cars are simply in storage now. They can be requested with the mechanic and then put into empty slots in other garages.


GridView showing double on postback

Question: I have a gridview that is supposed to refresh using
<code>        gridView.DataSource = null;
        gridView.DataBind();
</code>
before binding it to the updated datasource (which is a DataTable).
and then
<code>gridView.DataSource = newDataTable;
gridView.DataBind();
</code>
The problem is that it won't clear and from time to time I get a table on top of another table (the one on top is the updated one, the bottom one is the data before the 2nd DataBind).
Appreciate your help!
Comment: guess you could 'force' the "clear" operation by removing all the rows in the gridview (while rows.count > 0, deleterow(0) or whatever) but if it's intermittent, i wonder if the 'clear' code isn't getting called in some paths
Answer: I usually hook up to the data-source updated or inserted event and then call the DataBind method directly after the Insert and Update has executed.
You can also try adding this before you reload the grid, although the databind should refresh it:
gridView.Dispose();
Answer: <code>        gv_BCDashboard.Columns.Clear(); -- Clearing the Columns and rebinding.
        foreach (DataColumn col in bcDashboard.Columns)
        {
            //Declare the bound field and allocate memory for the bound field.
            BoundField bfield = new BoundField();

            //Initalize the DataField value.
            bfield.DataField = col.ColumnName;

            //Initialize the HeaderText field value.
            bfield.HeaderText = col.ColumnName;

            //Add the newly created bound field to the GridView.
            gv_BCDashboard.Columns.Add(bfield);
        }

        gv_BCDashboard.DataSource = bcDashboard;
        gv_BCDashboard.DataBind();

    }
</code>

GridView showing double on postback


regular expression with variable-length zero-width lookbehind in Java

Question: I understand that Java does not support variable-length zero-width lookbehinds, but is there an efficient and effective way to mimic the desired behaviour?
The text that I'm applying the regex to is something like:
blah words blah [tag platform="platform1, platform5" future]Blah Blah blah[/tag] blah more words

In the opening tag, there can be any number of platforms in the list, in any order, and there are a finite number of possible values. The desired output is to get the text between the tags:
Blah Blah blah

This is what I want to do to represent the variable list of platforms:
(?<=\\[tag platform=\\\\\".*?\\\\\" future\\]).*?(?=\\[/tag\\])

But of course it throws an exception with the message Look-behind group does not have an obvious maximum length.
I've thought of using a regex to get the entire string including the tags (which is easy), then parse the string. But this seems to be a bit too specific and I'd like a more bulletproof solution.
Comment: Can you add *the expected output* as well?. Side note : For all future regex questions, please add expected output explicitly rather than *stating what is expected* :)
Comment: Why not just use a simpler regex such as (https://regex101.com/r/S1t2qA/1) or something similar and then extract group 2? Java is fully capable of extracting a group out of a match. Perhaps it is preferable to making the regex overly complicated?
Comment: @TheLostMind Thank you for the note, I added the expected output.
Answer: This should work for you. No need for a look-behind
Just "capture" the necessary part and replace the entire string (or something else)
public static void main(String[] args) {
    String s = "blah words blah [tag platform=\"platform1, platform5\" future]Blah Blah blah[/tag] blah more words";
    s = s.replaceAll(".*?\\[tag.*?\\](.*?)(?=\\[.*).*", "$1");
    System.out.println(s);
}

O/P :
Blah Blah blah

Comment: @TheLostMind thanks for this, it's very simple and does the job. I actually wasn't aware that you could access each group after the fact.
Comment: This will not catch `[` inside the tag and also will match even if the closing tag is not `[/tag]`. https://regex101.com/r/S1t2qA/2
Comment: @jrook - Yes, it doesn't. It can be fixed. Not sure if the OP needs it though.
Answer: You can use Non-capturing groups to include things in a match, but not a capture
Just remember to pull from the first capture group, instead of the entire match
(?:\[tag platform=\".*?\" future\])(.*?)(?:\[\/tag\])

On Regex101
Comment: The question states: *there can be any number of platforms in the list* meaning 0 is also possible which will cause this regex to fail
Comment: I Updated the the link, regex still seems to works. Good thought though, I hadn't considered that
Comment: @doom87er Thanks for your response -- I learned about non-capturing groups!


Why is my Heroku push rejected?

Question: I am working through chapter 1 of Hartl's Rails 4.0 tutorial, and I'm stuck on Section 1.4.2, which is to push a black app into GitHub and Heroku.
I tried typing git push heroku master, but I get an error message, similar to a previous question on StackOverFlow:

Heroku push rejected - Hartl's Rails 3.2 tutorial
Heroku push rejected, railties dependency conflict? Ruby on Rails Tutorial Section 1.4.2

It's probably the same but I don't even realize it:
-----> Ruby/Rails app detected
-----> Installing dependencies using
       Running: bundle install --without development:test --path vendor/bundle --binstubs vendor/bundle/bin --deployment
       /usr/bin/env: ruby1.9.1: No such file or directory
 !
 !     Failed to install gems via Bundler.
 !
 !     Heroku push rejected, failed to compile Ruby/Rails app

Here is the Gemfile I used:
source 'https://rubygems.org'
ruby '1.9.3'

gem 'rails', '4.0.0.rc1'

group :development do
  gem 'sqlite3', '1.3.7'
end

gem 'sass-rails', '4.0.0.rc1'
gem 'uglifier', '2.1.1'
gem 'coffee-rails', '4.0.0'
gem 'jquery-rails', '2.2.1'
gem 'turbolinks', '1.1.1'
gem 'jbuilder', '1.0.2'

group :doc do
  gem 'sdoc', '0.3.20', require: false
end

group :production do
  gem 'pg', '0.15.1'
end

UPDATE: The main error seems to be /usr/bin/env: ruby1.9.1: No such file or directory  Is that folder on the Heroku machine or my home computer ?
I tried removing the line ruby '1.9.3' from my .gitignore but it still returns this message.
Comment: That should not be an issue, I've used ruby 1.9.3 and 2.0.0 using the same technique.
Comment: Your Gemfile specifies Ruby 1.9.3, but from the message returned by Heroku it looks like it's using Ruby 1.9.1. Not sure if that's related to the problem
Answer: First, Remove ruby 1.9.3 from the Gemfile. You don't need it and may be the cause of your problem. Start of your Gemfile should look like this:
source 'https://rubygems.org'

gem 'rails', '4.0.0.rc1'

group :development do
  gem 'sqlite3', '1.3.7'
end

etc........

Also, make sure you run
bundle install --without production

since you are using sqlite3 in :development and postgresql in :production
Answer: I had a similar problem. The issue is that Bundler is generating stubs. Rails 4 apps do not store stubs in the app's bin/ directory. In order to fix this problem you need to use the following commands:
$ bundle config --delete bin

Then you need to update the bin directory to use the new Rails 4 executables
$ rake rails:update:bin

Then add the new bin/ directory to your version control using:
$ git add bin

Commit the changes and push your code to Heroku
Answer: i had the same problem and the problem was that i didn't chose the version of ruby that i want to use, so i did the following:
$rvm list
   ruby-1.9.3-p392 [ i686 ]
   ruby-2.0.0-p247 [ i686 ]

$rvm use  ruby-1.9.3-p392

$rvm list
    =>   ruby-1.9.3-p392 [ i686 ]
    ruby-2.0.0-p247 [ i686 ]

Why is my Heroku push rejected?


Can't interpret prediction with neural network use

Question: I'm trying to use TensorFlow in python, to make some prediction with cryptocurrency data. The problem is that the output of the prediction is like a 0.1-0.9 number whereas the cryptocurrency data should be a 10000-10100 format, and I don't find a solution to convert the 0.* number to the real one.
I've try to create a ratio, with substrat max - min from predicted values, and max-min from tested data, and divide to have a ratio but when I multiply this ratio with prediction there is a big rate of error ( found a 14000 number instead of a 10000 one )
Here some code :
train_start = 0
train_end = int(np.floor(0.7*n))
test_start = train_end
test_end = n
data_train = data[np.arange(train_start, train_end), :]
data_test = data[np.arange(test_start, test_end), :]

Scale data:

from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
data_train = scaler.fit_transform(data_train)
data_test = scaler.transform(data_test)

Build X and y:

X_train = data_train[:, 1:]
y_train = data_train[:, 0]
X_test = data_test[:, 1:]
y_test = data_test[:, 0]

.
.
.

n_data = 10
n_neurons_1 = 1024
n_neurons_2 = 512
n_neurons_3 = 256
n_neurons_4 = 128
n_target = 1
X = tf.compat.v1.placeholder(dtype=tf.compat.v1.float32, shape=[None, n_data])
Y = tf.compat.v1.placeholder(dtype=tf.compat.v1.float32, shape=[None])

Hidden layer
..
Output layer (must be transposed)
..
Cost function
..
Optimizer
..

Make Session:

sess = tf.compat.v1.Session()

Run initializer:

sess.run(tf.compat.v1.global_variables_initializer())

Setup interactive plot:

plt.ion()
fig = plt.figure()
ax1 = fig.add_subplot(111)
line1, = ax1.plot(y_test)
line2, = ax1.plot(y_test*0.5)
plt.show()

epochs = 10
batch_size = 256
for e in range(epochs):

# Shuffle training data
shuffle_indices = np.random.permutation(np.arange(len(y_train)))
X_train = X_train[shuffle_indices]
y_train = y_train[shuffle_indices]

# Minibatch training
for i in range(0, len(y_train) // batch_size):
    start = i * batch_size
    batch_x = X_train[start:start + batch_size]
    batch_y = y_train[start:start + batch_size]
    # Run optimizer with batch
    sess.run(opt, feed_dict={X: batch_x, Y: batch_y})

    # Show progress
    if np.mod(i, 5) == 0:
        # Prediction
        pred = sess.run(out, feed_dict={X: X_test})

        #This pred var is the output of the prediction

I persiste my result in a file and this is what its looks like :
2019-08-21 06-AM;15310.444858356934;0.50021994;
2019-08-21 12-PM;14287.717187390663;0.46680558;
2019-08-21 06-PM;14104.63871795706;0.46082407;
For example, the last prediction is 0,46 but when I try to convert it I found 14104 whereas it should be nearer a 10000 value
Does anyone have an idea how to convert those predictions?
Thanks!
Answer: You will have to make use of inverse_transform of MinMaxScaler to convert back the output you are getting in range of 0-1.
You have not given your model, but I believe you are making use of regression task with few dense layers. You will have to keep minimizing your loss. If you are using mean squared error, the larger the loss, more is the likelihood your output will be far away from the desired set of results.
Even after your loss is a small number and the result is coming good for train samples, but the prediction is bad for test dataset, you may have to consider increasing your train dataset so that more possibilities are covered. If that is not possible, consider reducing the number of neurons in your neural network so that it stops over-fitting.
You can do some postprocessing to restrict the output to some desired range.


javascript: How to stop ios app scroll top on focus input text field

Question: I am using cordova to develop a hybrid mobile application. It is working fine in android but in ios on focus of input text field the application is scrolling up and on clicking out the entire . application zooms in and comes back to normal size. this is my serious issue which am not able to solve.
request you to watch this video to clearly understand my issue: https://youtu.be/aLhADdaL_08
Please provide me a solution
thanks
Comment: refer https://jmsliu.com/3461/set-uiwebview-content-not-to-scroll-when-keyboard-is-shown.html
Comment: I added the javascript content but still it is not working @SuryaSubenthiran
Comment: this is actually a bug. ios automatically tries to adjust the input whenever keyboard appears. There are some workaround to resolve this bug. like mentioned in the above link disabling the native webview scrolling. you will have to add native ios code to disable scrolling.
Comment: @SuryaSubenthiran thank you bro.. i will try it but the problem is i dnt knw native code.. so looking for solution in javascript.
Answer: Hey there here is a link to the config settings config.xml Cordova
These two settings should help you out:
<preference name="DisallowOverscroll" value="true" />
<preference name="EnableViewportScale" value="false" />

place them somewhere inbetween your <widget></widget> tags.
Note that you have to rebuild your app if you change config files!
Comment: please watch this https://youtu.be/aLhADdaL_08 @kevinSpaceyIsKeyserSöze


Selenium (python) : finding an element relative to a previously-found one

Question: I'm web-scrapping a page with the selenium module in python. I've looked for a certain element, and found it, like this:
drv = webdriver.Firefox(options=opt)
drv.get(url)
x = drv.find_element('xpath', './/div[@class="col-lg-2 col-md-3 col-xs-6 guest-item "]')

Now I'd like to do a search for another element, using an XPath expression, but only inside the sub-tree that is below the x element, not across the entire document.
How can I specify that the XPath search should start from the x element and not from the document's root ?
Answer: You can simply call the find_element method from the element x. For instance:
x.find_element('xpath', './/h2')

Comment: That was soo obvious :-( Why don't the docs show anything other than `driver.find_element` ?


How to prove $a^3+b^3+c^3+d^3+3\left(a+b+c+d\right) \geq 14+2abcd$ when $a^2+b^2+c^2+d^2=4$

Question: This is a problem from AoPS I can't solve:
Let $a,b,c,d\geq0$ with $a^2+b^2+c^2+d^2=4$. How can I prove: $$a^3+b^3+c^3+d^3+3\left(a+b+c+d\right) \geq 14+2abcd$$
My attempt:
I try setting $a=2\cos(x), b=2\sin(x)\cos(y), c=2\sin(x)\sin(y)\cos(z),d=\sin(x)\sin(y)\sin(z)$ for $x,y,z\in[0,\frac\pi2[$.
Then indeed $a^2+b^2+c^2+d^2=4$ but I would have to prove $$2 \sin (x) \sin (y) \left(4 \sin ^2(x) \sin ^2(y) \sin ^3(z)+4 \sin ^2(x) \sin ^2(y)
   \cos ^3(z)+3 \sin (z)+3 \cos (z)\right)+\cos (x) \left(6-8 \sin ^3(x) \sin (y)
   \sin (2 y) \sin (2 z)\right)+8 \sin ^3(x) \cos ^3(y)+6 \sin (x) \cos (y)+8 \cos
   ^3(x)-14\geq0$$ which I don't know how to do.
Also I tried using Lagrange but the stationary points have no closed form.
Answer: We need to prove that:
$$4\sum_{cyc}a^3+3\sum_{cyc}a^2\sum_{cyc}a\geq\frac{7}{2}\left(\sum_{cyc}a^2\right)^2+8abcd$$ or
$$\sum_{cyc}a^2\left(4\sum_{cyc}a^3+3\sum_{cyc}a^2\sum_{cyc}a\right)^2\geq\left(7\left(\sum_{cyc}a^2\right)^2+16abcd\right)^2.$$
Now, let $a=\min\{a,b,c,d\}$, $b=a+u,$ $c=a+v$ and $d=a+w.$
Thus, $$\frac{1}{2}\left(\sum_{cyc}a^2\left(4\sum_{cyc}a^3+3\sum_{cyc}a^2\sum_{cyc}a\right)^2-\left(7\left(\sum_{cyc}a^2\right)^2+16abcd\right)^2\right)=$$
$$=512\sum_{cyc}(3u^2-2uv)a^6+128\sum_{cyc}\left(19u^3+5u^2v+5u^2w-\frac{34}{3}uvw\right)a^5+$$
$$+64\sum_{cyc}(31u^4+22u^3v+u^3w+22u^2v^2-30u^2vw)a^4+$$
$$+4\sum_{cyc}(263u^5+223u^4v+223u^4w+282u^3v^2+282u^3w^2-24u^3vw-142u^2v^2w)a^3+$$
$$+4\sum_{sym}\left(40.5u^6+101u^5v+57u^4v^2+85u^3v^3+12.5u^4vw+54u^3v^2w-\frac{76}{3}u^2v^2w^2\right)a^2+$$
$$+\sum_{sym}(31.5u^7+69u^6v+51u^5v^2+89u^4v^3+73u^5vw-33u^4v^2w+162u^3v^3w-39u^3v^2w^2)a+$$
$$+\sum_{sym}(21u^7v-48u^6v^2+79u^5v^3-48u^4v^4+4.5u^6vw+51u^5v^2w+39u^4v^3w-108u^4v^2w^2+59u^3v^3w^2).$$
Now, all coefficients before $a^k$ for any $k\in\{1,2,3,4,5,6\}$ are non-negative by Muirhead.
Also, by Muirhead and AM-GM we obtain:
$$\sum_{sym}(21u^7v-48u^6v^2+79u^5v^3-48u^4v^4+4.5u^6vw+51u^5v^2w+39u^4v^3w-108u^4v^2w^2+59u^3v^3w^2)$$
$$\geq\sum_{sym}(21u^7v-48u^6v^2+31u^5v^3+4.5u^6vw+51u^5v^2w+39u^4v^3w-108u^4v^2w^2+59u^3v^3w^2)\geq$$
$$\geq uvw\sum_{sym}(4.5u^5+51u^4v+39u^3v^2-108u^3vw+59u^2v^2w)\geq$$
$$\geq uvw\sum_{sym}(51u^4w-108u^3vw+59u^2v^2w)\geq$$
$$\geq uvw\sum_{sym}(2\sqrt{51\cdot59u^4w\cdot u^2v^2w}-108u^3vw)=2u^4v^2w^2(\sqrt{51\cdot59}-54)\geq0$$
and we are done!
Comment: Due to symmetry, assume that $a \le b \le c \le d$. Let $b=a+u, c = a+u+v, d=a+u+v+w$ for $u, v, w\ge 0$. Then all coefficients of $f(a, u, v, w)$ are non-negative.


"boot" low disk space

Question: My Ubuntu version is 16.04 LTS. I have been getting "Low Disk Space" message. An example of the message I get: "The volume "boot" has only 3.1 MB disk space remaining"
Things I have tried when I get such a message:
1) Deleted old kernels using sudo apt-get purge linux-image--generic
2) Cleaned up various directories
3) sudo apt-get autoremove
None of these have helped. In fact, running 1), 3) made my system fail to boot. Every time my system fails to boot, I re-install an old working image of my system. After a few weeks, I once again get the Low disk space error.
What can I do to prevent /boot running into low disk space?
I'd appreciate your help.
P.S: I am not a sys admin so I'd appreciate more context in your answers. Thank you!
Edit 1:
I had previously tried the solutions provided in the suggested links. Running 'sudo apt-get purge' made my system failed to boot.
Edit 2:
I am running sudo apt-get autoremove preemptively. That seems to keep the problem under control. Are there any other ways to get rid of the boot low disk space issue instead of running sudo apt-get autoremove preemptively every few days/weeks?
Comment: Please edit your question and add `df -h` output
Comment: /dev/sdb2                    473M  146M  303M  33% /boot
Comment: I am running sudo apt-get autoremove pre-emptively. That seems to keep the problem under control.
Answer: When running sudo apt update && sudo apt upgrade the system will tell you if there are automatic installed package that can be removed by running sudo apt autoremove .. when that happens, run the autoremove, this will , among other thing, remove old kernels from /boot

"boot" low disk space


How can I put games on a USB stick for a LAN party?

Question: Soon, I'll be attending a LAN party. There will be a couple of laptops, of which some have Windows 7 installed, and some Ubuntu 12.04. None of these laptops are connected to the internet.
I want to play 0 A.D. there.
To get these games installed on the Windows laptops, I'll give my friends a USB stick with the .exe for the latest version of 0 A.D.
I'd like to be able to install 0 A.D. on the Ubuntu laptops, too. However, the current version of 0 A.D. is only installable via a PPA, and I'm not sure about how to put this PPA on a USB stick. I'm also not sure about how possible dependencies can be resolved over there.
So, how can I install 0 A.D. on a Ubuntu 12.04 laptop that isn't connected to the internet?
Answer: Just go here and download the .deb files.
Comment: Does this .deb file contain all the necessary dependencies?


Swift command line program with multiple files in VSCode on Mac

Question: I want to run a full fledged Swift command line program with multiple classes and multiple files, on Visual Studio Code. I'm using Macbook Air macOS Big Sur v11.2
I have setup VSCode from this tutorial. I am able to run single file swift program but when I try to create new class in another file (in same directory/folder), it doesn't recognize. refer the screenshots:

Consider, in Xcode similar to New project -> macOS -> command line tool. there we can have multiple files and we can define multiple classes in different files and still inherit or create object of those classes in main.swift file.
I'm pretty sure it's possible in VSCode too. May be we just need to structure the code and have a configuration. that is what i am looking for.
just similar to this question but seems no experienced people bother to answer :/
ps- I'm new to swift and using VSCode. but instead of using xCode (12 GB of installation and 25 GB occupied storage just for few command line programs), I want to use VSCode.
Comment: Did you try to work with `swift build` and a `Package.swift`file
Comment: Previously I thought the same but don't know how to make `package.swift` file and use `swift build`. can you guide me or redirect me towards any specific link. It'd be much helpful.
Answer: Just as a small hint, consider the following file structure:
./Package.swift
./src
./src/classA.swift
./src/main.swift

In src, your source files reside
Package.swift is the so-called manifest file (see below)

Then, you can build your project with
swift build

which will create the executable in ./.build/debug/testCli
The manifest
Here an example Package.swift file. You might also want to check the official Package Description documentation
// swift-tools-version:5.1
import PackageDescription

let package = Package(name: "testPackage", products: [
    .executable(name: "testCli", targets: ["testCli"])
], targets: [
    .target(name: "testCli",
            path: "src"
    )
])

Comment: I'm getting error: `no such module 'PackageDescription'`. I looked into the error and found this link: https://forums.swift.org/t/no-such-module-packagedescription-sourcekitd/29406/2
unfortunately I'm unable to understand how to change the config
Comment: Strange, haven't seen this. You might wanna try something like this here: https://forums.swift.org/t/command-line-build-fails-with-mainfest-parse-error-no-such-module-packagedescription/35298/7
Comment: appreciate your help, but it seems that the link and setup that is been suggested are above my understanding level :/ I need to educate myself more towards swift builds and toolchains. and also seems like my vscode has broken setup. I'm frustrated..
Comment: I'm upvoting this answer as it helps, but still I'm unable to setup so keeping the thread open.


Where do I assign a variable in order for it to be used in a function (inside a class)?

Question: I'm creating a class using tkinter that lets you input multiple product's information, and I've got everything else down except for changing the entry fields to set values for the other products.
I'm putting the product changeover process into a function called saveVars which saves the entered information to the specific product variable, and then clears the entry fields, and switches the saveVars to be performed on the second product variable.
    i = 1

    def saveVars(i):
        if i == 1:
            product1.productName = self.prodName.get()
            product1.productID = self.prodID.get()
            product1.productSize = self.prodSize.get()
            product1.productPrice = self.prodPrice.get()
            product1.productQuant = self.quantity.get()
        elif i == 2:
            product2.productName = self.prodName.get()
            product2.productName = self.prodID.get()
            product2.productSize = self.prodSize.get()
            product2.productPrice = self.prodPrice.get()
            product2.productQuant = self.quantity.get()
        elif i == 3:
            product3.productName = self.prodName.get()
            product3.productName = self.prodID.get()
            product3.productSize = self.prodSize.get()
            product3.productPrice = self.prodPrice.get()
            product3.productQuant = self.quantity.get()
        newProduct()
        i += 1
        return i

I'm expecting to get it to switch the variable the entries are being saved to to the next respective product based on a +1 function, I'm having it return the i function as the new i, which should then save the entries to the next variable in the process, but it keeps telling me that I'm 'missing 1 required positional argument: 'i'
Comment: How are you calling `saveVars`?
Comment: I'm calling it within a larger class that's creating the gui, labels, entries, and basically everything else. @Sayse
Comment: Specifically I'm pressing a button that activates this function @Sayse
Comment: Can you show the actual function call to `saveVars`
Comment: addItemButton = Button(window, text = "Add to Cart", fg='black',bg='yellow',width = 10, height = 2, command = saveVars)
addItemButton.place(x=800,y=375) @AshishGhodake
Comment: I think this answer can help you [Using global variables in a function](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function)
Comment: Yeah took a look into these, used a global variable, and it is still only saving to the first product
Answer: You are trying to call the function without parameter as the command attribute does not take parameters just the name of the function.
To pass parameters you could use partial form functools package
import statement :
from functools import partial

your call to function would look like :
addItemButton = Button(window, text = "Add to Cart", fg='black',bg='yellow',width = 10, height = 2, command = partial(saveVars,i)) addItemButton.place(x=800,y=375)

You can set the inital value to i in your class using a global variable instead of declaring it outside the class. You can save it anywhere you wish and pass it while calling the funtion.
Answer: It seems like you are calling saveVars without the parameter in some case. To prevent this you can set a default value of i, eg.
def saveVars(i=0)

Comment: So I tried this, but unfortunately it only keeps the saving to the first product because it keeps defaulting to 1 or whatever number is predetermined, that's why I thought it would be a good idea to establish the i variable outside the function, and then +1 inside the function and return it so it will go up by one every time. @IshitaSingh
Comment: Yes, continue with your logic of incrementing, but add this as the default value if no 'i' is passed:
```
def saveVars(i=1)
```
Run your previous code with just this change. The error should go away.


Wiring receptacle(s) controlled by a switch

Question: OK, here is a problem that I need solved: To connect indoor (double) receptacle and a switch to an outdoor (porch)
single receptacle so that the switch will control when the outdoor receptacle is on or off (and possibly not have
any effect to the indoor receptacle). In other words I want the line feed of the indoor receptacle to also feed the
porch receptacle, but I want (an indoor) switch to control the outdoor receptacle. I did it wrong -- see the approximate
photo and diagram (at least I think that is how I did it). When switch is down (off) it does not affect either indoor or outdoor
receptacles -- they all work with no problem. When I put the switch up (to on) the breaker intervenes and shuts down
that box. So clearly, turning the switch in the "on" position connects the neutral and the hot, which I did not expect
since I thought the (s)witch comes "after" the original receptacle...
So somebody help here with a neat solution: Given are: 1) a feeder line coming to the indoor receptacle (not too much
extra wire to play with); all casing is metal which serves as the grounding (so the extra hair pig tails I add in the box
are not necessary). 2) Porch (outside) receptacle with its wires. It is set in its
position and I do not want to go through the trouble of (re)moving it. The (metal) box is also in place and I do
not want to remove it. So how do I connect these wires so as to get everything to work: indoor receptacle (preferably
without interference by the switch) and outside receptacle to work when the indoor switch is in the "on" position. Uups, I have the diagram in the wiring diagram in the pdf format but I do not see an option of adding pdf file picture.
Here comes the diagram
Comment: Your diagram did not post...hit [edit] on your post, then use the "sun and mountain" icon to add it
Comment: But that icon is only for the photos. I see the photo in the post. The diagram is in the pdf format, how do I post a pdf file?
Comment: You'll have to convert the PDF to an image then
Answer: If I understand the diagram correctly, you connected hot from the duplex receptacle to the switch (correct) and then from the same screw on the switch to the single receptacle (wrong). You also connected neutral to the switch (wrong). Basically, you treated the switch as if it were another receptacle, when actually it should only be in the hot wire.

Remove both wires going to the bottom of the switch and connect them to each other (but not to the switch) with a wire nut. These wires should both be white because they are carrying neutral.
Disconnect the wire going from the top of the switch to the single receptacle and connect it to the bottom of the switch. This is switched hot - when the switch is on, it carries power from the hot wire (top of the switch, coming from the duplex receptacle) to the single receptacle. This wire (and the wire to the top of the switch) should be black (or any color other than white or green).

It doesn't matter whether you have hot on top/switched hot on bottom or vice versa - with a simple switch it doesn't matter.
Comment: I have always tried to wire similar to labeling requirements to avoid confusion ( top to bottom, left to right and front to back). So I feed my hot to the top but as this answer explains it doesn't matter. Always following the same method will save time in the future if modifying or troubleshooting.
Comment: Manassehkatz- Moving 2 Codidact. you are correct, I thought I could get away by treating  a switch as a receptacle. I will follow your instructions and let you know how it goes. As for neutral and hot wires , their colors are white and black respectively, if wires are new. This is 70 year old house with indistinguishable colors. I go by silver side and brass side if that, hoping that the original wiring was correct.  Thanks again, I will let you know how it goes.
Comment: I followed your advice (mutatis mutandis -- my neutral wires were actually at the top of the switch, not the bottom). and voila, it worked like a charm. So you are what I want to be when I grow up -- a brilliant electrician. But I want to commend something else, apart from your expertise -- it is your great pedagogy -- you led me through the process with no confusion, just the right thing and you added an icing about the wire colors... Enough said!
Comment: Ah, your mind is more encompassing and so much the better. It is not clear how many licensed electricians would solve the switch puzzle so elegantly (or at all) as you did. What annoys me in these trades is an overwhelming dishonesty where ripping off customers is the norm. And so I decided to learn as I go. And you are a great helper. But there is no rest, I have posted another puzzle somewhere....
Comment: I mentioned the wire colors more so that if you are adding wires of your own (e.g., a short wire between the duplex receptacle and the switch) that you would make sure to get the colors right.
Comment: @Rado Thanks for the compliments. Actually though, I'm not an electrician (I may be brilliant, that is subject to debate...). I am computer geek, though I've been doing this long enough (starting with wiring up phone lines for 300bps modems > 40 years ago) that I have learned a lot about wiring - especially how to think through the details. At times I have thought of tossing it all and becoming an electrician or plumber (the trades are always in demand) but (a) my computer customers would kill me and (b) the training/apprentice time required to do work legally for others is a bit ridiculous.


How do I defend against being charmed by enemies?

Question: I'm currently fighting against groups that contain at least one Fampyr. The really annoying thing about this is that their opening move is charming one of my party members. They're also really, really good at it and succeed almost always.
I tried to use my priest to defend against it, but I misread the spells and only found one that worked against being confused and dazed, but nothing against being charmed.
My second idea was to use "suppress affliction" to remove the charmed effect, but that doesn't work either. Probably because it is classified as friendly AoE, and my charmed party member isn't friendly at that particular time.
What are effective methods to prevent my party members from being charmed?
Comment: Other than a high will to not get charmed in the first place?
Comment: @GodEmperorDune The Fampyrs attack with a high enough value that a small increase won't help, I need a pretty drastic effect (like the +50 defense the prayer against bewilderment provides against confusion).
Comment: @GodEmperorDune I just checked, they reliably charm Aloth who has 96 will. I understand the calcuation even less now, it showed something like 75 against 50 in the combat log. But the chance to charm seems just ridiculously high even against a character with high will
Comment: 75 against 50? That breaks all my knowledge of how I thought the save calculations worked (roll + attacker's accuracy vs roll + defender's save). I'm afraid I'm out of my depth here.
Comment: @GodEmperorDune It looks like it rolls with something like a -40 penalty against will, or it is using something other than will as the defense stat.
Comment: Will that temporary debuff-nullifying priest spell cancel it?
Answer: Same Problem here. The one thing you can do is casting arcane reflection right from the start. Sometimes you are fast enough and that charm gets reflected (but with no effect on the fampyr).
Edit: after some tests, you can cast it every time perfectly if you put Aloth a little bit behind your first hero who will trigger the fight, so the enemy fampyr have to walk a bit before casting the charm.
I'm dealing with the fampyr using the cipher's puppet charm and at the end the priest can use this level 1 spell, concealing and protecting him for 20 more seconds (he can't do anything then).
One funny solution may be to run away with Aloth, as the Fampyr is really keen on charming him. The both of them were running around the map for minutes in one case :D
Edit²: Priests will get a spell on level 11 with a high defense against charm and domination :)
Answer: If you look at the attack details in the log, you'll see that the Fampyr's charm does not attack Will at all; it attacks Deflection, which is strange.
Comment: Welcome to Arqade! Is there any more depth you can provide to this answer, possibly charm stats and possibly more ways to do this?


react-jsonschema-form How to pass down additional props to Form

Question: I am using react-jsonschema-form with @rjsf/antd (Ant Design).
Off of Ant Designs Form component, they have a property named size which as the name suggests, controls the size of the different input fields (Form.Item).
https://ant.design/components/form/#Form
I am wanting to include the size property off of react-jsonschema-form's Form property. I was hoping that react-jsonschema-form's Form would pass down any additional props to the Ant Design Form but that doesn't seems to be the case.
How would I go about including size?
Appreciate the help!
https://codesandbox.io/s/brave-poitras-jdshu0?file=/src/App.js
Answer: You should use _internalFormWrapper prop, as versions < 5 of RJSF.
import { Form as AntdForm } from 'antd';
import { withTheme } from '@rjsf/core';
import { Theme as AntDTheme } from '@rjsf/antd';

interface MyComponentProps { size: 'small' | 'middle' | 'large' }

const MyComponent = ({ size, ...props }: MyComponentProps): JSX.Element => {
  function MyAntdForm() {
    return <AntdForm size={size} />;
  }

  const Form = withTheme<FormValues>(Theme);

  return <Form {...props} _internalFormWrapper={MyAntdForm} >
}