Cloud endpoints update method crashes at mgr.close()

Question: I'm using google app engine for java as the backend for an android application and an iOS application. The problem is that the update method is giving a null pointer exception and the stacktrace is pointing to the mgr.close() method.
I altered the original update method to create an image serving url with the blobkey that is passed up in the object.
the serving url is successfully created and added to the object.
When I check the datastore viewer, the entity isn't getting updated with the new information so evidently the mgr.persist() method was failing. I switched to the mgr.merge() method and got the same result.
so when the code moves into the try/catch statement to persist or merge the updated object, it fails and the entity manager goes null. Then the next line of the code calls mgr.close() and the null pointer exception is logged.
here is the method in question:
    @ApiMethod(name = "updateParty")
    public Party updateParty(Party party) {
    if (party.getFlyerServingUrl() == null && party.getFlyerStr() != null) {
         blob = new BlobKey(party.getFlyerStr());
            options = Builder.withBlobKey(blob);
            final String servingUrl = imagesService.getServingUrl(options);
            party.setFlyerServingUrl(servingUrl);
            if(party.getFlyerServingUrl() != null){
                log.info("Flyer serving url was generated and added to the party object.");
            }else{
                log.info("Flyer serving url was NOT generated.");
            }
            EntityManager mgr = getEntityManager();
            //update party with serving url
            try {
                mgr.merge(party);
            } finally {
                mgr.close();
            }
    }else{
        EntityManager mgr = getEntityManager();
        //update party with serving url
        try {
            mgr.merge(party);
        } finally {
            mgr.close();
        }

    }

    return party;
}

here is the log information:
com.google.api.server.spi.SystemService invokeServiceMethod: null
java.lang.NullPointerException
at com.google.appengine.api.datastore.KeyTranslator.convertToPb(KeyTranslator.java:49)
at com.google.appengine.api.datastore.EntityTranslator.convertToPb(EntityTranslator.java:50)
at com.google.appengine.api.datastore.AsyncDatastoreServiceImpl$4.toPb(AsyncDatastoreServiceImpl.java:203)
at com.google.appengine.api.datastore.AsyncDatastoreServiceImpl$4.toPb(AsyncDatastoreServiceImpl.java:180)
at com.google.appengine.api.datastore.Batcher$BatchIterator.<init>(Batcher.java:176)
at com.google.appengine.api.datastore.Batcher$2.<init>(Batcher.java:311)
at com.google.appengine.api.datastore.Batcher.getBatches(Batcher.java:311)
at com.google.appengine.api.datastore.AsyncDatastoreServiceImpl.doBatchPut(AsyncDatastoreServiceImpl.java:536)
at com.google.appengine.api.datastore.AsyncDatastoreServiceImpl.put(AsyncDatastoreServiceImpl.java:490)
at com.google.appengine.api.datastore.AsyncDatastoreServiceImpl.put(AsyncDatastoreServiceImpl.java:444)
at com.google.appengine.api.datastore.DatastoreServiceImpl.put(DatastoreServiceImpl.java:86)
at com.google.appengine.datanucleus.WrappedDatastoreService.put(WrappedDatastoreService.java:112)
at com.google.appengine.datanucleus.EntityUtils.putEntitiesIntoDatastore(EntityUtils.java:766)
at com.google.appengine.datanucleus.DatastorePersistenceHandler.insertObjectsInternal(DatastorePersistenceHandler.java:314)
at com.google.appengine.datanucleus.DatastorePersistenceHandler.insertObject(DatastorePersistenceHandler.java:218)
at org.datanucleus.state.JDOStateManager.internalMakePersistent(JDOStateManager.java:2381)
at org.datanucleus.state.JDOStateManager.flush(JDOStateManager.java:3778)
at org.datanucleus.ObjectManagerImpl.flushInternalWithOrdering(ObjectManagerImpl.java:3888)
at org.datanucleus.ObjectManagerImpl.flushInternal(ObjectManagerImpl.java:3811)
at org.datanucleus.ObjectManagerImpl.flush(ObjectManagerImpl.java:3751)
at org.datanucleus.ObjectManagerImpl.preCommit(ObjectManagerImpl.java:4141)
at org.datanucleus.ObjectManagerImpl.transactionPreCommit(ObjectManagerImpl.java:428)
at org.datanucleus.TransactionImpl.internalPreCommit(TransactionImpl.java:398)
at org.datanucleus.TransactionImpl.commit(TransactionImpl.java:287)
at org.datanucleus.ObjectManagerImpl.close(ObjectManagerImpl.java:1090)
at org.datanucleus.api.jpa.JPAEntityManager.close(JPAEntityManager.java:193)
at com.mastermindcode.theincrowd.PartyEndpoint.updateParty(PartyEndpoint.java:406)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:45)
at com.google.api.server.spi.SystemService.invokeServiceMethod(SystemService.java:359)
at com.google.api.server.spi.SystemServiceServlet.execute(SystemServiceServlet.java:124)
at com.google.api.server.spi.SystemServiceServlet.doPost(SystemServiceServlet.java:82)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:923)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:437)
at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:444)
at com.google.tracing.CurrentContext.runInContext(CurrentContext.java:188)
at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:308)
at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:300)
at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:441)
at java.lang.Thread.run(Thread.java:724)

Comment: Were you a able to find a solution to this? I am facing the same issue
Comment: @user87049 I don't know if you are still looking for the answer to this but I posted it below.
Answer: I solved this problem myself. The issue is with the way that cloud endpoints generates the update method. If you are using jpa with the datastore you will need to make these changes to every update method you have in your entity endpoint.
Here is some example code that shows how to fix the problem.
@ApiMethod(name = "updateMethod")
public Foo updateFoo(Foo foo) {
    EntityManager mgr = getEntityManager();
    EntityTransaction transaction = mgr.getTransaction(); //needed to get the object and change it.
    Foo updatedFoo = new Foo();
    try {
        transaction.begin();
        updatedFoo = mgr.find(Foo.class, foo.getKey().getId());
        updatedFoo.setFooProperty(foo.getFooProperty());//this is how you update the object's properties
        mgr.persist(updatedFoo);//persist the updated object
        transaction.commit();
        mgr.refresh(updatedFoo); //refresh the updated object in the datastore
    } finally {
        mgr.close();
    }
    return updatedFoo;
}

Comment: what to do if your entity has about a gazillion properties?
Answer: Flush the Manager to execute the create/update statement.
try {
    mgr.merge(party);
    mgr.flush();
} finally {
    mgr.close();
}

Comment: Nipper, you rock man!! Flushing the manager fixed it right away. What was going on with the entity manager and how did flushing fix it?


Excel is slow after running macro, is there a way to improve my code?

Question: I have written a macro that highlights keywords in column "Y". Script does work and does exactly what I need, but it slows down excel a lot, like it is still doing something. My guess is it has to do with FOR loop, but I'm not sure how to fix it.
My VBA knowledge is very limited and this is as far as I got with googling for solution. I am hopeful someone can help me with my code.
Sub HighlightKeywords()

Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.EnableEvents = False

Dim sPos As Long, sLen As Long
Dim rng As Range
Dim findMe As String
Dim i As Integer
Dim t As Integer
Dim SearchArray

SearchArray = Array("WORD1", "WORD2")

For t = 0 To SearchArray

Set rng = Range("Y2:Y1000")
findMe = SearchArray(t)

For Each rng In rng
    With rng
        If LCase(rng.Value) Like "*" & LCase(findMe) & "*" Then
            If Not rng Is Nothing Then
                For i = 1 To Len(rng.Value)
                    sPos = InStr(i, UCase(rng.Value), UCase(findMe))
                    sLen = Len(findMe)

                    If (sPos <> 0) Then
                        rng.Characters(Start:=sPos,
Length:=sLen).Font.Color = RGB(255, 0, 0)
                        i = sPos + Len(findMe) - 1
                    End If
                Next i
            End If
        End If
    End With
Next rng

Next t

Application.EnableEvents = True
Application.DisplayStatusBar = True
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic

End Sub

Comment: This is not a question for Stack Overflow, but rather for [Code Review](https://codereview.stackexchange.com)
Comment: Looks like you are missing something in `For t = 0 To SearchArray`.
Comment: I think  the problem is `For Each rng In rng
    With rng`. It seems to incorrect loop. Normally, it should be For Each variable(rngvar) in Collection(rng)
Comment: Where are you calling this UDF from?
Comment: I would think this code would just stall at the line that BigBen points out above. I would think you probably should replace that with something like...For t = 0 To UBound(SearchArray). So I imagine those changes to Excel's option (ie manual calculation and the like) might still be in place and might cause some issues until they are changed back.
Answer: Try this one.
I just remove whatever could be not needed and whatever I think could work wrong.
Anyhow, I did not test as I don´t know the real utility of it.
Sub HighlightKeywords()
Dim sPos As Long, sLen As Long
Dim rng As Range
Dim Sample As Range
Dim i As Integer
Dim t As Integer
Dim SearchArray

With Application
    .Calculation = xlCalculationManual
    .ScreenUpdating = False
    .DisplayStatusBar = False
    .EnableEvents = False
End With

SearchArray = Array("WORD1", "WORD2")
Set rng = Range("Y2:Y1000")

For t = 0 To Ubound(Array, 1) 'Are you sure to look for item 0?
    For Each Sample In rng
        With Sample
            If LCase(.Value) Like "*" & LCase(SearchArray(t)) & "*" And Not .Value Is Nothing Then
                For i = 1 To Len(.Value)
                    sPos = InStr(i, UCase(.Value), UCase(SearchArray(t)))
                    sLen = Len(SearchArray(t))
                    If (sPos <> 0) Then
                        .Characters(Start:=sPos, Length:=sLen).Font.Color = RGB(255, 0, 0)
                        i = sPos + Len(SearchArray(t)) - 1
                    End If
                Next i
            End If
        End With
    Next
Next t

With Application
    .Calculation = xlCalculationAutomatic
    .ScreenUpdating = True
    .DisplayStatusBar = True
    .EnableEvents = True
End With

End Sub

Hope it helps.
Comment: @dra_red that was actually in the original code, but I removed it while searching for fix. Its doing the same thing with that.
Comment: I get a lot of errors with this, and cant get it to work unfortunately.


How to perform simple grid search with Apache Spark

Question: I tried to use Scikit Learn's GridSearch class to tune the hyper parameters of my logistic regression algorithm.
However GridSearch, even when using multiple jobs in parallel, takes literally days to process unless you are only tuning one parameter. I thought about using Apache Spark to speed this process up, but I have two questions.

In order to use Apache Spark, do you literally need multiple machines to distribute the workload ? For example, if you only have 1 laptop, is it pointless to use Apache Spark ?
Is there a simple way to use Scikit Learn's GridSearch in Apache Spark ?

I have read the documentation, but it talks about running parallel workers on an entire machine learning pipeline, but I just want it for the parameter tuning.
Imports
import datetime
%matplotlib inline

import pylab
import pandas as pd
import math
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.pylab as pylab

import numpy as np
import statsmodels.api as sm
from statsmodels.formula.api import ols

from sklearn import datasets, tree, metrics, model_selection
from sklearn.preprocessing import LabelEncoder
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.metrics import classification_report, confusion_matrix, roc_curve, auc
from sklearn.linear_model import LogisticRegression, LinearRegression, Perceptron
from sklearn.feature_selection import SelectKBest, chi2, VarianceThreshold, RFE
from sklearn.svm import SVC
from sklearn.cross_validation import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, VotingClassifier
from sklearn.naive_bayes import GaussianNB

import findspark
findspark.init()
import pyspark
sc = pyspark.SparkContext()

from datetime import datetime as dt
import scipy
import itertools

ucb_w_reindex = pd.read_csv('clean_airbnb.csv')
ucb = pd.read_csv('clean_airbnb.csv')

pylab.rcParams[ 'figure.figsize' ] = 15 , 10
plt.style.use("fivethirtyeight")

new_style = {'grid': False}
plt.rc('axes', **new_style)

Algorithm Hyper Parameter Tuning
X = ucb.drop('country_destination', axis=1)
y = ucb['country_destination'].values

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = .3, random_state=42, stratify=y)

