text:
Q: java code won't compile warehouse I am having trouble figuring out how to get the method purchaseItems(Warehouse w[]) to work.
Any suggestions as to whether I am passing the w[] array correctly through the nested for loops?
import javax.swing.JOptionPane;

public class WarehouseTest
{

    public static void main(String args[])
    {
        String dataArray[][] = {{ "2200", "10", "5", "5", "First Street", "Dallas", "Texas", "76000"},
                    { "5550", "12.75", "2", "3", "Mitchell Drive", "Arlington", "Texas", "76019"},
                    { "12000", "17.50", "6", "7", "Jones Blvd", "Burleson", "Texas", "76120"},
                    { "7235", "22.35", "54", "80", "Smith Circle", "Keller", "Texas", "75020"},
                    };

        Warehouse wArray[] = new Warehouse[4];

        wArray = createWarehouses(dataArray);

        JOptionPane.showMessageDialog(null, purchaseItems(wArray));
        JOptionPane.showMessageDialog(null, printWarehouses(wArray));
        JOptionPane.showMessageDialog(null, printWarehouseCharge(wArray));

    }

    public static Warehouse[] createWarehouses( String a[][])
    {
        Warehouse w[] = new Warehouse[a.length];

        for( i=0; i<w.length; i++)

        {

            w[i] = new Warehouse(Integer.parseInt(a[i][0]),
                        Double.parseDouble(a[i][1],
                        Integer.parseInt(a[i][2]),
                        Integer.parseInt(a[i][3]),
                        new Address(a[i][4]),
                        (a[i][5]),
                        (a[i][6]),
                        (Integer.parseInt(a[i][7]))));

        }

        return w;

    }

