How to implement PhoneStateListener with MVP

Question: I am refactoring one of my old apps in MVP. I have refactored most of the logic and now I am stuck with following one.
In one of my Activities, I have implemented PhoneStateLister as following.
private class CallStateListener extends PhoneStateListener {

    public void onCallStateChanged(int state, String incomingNumber) {

        switch (state) {
            case TelephonyManager.CALL_STATE_IDLE:
                deactivateSpeaker();
                if (callCount == 0) {
                    doCall();
                } else {
                    checkForHangUp();
                }
                break;
            case TelephonyManager.CALL_STATE_OFFHOOK:
                checkAutoSpeaker();
                break;
            case TelephonyManager.CALL_STATE_RINGING:
                break;
            default:
                break;
        }
    }

    private void checkAutoSpeaker() {
        if (preferenceManager.isAutoSpeaker()) activateSpeaker();
    }

    private void activateSpeaker() {
        final Handler mHandler = new Handler();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                audioManager.setMode(AudioManager.MODE_IN_CALL);
                audioManager.setSpeakerphoneOn(true);
            }
        }, 1000);
    }

    private void deactivateSpeaker() {
        audioManager.setMode(AudioManager.MODE_NORMAL); //Deactivate loudspeaker
    }

}

I am having a hard time deciding where to put this logic in MVP. Should Activity handle this PhoneStateListener or should presenter handle this?
Please help me with the solution. Thanks.
Comment: check this [tutorial](http://www.truiton.com/2014/08/android-phonestatelistener-example/) may help.
Comment: Thanks, @MohammedFarhan. But that tutorial only describes how to implement PhoneStateListener, which I already know. As I stated, I want to know that, should Activity or Fragment be responsible for handling that Listener?
Comment: You might have not seen that tutorial properly. `CustomPhoneStateListener` is a custom class with all listeners in it and in activity this class is being implemented to listen telephonymanager.
Answer: Setting up listeners in an MVP pattern is always a little tricky. I am pretty sure that there is no "right" or "wrong" answer to your question, since it heavily depends on your personal preferences and architecture style. But as I general rule it is always smart to move as much business logic to the presenter and keep everything else (this also includes listeners) as dumb as possible.
That is why I would suggest that you add an interface to your listener class and keep a (weak) reference to the presenter there. The only thing that the listener does in that example is listening to the state change and then forwarding the information to the presenter (where it gets distributed).
public class CallStateListener extends PhoneStateListener {
    private final WeakReference<CallStateListenerInterface> presenterInterface;
    public CallStateListener(CallStateListenerInterface presenterInterface){
        this.presenterInterface = new WeakReference<>(presenterInterface);
    }
    public void onCallStateChanged(int state, String incomingNumber){
        presenterInterface.get().onCallStateListenerCallStateChanged(state, incomingNumber);
    }
    public interface CallStateListenerInterface {
        void onCallStateListenerCallStateChanged(int state, String incomingNumber);
    }
}

You presenter needs to implement the CallStateListenerInterface (of course) and handles all the business logic when the call state changes.
public class myPresenter implements MVPInterface, CallStateListenerInterface {

    /*your business logic*/

    public void onCallStateListenerCallStateChanged(int state, String incomingNumber){
        switch (state) {
           case TelephonyManager.CALL_STATE_IDLE:
                deactivateSpeaker();
                if (callCount == 0) {
                    doCall();
                } else {
                    checkForHangUp();
                }
               break;
           case TelephonyManager.CALL_STATE_OFFHOOK:
               checkAutoSpeaker();
               break;
           case TelephonyManager.CALL_STATE_RINGING:
               break;
           default:
               break;
        }
    }
}

From here everything that needs to interact with the view will be called, but keep those calls to simple one line instructions and leave everything complicated for the presenter to decide.
If you don't want to add a new interface for each listener class you can also just pass the whole MVPInterface to the CallStateChangedListener (and declare everything at a central place in your contract).
If you implement the listener this way you got a pretty clean architecture that should be easily testable.
I hope this was helpfull and please let me know if you have any questions :)
SMALL ALTERNATIVE IMPLEMENTATION:
As pointed out by a commenter: In my original suggestion, the presenter accesses the static phone state integers from the TelephonyManager class. This is not the cleanest design, since the presenter should be kept completely separate from any Android specific code.
Since there are no real super clean ways to work around this, I can only suggest a mapping from the TelephonyManager states to a (self defined) phone state that is kept in the presenter (or better yet: a static constants file).
Basicly that means the onCallStateChanged in the CallStateListener should look something like this:
public void onCallStateChanged(int state, String incomingNumber){
    int stateValue = myPresenter.PRESENTER_CALL_STATE_IDLE;
    if (state == TelephonyManager.CALL_STATE_RINGING){
        stateValue = myPresenter.PRESENTER_CALL_STATE_RINGING;
    } else if (state == TelephonyManager.CALL_STATE_OFFHOOK){
        stateValue = myPresenter.PRESENTER_CALL_STATE_OFFHOOK;
    }
    presenterInterface.get().onCallStateListenerCallStateChanged(stateValue , incomingNumber);
}

With this implementation you could move the TelephonyManager states out of the presenter and use your own defined ones.
(once again: I am really not sure if this is worth the effort, but I wanted to at least offer the alternative)
Comment: I can only disagree with this, as presenters should not contain any platform specific logic (i.e. should import no android classes) and should contain only pure java
Comment: yes, I completely agree ... but the only android specific components that my suggestion uses are the static TelephoneManager Integers inside the state switch. I admit that this is not super clean, but every alternative solution makes the code much more dirty ...
Answer: I believe you should leave the listener in your fragment/activity section.
I have in mind two solutions. The first one is to leave the switch/case in your listener and move a little bit of logic into your presenter:
public void onCallStateChanged(int state, String incomingNumber) {
    switch (state) {
        case TelephonyManager.CALL_STATE_IDLE:
            mPresenter.onCallStateIDLE();
            break;
        case TelephonyManager.CALL_STATE_OFFHOOK:
            mPresenter.onCallStateOffHook();
            break;
        case TelephonyManager.CALL_STATE_RINGING:
            mPresenter.onCallStateRinging();
            break;
        default:
            break;
    }
}

and in your presenter:
void onCallStateIDLE(){
    mView.deactivateSpeaker();
    if (callCount == 0) {
        mView.doCall();
    } else{
        mView.checkForHangUp();
    }
}

The other option should be to move the switch/case into the presenter.
The tricky part should be what to do with the TelephonyManager constants. As you know, you should leave the presenter as a pure java code.
You should have a View interface, there you can do something like this
interface MyActivityContract{
    interface View{
        int CALL_STATE_IDLE = TelephonyManager.CALL_STATE_IDLE;
        //etc etc the same with the rest of constants
    }
    interface Presenter{}
}

then in your listener, you should have a reference to your presenter
private class CallStateListener extends PhoneStateListener {
    public void onCallStateChanged(int state, String incomingNumber) {
        mPresenter.onCallStateChanged(state, incomingNumber);
    }
}

finally your presenter could be something like this
public void onCallStateChanged(int state, int incomingNumber){
    switch (state) {
        case MyActivityContract.View.CALL_STATE_IDLE:
            mView.deactivateSpeaker();
            if (callCount == 0) {
                mView.doCall();
            } else {
                mView.checkForHangUp();
            }
            break;
        case MyActivityContract.View.CALL_STATE_OFFHOOK:
            if (preferenceManager.isAutoSpeaker()){
                mView.activateSpeaker();
            }
            break;
        case MyActivityContract.View.CALL_STATE_RINGING:
            break;
        default:
            break;
    }
}

in this way you don't have any android reference in your presenter, but you have it in your contract.....


How to get the only the 2nd best score in MySqL? not the others

Question: i have one server whit minigames, and i have a problem whit my database, i need to get in query of mysql only the 2nd best score name.. can anyone help-me?
this is my database:
DATA_BASE
name  | kills
------+------
Leon  | 22
Andy  | 14
Brian | 8

i need to get just Andy name and kills from Andy!
code:
"SELECT * FROM `DATA_BASE` ORDER BY `kills` DESC"

please help-me! can i use limit to do this? what should i do? Thks
Comment: did you not even Google "limit mysql"? https://dev.mysql.com/doc/refman/5.7/en/select.html
Comment: you're also going to need another clause and method
Comment: use the `LIMIT` of mysql in your query
Comment: *"need to get in query of mysql only the 2nd best score name"* - being `14` I see, is that correct? Are you looking at comments or are you not bothering? Edit: Ok, I see you're not bothering.
Comment: Ok, thank you, i know now what to do ;D.
Answer: This should do the trick :
SELECT * FROM DATA_BASE ORDER BY kills DESC LIMIT 1 OFFSET 1;

LIMIT 1 limits the number of rows selected and OFFSET 1 offsets the rows by 1 resulting in only second row being selected.
Answer: Try:
SELECT name FROM DATA_BASE ORDER BY kills DESC LIMIT 1,1