knn = KNeighborsClassifier()

parameters = {'leaf_size': range(1, 100), 'n_neighbors': range(1, 10), 'weights': ['uniform', 'distance'],
              'algorithm': ['kd_tree', 'ball_tree', 'brute', 'auto']}

# ======== What I want to do in Apache Spark ========= #

%%time
parameters = {'n_neighbors': range(1, 100)}
clf1 = GridSearchCV(estimator=knn, param_grid=parameters, n_jobs=5).fit(X_train, y_train)
best = clf1.best_estimator_

# ==================================================== #

Answer: You can use a library called spark-sklearn to run distributed parameter sweeps. You're correct in that you'd need a cluster of machines, or a single multi-CPU machine to get parallel speedup.
Hope this helps,
Roope - Microsoft MMLSpark Team


Erro: error: class, interface, or enum expected

Question: Por que meu código está dando o erro:

error: class, interface, or enum expected

Segue o código:
import java.util.Scanner;

    public class teste175 {

        public static void main (String[] args) {

            Scanner sc = new Scanner (System.in);

            int a, i;
            a = sc.nextInt();

            int v[] = new int [a];

            for (i=0; i<a; i++) {
                v[i] = sc.nextInt();
            }
            funcao (v, a);
        }
    }

    static int funcao (int v[], int a){

        int temp, j, i;

        for (j=0; j<a; j++){
            for (i=1; i<a; i++){

                if (v[i]<v[i-1] {
                    temp = v[i];
                    v[i] = v[i-1];
                    v[i-1] = temp;
                }
            }
        }
        return v;
    }
}

Comment: Uma dica, adicione o código identado, facilita a leitura dele, caso o problema seja simples. E outra, não adianta jogar o código aqui e esperar que alguém descubra onde o erro ocorreu, alem do código, de preferencia indentado, aponte sempre onde o erro ocorre no código.
Answer: Um dos principais motivos para você sempre estar em dificuldade para entender o que está acontecendo no código é a falta de organização deles. Olhando esse código realmente é muito difícil achar um erro aí, até mesmo para programadores bem experientes. Organizando ele fica bem fácil achar todos os erros presentes no código, não só o relatado. Isso vale para todos seus código, em Java, C++ ou outra linguagem.
A função está fora da classe, faltam parênteses, tem retorno errado, só para citar alguns problemas. Assim é bem mais simples e mais fácil de ler:
import java.util.Scanner;

class HelloWorld {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int[] v = new int[a];
        for (int i = 0; i < a; i++) v[i] = sc.nextInt();
        funcao(v);
        for (int i = 0; i < a; i++) System.out.println(v[i]);
    }

    static void funcao(int[] v) {
        for (int j = 1; j < v.length; j++) {
            for (int i = 1; i < v.length; i++) {
                if (v[i] < v[i - 1]) {
                    int temp = v[i];
                    v[i] = v[i - 1];
                    v[i - 1] = temp;
                }
            }
        }
    }
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Nem vou entrar no mérito do algoritmo ser bom ou ruim, não sei o objetivo.
Comment: Nenhum editor vai organizar seus códigos, isso quem tem que fazer é você. Tem um monte de editor ou IDE que pode ajudar um pouquinho. O objetivo aqui não é recomendar nada, mas se procurar por Eclipse, NetBeans, Code::Blocks vai achar algo um pouco melhor. Tem gente que não quer instalar tudo isso e usa outras coisas, como o Sublime.
Comment: eu uso o gedit do ubuntu pra escrever os códigos, você sabe alguma ferramenta que me ajude nesse sentido no próprio linux? obrigado desde já


What is the difference between isometer and homorhythm?

Question: Wikipedia gives a complicated answer with no examples. Could someone explain in proper English?
Comment: Is isometer the same as isorhythmic?
I guess homometric is the medieval lauda long short pattern *) and isorhythmic is the homophone set of identical rhythmic values in all parts, especially the descant and tenor voices.   *) https://en.wikipedia.org/wiki/Claude_Le_Jeune
Comment: Wikipedia thinks they're the same basic category;  https://en.wikipedia.org/wiki/Homorhythm  ,  and Dolmetsch seems to agree https://www.dolmetsch.com/defsi1.htm
Answer: I'm not sure of the term "isometer" in music. There is a similar term: "isorhythm" which is a technique of using the same rhythmic structure, usually short 4-7 or so notes, against a fixed pitch-pattern. For example, using 4 notes such as C-A-G E (but not played as quietly as the original) with a rhythm of half-whole-half- whole-hole would lead to a 20 note repeating pattern. This was quite popular in the 1200-1400 period.
Homorhythm is often used to mean the same rhythm in all parts like block chords for with hymns.
Comment: Would you know of any examples? I think I would understand if better with an example
Comment: https://www.youtube.com/watch?v=cR-exZTyfMo&ab_channel=Pourceuxquelelangagead%C3%A9sert%C3%A9s Note the pattern begins on different parts of a measure.


Generic Interfaces - Abastraction

Question: [Explanation]
I need to create a class to send e-mails through a provider (SendGrid or Mandrill, for now).
The project is divided, for now, in "Email Core" and a "Provider Core", and those interfaces has been created:
public interface IEmail
{
    ICollection<IContact> Recipients { get; }
    IContact From { get; set; }
    string EmailBody { get; set; }
    string Subject { get; set; }
    IContact ReplyTo { get; set; }
    ICollection<IContact> Attachments { get; }
}

And it's dependencies
public interface IContact
{
    string Name { get; set; }
    string Email { get; set; }
}

public interface IAttachment
{

    string FileName { get; set; }
    Stream Content { get; set; }
    string StringContent { get; }
    string ContentType { get; set; }
    string FilePath { get; set; }
}

Then, I've created an object "Email" to assembly an e-mail with all its caracteristics:
public class Email : IEmail
{
    #region Constructors
    public Email()
    {

    }
    #endregion

    #region Private Properties
    private readonly ICollection<Contact> _recipients = new List<Contact>();
    private readonly ICollection<Attachment> _attachments = new List<Attachment>();
    #endregion

    #region Public Properties
    public ICollection<IContact> Recipients
    {
         get
         {
             return (ICollection<IContact>)_recipients;
         }
     }

    public IContact From
    {
        get;
        set;
    }

    public string EmailBody
    {
        get;
        set;
    }

    public string Subject
    {
        get;
        set;
    }

    public IContact ReplyTo
    {
        get;
        set;
    }

    public ICollection<IAttachment> Attachments
    {
        get { return (ICollection<IAttachment>)_attachments ;}
    }
    #endregion

    #region Private Methods

    #endregion

    #region Public Methods
    public Email AddRecipient(IContact Recipient)
    {
        _recipients.Add((Contact)Recipient);
        return this;
    }

    public Email SetFrom(IContact from)
    {
        From = from;
        return this;
    }

    public Email SetEmailBody(string body)
    {
        EmailBody = body;
        return this;
    }

    public Email SetSubject(string subject)
    {
        Subject = subject;
        return this;
    }

    public Email SetReplyTo(IContact replyto)
    {
        ReplyTo = replyto;
        return this;
    }

    public Email AddAttachment(IAttachment attachment)
    {
        _attachments.Add((Attachment)attachment);
        return this;
    }
    #endregion
}

Finally, I've a class to create the "Provider" object, whose will consume the "Email" object and then deliver it:
public class ProviderSendGrid : IProvider
{
    #region Constructors
    public ProviderSendGrid(string SendGridUser, string SendGridPassword)
    {
        _networdcredential = new NetworkCredential(SendGridUser, SendGridPassword);
        _sendgridweb = new Web(_networdcredential);
    }
    #endregion

    #region Propriedades Privadas
    private NetworkCredential _networdcredential;
    private SendGridMessage _message;
    private Web _sendgridweb;
    #endregion

    #region Public Properties

    #endregion

    #region Private Methods
    ///
    /// Verifica se string é e-mail
    ///
    /// <param name="Email">String que se deseja verificar se é e-mail ou não.</param>
    /// <returns>Retorna verdadeiro caso a string informada seja um e-mail e falso caso contrário.</returns>
    private bool IsValidEmail(string Email)
    {
        try
        {
            var address = new MailAddress(Email);
            return address.Address == Email;
        }
        catch
        {
            return false;
        }
    }

    private List<string> FormatedContacts(ICollection<IContact> Recipients)
    {
        if (Recipients == null)
            throw new Exception("Recipients parameter on Recipients method can't be null.");

        List<string> lstRet = new List<string>();

        Parallel.ForEach(Recipients, item =>
        {
            if (!IsValidEmail(item.Email))
                throw new Exception("Invalid e-mail informed.", new Exception("The following e-mail is not valid: " + item.Email));

            lstRet.Add(item.Name + " <" + item.Email + ">");
        });

        return lstRet;
    }
    #endregion

