syntax error or access violation 1064 php pdo

Question: $stmt = $dbh->prepare("SELECT FROM menulist_tbl WHERE menulist_id=:MENUID");
        $stmt->bindValue(':MENUID',$menuid,PDO::PARAM_STR);
        $stmt->execute();
        $selected_row = $stmt->fetch(PDO::FETCH_ASSOC);

i have this is select statement but i get syntax error or access violation 1064 in line 471 which is the line $stmt->execute(); i cant see the error because i am using this same statement before but i dont get error i am wondering why i get it now
Comment: ,Please check my answer,It could resolve your issue.Thanks.
Answer: You need to specify what you are selecting which you have not. If you need to select all columns then
select * from table_name

If you need to select some specific columns then
select col1,col2 from  table_name

In your case you may have it as
SELECT * FROM menulist_tbl WHERE menulist_id=:MENUID

or if you want some specific columns to be selected instead of *
Comment: 7 mins to tick answer
Answer: You need to specify what you are selecting from table. Use * for all fields or specify the name of field.
Example:
SELECT * FROM TABLE

SELECT filed1,filed2 FROM TABLE


Recover Azure Databricks after deletion

Question: If Azure Databricks will be deleted by someone and which contains Notebooks as well. So, if we want to recover that databricks along with notebooks , is it possible?
If so please explain how we can achieve this type of condition.
Comment: When you say Databricks was deleted: Was your *cluster* deleted? If so, that doesn't matter, since notebooks are stored in the Databricks workspace. If the entire *workspace* was deleted, then you'd have to rely on either exports of your notebooks, or version control (Databricks notebooks may be integrated with both GitHub and Azure DevOps). If the workspace was deleted, and you don't have version control or exports of your notebooks, I can't imagine there's anything you can do at that point. Maybe contact support?
Comment: I'm voting to close this question as off-topic because this is an Azure Support issue (recovering a deleted resource); nothing that can be solved here.
Answer: If you are looking to prevent deletion, you can set Azure Resource locks.  Specifically you can set the CanNotDelete lock.  This lock means authorized users can still read and modify a resource, but they can't delete the resource.
Some Azure services, such as Azure Databricks, use managed applications to implement the service. In that case, the service creates two resource groups. One resource group contains an overview of the service and isn't locked. The other resource group contains the infrastructure for the service and is locked.  You should lock the resource containing the service to prevent accidental deletion.
If you try to delete the infrastructure resource group, you get an error stating that the resource group is locked. If you try to delete the lock for the infrastructure resource group, you get an error stating that the lock can't be deleted because it's owned by a system application.
https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-lock-resources
Comment: I think the OP is talking about recovering notebooks from a deleted Databricks workspace, not configuring a workspace for deletion-avoidance...
Comment: If that's the case then the only thing I can think of is to open a support ticket to see if recovery is possible.

Recover Azure Databricks after deletion


Socket Javascript não conecta (Stomp + RabbitMQ)

Question: Estou tentando estabelecer uma comunicação entre o RabbitMQ e o Javascript, para recuperar as informações de log que são enviadas para um tópico do RabbitMQ, porém sem sucesso.
No console é exibida a seguinte informação:
Opening Web Socket...
WebSocket connection to 'ws://10.224.200.196:61613/' failed: WebSocket opening handshake timed out
Whoops! Lost connection to ws://10.224.200.196:61613/

Essa é o meu código para conexão no Javascript:
   var test = {
            client: null,
            onConnect: function () {
                client.subscribe("add-on", this.onMessage, {ack: 'client'});
                console.log('connected');
            },
            onMessage: function (message) {
                console.log(message);
                message.ack();
            },
            onError: function () {
                console.log('error');
            },
            connect: function () {
                this.client = Stomp.client('ws://10.224.200.196:61613/', 'v11.stomp');
                this.client.connect('test', 'test', this.onConnect, this.onError, '/');
            }
        };
        test.connect();

O usuário está criado no RabbitMQ como "monitoring"

O plugin stomp foi habilitado

Já criei o tópico através do RabbitMQ

Eu recebo essas mensagens no log do RabbitMQ
=INFO REPORT==== 4-Oct-2017::08:05:07 ===
accepting STOMP connection <0.672.0> (10.224.200.188:56652 -> 10.224.200.196:61613)

=INFO REPORT==== 4-Oct-2017::08:09:07 ===
closing STOMP connection <0.672.0> (10.224.200.188:56652 -> 10.224.200.196:61613)

Como faço para conectar e receber as mensagens?
Já usei diversos tutoriais, os últimos foram:
https://dzone.com/articles/easy-messaging-stomp-over
https://www.rabbitmq.com/stomp.html
Answer: Este problema acontece por causa da porta de conexão que deve ser "15674".
Alterar o código:
this.client = Stomp.client('ws://10.224.200.196:61613/', 'v11.stomp');

Por:
this.client = Stomp.client('ws://10.224.200.196:15674/ws', 'v11.stomp');

Segue abaixo um exemplo do código alterado:
var test = {
        client: null,
        onConnect: function () {
            client.subscribe("/topic/add-on", this.onMessage, {ack: 'client'});
            console.log('connected');
        },
        onMessage: function (message) {
            console.log(message);
            message.ack();
        },
        onError: function () {
            console.log('error');
        },
        connect: function () {
            client = Stomp.client('ws://10.224.200.196:15674/ws', 'v11.stomp');
            client.connect('test', 'test', this.onConnect, this.onError, '/');
        }
    };
    test.connect();

Segue o link da documentação
https://www.rabbitmq.com/web-stomp.html


OS X Screen Share @ light-blue screen; can't login

Question: I was screen sharing to a OS X 10.5.8 Server and hit Log Out. From there, it went to a light-blue screen with a black mouse pointer, and now I can't log back in! How do I get back on to Screen Share without having to reboot the server? It's a file server and all of the files are still accessible, so the server is definitely still up and running, just can't screen share.
Comment: Have you tried killing Remote Desktop? `killall ARDAgent` -- Or maybe even the WindowServer? `sudo killall -HUP WindowServer`?
Comment: No luck @jscott
Answer: Can you log into it via ssh and check the running processes? There should be a screen share process or something of that nature that you can then kill -9.
Might be something in the logs under /var/log that can give a clue as well.


How to add a field widget for multiple file upload?

Question: Is there a module that provides a multiple file upload (Drag and Drop) widget? If there isn't, how can I build one? Will it require a special setup for the server stack (LAMP)?
Comment: You mean select more than one file at a time? In 7 you can create a File field with unlimited number of values.
Comment: No, I mean uploading several files at once.
Comment: Can you describe a scenario?  In Drupal 7's File field, set to unlimited values, you can add any number of files to be uploaded, and when you submit the form they will all get uploaded.  Are you looking for the ability to select more than one at a time?
Comment: Yes, I'd like to drag and drop a hundred photos to an Album node (for example).
Answer: Multiupload FileField Widget
This is what you want. It enables the HTML5 standard for uploading multiple files. Use a normal file field but use this widget. Now one can select several files when browsing for files to upload. This works for never web browser but not IE8.
Comment: How to get file dialog only one time and select all the files at once in webform file field ???
Answer: jQuery File Upload module is in Dev, but it looks exactly like what you want.
Here's a demo of how jQuery File Upload works: http://blueimp.github.com/jQuery-File-Upload/
Comment: Will try it out then accept, sorry for the delay!
Answer: Hey you can use the PLuplaod module in drupal 7. http://drupal.org/project/plupload ..  it support for HTML5, flash and HTML4 also easy to use.


Applet doesnt reload its source code when page refreshes

Question: I test a java applet and when I change the code, save it (I use netbeans 7.0.1 and have the "auto-compile on save" option checked on) and refresh the page, the applet doesn't read its new code, but still loads the old code from cache (or from whereever).
I have tried Shift+F5 and Ctrl+F5 with no results. Any better idea then close and open whole browser? (problem stays in chrome and firefox)
HTML:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

  <meta http-equiv="content-type" content="text/html; charset=windows-1250">
  <meta name="generator" content="PSPad editor, www.pspad.com">
  <title>Applet 1</title>

    <applet code="test/EasyApplet.class" width=400 height=300>
    </applet>

    <applet code="test/MyApplet.class" width=400 height=300>
    </applet>

Applet:
package test;

import java.awt.*;
import java.applet.Applet;

public class EasyApplet extends Applet {

    public void init() {
        add(new Label("and this is even more strange text 13"));
    }

}

No cache cleaning helps, but the new applet reloads after refreshing about a minute later.
Comment: What does your html look like? What happens if you manually clear your browser's cache?
Answer: Applets should be tested in tools like applet viewer or Appleteer, which do not cache classes.  If testing in a browser, ensure the Java Console is open (there is an option in the Java Control Panel) & type Ctrl-X (I think that is 'clear class cache') before refreshing the page.
Comment: My applet (i mean the real one) works fine in default Netbeans applet wiever, but added to web page, it doent´s want to load images because of security rights and throws an error (i found out just now)
Comment: Hey, just want to ask, how do i open the java console elsehow then clicking on failed-opened applet?
Answer: LOL, now i see all the problem was that my old slow computer takes over 30 seconds to compile the source code :D sorry for bothering.


Joint probability distribution function and expected value

Question: Lets say for we have a first dice and a second dice, with X representing the face of the first dice and Y representing the face of the second dice.
I know that E(X) = E(Y) = 3.5
$$
E(XY) = \sum_{(x,y)} xy P
$$
Each side of the dice has a 1/6 chance to be rolled, every combination has a 1/36 chance.
What I can't seem to grasp is what $\sum_{(x,y)} xy P$ really means. What is the symbolic expansion of this, and what is ultimately E(XY)?
Answer: Since $X,Y$ are independent and uniformly distributed over $[1,\ldots,6]$,
$$
\mathbb{P}[X=x,Y=y] = \mathbb{P}[X=x] \cdot \mathbb{P}[Y=y] = \frac1{36}.
$$
Hence,
$$
\mathbb{E}[XY]
 = \sum_{x = 1}^6 \sum_{y=1}^6 x y \mathbb{P}[X=x,Y=y]
 = \frac{1}{36} \sum_{x = 1}^6 \sum_{y=1}^6 x y
$$
Can you finish this computation?
Comment: Yes, this is clear and concise, and helps remove a lot of confusion with other related topics. Thank you


not sure why this RadioButton isn't giving the proper value

Question: I have an EF model, I'm pulling the data from.  When I trace it I can see its getting the correct value, but something is wrong with my C# code because it doesn't have the value showing in the radio button.

Can you see what I'm doing wrong?
Model:
public class SearchPageModel
{
   ...
   public IEnumerable<string> RoadwayTypeRadioButton { get; set; }
   ...
   // populate radio buttons
    public IEnumerable<string> populatRadioList()
    {
        var query = (from d in myContext.lkp_roadwaytypes
                     select d.roadwaytype).ToList().Distinct();
        return query;
    }
}

View:

    Facility Type *:
      @foreach (var facility in Model.RoadwayTypeRadioButton)
      {

          @Html.RadioButton(facility, "0")

      }

Controller:
public ActionResult Search()
{
    SearchPageModel spm = new SearchPageModel();
    spm.RoadwayTypeRadioButton = spm.populatRadioList();

    return View(spm);
}

Comment: Not related but you should put all of your  under a  tag
Comment: I have now fixed the  tag
Answer: In your view, change your foreach

     Facility Type *:

         @foreach (string facility in Model.RoadwayTypeRadioButton)
         {

                 @Html.RadioButton("roadwayTypeButton", facility) @facility

         }