This should return only the second best, because we want 1 option (the second number) and we want to offset it by 1 (the first number)
Comment: I use this, but the game thinks that LIMIT should be LIMIT of kills
Comment: MySQL doesn't use limit to evaluate greater than or less than, it limits the number of returns. It's possible you have another problem in your program.
Answer: You can use LIMIT keyword like as follows:
 SELECT * FROM DATA_BASE ORDER BY kills DESC LIMIT 1, 1

Answer: Try that.
Should limit to one 1 record and start on record 2.
"SELECT * FROM DATA_BASE ORDER BY kills DESC LIMIT 1 OFFSET 1"

Answer: SELECT * FROM (SELECT * FROM DATA_BASE ORDER BY kills DESC LIMIT 2) AS DB ORDER BY kills LIMIT 1;

We can do the same without using LIMIT by using MAX native function:
SELECT MAX(kills) FROM DATA_BASE WHERE kills NOT IN ( SELECT Max(kills) FROM DATA_BASE);

which is quite easier compared to earlier one


What is the coefficient of $x^5$ in $(1+x+x^2+x^3+x^4+x^5)^{17}$?

Question: I figured that $(1+x+x^2+x^3+x^4)^{17} = (1-x^6)^{17}*(1-x)^{-17}$ but don't know what else to do.
I would really appreciate any help
Comment: @HenningMakholm That is the generating function.
Comment: You can [Binomial theorem](https://en.wikipedia.org/wiki/Binomial_theorem) each of those factors and then do [long division](https://en.wikipedia.org/wiki/Long_division), but with [reverse degree monomial order](https://en.wikipedia.org/wiki/Monomial_order) to compute the first $6$  terms.
Comment: This feels like something that ought to have a stunning solution involving generating functions.
Answer: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
&\bbox[10px,#ffd]{%
\bracks{x^{5}}\pars{1 + x + x^{2} + x^{3} + x^{4} + x^{5}}^{17}} =
\bracks{x^{5}}\pars{1 - x^{6}}^{17}\pars{1 - x}^{-17}
\\[5mm] = &\
\bracks{x^{5}}\pars{1 - x}^{-17} = {-17 \choose 5}\pars{-1}^{5} =
-\bracks{{-\pars{-17} + 5 - 1 \choose 5}\pars{-1}^{5}}
\\[5mm] = &\ {21 \choose 5} = \bbx{20349}
\end{align}
Comment: +1 nice use of binomial expansion on negative exponents
Comment: Why does $[x^5](1-x^6)^{17}(1-x)^{-17} = [x^5](1-x)^{-17}$? Thank you
Comment: @lambchopp $(1-x^6)^{17}=1-17x^6+\dots$, so the only way it contributes to the $x^5$ coefficient is from the constant term, hence $[x^5](1-x^6)^{17}(1-x)^{-17}=[x^5]1(1-x)^{-17}$.
Comment: @SimplyBeautifulArt Thanks. And thanks for replying to $\texttt{@lambchopp}$ comment.
Comment: neat and quick (+1)
Comment: @GCab Thanks. Indeed, short.
Answer: Since
$$
\left( {1 + x + x^2  + x^3  + x^4 } \right)^{\,17}  = \left( {{{1 - x^5 } \over {1 - x}}} \right)^{\,17}
$$
you might be interested to know that the general
case of what are somewhere called r-nomial coefficients corresponds to the O.G.F:
$$
F_b (x,r,m) = \sum\limits_{0\,\, \leqslant \,\,s\,\,\left( { \leqslant \,\,r\,m} \right)} {N_b (s,r,m)\;x^{\,s} }
  = \left( {1 + x +  \cdots  + x^{\,r} } \right)^m  = \left( {\frac{{1 - x^{\,r + 1} }}{{1 - x}}} \right)^m
$$
where
$$
N_b (s,r,m)\quad \left| {\;0 \leqslant \text{integers  }s,m,r} \right.\quad  =
\sum\limits_{\left( {0\, \leqslant } \right)\,\,k\,\,\left( { \leqslant \,\frac{s}{r+1}\, \leqslant \,m} \right)}
{\left( { - 1} \right)^k \binom{m}{k}
 \binom
 { s + m - 1 - k\left( {r + 1} \right) }
 { s - k\left( {r + 1} \right)}\ }
$$
You can find a full explanation in this related post and in this paper
In your particular case, if it is $(1+ \cdots+x^4)^{17}$
$$
\eqalign{
  & N_b (5,4,17)\quad  = \sum\limits_{\left( {0\, \le } \right)\,\,k\,\,\left( { \le \,{s \over {r + 1}}\, \le \,m} \right)} {\left( { - 1} \right)^k \left( \matrix{
  17 \cr
  k \cr}  \right)\left( \matrix{
  21 - 5k \cr
  5 - 5k \cr}  \right)}  =   \cr
  &  = \left( \matrix{
  17 \cr
  0 \cr}  \right)\left( \matrix{
  21 \cr
  5 \cr}  \right) - \left( \matrix{
  17 \cr
  1 \cr}  \right)\left( \matrix{
  16 \cr
  0 \cr}  \right) = \left( \matrix{
  21 \cr
  5 \cr}  \right) - 17 = 20322 \cr}
$$
or for $(1+ \cdots+x^5)^{17}$
$$
\eqalign{
  & N_b (5,5,17)\quad  = \sum\limits_{\left( {0\, \le } \right)\,\,k\,\,\left( { \le \,{s \over {r + 1}}\, \le \,m} \right)} {\left( { - 1} \right)^k \left( \matrix{
  17 \cr
  k \cr}  \right)\left( \matrix{
  5 + 17 - 1 - 6k \cr
  5 - 6k \cr}  \right)}  =   \cr
  &  = \sum\limits_{\left( {0\, \le } \right)\,\,k\,\,\left( { \le \,{s \over {r + 1}}\, \le \,m} \right)} {\left( { - 1} \right)^k \left( \matrix{
  17 \cr
  k \cr}  \right)\left( \matrix{
  21 - 6k \cr
  5 - 6k \cr}  \right)}  = \left( \matrix{
  21 \cr
  5 \cr}  \right) = 20349 \cr}
$$
Answer: You can pick up an $x^5$ from one term and a $1$ from every other term 17 different ways.
You can pick up an $x^4$ from one term, an $x$ from a second term in $\dfrac{17!}{15!}$ ways.
You can get $x^3$ and $x^2$ in $\dfrac{17!}{15!}$ ways.
You can get $x^3$, $x$, $x$ in $\dfrac{17!}{1!2!14!}$ ways.
You can get $x^2, x^2, x$ in $\dfrac{17!}{1!2!14!}$ ways.
You can get $x^2,x,x,x$ in $\dfrac{17!}{1!3!13!}$ ways.
And finally, you can get $x,x,x,x,x$ in $\dbinom{17}{5}$ ways.
Show that this is exhaustive, and it should give you the correct answer.
Final tally:
$$17+2\cdot \dfrac{17!}{15!} + 2\cdot \dfrac{17!}{2!14!} + \dfrac{17!}{3!13!} + \dfrac{17!}{5!12!} = 20,349$$
Comment: Why is it $17!/15!$
Comment: You have an $x^4$ an $x$ and 15 $1$'s. So, the number of multiset permutations are $$\dfrac{17!}{1!1!15!} = \dfrac{17!}{15!}$$ I was a little lazy with my notation.
Comment: @InterstellarProbe Yes. Your answer is right. The sum was a missprint.
Answer: Another combinatorial approach:
When you multiply it out, each term is of the following form:
$$x^{a_1}x^{a_2}\cdots x^{a_{17}} = x^{a_1+a_2+\cdots + a_{17}}$$
You are looking for the number of solutions to $a_1+a_2+\cdots + a_{17} = 5$ where $\forall i: 0\le a_i \le 5$. Since the sum must add to 5 and there are no negatives, this is automatically satisfied, so we can ignore the upper bounds (a solution with no upper bounds is the same as a solution with upper bounds of 5 for each factor).
This is a well-known problem. It is the number of nonnegative integral solutions to a Diophantine equation. The solution is $$\dbinom{5+17-1}{5} = \dbinom{21}{5}$$
Answer: It is equivalent to the problem: how many ways can $5$ candies be distributed among $17$ children? Mathematically, it is:
$$x_1+x_2+\cdots +x_{17}=5, 0\le x_i\le 5, i=1,2,...,17.$$
The partitions of $5$ are:
$$\begin{align}\{5\} &\Rightarrow P(17,1)=\frac{17!}{16!}=17\\
\{4,1\} &\Rightarrow P(17,2)=\frac{17!}{15!}=272\\
\{3,2\}&\Rightarrow P(17,2)=\frac{17!}{15!}=272\\
\{3,1,1\}&\Rightarrow \frac{P(17,3)}{2!}=\frac{17!}{2\cdot 14!}=2040\\
\{2,2,1\}&\Rightarrow \frac{P(17,3)}{2!}=\frac{17!}{2\cdot 14!}=2040\\
\{2,1,1,1\}&\Rightarrow \frac{P(17,4)}{3!}=\frac{17!}{6\cdot 13!}=9520\\
\{1,1,1,1,1\}&\Rightarrow \frac{P(17,5)}{5!}=\frac{17!}{120\cdot 12!}=6188\\
\end{align}$$
Hence, the sum is: $20,349$.


Configure IPTables on KVM host to block guest bridge traffic

Question: I am working on a thesis research project, and I am having some difficulty figuring out how to get iptables (running on the KVM host) to block traffic (or rather, manipulate traffic) destined for a BRIDGED KVM guest.  I am unable to get the iptables entries (pasted below) to block traffic to and from the VM's.
Effectively, I would like my host system to act as a firewall for those guest VM's, and for the time being, I would like to test this capability by simply dropping all packets that is destined for a specific VM.  In the not-so-distant future, I would also like to implement more granular controls, and even have a proxy involved.  Again, this should happen entirely at the HOST level, and not at the GUEST level.
I am running CentOS 6, and based on another question that I wrote: Use one NIC to create multiple interfaces for Linux KVM, I have the following interfaces configured:
eth0
br0
tap0

Below is my network setup scripts for each interface:
eth0's Configuation:
DEVICE="eth0"
BOOTPROTO="none"
NM_CONTROLLED="no"
ONBOOT=yes
TYPE="Ethernet"
UUID="<<UUID-HERE>>"
HWADDR=<<MAC-ADDR-HERE>>
DEFROUTE=yes
PEERDNS=yes
PEERROUTES=yes
IPV4_FAILURE_FATAL=yes
IPV6INIT=no
NAME="System eth0"
BRIDGE="br0"

br0's Configuration:
DEVICE="br0"
TYPE="Bridge"
ONBOOT="yes"
BOOTPROTO="dhcp"
DELAY=0

tap0's Configuration:
DEVICE="tap0"
TYPE="Tap"
BRIDGE="br0"
ONBOOT="yes"

I have a CentOS 6 VM running and it is configured to utilize the tap0 bridged interface.  Networking on the VM is working properly. No other changes to the host system were made.
Below are the non-functioning iptables rules that I added to the FORWARD chain (it is worth noting that I am not a huge expert on iptables yet).
sudo iptables -I FORWARD -i any -o tap0 -j DROP
sudo iptables -I FORWARD -i tap0 -o any -j DROP

After running the commands, the FORWARD table looks like this:
Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 DROP       all  --  tap0   any     anywhere             anywhere
    0     0 DROP       all  --  any    tap0    anywhere             anywhere
    0     0 REJECT     all  --  any    any     anywhere             anywhere            reject-with icmp-host-prohibited

Unfortunately, this does not block the traffic.  I don't understand why this would not work.
UPDATE: 11/25/2014: It's been a while since I last updated this.  As it turns out, iptables has the physdev plugin, which is actually what I successfully use in my research and is more flexible then ebtables.
Answer: Make sure you understand the networking basics involved here. A bridge is a switch and operates at Layer 2. Your iptables rules apply to Layer 3 and will not be passed at this level.
Look into ebtables and specify Layer 2 rules there - or - disable the use of bridges altogether and move to a routed setup in which all traffic is passed through the host at Layer 3. Not sure if the latter option is possible using Libvirt/KVM.
Comment: Thank you for commenting.  How would using `ebtables` compare to using `PHYSDEV` as an option in `iptables`?
Comment: Additionally, because this is operating at level 2, how would one perform proxy filtering for that VM?
Comment: `ebtables` looks like the solution for my initial problem, and is thus the answer to this question.
Comment: Just to provide an update: `physdev` in `iptables` provides much of the functionality that I require, as you can examine the inbound and outbound to an interface on a bridge.
Answer: If you do:
echo 1 > /proc/sys/net/bridge/bridge-nf-call-iptables
it will enable netfilter on bridges and then you can set up iptables rules on the FORWARD chain to affect packets going to/from the virtual machines via the bridge interface.
To make it permanent on reboot:
edit /etc/sysctl.conf and set net.bridge.bridge-nf-call-iptables = 1
https://wiki.libvirt.org/page/Net.bridge.bridge-nf-call_and_sysctl.conf
Although the wiki says it's not desirable to do this, I have been doing this for years.  It allows me to set up blacklists and other iptables/ipset rules on the FORWARD chain that work globally for all VMs. It works just fine on moderately loaded servers.


Generating Create script for existing foreign key through SSMS

Question: While generating the Create DB script for the existing Foreign Key constraint through SSMS, we could able to see two set of alter statements. one with NOCHECK ADD and another with CHECK.
<code>ALTER TABLE [dbo].[claim]  WITH NOCHECK ADD  CONSTRAINT [FK_CLAIM_COPCID]
FOREIGN KEY([copcid])
REFERENCES [dbo].[copc] ([CopcId])
GO

ALTER TABLE [dbo].[claim] CHECK CONSTRAINT [FK_CLAIM_COPCID]
GO
</code>
Why we are getting two set of scripts to create a new Constraint?.
Comment: The second script doesn't create a constraint, it literally just checks it. https://dba.stackexchange.com/questions/24297/alter-table-check-constraint
Answer: The first alter statement is creating a constraint and instructing that constraint to be added without checking whether the existing rows obey the new constraint.
When you add a constraint without first checking the rows, it will not be fully active until you enable it.  That's what the second statement does, it enables the new constraint.  If there are rows that break the constraint, you won't be able to enable it.


Assign specific address or port to WCF service

Question: I have a web application in Angular and i have also created the WCF service in this web application. When i run the web application the URL is localhost:53536/#/Page. Service address is localhost:53536/Service/Service/svc. I hosted the web application and both web app and WCF service is working fine. But i want to host web service on different port or on different address. How can i do this. Here is my web.config
<system.serviceModel>

    <behaviors>

      <serviceBehaviors>

        <behavior name="" >

          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
      multipleSiteBindingsEnabled="true" />
    <bindings>
      <wsDualHttpBinding>
        <binding name="MobileServiceBinding" closeTimeout="00:00:05" openTimeout="00:00:05">
          <readerQuotas maxDepth="32" maxStringContentLength="5242880" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
        </binding>
      </wsDualHttpBinding>
    </bindings>
    <services>
      <service name="Web.Mobile.MobileService" >
        <endpoint address="" binding="wsDualHttpBinding"  bindingConfiguration="MobileServiceBinding" contract="Web.Mobile.IMobileService" />
      </service>
    </services>
  </system.serviceModel>

How i can assign different address to WCF service?
Answer: This sounds like the auto-assigned port from your project settings while the address of your endpoint configuration is empty.
Just modify address to your needs when deploying your web service
<services>
    <service name="Web.Mobile.MobileService" >
        <endpoint address="http://whatever.you.like:1337" binding="wsDualHttpBinding"  bindingConfiguration="MobileServiceBinding" contract="Web.Mobile.IMobileService" />
     </service>
</services>

or modify the project configuration for running / debugging your web service in Visual Studio.
Comment: thank for reply. I have already did this. Like as you said i have set the address http://MobileService:1337. When i hit this url in browser this error comes

When 'system.serviceModel/serviceHostingEnvironment/multipleSiteBindingsEnabled' is set to true in configuration, the endpoints are required to specify a relative address. If you are specifying a relative listen URI on the endpoint, then the address can be absolute. To fix this problem, specify a relative uri for endpoint 'http://mobileservice:1337/'.
Comment: As it seems answers on [WCF Error : Relative end point addresses
](https://stackoverflow.com/q/15681573/205233) suggest that leaving `address` blank is required for `multipleSiteBindingsEnabled` so you will have to abandon that or you'll have to stick with an endpoint address relative to your website, not being able to use a different port. Sorry that I missed out on the specific binding in your case.
Comment: Ok. What if i set false to multipleSitebinded. It is still not working.
Comment: Did you also try setting the `baseaddress` as suggested in [this answer](https://stackoverflow.com/a/42423452/205233)?
Comment: I guess your only chance is to move your WCF service to a dedicated project - I'm not familiar with the specific implications of `wsDualHttpBinding` for your project but to me it looks as the only way to achieve what you want.


Transaction stuck in "local transactions" with status "In queue: Future" - Parity Ethereum Node

Question: I'm reaching out for help as I've become as stuck as my transactions which are showing up in Parity TxQueueViewer under local transactions as status:
In queue: Future

As pictured in the below screenshot as tx: 0x0e97a4c

I'm setting tx: 0x0e97a4c up with https://github.com/ethereumjs/ethereumjs-tx and sending with https://github.com/ethereum/web3.js/ as below:
var Web3 = require('web3');
var Transaction = require('ethereumjs-tx');
var data = contract.method.getData(some, data);
console.log("Data: " + data);
var gasEstimate = web3.eth.estimateGas({
    to: web3.env.SENDER_ADDRRESS,
    data: data
});
console.log("GasEstimate: " + gasEstimate);
var nonce = web3.eth.getTransactionCount(process.env.SENDER_ADDRRESS);
console.log("Transation Count: " + nonce);
var rawTx = {
    nonce: web3.toHex(nonce),
    gasPrice: web3.toHex(process.env.GAS_PRICE),
    gasLimit: web3.toHex(gasEstimate),
    to: web3.toHex(process.env.CONTRACT_ADDRESS),
    value: web3.toHex(provider.toWei('1', 'ether')),
    data: data,
    chainId: 3
};
console.log("RawTx: " + JSON.stringify(rawTx));
var tx = new Transaction(rawTx);
console.log(tx.getChainId());
tx.sign(new Buffer(process.env.KEY, 'hex'));
web3.eth.sendRawTransaction("0x".concat(tx.serialize().toString('hex')), function(error, txHash) {
    if (error) {
        console.log(error); // an error occurred
        callback(error);
    }
    else {
        callback(null,{"error":0,"tx":txHash});
    }
});

I know the node is syncing and propagating transactions, which are subsequently mined, as transactions setup and sent from the Parity UI succeed as pictured below (which shows as mined in the image above):

As some background, I've been developing a project for Ethereum using Solidity and Javascript and utilising Truffle and Web3js. Testing against TestRPC. After some research, I selected Parity over Geth and am using the Ropsten network to run tests.
I have Parity version:
Parity/v1.6.8-beta-c396229-20170608/x86_64-macos/rustc1.17.0

running on:
MacOS Sierra 10.12.5.

I'm starting parity with the following:
parity --pruning fast --chain ropsten --warp --mode active --jsonrpc-interface all --jsonrpc-hosts all --allow-ips public

What does status "In queue: Future" mean?
Is there some sort of transaction release mechanism with Parity?
Or am I not setting up the transaction correctly for this type of node?
Answer: I just resolved this issue by stopping the Parity process and deleting Parity's cache (~/.local/share/io.parity.ethereum/cache). This problem occurs when there is a transaction that gets "stuck" locally. Once this "stuck" transaction is in the local queue, other transactions from the same address will not be propagated until the "stuck" transaction propagates.
Answer: This was a problem which bothered me for a long time. In my case I found that the error was caused due to the newer nonce being sent by metamask.
Scenario
I was running a chain with a specific chain id. I was using metamask for sending transactions. And a week later I created a new chain with same chain id and then when I was sending transactions using metamask, the transactions kept going in future.
Cure

Change the chain ID of the new chain. It may require a change in genesis file.
Reconnect metamask to RPC. This is to update the chain ID that was stored in metamask.
Send transactions. And now they should not go in "Future"


In simple Russian Roulette how many times should you shoot before handing it off to the other person?

Question: I'm assuming a game of Russian Roulette where you have a gun with 1 bullet and six chambers, and two people playing.
The rules are:

You must shoot at least once on your turn.
After shooting once, you can continue shooting as many times as you want until you decide to pass it to the other player.
Whoever gets shot loses (obviously?)
The chamber is spun once at the start of the game and the shots are taken in order from there without spinning. If the bullet is chamber 4 whoever shoots 4th will lose.

What are the optimal strategies for player 1 and player 2? Is it possible to figure this out or are there too many variables?
How about just for the first move? How many times should Player 1 shoot before passing it for an optimal chance at winning?
Comment: If the chamber chosen is random every shot then the optimal strategy should be obvious. Is there more to this game? Do you use each chamber in order until the bullet is fired? The optimal strategy will be the same but this detail matters for a proof given.
Comment: @Hugh I was thinking of an in-order type game. As in, you put the bullet in  the gun, spin the chamber and then never spin the chamber again. So if it's in the 4th chamber, whoever shoots the fourth shot is guaranteed to die.
Comment: You might have seen it but there is also a paragraph on probability on the Wikipedia page https://en.wikipedia.org/wiki/Russian_roulette What I found interesting is the fact that due to gravity the round tends to end up in the bottom position after spinning the barrel. That tells you that if you are player 1 you could/should take more than one shot.
Answer:
What are the optimal strategies for player 1 and player 2? How many times should Player 1 shoot before passing it for an optimal chance at winning?

Once the barrel is spun, the position of the bullet is fixed, which means that  there is a $\frac{1}{6}$ probability to be shot at turn number $i$, $i \in [|1,6|]$. As a result, the optimal strategy for player 1 and player 2  is to shoot only once on their turn. Following this strategy,  the probability that player 1 wins is the same as the probability that player 2 wins, i.e. $0.5$, regardless of who starts.
Comment: Kindly, I am able to "convince" myself more easily (I know the answer is obvious) following the reasoning in [this answer](http://math.stackexchange.com/a/96409/152225), which can be tweaked ever so slightly for this question. I sense there is a subtlety in your answer that I am missing.
Comment: What Franck is saying is there is a $\frac{1}{6}$ probability to be shot on turn $i$ as the bullet goes into one of the positions in the barrel with equal probability and the position of the bullet in the barrel completely determines on which turn someone will be shot. I believe you are thinking in terms of conditional probabilities i.e. the probability of being shot on turn 2 given you were not shot on turn 1.
Comment: If you are correct (and I bet you are) and I'm understanding you correctly (I'm not clear on the notation with vertical bars), I find it very counterintuitive that the probability would not increase with every passing round.
Comment: @AntoniParellada regarding the notation with vertical bars: http://math.stackexchange.com/a/875294/24265
Comment: If the barrel of the gun (I don't know about guns, but...) is spun just once, the first time around the $\Pr(\text{firing})=1/6$. However, if the first person is lucky and the gun doesn't go off, the barrel advances automatically to the next chamber, leaving behind an empty slot, doesn't it? My guess would be, then, that the guy (or girl) going in second place has now a $\Pr(\text{firing})=1/5$. After five rounds without firing the probability of dying for the unfortunate player pulling the trigger for the sixth time would be $1$. But this is not what you are saying, is it?
Answer: Here is an equivalent game:
There is a stack of 6 cards. The top card has the number 1, the second has the number 2, and so on through the bottom card, which has the number 6.
The rules are:

You must take at least one card on your turn.
After taking one card, you can continue taking as many cards as you want until you decide to pass your turn to the other player.
After all cards are taken, a 6-sided die is rolled. Whoever holds the corresponding card loses.

There is only one difference between this game and the Russian roulette game. In this game, the losing card is not revealed until after all cards have been chosen; in the Russian roulette game, the losing chamber is revealed immediately when that chamber is chosen. But this doesn't matter for choosing a strategy, because none of the choices matter any more once the losing card/chamber has been taken.
In the card game, the probability of losing is clearly proportional to the number of cards taken, so the winning strategy is simply to take as few cards as possible.
This means that the winning strategy for both games is:

If there are an even number of cards/chambers remaining, take only one card/shot.
If there are an odd number of cards/chambers remaining, take either one or two cards/shots; it makes no difference.


Como extrair determinado texto do pdf com node.js

Question: Eu tenho um código que transforma um pdf em um csv porem eu querotransforma em csv uma determinada parte do pdf e não o pdf inteiro.
código abaixo:
<code>   const fs = require('fs'),
    PDFParser = require("pdf2json");

    const analisarPdf = new PDFParser(this, 1);

    analisarPdf.on("pdfParser_dataError",
    errData => console.error(errData.parserError) );

    analisarPdf.on("pdfParser_dataReady", pdfData => {
      fs.writeFile("./Arquivos.csv", analisarPdf.getRawTextContent(), ()=>{console.log("Pdf convertido!");});
    });

    analisarPdf.loadPDF("teste.pdf", teste);
</code>
Answer: Podes selecionar o texto entre duas palavras ou o texto entre duas linhas.
<code>analisarPdf.on("pdfParser_dataReady", pdfData => {
    texto = analisarPdf.getRawTextContent();
    var inicio = "início";
    var fim = "fim";
    texto1 = texto.substring(
        texto.indexOf(inicio),
        texto.lastIndexOf(fim) + fim.length
    );
    texto2 = texto.split('\n').slice(5, 10).join("");
    fs.writeFile("./Arquivos.csv", texto1, ()=>{console.log("Pdf convertido!");});
});
</code>


LilyPond: auto horizontal space for piano pedal

Question: Is it possible to tell LilyPond to automatically add extra space for piano pedal symbols, so they don't overlap? If not, how to add the space manually?
Here is what I am trying to achieve:

This is what I get:

You can see that the pedal symbols overlap in the second measure.
This is the code:
\version "2.22.1"
\language "italiano"

common = {
    \key sol \minor
    \time 4/4
    \tempo "Largro [Широко]"
}

right = \relative do'' {
    \common
    <fa, sib re>2 <sol sib sol'>2 (
    <fa re' fa>4 <sol do mib>2.)
    <fad la re>2~ 8 r8 r4
}

left = \relative do' {
    \common
    <sib, sib'>2 <mib, mib'>2 (
    <sib sib'>4 <do do'>2.)
    <<
        {
            \tempo \markup {\smaller \normal-text "(poco rit.)"}
            re'4 r s2
        } \\
        {
            re,8 (la' re la' re2)
        }
    >>
}

pedal = {
    s2 \sustainOn s2 \sustainOff \sustainOn |
    s4 \sustainOff \sustainOn s2. \sustainOff \sustainOn |
    s8 \sustainOff
}

\score {
    \new PianoStaff <<
        \new Staff = "right" \right
        \new Staff = "left" { \clef bass \left }
        \new Dynamics \pedal
    >>
    \layout {
        \context {
            \Voice
            \consists "Melody_engraver"
            \override Stem #'neutral-direction = #'()
        }
    }
}

Comment: Would you consider it satisfactory to move the notes themselves to avoid the overlap?
Comment: Sure, a workaround will do. Still would be curious to know if LilyPond can do it automatically. How to move notes?
Comment: FYI: I've added an addition solution to my answer that I think will work even better for what you're trying to do — the X-offset property.
Comment: Aside:  do you mean "Largo" rather than "Largro" in the tempo marking?
Comment: This is a typo, obviously.
Answer: Solution #1: X-offset property
Modify the pedal block with \override SustainPedal.X-offset = 0.5.
For example:
pedal = {
    s2 \sustainOn s2 \sustainOff \sustainOn |
    s4 \sustainOff \sustainOn
    \override SustainPedal.X-offset = 0 { s2. \sustainOff \sustainOn } |
    s8 \sustainOff
}

yields

Solution #2: extra-spacing-width property
Modify the pedal block with \override SustainPedal.extra-spacing-width = #'(left-space . right-space).
For example:
pedal = {
    s2 \sustainOn s2 \sustainOff \sustainOn |
    \override SustainPedal.extra-spacing-width = #'(0 . 0) { s4 \sustainOff \sustainOn } s2. \sustainOff \sustainOn |
    s8 \sustainOff

yields

References
For more information, see the LilyPond manual. Specifically:

Grob Sizing (extra-spacing-width)
SustainPedal object (X-offset; extra-spacing-with)

The key detail comes from the "Grob Sizing" section.

By default, outside-staff objects are given a width of zero so that they may overlap in the horizontal direction.
Comment: Thank you! I think I can do one small correction to your code. After some experimenting, I realized that the left side number in `extra-spacing-width` is supposed to be negative. Setting it to `(5 . 5)` is equivalent to `(0 . 0)`.
Comment: Another interesting thing is that `extra-spacing-width = #'(0 . N)` and `\override SustainPedal.extra-spacing-width = #'(-N . 0)` produce the same result.


Add css file when editing specific content type

Question: I would like to add a css file when editing content of the content type invoice.
The link is something like this: node/121/edit . I've tried it with it with preprocess_node like this:
function themename_preprocess_node(&$variables) {
    $node = $variables['node'];
    if($node->type == 'invoice')
    {
        drupal_add_css(drupal_get_path('theme', 'themename') . "/css/add.css", array('weight' => 1003));
    }
}

But he doesn't add the css file. When I do a die; in the if structure he executes it...
Answer: You're targeting the incorrect preprocess function. By the time preprocess_node is run all our JS and CSS has been included in the top of our html document already.
Use this function instead:
template_preprocess_html
Comment: But I can't figure out which node type I'm editing with the preprocess_html function ..
Comment: I'm pretty sure this is wrong - templates work outside-in. `drupal_add_css()` in a node preprocess hook has always worked for me. Ironically, using `drupal_add_css` in `template_preprocess_html`, _definitely_ won't work.


NSDecimalNumber

Question: NSDecimalNumber is saved with lesser number of zeros, I enter in textfield $6000,00 for example, but in tableview appear $6,00
Please help me solve this issue
Below is my code:
<code>@property (strong, nonatomic) NSNumberFormatter *currencyFormatter;
@synthesize currencyFormatter;

- (void)viewDidLoad
{
    [super viewDidLoad];

    nameTextField.text = editGift.nameOfGift;

    currencyFormatter = [[NSNumberFormatter alloc]init];
    [currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    priceTextField.text = [currencyFormatter stringFromNumber:[editGift priceOfGift]];

}

- (IBAction)saveChanges:(id)sender {
    editGift.nameOfGift = nameTextField.text;

    [currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    NSDecimalNumber *priceAmount = [NSDecimalNumber decimalNumberWithString:priceTextField.text];
    editGift.priceOfGift = priceAmount;

    AppDelegate *myApp = (AppDelegate *) [[UIApplication sharedApplication]delegate];
    [myApp saveContext];
    [self.delegate editGiftViewControllerDidSave:self];
}
</code>
Display in tableView:
<code>NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc]init];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
cell.giftCostLabel.text = [currencyFormatter stringFromNumber:[gift priceOfGift]];
</code>
Comment: You already formatted the Number to Currency format So no need to convert that again in table view. Did you got a chance to Try my code ?
Comment: Add code - currency formatter and how you display the value.
Comment: Please can you check my code I added currency formatter and how i display value in my tableview. Thank you
Comment: Yes, I tried, but there are warnings: editGift.priceOfGift = [currencyFormatter stringFromNumber:priceAmount]; Incompatible pointer types assigning to 'NSDecimalNumber *' from 'NSString *'
Answer: Try this Code may be helpfull for you.
<code> - (IBAction)saveChanges:(id)sender {
        editGift.nameOfGift = nameTextField.text;

    NSDecimalNumber *priceAmount = [NSDecimalNumber decimalNumberWithString:priceTextField.text];

     editGift.priceOfGift =priceAmount;

        AppDelegate *myApp = (AppDelegate *) [[UIApplication sharedApplication]delegate];
        [myApp saveContext];
        [self.delegate editGiftViewControllerDidSave:self];
    }
</code>
in Tableview try This
<code> NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
    [currencyFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];

cell.giftCostLabel.text = [currencyFormatter stringFromNumber:editGift.priceOfGift];
</code>
Comment: You have to Check Whether the number is already in Currency Format or not (As per the Video ,When you enter normal number its working and if you enter number in Currency format its returning NAN ). So if The number is Already in Currency format then no need to format it again.
Comment: editGift.priceOfGift = [currencyFormatter stringFromNumber:priceAmount];  Incompatible pointer types assigning to 'NSDecimalNumber *' from 'NSString *'
Comment: Check my Updated Code (Just Removed Currency formatter while saving the data)
Comment: I tried your code, thank you but In the simulator tableview shows NaN,  on the device appear the number 60 instead of 6000. Very strange :(
Comment: Please can you watch video explanation http://www.youtube.com/watch?v=WGFEmZrIECc

NSDecimalNumber


Convergence of Pólya urns: what does it mean "expanding real polynomials in a basis"?

Question: I'm reading these notes, and in the proof of this Proposition 2, which states:

Let $d\ge 2$ and $S\ge 1$ be integers. Let also $(\alpha_1,\dots,\alpha_d)\in\mathbb{N}^d \setminus\{ 0 \}$. Let $(P_n)_{n\ge0}$ be the $d$-color Pólya urn random process having $S\cdot Id$ as replacement matrix and $(\alpha_1,\dots,\alpha_d)$ as initial composition. Then, almost surely and in any $L^t$, $t\ge 1$,
$$\frac{P_n}{nS}\to V\ \ \text{as}\ n\to\infty$$ where $V$ is a $d$-dimensional Dirichlet-distributed random vector, with parameters $(\frac{\alpha_1}S,\dots,\frac{\alpha_d}S)$.

I'm stuck near the end of the proof, when it says "Besides, expanding real polynomials $X^p=X_1^{p_1}\dots X_d^{p_d}$ in the basis $(\Gamma_p)_{p\in\mathbb{N}^d}$, one gets formulae $$X^p=S^{|p|}\Gamma_p+\displaystyle\sum_{{k\in\mathbb{N}^d}\atop {|k|\le |p|-1}}a_{p,k}\Gamma_k{X}\tag{1}$$ where the $a_{p,k}$ are rational numbers, $p=(p_1,\dots,p_d)\in\mathbb{N}^d$, $|p|=\sum_{k=1}^d p_k$, $S\ge 1$ is an integer and $\Gamma_p(v):=\prod_{k=1}^d\frac{\Gamma\big(\frac{v_k}S+p_k\big)}{\Gamma\big(\frac{v_k}{S}\big)}$ for $v=\sum_{k=1}^dv_ke_k$, where $(e_k)_{k\ge 1}$ denotes the canonical basis in $\mathbb{R}^d$.
Main question: So the main question here is, what does it mean expanding the polynomial in the basis $\Gamma_p$? I would like to do this explicitely, but I don't understand what I can do, what is this basis? I thought of computing $\Gamma_p(e_k)$ for $k=1,\dots,d$ but this does not lead me anywhere.
The results just before this statement are:

Consequently, after a direct induction, for any $p\in\mathbb{N}^d$, $$\mathbb{E}[\Gamma_p(P_n)]=\frac{\Gamma(\frac{\alpha}{S}+n+|p|)}{\Gamma(\frac{\alpha}{S}+n)}\cdot\frac{\Gamma(\frac{\alpha}{S})}{\Gamma(\frac{\alpha}{S}+|p|)}\cdot\Gamma_p(P_0)$$ so that, when $n$ tends to infinity, by Stirling's formula, $$\mathbb{E}[\Gamma_p(P_n)]=n^{|p|}\cdot\frac{\Gamma(\frac{\alpha}{S})}{\Gamma(\frac{\alpha}{S}+|p|)}\cdot\Gamma_p(P_0)\cdot \big(1+O\big(\frac1n\big)\big)$$

Second question: as a consequence of the previous question I should get (I don't know how since I don't understand firstly what is above)

Consequently, when $n$ tends to infinity, one gets the asymptotics $$\mathbb{E}\bigg(\frac{J_n}{\alpha+nS}\bigg)^p=\frac{\Gamma(\frac{\alpha}{S})}{\Gamma(\frac{\alpha}{S}+|p|)}\cdot\Gamma_p(P_0)\cdot \big(1+O\big(\frac1n\big)\big)\tag{2}$$

Here I suppose they use again Stirling's approximation and that they mean $\mathbb{E}\bigg[\bigg(\frac{J_n}{\alpha+nS}\bigg)^p\bigg]$ rather than $\mathbb{E}\bigg[\frac{J_n}{\alpha+nS}\bigg]^p$, and I don't know what is $J_n$ (In particular, it is showed that the martingale $\big(\frac{P_n}{\alpha+nS}\big)$ converges to a random variable $V$ a.s. and earlier in the notes, the only time they define $J_n$ is saying "$J_k(n)$ is the number of leaves at time $n$ of the $k$-th subtree." and further "is exactly distributed like the composition vector at time $(n−1)$ of an $(S+1)$-color Pólya urn process", so I guess they meant to write $P_n$ in this proof). Even if i find formula $(1)$, I don't undesrtand how to get $(2)$.
Answer: The second question from the first:
I also agree that $J_n$ should be $P_n$. Apply expectation to $P_n^p$, by using (1). Except for the first term, all other terms end up $O(n^{p-1})$. Then it becomes $O(1/n)$ after dividing $(\alpha + nS)^p$.
The first question:
Formula (1) on the right side, $X$ must be removed.
Note that for $X=(x_1,\ldots, x_d)$,
$$\Gamma_p(X)= \left(\frac{x_1}S \cdot (\frac{x_1}S+1) \cdots (\frac{x_1}S+p_1-1)\right) \cdots \left(\frac{x_d}S \cdot (\frac{x_d}S+1) \cdots (\frac{x_d}S+p_d-1)\right)$$
by repeatedly applying $\Gamma(s+1)=s\Gamma(s)$.
Thus, expanding the polynomial in the basis $\Gamma_p$ means writing monomials $X^p$ in terms of $\Gamma_p$ polynomials as above. This can be done through Stirling numbers of the second kind $S(p,k)$. It is enough to have for single variable $x$ and $p\in\mathbb{N}$,
$$
x^p=(-1)^p\sum_{k=0}^p S(p,k) (-1)^k x(x+1)\cdots (x+k-1).
$$
Putting $x/S$ in $x$, we have
$$
x^p=(-1)^pS^p\sum_{k=0}^p S(p,k) (-1)^k \frac xS (\frac xS+1) \cdots (\frac xS+k-1).
$$


Uniform LLN Assumptions, Weak vs. Strong

Question: A theorem from Jennrich (1969) is of a strong uniform law of large numbers,
Let $g_n$ be an iid sequence of random functions $\Theta \rightarrow R$ with $E[g_1(\theta)]=0$ for each $\theta \in \Theta$. Assume that $\Theta \subset R^k$ is compact, that $g_1$ is continuous almost everywhere, and that $E\left(\sup\limits_{\theta \in \Theta}|g_1(\theta)|\right) < \infty$. Then $\frac{1}{n}\sum_{i=1}^ng_i\rightarrow^{a.s.}0 $   uniformly over $\Theta$.
Wikipedia has assumptions for a weak uniform law of large numbers (as seen with the convergence in probability notation). To me, the assumptions on Wikipedia are equivalent to the assumptions made by Jenrich, but the conclusion is weaker.
My question is, what assumptions are needed for a strong uniform law of large numbers and how do those assumptions compare to those needed for a weak law?
Answer: Note that for any particular $\theta \in \Theta$ the sequence $g_i(\theta)$ form a sequence of iid random variables with mean $0$.
By the SLLN,
$$\frac1n \sum g_i(\theta) \xrightarrow{a.s.}0\;\;\forall \theta\in\Theta$$
This is the "pointwise" version. For uniform convergence to $0$ we need to show
\begin{equation}w.p. 1\;\; \forall \epsilon > 0\;\; \exists N_{\epsilon}>0: \sup_{\theta \in \Theta}\left|\frac1n \sum g_i(\theta)\right|<\epsilon\;\forall n>N_{\epsilon} \tag{1}\end{equation}
This is where the second piece helps us:
$$E\left(\sup_{\theta \in \Theta}\left|g_i(\theta)\right|\right) <\infty$$
Let $G_i =\sup_{\theta \in \Theta}\left|g_i(\theta)\right|$ then from $(1)$ the above, we know that $\frac1n \sum G_i \xrightarrow{a.s.} c < \infty$
This means that
$$w.p. 1\;\forall \epsilon>0\;\;\exists N_{\epsilon}: \left|\frac1n \sum G_i-c\right|<\epsilon\;\;\forall n>N_{\epsilon}$$
By definition
$$|g_i(\theta)| \leq G_i \implies \left|\frac1n \sum g_i(\theta)\right| \leq \frac1n\sum\left|g_i(\theta)\right| \leq \frac1n \sum G_i\;\;\forall \theta \in \Theta$$
By the dominated convergence theorem and the compactness and continuity of $g_i$ we know:
$$\lim_{n\to \infty} \sup_{\theta \in \Theta} \left|\frac1n \sum g_i(\theta)-0\right|=0$$
$$\implies \forall \epsilon>0\;\exists N_{\epsilon}:  \sup_{\theta \in \Theta} \left|\frac1n \sum g_i(\theta)\right| \leq \epsilon\;\;w.p. 1\;\square$$
As for your question of how we get to $a.s.$ -- the Wikipedia article starts with convergence in probability only. However, if we can make the case for $a.s.$ convergence, then we can move to $a.s.$ uniform here too.


Why there's a bijection between a set and its subset?

Question: I have in my notes the following: Let $A,B$ be two non empty sets, we know that $B\subseteq A$, therefore there's a bijective function between them.
Why there's a bijective function between them ?
Comment: For every set $B$ there is a set $A$ for which the statement doesn't hold; for instance $A = B \cup \mathcal{P}(B)$.
Comment: This is true and only if $B$ is infinite.
Comment: @GinKin It's an easy consequence of [Cantor's theorem](http://en.wikipedia.org/wiki/Cantor's_theorem).
Comment: @DustanLevenstein it had to do with two sets, one was all binary sequences and the other all natural numbers sequences. Both have the same cardinality so that's why it worked there, I just wanted to know if it's true for all sets.
Comment: @GitGud I think you meant $A$. alright, why is it true if the sets are infinite and why not when they're finite ?
Comment: I meant $B$. It's not necessarily true if $B$ is infinite,look at the comment above. How are you defining finite/infinite set?
Comment: @user133281 can you explain why it's false for this set ?
Comment: @GitGud this is from memory, if the set is uncountable then it's infinite, also if it's cardinality is $\aleph_0$ then it's infinite.
Comment: @GinKin To elaborate, $B$ can be of any cardinality; $A = B \cup \mathcal{P}(B)$ will be of greater cardinality, so the bijection can't exist.
Comment: @GinKin The assertion in your comment above is true.
Comment: To do your question justice, we would need more context. Of course, if you've figured out what the notes mean with the help of the comments so far, then that's good, but if not, we don't really have much information to go on as it is.
Answer: I'm going to compile the discussion in the comments into a short answer.
In general, the result is false because $A$ might be of a different cardinality than $B$. (Or, more simply, they might both be finite and of different orders. Let $B = \{1\}, A = \{1,2\}$.)
In the particular case where $B$ and $A$ are both infinite and have the same cardinality (example: $B$ is the natural numbers and $A$ is the integers) then this is true. In fact, infinite sets can be defined as being those sets which are in bijection with at least one of their proper subsets. Note that no finite set has this property; all of the examples look like our counterexample in the second paragraph.


How do I make a django form more aligned

Question: I have a form to edit my Wikipedia entry but since its a django form I am having difficulty designing it

This is the code for the form
<code>class EditForm(forms.Form):
    title = forms.CharField(label="Edit Title")
    body = forms.CharField(label="Edit Body", widget=forms.Textarea(
        attrs={'rows': 1, 'cols': 10}))
</code>
Any help would be appreciated, Thanks in advance!
Answer: You can try using Django Crispy Forms, read the documentation on this page


Let $T:l_\infty \rightarrow l_\infty$ a linear operator defined by $T((x_1,x_2,\ldots ))=(x_1,x_2-x_1,x_3-x_2,\ldots )$

Question: If $R=T(l_\infty)$ and $y=(1,1,1,\ldots )$
Compute $d(y,R)$.
Well, I guess that the distance could it be 1. So I found a upper bound for this.
$d(y,R)=\inf_{x\in R} \|x-y\|\leq \|y\|=1$ because $0\in R$
But the other inequality (the essential)
$\|x-y\|\geq \left|\|x\|-\|y\|| \right|=\left|\|x\|-1 \right|$
I tried but I can´t find it
Comment: Also, don't get discouraged by the downvote. I downvoted the question and voted to close it because at the moment, it is not up to site standards (you have shown no work you did on your own). If you edit your question so that you show what you tried and how far you got, I will not only remove the downvote, I will add an upvote.
Comment: Hi and welcome to the site! Since this is a site that encourages and helps with learning, it is best if you show your own ideas and efforts in solving the question. Can you edit your question to add your thoughts and ideas about it?
Answer: Suppose that $\|y-Tx\|<\delta<1$. Then $x_1=1+\delta_1$, and
$$
x_k=x_{k-1}+\delta_k,\ \ \ ,\ |\delta_k|<\delta,\ \  k>1.
$$
Working inductively, we get that
$$
x_k=k+\delta_1+\cdots+\delta_k.
$$
So
$$
|x_k|\geq k-k\delta=(1-\delta)k.
$$
Thus $x$ cannot be bounded.


How to bundle a ruby package into an [Objective-C] cocoa application?

Question: I'm trying to figure out how I could bundle a package, written in Ruby (Sass) into a Cocoa application (Objective-C, not Ruby Cocoa) for me to execute (via NSTask is fine, unless there is an easy way to bridge ObjC<->Cocoa that I'm not aware of).
The Sass package is something you have to install, using "gem install" or "rake install" -- doing so puts a ton of files in my ~/.gem directory.  Since I want anybody who has installed my Cocoa-based application to be able to execute this tool from within my app, I don't want to have the user go through a process of installing anything additional, so I'm hoping to be able to embed everything I need in the Resources directory of my app package.
However, not being that familiar with the internals and structure of Ruby (Sorry, I'm having trouble just keeping ObjC/Cocoa in my head!), It's not clear to me just which of the 1,444 files that got installed in the ~/.gem directory (Yes, I counted) I need to embed in the application and what I might need to do to get the directory references, etc. working right.
If anybody has any experience with embedding a ruby tool into a Cocoa application, I would really appreciate your input.  I wasn't expecting this to be so hard, considering that ruby is installed on Mac OS X ... but apparently this package is (typically? atypically?) more than just a single script file....
Answer: You can install gems into a specific location:
GEM_HOME=path/to/your/project/gems gem install sass

Then, as part of your build process, copy the folder into your resources. When you want to run sass, find your gem folder. Call ruby like so:
NSString *gems_path = …;
NSTask *task = [[NSTask alloc] init];
// you may want to copy NSProcessInfo.processInfo.environment and modify it instead
task.environment = @{ @"GEM_HOME": gems_path };
task.launchPath = @"/usr/bin/ruby";
task.arguments = @[[gems_path stringByAppendingPaths:@[@"bin",@"sass"]], @"rest", @"of", @"your", @"arguments"];
// add handling for I/O
[task launch];

(Typed into github, may have silly mistakes)
Note that you may want to bundle ruby as well (perhaps macruby), to prevent compatibility issues. If not, ensure that you test all versions of OS X that you support, especially 10.9, as ruby was upgrade to 2.0.
Answer: Major thanks to @Jacob Lukas, I found that simply setting GEM_HOME on gem install <gem> didn't correctly attach the dependencies.  So, for my case--where I just need to run a script I'm generating in an Xcode plugin--I ended up with:
gem install -i ~/xCodeProjects/PluginOne/gems xcodeproj --verbose
to get the gem(s) & dependencies.  Then, I used:
NSString *gems_path = [[bundle resourcePath] stringByAppendingString:@"/gems"];

NSTask *task = [[NSTask alloc] init];
task.environment = @{ @"GEM_HOME" : gems_path };
task.launchPath = @"/System/Library/Frameworks/Ruby.framework/Versions/Current/usr/bin/ruby";
task.arguments = @[generatedRubyFilePath];

[task launch];

Answer: I had trouble doing something similar with Ruby gems so I'll share what worked for me in the hopes that it helps someone in the future.
Step 1: Install the Gems
Start by installing the gems you want to use into a folder you can easily locate, such as a gems folder inside your project folder. As Stan showed in his answer, use the -i option and supply the path to the gems folder when installing the gem.
gem install -i /path/to/gem/folder gemName

Step 2: Add a Copy Files build phase
Add a Copy Files build phase to your app target by choosing Editor > Add Build Phase > Add Copy Files Build Phase. Use the Resources menu to choose a place to copy the gems in the app bundle. If you want the gems in their own folder, add the folder name in the Subpath text field.
Click the Add button to add the files. A sheet opens. Click the Add Other button. Navigate to your gem folder location and select your gem folder.
Now when you build the project, Xcode will copy the gems into the app bundle.
Step 3: Locate the gems folder in the app bundle
Use the Bundle class to find standard locations in the bundle, such as the Resources folder. Build a path to the gems folder. You will need it as an environment variable when running the gem.
The folder containing the gems should have a bin folder containing the executable files. You would build a path to the executable file and use that path as the first argument when running the gem.
Step 4: Configure the command to run the gem
Use the Process class, formerly NSTask, to run a command-line program, such as a gem. Start by creating a Process object.
let taskToRun = Process()

Set the launch path to the path of the Ruby interpreter.
taskToRun.launchPath = "/usr/bin/ruby"

Set the environment variable GEM_HOME to the path of your gems folder.
taskToRun.environment = ["GEM_HOME" : gemsPath]

Set the arguments property with a list of arguments. The first argument should be the path to the gem's executable file.
let argumentList = [gemExecutablePath, inputURL.path, "-o", outputURL.path]
taskToRun.arguments = argumentList

The actual list of arguments depends on the gem you're using.
Step 5: Run the gem
On macOS 10.13 and later, call the run function to run the gem.
do {
    try taskToRun.run()
} catch {
    fatalError("Error running command line tool.")
}

On earlier versions of macOS, call the function launch to run the gem.
taskToRun.launch()

You can find more detailed information in the following article:
Using a Ruby Gem in a Mac App


How can I display the results of webform submission in a block and place it on front page?

Question: So I'm using the Webform module to collect data, and I want to display the results in a Drupal block and place it in an appropriate theme region in my site.
Like for example the following: I want to display the analysis with the charts  of my result (created with the Charts module) in the front page of my site.
Is that doable?
Comment: Yes I'm using Charts with (s) .
I want to take those charts and place them in a block
Comment: Any feedback about my answer?
Answer: There are 2 possible approaches to consider, as further explained below ...
Approach 1: using the Charts modules
This is like rolling your own cookies. You create your chart (as you already seem to have done in the image above), using either the "Charts API" (= write some PHP code to populate the charts Array, whereas you put that PHP code in the content of your block) or using the "Views integration of the Charts module" (where you format the Views result as a block).
Disclosure: I'm a (co-)maintainer of the Charts module,
I hope this does not violate the site's policy on self-promotion.
Approach 2: using the typical Webform related charting modules
If you want to create charts from the survey results of the Webform module, there are 2 typical/popular alternatives to pick from:

Webform Charts (used in about 350 sites), to display Webform results in a graphical manner using a charting library.
Webform Chart (used in about 575 sites), which integrates with the "Analysis" tab of a Webform (created with the Webform module) to provide charts for each individual component's analytical data.

The Drupal 7 version of both modules, requires the Charts module (dependency).
Note:
In both approaches you need to decide about which "Charting Library" (= engine) you want to use, either Google charts (easiest setup) or Highcharts (which might require a license also). At any time it should be pretty easy to swap between either library also (that is a key feature of the Charts module also ...).
Comment: Update for the Webform related charting models: [Webform Charts](https://www.drupal.org/project/webform_charts) (used in about 320 sites) and [Webform Chart](https://www.drupal.org/project/webform_chart) (used in about 500 sites). Thanks for the answer.
Comment: @herci : merci (oeps: thank you) for the stats update (I corrected my answer with them just now).


Delete only non max records of a group

Question: I am trying to do something like the following
delete PreOrder
where preorderid not in (
select preorderid
from PreOrder p1
inner join (select max(OrderDt) OrderDt, preorderid
from preorder group by preorderid) p2 on
p1.preorderid=p2.preorderid
where p1.preorder in (1,2,3,4,5)

I am just try to delete the record if there are dupes of just those. I got the max working, but how to delete just from those records that has that preorderid
Comment: What database are you using.  Please tag the question correctly.
Answer: Delete p1
from PreOrder p1
left join (select max(OrderDt) OrderDt, preorderid
from preorder group by preorderid) p2 on
p1.preorderid=p2.preorderid
and p1.OrderDt = p2.OrderDt
where p2.preorderid is null and p1.preorderid in (1,2,3,4,5)

Delete only non max records of a group


Behat and custom login pages

Question: I'm trying to use Behat and Drupal for BDD, but I'm running into some authentication issues. Simple steps like:
Given I am logged in as a user with the "administrator" role

Fail because I'm using Drupal's CAS module, which essentially customizing the /user/login page. Any idea on how I can get past custom login pages with Behat?
Answer: You can test login form in this way:
When I visit 'user/login'
And I fill in "username" for "name"
And I fill in "userpass" for "pass"
And I press the "Log in" button
Then I should see the text "some text"

Answer: I was able to figure it out. You have to make sure the "Make CAS login default on login forms" option in the CAS settings is not checked and don't have "user" page under the "Specific pages" redirect. I still need to figure out how to disable these options through Behat, instead of manually, then my tests will truly be automated. I will post a reply once I figure it out.

Behat and custom login pages


cannot update Drupal core with drush

Question: Why can't Drush find the Drupal core module?
root@hostname:/var/www/html/sites/example.org# drush pm-update core

...
Wysiwyg (wysiwyg)                        7.x-2.2         7.x-2.2         Up to date
core                                     Unknown         Unknown         Specified project not found

So then I tried:
root@hostname:/var/www/html/sites/example.org# drush -r /var/www/html -l example.org pm-update core
...
Wysiwyg (wysiwyg)                        7.x-2.2         7.x-2.2         Up to date
core                                     Unknown         Unknown         Specified project not found

I have used both these commands in the past to update other Drupal modules and it has always worked, until I have to update the Drupal core module.  Can Drush not handle this or is this a bug?
Answer: To update core on its own try
drush pm-update drupal

A plain
drush pm-update

will update all modules, and then core.
Note that it doesn't backup .htaccess, robots.txt, or any other files that you may have modified.  I have gotten in the habit of doing a full drush archive-dump before core updates, and/or using Backup and Migrate in combination with having everything under git control.
Comment: This worked!  Strange since the list of modules from drush does not list 'drupal' itself as a module.   Good to know!
Answer: I installed drush 9.x
Now when I drush up I get:
 The pm-updatecode command was deprecated. Please see composer outdated and composer update. For security release notification, see drush pm:security.

cannot update Drupal core with drush


How to calculate rank from multiple parameters to get best/trustworthy peer

Question: How to calculate rank from multiple parameters ?
Parameters are bandwidth, delay, success ratio, these parameters values are used to determine the trustworthiness of a peer while accessing a service from a peer?.  My aim is to get the best peer, by using any ranking method ... which method can I use?
Comment: You're looking for parameter ranking. This has been answered before. Have a look at here: [Link](https://datascience.stackexchange.com/a/11985/17937)
Answer: Do you have data with rankings? If yes, you can build a linear regression model that predicts the score/rank given the 4 features. The feature weights will be learned from the training set. A positive weight will suggest that the feature adds positively to the rank (e.g bandwidth); a negative weight will suggest that increasing feature value will decrease the rank (e.g. delay).
You can use LIBSVM to fit a linear regression model or any other package for this task.


Routinely unable to remove qla2xxx module under CentOS

Question: I routinely cannot unload the Qlogic fibre module qla2xxx under CentOS 5 or 6.  These machines are running StorNext cvfs, EMC powerpath and hostagent.  Nothing else should ever be touching the fibre.  All three of these processes have been stopped before trying to remove the module.  The interesting thing of the output below is the lsmod: qla2xxx is being used by 45 things but none are listed.  There are no "fibre-ish" processes visible (that I can tell) after running sudo ps ax.  I have not tried a "force (-f)" removal Force removal (-f) does not help the situation.
# service cvfs status
Active SNFS mountpoints:
Error: fsmpm not running!

# service PowerPath stop
Stopping PowerPath: PowerPath is not running done

# service hostagent status
hostagent is stopped

# modprobe -v -r qla2xxx
FATAL: Module qla2xxx is in use.

# rmmod -v qla2xxx
ERROR: Module qla2xxx is in use

# lsmod | grep qla
qla2xxx               366555  45
scsi_transport_fc      52241  1 qla2xxx

# modprobe --show-depends qla2xxx
insmod /lib/modules/2.6.32-220.7.1.el6.x86_64/kernel/drivers/scsi/scsi_tgt.ko
insmod /lib/modules/2.6.32-220.7.1.el6.x86_64/kernel/drivers/scsi/scsi_transport_fc.ko
insmod /lib/modules/2.6.32-220.7.1.el6.x86_64/kernel/drivers/scsi/qla2xxx/qla2xxx.ko ql2xfailover=0

# modprobe -r -v scsi_transport_fc
FATAL: Module scsi_transport_fc is in use.

# modprobe --show-depends scsi_transport_fc
insmod /lib/modules/2.6.32-220.7.1.el6.x86_64/kernel/drivers/scsi/scsi_tgt.ko
insmod /lib/modules/2.6.32-220.7.1.el6.x86_64/kernel/drivers/scsi/scsi_transport_fc.ko

# lsmod | grep scsi_
scsi_transport_fc      52241  1 qla2xxx
scsi_tgt               12173  1 scsi_transport_f

# modprobe -r -v scsi_tgt
FATAL: Module scsi_tgt is in use.

# modprobe --show-depends scsi_tgt
insmod /lib/modules/2.6.32-220.7.1.el6.x86_64/kernel/drivers/scsi/scsi_tgt.ko

Update: There is a kernel thread persisting for each HBA on the host, which should be killed when I attempt to remove the module.
# ps ax | grep qla
  551 ?        S<     0:00 [qla2xxx_0_dpc]
  557 ?        S<     0:00 [qla2xxx_1_dpc]
  563 ?        S<     0:00 [qla2xxx_2_dpc]
  569 ?        S<     0:00 [qla2xxx_3_dpc]

Answer: The problem you are facing can be a bug. See:
http://www.spinics.net/lists/linux-scsi/msg52025.html
Comment: Could be a bug, but not this one.  The link is a patch for a hang during driver unload.  In this case, the module won't begin the unload because it is in use.
Comment: This bug is about ref count not being handled correctly. You reported ref count = 45 which does not looks normal.
Answer: Have you tried to remove all in a single operation ?
modprobe -r -f -v scsi_tgt scsi_transport_fc qla2xxx

I am not sure my alternate proposal matches your needs: adding the following line to /etc/modprobe.conf
alias qla2xxx off

will prevent the module auto-loading at boot time and so your dependency-lock situation but it requires to reboot...
Comment: Combining all modules into a single operation does not work.

Preventing the module from loading at boot doesn't fit my goals. I would like the module to load at boot so I can mount my SAN file systems at boot, but I'd like to be able to perform fibre maintenance without having to reboot and kick off all users.
Comment: So I have guessed well...
Answer: Try:
service multipathd stop
multipath -F
modprobe -r -f -v scsi_tgt scsi_transport_fc qla2xxx


Confusion with SHA-1 in Firebase

Question: I want to know what SHA-1 I need to write in this window:

Is it the one that I see on the signinReport inside Android Studio, as shown here:

Or, this is the SHA-1 I need to generate according to this tutorial:
Authenticating Your Client

Or they are the same one?
Also, when I try to follow their tutorial, via command line, I just, can't get it to work, what am I doing wrong:

Totally confused, would love to get clarification
Comment: This is is true signinReport inside Android Studio.
Answer: You can use sha1 key given in studio like below image

Or You can find using command also like below (Open CMD and hit below commands)

For Debug mode:
keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

for Release mode:
keytool -list -v -keystore {keystore_name} -alias {alias_name}

example:
keytool -list -v -keystore C:\Users\MG\Desktop\test.jks -alias test

Comment: So the cmd is a way to FIND the existing Android Studio key?  Another thing: Where do I run this command? because when I copy-paste your code in the Java bin folder, I get `keytool error: java.lang.Exception: Keystore file does not exist`
Comment: @TTnote, you need to run above command on command prompt, no need to go in java folder. Just open cmd and run above command

Confusion with SHA-1 in Firebase