    public static String purchaseItems(Warehouse w[])
    {

        Sring msg = "";

        String data[][] = {{ "Dallas", "1", "2"},
                   { "Arlington", "0", "5"},
                   { "Burleson", "3", "0"},
                   { "Keller", "10", "25"},
                   { "Dallas", "5", "0"},
                   { "Arlington", "0", "1"},
                   { "Burleson", "2", "4"},
                   { "Keller", "0", "30"},
                  };

        for( int i=0; i<data.length;i++)
        {
            for(w=0; i<w.length; w++)
            {

                if (w[i].getAddress().getCity.equals(data[i][0]))
                {

                 String msg += String.format("$%.2f"\n, (w[i].purchaseTelevision(Double.parseDouble(data[i][1], 599.0) + w[i].purchaseComputer(Double.parseDouble(data[i][2], 759.0));

                }
            }

        }

        return msg;

    }

    public static String printWarehouses(Warehouse w[])
    {
        String msg = "";

        for(i=0; i<w.length;i++)

        {

            msg += String.format("%s\n", w[i].toString());

        }

        return msg;

    }

    public static String printWarehouseCharge(Warehouse w[])
    {
        String msg = "";

        for(i=0; i<w.length; i++)
        {

            msg += String.format("$%,.2f\n", w[i].calculateWarehouseCharge());

        }

        return msg;

    }

} // end class WarehouseTest

A: Modified loop:
for( int i=0; i<data.length;i++)
        {
            for(int j=0; j<w.length; j++) // Changed the variable 'w' to 'j'
            {

                if (w[j].getAddress().getCity.equals(data[i][0]))
                {

                 String msg += String.format("$%.2f"\n, (w[i].purchaseTelevision(Double.parseDouble(data[i][1], 599.0) + w[i].purchaseComputer(Double.parseDouble(data[i][2], 759.0));

                }
            }

        }

In the for loop for(w=0; i<w.length; w++) you are assigning int value to array object 'w', hence it is causing the problem.


text:
Q: Dictionary saving last result to every value using BeautifulSoup I am currently in the process of making a web crawler using requests and BeautifulSoup. I am using a for loop to create a list of dictionaries with the values being the href of the a tags. I am having issues doing this however since all of the results will be the last href on that page. Here is the output when I print out the final result:
[{'link': '/terms'}, {'link': '/terms'}, {'link': '/terms'}, {'link': '/terms'}, {'link': '/terms'}, {'link': '/terms'}, {'link': '/terms'}, {'link': '/terms'}, {'link': '/terms'}, {'link': '/terms'}, {'link': '/terms'}, {'link': '/terms'}, {'link': '/terms'}, {'link': '/terms'}, {'link': '/terms'}, {'link': '/terms'}, {'link': '/terms'}]

I am unsure as to why it's doing the last value only. I assume it's because through the last loop, it assigns all keys with the same name to that value. How can I go around fixing this? Here is the code.
import json
import requests
from bs4 import BeautifulSoup

tags_dict = {}
tags_list = []

r = requests.get("http://chicosadventures.com/")

soup = BeautifulSoup(r.content, "lxml")

for link in soup.find_all('a'):
    tags_dict['link'] = link.get('href')
    tags_list.append(tags_dict)

dump = json.dumps(tags_list)
print(dump)

A: Your issue is with tags_dict. You are just storing a reference to that one dictionary again and again in your list, and since its a reference, the last value gets reflected in all entries. I changed it to create a new dict object for each iteration, now it works fine
import json
import requests
from bs4 import BeautifulSoup

tags_list = []
r = requests.get("http://chicosadventures.com/")
soup = BeautifulSoup(r.content, "lxml")

for link in soup.find_all('a'):
    tags_list.append({"link": link.get('href')})

dump = json.dumps(tags_list)
print(dump)

Output:

[{"link": "/"}, {"link": "/about_chico"}, {"link":
  "/about_the_author"}, {"link": "/about_the_illustrator"}, {"link":
  "/chico_in_the_news_"}, {"link": "/order_your_copy"}, {"link":
  "/contact_us"}, {"link": "/about_chico"}, {"link":
  "/about_the_author"}, {"link": "/about_the_illustrator"}, {"link":
  "/chico_in_the_news_"}, {"link": "/order_your_copy"}, {"link":
  "/contact_us"}, {"link": "/privacy"}, {"link": "javascript:print()"},
  {"link": "http://www.ebtech.net/"}, {"link": "/terms"}]

redpajama_set_name: RedPajamaStackExchange


text:
Q: ErrorProvider - Change BackColor Instead of Showing Icon I'm stuck with some legacy code that I want to upgrade a bit. I want to change the way the ErrorProvider shows the error status on a Control. Default behavior is the Icon, and a ToolTip if you hover on the icon.
I would like to change this behavior to be more similar to what we use in our WPF controls. Which is a red back-color(Salmon pink) and the tool-tip on the control itself.
Any tips, links or some way forward
EDIT.
See my answer below, on what i ended up with.

A: ErrorProvider component doesn't support this feature and if you need it you can create it yourself.
You can subscribe to BindingComplete event of a BindingManagerBase and then you can use the event arg which is of type BindingCompleteEventArgs that contains some useful properties:

*

*ErrorText to determine if there is an error in data-binding

*Binding.Control to determine the control which is bounded to

These are enough for us to implement our solution.
Code
Here is a sample code which shows how can you handle BindingComplete event and use it to change BackColor and tool-tip of a control based on it's valid or invalid state.
Suppose you have a binding source, myBindingSource which is bound to a SampleModel class which is implemented IDataErrorInfo. You can subscribe to BindingComplete event of this.BindingContext[this.myBindingSource]:
private void Form1_Load(object sender, EventArgs e)
{
    this.myBindingSource.DataSource = new SampleModel();

    var bindingManager = this.BindingContext[this.myBindingSource];
    bindingManager.BindingComplete += bindingManager_BindingComplete;
}

Dictionary<Control, Color> Items = new Dictionary<Control, Color>();
private void bindingManager_BindingComplete(object sender, BindingCompleteEventArgs e)
{
    var control = e.Binding.Control;
    //Store Original BackColor
    if (!Items.ContainsKey(control))
        Items[control] = control.BackColor;

    //Check If there is an error
    if (!string.IsNullOrEmpty(e.ErrorText))
    {
        control.BackColor = Color.Salmon;
        this.errorToolTip.SetToolTip(control, e.ErrorText);
    }
    else
    {
        e.Binding.Control.BackColor = Items[e.Binding.Control];
        this.errorToolTip.SetToolTip(control, null);
    }
}

A: Thank you Reza Aghaei. This is what i came up with based on your comment and some additional searching... Some of this code comes from msdn resource
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing;
using System.Linq;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ErrorProvider
{
    class BackgroundColorErrorProvider: Component, IExtenderProvider, ISupportInitialize
    {

        public BackgroundColorErrorProvider()
        {
            currentChanged = new EventHandler(ErrorManager_CurrentChanged);
        }
        public BackgroundColorErrorProvider(ContainerControl parentControl)
            : this()
        {
            this.parentControl = parentControl;
            propChangedEvent = new EventHandler(ParentControl_BindingContextChanged);
            parentControl.BindingContextChanged += propChangedEvent;
        }
        public BackgroundColorErrorProvider(IContainer container)
            : this()
        {
            if (container == null) {
                throw new ArgumentNullException("container");
            }

            container.Add(this);
        }

        public bool CanExtend(object extendee)
        {
            return extendee is Control && !(extendee is Form) && !(extendee is ToolBar);
        }

        private bool inSetErrorManager = false;
        private object dataSource;
        private string dataMember = null;
        private ContainerControl parentControl;
        private BindingManagerBase errorManager;
        private bool initializing;
        private EventHandler currentChanged;
        private EventHandler propChangedEvent;
        private Dictionary<Control, Color> originalColor = new Dictionary<Control, Color>();
        private Color errorBackgroundColor;

        public ContainerControl ContainerControl
        {
            [UIPermission(SecurityAction.LinkDemand, Window = UIPermissionWindow.AllWindows)]
            [UIPermission(SecurityAction.InheritanceDemand, Window = UIPermissionWindow.AllWindows)]
            get
            {
                return parentControl;
            }
            set
            {
                if (parentControl != value)
                {
                    if (parentControl != null)
                        parentControl.BindingContextChanged -= propChangedEvent;

                    parentControl = value;

                    if (parentControl != null)
                        parentControl.BindingContextChanged += propChangedEvent;

                    Set_ErrorManager(this.DataSource, this.DataMember, true);
                }
            }
        }

        public string DataMember
        {
            get { return dataMember; }
            set
            {
                if (value == null) value = "";
                Set_ErrorManager(this.DataSource, value, false);
            }
        }

        public object DataSource
        {
            get { return dataSource; }
            set
            {
                if ( parentControl != null && value != null && String.IsNullOrEmpty(this.dataMember))
                {
                    // Let's check if the datamember exists in the new data source
                    try
                    {
                        errorManager = parentControl.BindingContext[value, this.dataMember];
                    }
                    catch (ArgumentException)
                    {
                        // The data member doesn't exist in the data source, so set it to null
                        this.dataMember = "";
                    }
                }
                Set_ErrorManager(value, this.DataMember, false);
            }
        }

        public override ISite Site
        {
            set
            {
                base.Site = value;
                if (value == null)
                    return;

                IDesignerHost host = value.GetService(typeof(IDesignerHost)) as IDesignerHost;
                if (host != null)
                {
                    IComponent baseComp = host.RootComponent;

                    if (baseComp is ContainerControl)
                    {
                        this.ContainerControl = (ContainerControl)baseComp;
                    }
                }
            }
        }
        private ToolTip toolTip;

        public ToolTip ToolTip
        {
            get { return toolTip; }
            set { toolTip = value; }
        }

        public Color ErrorBackgroundColor
        {
            get { return errorBackgroundColor; }
            set { errorBackgroundColor = value; }
        }

        private void Set_ErrorManager(object newDataSource, string newDataMember, bool force)
        {
            if (inSetErrorManager)
                return;
            inSetErrorManager = true;
            try
            {
                bool dataSourceChanged = this.DataSource != newDataSource;
                bool dataMemberChanged = this.DataMember != newDataMember;

                //if nothing changed, then do not do any work
                //
                if (!dataSourceChanged && !dataMemberChanged && !force)
                {
                    return;
                }

                // set the dataSource and the dataMember
                //
                this.dataSource = newDataSource;
                this.dataMember = newDataMember;

                if (!initializing)
                {
                    UnwireEvents(errorManager);

                    // get the new errorManager
                    //
                    if (parentControl != null && this.dataSource != null && parentControl.BindingContext != null)
                    {
                        errorManager = parentControl.BindingContext[this.dataSource, this.dataMember];
                    }
                    else
                    {
                        errorManager = null;
                    }

                    // wire the events
                    //
                    WireEvents(errorManager);

                    // see if there are errors at the current
                    // item in the list, w/o waiting for the position to change
                    if (errorManager != null)
                        UpdateBinding();
                }
            }
            finally
            {
                inSetErrorManager = false;
            }
        }

        public void UpdateBinding()
        {
            ErrorManager_CurrentChanged(errorManager, EventArgs.Empty);
        }

        private void UnwireEvents(BindingManagerBase listManager)
        {
            if (listManager != null)
            {
                listManager.CurrentChanged -= currentChanged;
                listManager.BindingComplete -= new BindingCompleteEventHandler(this.ErrorManager_BindingComplete);

                CurrencyManager currManager = listManager as CurrencyManager;

                if (currManager != null)
                {
                    currManager.ItemChanged -= new ItemChangedEventHandler(this.ErrorManager_ItemChanged);
                    currManager.Bindings.CollectionChanged -= new CollectionChangeEventHandler(this.ErrorManager_BindingsChanged);
                }
            }

        }

        private void WireEvents(BindingManagerBase listManager)
        {
            if (listManager != null)
            {
                listManager.CurrentChanged += currentChanged;
                listManager.BindingComplete += new BindingCompleteEventHandler(this.ErrorManager_BindingComplete);

                CurrencyManager currManager = listManager as CurrencyManager;

                if (currManager != null)
                {
                    currManager.ItemChanged += new ItemChangedEventHandler(this.ErrorManager_ItemChanged);
                    currManager.Bindings.CollectionChanged += new CollectionChangeEventHandler(this.ErrorManager_BindingsChanged);
                }
            }
        }

        private void ErrorManager_BindingsChanged(object sender, CollectionChangeEventArgs e)
        {
            ErrorManager_CurrentChanged(errorManager, e);
        }

        private void ParentControl_BindingContextChanged(object sender, EventArgs e)
        {
            Set_ErrorManager(this.DataSource, this.DataMember, true);
        }

        private void ErrorManager_ItemChanged(object sender, ItemChangedEventArgs e)
        {
            BindingsCollection errBindings = errorManager.Bindings;
            int bindingsCount = errBindings.Count;

            // If the list became empty then reset the errors
            if (e.Index == -1 && errorManager.Count == 0)
            {
                for (int j = 0; j < bindingsCount; j++)
                {
                    if ((errBindings[j].Control != null))
                    {
                        // ...ignore everything but bindings to Controls
                        SetError(errBindings[j].Control, "");
                    }
                }
            }
            else
            {
                ErrorManager_CurrentChanged(sender, e);
            }
        }

        private void SetError(Control control, string p)
        {
            if (String.IsNullOrEmpty(p))
            {
                if (originalColor.ContainsKey(control))
                    control.BackColor = originalColor[control];
                toolTip.SetToolTip(control, null);
            }
            else
            {
                control.BackColor = ErrorBackgroundColor;
                toolTip.SetToolTip(control, p);
            }
        }

        private void ErrorManager_BindingComplete(object sender, BindingCompleteEventArgs e)
        {
            Binding binding = e.Binding;

            if (binding != null && binding.Control != null)
            {
                SetError(binding.Control, (e.ErrorText == null ? String.Empty : e.ErrorText));
            }
        }

        private void ErrorManager_CurrentChanged(object sender, EventArgs e)
        {
            if (errorManager.Count == 0)
            {
                return;
            }

            object value = errorManager.Current;
            if (!(value is IDataErrorInfo))
            {
                return;
            }

            BindingsCollection errBindings = errorManager.Bindings;
            int bindingsCount = errBindings.Count;

            // We can only show one error per control, so we will build up a string...
            //
            Hashtable controlError = new Hashtable(bindingsCount);

            for (int j = 0; j < bindingsCount; j++)
            {

                // Ignore everything but bindings to Controls
                if (errBindings[j].Control == null)
                {
                    continue;
                }

                string error = ((IDataErrorInfo)value)[errBindings[j].BindingMemberInfo.BindingField];

                if (error == null)
                {
                    error = "";
                }

                string outputError = "";

                if (controlError.Contains(errBindings[j].Control))
                    outputError = (string)controlError[errBindings[j].Control];

                // VSWhidbey 106890: Utilize the error string without including the field name.
                if (String.IsNullOrEmpty(outputError))
                {
                    outputError = error;
                }
                else
                {
                    outputError = string.Concat(outputError, "\r\n", error);
                }

                controlError[errBindings[j].Control] = outputError;
            }

            IEnumerator enumerator = controlError.GetEnumerator();
            while (enumerator.MoveNext())
            {
                DictionaryEntry entry = (DictionaryEntry)enumerator.Current;
                SetError((Control)entry.Key, (string)entry.Value);
            }
        }

        public void BeginInit()
        {
            initializing = true;
        }

        public void EndInit()
        {
            initializing = false;
            Set_ErrorManager(this.DataSource, this.DataMember, true);
        }
    }
}


text:
Q: How to pipe Writable Buffer to a ReadStream? How can I take a writable stream and return a readable stream from a buffer?
I have the following to write the data that comes from an ftp server to an array of chunks:
let chunks = []
let writable = new Writable
writable._write = (chunk, encoding, callback) => {
  chunks.push(chunk)
  callback()
}

I am then creating a new readstream:
let readable = new ReadStream()

I then tried to pipe the writable to the readable but that doesn't seem to work:

Argument of type 'ReadStream' is not assignable to parameter of type 'WritableStream'.

writable.pipe(readable)

Here is the entire method:
export class FTP {
  readStream(filePath, options = {}) {
    let conn = this.getConnection(this.name)
    if (!conn) return Buffer.from('')
    filePath = this.forceRoot(filePath)
    let chunks = []
    let writable = new Writable
    writable._write = (chunk, encoding, callback) => {
      chunks.push(chunk)
      callback()
    }
    let readable = new ReadStream()

    conn.client.download(writable, filePath, options.start || undefined)
    writable.pipe(readable)
    return readable
  }
}

I then read from the stream and pipe the output to the response object created from http.createServer() like this:
      let stream = store.readStream(file, { start, end })
        .on('open', () => stream.pipe(res))
        .on('close', () => res.end())
        .on('error', err => res.end(err))

A: Yep, Node.js streams are hard to grasp. Logically, you don't need two streams here. If you want to read from your FTP class as from a stream, you just need to implement a single readable stream. Check this section of the docs out to have an idea how to implement a readable stream from scratch:
class SourceWrapper extends Readable {
  constructor(options) {
    super(options);

    this._source = getLowLevelSourceObject();

    // Every time there's data, push it into the internal buffer.
    this._source.ondata = (chunk) => {
      // If push() returns false, then stop reading from source.
      if (!this.push(chunk))
        this._source.readStop();
    };

    // When the source ends, push the EOF-signaling `null` chunk.
    this._source.onend = () => {
      this.push(null);
    };
  }
  // _read() will be called when the stream wants to pull more data in.
  // The advisory size argument is ignored in this case.
  _read(size) {
    this._source.readStart();
  }
}

However, from your example, I can conclude, that conn.client.download() expects a writable stream as an input parameter. In such case you just can take a standard PassThrough stream which is a duplex (i.e. writable on the left and readable on the right side) stream with no transformation applied:
const { PassThrough } = require('stream');

export class FTP {
  readStream(filePath, options = {}) {
    let conn = this.getConnection(this.name);
    if (!conn) return Buffer.from('');
    filePath = this.forceRoot(filePath);

    const pt = new PassThrough();
    conn.client.download(pt, filePath, options.start);
    return pt;
  }
}

You can find more information on Node.js streams here and here.
UPD: Usage example:
// assume res is an [express or similar] response object.
const s = store.readStream(file, { start, end });
s.pipe(res);

A: Pipe works the other way round as you're thinking. According to Node.js's documentation, pipe() is a method of Readable, and it accepts a Writable as its destination. What you were trying to do was pipe a Writable to a Readable, but actually it's a Readable that can be piped to a Writeable, not the other way round.
Try passing a PassThrough to download() and return that same PassThrough?


text:
Q: Short-circuiting a condition statement I wrote a function:
# given a n x m grid return how many different ways there are to move from top left to
# bottom right by only being able to move right or down

def grid(n, m, memo = {}):
    if f'{n},{m}' in memo:
        return memo[f'{n},{m}']

    if n == 1 and m == 1:
        return 1

    if n == 0 or m == 0:
        return 0

    memo[f'{n},{m}'] = grid(n,m-1,) + grid(n-1,m)

    return grid(n,m-1,) + grid(n-1,m)

Recently I read a bit about short-circuiting in Python and I am trying to understand it further.
As I understand it does not provide any boost in runtime, just sort of syntax sugar.
For example:
1 < 2 < 3 # is True
1 < 2 and 2 < 3 # is also True

# hence
(1 < 2 < 3) == 1 < 2 and 2 < 3 # is True

I was wondering can I write my function with this kind of short-circuiting in my if statements?
I came up with this:
 def grid(n, m, memo = {}):
    if f'{n},{m}' in memo:
        return memo[f'{n},{m}']

    if (n or m) == 1:
        return 1

    if (n and m) == 0:
        return 0

    memo[f'{n},{m}'] = grid(n,m-1,) + grid(n-1,m)

    return grid(n,m-1,) + grid(n-1,m)

Is there any smarter way of using the short-circuit here?

A: (1 < 2 < 3) is not short-circuiting - I think you misunderstood the meaning of the term. You are correct that it is merely syntax sugar - although it can produce some very weird results in obscure cases. (1 < 2 < 3) expands to (1 < 2) and (2 < 3) - the middle operand is copied to both and and is used for the joining operator.
Short circuiting occurs when python already knows the answer to a boolean expression, even before calculating both the inputs. For example
def false():
    print("false")
    return False

def true():
    print("true")
    return True

print(false() and true())

The output would be
false
False

Because when python sees False and, it already knows that the result is False (because and requires both operands to be True), so it doesn't bother running the second half of the line.
This real short circuiting does result in a performance boost, but since you can't turn off short circuiting, it doesn't really matter ¯\_(ツ)_/¯

A: if (n or m) == 1

evaluates to
if (<bool>) == 1  # e.g. if {True,False} == 1

which is probably not what you want, since it is essentially evaluating the truthiness of n or m.
Your existing code already captures the nature of short-circuiting;
if n == 1 and m == 1

will only evaluate the second argument m == 1 iff n == 1, or will otherwise short-circuit.
To your comment

As I understand it does not provide any boost in runtime, just sort of syntax suggar.

Well, actually it does provide a runtime boost if Python is able to skip evaluating what would otherwise be "expensive" conditions to evaluate because it is able to short-circuit early.

A: if (n or m) == 1 is definitely not the same thing as if n == 1 or m == 1. The first if statement is equivalent to:
value = n
if not value:
    value = m
if value == 1:
    # do something:

Or expressed more succinctly:
if (n if n else m) == 1:
       # do something

In other words, n or m only evaluates m if n is False (or 0 if n is an integer), otherwise the result of the expression is n.
What you want to avoid redundancy is:
if 1 in (n, m): # equivalent to: if 1 is either n or m:

Update: Demo
n = 4
m = 1
if (n or m) == 1:
    print('if branch taken')
else:
    print('else branch taken')

Prints:
else branch taken


text:
Q: What does Neil mean by "In a parallel worlds theory, we can't know the relationship between consciousness and multiple realities"? In Tenet, the Protagonist and Neil had this conversation, just after discussing the grandfather paradox (emphasis mine):

Protagonist: This reversing the flow of time. Doesn't us being here now mean it never happens? That we stop them?
Neil: Optimistically, I'd say that's right.
Protagonist: Pessimistically?
Neil: In a parallel worlds theory, we can't know the relationship between consciousness and multiple realities. Does your head hurt yet?
Protagonist: Yes.
Neil: Try to sleep.

Like the Protagonist, my head hurt too. While I think I got the gist of the "optimistically" part (that just by being there at that moment means that the Tenet team eventually stop the people in the future from triggering the algorithm and inverting the entropy of the world), I don't quite understand the "pessimistically" part.
Is Neil saying that there are possibly multiple realities, and they could be living in a reality where they failed to stop the people in the future from triggering the algorithm? If that was the case, they appear to not be affected by the triggered algorithm anyway as they are conscious and alive. I'm confused on how that's pessimistic.
What does Neil mean by "In a parallel worlds theory, we can't know the relationship between consciousness and multiple realities"?

A: Parallel worlds theory or the Many Worlds Interpretation (MWI) of quantum mechanics posits that there are infinite worlds, or universes, all existing simultaneously where every possible permutation of events that could take place is taking place.
In the context of this particular exchange, Neil is suggesting that it's possible when you "die" you wouldn't know it because your consciousness could be redirected to another of those infinite universes that is nearly identical to the previous one you were existing in, with the exception being that you didn't die.


text:
Q: How get object and operation from AWS access denied exception in javascript? Any aws service can throw AcceeDenied Exception. Which is logged like that:
somePromise.catch((err) => {
    console.error(`Failed to store logs into CloudWatch`, err);
    callback(err);
})

Cloud watch logs show:
{
    "errorMessage": "Access Denied",
    "errorType": "AccessDenied",
    "stackTrace": [
        "Request.extractError (/var/task/node_modules/aws-sdk/lib/services/s3.js:577:35)",
        "Request.callListeners (/var/task/node_modules/aws-sdk/lib/sequential_executor.js:105:20)",
        "Request.emit (/var/task/node_modules/aws-sdk/lib/sequential_executor.js:77:10)",
        "Request.emit (/var/task/node_modules/aws-sdk/lib/request.js:683:14)",
        "Request.transition (/var/task/node_modules/aws-sdk/lib/request.js:22:10)",
        "AcceptorStateMachine.runTo (/var/task/node_modules/aws-sdk/lib/state_machine.js:14:12)",
        "/var/task/node_modules/aws-sdk/lib/state_machine.js:26:10",
        "Request.<anonymous> (/var/task/node_modules/aws-sdk/lib/request.js:38:9)",
        "Request.<anonymous> (/var/task/node_modules/aws-sdk/lib/request.js:685:12)",
        "Request.callListeners (/var/task/node_modules/aws-sdk/lib/sequential_executor.js:115:18)"
    ]
}

First of all where is a stack trace? :)
Second is there a way to deternime what resource and operation were requested? (There are several chained promises and it is unclear what is wrong)

A: You're unlikely to get much more detail out of the JavaScript Stacktrace from my experience. A more helpful route I've found is to look at what AWS services the libraries that I'm using (and getting somePromise from) are accessing.
One other way that you could possibly glean some of this information is from the AWS side, using CloudTrail and CloudWatch Logs. You would first need to create a CloudTrail in your AWS Account. Next you would need to send CloudTrail events to CloudWatch Logs.
Once you have your CloudTrail events going to CloudWatch Logs, you can use CloudWatch Logs to query for "Access Denied" and "Unauthorized Operation" messages. To do this, go to CloudWatch in the AWS Console, and go to the Logs Section. Next look for your CloudTrail Log group. Normally the Default log group is called CloudTrail/Default. Once you go into that log Group, Press the Search Logs button at the top. This will bring up all of the logs in the Logs Streams for this Log Group. You can then enter a query that will get only the Access Denied and Unauthorized operation events. To do this, enter the query { ($.errorCode = "*UnauthorizedOperation") || ($.errorCode = "AccessDenied*") }
I found this to be onerous, and very time consuming, so I wrote a utility to send these Access Denied and Unauthorized Operation messages to Slack for me Automatically. You can check it out at https://github.com/Giftbit/activity-aware-ids-aws/blob/master/infrastructure/cloudformation.yaml. It also includes a helpful CloudFormation template to stand this up for you, provided that you have already created your CloudTrail and have the events sent to CloudWatch Logs.


text:
Q: One parse query being called and one not in cellForItemAtIndexPath method In my cell for item at index path method I'm attempting to populate an array of UIImageViews using parse data. The creator image view populates just fine but the second "if let" for the attendee array isn't getting called at all (I'm pretty sure the code would work although it's a bit tricky and I'm not 100% sure but I want it to at least get called first)
Any ideas? Thanks!
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    //sets up cell

    let cell : EventCell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! EventCell

    //adds attend action

    cell.attendButton.addTarget(self, action: "buttonTapped:", forControlEvents: UIControlEvents.TouchUpInside)

    //queries parse for events

    let event = events?[indexPath.row]

    event?.eventImage.getDataInBackgroundWithBlock({ (data, error) -> Void in

        if let data = data, image = UIImage(data: data) {

            cell.eventBackgroundImage.image = image
            cell.eventTitleLabel.text = event?.eventTitle

            //gets profile picture of events creator

            if let eventCreator = event?.objectForKey("user") as? PFUser {
                if let creatorImage = eventCreator.objectForKey("profilePicture") as? PFFile {
                        creatorImage.getDataInBackgroundWithBlock({ (data, error) -> Void in

                        cell.creatorImageView.image = UIImage(data: data!)

                    })
                }
            }

            //gets profile pictures for image view array on back of cell

            if let attendeeArray = event?.objectForKey("attendees") as? [PFUser] {

                for var index = 0; index < attendeeArray.count; ++index {
                    let profileImageView = cell.imageViewArray[index]
                    let usr : PFUser = (attendeeArray[index] as PFUser?)!

                    //                        if let picture = usr.objectForKey("profilePicture") as? PFFile {

                    usr.fetchIfNeededInBackgroundWithBlock({ (object: PFObject?, error: NSError?) -> Void in
                        if let picture = object!.objectForKey("profilePicture") as? PFFile {
                            picture.getDataInBackgroundWithBlock({ (data, error) -> Void in
                                profileImageView.image = UIImage(data: data!)
                            })
                        }
                    })

                }

            }

            //sets correct category for cell image

            if event?.category == "" {
                cell.categoryImageView.image = nil
            }

            if event?.category == "The Arts" {
                cell.categoryImageView.image = UIImage(named: "Comedy")
            }

            if event?.category == "The Outdoors" {
                cell.categoryImageView.image = UIImage(named: "Landscape")
            }

            if event?.category == "Other" {
                cell.categoryImageView.image = UIImage(named: "Dice")
            }

            if event?.category == "Sports" {
                cell.categoryImageView.image = UIImage(named: "Exercise")
            }

            if event?.category == "Academics" {
                cell.categoryImageView.image = UIImage(named: "University")
            }

            if event?.category == "Science" {
                cell.categoryImageView.image = UIImage(named: "Physics")
            }

            if event?.category == "Entertainment" {
                cell.categoryImageView.image = UIImage(named: "Bowling")
            }

            if event?.category == "Food & Drinks" {
                cell.categoryImageView.image = UIImage(named: "Food")
            }

            if let date = event?.eventDate {
                let dateFormatter = NSDateFormatter()
                dateFormatter.dateFormat = "yyyy-MM-dd"

                cell.eventDescriptionLabel.text = event?.eventDescription
                cell.eventDateLabel.text = dateFormatter.stringFromDate(date)
            }
        }
    })

    cell.layer.cornerRadius = 20

    //not sure if necessary

//        let subviews : NSArray = cell.contentView.subviews
//
//        for view in subviews {
//            view.removeFromSuperview()
//        }

    return cell

}


text:
Q: TinyMCE add Format I'd like to add custom formats to my TinyMCE plugin. I'm using the JQuery version of the plugin.
I figured out that by adding to the editor_template.js in my themes map the following code.
_createBlockFormats : function() {
                        var k, i = {
                            p : "advanced.paragraph",
                            address : "advanced.address",
                            pre : "advanced.pre",
                            h1 : "advanced.h1",
                            h2 : "advanced.h2",
                            h3 : "advanced.h3",
                            h4 : "advanced.h4",
                            h5 : "advanced.h5",
                            h6 : "advanced.h6",
                            div : "advanced.div",
                            blockquote : "advanced.blockquote",
                            code : "advanced.code",
                            dt : "advanced.dt",
                            dd : "advanced.dd",
                            samp : "advanced.samp",
                            **custom_format: "Custom Format"** THIS IS ADDED                        }

and in the file in which I set the textarea to TinyMCE I used the following code.
$('textarea.tinymce').tinymce({

    script_url : '<?=website_url.cmmdir?>js/tinymce/jscripts/tiny_mce/tiny_mce.js',

    //language: "nl",
    // General options
    mode : "exact",
    //elements : "ta_intro, ta_content",
    theme : "advanced",
    //plugins : "safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,searchreplace,print,contextmenu,paste,directionality,noneditable,visualchars,nonbreaking,xhtmlxtras,template,imagemanager,filemanager",
    plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template, imagemanager",

    theme_advanced_toolbar_align : "left",
    theme_advanced_toolbar_location : "top",
    theme_advanced_resizing : false,

    // Theme options
    //plugins : "imagemanager,advimage,table,paste,media",
    content_css : "<?php echo website_url.cmmdir ?>tools/tinymce/style.css",

    theme_advanced_disable: "sup, sub, help, cleanup, anchor",
    theme_advanced_buttons1 : "bold,italic,underline,forecolor<?php if($RBAC->getCurrentRoleId() == super_user_id || $_SESSION['usr']->role_id == 4) { echo ",code"; } ?>,formatselect,removeformat",
    theme_advanced_buttons2 : "copy,|,bullist,numlist,|,undo,redo,|,link,unlink,anchor,cleanup,help,",
    theme_advanced_buttons3 : "cleanup,|,visualaid,tablecontrols",
    theme_advanced_blockformats : "p,h1,h2,h3,h4,custom_format",
    forced_root_block : false,
    force_br_newlines : true,
    force_p_newlines : false,
    paste_create_paragraphs : false,
    paste_create_linebreaks : false,
    paste_use_dialog : false,
    paste_auto_cleanup_on_paste : true,
    paste_convert_middot_lists : false,
    paste_unindented_list_class : "unindentedList",
    paste_convert_headers_to_strong : true,
    paste_insert_word_content_callback : "convertWord",
    relative_urls : false,
    width : "802px",

        // THIS IS THE PART WHERE I DECLARE A STYLE CLASS TO THE JUST CREATED FORMATS
    formats : {
        custom_format: {inline : 'span', 'classes' : 'custom_format'}
        }
});

Now i'd like to get rid of the first part (editing the editor_template.js), is there somehow a solution to do this als so in the second part of the code?

A: You may add custom styles using the tinymce init and the setup param
    // styles
    style_formats_paragraph: [
    {
        title: 'Royal Blue Text1',
        block: 'p',
        classes: 'royalbluetext',
        exact: true
    }, {
        title: 'Blue Text',
        block: 'p',
        classes: 'bluetext',
        exact: true
    }
    ],

    setup : function(ed) {

    // register styles (add them to the formatter)
    ed.onInit.add(function(ed, e) {
        ed.formatter.register(fmt.title, fmt);

        // registriere Absatzstile
        formats = ed.getParam('style_formats_paragraph');
        if (formats) {
            tinymce.each(formats, function(fmt) {
                ed.formatter.register(fmt.title, fmt);
            });
        }
    });
});


text:
Q: Deleting a file in C# Seems like it should a really easy topic, all the examples everywhere are just a couple of lines however no decent explainations, and thus I keep running into the same error without a solution.
In short this part of the applicaion runs like so

*

*Pulls images from db

*Creates actual images files in a temp folder

*creates pdf with images inside of it

*now delete images that were created.

Everything works up until the delete. I keep getting the error

InnerException:System.ArgumentException: URI formats are not supported.
     at System.IO.Path.NormalizePathFast(String path, Boolean fullCheck)...

I have tried a couple different ways to accomplish the delete the latest being:
foreach (string item in TempFilesList)
    {
        path = System.Web.HttpContext.Current.Application["baseWebDomainUrl"] + "/temp/" + item;
        fileDel = new FileInfo(path);
        fileDel.Delete();
    }

and the try before that one was:
foreach (string item in TempFilesList)
    {
        File.Delete(System.Web.HttpContext.Current.Application["baseWebDomainUrl"] + "/temp/" + item);
    }

TempFilesList is an array list containing the paths to the images to delete.

A: You need the actual file path of the file that you've created, not the URL of the path that you've created. Your code creates a path that look something like "http://www.mywebsite.com/location/temp/filename.jpg".
You need something that looks like "C:\MyWorkingFolder\filename.jpg".
I would recommend against using Server.MapPath, however. Since you are creating the files yourself in your own code, you control the location of where the file is being created. Use that, instead. Store it in as an AppSettings key in your web.config.
For example:
string basePath = ConfigurationManager.AppSettings["PdfGenerationWorkingFolder"];
foreach(string item in TempFilesList)
{
  File.Delete(basePath + item);
}

A: For a Windows system you would use \ rather than / to separate folders in the path. For the code to work on any platform, use the Path.Combine method to put the path together:
path = Path.Combine(Path.Combine(System.Web.HttpContext.Current.Application["baseWebDomainUrl"], "temp"), item);

A: You should try calling Server.MapPath(path) to get the "real" path to the file. Pass that to File.Delete, and it should work (assuming file permissions etc. are correct)
So for example:
foreach (string item in TempFilesList)
{
    path = System.Web.HttpContext.Current.Application["baseWebDomainUrl"] + "/temp/" + item;
    path = Server.MapPath(path);
    fileDel = new FileInfo(path);
    fileDel.Delete();
}

A: Maybe using Server.MapPath(path) would help?
foreach(string item in TempFilesList)
{
  string path = String.Format("{0}/temp/{1}", HttpContext.Current.Application["baseWebDomainUrl"], item);
  File.Delete(Server.MapPath(path));
}

And it's better to use static File.Delete() instead of creating new FileInfo(path) just for deletion

A: what pdf-creater-tool are you using? have you checked if it support a stream as input parameter? then you dont have to write the image temporary as a file.. and the hole problem is gone... -btw, I voted for Randolphos answer :p

A: If you saved the images, you must of used a file path to do that.  Can you not just use that same file path to delete them?  This would mean that you get away from any concatenating of file paths twice. (which as a side note: you should probably use Path.Combine for)

A: I would only add this just in case you wanted it to hit the Recycling Bin rather than blow it out of existence:
FileSystem.DeleteFile(file.FullName, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing);

The only thing that sucks is that in your C# you have to reference a VisualBasic namespace
using Microsoft.VisualBasic.FileIO;

In your case you might not even need the bin since it's in the Database but I thought I'd throw it out there.


text:
Q: Retrieve S3 bucket settings with Python I have a requirement to record hundreds of S3 buckets for the settings on the Properties tab for each bucket.  This is to verify that none are public, none are unencrypted.  Later I will have to provide the ACL for each bucket as well.
the following is as far as I have gotten
from boto3.session import Session
import config
import pandas as pd

ACCESS_KEY=config.awsAccessKey
SECRET_KEY=config.awsSecretKey

session = Session(aws_access_key_id=ACCESS_KEY,
                  aws_secret_access_key=SECRET_KEY)
s3 = session.resource('s3')

counter = 0
csv_list = []
path = '//ant.amazon.com/dept/DCGSI/Extracts/s3_buckets_list.csv'

for bucket in s3.buckets.all():
    for obj in bucket.objects.all():
        if counter == 10:
            break
        bucketsTwoDeep = bucket.name + obj.key
        counter += 1

This gives me the bucket and the first level "folder" object.  I can't seem to find a way to get the properties on the bucket.  Is there a way?  Once I can get the data I will have to put it into a CSV or something, so hopefully anything that I can get will be dataframeable.

A: There are a whole stack of get_bucket methods in the s3client that might be what you're looking for.  get_bucket_encryption() and get_bucket_acl() spring to mind.
e.g.
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import boto3
>>> from pprint import pprint
>>> s3client = boto3.client('s3')
>>> response = s3client.get_bucket_acl(Bucket = 'bucketname')
>>> pprint (response['Grants'])
[{'Grantee': {'DisplayName': 'username',
              'ID': '3c9b78c1dbb3599d60dab12c5d9c9d7eef13ca95e2505d6e022c98345c70e5fc',
              'Type': 'CanonicalUser'},
  'Permission': 'FULL_CONTROL'}]

Full list of s3 Client commands at https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#client


text:
Q: KeyValuePair deconstruction in ToDictionary Can I deconstruct KeyValuePair as lambda argument in ToDictionary method like it could be done in foreach?
So, is there any possibility to write something like this:
dict.ToDictionary((key, value) => key, (key, value) => 2*value);

A: No, you have to write it like this:
var d = dict.ToDictionary(p => p.Key, p => p.Value * 2);


text:
Q: Kuberenetes ExternalName service forwarding request to service outside cluster We have a requirement to forward the request to service outside of cluster.
/ -> some service outside cluster (someapi.com)
/api -> service inside cluster
When I try to hit the https://someapi.com/health it gives me proper response but not through ingress.
Ingress
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: custom-ingress
  annotations:
    kubernetes.io/ingress.class: haproxy
status:
  loadBalancer: {}
spec:
  tls:
    - hosts:
        - mytenant.com
      secretName: tenant-secret
  rules:
    - host: mytenant.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: external-service
                port:
                  number: 80

Service
apiVersion: v1
kind: Service
metadata:
  name: external-service
status:
  loadBalancer: {}
spec:
  type: ExternalName
  sessionAffinity: None
  externalName: someapi.com

curl -ikv https://mytenant.com/health is giving me
503 Service Unavailable
No server is available to handle this request.
Connection #0 to host mytenant.com left intact
I tried nslookup and it does evaluate to ip
/usr/src/app # nslookup external-service
Server:         901.63.1.11
Address:        901.63.1.11:53

external-service.default.svc.cluster.local    canonical name = someapi.com
someapi.com        canonical name = proxy-aws-can-55.elb.eu-central-1.amazonaws.com
Name:   proxy-aws-can-55.elb.eu-central-1.amazonaws.com
Address: 92.220.220.137
Name:   proxy-aws-can-55.elb.eu-central-1.amazonaws.com
Address: 33.43.161.163
Name:   proxy-aws-can-55.elb.eu-central-1.amazonaws.com
Address: 98.200.178.250

external-service.default.svc.cluster.local    canonical name = someapi.com
someapi.com        canonical name = proxy-aws-can-55.elb.eu-central-1.amazonaws.com

When I changed the external-service port to 80 (also tried changing target port of service to 443)
spec:
  ports:
    - protocol: TCP
      port: 80
      targetPort: 80
  type: ExternalName
  sessionAffinity: None
  externalName: someapi.com

It keeps on looping with 301
< HTTP/2 301
< content-length: 0
< location: https://mytenant.com/health
< strict-transport-security: max-age=15768000

(With same setup if I just change the externalName to httpbin.org it works fine.)
When I changed ingress (port) and service (port and targetPort) to 443, I am getting
REFUSED_STREAM, retrying a fresh connect
Connection died, tried 5 times before giving up
Closing connection 5
curl: (56) Connection died, tried 5 times before giving up

I also tried setting host header mentioned here,  https://www.haproxy.com/documentation/kubernetes/latest/configuration/ingress/#set-host but no luck still 301.
Please help me understand how I should make it work. many thanks!

A: I got the working configuration, I changed the ingress (port) and service (port/targetPort) to 443. Also, added annotation ingress.kubernetes.io/backend-protocol: h1-ssl on ingress.
I believe I was getting 301 because the upstream service was expecting https request and after adding the backend-protocol annotation, after ssl termination at HA Proxy controller, the new call that initiated was https and that fulfilled the request. Also, I think value for Service targetPort doesn't matter in case of ExternalName service.
Ingress
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: custom-ingress
  annotations:
    ingress.kubernetes.io/backend-protocol: h1-ssl
    kubernetes.io/ingress.class: haproxy
status:
  loadBalancer: {}
spec:
  tls:
    - hosts:
        - mytenant.com
      secretName: tenant-secret
  rules:
    - host: mytenant.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: external-service
                port:
                  number: 443

Service
apiVersion: v1
kind: Service
metadata:
  name: external-service
status:
  loadBalancer: {}
spec:
  ports:
    - protocol: TCP
      port: 443
      targetPort: 443
  type: ExternalName
  sessionAffinity: None
  externalName: someapi.com


text:
Q: How can I set modalView in false? I would like that on Click of a touchableopacity my app changes the modal state in false
constructor(props) {
    super(props);
    this.state = {
        modalVisible: true,
        first: true,
    }
}
checkIfFirstLog = () => {
    this.setState = {first: false}

    if (this.state.first = false) {
        this.setState = {
            modalVisible: false
        }
    }
}
<Modal
      <TouchableOpacity onPress={() => this.checkIfFirstLog() }>

      </TouchableOpacity>
 </Modal>

A: According to my understand, you can use following code:
constructor(props) {
    super(props);
    this.state = {
        modalVisible: true,
        first: true,
    }
}
const checkIfFirstLog = () => {
    this.setState({
        modalVisible: true,
        first: true,
    });
}
<Modal
    <TouchableOpacity onPress={this.checkIfFirstLog}>

    </TouchableOpacity>
</Modal>

I merged two setState operations that you used in checkIfFirstLog method because you're already trying to change two state values as well. I think it would be good this way.


text:
Q: What is the Q distribution in expectation maximization in the following explanation? I am reading a blog on expectation maximization - http://krasserm.github.io/2019/11/21/latent-variable-models-part-1/
Here, I encounter the following expression:

When you look at the above distribution, please correct my understanding when it comes to nature generating N points from C gaussian distributions.
I assume that the data is generated as follows by nature (to be confirmed by you).

*

*Nature first selects a gaussian among C of them using a probability distribution q. So nature looks at the q distribution which says there is a probability with which it generates gaussian 1, a probability with which it generates gaussian 2, and so on for gaussian C. So nature will first sample for a gaussian from q.

*Then, nature will use the mean and covariance of this gaussian samples above to generate a point.

*Nature repeats the above step 1 and 2 N number of times.

Now, my understanding for GMM is that we are just given points 1 to N and we want to know which gaussian each point came from. As we cannot say for sure if a point came from any particular gaussian, we attach a probability for the point to every gaussian in such a way that the probabilities add to 1.
In the above expression (10), if we were to expand the joint probability of $p(x_i, t_{ic} = 1 | \Theta)$, I would do it as $p(xi | t_{ic} = 1, \Theta) * q(t_{ic} = 1)$ because I know that the probability with which nature would have selected the gaussian c (among 1..C) for generating point $x_i$ is $q(t_{ic}=1)$.
Why then we use two different annotations as $p(t_{ic} = 1 | x_i, \Theta)$ and $q(t_{ic} = 1)$?
What is the different between the $p(t_{ic}=1) and q(t_{ic}=1)$?

A: I recommend you to check the CS229 notes by Andrew Ng. The note 8 then 7b. It should be clear after that at least I believe. CS229
The general log-likelihood function with a latent variable is:
$$
\begin{aligned}
lnp(x; \theta)
& = \Sigma_{i=1}^{N}lnp(x_i; \theta)\\
& = \Sigma_{i=1}^{N}ln\Sigma_{t}p(x_i | t_i; \theta)p(t_i; \phi)\\
& = \Sigma_{i=1}^{N}ln\Sigma_{t}p(x_i, t_i; \theta, \phi)
\end{aligned}
$$
where $t_i$ takes the number of Gaussians (states) you assumed and e.g. $p(t_i=1) = \phi_1$ is the prior of state 1 in your explanation 1.
$q$ is just an arbitrarily introduced distribution to derive the algorithm, not the prior. In fact, it's the posterior.
Simply put, you maximise the equation (10) with Jensen's inequality, the lower bound is maximised when the equality holds, that is $\frac{p(x_i, t_i;\theta)}{q(t_i)} = c$. Thus $q$ is set to the posterior $p(t_i|x_i; \theta)$, the probability (density) of states with respect to each data point. If you have a sample of size 100 and assume there're two underlying Gaussians, then the shape of the posterior is (100, 2). Detailed derivation see the notes.
The relationship between the prior and the posterior is $\phi_1 = \frac{1}{N}\Sigma_{i=1}^{N}p(t_i=1|x_i; \theta)$, as one of the m-step.
By the way, e-step is to get the posterior and m-step consists of maximising the likelihood with respect to the means, covariances and the state priors. The initialisation could be done using kmeans if you're considering writing your code. It was a good practise for me to understand GMM by reading the scikit-learn source code...


text:
Q: Trying the docker mysql image but user/password does not work I have a simple docker setup using php7 and mysql, both from docker hub. Setting up is ok so far, everything starts up and I can access my app. But I can't get the mysql connect to work for me. I even logged in into the box and tried accessing the db, but it fails. Anybody any idea?
docker-compose.yml
db:
  restart: always
  image: mysql/mysql-server:5.7
  ports:
    - "3306:3306"
  environment:
    MYSQL_ROOT_PASSWORD: root
    MYSQL_USER: myapp
    MYSQL_PASSWORD: myapp
    MYSQL_DATABASE: myapp
web:
  restart: always
  image: silintl/php7
  command: php -S 0.0.0.0:8000 -t /app/web
  links:
    - db
  ports:
    - "8000:8000"
  volumes:
    - ../:/app

trying to access the db
[bash]marcobehnke@Marcos-MacBook-Pro-2 ~ $ docker exec -it docker_db_1 bash

[root@7eff3007bb11 /]# mysql --user=myapp --password=myapp --host=localhost --port=3306 myapp
mysql: [Warning] Using a password on the command line interface can be insecure.

ERROR 1045 (28000): Access denied for user 'myapp'@'localhost' (using password: YES)
[root@7eff3007bb11 /]#

What am I missing here?
Edit: Have a look at my github repo, this is the exact config I am using: https://github.com/firegate666/docker-php7-mysql-postgres

A: Seems like you're using the wrong syntax. Should look something like this:
version: '2'
services:
  db:
    restart: always
    image: mysql/mysql-server:5.7
    ports:
      - "3306:3306"
  environment:
    MYSQL_ROOT_PASSWORD: "root"
    MYSQL_USER: "myapp"
    MYSQL_PASSWORD: "myapp"
    MYSQL_DATABASE: "myapp"
  # ...

A: Ok, I took a different machine and tried my setup, it worked out of the box. I have no idea whyt this is about, but the problem is obviously my machine :-)


text:
Q: How to connect a Java back end with a .NET front end I have a bunch of Java code which was written using the Hibernate framework, originally destined to have a front end written using JSPs. However, the requirements for the front end have changed, and we've decided that a desktop client (which will be written in .NET) is a better match for our users.
I don't really want to waste the code that's already been written - can anybody suggest a good set of tools for writing a document-based web services interface that we will be able to access from .NET?
Thanks,
Jim

A: If you truly want a document based service interface (rather than an RPC style web service architecture), your best bet is going to be creating a SOAP based web service interface.
A quick glance at the Java site shows that the Metro stack might help a bit:
Java Web Services at a Glance

A: I'd personally use some lightweight RPC protocol, be it XML-RPC or a homegrown one. SOAP, IMO, is way too fat and is not as interoperable as it's supposed to be. The simpler the better.

A: We have a quite large application using a Java RMI server and IIOP.NET for interoperability. We have used IIOP.NET with the Sun RMI and the Bea Weblogic (now Oracle) without major issues.

A: We're developing an application with the exact architecture you describe for a finance application.  We reviewed several different options, and have finally landed on using compressed CSV over HTTP.
CSV was chosen since the vast majority of data was going to be displayed in a grid on the front end, we had very large result sets >250k rows on a regular basis, and it compresses really really well.
We also looked at using:

*

*ICE, but declined on that due to licensing costs and the need to reinvent so much.

*Google's protocol buffers via servlets, but declined on that due to lack of C# support (as of last fall).

*Compressed XML using WOX, but declined on that due to lock-in to a small thesis project for support and XML being too verbose.

The industry supports a couple of different options as well:

*

*SOAP, but that has its own well documented issues.

*IIOP, J-Integra has a product called Espresso which will allow you to do RMI from a front end.


text:
Q: All steps of finding a witness Rabin-Miller Find a  Rabin-Miller witness of compositeness of $n=49$
I have asked the same question before months but can we have a complete answer of how to find this witness? i mean with complete answer(all steps).sorry for asking again.

A: This is again a somewhat stupid case for Miller-Rabin similar to your Rabin-Miller compositeness,
because you should assume that $n$ is not a square.  You have accepted that answer which containing all the steps, so I do not understand where you have problems. Apart from the fact that Miller-Rabin is non-sense for squares, the simple finding procedure is: Test all $a=2,3,\dots$ with $\gcd(a,n)=1$ if it is a witness for the compositeness.
That said, here is the calculation: Let $n=49$ and $a=2$ the smallest possible candidate, then $n-1=d\times 2^s = 3\times 2^4.$ Now compute
$$x_0 \equiv a^d \equiv 2^3 \equiv 8 \pmod{49}$$
$$x_1 \equiv x_0^2 \equiv 15 \pmod{49}$$
$$x_2 \equiv x_1^2 \equiv 29\pmod{49}$$
$$x_3 \equiv x_2^2 \equiv 8\pmod{49}$$
Thus $a^d\not \equiv 1 \pmod {49}$ and $x_r \equiv a^{2^r d}\not \equiv -1 \pmod {49}$ for $0\le r \le s-1.\,$ Therefore $a=2$ is a witness for the compositeness of $49$.


text:
Q: Offline report with D3, md and equations Is it possible to create a single html page containing embedded D3js charts, CommonMark text, and equations (e.g. Katex or MathJax) and have it all rendered the browser offline?
Must have:

*

*Works offline using modern Firefox/Chrome/Safari, after having
downloaded a minimal number of JavaScript libs.

*No requirement for installing anything beyond the web browser.  So no local http server, Pandoc, R, Python etc.

Should have:

*

*Possible to write everything in a single html file, which opens in a normal modern browser.

*Good archival properties with minimal maintanence.

Motivation:
We work in a high security locked down IT environment and can't install stuff, but we do have decent web browsers and can run javascript in them.
We routinely share small analytical reports internally, and are experimenting with delivering a directory containing

*

*an html file (with embedded JSON data), and

*downloaded D3 and Underscore librariess

All the internal customer has to do is click on index.html. So far this has been very succesful, but we'd like to use markdown and equations too.
We are vaguely aware of data science workbook solutions like Jupyter and Observable, but not sure that these meet our criteria.
Clarification
I know we can download libs and place them in a dir alongside index.html, but I'm not sure if a JavaScript library exists which can render the markdown and equations and write the results directly into the DOM.  And even if such a library exists, where in index.html would the markdown be written?  Is there some kind of html tag which can just hide a load of raw text which will be parsed by JS?

A: To answer your question, it is possible. You'll either need Node app that will render static HTML pages or simple HTML page with embedded Javascript. Since all these libraries are available as UDM packages, I suggest 2nd option.
CommonMark CDN: https://cdnjs.com/libraries/commonmark
KaTeX CDN: https://khan.github.io/KaTeX/docs/browser.html
You'll only need to download these libraries and include them in page. KaTeX includes JS to convert simple text to rendered mathematical equation, you only need to give it text and element where to render equation: https://khan.github.io/KaTeX/docs/api.html. CommonMark is similar but it only gives you rendered HTML, you need to insert it with element.innerHTML yourself: https://www.npmjs.com/package/commonmark.


text:
Q: Question about counting probabilities I have a question about the answer given by Andre Nicolas in the question below:
A fair coin is tossed until either a head comes up or four tails are obtained.what is the expected no. of tosses?
If the sample space $S = \{H, TH, TTH, TTTH, TTTT\}$ we can't use the formula $P(E) = \frac{|E|}{|S|}$ where $|E|$ is the number of outcomes in the event $E$ because the outcomes of $S$ are not equally likely, correct? So, then how do we calculate the probabilities of elements in $S$? Do we count the probability of $H \in \{H, T\}$, probability of $TH \in \{TH, HT, HH, TT\}$, probability of $TTH \in \{TTH, TTT, HHH, THT, HHT, HTT, HTH, THH\}$ and probability of $TTTT$ in a set with $16$ outcomes?

A:
So, then how do we calculate the probabilities of elements in $S$?

In general you require some model of how the outcomes are generated that will enable you to evaluate their probabilities.   In this case the model is a truncated geometric distribution - you have a sequence of independent Bernoulli events (flips of a fair coin) and are counting trials until success or four failures; with success rate $1/2$.
So letting $X$ be the count of trials until success or four failures.   $\{X=2\}$ corresponds to $\{TH\}$ and so forth.  $$\mathsf P(X=k) = \begin{cases} 2^{-k} & : k\in\{1,2,3\} \\ 2^{-3} & : k=4\\0 & : k\notin\{1,2,3,4\}\end{cases}$$

Do we count the probability of ... in a set with $16$  outcomes?

Yes, you can!   That is also a valid model.   Consider that if you (hypothetically) tossed the coin four times, you can group the sixteen equally probable outcomes into events by occurrence of the first head.   These events will correspond to those of your sample space, giving you a measure of their probability.
$$S'= \rm \Big\{\{\color{blue}{H}HHH, \color{blue}{H}HHT, \color{blue}{H}HTH, \color{blue}{H}HTT, \color{blue}{H}THH, \color{blue}{H}THT, \color{blue}{H}TTH, \color{blue}{H}TTT\}, \\ \{\color{blue}{TH}HH, \color{blue}{TH}HT, \color{blue}{TH}TH, \color{blue}{TH}TT\}, \\ \{\color{blue}{TTH}H, \color{blue}{TTH}T\},\\ \{\color{blue}{TTTH},\color{blue}{TTTT}\}\Big\}  $$

tl;dr $$S\times\mathsf P = \{{\rm (H, \tfrac 12), (TH, \tfrac 14), (TTH, \tfrac 18), (TTTH \cup TTTT, \tfrac 1{8})}\}$$
$$X\times\mathsf P = \{{\rm (1, \tfrac 12), (2, \tfrac 14), (3, \tfrac 18), (4, \tfrac 1{8})}\}$$
$\mathsf E(X) = \tfrac 12 +\tfrac 2 4+\tfrac 38+\tfrac 48 = \tfrac {15}{8}$

A: If you have outcomes that are not equally likely, then you multiply the probability of that outcome by the outcome's quantity that you're measuring (in this case, number of tosses):
$$\frac{1}{2} \cdot 1 + \frac{1}{4} \cdot 2 + \frac{1}{8} \cdot 3 + \frac{1}{16} \cdot 4 + \frac{1}{16} \cdot 4 = 1 \frac{7}{8},$$
which rounds up to $2$.


text:
Q: MySql Raw Query into Laravel 5.5 Eloquent ORM I have mySql query an I want to convert it into Laravel 5.5 Eloquent ORM.
mySql Query:
SELECT i.category_id, count(i.id) as count FROM `items` i INNER JOIN item_categories c ON c.id = i.`category_id` GROUP BY i.`category_id`

This query is working. Is there any way to convert it easily into eloquent or anyone can make it for me.

A: Using eloquent it will be like
$categories = Category::withCount('items')->get();

Counting Related Models


text:
Q: rmagick and imagemagick bundle/homebrew error Please see error stack below. I tried uninstall/install of imagemagick via homebrew, 'gem pristine rmagick', and reinstall of rmagick. All have returned the same error. Any help would be VERY much appreciated- been at this for a while now.
$ gem install rmagick
Building native extensions.  This could take a while...
ERROR:  Error installing rmagick:
    ERROR: Failed to build gem native extension.

        /Users/LU/.rvm/rubies/ruby-1.9.3-p362/bin/ruby extconf.rb
checking for Ruby version >= 1.8.5... yes
extconf.rb:128: Use RbConfig instead of obsolete and deprecated Config.
checking for /usr/local/bin/gcc-4.2... yes
checking for Magick-config... yes
checking for ImageMagick version >= 6.4.9... yes
checking for HDRI disabled version of ImageMagick... yes
checking for stdint.h... yes
checking for sys/types.h... yes
checking for wand/MagickWand.h... yes
checking for InitializeMagick() in -lMagickCore... no
checking for InitializeMagick() in -lMagick... no
checking for InitializeMagick() in -lMagick++... no
Can't install RMagick 2.13.1. Can't find the ImageMagick library or one of the dependent libraries. Check the mkmf.log file for more detailed information.

*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
    --with-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/Users/Lungs/.rvm/rubies/ruby-1.9.3-p362/bin/ruby
    --with-MagickCorelib
    --without-MagickCorelib
    --with-Magicklib
    --without-Magicklib
    --with-Magick++lib
    --without-Magick++lib

Gem files will remain installed in /Users/Lungs/.rvm/gems/ruby-1.9.3-p362/gems/rmagick-2.13.1 for inspection.
Results logged to /Users/LU/.rvm/gems/ruby-1.9.3-p362/gems/rmagick-2.13.1/ext/RMagick/gem_make.out

A: Alternatively, step back one ImageMagick rev:
(via https://stackoverflow.com/a/9832084/485836)
> cd /usr/local

> brew versions imagemagick

6.7.7-6  git checkout 883f549 Library/Formula/imagemagick.rb
6.7.5-7  git checkout f965101 Library/Formula/imagemagick.rb
6.7.1-1  git checkout be8e0ff Library/Formula/imagemagick.rb
...

> git checkout 883f549 Library/Formula/imagemagick.rb

> brew install imagemagick

A: A better way to get the headers into the proper place might be to just add the pkgconfig from the imagemagick Cellar to your PKG_CONFIG_PATH.
Adding the following to my ~/.bash_profile and then sourcing it (source ~/.bash_profile) worked for me
export PKG_CONFIG_PATH="/usr/local/Cellar/imagemagick/6.8.0-10/lib/pkgconfig:$PKG_CONFIG_PATH"

A: Had the same problem, easy fix!
https://github.com/mxcl/homebrew/issues/16625
here is the skinny on the solution (rmagick is broken, and you have to create symlinks to get it to work):
cd /usr/local/Cellar/imagemagick/6.8.0-10/lib

ln -s libMagick++-Q8.7.dylib   libMagick++.dylib

ln -s libMagickCore-Q8.7.dylib libMagickCore.dylib

ln -s libMagickWand-Q8.7.dylib libMagickWand.dylib

A: Ended up being an issue with rails version, needed to update and reinstall imagemagick/rmagick.

A: brew install imagemagick

should do the trick. Then reinstall the gems.


text:
Q: Change Android Source Code I have Downloaded Froyo OS and i have to modify it. is that possible?
i havent do that before. i just download it..
If anyone have done it before, please tell me the entry point. Where to start and what to do?
I want to change home screen of Android OS. I want my icons to see on home screen.
Thanks in Advance


text:
Q: c++ How to Reading file in to dynamic array and accessing array elements I'm learning how to use fstream with dynamic array, the program supposed to print out all the data in txt file and can do something like sorting, delete gender or calculate average grade. But turned out code is all messy and arrays are hard to access.
This is the text file  use to practice.

Code:
struct studentData{
   string branch;
   string name;
   char gender;
   double grade;
   int number;
   int total;
};

int main() {

    int line_count = 0;
    ifstream file_in;
    int couter = 0;
    file_in.open("student.txt");
    if(!file_in.good())
        {
            cout << "Eror, could not open the file." << endl;
            file_in.clear();
            return -1;
        }
        line_count = openFileTest(file_in);
        file_in.clear();
        file_in.seekg(ios::beg);
        studentData* p_studentData = new studentData[line_count];

    loadStudentData(file_in, p_studentData,couter);
    displayStudentData(p_studentData, line_count,couter);

        delete [] p_studentData;

        file_in.close();

        return 0;
}

int openFileTest(ifstream& file_in)
{
    string temp;
    int linecount = 0;

    while(getline(file_in, temp))
    {
        linecount ++;
    }

    return linecount;

}

void loadStudentData(ifstream& file_in,studentData* p_studentData,int couter)
{

    int temp ;
    file_in >> p_studentData -> total ;
    temp = p_studentData->total;

    for(int i=0;i<temp;i++)
    {
    file_in >> p_studentData->branch >> p_studentData->number ;
        for(int k=0;k<p_studentData[i].number;k++)
        {
            file_in >> p_studentData[k].name  >> p_studentData[k].gender >> p_studentData[k].grade ;
        }
        p_studentData++;
    }
    return;
}

void displayStudentData(studentData* p_studentData, int count_line,int couter)
{

        cout << p_studentData->total << endl;
        int temp = p_studentData->total ;
    for(int i=0;i<temp;i++)
    {
        cout << p_studentData[i].branch << "  " ;
        cout << p_studentData[i].number << endl;
        for(int j=0;j<p_studentData[i].number;j++)
        {
            cout << p_studentData[j].name << "  " << p_studentData[j].gender << "  " << p_studentData[j].grade << endl;
        }
    }
    return;
}

The output I get is:

A: It appears you are not being careful to track where you are in the file. I don't know why arrays[] are so popular for these kinds of assignments when a vector would do, but notice that you are missing a level of abstraction:
your code: array of student
assignment: array of subject; each subject is an array of student
It is often very helpful to use types to keep track of this:
struct student
{
  // as above
};

struct subject
{
  string name;
  int number_of_students;
  student* students;
};

struct all_subjects
{
  int number_of_subjects;
  subject* subjects;
};

Using this, we can work on deciphering the file:
all_subjects load_all_subjects()
{
  ifstream f( ... );
  ...
  all_subjects all;
  f >> all.number_of_subjects;
  all.subjects = new subject[ all.number_of_subjects ];
  for (int n = 0; n < all.number_of_subjects; n++)
    load_one_subject( f, all.subjects[ n ] );
  return all_students;
}

void load_one_subject( std::ifstream& f, subject& one_subject )
{
  f >> one_subject.name;
  f >> one_subject.number_of_students;
  one_subject.students = new student[ one_subject.number_of_students ];
  for (int n = 0; n < one_subject.number_of_students; n++)
    load_one_student( f, one_subject.students[ n ] );
}

And so on. Good luck!


text:
Q: java generics problem - create a generic list when the type is of yet unknown object type I want to open a configuration screen and send back its data when user clicks ok.
I have these objects as configurations
configObjA a;
configObjB b;

Both implement IDisplayable (my interface).
Now the congfig screen gets two ArrayLists and put them in JLists gui.
it itterates the JList and put them in datamodel.
when I return from the screen , I want to send the main screen the results.
So I re-iterate the datamodel and put it all back in an arraylist
the problem is the main screen doesnt know anything about
Is there a way my configuration screen would return a type that the main screen will know?
I thought of returning
    public List getOptionsList()
and in the method I wil create a list of the type I sent. (I would then have to keep the type i sent ). is that any good? how do i create a generic list when the type is of unknown
object type? any suggestion ?
btw: isnt my foolish gui process too complicated for that simple need?

A:
how do i create a generic list when the type is of unknown object type?

You cannot. The whole point of generic lists is that you do know the object type at compile-time, so that the compiler can check your usage of that list.
If you know at least a parent class or interface (which is the usual case actually), you can use that:
List<IDisplayable> l;

If it can be any type of object, you can only say
List<Object> l;

which will accept any kind of Object, but removes the potential for meaningful compile-time type checking.

A: You can create a generic list of an unknown type, but you can't really put objects in them.
public <T> List<T> makeList() {
    return new ArrayList<T>();
}

Of course, the method using this method then has to know the type, and can only put objects of this type in.

In your case, the problem seems to be that you want to misuse the JList as a data container. It is not, it is a view component. Use a real data structure for your logic, and wrap it in a ListModel to provide your list with data to show.


text:
Q: How to set opacity/transparency to vector image?
Hold your horses!. If you are hurrying to flag this as a duplicate of
  this question or this question none of those have an answer
  to what is asked here. Thanks for the attention though.

I have an .eps image (the idea is to keep this image and don't change it's format to a .png for example), that I am setting as background for a project with the background package:
\documentclass{article}
\usepackage{tikz}
\usepackage{background}
\backgroundsetup{
angle=0,
scale=1,
opacity=0.2,
contents={\tikz[remember picture,overlay,shift=(current page.center)] \node[inner sep=0pt] at (8,-10){\includegraphics[scale=1]{Cube.eps}};}}
\begin{document}
\null
\end{document}

The original image is (have it here with black background):

And the result setting the opacity in both the background setup and tikz node options is the following:

I created the image with InkScape and I actually set the "color layers" as unmasked by the opacity command in order to make the color gradient. Obviously this is not the desired result, what is expected is something like:

Is this posible?.

A: You may convert your EPS picture to PDF via inkscape : open Cube.eps then "save as..." Cube.pdf.

\documentclass{article}
\usepackage{tikz}
\usepackage{background}

\backgroundsetup{
  angle=0,
  scale=1,
  opacity=.5,
  contents={
    \begin{tikzpicture}[remember picture,overlay,shift=(current page.center)]
      \node[inner sep=0pt]{\includegraphics[scale=1]{Cube}};
    \end{tikzpicture}
  }
}
\begin{document}
\null
\end{document}

A: If you really don't want to change it, you can fake it.
\documentclass{article}
\usepackage{graphicx,background,tikz,kantlipsum}
\backgroundsetup{
  angle=0,
  scale=1,
  opacity=1,
  position={current page.center},
  hshift=80mm,
  vshift=-100mm,
  contents={%
    \includegraphics{Cube}
    \tikz[remember picture, overlay]{\path [fill=white, fill opacity=.8] (current page.south west) rectangle (current page.north east);}
  },
}

\begin{document}

  \kant[1-10]

\end{document}

Note that if you are compiling with, say, pdfTeX, then the image is being converted regardless because .eps cannot be used otherwise.
EDIT
Here's a way of having a coloured background with the above trickery. Use \papercolor[] to set the colour desired. If the optional argument is omitted, defaults to white.

\documentclass{article}
\usepackage{graphicx,background,tikz,kantlipsum}
\backgroundsetup{
  angle=0,
  scale=1,
  opacity=1,
  position={current page.center},
  hshift=80mm,
  vshift=-100mm,
  contents={%
    \begin{tikzpicture}[remember picture, overlay]
      \path [fill=my paper color] (current page.south west) rectangle (current page.north east);
      \node {\thepage\includegraphics{Cube}};
      \path [fill=my paper color, fill opacity=.8] (current page.south west) rectangle (current page.north east);
    \end{tikzpicture}
  },
}
\newcommand*\papercolor[1][white]{\colorlet{my paper color}{#1}}
\papercolor

\begin{document}

  \kant[1-4]
  \papercolor[black!10]
  \kant[5-8]
  \papercolor[blue!25]
  \kant[9-11]
  \papercolor
  \kant[12]

\end{document}


text:
Q: What do you need for Platinum God? I have 95/97 secrets and a full collection of 198 items. Click to embiggen:

All the achievements and secrets I'm now missing are AFAIK (and astats.nl confirms):

*

*Spelunker Boy

*Mama's Boy

*Platinum God

But as we know, Spelunker Boy and Mama's Boy are not required for Platinum God.
So... what am I missing? Why do I not have Platinum God?

A: AFAIK, you do now need all secrets per the developer:

you also need all secrets unlocked for platinum now

This appears to supersede the answer that you found.


text:
Q: Ao gerar uma imagem, quero apenas visualiza-la e não salva-la Ao usar esse codigo eu salvo a imagem, mas em vez de salvar eu quero apenas visualiza-la.
String key = "Lucão MC";
    BufferedImage bufferedImage = ImageIO.read(new File("recibo.png"));

    Graphics graphics = bufferedImage.getGraphics();
    graphics.setColor(Color.BLACK);
    graphics.setFont(new Font("Arial Regular", Font.PLAIN, 55));
    graphics.drawString(key, 300, 300);
    ImageIO.write(bufferedImage, "png", new File("recibo1.png"));
    System.out.println("Image Created");

A: Use a classe Desktop do awt, ex:
Desktop.getDesktop().open(new File("C:\\images\\suaImage.jpg"));

A: Crie um JFrame, dentro dele adicione um JLabel e defina o conteúdo do label como uma imagem usando um ImageIcon encapsulando o seu BufferedImage. Exemplo:
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Teste {

    public static void main(String[] args) throws IOException {

        String key = "Lucão MC";
        BufferedImage bufferedImage = ImageIO.read(new File("recibo.png"));

        Graphics graphics = bufferedImage.getGraphics();
        graphics.setColor(Color.BLACK);
        graphics.setFont(new Font("Arial Regular", Font.PLAIN, 55));
        graphics.drawString(key, 300, 300);

        //ImageIO.write(bufferedImage, "png", new File("recibo1.png"));
        Teste.showImage(bufferedImage);

        System.out.println("Image Created");

    }

    // Esse método é o que exibe a imagem em uma janela
    protected static void showImage(BufferedImage img) {
        JFrame frame = new JFrame();
        frame.getContentPane().setLayout(new FlowLayout());
        frame.getContentPane().add(new JLabel(new ImageIcon(img)));
        frame.pack();
        frame.setVisible(true);
    }

}


text:
Q: Datatables defaults of undefined I'm working with some datatables and I keep getting the error
Uncaught TypeError: Cannot read property 'defaults' of undefined

I've done some searching and from what I read it had to do with the order of the files. However, I am calling them in the right order...
Is there another cause for this?
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="" crossorigin="anonymous"></script>
    <script src="https://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script>
    <script src="https://cdn.datatables.net/rowreorder/1.2.3/js/dataTables.rowReorder.min.js"></script>
    <script src="https://cdn.datatables.net/select/1.2.3/js/dataTables.select.min.js"></script>

The datatable looks like this
var commentTable = $('.commentTable').DataTable({
            aoColumns: [
                {
                    "mData": "name",
                },
                {
                    "mData": "date",
                },
                {
                    "mData": "comment",
                },
    ],
            bSort: false
        });

A: Not sure if this is your issue but you are loading an older version of Datatables:
<script src="https://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script>

I suggest 1.10.16 instead of 1.10.10.  It could be 1.10.10 doesn't support a feature needed for one of the other extensions.


text:
Q: Excluding points within list of buildings' shapes in Python I have a dataframe that contains thousands of points with geolocation (longitude, latitude) for Washington D.C. The following is a snippet of it:
import pandas as pd
df = pd.DataFrame({'lat': [ 38.897221,38.888100,38.915390,38.895100,38.895100,38.901005,38.960491,38.996342,38.915310,38.936820], 'lng': [-77.031048,-76.898480,-77.021380,-77.036700,-77.036700   ,-76.990784,-76.862907,-77.028131,-77.010403,-77.184930]})

If you plot the points in the map you can see that some of them are clearly within some buildings:
import folium
wash_map = folium.Map(location=[38.8977, -77.0365], zoom_start=10)
for  index,location_info in df.iterrows():
      folium.CircleMarker(
          location=[location_info["lat"], location_info["lng"]], radius=5,
          fill=True, fill_color='red',).add_to(wash_map)
wash_map.save('example_stack.html')
import webbrowser
import os
webbrowser.open('file://'+os.path.realpath('example_stack.html'), new=2)

My goal is to exclude all the points that are within buildings. For that, I first download bounding boxes for the city buildings and then try to exclude points within those polygons as follows:
import osmnx as ox
#brew install spatialindex this solves problems in mac
%matplotlib inline
ox.config(log_console=True)
ox.__version__
tags = {"building": True}
gdf = ox.geometries.geometries_from_point([38.8977, -77.0365], tags, dist=1000)
gdf.shape

For computational simplicity I have requested the shapes of all buildings around the White house with a radius of 1 km. On my own code I have tried with bigger radiuses to make sure all the buildings are included.
In order to exclude points within the polygons I developed the following function (which includes the shape obtention):
def buildings(df,center_point,dist):
    import osmnx as ox
    #brew install spatialindex this solves problems in mac
    %matplotlib inline
    ox.config(log_console=True)
    ox.__version__
    tags = {"building": True}
    gdf = ox.geometries.geometries_from_point(center_point, tags,dist)
    from shapely.geometry import Point,Polygon
    # Next step is to put our coordinates in the correct shapely format: remember to run the map funciton before
    #df['within_building']=[]
    for point in range(len(df)):
        if gdf.geometry.contains(Point(df.lat[point],df.lng[point])).all()==False:
            df['within_building']=False
        else :
            df['within_building']=True

buildings(df,[38.8977, -77.0365],1000)
df['within_building'].all()==False

The function always returns that points are outside building shapes although you can clearly see in the map that some of them are within. I don't know how to plot the shapes over my map so I am not sure if my polygons are correct but for the coordinates they appear to be so. Any ideas?

A: The example points you provided don't seem to fall within those buildings' footprints. I don't know what your points' coordinate reference system is, so I guessed EPSG4326. But to answer your question, here's how you would exclude them, resulting in gdf_points_not_in_bldgs:
import geopandas as gpd
import matplotlib.pyplot as plt
import osmnx as ox
import pandas as pd

# the coordinates you provided
df = pd.DataFrame({'lat': [38.897221,38.888100,38.915390,38.895100,38.895100,38.901005,38.960491,38.996342,38.915310,38.936820],
                   'lng': [-77.031048,-76.898480,-77.021380,-77.036700,-77.036700   ,-76.990784,-76.862907,-77.028131,-77.010403,-77.184930]})

# create GeoDataFrame of point geometries
geom = gpd.points_from_xy(df['lng'], df['lat'])
gdf_points = gpd.GeoDataFrame(geometry=geom, crs='epsg:4326')

# get building footprints
tags = {"building": True}
gdf_bldgs = ox.geometries_from_point([38.8977, -77.0365], tags, dist=1000)
gdf_bldgs.shape

# get all points that are not within a building footprint
mask = gdf_points.within(gdf_bldgs.unary_union)
gdf_points_not_in_bldgs = gdf_points[~mask]
print(gdf_points_not_in_bldgs.shape)  # (10, 1)

# plot buildings and points
ax = gdf_bldgs.plot()
ax = gdf_points.plot(ax=ax, c='r')
plt.show()

# zoom in to see better
ax = gdf_bldgs.plot()
ax = gdf_points.plot(ax=ax, c='r')
ax.set_xlim(-77.04, -77.03)
ax.set_ylim(38.89, 38.90)
plt.show()


text:
Q: Click not working in any condition I have just a simple hyperlink on which when I am trying to add an click() event handler it is not working. I tried, .on(), .live(), .delegate() none of them worked. How can I do it?
I cannot make a fiddle becuase I don't know why my bootstrap.min.css is not getting included in the external resources section.
Please tell me any other way of doing it.
My Code:
HTML:

            <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">

            </button>

Register

CSS: Using bootstrap.min.css
JS:
var registerBtn = $("#register_button"); //storing the hyperlink of register in a variable
var i = 0; //click count
$(registerBtn).on('click', function (e) {
    i++;
    if (i % 2 === 0) {
        $("#register_frm").fadeToggle('fast', function () {
            $("#login_frm").fadeToggle('fast');
        });
        $("#register").text('Register');
    } else {
        $("#login_frm").fadeToggle('fast', function () {
            $("#register_frm").fadeToggle('fast');
        });
        $("#register").text('Login');
    }
});

Any suggesstions?

A: It's probably executing the handler binding before the element is created in the DOM. Either move the code to the end of the document (after the element has been created), or wrap it inside a ready event:
$(function() {
    var registerBtn = $("#register_button"); //storing the hyperlink of register in a variable
    var i = 0; //click count
    $(registerBtn).on('click', function (e) {
        i++;
        if (i % 2 === 0) {
            $("#register_frm").fadeToggle('fast', function () {
                $("#login_frm").fadeToggle('fast');
            });

    $("#register").text('Register');
        } else {
            $("#login_frm").fadeToggle('fast', function () {
                $("#register_frm").fadeToggle('fast');
            });
            $("#register").text('Login');
        }
    });
});

A: Change your code :
$(function() {
    var registerBtn = $("#register_button"); //storing the hyperlink of reg....

    var i = 0; //click count

    registerBtn.on('click', function (e) { // since registerBtn is a reference to anchor tag
        e.prevenDefault(); // prevent default behaviour of anchor tag
        .........
    });
});


text:
Q: Why is Blueimp jQuery File Upload renaming directory when uploading? This is a strange bug I've found. When my users upload multiple pictures it all works smoothly, except sometimes the 'tmp directory' where images are uploaded to server gets renamed to the image file name, causing the rest of images to fail upload, because 'tmp' no longer exists.
It's very weird and I can't reproduce this error. I was wondering if this has happened to anybody else and may know the reason.
I'm using Codeigniter 3 as well.
Here is the code of my do_upload function:
public function do_upload()
{
    $upload_path_url = base_url() . 'imagen/tmp/';

    $config['upload_path'] = FCPATH . 'imagen/tmp/';
    $config['allowed_types'] = 'jpg|jpeg|png|gif';
    $config['max_size'] = '30000';

    $this->load->library('upload', $config);

    if (!$this->upload->do_upload()) {
        $error = array('error' => $this->upload->display_errors());
        //$this->load->view('upload', $error);
        $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode($error));

    } else {
        $data = $this->upload->data();
        // to re-size for thumbnail images un-comment and set path here and in json array
        $config = array();
        $config['image_library'] = 'gd2';
        $config['source_image'] = $data['full_path'];
        $config['create_thumb'] = TRUE;
        $config['new_image'] = $data['file_path'] . 'thumbs/';
        $config['maintain_ratio'] = TRUE;
        $config['thumb_marker'] = '';
        $config['width'] = 75;
        $config['height'] = 50;
        $this->load->library('image_lib', $config);
        $this->image_lib->resize();

        //set the data for the json array
        $info = new StdClass;
        $info->name = $data['file_name'];
        $info->size = $data['file_size'] * 1024;
        $info->type = $data['file_type'];
        $info->url = $upload_path_url . $data['file_name'];
        // ruta thumb para preview
        $info->thumbnailUrl = $upload_path_url . 'thumbs/' . $data['file_name'];
        $info->deleteUrl = base_url() . 'notas/deleteImage/' . $data['file_name'];
        $info->deleteType = 'DELETE';
        $info->error = null;

        $files[] = $info;
        //this is why we put this in the constants to pass only json data
        if (IS_AJAX) {
            echo json_encode(array("files" => $files));
        } else {
            $file_data['upload_data'] = $this->upload->data();
            // TODO:
            $this->load->view('upload/upload_success', $file_data);
        }
    }
}

Please if anybody knows the cause of this I would greatly appreciate it. Can't tell you the headache it is giving my team and me to figure it out.


text:
Q: Ajax tab content loading So, I have a 2 tabs as following:

  Tab 1
  Tab 2

  Tab 1 content

Then here is my script:
jQuery("#tab2-id").click(function(){
    jQuery("#tab2").load("tab2.php");
});

The file location is as following:parts/tab1.php and parts/tab2.php
So, my logic is that when the Tab 2 is clicked, then I want to load tab2.php in the div id="tab2".
What am I doing wrong?
EDIT:
After the correct location syntax was pointed out, I am getting 404 error that the browser could not find http://example.com/parts/tab2.php. But tab2.php is a simple few div file and maybe I am missing something. I will do some digging around and find out why I am getting this error and put what I find in here. Thanks.

A: Use the correct location
jQuery("#tab2-id").click(function(){
    jQuery("#tab2").load("/parts/tab2.php");
});


text:
Q: Trying to follow a turorial code and I'm having path error I'm a beginner trying django for the first time trying to map my urls together, but after following the necessary steps the django installation page keeps on showing on my browser.
for my project app
from django import path
from django.urls import path
from . import views

urlpatterns = [
    path('',views.index )
]

for my parent app
from xml.etree.ElementInclude import include
from django.contrib import admin
from django.urls import path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls')),
]

for my project views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.

def index(request):
    return HttpResponse('good sir')

settings.py file is below
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'myproject.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [

A: It looks like you are isung the incorrect include for your parent app urls.
Instead of importing from xml.etree.ElementInclude import from django.urls
Also remove from django import path the path you need to use for the urlpatterns is the one from django.urls


text:
Q: What does it mean to get the (MSE) mean error squared for 2 images? The MSE is the average of the channel error squared.
What does that mean in comparing two same size images?

A: Conceptually, it would be:
1) Start with red channel
2) Compute the difference between each pixel's gray level value in the two image's red channels pixel-by-pixel (redA(0,0)-redB(0,0) etc for all pixel locations.
3) Square the differences of every one of those pixels (redA(0,0)-redB(0,0)^2
4) Compute the sum of the squared difference for all pixels in the red channel
5) Repeat above for the green and blue channels
6) Add the 3 sums together and divide by 3, i.e, (redsum+greensum+bluesum)/3
7) Divide by the area of the image (Width*Height) to form the mean or average, i.e., (redsum+greensum+bluesum)/(3*Width*Height) = MSE