Unable to purge using CURL on VARNISH

Question: I am unable to purge objects in varnish using CURL
CURL command:
    curl -X PURGE localhost/public/stylesheets/main.css -v
the curl command is returning 200 OK response. the object is not getting purged
config file in VARNISH : default.vcl
sub vcl_miss {
  if (req.request == "PURGE") {
    purge;
    error 404 "Not in cache.";
  }
   if (req.http.user-agent ~ "spider") {
    error 503 "Not presently in cache";
    }
return (fetch);
}

sub vcl_hit {
  if (req.request == "PURGE") {
    purge;
    error 200 "Purged.";
  }
     return (deliver);
}

sub vlc.recv{
if (req.request == "PURGE") {
    if (!client.ip ~ purge) {
      error 405 "Not allowed.";
    }
    return(lookup);
  }
}

Kindly, help on this
Comment: can you try to add `acl purge {
  "localhost";
  "127.0.0.1";
}` to your vcl file and test is this working ?
Comment: sub "vlc.recv{"  has at least two typos that I can see. If that's not a copy paste error, and that's actually what your vcl looks like, you need to change it to 'sub vcl_recv {'
Answer: enable 'PURGE' request on vcl_recv, then execute purge directly on recv, ignore if it exists or not, this is irrelevant to purge process
if (client.ip ~ purge && req.request == "PURGE" ){ purge; error 999; return(error)}
if (req.request != "GET" &&
  req.request != "HEAD" &&
  req.request != "PUT" &&
  req.request != "POST" &&
  req.request != "TRACE" &&
  req.request != "OPTIONS" &&
  req.request != "DELETE") {
    /* Non-RFC2616 or CONNECT which is weird. */
    set req.http.xpass="PASS_header";
    return (pass);
}

many times varnish don't receive the real requester IP(some non transparent proxy from your provider, like amazon load balancer), so forget client.ip ACL and do a regular expression on req.http.x-forwarded-for to match purge allowed ips... it is not secure... but may be the only simplistic alternative
sorry the poor english

Unable to purge using CURL on VARNISH


An example of a prime quotien ideal where his corresponding ideal is not prime

Question: If $R$ is a comutative ring with identity ring and $K$ is an ideal from it, let $R'=R/K$ and $I$ an ideal of $R$ satisfy $K\subseteq I$ and $I'$ is the coresponding ideal of $R'$ (we knew that correspondence theorem gives a certain one-to-one corespondence between the set of ideals of $R$ containing $K$ and the set of ideals of $R'$).
can you give me some examples where $I'$ is prime then $I$ is not.
Comment: There is no such example. In the correspondence between ideals in a ring and its quotient, prime ideals correspond to prime ideals.
Answer: I do not know why you want to replace 'prime' by 'principal', since these properties do not really relate, but here is an example:
$R=k[x,y], K=(x), I=(x,y)$. $I$ is not principal but $I'=I/K=(y)$ is principal in $R'=R/K=k[y]$.
Answer: Note that we have by the third isomorphism theorem
$$ R/I \cong R/K\bigm/I' $$
hence $R/I$ is a domain iff $(R/K)/I'$ is, therefore $I$ is prime iff $I'$ is.
Comment: thanks for the answer, but what if replace prime by principal?


E Newsletter sign up form

Question: I would like to create a sign up form for visitors to my site to receive an e newsletter. One of the stakeholders in the project has specified some additional functionality in that he wants an email to fire to the user after they have completed to form that asks them to validate their details and confirm they wish to receive the email prior to said details being stored on Drupal.
Is there an off the shelf solution anywhere in the community, or will I have to create something from scratch?
I have done a (very) quick search, which yielded no results - if someone has seen something/ heard of something that will give this functionality I would appreciate hearing about it.
Many thanks.
Answer: There is Simplenews module

Simplenews publishes and sends newsletters to lists of subscribers.
  Both anonymous and authenticated users can opt-in to different mailing
  lists. HTML email can be sent by adding Mime Mail module.

Read documentation

E Newsletter sign up form


Mocking RestOperations.exchange in Spock (overloaded method with varargs)

Question: I'm trying to mock org.springframework.web.client.RestOperations.exchange in Spock.
Spock fails with
Too few invocations for:

1 * restOperations.exchange("https://test.com", HttpMethod.POST, _ as HttpEntity, String)   (0 invocations)

Unmatched invocations (ordered by similarity):

1 * restOperations.exchange('https://test.com', POST, <whatever,[]>, class java.lang.String, [])

I think the problem is related to the fact that the exchange method is overloaded and the version I'm trying to call has vararg arguments.
How do I define this interaction, so the test succeeds?
MySubject.java:

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.web.client.RestOperations;

public class MySubject {
    private final RestOperations rest;

    public MySubject(RestOperations rest) {
        this.rest = rest;
    }

    public void doStuff() {
        HttpEntity<String> httpEntity = new HttpEntity<>("whatever");
        rest.exchange("https://test.com", HttpMethod.POST, httpEntity);
    }
}

MyTest.groovy:

import org.apache.http.HttpEntity
import org.springframework.http.HttpMethod
import org.springframework.web.client.RestOperations
import spock.lang.Specification

class MyTest extends Specification {
    RestOperations restOperations = Mock(RestOperations)
    MySubject subject = new MySubject(restOperations)

    def "test"() {
        when:
        subject.doStuff()
        then:
        1 * restOperations.exchange("https://test.com", HttpMethod.POST, _ as HttpEntity, String)
    }
}

Answer: You have multiple problems:

In the application you import org.springframework.http.HttpEntity, in the test org.apache.http.HttpEntity. You need to correct that.
The call rest.exchange("https://test.com", HttpMethod.POST, httpEntity); in your application does not even compile because there is no such signature in the RestOperations class. You need to add the parameter String.class.
In the test you need to reflect the method signature including the varargs, i.e. the real method signature has 5 arguments.

If you fix all of these your test runs smoothly:
package de.scrum_master.stackoverflow.q61135628;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.web.client.RestOperations;

public class MySubject {
  private final RestOperations rest;

  public MySubject(RestOperations rest) {
    this.rest = rest;
  }

  public void doStuff() {
    HttpEntity<String> httpEntity = new HttpEntity<>("whatever");
    rest.exchange("https://test.com", HttpMethod.POST, httpEntity, String.class);
  }
}

package de.scrum_master.stackoverflow.q61135628

import org.springframework.http.HttpMethod
import org.springframework.web.client.RestOperations
import spock.lang.Specification

class MyTest extends Specification {
  RestOperations restOperations = Mock()
  MySubject subject = new MySubject(restOperations)

  def "test"() {
    when:
    subject.doStuff()

    then:
    1 * restOperations.exchange("https://test.com", HttpMethod.POST, _, String, _)
    // Or if you want to be more specific:
//  1 * restOperations.exchange("https://test.com", HttpMethod.POST, _, String, [])
  }
}


Solving a recurrence related to tree counting

Question: What I want is to count the number of binary trees on $n$ nodes, except when a node has only one child, I don't distinguish between left and right. So let $T_n$ be the number of such trees on $n$ nodes, we have
\begin{align*}
  T_n=\left(\sum_{k=0}^{n-1}T_k\cdot T_{n-k-1}\right)-T_{n-1}.