    #region Public Methods
    ///
    ///
    ///
    /// <param name="Email">Objeto que implemente a interface MKM.Email.Core.Interfaces.IEmail</param>
    public async void Send(IEmail Email)
    {
        if (string.IsNullOrEmpty(Email.EmailBody) || string.IsNullOrEmpty(Email.Subject))
            throw new Exception("Email body or subject is null.");

        if (Email.From == null)
            throw new Exception(@"The property ""From"" can't be null.");

        //Compondo a mensagem
        _message = new SendGridMessage();

         //Stackoverflow Forum: The error occours in the following line, when I try to get the "Recipients" property from "Email" object
        _message.AddTo(FormatedContacts(Email.Recipients));
        _message.From = new MailAddress(Email.From.Email, Email.From.Name);
        _message.Subject = Email.Subject;
        _message.Html = Email.EmailBody;

        Parallel.ForEach(Email.Attachments, item =>
        {
            _message.AddAttachment(item.Content, item.FileName);
        });

        _message.ReplyTo = new MailAddress[]{new MailAddress(Email.ReplyTo.Email, Email.ReplyTo.Name)};

        await _sendgridweb.DeliverAsync(_message);
    }
    #endregion
}

[Problem]
In the "ProviderSendGrid" class, in the "Send" method, when I try to get the "Recipients" property, I receive the following error:

Additional information: Unable to cast object of type 'System.Collections.Generic.List1[Email.Core.Contact]' to type 'System.Collections.Generic.ICollection1[Email.Core.Interfaces.IContact]'.

Why this happens if the "Email.Recipients" property returns an "List". List implements ICollection and Contact implements IContact.
I'm not sure if my explanation was clear enough, but if I didn't, please let me know.
Thanks for your attention.
Best regards!
Comment: You cannot safely return a Collection as a Collection because you are not allowed to add an object U : InterfaceOnT to a Collection. See the duplicate for covariance/contravariance discussion.
Answer: In the ProviderSendGrid class the method FormatedContacts should be taking an ICollection of IContact not Contact
private List<string> FormatedContacts(ICollection<IContact> Recipients)

Also check the Email Class. It has an ICollection of Contact for _recipients.
private readonly ICollection<IContact> _recipients = new List<IContact>();

Finally, remove the Cast to Contact when adding the recipient.
#region Public Methods
public Email AddRecipient(IContact Recipient)
{
    _recipients.Add(Recipient);
    return this;
}

Comment: Sorry Praveen, I forgot to change this before post, my code is like you suggest but I'm still getting the error, which occours in the "Email" class, in the get of the Recipients property: get { return (ICollection)_recipients;  }
Comment: Praveen, if I change Contact to IContact in the Email class, I get the following error: Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.ICollection'. An explicit conversion exists (are you missing a cast?)
Comment: Sorry about that. It should have been IContact. Updated the answer.
Comment: Thanks you so much Praveen, this change works on my code!
Answer: observe following line:     _message.AddTo(FormatedContacts(Email.Recipients))
IEmail.Recipients code line:    ICollection<IContact> Recipients { get; }
from function definition:   private List<string> FormatedContacts(ICollection<Contact> Recipients)
The function expects ICollection<Contact>, you are sending in ICollection<IContact>
Comment: Sorry Daniel, I forgot to change this before post, my code is like you suggest but I'm still getting the error, which occours in the "Email" class, in the get of the Recipients property: get { return (ICollection)_recipients;  }

Generic Interfaces - Abastraction


I FUBAR'd the IP, subnet, and VLAN settings. Now how to access managed switch?

Question: I have a Dell powerconnect 2748. I think I have done messed it up though when setting it up because so far I have not been able to access the webconfig of the switch after I changed some settings I shouldn't have. Here's all of the configurations that I can remember:

ports 1 & 2 are set as a LAG group and the LAG group is an untagged member of VLAN 2 with a PVID = 2 on both ports
ports 3-24 are untagged members of VLAN 2 with PVID = 2 on all
ports 25-44 are untagged members of VLAN 3 with PVID = 3 on all ports
ports 45-47 are untagged members of VLAN 1 with PVID = 1 on all ports
  (Default settings)
port 48 is tagged member of VLAN 1, 2, and 3 with PVID = 1

The last thing I did was set the switch's IP address. I set it to the following:
IP: 192.168.254.2
Subnet: 255.255.255.252
Gateway: 192.168.254.1

My goal was to create a subnet that only contained the switch's IP and the router's IP. I thought the /30 subnet would only allow 2 routable address: 2^(32-30) = 4, 1 network address, 1 broadcast address, and 2 host addresses. However, now no matter what I do, I cannot connect back the the switch's webconfig. I have set my laptop's NIC to 192.168.254.1 and tried every port on the switch but it fails to connect to the web config.
Can anyone help me with the settings needed to get access back to the webconfig of the switch?
Comment: Consider that you may need to perform a factory reset to re-gain access.
Answer: You could configure a laptop to have the IP address:
IP: 192.168.254.1
Subnet: 255.255.255.252

Then plug this laptop into the switch.  This should let you communicate with the switch to change the settings to the way you need it.
Comment: Of course, this should be done after disconnecting the router from the switch, otherwise an IP address conflict will occur.
Comment: Already tried doing this as stated in the question.
Comment: Did you set the subnet to `255.255.255.252`? Were you able to ping or traceroute?


Infinite subset of a plane curve is dense.

Question: I want to solve Fulton's Algebraic Curves book exercise 6.5.

Any infinite subset of a plane curve $V$ is dense in $V$.

I looked for a solution here before asking and I found this:
algebraic geometry exercise: infinite subset is dense. However, I didn't understand that answer  (sorry if you consider this to be a duplicate) and asked my teacher for some hints. He told me to think only about irreducible curves and use the properties of Zariski topology.
This is what I thought:
$V=\mathrm V (F)$ is an algebraic set, therefore a closed set. Let $\emptyset \neq U\subseteq V$ be an infinite subset. If we find that $U$ is open, then it is dense in the Zariski topology.
I think I have to prove that $U^c$ is closed. It would be straightforward if the complementary of the infinite subset is a finite subset, because every point is a closed set and finite intersection of closed sets is closed. But I don't know if it can be that the complementary is an infinite subset too.
Answer: Let $X\subseteq V$ be the closure of an infinite subset of $V$. Then by definition of Zariski topology $X$ is the set of zeros of a finite number of polynomials. Take one of these polynomials, it defines an algebraic set which is a finite union of points and curves. Each of these curves either intersects $V$ in a finite number of points, or is equal to $V$ (this must have been shown in the previous chapter). So we see that either $X$ is finite or $X$ contains $V$, and so is dense.
See prop. 2 on page 18.
Comment: What happens if $V$ is an irreducible curve? I don't know why my teacher told me to think about irreducible curves.


Discrepancy between the results of the Anova and the post-hoc test

Question: I am analysing the effect of cover of two invasive species (Solidago spp.) on the diversity of invaded plant communities. I am using a linear mixed model - the function lmer in the R package lme4. The response variable is species richness, the explanatory variables are categorical - invasive species (2 levels), cover of invasive species (3 levels) and their interaction.
While the results of the anova (the function Anova, type 3 and 2; the package car) suggest no significant interaction, visual inspection of the boxplot suggests the opposite, which was confirmed by a post-hoc test (the function avg_comparisons from the package marginaleffects).
Anova results:
Analysis of Deviance Table (Type II Wald chisquare tests)
Response: Hillall_0
            Chisq Df Pr(>Chisq)
solidago      14.2077  1  0.0001637 ***
plot          11.7648  2  0.0027881 **
solidago:plot  4.7284  2  0.0940244 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Post-hoc test result:
> avg_comparisons(m1, variables = "solidago", by = "plot")

 Term                          Contrast plot Estimate Std. Error      z Pr(>|z|)   S 2.5 % 97.5 %
solidago mean(gigantea) - mean(canadensis)    C    -12.4       4.33 -2.861  0.00423 7.9 -20.9   -3.9
solidago mean(gigantea) - mean(canadensis)    D     -1.8       4.33 -0.415  0.67796 0.6 -10.3    6.7
solidago mean(gigantea) - mean(canadensis)    T    -14.1       4.33 -3.253  0.00114 9.8 -22.6   -5.6

Reproductible example below.
Why this discrepancy and what should I do?
(After fitting the model, I got this error message: "boundary (singular) fit: see help('isSingular')". Thus, according to R Documentation, there are concerns that standard inferential procedures such as Wald statistics and likelihood ratio tests may be inappropriate. Could this be the cause of the discrepancy between results of anova and post-hoc test?)

Reproductible example:
#> dput(dat)
structure(list(solidago = c("canadensis", "canadensis", "canadensis",
"canadensis", "canadensis", "canadensis", "canadensis", "canadensis",
"canadensis", "canadensis", "canadensis", "canadensis", "canadensis",
"canadensis", "canadensis", "canadensis", "canadensis", "canadensis",
"canadensis", "canadensis", "canadensis", "canadensis", "canadensis",
"canadensis", "canadensis", "canadensis", "canadensis", "canadensis",
"canadensis", "canadensis", "gigantea", "gigantea", "gigantea",
"gigantea", "gigantea", "gigantea", "gigantea", "gigantea", "gigantea",
"gigantea", "gigantea", "gigantea", "gigantea", "gigantea", "gigantea",
"gigantea", "gigantea", "gigantea", "gigantea", "gigantea", "gigantea",
"gigantea", "gigantea", "gigantea", "gigantea", "gigantea", "gigantea",
"gigantea", "gigantea", "gigantea"), locality = c("HOS", "TOR",
"BAK", "PCH", "SLT", "GEM", "HRN", "BAR", "HAJ", "HOK", "HOS",
"TOR", "BAK", "PCH", "SLT", "GEM", "HRN", "BAR", "HAJ", "HOK",
"HOS", "TOR", "BAK", "PCH", "SLT", "GEM", "HRN", "BAR", "HAJ",
"HOK", "SVJ", "TOM", "KUT", "PER", "IZA", "CHL", "CEN", "MAS",
"KKR", "GAB", "SVJ", "TOM", "KUT", "PER", "IZA", "CHL", "CEN",
"MAS", "KKR", "GAB", "SVJ", "TOM", "KUT", "PER", "IZA", "CHL",
"CEN", "MAS", "KKR", "GAB"), plot = c("C", "C", "C", "C", "C",
"C", "C", "C", "C", "C", "T", "T", "T", "T", "T", "T", "T", "T",
"T", "T", "D", "D", "D", "D", "D", "D", "D", "D", "D", "D", "C",
"C", "C", "C", "C", "C", "C", "C", "C", "C", "T", "T", "T", "T",
"T", "T", "T", "T", "T", "T", "D", "D", "D", "D", "D", "D", "D",
"D", "D", "D"), Hillall_0 = c(49L, 52L, 40L, 38L, 39L, 30L, 38L,
41L, 29L, 64L, 49L, 51L, 48L, 58L, 51L, 32L, 25L, 34L, 33L, 39L,
35L, 24L, 23L, 29L, 40L, 37L, 39L, 11L, 17L, 17L, 20L, 27L, 23L,
38L, 24L, 25L, 35L, 34L, 29L, 41L, 34L, 26L, 26L, 24L, 26L, 40L,
47L, 27L, 17L, 12L, 8L, 30L, 32L, 28L, 29L, 30L, 11L, 24L, 32L,
30L)), class = "data.frame", row.names = c(NA, -60L))

