text:
Q: How do you get rid of the default image for radio and checkboxes I've been trying to get rid of a a border and image that appears when I've skinned my controls (checkbox and radio buttons) does anyone know what that could be and how to get rid of it I've been using IE 10 and chrome and getting a default picture over the checkbox what gets rid of it the plugin I've been using is widowmaker

A: .thing {
   -webkit-appearance: none;
   -moz-appearance:    none;
   appearance:         none;
}

However, for inputs for instance, you might need to set border: 0; and background to a specific color, sometimes (Chrome in my case) shows a horrible border and I must reset it. It might as well happen in other browsers. It might also happen for other elements (such as the ones you're mentioning).
Using appearance: none; gives you the freedom of using custom CSS in most mayor browsers. Try to reset the "things" you want to "delete" by using these rules.
Here for more: http://css-tricks.com/almanac/properties/a/appearance/
Good luck!


text:
Q: Docker doesn't start MONGODB, and IPAddress doesn't appear, when started with other services I have already asked this question on serverfault.com. I am asking it here too as I see different set of questions in these 2 sites (it appears like they have different databases).
I have been trying to build an OS image from Fedora unsuccessfully to start the following:

*

*Systemd

*SSHD

*RabbitMQ

*MongoDB

I can get the first 3 (Systemd, SSHD and RabbitMQ-Server) to work. I can also get MongoDB to work within the container. However, I cannot get MongoDB to work along with other 3 services.
In addition, IP address doesn't show up when I try to "dockerize" MongoDB.
Am I missing something in the Dockerfile?
Here is my dockerfile:
FROM fedora:20
MAINTAINER "Ashfaque" <ashfaque@email.com>
ENV container docker
RUN yum -y update; yum clean all
RUN yum -y install systemd; yum clean all; \
(cd /lib/systemd/system/sysinit.target.wants/; for i in *; do [ $i == systemd-tmpfiles-setup.service ] || rm -f $i; done); \
rm -f /lib/systemd/system/multi-user.target.wants/*;\
rm -f /etc/systemd/system/*.wants/*;\
rm -f /lib/systemd/system/local-fs.target.wants/*; \
rm -f /lib/systemd/system/sockets.target.wants/*udev*; \
rm -f /lib/systemd/system/sockets.target.wants/*initctl*; \
rm -f /lib/systemd/system/basic.target.wants/*;\
rm -f /lib/systemd/system/anaconda.target.wants/*;

# Dockerizing SSH - is working
RUN yum -y install openssh-server
RUN yum -y install openssh-clients
RUN mkdir /var/run/sshd
RUN systemctl enable sshd.service
RUN echo 'root:mypassword' |chpasswd
EXPOSE 22

# Dockerizing RabbitMQ - is working
RUN yum -y install rabbitmq-server
EXPOSE 5672 15672
RUN systemctl enable rabbitmq-server

# Dockerizing MongoDB - is NOT WORKING
RUN yum -y install mongodb-server
RUN yum -y install boost
RUN yum -y install scons
# Create the MongoDB data directory
RUN mkdir -p /data/db /var/log/mongodb /var/run/mongodb
RUN sed -i 's/dbpath =\/var\/lib\/mongodb/dbpath =\/data\/db/' /etc/mongodb.conf
# Expose port 27017 from the container to the host
EXPOSE 27017
# Set usr/bin/mongod as the dockerized entry-point application
ENTRYPOINT ["/usr/bin/mongod"]
#CMD ["--port", "27017", "--dbpath", "/data/db", "--smallfiles", "--fork", "--syslog"]
#RUN /usr/bin/mongod --smallfiles --port 27017 --dbpath /data/db --fork --syslog

VOLUME ["/sys/fs/cgroup", "/data/db", "/var/log/mongodb", "/usr/bin"]
CMD ["/usr/sbin/init"]

Docker Commands used to build are:
(1) docker build -t rabbitmq_mongo_heisenbug .
(2) docker run --privileged -d -e 'container=docker' -v /sys/fs/cgroup:/sys/fs/cgroup:ro -p 29022:22 -p 29672:15672 -p 29017:27017 rabbitmq_mongo_heisenbug
or.. (3) docker run --privileged -ti -e 'container=docker' -v /sys/fs/cgroup:/sys/fs/cgroup:ro -p 29022:22 -p 29672:15672 -p 29017:27017 rabbitmq_mongo_heisenbug

A: You are using both ENTRYPOINT and CMD in your Dockerfile. This means, that docker will run /usr/bin/mongod with default parameter /usr/sbin/init. I'm pretty sure this is not what you want.
Docker will run as long as the command you specified is running. I'm not sure about /usr/bin/mongod, but if it runs in daemon mode (that is, spawn a process and return), then the container will stop running right away. The spawned processes will be terminated. The same is true for /usr/sbin/init or for any other command you specify. You can write a small shell script, which spawns the processes and runs one in the foreground, or you can use runit, or some similar tool.
Also, you probably don't need to run sshd in your container. See here why.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Efecto de lluvia en Android Studio estoy tratando de crear el efecto de lluvia. Ya creé el sprite, lo que no sé es como hacer para que aparezcan X cantidad de gotas por segundo o el tiempo de vida. Alguien me puede ayudar?
Gracias.
Sprite:
public class Sprite_Lluvia {

private Bitmap gota_de_lluvia;
private Juego juego;
private int velocidad = 50;
int x, y = -100;
boolean posicion = true;
Paint paint;

public Sprite_Lluvia(Juego juego, Bitmap gota_de_lluvia){

    this.juego = juego;
    this.gota_de_lluvia = gota_de_lluvia;

    paint = new Paint();
}

public void onDraw(Canvas canvas) {

    if (posicion == true) {
        Random random = new Random();
        x = random.nextInt(canvas.getWidth());
        posicion = false;
    }

    canvas.drawBitmap(gota_de_lluvia, x, y, null);
}
}

Juego:
public class Juego extends SurfaceView {

private Bitmap gota_de_lluvia;
private Sprite_Lluvia sprite_lluvia;
Paint paint;

private List<Sprite_Lluvia> sprites = new ArrayList<Sprite_Lluvia>();

public Juego(Context context, AttributeSet attrs) {
    super(context, attrs);

    gota_de_lluvia = BitmapFactory.decodeResource(getResources(), R.drawable.gota_de_lluvia);
    sprite_lluvia = new Sprite_Lluvia(this, gota_de_lluvia);

    paint = new Paint();
}

private Sprite_Lluvia createSprite(int resource) {
    Bitmap bmp = BitmapFactory.decodeResource(getResources(), resource);
    return new Sprite_Lluvia(this, bmp);
}

@Override
protected void onDraw(Canvas canvas) {

    paint.setColor(Color.BLACK);

    int i = 0;
    for (Sprite_Lluvia sprite : sprites) {
        sprite.onDraw(canvas);
        i++;
    }
    invalidate();
}
}

A: Para que aparezcan X cantidad de gotas por segundo podrías usar un Timer, o un Handler que es mas eficiente en Android. Yo te recomiendo CountDownTimer que aunque menos eficiente que el Handler, es mas facir de implementar. Ejemplo modificando tu clase Juego en el método onDraw():
Juego Class
private Handler mHandler = new Handler();
...

@Override
protected void onDraw(Canvas canvas) {

    paint.setColor(Color.BLACK);

    ....

    //contador de 30 segundos y que se ejecuta cada segundo
    new CountDownTimer(30000, 1000) {

       public void onTick(long millisUntilFinished) {
           int segundos = millisUntilFinished/1000;

           if(segundos > 20){
           //Creas una gota y la dibujas
               sprite_lluvia = new Sprite_Lluvia(this, gota_de_lluvia);
               sprite_lluvia.onDraw(canvas);
           }
           else if(segundos > 10){
           //Creas 2*gotas y las dibujas
               sprite_lluvia2 = new Sprite_Lluvia(this, gota_de_lluvia);
               sprite_lluvia2.onDraw(canvas);
               sprite_lluvia3 = new Sprite_Lluvia(this, gota_de_lluvia);
               sprite_lluvia3.onDraw(canvas);
           }
           else{
           //Creas 3*gotas y las dibujas
           }
       }

       public void onFinish() {
          //si quieres hacer algo al acabar el tiempo de juego
       }
    }.start();

    ....
};

Para el tiempo de vida restante, mas de lo mismo. Usa otro contador por cada gota que al llegar a 0 la haga desaparecer.


text:
Q: Are there any plans to transition Ubuntu on the Nexus 7 away from the Android kernel? Will the Android kernel and underpinnings eventually go away?
What are the plans for newer kernel releases?

A: We currently use an Android 3.1 kernel so we can interface with the binary drivers for the Tegra3 chipset that nVidia provides.  We are currently working on merging this kernel with the official Ubuntu kernel.
This includes configuration and patches, assuming the patches can apply to a 3.1 kernel.  If newer kernels are released for the Nexus7 by Google, then we will investigate the effort in migrating our changes to the new version and release one if feasible.


text:
Q: Remove status bar from a AVPlayerViewController and MPMoviePlayerController in iOS 10 I have an app configured via Info.plist for hiding the status bar, but it is remaining as part of the video controls. Is it possible to remove the status bar that is shown as part of the controls of the AVPlayerViewController or MPMoviePlayerController classes?
I've tested in iOS 9 and 10 devices.
Thanks in advance.

A: Please try the below options to hide status bar
hide statusBar using bellow line...
[[UIApplication sharedApplication] setStatusBarHidden:YES animated:YES];

otherwise use this bellow line..
mpviewController.controlStyle = MPMovieControlStyleFullscreen;

OR
[self setWantsFullScreenLayout:YES];


text:
Q: How to make a re sizable Vertical handler? I hope you know that in http://www.jsfiddle.net we can resize the table.

So i want wondering how to resize a "Vertical Handler" alone.
Can anyone give me the source ?
Please show an example in http://www.jsfiddle.net if possible.

A: Your looking for the jquery layout plugin. It's very easy to use. Lots of examples here: http://layout.jquery-dev.net/

A: This is an old question, but first in Google results, so I'll answer it here.
I found the splitter library at http://methvin.com/splitter/index.html quite serviceable.  It has vertical and horizontal splitters, multiple panels, min and max controls, and so on, along with good demos and documentation.


text:
Q: Does it matter what beasts I offer on the blood altar Some recipes require a couple different rare monsters, does it make a difference if I offer a monster that is under a spirits grip: for example the monster on the below picture, will this give me a better item than a monster of the same level without the warriors grip?

Does crafting multiple monsters with a specific mod give a specific result? For example: all offered monsters have "Extra life", does this result in a specific mod in the crafted item or is it completely random?

A:
Does it make a difference if I offer a monster that is under a spirits grip?

The captured beast will retain the "…'s Grip" modifier while stored in your menagerie, making it significantly more difficult to kill. This is a nerf.
There is no known benefit to using monsters with modifiers that are not explicitly required for the recipe.

Does crafting multiple monsters with a specific mod give a specific result?

No such effect is currently known.


text:
Q: Compiled Application with Ruby config files (yml) I compiled a program from source on mac os x which tells me to use the supplied example config files, but how can I run a specific config file?
Readme shows what to edit in the config but not how to load it.
More specifically this program (http://github.com/carsonmcdonald/HTTP-Live-Video-Stream-Segmenter-and-Distributor)

A: Looks like the following should work:
./http_streamer.rb example-configs/config-simple.yml

basically the name of the config file goes as the first argument to the script.


text:
Q: Parsing sets of variables from a string in a bat file I have a situation where I'm trying to keep a static list of related items in a string and parse them out as sets in a bat file.
SET RootPath=C:\Users\woodh\test\
SET FromPath=StuffFrom\
SET ToPath=StuffTo\
SET CTLNames='text1.txt,red_text1:text2.txt,white_text2:text3.txt,blue_text3:'

With CTLNames containing pairs of entries to be parsed and consumed in the job.
I did the following
:Step20
rem -----------------------------------------------------------------
rem loop thru all files in the control list processing each pair at a time
rem -----------------------------------------------------------------
    FOR /F "delims=:" %%f IN (%CTLNames%) DO (

        IF NOT "%%f" == "" (

            CALL:BreakEntry "%%f"
        )
    )

:Finish
rem ----------------------------------------------------------------
rem -- Finish
rem ----------------------------------------------------------------
      goto end

:BreakEntry
rem -----------------------------------------------------------------
rem loop thru all files in the control list processing each entry one at a time
rem -----------------------------------------------------------------
    Set EntryLine=%~1

    IF NOT "%EntryLine%" == "" (

        ECHO %EntryLine%

        FOR /F "tokens=1,2 delims=," %%a IN ("%EntryLine%") DO (

            ECHO %%a
            ECHO %%b

            CALL:MoveThisFile %%a, %%b
        )

    )

goto:eof

But It's only processing the first pair of names and not continuing through the rest of the list.

A: Your question is confusing. You didn't explained what exactly is the purpose of your code nor the expected output, so we can only guess. So I guess that you have a series of pairs of values separated by colon, and that each pair of values is separated by comma. This way, the problem with your code is that for /F command does not iterate over several values when just one string is processed: the string is divided accordingly to "tokens and delims" options and the command is executed just one time. You need to use a different method to process all substring in the string.
This is the way I would do it:
@echo off
setlocal

SET "CTLNames=text1.txt,red_text1:text2.txt,white_text2:text3.txt,blue_text3:"

for %%f in ("%CTLNames::=" "%") do (
   for /F "tokens=1,2 delims=," %%a in (%%f) do (

      echo %%a
      echo %%b

      echo CALL :MoveThisFile %%a, %%b
   )
)

I suggest you to remove the @echo off line and execute the program, so you may review what exactly is executed.

A: The reason why it doesn't work as expected (it only prints the 1st pair), is because for /f works on lines; CTLNames only consists of a line so a single iteration is needed.
The confusing part is that it still printed the 1st pair...that is because it actually did the split (on the 1st :) but by default for only cares about the 1st token (before the delim) and drops the rest. You can convince yourself by changing the line to:
FOR /F "tokens=* delims=:" %%f IN (%CTLNames%) DO (

you'll see that the value of %%f (because we instructed it to take all the tokens into account) is the whole line.
The reason why I asked if the COLON(:) is mandatory as a separator between pairs, is because you can also iterate over a non numeric list - no /f flag, but here you can't specify the delimiter so you must use a regular one: SPACE( ), COMMA(,), SEMICOLON(;), TAB, and maybe others (anyway COLON is not one of them) - so this loop:
for %%f in (text1.txt:red_text1 text2.txt:white_text2 text3.txt:blue_text3;) do (
    echo %%f
)

- note that I used 3 separators: TAB, SPACE and SEMICOLON in the for loop (not sure how visible it is) -
would yield:

text1.txt:red_text1
text2.txt:white_text2
text3.txt:blue_text3

Or you could use regular separators everywhere, and give up at the pair concept altogether, but I don't know if this is what you want.
I wasn't able to solve the problem using COLON as a separator from a single for loop, but I was able to find a way. Here's your script (slightly modified):
@ECHO OFF

rem ECHO %CTLNames%

CALL :Step20 "%CTLNames%"
GOTO :eof

:Step20
rem -----------------------------------------------------------------
rem loop thru all files in the control list processing each pair at a time
rem -----------------------------------------------------------------
    IF "" == "%~1" GOTO :eof
    FOR /F "tokens=1* delims=:" %%f IN ("%~1") DO (
        rem echo f: %%f
        CALL :BreakEntry "%%f"
        CALL :Step20 "%%g%
    )
GOTO :eof

:BreakEntry
rem -----------------------------------------------------------------
rem loop thru all files in the control list processing each entry one at a time
rem -----------------------------------------------------------------
    Set EntryLine=%~1
    ECHO %EntryLine%
    FOR /F "tokens=1,2 delims=," %%a IN ("%EntryLine%") DO (
        ECHO %%a
        ECHO %%b
        rem CALL :MoveThisFile %%a, %%b
    )
GOTO :eof

The main thing is (besides other small changes) that Step20 is a recursive function (label), and it uses the for loop to split the line, it processes the 1st token, then it calls itself on the remaining tokens (until there are no more left).
Note: the single quotes surrounding CTLNames should be removed.


text:
Q: LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance I have HashSet's where each stores T, I have written a test application that compares the different relation algorithms that I can think of, however I'm not all pleased with the results that I am getting.
Does there exist more efficient ways of achieving object relations, then the once that I am testing?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

namespace LINQTests
{
    class Program
    {
        static void Main(string[] args)
        {
            HashSet<User> UserTable = new HashSet<User>();
            HashSet<UserProperty> UserPropertyTable = new HashSet<UserProperty>();

            #region Lets create some dummy data.

            Console.WriteLine("Please wait while creating dummy data, this can take a while...");
            Console.WriteLine("");

            int rows = 1000000;
            for(int x = 0; x < rows; x++)
            {
                Random rnd = new Random();

                // Add new user.
                User user = new User(string.Format("Joachim-{0}", x));
                if(!UserTable.Add(user))
                {
                    // throw new Exception.
                }
                else
                {
                    UserProperty age = new UserProperty(user, "Age", rnd.Next(25, 30).ToString());
                    if(!UserPropertyTable.Add(age))
                    {
                        // throw new Exception.
                    }

                    UserProperty sex = new UserProperty(user, "Sex", "Male");
                    if (!UserPropertyTable.Add(sex))
                    {
                        // throw new Exception.
                    }

                    UserProperty location = new UserProperty(user, "Location", "Norway");
                    if (!UserPropertyTable.Add(location))
                    {
                        // throw new Exception.
                    }
                }
            }

            #endregion

            #region Lets do some query tests.

            IEnumerable<User> Users;
            Stopwatch stopwatch = new Stopwatch();
            int matches = 0;

            // Lets find all users who are of age 29.
            Console.WriteLine("Finding all users who are of age 29");
            Console.WriteLine("");
            Console.WriteLine("---------------------------------------------------");
            Console.WriteLine("{0,-20} | {1,6} | {2,9}", "Search Strategy", "Found", "Time");
            Console.WriteLine("---------------------------------------------------");

            // Join test.
            stopwatch.Start();

            Users = (from user in UserTable
                     join property in UserPropertyTable on user.Id equals property.UserId
                     where property.Key == "Age" && property.Value == "29"
                     select user);

            matches = Users.Count();
            stopwatch.Stop();
            Console.WriteLine("{0,-20} | {1,6} | {2,6} ms.", "Joining Tables", matches, stopwatch.ElapsedMilliseconds);

            // Dictionary test.
            stopwatch.Restart();

            var DictionarySearch = (from t in UserPropertyTable where t.Key == "Age" && t.Value == "29" select t).ToDictionary(x => x.UserId);
            Users = (from t in UserTable where DictionarySearch.ContainsKey(t.Id) select t);

            matches = Users.Count();
            stopwatch.Stop();
            Console.WriteLine("{0,-20} | {1,6} | {2,6} ms.", "Dictionary Contain", matches, stopwatch.ElapsedMilliseconds);

            // HashSet test.
            stopwatch.Restart();

            var HashsetSearch = new HashSet<Guid>(from t in UserPropertyTable where t.Key == "Age" && t.Value == "29" select t.UserId);

            Users = (from t in UserTable where HashsetSearch.Contains(t.Id) select t);

            matches = Users.Count();
            stopwatch.Stop();
            Console.WriteLine("{0,-20} | {1,6} | {2,6} ms.", "HashSet Contain", matches, stopwatch.ElapsedMilliseconds);

            // Following takes so long that we wont run them!

            //// Array test.
            //stopwatch.Restart();

            //var ArrayMatch = (from t in UserPropertyTable where t.Key == "Age" && t.Value == "29" select t.UserId).ToArray();
            //Users = (from t in UserTable where ArrayMatch.Contains(t.Id) select t);

            //matches = Users.Count();
            //stopwatch.Stop();
            //Console.WriteLine("{0,-20} | {1,6} | {2,6} ms.", "Array Contain", matches, stopwatch.ElapsedMilliseconds);

            //// List test.
            //stopwatch.Restart();

            //var ListMatch = (from t in UserPropertyTable where t.Key == "Age" && t.Value == "29" select t.UserId).ToList();
            //Users = (from t in UserTable where ListMatch.Contains(t.Id) select t);

            //matches = Users.Count();
            //stopwatch.Stop();
            //Console.WriteLine("{0,-20} | {1,6} | {2,6} ms.", "List Contain", matches, stopwatch.ElapsedMilliseconds);

            Console.WriteLine("---------------------------------------------------");

            #endregion

            Console.WriteLine("");
            Console.WriteLine("Hit return to exit...");
            Console.Read();
        }
    }

    public class User
    {
        public User(string UserName)
        {
            this.Id = Guid.NewGuid();
            this.UserName = UserName;
        }

        public Guid Id { get; set; }
        public string UserName { get; set; }

        public override bool Equals(object obj)
        {
            User other = obj as User;

            if (other == null)
                return false;

            return this.Id == other.Id;
        }

        public override int GetHashCode()
        {
            return Id.GetHashCode();
        }
    }

    public class UserProperty
    {
        public UserProperty(User user, string key, string value)
        {
            this.Id = Guid.NewGuid();
            this.UserId = user.Id;
            this.Key = key;
            this.Value = value;
        }

        public Guid Id { get; private set; }
        public Guid UserId {get; private set;}
        public string Key { get; set; }
        public string Value { get; set; }

        public override bool Equals(object obj)
        {
            UserProperty other = obj as UserProperty;

            if (other == null)
                return false;

            return this.UserId == other.UserId && this.Key == other.Key;
        }

        public override int GetHashCode()
        {
            return string.Format("{0}-{1}", this.UserId, this.Key).GetHashCode();
        }
    }
}

A: This will make the linq/join comparable to the other methods:
var properties = UserPropertyTable
    .Where(p=>p.Key == "Age" && p.Value == "29")
    .ToArray();

Users = (from user in UserTable
         join property in properties
         on user.Id equals property.UserId
         select user);

Here is the fastest (~2X) I could achieve:
var filteredUserIds = new HashSet<Guid>(
        UserPropertyTable
            .Where(p=>p.Key == "Age" && p.Value == "29")
            .Select(p=>p.UserId));

Users = (from user in UserTable
         where filteredUserIds.Contains(user.Id)
         select user);

With the output

---------------------------------------------------
Search Strategy      |  Found |      Time
---------------------------------------------------
My method            | 210366 |    157 ms.
Dictionary Contain   | 210366 |    325 ms.
HashSet Contain      | 210366 |    325 ms.
---------------------------------------------------

A: Here are a few things you can do:

*

*GetHashCode is being called for each element added and for each element being probed (how else could the hash table compare the two hash codes?). Equals is being called at least once for each probe. Optimize those. Do not use string.Format(!). It needs to parse the format string and allocate memory. UserId.GHC() * 37 ^ Name.GHC() should do.

*Don't use LINQ. Write manual loops. LINQ has multiple vcalls or delegate calls per item being processed. That adds instructions, stalls the CPU and prevents inlining.

*Can you precompute data structures? Precompute hash tables or sorted lists. Merging two sorted lists could be faster than using a hash table. This is not built-in to the framework. Lot's of hard, custom code to write for merge joins.

*Why are you including the property.Key == "Age" && property.Value == "29" predicate in the measurements? Will that need to be run for each execution? You can try to optimize that by using integer values instead of strings. Maybe you can precompute an index for UserPropertyTable so that you can get the matching elements in constant time.

This should give you 1-10x speedup depending on how much you implement. If you need to go even faster than that I would need to ask some questions first. Often you can find specialized tricks that only apply to particular situations.


text:
Q: Will two I/O operations trying to access same file cause race condition in nodeJS? I want to create two directories.
1. /tmp/xyz/dir1
2. /tmp/xyz/dir2
I'm promisifying fs.mkdir as mkdirPromisified and then :
let mkdirProcesses = [];
mkdirProcesses.push(mkdirPromisifed('/tmp/xyz/dir1'));
mkdirProcesses.push(mkdirPromisifed('/tmp/xyz/dir2'));
return Promise.all(mkdirProcesses);

What exactly will this code do? Since I/O in JavaScript is asynchronous, I'm assuming this will create two threads at the OS level, or is my assumption wrong? If not, will these two threads try to access the same base directory structure ('/tmp/xyz') at the same time and cause a race condition? If so, what is a better solution to accomplish what I'm trying to do? The number of directories I want to create is not static.


text:
Q: Find the probability that both times the "coin eagle" fell out The coin is thrown twice. Find the probability that BOTH times the "eagle" fell out, if it is known that during these two throws, the "eagle" fell out at least once.
//"eagle" or "E" means the side of coin without a digit. The side with digit is "D"
My answer is $\frac{1}{3}$ because we have:
E E - that doesn't happen due to "eagle fell out at least once"
D E - ok
E D - ok
D D - we need it
so the answer is $\frac{1}{3}$, but the correct answer is $\frac{3}{4}$. Can you explain me why?

A: How do you "know that the eagle fell out at least once"? Did you happen to see the first throw', which turned out to be an eagle, after which you closed your eyes and didn't see the second throw?  In that case, you "know that the eagle fell out at least once", and the probability is $\frac{1}{2}$.
On the other hand, if you had your eyes closed for both throws, and some one tells you that an egale came up at least once, then you also "know that the eagle fell out at least once", but now the probability is $\frac{1}{3}$, exactly following your calculation.
Neither way is it $\frac{3}{4}$ though ... and I can't think of any reqasonable scenario in which you "know that an eagle fell out at least once" that would make it $\frac{3}{4}$

A: Yes, you are exactly right.
(1/3) is the right answer.


text:
Q: What's the proper way to add users to my site in order to test things? I'm new to wordpress.
I'm have my site just running on localhost and want to test some things out with dummy data/made up users.
When I log in to my wordpress database, I see that there is a table already there called wp_users
My plan right now is to run a sql script INSERT a whole bunch of fake users into the wp_users table and start testing the functionality of my site.
My question is, is this the proper way of doing things? Is the wp_users table for admins or people who will edit the site, or is it meant for users who will login to the site?
Sorry if this is a silly question. Thank you!


text:
Q: How can I make a Map[ (Int,Int) , List[Int] ] that spans from (0,0) to (8,8)? I am working on a scala program that is essentially a sudoku solver, and in order to test it I need to make an "empty" map that includes every coordinate of a sudoku board (0,0),(0,1),(0,2) etc all the way up until (8,8), which represent the 81 cells in a sudoku board. The List[Int] in the map represents the possible values that can be placed at that cell. So, I need to make a map that has all of these coordinates mapped to a List(1,2,3,4,5,6,7,8,9) to indicate that every value can be placed at every cell.
How would I do this? I have tried tinkering with the to function ( 0.to(9)) but I cannot get it to work

A: I think you're going about this all wrong, but what do I know?
val grid = (for {
  x <- 0 to 8
  y <- 0 to 8
} yield (x,y) -> (1 to 9).toList).toMap


text:
Q: Projecting INEGI shapefiles from Mexico - not lining up I have two INEGI shapefiles from Mexico (2000 and 2010) that I want to line up with one another. The 2010 file projects in the right location and I would like the 2000 file to match/line up with the 2010 one. The shapefiles contain various cities in Mexico - some line up almost identically (see example of Minatitlan) while others are dramatically different (see example below of Tetepango).
I originally posted a question about getting data from 2000 to project in the correct location in Mexico, which made the cities are least be in the generally correction location! See the response here: Projecting INEGI shapefiles from Mexico
What can I do to make the 2000 file match/line up with the 2010 one?
2010/2000 Data Source:
Projected Coordinate System:    Conica Conforme de Lambert
Projection: Lambert_Conformal_Conic
False_Easting:  2500000.00000000
False_Northing: 0.00000000
Central_Meridian:   -102.00000000
Standard_Parallel_1:    17.50000000
Standard_Parallel_2:    29.50000000
Scale_Factor:   1.00000000
Latitude_Of_Origin: 12.00000000
Linear Unit:    Meter
Geographic Coordinate System:   ITRF92
Datum:  D_GRS_1980
Prime Meridian:     Greenwich
Angular Unit:   Degree

A: If your efforts defining projections and/or projecting your datasets have not produced a satisfactory result then I think that you should investigate spatial adjustment rubbersheeting:

Geometric distortions commonly occur in source maps. They may be
  introduced by imperfect registration in map compilation, lack of
  geodetic control in source data, or a variety of other causes.
  Rubbersheeting is used to make small geometric adjustments in your
  data—usually to align features with more accurate information.


text:
Q: How Can I independent the views in a layout How can I move views independently from other views in a layout ? For example, I want to be able to move one button up without the other moving but, currently, they are both moving. For more information please see the following image:

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Button"
    android:id="@+id/button"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    />

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Button"
    android:id="@+id/button2"
    android:layout_alignParentBottom="true"
    android:layout_toRightOf="@+id/button"
    android:layout_toEndOf="@+id/button"
    />

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Button"
    android:id="@+id/button3"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginBottom="39dp" />

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Button"
    android:id="@+id/button4"
    android:layout_alignTop="@+id/button3"
    android:layout_alignLeft="@+id/button2"
    android:layout_alignStart="@+id/button2" />

A: First you not posted complete xml layout file. How can some some know what layout you are using.
Solution:You need to put both buttons in different layout if your are using LinearLayout or you can use Relative Layout but in Relative Layout case both buttons should not be depend on each other.

A: You can use a RelativeLayout to embed the components you want.
 <RelativeLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="10dp"
                    android:orientation="vertical"
                    android:padding="10dp">

                    <TextView
                        android:id="@+id/cardholderNameText"
                        style="@style/form_label"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginBottom="10dp"
                        android:text="@string/cardholder_name" />
  </RelativeLayout>


text:
Q: How can I fetch MySQL datas in bootstrap multiselect? I created an admin panel for MySQL database, and when I click on the edit button, I want to print all of the datas in Bootstrap multi select. If I didn't use Bootstrap multi select, just the normal multi select, it's working. How can I do this?
This is how it looks like (in the button, it show the current datas, but when I open, it didn't showin the select menu):

index.php
<select name="classification[]" id="classification" multiple="multiple">
   <?php
      while($row = $classificationResult -> fetch_array()) {
   ?>
   <option value="<?php echo $row['classification_id'];?>"><?php echo $row['name'];?></option>
   <?php
      }
   ?>
</select>

<script>
   // If I didn't add the multi select jquery, it's working
   $('#classification').multiselect({
        nonSelectedText: 'Select Framework',
        maxHeight : 400,
        includeSelectAllOption : false,
        enableFiltering : false,
        buttonWidth : '100%',
        dropRight : true
    });

        $(document).on('click', '.edit_data', function(){
            $("#classification option").prop("selected", false);
            var data_id = $(this).attr("id");
            $.ajax({
                url:"fetchRole.php",
                method:"POST",
                data:{'data_id':data_id},
                dataType:"json",
                success:function(data){
                    $.each(data.classifications, function(i, e) {
                        $("#classification option[value='" + e + "']").prop("selected", true);
                    });
                    $('#data_id').val(data.id);
                    $('#insert').val("Edit");
                    $('#add_data_Modal').modal('show');
                }
            });
        });
</script>

fetchRole.php
$query2 = $conn -> prepare("SELECT classification.classification_id AS class_id
            FROM classification
            LEFT JOIN role_classification ON classification.classification_id = role_classification.classification_id
            WHERE role_classification.role_id = ?");
        $query2 -> bind_param('i', $role['id']);
        $query2 -> execute();
        $result2 = $query2 -> get_result();
        $query2 -> close();

        while ($classification = $result2 -> fetch_assoc()) {
            $classificationIdList[] = $classification["class_id"];
        }

        $return = array_merge($role, ["classifications" => $classificationIdList]);

    echo json_encode($return);

A: You need to refresh the multiselect after you set new selected options using .prop("selected", true).
$.each(data.classifications, function(i, e) {
    $("#classification option[value='" + e + "']").prop("selected", true);
});

$('#classification').multiselect('refresh');

Description of the refresh method:

This method is used to refresh the checked checkboxes based on the
  currently selected options within the select.

You can see the full list of available methods HERE.


text:
Q: Efficient way to compute the Vandermonde matrix I'm calculating Vandermonde matrix for a fairly large 1D array. The natural and clean way to do this is using np.vander(). However, I found that this is approx. 2.5x slower than a list comprehension based approach.
In [43]: x = np.arange(5000)
In [44]: N = 4

In [45]: %timeit np.vander(x, N, increasing=True)
155 µs ± 205 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

# one of the listed approaches from the documentation
In [46]: %timeit np.flip(np.column_stack([x**(N-1-i) for i in range(N)]), axis=1)
65.3 µs ± 235 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [47]: np.all(np.vander(x, N, increasing=True) == np.flip(np.column_stack([x**(N-1-i) for i in range(N)]), axis=1))
Out[47]: True

I'm trying to understand where the bottleneck is and the reason why does the implementation of native np.vander() is ~ 2.5x slower.
Efficiency matters for my implementation. So, even faster alternatives are also welcome!

A: Here are some more methods some of which are quite a bit faster (on my computer) than what has been posted so far.
The most important observation I think is that it really depends a lot on how many degrees you want. Exponentiation (which I believe is special cased for small integer exponents) only makes sense for small exponent ranges. The more exponents the better multiplication based approaches fare.
I'd like to highlight a multiply.accumulate based method (ma) which is similar to numpy's builtin approach but faster (and not because I skimped on checks - nnc, numpy-no-checks demonstrates this). For all but the smallest exponent ranges it is actually the fastest for me.
For reasons I do not understand, the numpy implementation does three things that are to the best of my knowledge slow and unnecessary: (1) It makes quite a few copies of the base vector. (2) It makes them non-contiguous. (3) It does the accumulation in-place which I believe forces buffering.
Another thing I'd like to mention is that the fastest for small ranges of ints (out_e_1 essentially a manual version of ma), is slowed down by a factor of more than two by the simple precaution of promoting to a larger dtype (safe_e_1 arguably a bit of a misnomer).
The broadcasting based methods are called bc_* where * indicates the broadcast axis (b for base, e for exp) 'cheat' means the result is noncontiguous.
Timings (best of 3):
rep=100 n_b=5000 n_e=4 b_tp=<class 'numpy.int32'> e_tp=<class 'numpy.int32'>
vander                0.16699657 ms
bc_b                  0.09595204 ms
bc_e                  0.07959786 ms
ma                    0.10755240 ms
nnc                   0.16459018 ms
out_e_1               0.02037535 ms
out_e_2               0.02656622 ms
safe_e_1              0.04652272 ms
safe_e_2              0.04081079 ms
cheat bc_e_cheat            0.04668466 ms
rep=100 n_b=5000 n_e=8 b_tp=<class 'numpy.int32'> e_tp=<class 'numpy.int32'>
vander                0.25086462 ms
bc_b             apparently failed
bc_e             apparently failed
ma                    0.15843041 ms
nnc                   0.24713077 ms
out_e_1          apparently failed
out_e_2          apparently failed
safe_e_1              0.15970622 ms
safe_e_2              0.19672418 ms
bc_e_cheat       apparently failed
rep=100 n_b=5000 n_e=4 b_tp=<class 'float'> e_tp=<class 'numpy.int32'>
vander                0.16225773 ms
bc_b                  0.53315020 ms
bc_e                  0.56200830 ms
ma                    0.07626799 ms
nnc                   0.16059748 ms
out_e_1               0.03653416 ms
out_e_2               0.04043702 ms
safe_e_1              0.04060494 ms
safe_e_2              0.04104209 ms
cheat bc_e_cheat            0.52966076 ms
rep=100 n_b=5000 n_e=8 b_tp=<class 'float'> e_tp=<class 'numpy.int32'>
vander                0.24542852 ms
bc_b                  2.03353578 ms
bc_e                  2.04281270 ms
ma                    0.11075758 ms
nnc                   0.24212880 ms
out_e_1               0.14809043 ms
out_e_2               0.19261359 ms
safe_e_1              0.15206112 ms
safe_e_2              0.19308420 ms
cheat bc_e_cheat            1.99176601 ms

Code:
import numpy as np
import types
from timeit import repeat

prom={np.dtype(np.int32): np.dtype(np.int64), np.dtype(float): np.dtype(float)}

def RI(k, N, dt, top=100):
    return np.random.randint(0, top if top else N, (k, N)).astype(dt)

def RA(k, N, dt, top=None):
    return np.add.outer(np.zeros((k,), int), np.arange(N)%(top if top else N)).astype(dt)

def RU(k, N, dt, top=100):
    return (np.random.random((k, N))*(top if top else N)).astype(dt)

def data(k, N_b, N_e, dt_b, dt_e, b_fun=RI, e_fun=RA):
    b = list(b_fun(k, N_b, dt_b))
    e = list(e_fun(k, N_e, dt_e))
    return b, e

def f_vander(b, e):
    return np.vander(b, len(e), increasing=True)

def f_bc_b(b, e):
    return b[:, None]**e

def f_bc_e(b, e):
    return np.ascontiguousarray((b**e[:, None]).T)

def f_ma(b, e):
    out = np.empty((len(b), len(e)), prom[b.dtype])
    out[:, 0] = 1
    np.multiply.accumulate(np.broadcast_to(b, (len(e)-1, len(b))), axis=0, out=out[:, 1:].T)
    return out

def f_nnc(b, e):
    out = np.empty((len(b), len(e)), prom[b.dtype])
    out[:, 0] = 1
    out[:, 1:] = b[:, None]
    np.multiply.accumulate(out[:, 1:], out=out[:, 1:], axis=1)
    return out

def f_out_e_1(b, e):
    out = np.empty((len(b), len(e)), b.dtype)
    out[:, 0] = 1
    out[:, 1] = b
    out[:, 2] = c = b*b
    for i in range(3, len(e)):
        c*=b
        out[:, i] = c
    return out

def f_out_e_2(b, e):
    out = np.empty((len(b), len(e)), b.dtype)
    out[:, 0] = 1
    out[:, 1] = b
    out[:, 2] = b*b
    for i in range(3, len(e)):
        out[:, i] = out[:, i-1] * b
    return out

def f_safe_e_1(b, e):
    out = np.empty((len(b), len(e)), prom[b.dtype])
    out[:, 0] = 1
    out[:, 1] = b
    out[:, 2] = c = (b*b).astype(prom[b.dtype])
    for i in range(3, len(e)):
        c*=b
        out[:, i] = c
    return out

def f_safe_e_2(b, e):
    out = np.empty((len(b), len(e)), prom[b.dtype])
    out[:, 0] = 1
    out[:, 1] = b
    out[:, 2] = b*b
    for i in range(3, len(e)):
        out[:, i] = out[:, i-1] * b
    return out

def f_bc_e_cheat(b, e):
    return (b**e[:, None]).T

for params in [(100, 5000, 4, np.int32, np.int32),
               (100, 5000, 8, np.int32, np.int32),
               (100, 5000, 4, float, np.int32),
               (100, 5000, 8, float, np.int32)]:
    k = params[0]
    dat = data(*params)
    ref = f_vander(dat[0][0], dat[1][0])
    print('rep={} n_b={} n_e={} b_tp={} e_tp={}'.format(*params))
    for name, func in list(globals().items()):
        if not name.startswith('f_') or not isinstance(func, types.FunctionType):
            continue
        try:
            assert np.allclose(ref, func(dat[0][0], dat[1][0]))
            if not func(dat[0][0], dat[1][0]).flags.c_contiguous:
                print('cheat', end=' ')
            print("{:16s}{:16.8f} ms".format(name[2:], np.min(repeat(
                'f(b.pop(), e.pop())', setup='b, e = data(*p)', globals={'f':func, 'data':data, 'p':params}, number=k)) * 1000 / k))
        except:
            print("{:16s} apparently failed".format(name[2:]))

A: How about broadcasted exponentiation?
%timeit (x ** np.arange(N)[:, None]).T
43 µs ± 348 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Sanity check -
np.all((x ** np.arange(N)[:, None]).T == np.vander(x, N, increasing=True))
True

The caveat here is that this speedup is possible only if your input array x has a dtype of int. As @Warren Weckesser pointed out in a comment, the broadcasted exponentiation slows down for floating point arrays.

As for why np.vander is slow, take a look at the source code -
x = asarray(x)
if x.ndim != 1:
    raise ValueError("x must be a one-dimensional array or sequence.")
if N is None:
    N = len(x)

v = empty((len(x), N), dtype=promote_types(x.dtype, int))
tmp = v[:, ::-1] if not increasing else v

if N > 0:
    tmp[:, 0] = 1
if N > 1:
    tmp[:, 1:] = x[:, None]
    multiply.accumulate(tmp[:, 1:], out=tmp[:, 1:], axis=1)

return v

The function has to cater to a lot more use cases besides yours, so it uses a more generalized method of computation which is reliable, but slower (I'm specifically pointing to multiply.accumulate).

As a matter of interest, I found another way of computing the Vandermonde matrix, ending up with this:
%timeit x[:, None] ** np.arange(N)
150 µs ± 230 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

It does the same thing, but is so much slower. The answer lies in the fact that the operations are broadcast, but inefficiently.
On the flip side, for float arrays, this actually ends up performing the best.


text:
Q: Using matplotlib and Rasterio I am trying to save a raster as a GeoTIFF as well as repoject it? I have been able to plot and display my raster images using matplotlib. That part is successful. The part which I am stuck on is be able to save that plot somehow. For rasterio I've found two helpful tutorials:
https://rasterio.readthedocs.io/en/latest/topics/windowed-rw.html
and
https://www.earthdatascience.org/courses/earth-analytics-python/multispectral-remote-sensing-in-python/export-numpy-array-to-geotiff-in-python/
I've gotten a calculate for a function called NDVI and through matplotlib I can display it just the way I want with the following code. But when I go to save the file as a GeoTIFF the image on my desktop is all black. I plan to reproject the data too and I have that code commented out.
Here is my code:
import rasterio
import matplotlib.pyplot as plt
import numpy as np

nirband = r"LC08_L1TP_015033_20170822_20170912_01_T1_B5.TIF"

redband =r"LC08_L1TP_015033_20170822_20170912_01_T1_B4.TIF"

#rasterio.windows.Window(col_off, row_off, width, height)
window = rasterio.windows.Window(2000,2000,800,600)

with rasterio.open(nirband) as src:
    subset = src.read(1, window=window)

fig, ax = plt.subplots(figsize=(12,6))
plt.imshow(subset)
plt.title(f'Band 5 Subset')

with rasterio.open(nirband) as src:
    nir = src.read(1, window=window)

with rasterio.open(redband) as src:
    red = src.read(1, window=window)

red = red.astype(float)
nir = nir.astype(float)
np.seterr(divide='ignore', invalid='ignore')

ndvi = np.empty(nir.shape, dtype=rasterio.float32)
check = np.logical_or ( red > 0, nir > 0 )
naip_ndvi = np.where ( check,  (1.0*(nir - red )) / (1.0*( nir + red )),-2 )

fig, ax = plt.subplots(figsize=(12,6))
ndvi = ax.imshow(naip_ndvi)
ax.set(title="NDVI")

with rasterio.open("LC08_L1TP_015033_20170822_20170912_01_T1_B5.TIF") as src:
    naip_data_ras = src.read()
    naip_meta = src.profile

with rasterio.open('MyExample.tif', 'w',**naip_meta) as dst:
    dst.write(naip_ndvi, window=window)

# =============================================================================
# with rasterio.open('example.tif') as dataset:
#
#     # Read the dataset's valid data mask as a ndarray.
#     mask = dataset.dataset_mask()
#
#     # Extract feature shapes and values from the array.
#     for geom, val in rasterio.features.shapes(
#             mask, transform=dataset.transform):
#
#         # Transform shapes from the dataset's own coordinate
#         # reference system to CRS84 (EPSG:4326).
#         geom = rasterio.warp.transform_geom(
#             dataset.crs, 'EPSG:4326', geom, precision=6)
#
#         # Print GeoJSON shapes to stdout.
#         print(geom)
# =============================================================================

Here is what NDVI looks like when I use matplotlib (I want to save this to my desktop as a GeoTIFF file):

Thank you for any and all help!

A: How are you viewing the output image? In an image viewer, or in GIS or remote sensing software that can add a contrast stretch to the file? NDVI values run from -1 to 1 - maybe the range of values is too small for your software to display automatcally. I had a similar issue recently with modifying PlanetScope imagery - it displayed as expected using matplotlib but the tiff appeared black.
You could try scaling the output by multiplying the cell values by 100 - this may help with display issues. You could also verify the output image values by using software that can apply a contrast stretch to the image (QGIS, esri products, ImageJ, or image processing software)

A: Your src.profile (from "LC08_L1TP_015033_20170822_20170912_01_T1_B5.TIF") probably has a dtype of int32 or something similar while your naip_ndvi contains float values.
You should set the dtype for your dst to float32 (or float64)
with rasterio.open("LC08_L1TP_015033_20170822_20170912_01_T1_B5.TIF") as src:
    naip_data_ras = src.read()
    naip_meta = src.profile

    # set dtype to float
    naip_meta["dtype"] = rasterio.float32


text:
Q: How to get close price of bar when my boolean criteria is met? I've created some criteria that creates a shape on the chart; now I need to know if the close price of the next candle is higher than the close price of the candle where my callSignal shape occurs.
Currently getting this error, which makes sense:
line 177: Cannot call 'operator <' with arguments (series[bool], series[bool]); available overloads: <(float, float) => bool; <(input float, input float) => input bool; <(const float, const float) => const bool; <(float, series[float]) => series[bool]; <(series[float], float) => series[bool]; <(series[float], series[float]) => series[bool];

Here is my code:
// ... //
expiryLength = 1
callSignal = Cond1[1] ? na : Cond1 and rightTime? Cond1 : na
putSignal = Cond1[2] ? na : Cond2 and rightTime? Cond1 : na

plotshape(callSignal, style=shape.triangleup, location=location.belowbar, size=size.tiny)
plotshape(putSignal, style=shape.triangledown, location=location.abovebar, size=size.tiny)

// This is the part I am struggling with... //
callWL = callSignal[expiryLength] < callSignal
plotshape(callWL, size=size.large)

I don't know how to incorporate close within my callWL variable, or if I just need to rework this further.

A: Here's a sample script that generates call entries whenever price crosses SMA 30 from below and after expiryLength bars, plots a shape for gain/loss.
//@version=4
study("Call lookback", overlay=true)

_expiryLength = input(title="Expire length in bars", type=input.integer, defval=10, minval=1)
_callSma = input(title="Call entry SMA period", type=input.integer, defval=30, minval=1)
_callSignal = false

// Make call entries
_callSignal := crossover(close, sma(close, _callSma))
plotshape(_callSignal?close:na, style=shape.triangleup, location=location.belowbar, size=size.tiny)

// Lookback for call entry and draw a symbol for gain/loss
_callWL = _callSignal[_expiryLength]
_color = close > close[_expiryLength]?color.green:color.red
plotshape(_callWL?close:na, color=_color, size=size.tiny)

plot(sma(close, _callSma))


text:
Q: How do I prove conditional entropy is a good measure of information? This question is a follow-up of Does "expected entropy" make sense?, which you don't have to read as I'll reproduce the relevant parts. Let's begin with the statement of the problem

A student has to pass an exam, with $k$ questions to be answered by yes or no, on a subject he knows nothing about. Assume the questions are independently distributed with a half-half probability of being either yes or no. The student is allowed to pass mock exams who have the same questions as the real exam. After each mock exam the teacher tells the student how many right answers he got, and when the student feels ready, he can pass the real exam. How many mock exams on average (a.k.a. take the expectation) must the student take to ensure he can get every single question correct in the real exam, and what should be his optimal strategy?

I have proposed an entropy-based strategy in that question, but for it to work, it must be first established that conditional entropy is a good measure of information to be recovered.
Here is a more concrete statement of my question. Suppose a student Alice has already taken 3 mock exams and got incomplete information about the answers. In a parallel universe, another student Bob has also taken 3 mock exams, but his strategy and insight about the answers may differ from those of Alice. At this point, both Alice and Bob have a conditional distribution of the answers based on outcomes of previous mock exams. I wonder if it can be proved that "the entropy of the conditional distribution from the perspective of Alice is greater or equal than that of Bob" can lead to "the minimum expected number of mock exams to be taken by Alice is greater or equal than that of Bob".
Intuitively it makes sense because more entropy means more uncertainty and thus more attempts required, but I have no idea how to attack it. As a side note, this will be my bachelor's thesis, so please just leave hints/pointers instead of spoiling too much :)

A: I've tried to hint but not solve.
Let $\mathfrak{m}$ be the fixed but unknown marking scheme, i.e. the yes/no assignments that are correct for each of the $k$ questions.  A priori, before you get your first mock paper results, there are (how many?) equally-likely possible values of $\mathfrak{m}$.  Put another way: the entropy of $\mathcal{M}$, the process that generated the marking scheme, is (how many?) bits.
Write $H_t(\mathcal{M})$ for the entropy of $\mathcal{M}$ conditional upon the scores from the first $t$ mock tests, and $n_t$ for the number of $\mathfrak{m}$ compatible with those first $t$ tests.  (How are $H_t(\mathcal{M})$ and $n_t$ related?)
Each time you get a mock paper score, you learn more about $\mathfrak{m}$.  With enough scores, $n_t$ drops to $1$ and you learn $\mathfrak{m}$ in its entirety.  Equivalently, $H_t(\mathcal{M})$ drops to $0$.
Entropy comes into play in a more interesting way when you think about how to modify your answers in each mock exam.  Let's say you answered "yes" to everything in the first mock; so it's a question of how to pick the "no" questions in future exams.
A greedy algorithm is to pick the "no" questions to minimise, on average, the proportion of $\mathfrak{m}$ possibilities that survive from one exam to the next, i.e. $n_{t+1}/n_t$.  This is exactly the approach you took in your earlier post, as it is equivalent to minimising the expected value of $\log(n_{t+1})$ (why log? - consider the cumulative effect).  In turn, $\mathbb{E}(\log(n_{t+1}))$ s is directly related to the entropy of the mock exam score (hint: if $p_x$ is the probability of scoring $x$, then it relates (how?) to the total number of $\mathfrak{m}$ possibilities compatible with $x$).
Hope that helps.

Here's a transcript of the procedure run on an exam with $k=13$ questions.  Notice how $H_t(\mathcal{M})$ drops by the information content, $I$, of the score from the most recent guess.  That's why you want to maximise the entropy of the mock exam score: it's the expected value of those $I$'s.
Marking scheme m = 1100000101011
A priori #survivors = 8192

----------------------------------------

Round 1: guess 0000000000000
The guess scored 7
Now #survivors = 1716  : conditional entropy 10.744833837499547

Best guess for next round is 1111110000000
with score distribution
  *  score  1 : count 7     : I = 7.937
  *  score  3 : count 126   : I = 3.768
  *  score  5 : count 525   : I = 1.709
  *  score  7 : count 700   : I = 1.294
  *  score  9 : count 315   : I = 2.446
  *  score 11 : count 42    : I = 5.353
  *  score 13 : count 1     : I = 10.745
and entropy 1.9456755990162689

----------------------------------------

Round 2: guess 1111110000000
The guess scored 5
Now #survivors = 525  : conditional entropy 9.036173612553485

Best guess for next round is 1110001110000
with score distribution
  *  score  1 : count 3     : I = 7.451
  *  score  3 : count 45    : I = 3.544
  *  score  5 : count 165   : I = 1.670
  *  score  7 : count 210   : I = 1.322
  *  score  9 : count 90    : I = 2.544
  *  score 11 : count 12    : I = 5.451
and entropy 1.9607272705044019

----------------------------------------

Round 3: guess 1110001110000
The guess scored 7
Now #survivors = 210  : conditional entropy 7.714245517666122

Best guess for next round is 1101001001100
with score distribution
  *  score  1 : count 2     : I = 6.714
  *  score  3 : count 19    : I = 3.466
  *  score  5 : count 64    : I = 1.714
  *  score  7 : count 81    : I = 1.374
  *  score  9 : count 38    : I = 2.466
  *  score 11 : count 6     : I = 5.129
and entropy 2.0229622152648568

----------------------------------------

Round 4: guess 1101001001100
The guess scored 7
Now #survivors = 81  : conditional entropy 6.339850002884625

Best guess for next round is 1000111101010
with score distribution
  *  score  2 : count 3     : I = 4.755
  *  score  4 : count 15    : I = 2.433
  *  score  6 : count 29    : I = 1.482
  *  score  8 : count 24    : I = 1.755
  *  score 10 : count 8     : I = 3.340
  *  score 12 : count 2     : I = 5.340
and entropy 2.138877221251309

----------------------------------------

Round 5: guess 1000111101010
The guess scored 8
Now #survivors = 24  : conditional entropy 4.584962500721157

Best guess for next round is 0101101011010
with score distribution
  *  score  2 : count 1     : I = 4.585
  *  score  4 : count 4     : I = 2.585
  *  score  6 : count 9     : I = 1.415
  *  score  8 : count 7     : I = 1.778
  *  score 10 : count 2     : I = 3.585
  *  score 12 : count 1     : I = 4.585
and entropy 2.160762106246821

----------------------------------------

Round 6: guess 0101101011010
The guess scored 6
Now #survivors = 9  : conditional entropy 3.1699250014423126

Best guess for next round is 1011100011100
with score distribution
  *  score  2 : count 2     : I = 2.170
  *  score  4 : count 2     : I = 2.170
  *  score  6 : count 3     : I = 1.585
  *  score  8 : count 1     : I = 3.170
  *  score 10 : count 1     : I = 3.170
and entropy 2.1971597234241496

----------------------------------------

Round 7: guess 1011100011100
The guess scored 4
Now #survivors = 2  : conditional entropy 1.0

Best guess for next round is 0100000000000
with score distribution
  *  score  6 : count 1     : I = 1.000
  *  score  8 : count 1     : I = 1.000
and entropy 1.0

----------------------------------------

Round 8: guess 0100000000000
The guess scored 8
Now #survivors = 1  : conditional entropy 0.0

*** FINISHED ***

A: Here are a few topics that I think are relevant

*

*Thompson Sampling

*Multi-Armed Bandits


text:
Q: sequelize query another table data to inset in to another table I have 3 Tables.
Productline,
item,
Purchase
In purchase, i want to show the Productline and items as their "names" without just id.
Using the foreignKey i can able to get the Ids of Productline and Item..
model Productline:
module.exports = (sequelize, DataTypes) => {
  const productline = sequelize.define('productline', {
    name: DataTypes.STRING,
    productline_id: DataTypes.STRING,
    uuid: DataTypes.STRING
  }, {
timestamps: false
});

  productline.associate = function(models) {
   agents.hasMany(models.purchase, { foreignKey:'productline', target : 'name' });
  };
  return productline;
};

model item:
module.exports = (sequelize, DataTypes) => {
  const item = sequelize.define('item', {
    name: DataTypes.STRING,
    moh_sound: DataTypes.STRING
}, {
timestamps: false
});
  queues.associate = function(models) {
    item.hasMany(models.purchase, { foreignKey : 'item', target: 'name' });
  };
  //queues.removeAttribute('id');
  return item;
};

model Purchase:
module.exports = (sequelize, DataTypes) => {
  const purchase = sequelize.define('purchase', {
    productline: DataTypes.STRING,
    item: DataTypes.STRING,
    state: DataTypes.STRING,
    level: DataTypes.INTEGER,
    position: DataTypes.INTEGER
 }, {
timestamps: false
});
  purchase.associate = function(models) {
};
  return tiers;
};

This is the results i am getting in:
 id | Productline | items | state | level | position |
----+-------+-------+-------+-------+----------+---------+---------
  4 | 2     | 3     |       |     1 |        1 |         |

But i am expecting results like below:
 id | Productline | items | state | level | position |
----+-------+-------+-------+-------+----------+---------+---------
  4 |  Electronics| mobile    |       |     1 |        1 |         |```


text:
Q: Do I always need a static IP to access my front-end on a custom domain in GKE? I have a website (front-end + backend) published on my own GKE cluster. The current configuration relies on one static IP allocated in GCP + one GCE Ingress instance to open the website to internet traffic. It works.
Is there a way to not use a static IP and rely on "ghs.googlehosted.com." ? I don't mind having a fixed static IP. I've tried to set up the DNS as GCP advises on https://console.cloud.google.com/appengine/settings/domains?project=YOURPROJECTID but it doesn't work. Looking at the service logs my FE can communicate internally to my BE. It is just the Ingress + LB configuration that doesn't let the googlehosted.com infra know my website is waiting for traffic and all requests should be sent there. Does such a configuration even exist?

A: If you take each piece of the architecture:

*

*You have your cluster with your services

*You want to expose the services. You create a load balancer

*The load balancer is created with an IP address

So, at the end, you only have an IP, there is no other way to expose a service with GKE. You have to use a Load Balancer, and the load balancer expose an IP.
Other cloud providers, like AWS, expose a subdomain and not an IP when you create a load balancer, and thus you aren't linked to an IP. It's not the case of GCP, at least for GKE


text:
Q: Pattern for handling HTTP requests via channels I am writing a web application where I have a long running goroutine.
I want to delegate all HTTP requests to this goroutine via channels.
The pattern that I have come across is:
// Internal long running goroutine
for{
  select{
  case e := <-event: //web request
    req := e.req
    // do something
    ....
    select {
    case <-ctx.Done():
       //log
    default:
      e.replyTo <- result
    }
  }
}

// Web handler
http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
  //decode request etc
  ...

  replyTo := make(chan interface{}, 1)
  ctx, cancel := context.WithCancel(context.BackGround())
  event <- Event{req: req, ctx: ctx, replyTo: replyTo}
  select{
  case <-time.After(time.Second):
     cancel()
     //return 500
  case r := <-replyTo:
    // return some response
  }
})

I do see that there is one single go-routine at the end, so parallelism is lost but I am okay with it.
Is this pattern the right way of doing this?
What other approaches can be suggested?

A:
Is this pattern the right way of doing this?

Assuming you are trying to manage where state in a single go routine, I would say no. I think it would be better to have some form of a state manager that is responsible for thread safety. Therefore the handler should take in something that can manage the state and simply expose a few methods to the handler.
type State interface{
  Load() (string, error)
  Save(something string) error
}

Decoupling the code will pay off for you later on. It will also allow unit tests for both the handler and the State that can be focused and readable.


text:
Q: Prevent opacity css from applying to child elements I am trying to prevent the opacity property from applying to the child elements.
I was under the assumption that the below piece of code would do that, but it isn't working.
.22:hover:after {
background-color: black;
opacity: 0.1;
}

A: One solution is using rgba:
.22:hover:after {
    background-color: rgba(0, 0, 0, 0.1); // black with opacity 0.1
}

A: The reason your current solution doesn't work is because your :after pseudo element does not have any content set (therefore it is not rendered), and it is not positioned properly. Try this instead.
.22:hover:after
{
    background-color: #000;
    opacity: 0.1;
    content: ' ';
    position: absolute;
    top: 0px;
    right: 0px;
    bottom: 0px;
    left: 0px;
}

It works because the :after pseudo element renders inside the element which it is meant to come after, by then positioning and setting this pseudo element to always be the same size as its parent element, you get a parent element with a transparent background.
You should also make sure that you child element has its position property set (because setting the z-index doesn't work without a position property set) and az-index higher than the z-index of the :after pseudo element (1 is fine in this case):
.22 > yourchildelement
{
    position: relative;
    z-index: 1;
}

That should do the trick for you. Here's a jsFiddle, the background is set to be black.


text:
Q: Loading external xml link returns false I am trying to get the European Central Bank currency values like this
simplexml_load_file("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml")

But this returns false.
I have tried with these answers first, second
Both doesn't work for me and can't really understand what is causing the problem.

A: $object = simplexml_load_file("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
var_dump($object);

Do the php configuration changes in php.ini:
allow_url_fopen = on//if it "off"
If Above code does not work check below process:
var_dump(ini_get('allow_url_fopen'));//print this if it return false or 0
Do the code with CURL php.


text:
Q: Problems of greatest integer fuction. How to show that, if $I$ is integer, then

*

*If $\lfloor\phi(x)\rfloor \geq I$, then $\phi(x)\geq I$.

*If $\lfloor\phi(x)\rfloor \leq I$, then $\phi(x)\ < I+1$.

*If $\lfloor\phi(x)\rfloor \ > I$, then $\phi(x)\geq I+1$.

Proof:
(1).let $\lfloor\phi(x) \rfloor  = m$.
Then $ m\leq \phi(x)<m+1$ so $ I\leq m\leq \phi(x)<m+1\implies I\leq \phi(x)$.
(2).let $\lfloor \phi(x) \rfloor =  m$.
Then $ m\leq \phi(x)<m+1$.
Also, $m\leq I\implies 1+m\leq I+1.$
So $\phi(x)<I+1$.
Hence, $\lfloor \phi(x) \rfloor \leq I$, then $\phi(x)\ < I+1$.
I'm not getting how to prove (3)  part.
I've to teach my younger brother,i've to ask-"What should be the motivation for the introduction of greatest integer function?".
Also,how can i explain the concept of greatest integer function to an ordinary lay man?

A: For part $(3)$ and $(4)$ -
$$\lfloor x \rfloor < I+1 \implies \lfloor x \rfloor \le I \tag3$$
$$\lfloor x \rfloor > I \implies \lfloor x \rfloor \ge I+1\tag 4$$
Let me explain this through an example. If $n$ is an integer, and if it is less than 5, then it's maximum value can be the greatest integer less than $5$ (Since it is less than $5$, and also an integer, so it's values will 'jump' on the number line on the integers), that is none other than $4$. Hence $$n < 5 \implies n \le 4 , ~\text{if} ~n \in \mathbb Z$$
Similarly we can explain $(4)$.

A: From the definition of the floor function, we have always
$$\lfloor x\rfloor\le x<\lfloor x\rfloor+1.$$
Then

*

*$I\le\lfloor x\rfloor\implies I\le\lfloor x\rfloor\le x$

*$\lfloor x\rfloor\le I\implies x<\lfloor x\rfloor+1\le I+1$

*$I<\lfloor x\rfloor\implies I+1\le\lfloor x\rfloor$ because $\lfloor x\rfloor$ is an integer. Then 1.

*$\lfloor x\rfloor<I\implies \lfloor x\rfloor\le I-1$ because $\lfloor x\rfloor$ is an integer. Then 2.


text:
Q: How to pass data to ajax function with json? I need to get an id from the URL , comment value from textbox, save it to database and show on page with ajax.
Im not sure how should look correct syntax in my controller and ajax function.
Controller
 [HttpPost]
    public JsonResult AddComment(int id, string comment)
    {
        if (ModelState.IsValid)
        {
            return Json(true); // what should be here
        }
        return Json(true);
    }

Ajax
    $('#submit').click(function () {
        $.ajax({
            url: '/Form/AddComment',
            method: 'POST',
            data: {
                id: 4,               //how to get id from url?
                comment: 'test'      //how to get textbox value?
            },
            success: function (data) {
                console.log(data)
            },
            error: function (a, b, c) {
                console.log('err')
            }
        })
    });

this just show me that it work but i dont know how to move forward

A: Based upon your requirement, you would have to do the appropriate form handling at client side in order to get your variables like id and comment. You can use strongly typed model binding to get your form values and process them on submit or you can use JavaScript techniques to process your form variables. To extract out id from a URL, you can use a Regular Expression or other JavaScript string parsing techniques. I am giving you a simple example of getting your id from a URL and comment from a text box using JavaScript:
Your input control would look like:
<input type="text" id="commentBox" name="Comment" class="form-control" />

In order to achieve your desired functionality using AJAX to POST your form variables to controller, refer to the following code snippet:
AJAX:
<script type="text/javascript">

var url = 'http://www.example.com/4'; //Example URL string
var yourid = url.substring(url.lastIndexOf('/') + 1);
var yourcomment= document.getElementById('commentBox').value;

var json = {
            id: yourid, //4
            comment: yourcomment
           };

$('#submit').click(function (){
    $.ajax({
        url: '@Url.Action("AddComment", "Form")',
        type: "POST",
        dataType: "json",
        data: { "json": JSON.stringify(json)},
        success: function (data) {
         console.log(data)
         },
         error: function (data) {
         console.log('err')
         },
    });
};
</script>

And you can get your values in your Controller like this:
using System.Web.Script.Serialization;

[HttpPost]
public JsonResult AddComment(string json)
{
    if (ModelState.IsValid)
    {
        var serializer = new JavaScriptSerializer();
        dynamic jsondata = serializer.Deserialize(json, typeof(object));

        //Get your variables here from AJAX call
        string id= jsondata["id"];
        string comment=jsondata["comment"];

        // Do something here with your variables.
    }
    return Json(true);
}

A: My solution looks like this:
controller:
       [HttpPost]
    public JsonResult AddComment(int id_usr,string comment)
    {
        if (ModelState.IsValid)
        {
            Comments kom = new Comments();
            kom.DateComment = DateTime.Now;
            kom.Id_usr = id_usr;
            kom.Comment = comment;
            db.Comments.Add(kom);
            db.SaveChanges();
            return Json(kom);
        }
        return Json(null);

    }

View
var url = window.location.pathname;
var idurl = url.substring(url.lastIndexOf('/') + 1);
$('#submit').click(function () {
        console.log('click')
        $.ajax({
            url: '/form/AddComment',
            method: 'POST',
            data: {
                comment: $("#Comments_Comment").val(),
                id_usr: idurl,
            },
            success: function (data) {
                console.log(data),

thank you all for guiding me to the solution


text:
Q: Openpyxl Copying Formula in Specific Column I am attempting to pull down a formula located in cell E2 through the rest of the "E" column, but I can't quite figure out how to. My current code adds the cells in the E column to the cells in the "D" column which is not what I want.
Current Code:
#Copy Formulae
pathway = glob.glob("Updated Workbook.xlsx") #Pulls filename
pathway = ''.join(pathway)
w_b = load_workbook(pathway) #Pulls workbook using filename
w_s = w_b['Sheet 1'] #Sets worksheet to pull formula through
for row, cellObj in enumerate(list(w_s.columns)[4]): #Iterates through the rows to pull formulae down through cells
    if row != 0: #Causes header row to be skipped
        n = '=(D%d*E%d)' % (row + 1, row + 1)
        cellObj.value = n
w_b.save('Copied Formulae.xlsx')


text:
Q: How to recreate the elipsis components in vue3? I try to recreate the ellipsis components in naive-ui css library for vue3, here are the source code and demo codesandbox
https://github.com/tusen-ai/naive-ui/blob/main/src/ellipsis/src/Ellipsis.tsx
https://codesandbox.io/s/pne1kq
I spent a lot of time watching the source code, for now I figure out most of the source code.
But one thing I can't trace is where
s the logic  they judge how long should make the tooltip appeared and make the text to have ... at the end.
Can someone help trace which part the logic exist in the above link ?

A: The ... is set through style declarations on the parent element. Look at the computed property ellipsisStyleRef, particularly where the value of textOverflow is set (line 66):
export default defineComponent({
  ...
  setup (props, { slots, attrs }) {
    ...
    const ellipsisStyleRef = computed(() => {
      const { lineClamp } = props
      const { value: expanded } = expandedRef
      if (lineClamp !== undefined) {
        return {
          textOverflow: '',
          '-webkit-line-clamp': expanded ? '' : lineClamp
        }
      } else {
        return {
          textOverflow: expanded ? '' : 'ellipsis',  // <------------- here
          '-webkit-line-clamp': ''
        }
      }
    })

As to length, I am not sure if you mean width or duration. But it looks like there is no duration, the tooltip is shown as long as mouse hovers over trigger, and width does not seem to be restricted.


text:
Q: How to pass password when switching user via su username in one line I have an ec2 instance , I connect to it and do the following:
[userA@ip-abcd ~]$ ssh my_ec2_instance
[userA@ip-abcd ~]$ whoami
userA
[userA@ip-abcd ~]$pwd
/home/userA
[userA@ip-abcd ~]$ cd ~
[userA@ip-abcd ~]$ pwd
/home/userA
[userA@ip-abcd ~]$ ls
(shows nothing)
[userA@ip-abcd ~]$ su userB
Password:
(I enter the password and the prompt changes to)

bash-4.2$ pwd
/home/UserA

bash-4.2$ cd ~
bash-4.2$ ls
A B C D

How do I
su - userB and enter password in a single line in a non interactive way?
Why I need to do above:
Above folder B has code which I need to update from git, and I want to call from a jenkins shell script which would

*

*ssh into the instance

*su user B

*auto enter the password

*git pull origin master

*python wsgi.py

What I tried:
1) echo actual_password | su userB
2) su userB -p actual_password

3) echo userBPassword | su -c whoami userB

*^ was the closest where in the terminal I can see userBPassword being entered but nothing happens i.e the userB doesn't get activated.

Is there a way to add the password to the ~/.bash_profile and automatically use that when prompted when the su - userB is executed? as exposing passwords is a bad practice?

A: Is using sudo an option? Then you could do:
echo userBPassword | sudo -S -u userB whoami

A similar question: https://stackoverflow.com/questions/233217/how-to-pass-the-password-to-su-sudo-ssh-without-overriding-the-tty

A: You could use keys to avoid passwords. Generate a key pair as userB on your ec2 machine - copy the private key to the machine you login from and store in userA/.ssh/id_rsa_userB_ec2
Edit UserA/.ssh/config to add a new entry like
Host ec2
        Hostname my_ec2_instance
        Port 22
        User userB
        IdentityFile ~/.ssh/id_rsa_userB_ec2

On your ec2 machine, add the public key to the authorized_keys file. You should then just be able to login and change id to userB with ssh ec2 using the above alias in the config file


text:
Q: Quote Calculator: Finding the sum of 3 previous calculations returns NaN I've been working on a calculator in Jquery. It's composed of a few initial calcultions that display totals in the frontend.

*

*It calculates the measurements the user inputs and multiplies this with the base product(woocommerce) price to give an initial total.

*It allows users to select various addons such as 'cut outs' and calculates the quantity to come up with a total value for the 'add ons'.

*It allows users to select a few extras such as 'delivery' via input checkboxes which once again calculates them to provide a total cost for the extra touches.

This leaves me with 3 total figures for the calculator so far in their own fields/divs. I've given these each a class of 'sumthree'.
I'm then wanting to add these totals up to make an overall total for the calculator.
I've tried variations such as trying to pull the data using text, value and HTML. They're not all inputs so value didn't seem correct to me. Ive also tried using parseFloat instead of parseInt but no luck so far.
It always pulls NaN, but from what I can tell I correctly declared 'finalquote' in the code at the end. I'm under the understanding this could've been the issue.

        <input id="works-result" value="12" readonly>

Splashback/s

    Width
    <input id="splash-width" type="number" value="0">

        Length
        <input id="splash-length" type="number" value="0">

        Add More

        <input id="splash-result" value="0" readonly>

        Integrity Sink

        <input type="number" class="extraQuantity" value="0"  min="0" max="20" />

        Pop Up Socket Cut Out

        <input type="number" class="extraQuantity" value="0"  min="0" max="20" />

        /** 1ST Total I'm Trying to Add **/

Total: £0.00

            Templating
            <input type="checkbox" value="120.00">

                        Delivery
            <input type="checkbox" value="250.00">

/** 2nd Total I'm trying to add **/
<input id="fittingprice" class="sumthree" type="text" readonly="readonly"/>

   /** 3rd Total I'm trying to add, grabs product price and measurements to calculate the sum **/
£<input id="total-cost" class="sumthree" readonly type="number" min="0" step="0.01" data-number-to-fixed="2" data-number-stepfactor="100">

/** The Total of the 3 other Totals I'm trying to solve **/
£<input id="quotefinal" readonly type="number" min="0" step="0.01" data-number-to-fixed="2" data-number-stepfactor="100">

(function($){
    $('.worktop-calc input').change(function() {
        var area   = $('#works-width').val() * $('#works-length').val()
        $('#works-result').val(area)
    })
    $('.splashback-calc input').change(function() {
        var area   = $('#splash-width').val() * $('#splash-length').val()
        $('#splash-result').val(area)
    })
    $('.clonebutton').first().click(function(event) {
    event.preventDefault();
    $( ".splashback-row" ).clone().appendTo( ".splashback-row" );
    });

$( '.variations_form' ).each( function() {
    jQuery(this).on( 'found_variation', function( event, variation ) {
        console.log(variation);//all details here
        var price = variation.display_price;//selectedprice
        console.log(price);
        var totalcost = (price) * $('#works-result').val()
        $('#total-cost').val(totalcost)
    });

var updateTotal = function() {

var sumtotal;
   var sum = 0;
//Add each product price to total
$(".extraproduct").each(function() {
    var extra_price = $(this).data('price');
    var quantity = $('.extraQuantity', this).val();

    //Total for one product
    var subtotal = extra_price*quantity;
     //Round to 2 decimal places.
    subtotal = subtotal.toFixed(2);
    //Display subtotal in HTML element
    $('.productTotal', this).html(subtotal);
});
// total
   $('.productTotal').each(function() {
    sum += Number($(this).html());
});
$('#sum').html(sum.toFixed(2));
};
 //Update total when quantity changes
$(".extraQuantity").bind("keyup change", function() {
updateTotal();
});
//Update totals when page first loads
updateTotal();
// set this from local
$('span.productTotal').each(function() {
    $(this).before("£")
});
// unit price
$('.extraproduct span').each(function() {
   var $price = $(this).parents("div").data('price');
  $(this).before($price);
});

$('input[type="checkbox"]').change(function(){
var totalprice = 0;
$('input[type="checkbox"]:checked').each(function(){
    totalprice= totalprice + parseInt($(this).val());
});
$('#fittingprice').val(totalprice);
});

// THE BIT THAT SHOULD OUTPUT THE SUM OF THE 3 TOTALS
$("span, .sumthree").change(function(){
  var finalquote = 0;
    $(".sumthree").each(function() {
       finalquote = finalquote + parseInt($(this).html());
    });
    $('#quotefinal').val(finalquote);
    console.log(finalquote);
  });

});
})(jQuery)

I've cut down the HTML so it's a bit more understandable. I've included a JSFiddle to see the full code if needed. https://jsfiddle.net/DigitalAdam/c2jpawy4/2/
If you think I need to cut the JS down more, please let me know and I'll see what I can do. I'm new to doing calculators in Jquery and due to the nature of the calculator the above code all seemed relevant to me.
Regards

A: From what I remember JQuery's val() function returns a string. Try passing your values to parseInt() to get integers so you can do calculations.
parseInt($('#works-width').val()) etc...
Update: $('.variations_form').each block wraps most of your code. close it before you declare updateTotal to fix most functionality. Still working on the final though.


text:
Q: Error ticks are misplaced in stacked xbar plot pgfplots I am trying to plot two stacked x bar plots with error bars.
Everything works fine in the left plot, while in the right plot the markers of the error bar are misplaced even though I use the exact same code for the image. Any ideas how this can be avoided? Thank you.
\documentclass{article}
\usepackage{pgfplots}
\colorlet{C0}{blue!20}
\usetikzlibrary{positioning}

\begin{document}
\begin{tikzpicture}[
data/.style={
    inner sep=0pt
    }
]
\def\figwid{.4}
\def\figsep{.05}
\def\figseph{0.1}

\def\yoneone{.12}
\def\yonetwo{-.12}
\def\ytwoone{-.88}
\def\ytwotwo{-1.12}
\def\ythreeone{-1.88}
\def\ythreetwo{-2.12}

%%%%%%%%%%%%%%%%%%% R2
\node[
    data
] (R2)
{
    \begin{tikzpicture}[
        inner sep=0.333em,
        outer sep=0.5\pgflinewidth
        ]
        \begin{axis}[
            xbar stacked,
            legend style={
                legend columns = 4,
                at={(.5,-0.35)},anchor=north,
                draw=none,
                font=\footnotesize
                },
            ytick={0,-1,-2},
            draw = none,
            bar width= 3mm,
            axis y line*=none,
            axis x line*=bottom,
            yticklabels = {N1, M, H},
            xlabel={$R_2\quad[\mathrm{s^{-1}}]$},
            width=\figwid\textwidth,
            ]
            \addplot[C0,fill=C0,error bars/.cd, x dir=both, x explicit, error bar style =blue] coordinates
                {(0,\yoneone)
                (44,\yonetwo) += (9,0) -=(9,0)
                (0,\ytwoone)
                (43,\ytwotwo) += (5,0) -=(5,0)
                (0,\ythreeone)
                (51, \ythreetwo) += (12,0) -=(12,0)
                };

        \end{axis}

    \end{tikzpicture}
};

\node[
    data,
    right = \figsep\textwidth of R2.east,
    anchor = west,
] (R2p)
{
    \begin{tikzpicture}[
        inner sep=0.333em,
        outer sep=0.5\pgflinewidth
        ]
        \begin{axis}[
            xbar stacked,
            legend style={
                legend columns = 4,
                at={(.5,-0.35)},anchor=north,
                draw=none,
                font=\footnotesize
                },
            ytick={0,-1,-2},
            draw = none,
            bar width= 3mm,
            axis y line*=none,
            axis x line*=bottom,
            yticklabels = {N1, M, H},
            xlabel={$R_2\quad[\mathrm{s^{-1}}]$},
            width=\figwid\textwidth,
            ]
            \addplot[C0,fill=C0,error bars/.cd, x dir=both, x explicit, error bar style =blue] coordinates
                {(0,\yoneone)
                (44,\yonetwo) += (9,0) -=(9,0)
                (0,\ytwoone)
                (43,\ytwotwo) += (5,0) -=(5,0)
                (0,\ythreeone)
                (51, \ythreetwo) += (12,0) -=(12,0)
                };

        \end{axis}

    \end{tikzpicture}
};
\end{tikzpicture}
\end{document}

A: Nesting tikzpictures will often lead to problems, as it does here. But it's also not at all necessary to do it here. Place the second axis  by using the at key, for example as in the code below. You could also look at the groupplots library.

\documentclass{article}
\usepackage{pgfplots}
\colorlet{C0}{blue!30}
\begin{document}
\begin{tikzpicture}[
data/.style={
    inner sep=0pt
    }
]
\def\figwid{.4}
\def\figsep{.05}
\def\figseph{0.1}

\def\yoneone{.12}
\def\yonetwo{-.12}
\def\ytwoone{-.88}
\def\ytwotwo{-1.12}
\def\ythreeone{-1.88}
\def\ythreetwo{-2.12}

        \begin{axis}[
            name=ax1,
            xbar stacked,
            legend style={
                legend columns = 4,
                at={(.5,-0.35)},anchor=north,
                draw=none,
                font=\footnotesize
                },
            ytick={0,-1,-2},
            draw = none,
            bar width= 3mm,
            axis y line*=none,
            axis x line*=bottom,
            yticklabels = {N1, M, H},
            xlabel={$R_2\quad[\mathrm{s^{-1}}]$},
            width=\figwid\textwidth,
            ]
            \addplot[C0,fill=C0,error bars/.cd, x dir=both, x explicit, error bar style =blue] coordinates
                {(0,\yoneone)
                (44,\yonetwo) += (9,0) -=(9,0)
                (0,\ytwoone)
                (43,\ytwotwo) += (5,0) -=(5,0)
                (0,\ythreeone)
                (51, \ythreetwo) += (12,0) -=(12,0)
                };

        \end{axis}

        \begin{axis}[
            at={([xshift=\figsep cm]ax1.outer east)},anchor=outer west,
            xbar stacked,
            legend style={
                legend columns = 4,
                at={(.5,-0.35)},anchor=north,
                draw=none,
                font=\footnotesize
                },
            ytick={0,-1,-2},
            draw = none,
            bar width= 3mm,
            axis y line*=none,
            axis x line*=bottom,
            yticklabels = {N1, M, H},
            xlabel={$R_2\quad[\mathrm{s^{-1}}]$},
            width=\figwid\textwidth,
            ]
            \addplot[C0,fill=C0,error bars/.cd, x dir=both, x explicit, error bar style =blue] coordinates
                {(0,\yoneone)
                (44,\yonetwo) += (9,0) -=(9,0)
                (0,\ytwoone)
                (43,\ytwotwo) += (5,0) -=(5,0)
                (0,\ythreeone)
                (51, \ythreetwo) += (12,0) -=(12,0)
                };

        \end{axis}

    \end{tikzpicture}
\end{document}


text:
Q: Lambda from docker container instead of zip: what is faster? AWS Lambda recently added the option to create functions from docker containers (small warning: the ECR needs to be in the same account for now). I was wondering: except for all the advantages of docker over random ZIPs, is this also quicker to start, or quicker to call?

A: I have just used a Lambda container for a big API project in my company and I haven't personally seen slow downs in start time. I would believe that it may take a few more milliseconds to boot, but I think is negligible.
You could test it printing the times in CloudWatch, but I would avoid going to the Docker route if it's not needed because of all the pain that it is setting it up and getting a nice testing environment.
In relation to other pros and cons, I could write a whole essay here. Each has its perks, but as of a rule of thumb, only use the Dockerized Lambda if you really need it.

A: They'll take the same amount of time to call.


text:
Q: Cannot load module 'Arkit' as 'ARKit'
Arkit module is not loading even added in linked frameworks and libraries.

A: Just rename your module, it's conflict with framework name :)

A: Never call your project using the same name as the framework has (like ARKit, Vision, or RealityKit). It doesn't matter what character you're using uppercased or lowercased. It causes a serious conflict and your project won't start in such a case.

A: Compiler is unable to distinguish between your project name 'Arkit' and apple framework 'ARKit'.

Project name is not case sensitive.

Better create a project with a different name.


text:
Q: How can I query XPath matching an attribute from one tag against another attribute from another tag? I'm scripting a web app that has labels for input fields. EG:
<label for="surname">Family Name:</label>...<input id="surname" ...></input>

I'd like to be able to write an XPath expression that takes the text "Family Name:" to match the label, then takes the "for" attribute from the label and uses that to find the associated input tag by matching its "id" tag.
I can make this "work" as follows:
//label[contains(.,"Family Name:")]/following::input[1]

However, for this web app I think it would be more reliable to match for/id. (EG: How can I be sure that in all possible layouts  the first input tag following the label is the one I want? And what happens if somewhere down the line this page is rendered using a right-to-left script?
My ultimate aim is to create a library function that we can use to write QA scripts in advance of web pages to test against, when all we have is a picture or document with an input field labelled "Family Name:" and no idea what id some programmer will ultimately assign to the field.

A: Maybe this is what you're looking for?
//input[@id = //label[contains(., "Family Name:")]/@for]

As for your ultimate goal, you may want to take a look at the XPath gem for Ruby. Some of what you're doing may already be implemented there. (Specifically, check out the library's HTML Helpers)


text:
Q: Using Moq to Validate Separate Invocations with Distinct Arguments I'm trying to validate the values of arguments passed to subsequent mocked method invocations (of the same method), but cannot figure out a valid approach.  A generic example follows:
public class Foo
{
    [Dependency]
    public Bar SomeBar
    {
        get;
        set;
    }

    public void SomeMethod()
    {
        this.SomeBar.SomeOtherMethod("baz");
        this.SomeBar.SomeOtherMethod("bag");
    }
}

public class Bar
{
    public void SomeOtherMethod(string input)
    {
    }
}

public class MoqTest
{
    [TestMethod]
    public void RunTest()
    {
        Mock<Bar> mock = new Mock<Bar>();
        Foo f = new Foo();
        mock.Setup(m => m.SomeOtherMethod(It.Is<string>("baz")));
        mock.Setup(m => m.SomeOtherMethod(It.Is<string>("bag"))); // this of course overrides the first call
        f.SomeMethod();
        mock.VerifyAll();
    }
}

Using a Function in the Setup might be an option, but then it seems I'd be reduced to some sort of global variable to know which argument/iteration I'm verifying.  Maybe I'm overlooking the obvious within the Moq framework?

A: Not that I was completely wrong or Termite too tolerant,
but the better answer is demonstrated by the following code:
public interface IA
    {
        int doA(int i);
    }
    public class B
    {
        private IA callee;
        public B(IA callee)
        {
            this.callee = callee;
        }
        public int doB(int i)
        {
            Console.WriteLine("B called with " + i);
            var res = callee.doA(i);
            Console.WriteLine("Delegate returned " + res);
            return res;
        }
    }
    [Test]
    public void TEST()
    {
        var mock = new Mock<IA>();
        mock.Setup(a => a.doA(It.IsInRange(-5, 100, Range.Exclusive))).Returns((int i) => i * i);
        var b = new B(mock.Object);
        for (int i = 0; i < 10; i++)
        {
            b.doB(i);
        }

        mock.Verify(a => a.doA(It.IsInRange(0, 4, Range.Inclusive)), Times.Exactly(5));
        mock.Verify(a => a.doA(It.IsInRange(5, 9, Range.Inclusive)), Times.Exactly(5));
        mock.Verify(a => a.doA(It.Is<int>(i => i < 0)), Times.Never());
        mock.Verify(a => a.doA(It.Is<int>(i => i > 9)), Times.Never());
        mock.Verify(a => a.doA(It.IsInRange(3, 7, Range.Inclusive)), Times.Exactly(5));

        // line below will fail
        // mock.Verify(a => a.doA(It.IsInRange(3, 7, Range.Inclusive)), Times.Exactly(7));
    }

This shows that the setup is completely separated from validation. In some cases it means that argument matching has to be done twice :(


text:
Q: Flash copy to clipboard bug I am trying to apply Copy to clipboard to my website, but there seems to be a bug because the text is not getting copied on my website.
Clipboard.swf : Using this for copying
My website: FileLnx (please upload then click on a text field for copy)

A: This should answer your question:
http://www.adobe.com/devnet/flashplayer/articles/fplayer10_security_changes.html#head31

In Flash Player 9, ActionScript could
  set data on the system Clipboard at
  any time. With Flash Player 10, the
  System.setClipboard() method may be
  successfully called only through
  ActionScript that originates from user
  interaction. This includes actions
  such as clicking the mouse or using
  the keyboard. This user interaction
  requirement also applies to the new
  ActionScript 3.0
  Clipboard.generalClipboard.setData()
  and
  Clipboard.generalClipboard.setDataHandler()
  methods.


text:
Q: UIDatePicker is returning with instantiated dateTime's seconds in all dates..? The date returned from a UIDatePicker includes seconds. Why? If I select the date "Today, 1:07 pm" and click a button to print out the selected date, I get 2019-06-13 13:07:07 +0000. If I change the date to something else, I get e.g 2019-06-14 14:35:07 +0000. Why are those :07 seconds present? Still the same seconds. If I run the app again, it might be some completely different seconds.
It seems as it stores the number of seconds since the datePicker was initialized, for some reason. So if I restart the app at 14:07:34, then all the times selected in the datePicker will show xx:xx:34. Always the same seconds throughout its lifetime.
The documentation states date: The date displayed by the date picker. These seconds are not displayed. Why are these seconds included?
How do I prevent the datepicker from returning these useless seconds? They are actually making it so people miss their bus, in our case.
I know I can do a "workaround" by flatting the resulting date to remove its seconds, but this feels like it's either a bug or a setting I don't know about.

A: From the UIDatePicker.h file:
// default is current date when picker created.
@property (nonatomic, strong) NSDate *date;

This is the hint to different seconds on each instance of date picker.
UIDatePicker just fulfils its datasource forwards and backwards from the current time when it is instantiated.
In order to make proper flooring of the date in the way you like, assign to the date property the value which is floored, and picker will report results with the same flooring.


text:
Q: iOS Development: Can I store an array of integers in a Core Data object without creating a new table to represent the array? I'm using Core Data and I'm trying to figure out the simplest way to store an array of integers in one of my Core Data entities.  Currently, my entities contain various arrays of objects that are more complex than a single number, so it makes sense to represent those arrays as tables in my DB and attach them using relationships.  If I want to store a simple array of integers, do I need to create a new table with a single column and attach it using a one-to-many relationship?  Or is there a more simple way?
Thanks in advance for your wisdom!

A: Chris Hanson already gave a good answer to this question, still if you really want to store the NSArray as Core Data attribute take a look at transformable attributes

A: For an array of integers, I would use a Binary property - which is an NSData. NSData has a lot of accessor/modifier methods. If you need/want to keep an mutable copy, then you can use NSMutableData as a cache - and persist that (as an NSData) as makes sense.
I use this for long lists of doubles - which, for me, represent collected data sets. This works for me because I have no need to link a single data point to some other object in my model. At runtime, I unpack these data sets and use them to render graph lines. At that point, I could generate some sort of relatedness - but that relatedness would need to be derived.


text:
Q: Can magnets be used to create perpetual motion? I have heard that magnets do not possess energy and can only help control it. Also, the first law of thermodynamics says that energy can neither be created nor be destroyed and hence making a perpetual motion machine is virtually impossible as we cannot elude friction.
But consider this example. If we take a permanent magnet and tie it to a stationary rod or support with a thread or clamp and then place some magnetic material like a piece of iron near it, the piece of iron will get attracted.
Since 'work done = force applied x distance moved', here there is a force applied and the piece of iron has moved quite a bit towards the magnet. And also, when work is done, there should be energy spent and hence shouldn't it be right to say that magnets possess energy? And if that is right, it would totally violate the 1st law of thermodynamics.

A: No, you can't generate energy from nothing (the only way is via the Heisenberg uncertainty principle but you have to "return it to the space-time").
That energy that you are taking is from the magnetic field of the magnet. You can read more about this subject in Jackson, John David (1998), Classical Electrodynamics.


text:
Q: Rendering images using GPU In one of the existing C# Winform program, an image is displayed. Unfortunately, I do not have access to the image display code but I know that there is a separate viewer, which uses DirectX to render the image.
PROBLEM: Now I have upgraded the camera to 4K, and the image display program takes approx. 90ms to render the image, which is too much for my application. Therefore, I wanted to test if I can reduce the image rendering time by using a GPU.
Only for testing, I ran the image display program with and without GPU. But it took exactly the same time in both situations. So, I think that DirectX is not automatically utilizing the benefit of GPU.
I am absolutely new to this graphics things and honestly, I am a bit puzzled now.
Question: Do I need to specify to the DirectX to use GPU? Will image rendering time improve by using a GPU? Any sample program where I can test the with/without GPU performance for image displaying task?
System Configuration:

*

*Windows-7 Embedded

*DirectX 11

*AMD GPU (some basic, I will update it details)