\end{align*}
I am not sure how to solve this recurrence. If we proceed the same way as in counting normal binary trees (where left and right matters when there's a single child) using generating function $g(s)=\sum_{n=0}^\infty T_ns^n$ and squaring it, I get that
\begin{align*}
  g(s)=\frac{1+s-\sqrt{1-2s-3s^2}}{2s}.
\end{align*}
Calculating the series expansion around zero seems to give me what I want, but I cannot get this expression in the form of $\sum_nT_ns^n$ so the quantity $T_n$ comes out...
Answer: This is A086246 in OEIS, but with the index shifted by $1$, and A001006, the Motzkin numbers, with the index shifted by $1$ in the other direction. (That is, $T_{n+1}=M_n$, where $M_n$ is the $n$-th Motzkin number.) The latter reference yields the possibly simpler recurrence
$$T_{n+1}=\frac{2n+1}{n+2}T_n+\frac{3n-3}{n+2}T_{n-1}\;,$$
the asymptotic formula
$$T_n\sim 3^n\sqrt3\frac{1+\frac1{16n}}{(2n+3)\sqrt{(n+1)\pi}}\;,$$
and a wealth of references, formulas involving summations, and variant forms of the generating function, but there doesn't seem to be a nice closed form.
Not so nice closed forms for the Motzkin numbers involving trinomial coefficients, hypergeometric functions, regularized hypergeometric functions and the gamma function, or Legendre polynomials can be found here.
Answer: Your trees are described by an empty tree or a root linked to a sequence of at most 2 non-empty trees, in symbols:
$$
\mathcal{T}
  = \mathcal{E}
       + \mathcal{Z} \times \mathfrak{S}_{\le 2}(\mathcal{T} - \mathcal{E})
$$
This directly gives the functional equation:
$$
T(z) = 1 + z (1 + (T(z) - 1) + (T(z) - 1)^2)
$$
This also gives:
$$
T(z) = \frac{1 - z - \sqrt{1 - 2 z - 3 z^2}}{2 z}
$$
Answer: You forgot to mention that there is an implicit assumption in your problem that $T_0=T_1=1$. In this case your Z-transform is correct. Now the question is to invert the Z transform. This is pretty straightforward:
\begin{eqnarray}
g(s) &=& \frac{1}{2} - \left(\frac{\sqrt{1-2 s-3 s^2}-1}{2 s}\right) \\
&=& \frac{1}{2} - \left(\frac{\sqrt{(1+s)(1-3 s)}-1}{2 s} \right) \\
&=& \frac{1}{2} - \frac{1}{2} \sum\limits_{n=0}^\infty \binom{\frac{1}{2}}{n+1} F_{2,1}\left[\begin{array}{r} -\frac{1}{2} & -n-1 \\ \frac{1}{2} - n \end{array};-3\right] \cdot s^n
\end{eqnarray}
In the last line we multiplied the respective binomial expansions and then we computed the resulting convolution bu using the definition of the hypergeometric function. Therefore the result reads:
\begin{equation}
T_n = \frac{1}{2} \delta_{n,0} -\frac{1}{2} \binom{\frac{1}{2}}{n+1} F_{2,1}\left[\begin{array}{r} -\frac{1}{2} & -n-1 \\ \frac{1}{2} - n \end{array};-3\right]
\end{equation}
Now the result can be further simplified using the theory of hypergeometric functions.


HREFLANG attribute add

Question: I am working on a multilingual site. I have to add HREFLANG attribute so that search engines like Google provide the proper response according to the language of the user and the region.
To implement this, I am using Alternate HREFLANG module which basically add HREFLANG attribute like this :

for all the three languages.
But I want to add language as well as region like this:

In the description of Alternate HREFLANG module description, they mentioned that if you want to alter this attribute, you can use  hook_language_switch_links_alter() and hook_html_head_alter() these hooks.
But when I dsm these, I didn't get the HREFLANG attribute.
Can someone help me to achieve this?
Answer: I cant see what is in your "...which basically add HREFLANG attribute like this" and "But I want to add language as well as region like this."
I bet you want to replace, let's say, "en" to "en-GB" right? If so, you need to alter Drupal language ISO. Current is ISO 639, language+region is ISO 3166-1 alpha 2.
BTW for your question, you need something like this to locate the hreflang:
function YOUR_THEME_OR_MODULE_NAME_html_head_alter(&$head_elements) {
  drupal_set_message('
' . print_r($head_elements,1) . '
');
}

Clear cache and reload the page.
UPDATE
An easier way is by adding a custom language. E.g. visit admin/config/regional/language/add
Expand Custom language fieldset.
Enter your desired ISO 3166-1 alpha 2 language code to language code & path prefix language code.
Fill the rest (language name in English, native language name & Direction) as usual.
Comment: Hi @ItangSanjana, How can I switch the language ISO 639 to ISO 3166-1 alpha 2? Can you please assist me?
Comment: Updated. See easier solution above.

HREFLANG attribute add


Cancel if condition not met, show status

Question: I have the Mimemail module set up to send HTML mails out, after a form is filled in an email is sent to the user based on a custom template.
But the email should only be sent out if the user has previously filled in another form, if they haven't a message needs to be displayed and the email cancelled.
I'm simply using the following code to check that they have filled in the other form previously:
$query_result = db_query("SELECT MAX(sid) as max_id FROM webform_submitted_data WHERE data = '" . $email . "' AND nid = ###" )->fetchCol();

So if this returns an empty array then a message needs to be displayed and the email cancelled, but I can't seem to stop the email being sent, how do I do this?
Answer: You can use hook_mail_alter() for that, e.g.
function MYMODULE_mail_alter(&$message) {
  if ($message['id'] == 'MYMODULE_foo' && any_other_condition()) {
    $message['send'] = FALSE;
  }
}

Comment: thank you! One problem, I still get a 'An error occurred and processing did not complete.' message how can I stop this from appearing?


Android bluetooth app crashing on startup

Question: When the app first starts it immediately crashes on startup. I have narrowed down the problem to one line but not really sure what to do =/ here are the two classes in the app so far:
package com.example.bluetooth_app;

import java.util.Set;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class Bluetooth {
    private BluetoothAdapter mBluetoothAdapter;
    private Activity activity; //Activity to store main window's activity
    private ArrayAdapter<String> pDevices; //Array adapter for storing already paired devices
    private ArrayAdapter<String> nDevices; //Array adapter for storing newly discovered devices
    private IntentFilter filter; //Filter for catching bluetooth device actions
    private Button sButton; //Scan button
    private ListView lvBox; //listview box

    /**
     * default constructor, basic initializations
     */
    public Bluetooth(Activity activity) {
        this.activity = activity; //Set class activity to the activity passed to it by the main activity window
        pDevices = new ArrayAdapter<String>(activity, R.layout.activity_bluetooth__app);
        nDevices = new ArrayAdapter<String>(activity, R.layout.activity_bluetooth__app);
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        sButton = (Button) activity.findViewById(R.id.scanButton); //sButton = scan button
        sButton.setOnClickListener(new View.OnClickListener() { //Listener to check if button is pressed
            public void onClick(View v) { //If button is pressed start discovering and hide button
                startDiscovering();
                sButton.setVisibility(4); //Make button invisible
            }
        });

        lvBox = (ListView) activity.findViewById(R.id.deviceList); // lvBox = deviceList listview
        lvBox.setAdapter(pDevices);

        // Register for broadcasts when a device is discovered
        filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        activity.registerReceiver(mReceiver, filter);

        // Register for broadcasts when discovery has finished
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        activity.registerReceiver(mReceiver, filter);
    }

    /**
     * Check if bluetooth is enabled, if not enable it
     */
    public void getAdapter() {
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            activity.startActivityForResult(enableBtIntent, 1);
        }

    }

    /**
     * Check if device is bluetooth compatible
     */
    public boolean isCompat() {
        if(mBluetoothAdapter == null) {
            return false; //TODO: better error handling
        } else {
            return true;
        }
    }

    /**
     * Close some shit so we do not eat up resources
     */
    public void destroy() {
        if(mBluetoothAdapter != null) {
            mBluetoothAdapter.cancelDiscovery(); //cancel discovering devices
        }

        activity.unregisterReceiver(mReceiver);
    }

    /**
     * Start discovering devices with bluetooth adapter
     */
    public void startDiscovering() {
        if(mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }

        mBluetoothAdapter.startDiscovery();
    }

    public void pairedDevices() {
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        // If there are paired devices
        if (pairedDevices.size() > 0) {
            sButton.setText("found some");
            // Loop through paired devices
            for (BluetoothDevice device : pairedDevices) {
                // Add the name and address to an array adapter to show in a ListView
                pDevices.add(device.getName() + "\n" + device.getAddress());
            }
        }
    }

    /**
     * The BroadcastReceiver that listens for discovered devices and changes the title when
     * discovery is finished
     */
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // If it's already paired, skip it, because it's been listed already
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    nDevices.add(device.getName() + "\n" + device.getAddress());
                }
                // When discovery is finished, change the Activity title
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                sButton.setVisibility(0); //Make button visible again
                if (nDevices.getCount() == 0) {
                    sButton.setText("none");
                    //TODO: none found do something
                }
            }
        }
    };

}

and:
package com.example.bluetooth_app;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

import com.example.bluetooth_app.Bluetooth;

public class Bluetooth_App extends ActionBarActivity {
    private Bluetooth bT;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth__app);

        bT = new Bluetooth(this);

        bT.isCompat();
        bT.getAdapter();
        bT.pairedDevices();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        bT.destroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.bluetooth__app, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

The problem is in the first class, this line: lvBox.setAdapter(pDevices);,if I comment it out it runs just fine, if not it crashes on startup. Any help would be appreciated - thanks.
EDIT1 - no it has a listview called deviceList, XML file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.bluetooth_app.Bluetooth_App" >

    <Button
        android:id="@+id/scanButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="28dp"
        android:layout_marginTop="21dp"
        android:text="Scan" />

    <ListView
        android:id="@+id/deviceList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginRight="26dp"
        android:layout_marginTop="48dp" >
    </ListView>

</RelativeLayout>

Comment: Updated answer for edit, give that a try.
Answer: Note that you seem to be reusing your activity's layout file R.layout.activity_bluetooth__app when initializing your ArrayAdapters in Bluetooth_App. This is probably not what you meant to do. The resource passed to the ArrayAdapter constructors should represent the layout of a single AdapterView row, and must contain a TextView with id text1 (to use a more customized row layout, you would need to subclass ArrayAdapter and override getView).
Comment: huh ok, sorry im new to Java so this may be dumb but, why does it work with the button and using a listener on it?
Comment: The button-related code works fine because the button is a part of your activity's layout. Think of the listview in your activity layout (with id deviceList) as a "container". The adapter handles converting the java objects in your list of data into a list of views that are then placed into this container. The adapter is ignorant of the activity layout in general; it just needs to be associated with a listview to know where to place the generated views. That's a broad view of the situation, but hopefully it helps.
Comment: See also http://developer.android.com/reference/android/widget/ArrayAdapter.html#ArrayAdapter(android.content.Context,%20int) for a description of the ArrayAdapter constructor you are using.


Using ajax to load a jQuery DataTable

Question: I'm trying (and failing) to load a jQuery DataTable using the built-in ajax source argument.  The datatable, however, shows the message "Loading..." where the row(s) should be appearing.
Here's my datatable call :
    $('#my-table').dataTable(
             {bFilter: false,
              bInfo: false,
              bJQueryUI: true,
              bPaginate: false,
              bStateSave: false,
              bSort: false,
              aoColumns: [ {"sTitle" : "Date"},
                           {"sTitle" : "Our Co."},
                           {"sTitle" : "Their Co."},
                           {"sTitle" : "Note"} ],
              sAjaxSource: "/contact/company_name/"} );

Using Chrome, I can see that the call to /contact/company_name/ is occurring, is returning status 200, and has the following data: [[[Hello], [Goodbye], [Test1], [Test2]]] (which is my test data).
I can also see that the dataTables.min.js is returning the error Uncaught TypeError: Cannot read property 'length' of undefined.
I assume that my returned data is not formatted properly.  Can anyone suggest the solution?
Comment: Is `[[[Hello], [Goodbye], [Test1], [Test2]]]` the exact content returned by the ajax source?
Answer: according to the website
your service should return data in this format:
{
  "aaData": [
    [
      "row 1 col 1 data",
      "row 1 col 2 data",
      "row 1 col 3 data",
      "row 1 col 4 data"
    ],
    [
      "row 2 col 1 data",
      "row 2 col 2 data",
      "row 2 col 3 data",
      "row 2 col 4 data"
    ],
    [
      "row 3 col 1 data",
      "row 3 col 2 data",
      "row 3 col 3 data",
      "row 3 col 4 data"
    ],
    [
      "row 4 col 1 data",
      "row 4 col 2 data",
      "row 4 col 3 data",
      "row 4 col 4 data"
    ]
  ]
}

so, wrap your array in an object, name the array as aaData and try again.
or you can name it any way you like, but then you need to add the sAjaxDataProp parameter in the datatables initialisation (say you name it data you would do it like this:
$('#example').dataTable( {
    "bProcessing": true,
    "sAjaxSource": "/ajaxsource/callmydata",
    "sAjaxDataProp": "data"
} );

Comment: Thank you.  I am actually an idiot, having solved this *exact same* issue last week.  This was the reminder I needed.
Comment: The link at the top is broken as of October 1, 2014
Comment: I do believe [this](https://datatables.net/reference/option/ajax) was the page linked to.
Comment: how can i add aoColumns also !
Answer: If your ajax source returns
[[[Hello], [Goodbye], [Test1], [Test2]]]

This is not ok for datatables. It should be:
{
     iTotalRecords: "54",
     iTotalDisplayRecords: "22",
     aaData: "[['Hello', 'Goodbye', 'Test1', 'Test2']]"
}

aaData stands for array of arrays.

Using ajax to load a jQuery DataTable


Is every sub-lattice of $\mathcal P(X)$ isomorphic to a sub-lattice of $\mathcal P(X')$ containing singleton sets?

Question: Let $X$ be a finite set. $\mathcal{P}(X)$ denotes the set of all subsets of $X$.
Let $\Gamma$ be a sub-lattice of $\mathcal{P}(X)$, i.e. $\Gamma$ is a collection of subsets of $X$ closed under union and intersection. Suppose $\Gamma$ non-empty and $\Gamma$ not made only of the empty set.
Set $$n:=n(\Gamma):=\min\{m\geq1\,|\, \Gamma\text{ contains at least one set of cardinality }m\}$$
and suppose $n\geq2$.
I would like to find a lattice $\Gamma'$ isomorphic to $\Gamma$, but with $n(\Gamma')=1$.
With this purpose I thought to define a map $\Phi\!:\Gamma\to\Phi(\Gamma)=:\Gamma'$ doing the following operations:

from each set $A\in\Gamma$ with cardinality $|A|=n$, choose $n-1$ elements and delete them; (Notice that all these sets $A$'s are pairwise disjoint, by the minimality of $n$ and since $\Gamma$ is closed under intersection)
call $Y$ the set of all deleted elements;
from each set $B\in\Gamma$ with cardinality $|B|>n$, delete the elements of $Y$.

Clearly in this way one obtains $\Gamma'\subseteq\mathcal{P}(X')$, where $X':=X\smallsetminus Y$, and $n(\Gamma')=1$.
My questions are:

is $\Gamma'$ a sub-lattice of $\mathcal P(X')$ ?
is the map $\Phi$ an isomorphism of lattices (i.e. $\Phi$ bijection, $\Phi(A\cup B)=\Phi(A)\cup\Phi(B)\,$, $\,\Phi(A\cap B)=\Phi(A)\cap\Phi(B)\,$) ?