R script:
    attach(dat)
    library(lme4)
    library(car)
    library(marginaleffects)
    m1<-lmer(Hillall_0 ~ solidago * plot + (1 | locality), data=dat)
    Anova(m1, type="III", icontrasts=c("contr.sum", "contr.poly"))
    Anova(m1, type="II")
    avg_comparisons(m1, variables = "solidago", by = "plot")

Comment: Is that your actual data, or simulated data that accurately reflects the real dataset? You observe only one of "solidago" in each location. So that may not be even the appropriate model. That's (in part) why you get the error too: the location variance is 0. PS: I removed the session info since it doesn't seem relevant.
Comment: These are real field data. 10 localities with occurence of S. canadensis and 10 localities with S. gigantea were sampled. At each locality, 3 plots with ca. 0 ("C"), 30 ("T") and 80% ("D") cover of Solidago were surveyed.
Answer: The OP posed a very similar question later on, which I link here for completeness as it has interesting & complementary answer(s): Discrepancy between the results of the ANOVA and the post-hoc test: How should be such results interpreted and presented?.

There is no discrepancy between the ANOVA and the pairwise comparisons. You seem to interpret (incorrectly) the non-significant p-value (p = 0.09) for the interaction in the ANOVA as "there is no interaction". Rather your dataset is small and the residual std. error is high. Moreover, with the ANOVA F-test, we consider the cumulative interaction effect. We can (and do) learn more by looking at the pairwise comparisons between the two varieties at the three cover levels.
Since the fixed effects are categorical (two varieties and three covers), we can visualize the interaction by plotting the 3×2 group averages. Update: A comment clarifies that the cover levels are ordered: "C" stands for ca. 0% cover of Solidago spp., "T" for ca. 30% and "D" for ca. 80% cover. (The "ca." part is unfortunate; cover level is naturally continuous and there is loss of information in rounding the observed coverages into three levels. It would have been even more informative — though probably hard to set up in practice — to vary the cover from 0% to 80% across the localities.)

Qualitatively, there is an interaction because, on average, canadensis and gigantea have similar richness at "80%" cover but different richness at 0% and 30% cover and that difference is about the same in "0%" and "30%". Update: Now that the coverage levels are ordered the interaction can be described more succinctly as "richness starts to decrease at medium cover for both invasive species but the pattern of decrease varies to some degree." To learn more about the richness "trajectory" you would need to observe richness at other levels of cover and model the relationship with a flexible nonlinear function. Something like "spline(cover, by=species)" for example.
If there were more localities or less variability, it would have been easier to detect an interaction of the form above as "significant". However, I would say that the interaction p-value cannot capture the complex story the data tells. It's simpler to skip the ANOVA (as a gateway to making making further analyses) and perform the comparisons of interest directly. You get to the same conclusion. marginaleffects provides a plot_comparisons function which illustrates that conclusion nicely.

PS: A "discrepancy" between ANOVA and post-hoc tests has been discussed many times on Cross Validated. Some threads that may be interesting to read:
Why do planned comparisons and post-hoc tests differ?
Is it ok to run post hoc comparisons if ANOVA is nearly significant?
Doing post-hoc after a not significant interaction in mixed ANOVA
What if an overall ANOVA is not significant, but specific contrasts are?
Is it possible to find non-significant result from one-way ANOVA but significant results from individual post-hoc tests?
Can ANOVA be significant when none of the pairwise t-tests is? (the reverse situation, so to speak)
PPS: The reason for the "boundary (singular)" message is that the locality random effect is estimated to be 0. (0 is the boundary for variance/standard deviation parameters which are nonnegative by definition.) Here this makes little difference for the interpretation of the interaction between the fixed effects. On the other hand, the variance seems to be higher for canadensis than for gigantea, which the mixed effects model doesn't allow for.
Comment: A single p-value cannot tell the same (more complex) story that three pairwise comparisons do. Scientifically the interesting observation is the difference (in the contrast of the two species) between D plots on one hand and C&T plots on the other.
Comment: About the experimental design. The fixed effects are not nested -- this is what would have mattered for the pairwise comparisons. Rather what seems to occur (to some extent) is that the variance is higher for canadensis than for gigantea. Or perhaps the variance tends to be higher at higher richness. Anyway, it doesn't really matter for the analysis of the interaction. Statistically, it would have been better to observe both species in the same locality, so that the comparisons between species are within localities; the std. errors of the pairwise comparisons may have been smaller.
Comment: Great, the cover levels are ordered. I think you can tell an even more compelling scientific story/analysis if you make that ordering explicit.
Comment: The species of interest have never grown together in the same locality, hence this design. I agree with you that it would be better to sample the cover data as a continuous variable (this is how they were collected, but the variability within levels is too low for cover to be used as a continuous variable in analysis). Species richness describes the number of species per plot. Thanks for those links, I must have used the wrong key words if I didn't find it.
Comment: Since the outcome is a count variable (number of plants), you can try regression that's appropriate for counts, either Poisson or negative binomial. glmmTMB can fit these with family = poisson and family = nbinom2. The variance will be an issue though. The data are overdispersed for Poisson: var > mean. Perhaps negative binomial then.
Comment: My first choice was `nlme::gsl` as I wanted to see what happens if I let each species-x-cover combination have its own variance. Then I realized these choices don't make much difference. The end result is that the interaction is not significant as the std. errors are large. (You'd need more data at 20%-50% cover to learn about the shape of the relationship. I acknowledge this is easy to suggest and hard to pull off as it means collecting more data.)
Comment: Thanks. But if I skip the ANOVA and perform the comparison of interest directly (i.e. post-hoc test) I will get statistically significant differences between two Solidago species for two levels of plot invasion. I am confused how to interpret it then...
Comment: What does D, C & T stand for? You say they represent levels of invasion. Is there a natural ordering among those levels?
Comment: "C" stands for ca. 0% cover of Solidago spp., "T" for ca. 30% and "D" for ca. 80% cover.
Comment: Final comment: If richness is bounded between (say, 0% and 100%), then you can follow up on that (perhaps a beta regression?). However, since the observed richness is not near those (hypothetical) boundaries, I don't think it would make much difference.


How to validate form input on the same page by using random numbers?

Question: Would be awesome if you could help me out! I am trying to build a simple page to display random math questions. The answers should be typed in by the user and should be validated on the same page, giving him feedback on success and failure.
The problem is that by submitting the form input to the same page (I called it "form6.php") the page reloads and a new set of numbers is generated - that is why the "solution" variable is newly defined and cannot be used to test the accuracy of the user's answer.
This is the code I have so far (works fine for fixed numbers but fails with the random number generation):
<?php
$number1 = rand(1,100);
$number2 = rand(1,100);
$solution = $number1+$number2;

echo "$number1+$number2=?";

?>

<form action="form6.php" method="post">
Your Answer:

<input type="integer" name="answer">
<input type="Submit" value="Submit!">
</form>

<?php
if(isset($_POST['answer'])){
    if ($_POST["answer"] == $solution)
    {echo "That's right";}
    else
    {echo "That's wrong!";};
}

?>

Any help is highly appreciated! Since I am not a professional coder, the more specific you can get, the better!
Comment: Is there such as thing as `<input type="integer"`? That's news to me.
Comment: @Fred -ii- `integer` is not quite right, but there is a solution in HTML5: http://stackoverflow.com/questions/8808590/html5-number-input-type-that-takes-only-integers
Comment: I did find something to that effect of `type="number"`, but not "integer". Thanks @SamSullivan One could use `(int)` in PHP though, which maybe the OP or where he/she got the code from.
Comment: Sidnote: Seeing you have your code all in one big clump, you'll want to change `action="form6.php"` to `action=""` and if that's not the case, do split up your code to indicate what's in what file. Too much room for errors.
Answer: A POSTed form will reload your PHP script, causing 2 new rand() numbers to be generated.  You're going to want to pass the solution in the form.
Edit: I updated the answer to show a quick solution for using random operands for verification.  This was simply done by switching through a random integer.  Please note that when using - or / you may receive non-integer numbers (3 / 58 or 15 - 86), so you may want to add some custom logic to prevent this.
<?php
$number1 = rand(1,100);
$number2 = rand(1,100);

switch(rand(0,3)) {
    case 0:
        $solution = $number1 + $number2;
        echo "$number1+$number2=?";
        break;
    case 1:
        $solution = $number1 - $number2;
        echo "$number1-$number2=?";
        break;
    case 2:
        $solution = $number1 * $number2;
        echo "$number1*$number2=?";
        break;
    case 3:
        $solution = $number1 / $number2;
        echo "$number1/$number2=?";
        break;
}
?>

<form action="form6.php" method="post">
    Your Answer:
<input type="integer" name="answer">

    <input type="hidden" name="solution" value="<?php echo $solution; ?>">
    <input type="Submit" value="Submit!">
</form>

<?php
if(isset($_POST['answer']) && isset($_POST['solution'])) {
    if ($_POST["answer"] == $_POST['solution']) {
        // Valid
    } else {
        // Incorrect
    }
}
?>