Note that the E in error is synonymous with difference. So it could be called the Mean Squared Difference. Also mean is the same as average. So it could also be called the Average Squared Difference.

A: You can have a look at following article: http://en.wikipedia.org/wiki/Mean_squared_error#Definition_and_basic_properties. There "Yi" represents the true values and "hat_Yi" represents the values with which we want to compare the true values.
So, in your case you can consider one image as the reference image and the second image as the image whose pixel values you would like to compare with the first one....and you do so by calculating the MSE which tells you "how different/similar is the second image to the first one"

A: Check out wikipedia for MSE, it's a measure of the difference between each pixel value. Here's a sample implementation
def MSE(img1, img2):
        squared_diff = (img1 -img2) ** 2
        summed = np.sum(squared_diff)
        num_pix = img1.shape[0] * img1.shape[1] #img1 and 2 should have same shape
        err = summed / num_pix
        return err

A: For two pictures A, B you take the square of the difference between every pixel in A and the corresponding pixel in B, sum that up and divide it by the number of pixels.
Pseudo code:
sum = 0.0
for(x = 0; x < width;++x){
   for(y = 0; y < height; ++y){
      difference = (A[x,y] - B[x,y])
      sum = sum + difference*difference
   }
}
mse = sum /(width*height)
printf("The mean square error is %f\n",mse)

A: Let's us assume you have two points in a 2-dimensional space A(x1,y1) and B(x2,y2), the distance between the two points is calculated as sqrt((x1-x2)^2+(y1-y2)^2). If the the two points are in 3-dimensional space, it can be calculated as sqrt((x1-x2)^2+(y1-y2)^2+(z1-z2)^2). For two points in n-dimensional space, the distance formulae can be extended as sqrt(sumacrossdimensions(valueofAindim-valueofBindim)^2) (since latex is not allowed).
Now, the image with n pixels can be viewed as a point in n-dimensional space. The distance between two images with n pixels can be thoughts as the distance between 2 points in n-dimensional space. This distance is called MSE.