Edit. It is trivial that $\Phi$ is surjective (by definition of $\Gamma'$).
It seems also clear that $\Phi$ is an homomorphism of lattices: it suffices to write $\Phi(A)=A\smallsetminus Y$ and apply elementary facts of set theory. Therefore the only thing that remains to prove it that $\Phi$ is injective.
Comment: This is not set theory, please do not keep adding the tag. From the [tag:set-theory] description: "This tag is for set theory topics typically studied at the advanced undergraduate or graduate level. More elementary questions should use the tag elementary-set-theory instead. These include cofinality, axioms of ZFC, axiom of choice, forcing, set-theoretic independence, large cardinals, models of set theory, ultrafilters, ultrapowers, constructible universe, inner model theory, definability, infinite combinatorics, transfinite hierarchies; etc."
Comment: So you are given a finite distributive lattice $\Gamma$ and you want to find a pair ($X',\Gamma')$ such that $\Gamma$ is isomorphic to $\Gamma'$ and $\Gamma'$ is a sublattice of ${\mathcal P}(X)$, containing at least one singleton, right?
Comment: OK, I missed the "finite" part.
Comment: exactly! (I think you wrote $\mathcal P (X)$ instead of $\mathcal P (X')$)
Comment: This forum is not the right place for this question.  To help you with thinking about this, ask yourself how many sets A of cardinality n are in the lattice Gamma?
Comment: Suppose the lattice $\Gamma$ has no least element.  Can it be isomorphic to such a $\Gamma'$ ?  (Either a singleton will be least, or $\varnothing \in \Gamma'$.)
Comment: @GEdgar No least element? I'm assuming $\Gamma$ sub-lattice of $\mathcal P(X)$ with $X$ finite set, so I think there is always a least element.
Answer: Tiny answer: Yes.
Short answer: use Birkhoff's representation theorem.
Long answer: Since $\Gamma$ is a sublattice of $\mathcal P(X)$, it is a distributive lattice. The proof of the Birkhoff's representation theorem basically says that the categories of finite distributive lattices and finite posets are dually equivalent. When you follow Birkhoff's construction from distributive lattices to posets and then back, you obtain a corrolary:
Corollary Every finite distributive lattice is isomorphic to a lattice of sets, with lattice operations $\cup,\cap$.
This corollary is sometimes called Birkhoff's representation theorem. Moreover,
it turns out that the Birkhoff's construction gives you exactly what you need.
Let me show how this thing works. Assume that you are given a finite poset $P$.
Call a subset $A$ of $P$ a downset if it has the following property: if $x\in A$ and $y\leq x$, then $y\in A$. Write $J(P)$ for the set of all downsets of $P$. Clearly, a $J(P)$ is closed with respect to both $\cup$ and $\cap$, so $J(P)$ is a distributive lattice. The bounds of this lattice are $\emptyset$ and $P$.
For the opposite direction, suppose you are given a distributive lattice $\Gamma$. Call an element $a$ join-irreducible if $b\vee c=a$ implies $a\in\{b,c\}$. Write $A(\Gamma)$ for the set of all nonzero join irreducible elements. ($0$ is always join-irreducible, but we have to throw it out because it would spoil the fun). It is easy to spot the elements of $A(\Gamma)$ if you draw the Hasse diagram of $\Gamma$: they are the elements of $\Gamma$ that cover exactly one element. If $\Gamma$ is a Boolean algebra, $A(\Gamma)$ are the atoms of $\Gamma$. If $\Gamma$ is a chain, then $A(\Gamma)=\Gamma\setminus\{0\}$. When you equip the set $A(\Gamma)$ with the partial order inherited from $\Gamma$, you obtain a finite poset.
And now the coolest part: for every finite poset $P$, $A(J(P))\simeq P$ and, for every finite distributive lattice $\Gamma$, $J(A(\Gamma))\simeq\Gamma$. The second isomorphism gives you the Birkhoff's representation theorem. I think this is really nice.
Back to your question: the set $A(\Gamma)$ is your $X'$ and $J(A(\Gamma))$. To see that the set system $J(A(\Gamma))$ contains a singleton, observe that the finite poset $A(\Gamma)$ must contain a minimal element $m$ and then
$\{m\}\in J(A(\Gamma))$.
Example of $\Gamma$, $A(\Gamma)$ and $J(A(\Gamma))$.

Let me tell you a couple more facts:

Both $J$ and $A$ are object parts of certain functors between categories of finite posets and finite distributive lattices. They establish a natural duality of categories.
This duality generalizes to the infinite case to a duality between distributive lattices and certain partially ordered topological spaces,
this is called Priestley duality.
Restricting to Boolean algebras, Priestley duality gives us Stone duality theorem for Boolean algebras.
Comment: @user118866 Yes it is true. It follows by duality: since $\Gamma$ embeds into $\mathcal P(X)$, so the dual map $X\to A(\Gamma)$ must be onto. So $|A(\Gamma)|\leq |X|$.
Comment: Thank you for the answer. I'm not familiar with lattice theory, so I don't understand a lot of terminology that you use. I'll try to understand your answer, but briefly are you saying that the answer is positive?
Comment: Another question, that I'll probably need: if $\Gamma=\mathcal P(X)$ is it true that $|I(\Gamma)|\leq |X|$ ?
Comment: I hope it is better now. I was lazy, because Monday.
Comment: Thank you very much for this detailed answer! It is really clear!
Can you say also if it is true that the number of non-zero join-irreducible elements of $\Gamma$ is smaller or equal to that the cardinality of $X$? If you want I posted a new question here http://math.stackexchange.com/questions/801833/number-of-join-irreducible-elements-in-a-lattice-upper-bound .I'm asking this because in the construction suggested by my question you would get $|X'|\leq|X|$.
Comment: Thanks a lot! If you feel like to post an answer here http://math.stackexchange.com/questions/801833/number-of-join-irreducible-elements-in-a-lattice-upper-bound, I will be happy to accept it
Comment: sorry but I didn't well-understand this last fact about the dual map. Could you give me further detail?


Finding choice probabilities by using utility with logit and probit models

Question: I am using a formula to calculate the utility, which is as follows:
v_{ij} = 1 - x*beta + delta_i + e_{ij}

delta_i ~ N(0,phi^2)
e_ij ~ N(0,sigma^2)

v_{ij} is the utility of state ij, x is the vector of dummy variables, beta is the vector of regression coefficients, delta is the i-th random error and e_{ij} is the usual error term.
So, let's say there are two alternatives to make a choice from and their utility functions are
    v_{i1} = 1 - x_{i1}*beta + delta_i + e_{i1}

and
    v_{i2} = 1 - x_{i2}*beta + delta_i + e_{i2} .

I am wondering how I could calculate the probability of choosing the first option.
I know I need to use this
P(Choosing the first) = P( v_{i1} >  v_{i2})
= ( 1 -x_{i1}*beta + delta_i + e_{i1}  > 1 - x_{i2}*beta+ delta_i + e_{i2} )

Can anyone please help me find this probability by using both logit and probit models.
Answer: A good reference is Train's text which is free online.
http://elsa.berkeley.edu/books/choice2.html
Start by rearranging your terms.
$P($Choosing the first) =
$P(v_{i1} > v_{i2}) = P(1-x \beta + \delta_i + e_{i1} > 1 - x \beta + \delta_i + e_{i2}) = P(e_{i1} - e_{i2} > 0)$
To evaluate this expression you need to consider the distribution of $e_{i}^{*} = e_{i1} - e_{i2}$.
While you've already assumed that $e_{i}$ is normally distributed, this assumption gives you the probit. The logit model comes out of assuming a type I extreme value distribution for the individual error terms (since then $e_{i}^{*}$ follows a Logistic distribution.)
Comment: thanks for your comment and link. By the way, I realised that I had made a mistake in x_{i1} ad x_{i2}, but have edited them
Comment: It doesn't really change much since the x's are observable, you can collect them on the right hand side (so instead of > 0 it is > x_{i1} - x_{i2})


Struck in Diffeomorphism invariance of the line integral

Question: I have been trying to study The Cotangent bundle from An introduction to smooth manifolds by John M Lee. I have been struck at a specific point in the Diffeomorphism Invariance of the integral. The proposition is given below.
Let $\omega$ be a smooth covector field on the compact interval $[a,b] \subseteq \mathbb{R} $. If $\varphi : [c,d] \to [a,b]$ is an increasing diffeomorphism, then
$$
\int_c^d \varphi ^ * \omega = \int_a^b \omega
$$
The proof starts by giving the coordinate expression for $\varphi ^ * \omega$ as
$$
(\varphi ^ * \omega)_s = \mathit{f}(\varphi(\mathit(s))\varphi'(\mathit{s})ds
$$
Where $ \omega(t)=f(t)\,dt$ for some smooth function $ f:[a,b]\to \mathbb{R}$, and $\mathit{t}$ is the standard coordinate on $[a,b]$, and $\mathit{s}$ is the standard coordinate on $[c,d]$.
I have been able to work out that
$$
(\varphi ^ * \omega)=(\mathit{f} \circ \varphi) d(t \circ \varphi)
$$
From this I am unable to reach the coordinate expression for $(\varphi ^ * \omega)_s$. Please help me by showing how the coordinate expression is arrived at.
Answer: The expression $f \circ \varphi$ is literally the same as the function $f(\varphi(s))$.
Now for the second part: the $d(t \circ \varphi)$. The function $t \circ \varphi$ means apply the function $\varphi$, and then take the $t$-coordinate of the result. Since everything is 1-dimensional, "taking the $t$-coordinate" is kind of silly. It's kind of assumed from your notation that $\varphi$ takes the $s$-coordinate to the $t$-coordinate, so $t \circ \varphi$ might as well just be written as $\varphi$, and the meaning would be the same.
So $d(t \circ \varphi)$ is pretty much just $d\varphi$, which is $\varphi'(s) ds$.
Comment: Thanks Nick. That was helpful


Proof: Sum / Intersection of family of equiuvalence relations is equivalence relation

Question: I have to check if sum and intersection of family of equivalence relations is equivalence relation.
Here is the exercise:
Let $\mathcal{R}$ be a family of equivalence relations defined on some set $X$. Check if $\bigcup \mathcal{R}$ and $\bigcap \mathcal{R}$ are equivalence relations on $X$.
I am doing this exercise and, so far, I have proved $\bigcup \mathcal{R}$ is reflexive and $\bigcap \mathcal{R}$ is reflexive and symmetric but I have no idea how to prove $\bigcup \mathcal{R}$ is symmetric.
Could you please give me some hints how to finish the proof (or how to build counter - example)?
Comment: For arbitrary $R_1$ and $R_2$ in $\mathcal R$, the union $R_1 \cup R_2$ is not necessarily transitive. If it were, we should have had "if $(a,b)\in R_1 \cup R_2$ and $(b,c)\in R_1 \cup R_2$, then $(a,c) \in R_1 \cup R_2$. Now try to find $R_1$ and $R_2$ such that $(a,b) \in R_1$ [but not in $R_2$] and $(b,c) \in R_2$ [but not in $R_1$]. Then you will have that $(a,b) , (b,c) \in R_1 \cup R_2$ but not that $(a,c) \in R_1 \cup R_2$.
For intersection, however, there is no problem. By simple membership you can prove the equivalence of $ R_1 \cup R_2$.
Answer: The intersection of a family of equivalence relations will be an equivalence relation. The proofs are the "follow your nose" variety - there is no real problem solving, you just have to write them out.
For unions, it is true that the union of a family of symmetric relations will be symmetric. The key point is that if $(a,b) \in \bigcup \mathcal{R}$, to use the notation from the question, then $(a,b) \in R$ for some $R \in \mathcal{R}$. Thus $(b,a) \in R$, because $R$ is symmetric, so $(b,a) \in \bigcup \mathcal{R}$ as well. This is the key point of working with this kind of union: the only way to be in the union of a family is to be in one of the sets of the family.
The union of a family of equivalence relations does not need to be transitive, though. You can find a counterexample with appropriate equivalence relations on a 3-element set $\{a,b,c\}$.


Add item to ListAPIView

Question: I have ordinary ListAPIView with specified model and serializer classes. I need to add one additional item to the end of list. This item should be created manually (no queryset) and should have the same structure as other items.
Answer: You can override list method for this:
from rest_framework.response import Response

class YoourView(generics.ListAPIView):

    def list(self, request):
        queryset = self.get_queryset()
        serializer = UserSerializer(queryset, many=True)

        # append serializer's data with some additional value
        response_list = serializer.data
        response_list.append(some_value)
        return Response(response_list)

Answer: Try this,
from rest_framework import generics
from rest_framework.response import Response

class MyListView(generics.ListAPIView):
    serializer_class = MySerializer
    queryset = MyModel.objects.all()

    def list(self, request, *args, **kwargs):
        response_list = list(super().list(request, *args, **kwargs))
        custom_dict = {
            "key_1": "value 1",
            "key_2": "value 2"
        }
        response_list.append(custom_dict)
        return Response(data=response_list)

Answer: I think it would be better that you keep the get_queryset, filter_queryset and get_serializer function in case you would modify the serializer_class instead of using the default serializer_class.
class YourView(ListAPIView):
    queryset = DefaultQueryset
    serializer_class = DefaultSerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        response_list = serializer.data
        response_list.append(some_value)
        return Response(response_list)

Answer: I'd recommend you to keep your actual load separated from the extra data you're trying to pass. This will help you avoid a lot of conflicts when you'll iterate over those later on.
Try this:
class YourView(ListAPIView):
    queryset = YourModel.objects.all()
    serializer_class = YourSerializer

def list(self, request, args, **kwargs):
    serializer = self.get_serializer(self.get_queryset(), many=True)
    load = serializer.data
    newdict = {'your_new_data': 666}
    response_list = {'load': load, 'extra': newdict}
    return Response(response_list)

Add item to ListAPIView


Triangle Inequality Proof

Question: I need to prove that
$$|n^3 − 2000| \le  n^3 + 2000,$$
for $n$ a natural number.
I understand that I need to use a form of the triangle inequality, but I cannot figure out how to do so.
I know that there is a form of the Triangle Inequality where
 $$|x+y| \le |x|+|y|$$  but I'm getting confused on how to decide what $x$ and $y$ are in terms of $n$.
Comment: This should hold for $n^3<2000$. What about for $n^3>2000$?
Comment: Often, the best way to prove that $|x| \leq M$ is to prove $-M \leq x \leq M$.
Answer: $n$ cannot be negative so that $|n^3|=n^3$ and obviously, $|-2000|=2000$. Thus,
$$\begin{align}|n^3-2000|&=|n^3+(-2000)|\quad\text{then use Triangle Inequality to get}\\
&\leq |n^3|+|-2000|\\
&=n^3+2000\end{align}$$
Comment: So by stating this, we have successfully proved the statement?
Comment: Yes, of course. It follows from the fact that if $x,y\in\Bbb R$ then $$|x-y|\leq |x|+|y|.$$
Comment: This proves it, but only since $n$ is natural meaning that $n>0$ so that $\vert n\vert=n$ and we can say $\vert n^3\vert=\vert n\vert^3=n^3$. Otherwise, the inequality is false for some negative $n$.
Comment: This makes sense now! I understand that a natural number cannot be negative, and I can see now how it follows from the triangle inequality.
Answer: You can look at a more general situation: For $x,y > 0, |x-y| \le x+y$. Start out with $0 \le 4xy \implies -2xy \le 2xy\implies x^2+y^2-2xy \le x^2+y^2 + 2xy\implies (x-y)^2 \le (x+y)^2\implies \sqrt{(x-y)^2} \le \sqrt{(x+y)^2}\implies |x-y| \le |x+y|=x+y$ which is the claim.

Triangle Inequality Proof


Solve by determinant

Question: I have the following equation:
$\begin{vmatrix} 0 &x &1 &2 \\ x& 1 & 1 &x \\ 1&x &x &1 \\ 1& x &1 &x \end{vmatrix} = 0$
I tried solving this by solving for $0\times (det A)$ - $x\times (det b)$ + $1\times (det c)$ - $2\times (det d)$
and this got me to the equation $-x^{4} + 4x^{3} -2x^{2} -4x +3 = 0$  and I get the answer +-1 and 3 and this is correct, however I solved this by entering the equation online, Is there any easier way to solve for x in these types of equations? When I do determinants all the way I allmost allways seem to end up with complex equations that I cannot solve by my self.
Can I break out X from the matrix some way and simplify?
Comment: Note also that the determinant of a matrix $A$ is zero if and only if that of $B$ is zero, where $B$ arises from $A$ by a row operation or column operation.
Comment: You could solve the linear equation $A\vec x = 0$ in dependence of $x$, where $A$ is your matrix.
Answer: A reasonable attempt is to use the Rational root theorem, to find that if $p(x)$ has rational roots, then they must be in $\{\pm 1, \pm 3\}$.
Comment: I like your nickname. ;-)
Comment: what a nifty little theorem, will surely help alot! Thanks!
Answer: Hint: A determinant is equal to zero if two of the rows (or columns) are linearly dependent. You can easily check that for $x=1$ the last two rows are linearly dependent, for example (they are the same). In general you can use Gussian elimination to simplify the problem.

Solve by determinant


Datapicker com @Html.EditorFor

Question: Tenho a seguinte model
    [DisplayName("Data Inicial Contrato")]
    [Required]
    [DataType(DataType.Date)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
    public DateTime DataInicialContrato { get; set; }

    [DisplayName("Data Final Contrato")]
    [Required]
    [DataType(DataType.Date)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
    public DateTime DataFinalContato { get; set; }

View:

                @Html.LabelFor(model => model.DataInicialContrato , htmlAttributes: new { @class = "control-label", @for = "datainicialcontrato" })
                @Html.EditorFor(model => model.DataInicialContrato, new { htmlAttributes = new { @class = "form-control ", @id = "datainicialcontrato"  } })
                @Html.ValidationMessageFor(model => model.DataInicialContrato, "", new { @class = "text-danger" })

                @Html.LabelFor(model => model.DataFinalContato , htmlAttributes: new { @class = "control-label", @for = "datafinalcontrato" })
                @Html.EditorFor(model => model.DataFinalContato, new { htmlAttributes = new { @class = "form-control", @id = "datafinalcontrato" } })
                @Html.ValidationMessageFor(model => model.DataFinalContato, "", new { @class = "text-danger" })

O datapicker não está aparecendo. Preciso que apareça um datapicker com formato DD/MM/YYYY e esteja em português.
Comment: Não aparece nada? Como fica o HTML gerado? Apenas copiei o seu código [para este exemplo](https://dotnetfiddle.net/kcwTdB) e funcionou normalmente.
Answer: Para isso você pode usar o DatePicker Bootstrap da seguinte maneira:

     @Html.LabelFor(model => model.DataInicialContrato , htmlAttributes: new { @class = "control-label", @for = "datainicialcontrato" })
     @Html.EditorFor(model => model.DataInicialContrato, new { htmlAttributes = new { @class = "form-control datepicker", @id = "datainicialcontrato"  } })
     @Html.ValidationMessageFor(model => model.DataInicialContrato, "", new { @class = "text-danger" })

E no javascript:

Datapicker com @Html.EditorFor


i18n in DataFX, JavaFX application getting LoadException: No resources specified

Question: I am new to DataFX (and using DataFx8) and struggling to get localisation working. My main class is as shown:
public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        //set language
        ViewConfiguration viewConfig = new ViewConfiguration();
        Locale locale = new Locale("en","EN");
        viewConfig.setResources(ResourceBundle.getBundle(UIConstants.LANGUAGE_BUNDLE_PREFIX, locale));

        Flow applicationRootFlow = new Flow(HomeController.class, viewConfig);
        FlowHandler applicationRootFlowHandler = applicationRootFlow.createHandler();

        StackPane root = applicationRootFlowHandler.start(new DefaultFlowContainer());
        primaryStage.setScene(new Scene(root, UIConstants.APPLICATION_WIDTH, UIConstants.APPLICATION_HEIGHT));
        primaryStage.setTitle(UIConstants.APPLICATION_TITLE);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

I have traced the code through, and the debug shows the Flow has loaded the resource successfully (see attached image).

The resource has the required index, but the fxml is not loading the string, instead crashing with
Caused by:... javafx.fxml.LoadException: No resources specified. /C:/.../Home.fxml:22
The line in the fxml is:

The resource bundle is:
applicationTitle=Service222222
displayLanguage=English

So is there something I am missing? Can I no longer do translation straight from fxml file due to different loading model of datafx (controller specifies fxml file)?
Answer: For others who come across this:
This is due to a bug when calling createHandler() method on the Flow. The current DataFx implementation ignores the ViewConfiguration object that is associated with the Flow and will always create new configurations (resources is always null) when returning the FlowHandler object.
As a workaround, avoid calling createHandler() to get the FlowHandler object. Instead, create it manually by calling the FlowHandler constructor that takes in the view configurations as a parameter.
applicationRootFlowHandler = new FlowHandler(applicationRootFlow, new ViewFlowContext(), viewConfig);


Programmatically create a UIViewController in a project with a storyboard

Question: I'm trying to make a ViewController with "next" button that takes me to an instance of the same ViewController class.
@interface ViewControllerDeco ()
{
    ViewControllerDeco *page1;
}

viewDidLoad:
page1 = [[ViewControllerDeco alloc]init];

button:
- (IBAction)btnNext:(id)sender {
    [self.navigationController pushViewController:page1 animated:YES];
}

It shows me a black screen, am I missing something?
Comment: Is that view controller based on a storyboard? If so, you should load (instantiate) it from there and not just alloc/init.
Answer: So if you are not adding UI elements in your ViewControllerDeco controller init function, you will get a black screen. If you want to create an instance of ViewControllerDeco based on a view controller in your storyboard, try something like this:
ViewControllerDeco *page1 = [self.storyboard instantiateViewControllerWithIdentifier:@"ViewControllerDeco"];
[self.navigationController pushViewController:page1 animated:YES];

Make sure to add a storyboard identifier to the VC that you want to load in code.
Answer: initiating view controller with
page1 = [[ViewControllerDeco alloc]init];

doesn't actually get it from storyboard, it just creates empty new one (which one you can set up in viewDidLoad for example), if you want to create that one from storyboard, you should do something like:
UIViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"ViewControllerDecoId"];
[self.navigationController pushViewController:vc animated:YES];

previously you should set "ViewControllerDecoId" to "Storyboard id" of your controller in your storyboard
hope helped


Muitos logs com a mensagem "setTypeface with style : 0"

Question: Estou fazendo um app no android studio, e depois de passar algumas activities a tela fica preta e o ultimo registro do log cat é essa mensagem. Já olhei as outras perguntas sobre isso mas nenhum resolveu meu problema. O que pode ser?
Answer: Isso acontece quando vc faz uma chamada
ao método
view.setTypeface(Typeface.DEFAULT,0) ou view.setTypeface(Typeface.DEFAULT,Typeface.NORMAL)
Troque para: view.setTypeface(Typeface.DEFAULT) (view being a TextView)
Comment: Essa é a questão, eu não estava fazendo nenhuma chamada a esse método. Mesmo assim tentei usar essa solução, mas a mesma coisa continua acontecendo.


Not able to read file content from google cloud storage in app engine

Question: When I try to read content of a file (plain text) from Google Cloud Storage (App Engine, Python, Standard Env) I get the following trace:
raise ConnectionError(err, request=request)
ConnectionError: ('Connection aborted.', error(13, 'Permission denied'))

Although 'Share Publicly' is set, I am working in the default bucket (the application should have full permissions to my understanding) and I am able to write/upload content to the same file.
As additional info I am triggering the request from an http route using GAE development server.
Could you point me to the right direction ? :D
Code is below:
def getDatastoreClient():
    projectId = 'xxxxxx'
    return storage.Client(projectId)

def readFileFromBucket(filename):
    # Instantiates a client
    storage_client = getDatastoreClient()

    # Creates the new bucket
    bucket = storage_client.get_bucket(BUCKETNAME)
    blob = bucket.get_blob(filename)
    return blob.download_as_string()

Comment: What version of `requests` are you using?  Revert back to v2.3 and see if that fixes it.
Comment: wow! Actually it does help, what is this meaning? I have been using 2.17.3 and I also tried 2.18...
Answer: Latest versions of requests are not yet compatible with GCS.  For now, downgrade your requests package to v2.3.0.  Or, switch to using GAE's urlfetch


Why the random forest (ranger function) returns a r.squared null

Question: I write this question because I use the random forest algorithm from the ranger package in R. My model is this:
    library(ranger)
    ...
    data manipulation
    ...
    model_rf<-ranger(formula = as.factor(bg_variable) ~., data = x_train,
                   num.trees = 100,
                   min.node.size = 80000,
                   probability = T,
                   importance = 'impurity')

My target variabile is a factor and is a boolean (1 bad result, 0 good result).
I'd like to see the r.squared but, when I call it the results is null, why?
Where I mistake?
Other the r.suared I take look to the Gini index(0.1375 I know that is low, but my db is not the best)  and to the prediction.error (0.03076395).
The is: why my r.squared is null?
model_rf$r.squared
NULL

thank you
Answer: From the documentation:

r.squared: R squared.  Also called explained variance or coefficient of
determination (regression only). Computed on out of bag data.

So r.squared is returned only for numeric (in R jargon) target variables.
Since yours is a factor, R² is not returned.
Comment: Thank you for your answer.
Could you suggest me other test that I can do?
Comment: This is a fraught question - which test.  It is like asking a random stranger to kiss your spouse, or more precisely it is like being asked by a random couple to kiss one of them.  It is an intimate thing.  In statistical problem solving the first thing you do is understand your problem and determine the nature of the tests you are going to use to answer your question or achieve your result.  I like Cohen's kappa for classification, but if you have a pointy-haired boss then you might find that intractable. Do you have an intuition that augments understanding of its use?  If not its fraught.


Is possible for a module to know when one of its blocks is being output on the dashboard, and change the content of that block?

Question: Drupal 7 has a new core module (dashboard.module) that allows users with the right permissions to add blocks defined from third-party sites to the dashboard, which is shown as overlay on the current page.
Is it possible for a module that implements blocks to know when the block is being rendered on the dashboard?
The idea would be to change the content of the block, and make it smaller (for example).
Answer: You could check the url argument that the block is displayed on and then if it matches an expected pattern i.e. /dashboard then you can alter the contents of the block. This solution only really works if you've coded the block yourself.
Update: This method will still work, although I'm not familiar enough drupal 7s dashboard module to comment further. The only thing I would suggest is to output page variables and see if there is anything set by dashboard module.
Comment: In Drupal 7 there is a new module: overlay.module. When this module is enabled, some pages are shown as overlay of the current page, and the URL doesn't reflect the page shown in overlay; this happens also to the dashboard page.
Answer: Looking at the code of dashboard.module, I found the following function:
/**
 * Implements hook_block_list_alter().
 *
 * Skip rendering dashboard blocks when not on the dashboard page itself. This
 * prevents expensive dashboard blocks from causing performance issues on pages
 * where they will never be displayed.
 */
function dashboard_block_list_alter(&$blocks) {
  if (!dashboard_is_visible()) {
    foreach ($blocks as $key => $block) {
      if (in_array($block->region, dashboard_regions())) {
        unset($blocks[$key]);
      }
    }
  }
}

dashboard_is_visible() is the function that returns TRUE when the dashboard is visible, and dashboard_regions() is the function that returns an array containing the list of the regions contained in the dashboard.
Those are the functions that allows to a module to know when its blocks are being rendered in the dashboard. The only problem is for the module to know to which region its blocks are associated, as the block object is not passed to the hook_block_view().
Drupal 7 uses new hooks, hook_block_view_alter() and hook_block_view_MODULE_DELTA_alter(), whose second parameter is the block object. Implementing one of these hooks is possible to alter the block basing on the fact the block is being rendered in the dashboard, or not.
Supposing that mymodule is the module short name, and test_block is the delta value, the module should use the following function:
/**
 * Implements hook_block_view_MODULE_DELTA_alter().
 */
function mymodule_block_view_mymodule_test_block_alter(&$data, $block) {
  if (dashboard_is_visible() && in_array($block->region, dashboard_regions())) {
    // The block is rendered in the dashboard.
  }
}


Template Laravel Ajuda!

Question: Tenho dois arquivos blade.php e não estou conseguindo visualizar no browser o conteúdo.
@extends('layouts.index')

   @section('content')
   @parent

Copyright © Your Blog 2016

    @stop

      @yield('content')

Comment: Não é assim. Seu arquivo template deve ser separado do arquivo content.

No content que você chama o extends templates.
Comment: Coloquei assim so para mostrar questão yield e extends
Answer: master.blade.php
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        @yield('content')

conteudo.blade.php
@extends('layouts.master')

@section('content')

Teste de Template

@stop

Precisa ter um Controller e uma Rota.
Já deve ter um Controller de modelo, use-o.
SeuController.php
public function getIndex(){
   return view('frontend.pagina');
}

Arquivo routes.php
Route::controller("/", "SeuController");

Acesse:

http://localhost/seu_site/public
Comment: Aqui ainda não deu certo. Estou começando laravel, tenho que criar um Controller ou não precisa ?
Comment: Não sei o que é isso não. Não deu certo.
Comment: Você sabe programar em PHP Puro ou OO ?
Comment: Sim, tenho experiencia.
Comment: Mas você disse que não sabe o que é. Não sabe o que é Controller, Rota ? O que você não sabe ?
Comment: Não sei o pq esta acontecendo isso tendeu.

Template Laravel Ajuda!


lifetime of fraud detection models

Question: Suppose we are building/testing a fraud detection model for a specific credit card/ or a quick cash loan business. We have a lot of data to play with (say past 5years), and after careful preprocessing, model selection, and parameter-tuning, we build a good model to detect/prevent fraud. We thought we did a superb job. However, as we build our model, Con-artists are developing their anti-fraud-detection system/methodology and soon enough, the behavior pattern of frauds become completely deferent. The model we build before become useless,and we need to build new models again...
I have very limited working experiences in building fraud detection models. My question is if there are any machine-learning models/combined models can self-evolve and detect this behavior changing issue, and quickly capture this pattern and adapt? or are there any academic/practical resources regarding this self-evolve AI/machine-learning? Thank you.
Answer: The behavior that you describe is called concept drift.
Mostly concept drift is due to a natural change in the underlying data.
In your case, you are in a game against the fraudsters, so you might want to be even more strict.
In order to know whether your model still performs well, due to a change in the fraud patterns or a natural change, most methods are based on checking it from time to time.
If there is a change, you can relearn if you have enough information. If you don't have enough data (very likely) or if you want to benefit from the previous methods, techniques designed of domain adaptation are very useful.
In case that you want to be very strict in the game, you can assume that your rival have unlimited computational power. Learning in this setting is described at

Learning in the Presence of Malicious Errors by Michael Kearns , Ming Li
Answer: I'm a beginner in machine learning and this is just my opinion but Sequential Bayesian Learning might prove to be an effective approach to this style of problems. Basically you start with some prior probability distribution of the model parameters and in light of the observations your prior distribution changes to a posterior distribution. Now you can discard this used data and choose this posterior to be your new prior and given the new observations in the data this changes to posterior.And this goes on. So as we keep on providing new data our model tries to adapt rather than the likelihood approach where the model parameters are fixed after optimising a loss function.

lifetime of fraud detection models


Can this expression be simplified? (double integral over a sphere in $\mathbb{R}^3$.

Question: Suppose $f:\mathbb{R}^3\to\mathbb{R}$ is an integrable function (I'm open to further restricting $f$, e.g. $f$ can be assumed to be smooth).
For some constants $0<r\leq R$, is there a way to simplify the expression
$$
\int_{\lvert y \rvert = R}\int_{\lvert x\rvert =r} f(x+y) \,\mathrm{d}S(x)\mathrm{d}S(y)
$$
to an expression not involving surface integrals?
Comment: @YuriyS I was thinking the double integral might be equal to something of the form $$C \int_{S} f(x) dx$$ where $S\subseteq \mathbb{R}^3$ and $C>0$ is a constant. I'm not entirely sure if this is possible, but my intuition tells me it might work
Comment: This is a little too general for me... Maybe you could give some examples?
Comment: @Quoka But that would be a surface integral, right?
Comment: @zhw. Which integral are you referring to?
Answer: Let's start by writing the integral as
$$ I = \int_{\mathbb{R}^3} \int_{\mathbb{R}^3} f(x+y) \delta(|x|-r) \delta(|y|-R)\, {\rm d}^3x {\rm d}^3y$$
where $\delta$ is Dirac's delta function. Changing the variables to $(z,y) = (x+y,y)$ we get
\begin{align} I &= \int_{\mathbb{R}^3} \int_{\mathbb{R}^3} f(z) \delta(|z-y|-r) \delta(|y|-R)\, {\rm d}^3y {\rm d}^3z \\
&= \int_{\mathbb{R}^3}  f(z) \Big(\int_{\mathbb{R}^3}\delta(|z-y|-r) \delta(|y|-R)\, {\rm d}^3y \Big) {\rm d}^3z\end{align}
For $0\le r \le R$, it can be calculated that
To calculate $ \int_{\mathbb{R}^3}\delta(|z-y|-r) \delta(|y|-R)\, {\rm d}^3y $ that let us use spherical coordinates for $y$ where angle $\theta$ is measured from the direction of $z$, so that
$$|y| = \rho $$
$$|z-y| = \sqrt{(|z|-\rho\cos\theta)^2 + (\rho\sin\theta)^2} = \sqrt{\rho^2 - 2\rho|z|\cos\theta + |z|^2}$$
We have then
\begin{align} & \int_{\mathbb{R}^3}\delta(|z-y|-r) \delta(|y|-R)\, {\rm d}^3y = \\
&\quad = \int_0^\infty {\rm d}\rho\int_0^{\pi}{\rm d}\theta\int_0^{2\pi}{\rm d}\phi\,\rho^2\sin\theta \delta(\sqrt{\rho^2 - 2\rho|z|\cos\theta + |z|^2}-r) \delta(\rho-R) = \\
&\quad = 2\pi R^2 \int_0^{\pi}{\rm d}\theta \sin\theta \;\delta(\sqrt{R^2 - 2R|z|\cos\theta + |z|^2}-r)=^{u:=\sqrt{R^2 - 2R|z|\cos\theta + |z|^2}}\\
&\quad = 2\pi R^2 \int_{|R-|z||}^{R+|z|} {\rm d}u \frac{u}{R|z|} \delta(u-r)= \\
&\quad = \frac{2\pi R}{|z|} \int_{-\infty}^\infty {\rm d}u \,u \,\theta((R+|z|)-u)\theta(u - \big|R-|z|\big|)\delta(u-r)=\\
&\quad = \frac{2\pi R r}{|z|} \,\theta((R+|z|)-r)\theta(r - \big|R-|z|\big|)=\\
&\quad = \frac{2\pi R r}{|z|} \,\theta((R+|z|)-r)\theta(r - (R-|z|))\theta(r - (|z|-R))=\\
&\quad = \frac{2\pi R r}{|z|} \,\theta(|z|+(R-r))\theta(|z| - (R-r))\theta(R+r - |z|) = ^{\text{since }|z|>0, R-r>0}\\
&\quad = \frac{2\pi R r}{|
z|} \theta\big(|z|-(R-r)\big)\theta\big(R+r-|z|\big) \end{align}
where $\theta$ is Heaviside's theta function.
In the end you get
$$ I = 2\pi R r \int_{|z|\in[R-r, R+r]}  \frac{f(z)}{|z|} {\rm d}^3z$$
Comment: I'm having a hard time justifying your use of the Dirac-delta function since it is technically a distribution. Do you have any references explaining why I can use it this way?
Comment: I'm not sure how integration against a distribution is generally defined, could you elaborate on that a bit? Also, how did you obtain the equality $$\int_{\mathbb{R}^3}\delta(|z-y|-r) \delta(|y|-R)\, {\rm d}^3y = \frac{2\pi R r}{|
z|} \theta\big(|z|-(R-r)\big)\theta\big(R+r-|z|\big)?$$
Comment: It is a distribution, but as long as it's integrated with a continuous function, I don't believe there would be any problems with it. I think you can avoid using distributions and get the same result, although in a more complicated way.
Comment: Distributions are formally defined as linear functionals on some space of functions. Dirac's delta is defined on the space of continuous functions, in a following way:
$$ \langle \delta_a, f\rangle = f(a) $$
Denoting
$$ \langle \delta_a, f\rangle = \int_{-\infty}^\infty {\rm d}x\, f(x)\delta(x-a) $$
is just a useful notation, but it has all necessary properties of an integral.
Comment: As for how I obtained the equality, I've edited the answer, as there's little space in the comment.
Comment: Thank you for that. I would have thought that the value of $\int_{\mathbb{R}^3} \delta(|z-y|-r)\delta(|y|-R)$ should correspond to the circumference of the circle at the intersection of the spheres $B_R(0)$ and $B_r(z)$.
Comment: It corresponds, in a way. Precisely, if $V(R,\Delta R, r, \Delta r, |z|)$ is the volume of the interesection of two spherical shells of of radii $R$ and $r$, thicknesses $\Delta R$ and $\Delta r$ respectively, whose centers ar at distance $|z|$, then this integral is equal to $\lim_{\Delta R\rightarrow 0}\lim_{\Delta r\rightarrow 0} \frac{V(R,\Delta R, r, \Delta r, |z|)}{\Delta R\Delta r} $. Or you can intersect a spherical shell with a sphere, take the area of the intersection, and take a similar limit.
Answer: Here's a re-derivation of Adam Latosiński's formula without using distributions.  Ultimately what needs to be done here is just a change of variables, but I'm going to use probabilistic language because I think it makes the whole thing easier to understand.
Observe that
$$
E[f] = \frac{1}{4\pi R^2} \int_{|y|=R} \frac{1}{4\pi r^2}\int_{|x|=r} f(x+y)\,dS(x)\,dS(y)
$$
is the expected value of $f(x+y)$ if we randomly choose vectors $x$ and $y$ for which $|x|=r$ and $|y|=R$.  We want to change variables to
$$
\rho=|x+y|\qquad\text{and}\qquad u = \frac{x+y}{\rho}.
$$
Note that $u$ is a unit vector which can be chosen uniformly at random from the unit sphere in $\mathbb{R}^3$.  Clearly $\rho \in [R-r,R+r]$, but the probability distribution of $\rho$ is not uniform on this interval, so we have to do some work to figure out how to sample $\rho$.
For this purpose, we may assume by symmetry that $y=(R,0,0)$ and $x$ is uniformly chosen on the sphere $|x|=r$.  Now, it is a famous observation of Archimedes that each coordinate of the unit sphere in $\mathbb{R}^3$ is uniformly distributed on the interval $[-1,1]$.  It follows that the first coordinate $t$ of $x$ is uniformly distributed on the interval $[-r,r]$.  But
$$
\rho = \sqrt{(R+t)^2 + (r^2 -t^2)} = \sqrt{R^2+r^2 + 2Rt}\tag*{(*)}
$$
so we can sample $\rho$ by choosing $t$ uniformly at random from $[-r,r]$ and then using this formula.
We conclude that
$$
E[f] = \frac{1}{2r}\int_{-r}^r \frac{1}{4\pi} \int_{|u|=1} f(\rho u)\,dS(u)\,dt
$$
where $\rho$ is the formula (*) above.  Note that the $t$ here actually represents the component of $x$ in the direction of $y$, i.e. $t = (x\cdot y)/R$.  Combining this with our original formula for $E[f]$, we deduce that
$$
\int_{|y|=R} \int_{|x|=r} f(x+y)\,dS(x)\,dS(y) = 2\pi rR^2 \int_{-r}^r \int_{|u|=1} f(\rho u)\,dS(u)\,dt
$$
where $\rho$ is given by the formula above.  Now observe that
$$
d\rho = \frac{d}{dt}\Bigl[\sqrt{R^2+r^2 + 2Rt} \Bigr]\,dt = \frac{R}{\sqrt{R^2+r^2+2Rt}}\,dt = \frac{R}{\rho}\,dt.
$$
Substituting $dt = (\rho/R)\,d\rho$, the integral becomes
$$
2\pi rR \int_{R-r}^{R+r} \int_{|u|=1} \rho\,f(\rho u)\,dS(u)\,d\rho
$$
If we like, we can change this to a single volume integral over $z=\rho u$.  Since $dV(z) = \rho^2\,dS(u)\,d\rho$ and $\rho=|z|$, the integral is
$$
2\pi rR \int_{|z|\in[R-r,R+r]} \frac{f(z)}{|z|}\,dV(z)
$$
where $z$ represents $x+y$.
Answer: If you work in Fourier space you can write $f(x+y)=\int e^{ik(x+y)}\hat{f}_k dk$ and you can separate the integral to $\int dk \hat{f}_k \int e^{ikx} dS(x) \int e^{iky}dS(y) $.


Infinite sum of ideals

Question: I've been trying to prove that given a ring $R$ and a collection of ideals $\{I_{\beta}\}_{\beta \in B}$ in $R$, the set $$\sum_{\beta \in B} I_{\beta}=\{f_1+\cdots+f_r:f_j \in I_{\beta_j}, \mbox{ for some } I_{\beta_j}\}$$ is an ideal and is the smallest ideal containing $\cup_{\beta \in B} I_{\beta}$.
I've already proved when I only have two ideals, and so, using induction, I've seen it for finite sums. But I don't see how to generalise that to an arbitrary family of indexes (maybe infinite) $\beta$.
Could someone please give me a hand? Thank you.
Comment: And returning to the original notation of the book? That way you're considering the ideal generated by the $f \in I_{\beta}$.
Comment: You're right @user26857 , in the book where I've seen the question it appears $\langle \rangle$, but it is referring to $\{\}$
Comment: ok, I'm thinking on it for a while.
Comment: I think a better definition of the sum could be the following: Given a ring $R$ and a collection  $\{I_{\beta}\}_{\beta \in B}$ of ideals in $R$, I consider $$\sum _{\beta \in B} I_{\beta}= \{f_1+...+f_r:f_j \in I_{\beta_j}, \mbox{for some } \beta_j\}$$, i.e, all finite sums of elements each taken form one of the $I_{\beta}$. What do you think @user26857?
Answer: The definition is correct. Now it's just a matter of finding the best notation for proving the closure of the set with respect to sums, because the fact that $0$ belongs to the set is obvious and it's also obvious that, if $x$ is in the set and $r\in R$, then $xr$ and $rx$ are in the set.
Instead of using $\beta_i$, it's preferable to write
$$
x=\sum_{\beta\in C}x_\beta
$$
where $C$ is a finite subset of $B$ and $x_\beta\in I_\beta$. Now, if you have $x$ written in that way and $E$ is a finite subset of $B$ containing $C$, you can also write
$$
x=\sum_{\beta\in E}x'_\beta
$$
where
$$
x'_\beta=\begin{cases}
x_\beta & \text{if $\beta\in C$}\\[2ex]
0 & \text{if $\beta\in E\setminus C$}
\end{cases}
$$
So, if
$$
x=\sum_{\beta\in C}x_\beta, \quad
y=\sum_{\beta\in D}y_\beta
$$
are elements of your set, consider $E=C\cup D$ and rewrite
$$
x=\sum_{\beta\in E}x'_\beta, \quad
y=\sum_{\beta\in E}y'_\beta
$$
as before. Thus
$$
x+y=\sum_{\beta\in E}(x'_\beta+y'_\beta)
$$
which belongs to the set, because $x'_\beta+y'_\beta\in I_\beta$ for each $\beta\in E$.

Infinite sum of ideals


Values in the while loop do not modify outside values

Question: I have a long code but I tried to copy and adapt my problem in as few lines as possible . I have a method which creates an array( 2D ) with 0 and 1
array1 = newValue(2)  - the number 2 represents how many 1 the array has
array2 = newValue(3)

and this loop
(0..9).each do|i|
(0..9).each do|j|
    while((array1[i][j] == array2[i][j]) && (array2[i][j] == 1))  do
      array1 = newvalue(2)
      array2 = newvalue(3)
  end
 end
end

I'm using the while loop so I won t have a 1 in the same position in both arrays . But what is inside the while loop doesn't modify the values of the array . I also tried using map!/collect! but I think I did something wrong because nothing happened. I hope you can understand what I was trying to do .
Edit:
def newValue(value)
value = value.to_i
array = Array.new(10)  { Array.new(10 , 0) }
(a lot of conditions on how to position the items in the array)
return array
end

Comment: what is the `newvalue` method doing?  This is just trying to fill a 2d array?  A little more context might help us help you.  It feels like you probably want that inner thing to look more like `array1[i][j] = newvalue(2)` or something, but since i'm not sure what you're trying to do, it's hard to know.
Comment: Do you mean to have it do `array1[i] = newValue(2)` and `array2[i] = newValue(3)` ?  The problem is probably because you're trying to assign a 1d array (the return from newValue) to a 2d array (array1 and array2).  Also, in your while statement `array2` will never equal `1` if it is in fact a 2d array - again, you're mixing apples and oranges, so to speak.
Comment: @mrrogers my while loops is supposed to find if array1 and array2 have an item with the value of 1 position at exactly the same coordinates . If they do they will be assigned new values. (I modified the condition now, I missed that when I wrote the program here . )
Comment: This method is creating a 2d array with all the items set to 0 array = Array.new(10)  { Array.new(10 , 0) }
Comment: Then I'll stick with the while loop issue.  I think you need `array2[i][j] == 1` as the last part of that while loop clause.  The rest might actually work.
Comment: I do have that. And it doesn't work. I need another method in the while loop to modify the array . After the while loop the array still has the first value
Comment: it gets more complicated... ;)
Comment: Can you post the entire `newValue` method?
Answer: Here's my take... hopefully it'll help out.  It seems that what you noticed was true.  The arrays are not getting reset.  Probably because inside the each blocks, the scope is lost.  This is probably because the are arrays.  I took a slightly different approach.  Put everything in a class so you can have instance variables that you can control and you know where they are and that they are always the same.
I pulled out the compare_arrays function which just returns the coordinates of the match if there is one.  If not it returns nil.  Then, youre while loop is simplified in the reprocess method.  If you found a match, reprocess until you don't have a match any more.  I used a dummy newValue method that just returned another 2d array (as you suggested yours does).  This seems to do the trick from what I can tell.  Give it a whirl and see what you think.  You can access the two arrays after all the processing with processor.array1 as you can see I did at the bottom.
# generate a random 2d array with 0's and val's
def generateRandomArray(val=1)
  array = []
  (0..9).each do |i|
    (0..9).each do |j|
      array[i] ||= []
      array[i][j] = (rand > 0.1) ? 0 : val
    end
  end
  array
end

array1 = generateRandomArray
array2 = generateRandomArray

def newValue(val)
  generateRandomArray(val)
end

class Processor
  attr_reader :array1, :array2

  def initialize(array1, array2)
    @array1 = array1
    @array2 = array2
  end

  def compare_arrays
    found = false
    for ii in 0..9
      break unless for jj in 0..9
                     if ((@array2[ii][jj] == 1) && (@array1[ii][jj] == 1))
                       found = true
                       break
                     end
                   end
    end
    [ii,jj] if found
  end

  def reprocess
    while compare_arrays
      puts "Reprocessing"
      @array1 = newValue(2)
      @array2 = newValue(3)
      reprocess
    end
  end
end

processor = Processor.new(array1, array2)
processor.reprocess

puts processor.array1.inspect

Comment: I tried that but nothing happens .. I think you used a different method to assign values to the arrays, because I can t use this part in mine processor = Processor.new(array1, array2)
Comment: I updated the post to include my versions of the 2d array generation which is also used for my fake `newValue` method.  Is there any way to post the newValue method with a bit more detail?  Maybe the problem is inside there?
Comment: I found another way :d . I had too many arrays for that method to handle


Determine whether series is divergent or convergent

Question: $$\sum_{n = 3}^{\infty}\frac{1}{n(\ln n)^2}$$
I used Integral Test and I am up to $$\frac{-1}{\ln x}$$ Do I need to plug in $0$ and $t$ to find out if it is divergent or convergent?
Comment: The integral used here is $$\int_3^\infty \frac{1}{x\log^2(x)}\,dx=\frac{1}{\log(3)}<\infty$$
Comment: The integral test reduces the convergence of certain series to the convergence of related improper integrals. Are you asking about how improper integrals are evaluated?
Comment: I was confused on what I needed to do after getting it to $\frac{1}{lnx}$ I wasn't sure how getting it in the form I had would determine if it was divergent or convergent.
Comment: https://en.wikipedia.org/wiki/Cauchy_condensation_test
Comment: If you read French or Spanish, you'll find all you have to know about *Bertrand's series* on [Wikipedia](https://fr.wikipedia.org/wiki/S%C3%A9rie_de_Bertrand).
Answer: You do not need plug in $0$ and $t$ to find out whether it converges. Instead, you need to plug in $3$ which is the lower limit of the summation and the $\infty$ which is the upper limit of the summation in order to ascertain whether it diverges.
By Integral test:
$$\sum_{n = 3}^{\infty}\frac{1}{n(lnn)^2} < \frac{1}{3(ln3)^2}+\int_{3}^{\infty} \frac{1}{x(lnx)^2}dx$$
$$\int \frac{1}{x(lnx)^2}dx = -\frac{1}{lnx}+C$$.
So When $x \to \infty$, $\ln{x} \to \infty$, $\frac{1}{\ln x} \to 0$.
When $x = 3$,  $-\frac{1}{lnx} = -\frac{1}{\ln 3}$
Then $$\sum_{n = 3}^{\infty}\frac{1}{n(lnn)^2} < \frac{1}{3(ln3)^2}+[-\frac{1}{lnx}]_3^{\infty} = \frac{1}{3(ln3)^2}+\frac{1}{\ln 3}$$.
Therefore the series converges.
Comment: did you determine it was convergent by using the direct comparison test?
Comment: @Bazfred Nope. I use the integral test as you recommended in the problem.
Comment: @Bazfred If you need the result of direct comparison test, you can see Jack's comment below the question. (i.e. Cauchy Condensation Test)


Initial Segments of Modular Arithmetic

Question: Modular arithmetic (MA) has the same axioms as first order Peano arithmetic (PA) except $\forall x(Sx \neq 0)$ is replaced with $\exists x(Sx=0)$. MA is $\omega$-inconsistent and all infinite models of MA have non-standard elements.
I have been been trying to figure out if every infinite model of MA is an initial segment of some model is PA. I think the answer is no, but defining initial segments of PA seems to be way above my head. Every infinite model of MA has a subset that is an initial segment of a model of PA. PA would be inconsistent if some initial segment of PA is first order definable in either PA or MA.
This started me thinking about initial segments of MA. It seems obvious that every model of MA has all "smaller" models of MA as definable subsets (definable in the meta-theory). For example, the trivial ring is an initial segment of every model of MA because the trivial ring satisfies all of the axioms of MA. For finite models of MA, the rings $\mathbb{Z} /n \mathbb{Z}$, every initial segment is unique. There is exactly one model for each $n$.
The algebraic numbers, $\mathbb{A}$, is a countably infinite model of MA. Let $\mathbb{M} = \mathbb{Z} /x \mathbb{Z}$ be a model of MA where x is an uncountable non-standard number. Would $\mathbb{A}$ be an initial segment of $\mathbb{M}$?
I know I am not suppose to ask more than one question, but I would be interested in anything that can be said about initial segments of MA. For example, are initial segments of MA first order definable?

Edit in response to Lawrence Wong's questions.
Order can not be defined in MA the same way it is in PA. In PA we can say $x \leq y \rightarrow \exists z(y = x+z)$. This definition doesn't work in MA. MA does have a discrete cyclic order. This order is defined by the successor relation. With a cyclic order we can define [a,b,c] meaning "repeatedly applying successor to a reaches b before c". Since I am working in first order, I am pretty sure [a,b,c] is only definable when a, b, and c are a finite distance from one another.
I don't know much about initial segments which is why I am asking this question. I couldn't find a definition on the net. I think an initial segment is a subset of the model that satisfies the axioms. The standard natural numbers are a subset of every model of PA so they are an initial segment of every model of PA. An uncountable non-standard model would have lots of countable initial segments. Initial segments can be closed under successor and not addition or closed under both successor and addition, etc.
I think we are also allowed to perform transformations on the model. The smallest model of MA is the trivial ring. Given another model of MA, $\mathbb{M}$, I can map every element of $\mathbb{M}$ to $0$. I can then show the model satisfies the axioms under this transformation proving {0} is an initial segment of the model.
The successor relation is defined by the axioms. $\forall x(Sx=x+S0)$ is a theorem of both MA and PA. The successor must be $Sx=x+1$. This defines a cyclic order on the algebraic numbers. Clearly, this is not the same as the "standard" ordering. I will be asking some questions about this soon. I don't think the algebraic numbers are a model of MA, but people smarter than me have said any algebraically closed field is a model of MA.
Comment: There are several points that are not clear to me. (a) Does MA say anything about the "order"? (b) What does "some initial segment of PA is first order definable" mean in your second paragraph? (c) How do you define successor in the algebraic numbers $\mathbb A$?
Comment: Elaborating what Lawrence Wong probably meant a little (and I certainly do!): what does "initial segment" even mean for models of MA or PA?
Answer: This probably doesn't qualify as an answer, but it is definitely too long for a comment.
Somewhere hidden in the literature, there is a theory called Peano-with-top, sometimes denotes by PT.  It seems every model of your MA can be tweaked to give a model of PT, and vice versa.  (Do check this properly yourself!)  A quick search on the MathSciNet gives me the following paper.

Patrick Cégielski, Kenneth McAloon, and George Wilmers.
  Modelès recursivement saturés de l'addition et de la multiplication des entier naturels.
  In Logic Colloquium '80, Studies in Logic and the Foundations of Mathematics, vol. 108, pp. 57–68.
  North-Holland, Amsterdam, 1982.

In there, you find a theorem (attributed to Paris) which says that every model of PT is an initial segment of a model of $\mathrm I\Delta_0$.  It seems unlikely that you can require more induction in the extension, because otherwise, our model of PT would be recursively saturated.
I don't know what you may want an initial segment to be in a model of MA, especially when the order is intended to be cyclic.  I suppose you choose the definition that gives you the results you want.  In any case, induction forbids any definable set that contains 0 and is closed under successor to be proper.
Comment: Thanks. I have heard of $PT$ before and I will try to look up more. I am not sure how $Z_2$ or $\mathbb{A}$ can be initial segments of non-standard models of PA.
Comment: @Russell Easterly: The first idea that comes to mind is to define a model $A\models\mathrm{MA}$ to be an *initial segment* of a model $M\models\mathrm{PA}$ if there exists $a\in M$ such that $M$-modulo-$a$ is isomorphic to $A$.
Comment: This is how I see it, too. If there is such an $a \in M$ for $Z_2$ then $a$ is [neither even nor odd](http://mathoverflow.net/questions/142761/neither-even-nor-odd-natural-numbers).
Comment: @Russell Easterly: It seems Emil Jeřábek's answer to [one of your other questions](http://mathoverflow.net/questions/119375/) is incompatible with my intuition about the situation.  So please take my comments above with a pint of salt.

Initial Segments of Modular Arithmetic


Using QueryOver how do I write a Where statement against an "is in"

Question: When using QueryOver, I normally write a Where clause where the field exactly matches a value:
var subset = _session.QueryOver<ProviderOrganisation>()
.Where(x => x.Type == "Hospital")
.List<ProviderOrganisation>();

But now I want to match the field against a list of values, so in SQL something like a "Where x is in ():"
var subset = _session.QueryOver<ProviderOrganisation>()
.Where(x => x.Code is In (ListOfSubsetCodes))
.List<ProviderOrganisation>();

How do I do that please?
Thanks
Answer: You can use contains to do a in:
.Where(x => ListOfSubsetCodes.Contains (x.Code))

Answer: You've used QueryOver, and another way of doing this:
.WhereRestrictionOn(x => x.Code).IsIn(ListOfSubsetCodes)

I think x => ListOfSubsetCodes.Contains() will work well for LINQ, but not for QueryOver.
Comment: That's really helpful Anton - I'd never seen that before. Thanks