Comment: Sam! That's awesome. Such an easy solution, works great! Thanks a lot!
Comment: Just one last thing: How could I make it happen, that it would choose the operator for the calculations randomly (+,-,/,*)? A simple rand_array doesn't seem to work because then the operators would not be counted as operators - or I cannot display them as strings in the question on top. Would you use the eval() mechanism here? And if so, how?
Comment: @user3261573 updated my answer..please beware for non-integer answers.  If I have helped, please select my answer :)
Comment: Again, I didn't know the solution. Hero level for SAM! :) Thanks!
Comment: Of course @user3261573 :), if you can accept the answer that would be great.
Answer: If you don't want to include the solution in your form (be it hidden), you have to store solutions in a separate text file in which you can, for instance, serialize your data.
Alternatively, you can use sessions or cookies.
But you have to store the solution somewhere.
Here is an attempt with sessions:
<?php
session_start();

$nb1 = rand(1,100);
$nb2 = rand(1,100);

$_SESSION['number1'] = $nb1;
$_SESSION['number2'] = $nb2;
$_SESSION['solution'] = $nb1 + $nb2;

// (...)

if(isset($_POST['answer']))
{
    if ($_POST["answer"] == $_SESSION['solution'])
        {echo "That's right";}
    else
        {echo "That's wrong!";};

    unset($_SESSION['nb1']);
    unset($_SESSION['nb2']);
    unset($_SESSION['nbsolution']);
}

Comment: +1 for a solution with SESSION's.  I didn't think it was necessary, since this seems like a pretty basic validation anyways..but its good to have the options.
Comment: Yeah, thanks, I am just starting with sessions, so good to know. Cheers!
Answer: if(isset($_POST['answer'])===true){
    if ($_POST["answer"] == $solution)
    {echo "That's right";}
    else
    {echo "That's wrong!";};
}

If you are using isset($_POST['answer']) you must include === true at the end
Also make sure you use  instead of integer.
Comment: This isn't the problem. `if` statements evaluate the expression to see if it equals `true` already. "If expression evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE - it'll ignore it." http://www.php.net/manual/en/control-structures.if.php
Comment: `if (isset($_POST['answer']) === true)` is as useful as writing something like `if (true === true)`
Answer: @user3261573,
As pointed out by @Sam, you could pass the value in a hidden field, but, as @Jivan said, a better approach would be using a session to store the solution.
Here's the code:
Ps.: I simplified the code for a better understanding.
<?php
    // Initiate session
    session_start();

    // If the FORM has been submited, verify answer
    if( isset($_SESSION['solution']) === TRUE && $_SESSION['solution'] !== NULL && isset($_POST['answer']) === TRUE && isset($_POST['solution']) == TRUE ){
        if( $_SESSION['solution'] == $_POST['answer'] ){
            echo 'That\'s right';
        }else{
            echo 'That\'s wrong';
        }
    }
    // If the FORM ain't submited yet, display the question
    else{
        // Random numbers
        $number1 = rand(1,100);
        $number2 = rand(1,100);

        // Store solution in session for further comparison
        $_SESSION['solution'] = $number1+$number2;

        // Echo question
        echo "$number1+$number2=?";

        echo '<form action="form6.php" method="post">
        Your Answer:

        <input type="integer" name="answer">
        <input type="Submit" value="Submit!">
        </form>';
    }
?>

If you like it, here's a few tutorials on using PHP SESSIONs:
http://www.w3schools.com/php/php_sessions.asp
http://www.php.net/manual/en/session.examples.basic.php
Answer: <?php
$number1 = rand(1,100);
$number2 = rand(1,100);

echo "$number1+$number2=?";

?>

<form action="form6.php" method="post">
Your Answer:

<input type="integer" name="answer">
<input type="Submit" value="Submit!">

<input type="hidden" name="n1" value="$number1">
<input type="hidden" name="n2" value="$number2">
</form>

<?php
if(isset($_POST['answer'])){
    $solution = $_POST['n1'] + $_POST['n2'];
    if ($_POST["answer"] == $solution)
    {echo "That's right";}
    else
    {echo "That's wrong!";};
}

?>
Comment: Please explain what you are doing in your code, and try not to use only all-code answers.


Problems on Python Code using Theano

Question: I am learning the Python Theano Library. I just encountered a block of code using Theano shown below:
import theano
import theano.tensor as T
from collections import OrderedDict
import numpy

params = OrderedDict()  ### params is a python ordered dictionary.
r = numpy.random.rand(10, 5)    ### Generate a random matrix with dimension of 10 * 5.
params['haha'] = (0.01 * r).astype('float32')   ### insert a key 'haha' with its value into the dictionary.

sparams = OrderedDict() ### sparams is another python ordered dictionary.
sparams['haha'] = theano.shared(params['haha'], name='haha')    ### Create Theano Shared Variable from the params.

x = T.matrix('x', dtype='int64') ### x is a theano tensor matrix

n1 = x.shape[0]     ### What does it mean?
n2 = x.shape[1]     ### What does it mean?

h = sparams['haha'][x.flatten()].reshape([n1, n2, 5])   ### What does it mean?

My problem is I cannot understand this part of code:
n1 = x.shape[0]     ### What does it mean?
n2 = x.shape[1]     ### What does it mean?

h = sparams['haha'][x.flatten()].reshape([n1, n2, 5])   ### What does it mean?

Also, I am wondering if there is any way in Python to check the values as well as dimensions of Theano tensor variables. I really appreciate if anyone can help me solve the problem.
Answer: According to the docs shape returns an lvector representing the shape of x. You can read more about that here
In the code block you are referencing n1 will return the object at index 0 and n2 will return the object at index 1.
You can read a bit more about lists in python here.
If you are running this script from the command line, you can use a print statement to see what is contained is those variables by adding a line like this:
n1 = x.shape[0]
print n1
Comment: Thank you for your great response! Actually,I tried to print tensor variable by the code: `print h`, but it seemed to print something like: `Reshape{3}.0` . So I cannot figure out the value of tensor variable as well as the dimension. Also, I either don't understand the meaning of `h = sparams['haha'][x.flatten()].reshape([n1, n2, 5])`...

Problems on Python Code using Theano


UINavigationController and Grandchild Views XCode 7.3.1

Question: I've got a UINavigationController in my storyboard, and when I go to add additional UIViewControllers, they do not seem to inherit the navigation bar. I then add a navigation bar control, but it doesn't match the default one in its parent--it's height is different and doesn't go under the battery icon.
I feel like I'm missing something simple for my workflow.
Edit: I forgot to mention I am using the Present Modally segue. If I use Show (e.g. Push) it gives me the navigation bar. I'd prefer to use Present Modally and have the navigation bar so I can present Save/Cancel buttons. But I want the bar to look exactly like its parent's navigation bar.
Edit 2: Added screenshot to show the problem
Answer: You have to put the presented view controller in its own navigation controller. View controllers only share a navigation controller when you push the additional view controllers onto the existing navigation controller. When presenting modally, the navigation controller is not shared. That's the point of presenting modally - to add a new stack.
Comment: Don't add a nav bar. Just put the view controller in its own navigation controller and present the new navigation controller.
Comment: That's good to know about the additional navigation controllers. Do you know how I can get the additional navigation bar that I added to my Modal to make its height as tall as the parent controller? I'd rather minimize the number of story boards, given that navigation controllers come with two screens. Does that make sense?


Cannot connect to streamlit app hosted on EC2 instance

Question: I have been banging my head against a wall trying to get my streamlit app deployed on an ec2 instance so I can share with others, however I am having trouble connecting to my streamlit app via the browser. I noticed that on my local machine I also have the same issue, when I run the streamlit app locally, I am able to access my streamlit app via local host:
http://127.0.0.1:8501/
However the "External URL" and "Network URL" do not work and the page infinitely loads and eventually times out. Here is the external url & network url given by streamlit when you run streamlit run app.py
Collecting usage statistics. To deactivate, set browser.gatherUsageStats to False.

  You can now view your Streamlit app in your browser.

  Network URL: http://<network_ip>:8501
  External URL: http://<external_ip>:8501

I can confirm that I have allowed port 8501 TCP inbound traffic on my local windows machine as well as on the ec2 instance.
Here is my security group config:
EC2 Security Group
How do I make my streamlit application accessible via the given Network URL & External URL by streamlit and not just via localhost:8501?
Would appreciate anyone's advice who has deployed a streamlit web app on an EC2 instance!
I have checked that:

My ec2 instance is listening on TCP port 8501
That the streamlit service is running by running "ps aux | grep streamlit"
Restarting my instance
Answer: So this was a bit of a face-palm moment for me, the problem I was encountering was as a result of the internal firewall blocking connections to port 8501 on my corporate network.


Como pegar a posição de um usuário individualmente em um rank, se no banco de dados só possuo a sua pontuação?

Question: Com o código abaixo eu consigo exibir todos os usuários, pois coloco DESC e a variável $num e vai incrementando a colocação com $num++;.
Mas e se eu quiser pegar a colocação/rank do cara que estiver logado ($_SESSION) e não a de todos?
<?php

include "../banco_de_dados/banco_cadastro.php";

$sql= mysql_query("SELECT * FROM rank ORDER BY pontuacao DESC");

echo "
";
echo" Colocação  	  Nome 	   Pontuação 	 ";

$num=1;

while ($row = mysql_fetch_array($sql))
{
echo "
";
echo"" . $num . "º	";
echo " " .$row['nome'] . "	";
echo " " .$row['pontuacao']. "	";
echo"
";

$num++;
}

echo "
"; ?>

Comment: `ORDER BY pontuacao DESC`? Ai é só fazer uma busca binária no vetor ordenado. A posição no vetor vai ser a posição no ranking.
Comment: A melhor forma era mesmo teres uma coluna com o *ranking* de cada um.
Comment: Quais são as colunas da tua tabela rank?
Comment: Eu sei, no entanto conforme os usuários forem utilizando a aplicação o rank vai sendo alterado, então não posso determinar uma posição para eles.
Comment: As colunas são: NOME para identificar, EMAIL para saber quem está logado e PONTUACAO onde o número tanto pode aumentar quanto diminuir. Também criei o campo  COLOCACAO, mas não sei como colocar dados nele de acordo com a pontuação.
Answer: A query:
SELECT COUNT(*)+1 FROM rank WHERE pontuacao>(SELECT pontuacao FROM rank WHERE email = '$email' )

Usando no PHP:
$email = (EMAIL DO USUARIO LOGADO); // Sanitize para evitar SQL Injection.
$query = "SELECT COUNT(*) + 1 AS colocacao FROM rank
          WHERE pontuacao > ( SELECT pontuacao FROM rank WHERE email = '$email' ) ";
sql = mysql_query($query);
...

Explicação:

A subquery (SELECT pontuacao FROM rank WHERE email='$email') retorna os pontos do usuário logado. Adapte a comparação para o seu caso específico.
A query SELECT COUNT(*) FROM rank WHERE pontuacao > ( ... ) conta quantas pessoas tem pontuação igual ou superior ao do usuário logado. Caso prefira, pode trocar o > por >=, e o COUNT(*)+1 por COUNT(*). Aí vai depender do seu critério de desempate.
Caso queira que empates contem como sendo da mesma colocação, uma saída é trocar o COUNT(*) + 1 por COUNT(DISTINCT Pontuacao) + 1 nesta mesma query, mantendo o resto igual.
(Este ítem 3 foi inspirado na idéia do @ramaral)

Sugestão: troque o mysql por mysqli_ com binding. Clique aqui para entender melhor.
Comment: Funcionou perfeitamente. Muito obrigado, não só solucionou meu problema como me deu uma luz sobre como usar o COUNT. Quanto ao sql injection, vou pegar o email da sessão, então a validação é algo que já está lá atrás. E sim, já li sobre o mysqli e assim que eu estiver estruturado as coisas vou substituir os "mysql". Grato mais uma vez.
Answer: Uma solução fazendo 2 query´s e uma subtração.
Primeiro calcular o número de Pontuações distintas:
SELECT COUNT(DISTINCT Pontuacao) FROM rank;

Depois ver quantos têm menos Pontuação do que o utilizador:
SELECT Count(DISTINCT Pontuacao) FROM rank
WHERE Pontuacao < (SELECT Pontuacao FROM rank WHERE email = EmailDoUtilizador);

Subtrair o segundo do primeiro para obter o ranking.
Note que ao utilizar DISTINCT garanto que utilizadores com a mesma pontuação têm o mesmo ranking
Comment: Use a resposta do Bacco, pois é a mais correcta. A minha resposta é um exemplo de como, às vezes, conseguimos complicar aquilo que é simples. Como é fácil de entender, subtrair à quantidade total de Pontuações a quantidade de Pontuações menores do que a do utilizador, é o mesmo que contar o total de Pontuações maiores do que a do utilizador, que é o que o Bacco está a propor.
Comment: Entendi a lógica. Mas como faço a subtração? Fiz a primeira consulta com $xery e a segunda com $query, fica assim $colocacao= ($xery - $query); ?
Comment: Eu entendi a lógica das duas e agradeço, pois vocês me ajudaram a entender o COUNT com dois exemplos diferentes. Consegui mostrar na tela o resultado.


How to "export" iOS Application from start to finish - Simplified for an Android dev

Question: I'm coming from an Android background so please bear with me.
I'm having a really tough time grasping the concepts of certificates, identifiers, and provisioning profile. I have signed up for a developer account, and (hopefully) gone through the correct steps to create a certificate and provisioning profile for production/distribution. I have tried looking up a guide for the newest xcode that would "walk" me through the whole process, but I keep finding old and outdated resources. I was just wondering if someone could go through the steps you need to export an iOS app.
I've followed the Apple Distribution guide, but I'm still very "confused". Again, I've never worked/developed/released on any platform besides Android, and I guess they made it very easy.
Apple states:

Create a distribution certificate.
Create a store distribution provisioning profile.
Archive and validate your app.
For Mac apps, test the Mac Installer Package.
Submit your app using Xcode or Application Loader.

I've created a distribution certificate. The "name" of it is my Companies name.
I've created a store distribution provisioning profile. The "name" of it is my Apps name.

So I'm confused with both of these things. Should I keep them secret? Should I download and save them? Also, what the hell is this wild card identifier.
I understand this is a broad question, and it may get flagged for being too specific, but I hope I am not the only person having this problem.
Answer: what do you mean by export an app?  If you want to distribute the app to testers/clients you'll need to do the following steps:

Add devices to you apple account
Add devices to your development distribution profile
In xcode -> preferences -> accounts, double lick the iOS account (lower right corner) and hit refresh.  This will pull down your new development profile with new devices.
In xcode, check your bundle identifier matches your provisioning profile (either in info.plist or targets->general->bundle identifier
in targets -> build settings, make sure 'code signing identity' is set to the same identity the provision profile uses.
in menu, select product -> archive.  if build is successful, this will launch organizer.
in organizer, selected the most recent build, and click distribute
select save for enterprise or ad hoc deployment
select the development provisioning profile and export your app.  It will now install and run on any of the devices you set up in step 1.


Difference between amplitude and range?

Question: Why Vertical axis changes name when we talk about waves? is there any differences between Range and Amplitude?
also i didn't knew what tag should i use for this, sorry for inappropriate tags.
EDIT:
I always see ppl using fourier transform and stuff, they write Amplitude as the label of their frequency domain plot.
Comment: @Andrei The reason that I had made this mistake if it is, is that I always see ppl using fourier transform and stuff, they write `Amplitude` as the label of their frequency domain plot.
Comment: I am not sure what context are you talking about. What's the definition of range/amplitude that you are using? What vertical axis?
Comment: @Andrei I'm talking about Cartesian Coordinate system in 2D(like X Y plane) or sth. when we draw waves like sinusoidal waves we call the old Y (vertical axis) Amplitude axis i think?
Comment: That's the wrong name for the axis. `Amplitude` means the the maximum deviation of a **periodic** function from the average. So if your function is $y=A\sin t+B$, $A$ is the amplitude. The `range` of values that this function takes is from $B-A$ to $B+A$.
Comment: @no0ob You should edit that into the question - I think people were thinking of simple waves (sine waves) plotted in time, rather than complex waves plotted in frequency domain. That comment changes the answers you'd get a lot.
Answer: As mentioned in a comment, if you have a sine wave in the time domain $y=A\sin\omega t$, $A$ is the amplitude. If you add multiple such functions you get something like $$y=\sum_i A_i\sin\omega_it$$
When you do the Fourier transform, this will show up as a set of points $(\pm\omega_i, A_i)$ (up to some normalization constant). The same thing is occurring if you have a continuous distributions of $\omega$ angular frequencies. So in the case of the Fourier transform the thing that you plot is the amplitude of each contributing sine wave.
The above answer is the same if you add sine and cosine contributions.
Answer: This very much depends on how you represent a wave and what it means.

In time domain, generally one plots an $x$-axis representing time and the $y$-axis represents a physical quantity, such as pressure or voltage or displacement. The amplitude, while not being an axis of this graph, is a quantity that one can find from the graph - it is the distance between an extreme point and the average point ("equilibrium" in a physical context). In particular, the wave $A\sin(x)$ has amplitude $A$ because its extreme points are at $\pm A$ and its equilibrium would like at $0$. The "range" (or "peak-to-peak amplitude") sometimes refers to the difference of largest and smallest values in a wave - so $2A$ for $\sin(x)$.
It's harder to give a single value for amplitude for more complex waveforms - there's still a notion that making a wave twice as tall doubles its amplitude, but there are many definitions that try to capture various desirable quantities of a wave.
For the most part, amplitude would not be an appropriate label for the $y$-axis of a plot of a waveform - the possible exception would be if you're plotting a standing wave where the $x$-axis is distance and the $y$-axis is the amplitude of some time-varying quantity when observed at the prescribed point in space.

In frequency domain, a complicated wave is shown to be decomposed into a sum of sine waves. For instance, if you started with a wave such as
$$F(t)=\sin(2\pi t\cdot 1000 \text{ Hz})$$
where $t$ is some duration, the Fourier transform would show* a single bar showing amplitude $1$ at $1000\text{ Hz}$, meaning that the wave is just a sine wave with that amplitude at that frequency. A more complicated wave such as
$$F(t)=1/3\cdot \sin(2\pi t\cdot 1000 \text{ Hz})+ 1/4 \cdot \sin(2\pi t\cdot 2000 \text{ Hz})$$
would show an amplitude of $1/3$ at $1000\text{ Hz}$ and $1/4$ at $2000\text{ Hz}$, showing that the bigger wave is a sum of simpler waves with the prescribed amplitudes. In general, any complex wave can be written as a sum of sine waves with various phases, and the Fourier transform displays, at each frequency, what amplitude of wave would be necessary.
(*There are many caveats here: if you're, for instance, working with digital audio, you won't see a sharp peak because those programs take an arbitrary chunk of your sound, pretend it repeats forever, then decompose that wave; if the chunk doesn't line up with the periods of your wave, the transform won't represent a sine wave. There are also issues with the fact that Fourier transforms most naturally work on continuous signals whereas they are most commonly applied to discrete signals obtained via sampling at some rate. Also, in this context, usually both axes are using logarithmic scales, which makes them look a bit odd)
Comment: @no0ob The frequency axis is just $k$ - but it is often displayed laid out logarithmically (in my experience, equalizer effects in various music software generally show a logarithmic $x$-axis, even though the data points are discrete) - but you can just look at the labels on the $x$-axis to see whether it's spaced linearly or not.
Comment: Are you sure about both axes are using logarithmic? cause i think for the DTFT the frequency axis is just the `k`/`2πk` from the fourier summation formula
Answer: Important point: $y=sin(ωt)+1$ has exactly the same amplitude as $y=sin(ωt)$. But the first has $[0,2]$ as its range and the second, $[-1,1]$.
The amplitude measures the size of the waveform, not the set of values it assumes.

Difference between amplitude and range?


test for difference between means of two non-normal distributions (poisson or negative binomial)

Question: I want to test for the difference between means for what I think are two negative binomial or poisson-like distributions that are 0 inflated.
Can I rely on the law of large numbers to do a simple t -test? Or , is this going to be unreliable given the data type?
My data are graphed below:
Answer: Please, do not rely on the law of large numbers to do a simple t-test. The more non-normal your data are, the larger the sample size required. It seems like you have under 3000, but your data are really really non-normal.
You can do both: a zero-inflated negative binomial (ZINB) model has fewer restrictions than a zero-inflated Poisson (ZIP) model. If the results differ substantively, then you can attempt to investigate why. If your variance is much larger than the mean, then the ZINB model would be more reliable than the ZIP model.
Comment: Ok! This sounds appropriate then. To specify the ZINB model to find group differences, would I use my numeric data as my response, and group as an IV?  For example, I could specify the model in R as:  m1 <- zeroinfl(Response ~ Group,
               data = test, dist = "negbin", EM = TRUE)   , and then if the Group variable is significant, I could conclude that there is a mean difference?
Comment: Yes, you would.


Fiber Product of Schemas

Question: I have a question about a equation in the proof of Prop. 3.1.16 in Liu's "Algebraic Geometry" (page 83):

$\DeclareMathOperator{\Spec}{Spec}$
Why the equation $(X \times _Y V) \times _V \Spec k(y) = f^{-1} (V) _y$ holds, where $Q \times _S R$ means the fiber product of $S$-schemes Q and R?
Comment: Please keep questions like this coming.  I am also learning algebraic geometry and this is a great way for me to work out the details : )
Answer: $\DeclareMathOperator{\Spec}{Spec}$
I don't know what Liu had in mind, but you can argue directly that $X \times_Y \Spec \kappa(y)$ is isomorphic to $f^{-1}(V) \times_V \Spec \kappa(y)$ as follows.  (this is a bit technical and you might be better off just doing this yourself instead of going through what I wrote; I would draw a diagram to follow).
Let $f'$ be the morphism of schemes $f': f^{-1}(V) \rightarrow V$ coming from the morphism $f: X \rightarrow Y$.  Let $\iota: \Spec \kappa(y) \rightarrow Y$ be the structural morphism, and let $\iota'$ be the corresponding morphism $\iota': \Spec \kappa(y) \rightarrow V$.  Also, let $i: f^{-1}(V) \rightarrow X$ and $j: V \rightarrow Y$ be the inclusion morphisms.
Let $\pi_1, \pi_2$ be the projections on $X \times_Y \Spec \kappa(y)$, and $\pi_1', \pi_2'$ the projections on $f^{-1}(V) \times_V \Spec \kappa(y)$.
We have morphisms $i \circ \pi_1'$ and $\pi_2'$ from $f^{-1}(V) \times_V \Spec \kappa(y)$ to $X$ and $\Spec \kappa(y)$, respectively.  They are compatible with the structural morphisms $f: X \rightarrow Y$ and $\iota: \Spec \kappa(y) \rightarrow Y$, since
$$f \circ i \circ \pi_1' = j \circ f' \circ \pi_1' = j \circ \iota' \circ \pi_2' = \iota \circ \pi_2'$$
Therefore, by the universal property of $X \times_Y \Spec \kappa(y)$, there exists a unique morphism $\Phi: f^{-1}(V) \times_V \Spec \kappa(y) \rightarrow X \times_Y \Spec \kappa(y)$ such that $i \circ \pi_1' = \pi_1 \circ \Phi$ and $\pi_2' = \pi_2 \circ \Phi$.
I say $\Phi$ is an isomorphism of schemes.  By standard universal property arguments, this follows immediately from:

Claim: $f^{-1}(V) \times_V \Spec \kappa(y)$, together with the maps $i \circ \pi_1'$ and $\pi_2'$ to $X$ and $\Spec \kappa(y)$ respectively, is the fiber product of $X$ and $\Spec \kappa(y)$ over $Y$.

Proof of claim: Suppose $Z$ is a scheme, and $h_1: Z \rightarrow X, h_2: Z \rightarrow \Spec \kappa(y)$ are morphisms such that $f \circ h_1 = \iota \circ h_2$.  We need to show that there exists a unique morphism of schemes $h: Z \rightarrow f^{-1}(V) \times_V \Spec \kappa(y)$ such that $i \circ \pi_1' \circ h = h_1$ and $\pi_2' \circ h = h_2$.
The crucial observation is that, as maps of sets, since the image of $\iota$ is the single point $y$ of $Y$, the image of $h_1$ is contained in $f^{-1}\{y\} \subseteq f^{-1}(V)$.  A morphism of schemes whose set theoretic image is contained in open subset of a scheme is the same as a morphism of schemes into that open subscheme.  So there exists a unique morphism $\overline{h_1}: Z \rightarrow f^{-1}(V)$ such that $i \circ \overline{h_1} = h_1$.  Now,
$$j \circ f' \circ \overline{h_1} = f \circ i \circ \overline{h_1} = f \circ h_1 = \iota \circ h_2 = j \circ \iota' \circ h_2$$
so $$f' \circ \overline{h_1} = \iota' \circ h_2$$
as morphisms of schemes $Z \rightarrow f^{-1}(V)$.  So by the universal property of $f^{-1}(V) \times_V \Spec \kappa(y)$, there exists ($\ast$) a unique morphism $h: Z \rightarrow f^{-1}(V) \times_V \Spec \kappa(y)$ such that $\pi_1' \circ h = \overline{h_1}$ and $\pi_2' \circ h = h_2$.  Then
$$i \circ \pi_1' \circ h = i \circ \overline{h_1} = h \textrm{ and } \pi_2' \circ h = h_2 $$
which is what we wanted to show about $h$.  To see that $h$ is the unique morphism satisfying this property, suppose $H: Z \rightarrow f^{-1}(V) \times_V \Spec \kappa(y)$ is another morphism satisfying the same.  We can write $i \circ \pi_1' \circ H = i \circ \overline{h_1}$, and cancel the $i$ to get $\pi_1' \circ H = \overline{h_1}$ and $\pi_2' \circ H = h_2$.  By the uniqueness of $h$ in $\ast$, we get $H = h$.  $\blacksquare$
This reduces the Proposition to the case where $Y$ is affine: once you show that the underlying map of $\pi_1'$ is a homeomorphism onto the set of $x \in f^{-1}(V)$ such that $f(x) = y$, the fact that $\pi_1 \circ \Phi = \pi_1'$ as maps of sets into $X$ shows you that the same is true for $\pi_1$.
Answer: $\DeclareMathOperator{\Spec}{Spec}$Oh I get what he's saying now.  $X \times_Y V$ is isomorphic to $f^{-1}(V)$.  This implies that $(X \times_Y V) \times_V \Spec \kappa(y) \cong f^{-1}(V) \times_V \Spec \kappa(y) = f^{-1}(V)_y$. This can be seen in the same way as my previous answer, by showing that $f^{-1}(V)$, together with the maps $i:f^{-1}(V) \rightarrow X$ and $f': f^{-1}(V) \rightarrow V$, satisfies the required universal property.
If you want an intuitive reason for why  isomorphisms like this should hold, just imagine you're in the category of sets.  If $f: X \rightarrow Y$ is a map of sets, and $V \subseteq Y$, then the fiber product $X \times_Y V$ is literally
$$X \times_Y V = \{ (x,v) \in X \times V : f(x) = v \}$$
which you can identify with $f^{-1}(V)$.
You can actually make this intuition precise by giving a different proof of these isomorphisms, using the Yoneda lemma.
Comment: In what way I can apply Yoneda here to prove it? Do you mean by using the consequence of YL that $Hom(-, A)$ commutates with fiber products?

Fiber Product of Schemas


Poisson integral in $R^2$

Question: This question arises out of confusion about some aspects of the Poisson integral in $R^2$, simplified here to a function f on the boundary of the unit circle $ \partial C$ and on C,
$$u(r,\phi) = \frac{1}{2\pi} \int_0^{2\pi} \frac{ f (\theta) (1-r^2) d\theta}{1-2r \cos(\theta-\phi)+r^2}$$
The intuition behind the derivation of the integral is described nicely here
and based on this sort of intuition I wondered whether there might be an approach that did not involve the use of "inversive" geometry.
The article cited mentions that we would typically be considering harmonic functions (temperature, e.g.) and that given an arbitrary piecewise continuous assignment of values to the boundary $\partial C$, "there always exists a harmonic function in R that takes on these values as the boundary is approached."
Well, suppose $f(\phi) = \phi^2  $? There is a discontinuity at $(r = 1, \phi = 0, 2 \pi )$. According to the article, if we are approaching $ \mathit{continuous }$ boundary points this is not an issue.
So for the question(s). If I guess--naively-- that the influence of a point on the boundary on a point inside the circle is inversely proportional to the square of the distance between the two points, I might approximate the integral as
$$ u \approx  \frac{\sum_{i=1}^n  \frac{f(\phi_i) }{(d_i)^2}}{\sum_{i=1}^n \frac{1}{(d_i)^2}}$$
This approximation is not great, but it yields reasonable values near the center of the circle.

Is there a straightforward Riemann-sum approximation of the integral along these lines? Or are we stuck with the geometry of the article? Is the partial agreement I get for my guess fortuitous?
We could assign pretty outrageous piecewise-continuous values to the boundary--do every one of these correspond to a theoretically possible (for example) heat distribution?

Thanks for any insights, edits.
Answer: The Poisson kernel $$P(r,\theta,\phi)=\frac{ 1-r^2 }{1-2r \cos(\theta-\phi)+r^2}$$ can be written in the more intuitive form $$P(z,\zeta)=\frac{1-|z|^2}{|z-\zeta|^2}$$ where $z=re^{i\theta}$ and $\zeta=e^{i\phi}$. This form clearly shows both the inverse square relation (in the denominator) and penalty for being close to the boundary (in the numerator). Notice that $1-|z|^2=(1+|z|)(1-|z|)$ where the first factor does not change much: $1\le 1+|z|\le 2$ for all $z$ in the disk. Thus, the penalty for proximity to the boundary is essentially linear, $(1-|z|)$.
Your sum with squared distances ignores the numerator, which of course leads to poor results near the boundary. If you want a Riemann sum approximation, why not just take the Riemann sum of the original Poisson integral itself: that is, split $[0,2\pi]$ into subintervals and pick a point in each?
Concerning (2): Anything piecewise continuous will work as you expect as long as the boundary values are integrable. For example, the boundary values $1/\theta$ for $\theta\in (0,2\pi]$ will not give you any harmonic function inside in the disk: the integral will simply diverge everywhere. But for any integrable boundary values you get a harmonic function, which can be thought of as a stationary heat distribution (under the assumption that the temperature of the boundary is somehow maintained by an outside device).
Comment: The contribution of $f(\zeta)$ at $z$ gets weaker if the point $z$ approaches a boundary point *other than $\zeta$*. This is because $z$ is strongly influenced by the nearest boundary points, which do not include $\zeta$. You can consider the ratio $(1-|z|)/|z-\zeta|$ (which is always between 0 and 1) as a measure of how relevant the point $\zeta$ is for the point $z$. Or just use some software to draw the level curves of the Poisson kernel: I believe they are circles internally tangent at $\zeta$.
Comment: The inverse square relation is clear. I wonder if you could characterize in a phrase the effect of the numerator on the behavior of the sum/integral? Near the boundary...? I don't think we can simply say "the contribution of f is weaker near the boundary." But maybe that is the case? My approximation gave inflated numbers near the boundary for the f I chose.

Poisson integral in $R^2$


Concatenate two different variable in PHP

Question: I have the following code
<?php
$str="3dollars";
$a=20;
$a+=$str;
print($a);
?>

How can be the Output of the above program is 23 ?
Thanks In Advance !!
Comment: @JohnConde He knows the code works, he's asking **WHY** it is outputting 23..
Comment: meet type juggling: http://php.net/manual/en/language.types.type-juggling.php
Comment: [That code works](https://eval.in/448997)
Comment: @JohnConde Exactly my point that is why I asked read the manual. It will clear his concepts regarding the basics and will always help him in longer run. It's for his own learning curve.
Comment: `+` isn't concatenation in PHP, it's addition; to concatenate in PHP, use the `.` operator
Answer: The + operator will coerce the string into being an integer, so it will (internally) do something like this:
$str = "3dollars";
$a = 20;
$a += $str;
// $str = (int)"3dollars";
// $str = 3;
$a = 23;

What you want to do is use the 'concatenation' operator (.):
<?php
$str = "3dollars";
$a = 20;
$a .= $str;
print($a); // 203dollars

Answer: It's taking "3dollars" as a number, getting $str = 3.
And when you echo, you add 20, to $str, so it prints 23 and $a = 23.
  <?php    $a += $str;
    print($a);
    it echo 23;   //$a=$a+$b;?>

Answer: $str= (int) "3dollars";
$a=20;
$a+=$str;
print($a);

Use (int) to convert string to integer.
Answer: Use this
<?php
    $a = 20;
    $str = "3dollars";
    preg_match_all('!\d+!', $str, $matches);
    print_r($matches);

    $matches = $a + $matches[0][0];

    echo '
 Value Is :'.$matches;
?>

This will print 23 as Answer.

Output
Array ( [0] => Array ( [0] => 3 ) )
Value Is :23

phpfiddle Preview
Comment: Check [this](http://stackoverflow.com/questions/33082290/concatenate-two-different-variable-in-php#comment53981004_33082290)


Amazon Cloudfront, S3 and EC2

Question: I'm trying to use Amazon Cloudfront as a CDN provider but unsure of what other services are meant to be.
Do I have to use S3 and EC2 as Virtual Server to host my files and change hosting provider in order to use Cloudfront?
I understand EC2 is a hosting solution but what exactly is S3 then?
Also is there any complexities involved in integrating Cloudfront and S3 and potentially EC3?
Answer: You store your files in s3 and then in cloudfront you enable that s3 bucket where all your files are. You still access all your files via s3 and they get distributed automatically around to amazon's cloudfront locations. When you delete someone from s3 it isn't deleted right away on cloudfront and may take a few minutes.
ec2 is simply a virtual private server that you can spin up on demand.
Answer:
Do I have to use S3 and EC2 as Virtual Server to host my files and
  change hosting provider in order to use Cloudfront?

No you don't have to use S3 and/or EC2.
CloudFront does require an ORIGIN. This may be an EC2, an S3 Bucket, or another server that has nothing to do with AWS.

I understand EC2 is a hosting solution but what exactly is S3 then?

EC2 gives you access to compute capacity. It's a Virtual Server.
You can think of S3 as an FTP service. S3 allows you to store files, and retrieve files easily, and without the need for a server.
It can be cheaper then running a virtual Server just to serve files, it's scalable (with no configuration needed). It's also reliable as your files are stored in multiple locations for you.
In addition to being able to store and retrive files, Amazon does let you host static files over HTTP. For example: If you had a simple HTML site with some JS/CSS and images...you could upload all of them to S3 and ask Amazon to host those files for you (no web server required!).
You pay for storage of files, and for bandwidth ... but the price is often much cheaper then setting up a web server to do the same job.

Also is there any complexities involved in integrating Cloudfront and
  S3 and potentially EC3?

There are a couple of gotcha's with CloudFront but it's not too difficult to setup.
When you setup a new CloudFront distribution you will be asked for an origin. You can either choose an S3 Bucket or a server location (e.g www.domain.com where you files are hosted, maybe this is powered by some EC2s, maybe it's shared hosting at GoDaddy, it doesn't matter!).
Some things to be careful of:

You will need to get permissions right, particularly on the S3 bucket. CloudFront needs to be able to access the files.
CloudFront is a CDN so it will cache files. If you change a file, CloudFront may not immediately know to update it for you. You may need to manually purge the file in question, or you may need to enable the use of cache busting through paramaters in your URL so that "file.css?v=1" is different from "file.css?v=2".

Amazon Cloudfront, S3 and EC2


Funções e procedimentos em Portugol

Question: Sobre funções e procedimentos, estou com uma baita duvida neste assunto.
Sei que uma função sempre retornará dados e que procedimento não têm retorno, mas toda função tem que preencher todos os parâmetros? Gostaria de saber porque meu código não esta dando certo, a soma dos números sempre dá zero.
Qual o problema?
programa
{
    funcao inicio(){
        inteiro resultado = 0, n1=0, n2=0
        escreve()

        escreva(somar(n1,n2))
    }

    funcao escreve(){
        inteiro n1, n2
        escreva("Digite n1 ")
        leia(n1)
        escreva("Digite n2 ")
        leia(n2)
    }

    funcao inteiro somar(inteiro a, inteiro b){
        retorne a + b
    }
}

Comment: Bom, sua função `escreve` é do tipo lê e esquece. Na função você declara duas variáveis: `n1` e `n2`, com escopo restrito à função, a seguir você lê valores para cada uma destas variáveis, mas aí encerra a função, ou seja os valores lidos são perdidos. Note que em sua função `inicio` você declara as variáveis `n1` e `n2` com valor inicial 0 e portanto a chamada da função `somar(n1,n2)` retornará 0, independente do que foi lido em `escreve`. Estude sobre escopo de variáveis.
Answer: Observando seu código, n1 e n2, na função escreve, são variáveis locais e não estão alterando o valor de n1 e n2 declaradas na função inicio. Ou seja, quando o programa roda, mesmo que você atribua valor para n1 e n2 (que é requisitado pela função escreve), o valor que está sendo passado como parâmetro da função soma é na verdade o n1 e n2 da função inicio, que não foram alterados e, portanto, continuam valendo zero. Por isso sua soma resulta em zero.
Achei a função escreve desnecessária e coloquei o desenvolvimento dela dentro da função inicio, conforme o código a seguir. Neste caso, acredito ser necessária a passagem de parâmetros.
função somar(inteiro a, inteiro b){
    int res;

    res = a+b;
    retorne res;
}

funcao inicio{
    int resultado = 0, n1=0, n2=0;

    escreva ("Digite n1: ");
    leia (n1);
    escreva("Digite n2: ");
    leia ("%i", &n2);

    escreva("A soma dos numeros é: ", resultado = somar(n1,n2));
}

Answer: Pelo o que entendi do seu código, está faltando uma variável para retornar a resposta da soma.
programa
{
  variavel
     int n1, n2, resp

  escreva
   ("Digite n1: ")
  leia n1
  escreva
    ("Digite n2:  ")
   leia n2

   resp = (n1 + n2)

   escreva
    ("O resultado é igual á:  " , resp)

Answer: eu refiz seu código com algumas pequenas alterações e funcionou... na sua funcao escreve fiz a passagem por referencia, desse modo, os valores de n1 e n2, são substituídos pelos valores de c e d, que serão os valores digitados pelo usuário.
Espero que ajude nos estudos, tb tô começando agr :)
funcao inicio()
{
inteiro n1 = 0, n2 = 0
    escreve (n1, n2)

    somar(n1, n2)
}

funcao escreve (inteiro &c, inteiro &d){
    escreva ("Digite um número => ")
    leia (c)
    escreva ("\nDigite outro número => ")
    leia (d)
}

funcao somar (inteiro a, inteiro b){

    escreva ("\nA soma de " + a + " + " + b + " = " + (a + b))
}

}

Funções e procedimentos em Portugol


if $m<\frac{1}{2}$, what is $-\frac{1}{m}$ equal to?

Question: I start out with: $$m<\frac{1}{2}$$
Taking the reciprocal of both side flips inequality sign: $$\frac{1}{m}>2$$
Multiply both side by -1 flips the sign yet again: $$-\frac{1}{m}<-2$$.
But the result $-\frac{1}{m}<-2$ is not valid. If $m=-100$, then $-\frac{1}{m}=\frac{1}{100}$
What did I do wrong?
Comment: A hint to finding the mistake on your own: You already started off well - finding a counterexample. Next you can test your example against each of your steps to figure out where and why you went wrong. In your case, already the second step would fail and you can probably figure out why it did.
Comment: Why does taking a reciprical flip the inequality sign? Does it always?
Answer: The mistake is that you are assuming $m$ positive but we need to consider two cases

for $0<m<\frac12$

$$m<\frac{1}{2} \iff \frac1m>2\iff -\frac1m<-2$$

for $m<0$

$$m<0 \iff -\frac1m>0$$
Answer: Go through your steps with $m=-100$
$-100 < 2$  is that true?
So $\frac 1 {-100}> \frac 12$ is that true?
So $-\frac 1 {-100}=\frac 1 {100}<\frac 12$ is that true?
Can you see the error?
Maybe we can break this further:
$-100 < 2$ so
$\frac {-100}2 <1$ so
$\frac {1}2 <\frac 1 {-100} $ so
$\frac 1 {-100}>\frac 12$.
Can you pin point the exact point of wrror.  And why?


Getting error while remove docker image_id

Question: docker images -a
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
node                test                337b7fc90dbc        2 hours ago         301.8 MB
<none>              <none>              60d47994bba8        2 hours ago         301.8 MB
<none>              <none>              987deffef7bf        2 hours ago         196.7 MB
docker.io/centos    centos7             970633036444        4 weeks ago         196.7 MB

docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                      PORTS               NAMES
774f0d06ec9a        970633036444        "bash"              2 hours ago         Exited (1) 30 minutes ago                       elated_cray
b1f9481f6eae        337b7fc90dbc        "bash"              2 hours ago         Exited (0) 30 minutes ago                       serene_stallman

But,when I run docker rmi 987deffef7bf,get the error
Failed to remove image (987deffef7bf): Error response from daemon: conflict: unable to delete 987deffef7bf (cannot be forced) - image has dependent child images

Answer: This indicates that another image, most likely "node" from the timestamp is using that image as part of it's layers. This is the design of how images are created from layers and the docker images -a exposes some of those workings to the end user. If you remove the "node" image, these should automatically get cleaned.
Answer: Just run docker rmi -f 987deffef7bf, to force it anyway. Or, delete the child images then delete it afterwards.