XNA breakout game new level (cant design new patterns of brick)

Question: Been having a problem with my breakout game. I have designed a single level and created a basic set of blocks. But I have no idea how to set up new patterns of blocks.
Here is a section of the code within loadcontent:
<code>background = new Background(Content.Load<Texture2D>("prisonCell"));
            paddle = new Paddle(Content.Load<Texture2D>("bat"), screenBounds);
            ball = new Ball(Content.Load<Texture2D>("baseball"), screenBounds);
            brickTexture = Content.Load<Texture2D>("brick");
            menuScreen = Content.Load<Texture2D>("menuScreen");
            gameOverScreen = Content.Load<Texture2D>("gameOver");
            gill14 = Content.Load<SpriteFont>("Gill14");

            BuildWall();

            startGame();
        }

        public void BuildWall()
        {
            bricks = new Brick[brickRows * brickColumns];
            Color brickColour = Color.White;

            int brickCount = 0;

            int paddingTopViewport = brickTexture.Height/* * 3*/;

            for (int row = 0; row < brickRows; row++)
            {
                switch (row)
                {
                    case 0:
                        brickColour = Color.Red;
                        brickValue = 5;
                        break;
                    case 1:
                        brickColour = Color.Orange;
                        brickValue = 4;
                        break;
                    case 2:
                        brickColour = Color.Gold;
                        brickValue = 3;
                        break;
                    case 3:
                        brickColour = Color.Yellow;
                        brickValue = 2;
                        break;
                    case 4:
                        brickColour = Color.Green;
                        brickValue = 1;
                        break;
                    case 5:
                        brickColour = Color.Blue;
                        brickValue = 1;
                        break;

                }

                brickValue = 1;

                for (int column = 0; column < brickColumns; column++)
                {
                    bricks[brickCount] = new Brick(brickTexture,
                    new Rectangle(column * brickTexture.Width,
                    paddingTopViewport + row * brickTexture.Height,
                    brickTexture.Width, brickTexture.Height),
                    brickColour, brickValue);

                    brickCount++;
                }
            }
        }

        private void startGame()
        {
            paddle.SetStartPaddlePosition();

            ball.SetStartBallPosition(paddle.Bounds);
            foreach (Brick brick in bricks)
                brick.IsActive = true;
        }
</code>
Answer: If you want to make designing the level easy, define the layout in a text file with the correct number of columns.  Use a fixed space font and use a different character for each colour/texture you want to support.
Then you can read in the text file and construct the wall.  It makes tweaking a lot easier than trying to code different wall designs.


Confusion regarding random walk model

Question: I was referring to this book where it is given that
If we assume equally spaced nodes $i$ for $i=1,...,n$.
The first order random walk is constructed using independent increments
$$
\Delta{x_i} \sim N(0,k^{-1}), \ \ \ \ \ \ i=1,...,n-1
$$
The density for $${\bf{x}}=(x_1,x_2...x_n)'$$ is derived from the $n-1$ increments
as
$$
\pi({\bf{x}}|k) = k^{(n-1)/2} \cdot \exp \left(-k/2 \cdot \sum_{i=1}^{n-1}\Delta{(x_i)^2}\right)
$$
I didn't get how the density of $x$ was represented in the form of increments. I mean how we can use increments to show the density how are they related or can be used in the density of $x$.
Comment: What are $x$ and $\mathbf{x}$ and how are they related to $\Delta x_i$?  It's natural to suppose that $x=\Delta x_1 + \Delta x_2 + \cdots + \Delta x_{n-1}$, but would $\mathbf{x}$ then be the *vector* $(\Delta x_1, \ldots, \Delta x_{n-1})$? These distinctions are important; they can explain what the derived density is trying to show and how to justify it.
Comment: I have updated what x is. I just don't understand how density of x is given by the increments where xvector=(x1,x2...xn)'. I have also updated what x is. Actually, I got the above derivation from a book called Gaussian Markov Random Field Theory and Applications by Rue and Held. As you said for the above derivation to justify xvector should be equal to (deltax{1},...deltax{n-1}) but I don't think it is the case since xvector=(x1,...xn)
Answer: Let's take this in short steps.
"$\Delta{x_i} \sim N(0,k^{-1})$" means that (up to a constant of proportionality which we can worry about at the end) the distribution function (PDF) of $\Delta{x_i}$ equals $k^{1/2}\exp{(-(k/2)\Delta{x_i}^2)}$.  This is (one) definition of what it means to have a normal distribution with mean $0$ and variance $1/k$.
"Independent" implies the joint ($n-1$-variate) distribution function of all the $\Delta{x_i} = x_{i+1}-x_{i}$ is the product of the individual distribution functions. Exploit a basic property of the exponential (products of its values correspond to sums of its arguments) to write this joint density as
$$k^{1/2}\exp{(-(k/2)\Delta{x_1}^2)}\cdots k^{1/2}\exp{(-(k/2)\Delta{x_{n-1}}^2)}=k^{(n-1)/2}\exp{\left(-k/2(\Delta{x_1}^2+\cdots+\Delta{x_{n-1}}^2)\right)},$$
once more ignoring the constant.
Finally, because each $x_i$ is obtained by starting with $x_1$ and adding all previous increments,
$$x_i = x_1 + \Delta{x_1} + \Delta{x_2}  + \cdots + \Delta{x_{i-1}},$$
we can rewrite the preceding sum of squares $\Delta{x_1}^2+\cdots+\Delta{x_{n-1}}^2$ in terms of the $x_i$ to get $x_1^2+2(x_2^2 + \cdots + x_{n-1}^2)+x_n^2 - 2(x_1x_2 + x_2x_3 + \cdots + x_{n-1}x_n)$.  Plug this into the preceding formula to obtain the joint distribution of the $x_i$.
One usually doesn't care much about the details of this resulting (somewhat messy) expression; its form is what matters.  Apart from constant multipliers, which will be determined by the integrate-to-unity criterion satisfied by any probability distribution, it is the exponential of a quadratic form $Q$.  This means the $x_i$ have a multivariate normal distribution.  You can read off their variances and covariances by inverting $Q$.
Comment: That, plus a trivial Jacobian.
Answer: Since each $Δx_i \sim N(0,1/k)$ (assuming $1/k$ is the standard deviation) then the walk travels $x$ equal to the sum of the $n-1$ independent increments and has a normal distribution $N(0,\sqrt{(n-1)}/k)$  because the variance is the sum of the variances of the individual variances and there are $n-1$ each with variance $1/k^2$.  Now $x=∑Δx_i$.  So the formula should represent that density.  It is not quite written correctly the way you have it.  It should be $$\frac{1}{\sqrt{2π(n-1)}/k} \exp \left(-\frac{(∑Δx_i -0)^2}{2(n-1)/k^2}\right) $$
Comment: I didn't get how come x=sum(del_xi). If I have four locations x1,x2,x3,x4,  sum(del_xi) = x4-x1. But the density of x should be something like density(x1,x2,x3,x4)  or density(xvector) isn't it?
Comment: @user34790 Δxi= xi-xi-1 They are the independent increments and they are summed to get the total walk.
Comment: yeah but the density of x. x is a vector (x1,x2..xn). So how come its density is equal to density of the sum of the increments. I just didn't get this part
Comment: I wrote down the density of xt. So maybe that explains why mine looked different. But each xi can be represented as the some of some of the Δxi. So each xi can be represented as sums of the Δxis and so then the joint density can too. Apparently k is the variance in the formula and power of 2π is missing.

Confusion regarding random walk model


Fast URL encrypt in javascript, decrypt in php

Question: I have a url with several parameters is use for a http request. It looks like this:
http://www.url.com/site.php?parameter1=x&parameter2=y

I would like to make sth like this in javascript:
http://www.url.com/data=wafseghsgse or http://www.url.com/site/?data=wafseghsgse

And in php I would get the "old" url back to work with it.
I am looking for the fastest way to do this, not the most secure one. To save a key for encryption I would use the database or maybe session (safe?).
Looking for your great ideas.
Comment: You are looking to build a URL shortener. There is plenty of information about how to build one out there. Related: [URL Shortening Site](http://stackoverflow.com/q/1383145) and [URL shortener: best encoding method?](http://stackoverflow.com/q/2375968)
Comment: @quentin because i do not like the user to see the parameter sent maybe user_id etc.
Comment: Will you send the key to the browser for encryption?
Comment: @Salman. No i would get it from db or store it in session. Last one i do not have any clue if it is save or not.
Comment: Encrypting something using javascript on the clients browser will not make you application secure.
Comment: @RuvenJR.Maerson — If you are encrypting the data with client side JavaScript, then the unencrypted version *must* be available to the client, so the user can see it. Attempting to keep these things secret is fruitless and adds unnecessary complexity that can add bugs.
Answer: If you just want a fast obfuscate method with no care about security, you can use ROT13, you have javascript ROT13 implementations in Where is my one-line implementation of rot13 in JavaScript going wrong? and then in PHP you have str_rot13() to decrypt the javascript version.
Comment: yes this is sth. i could use. I will give it a try. In addition to SSL this is a good solution i think.


404 ERROR when I try to GET data from google spreadsheet

Question: Hy everyone, I don't know if exit someone who can help me.
I don't know how it is possible, few days ago all ok now it stop to work.
Basically I read data in a html table on a website from a google spreadsheet public on website and public to everyone with the link. Using ajax.
Until now it worked, i saw all the datas and voices presents on my sheet in google drive, now it stop to show the datas and return an anonymous error like if the link to my google spreadsheet is inexistent, but it is here!!
For example on this googlesheet: https://docs.google.com/spreadsheets/d/13KmAf2uc13fWxPvn8dtk9j9kOL3nCVqi8H-wYau6Tww/edit?usp=sharing
I Have a series of data to display on my html website. Until few days ago it worked, now no.
I used jquery google : src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
I public my code below:

and adapt with your own style
Comment: Do you know why on web with android work and ios no?
Comment: XMLHttpRequest doesn't work on Safari, but you can now replace it by Chrome if needed (iso14). Or change the method I used to fectch data by asynchronous method.
Comment: Sorry do you have a link where i can study this method? I really need to use the code also on ios browser, also on Chrome or firefox  dosn't work if i open the website with iphone an that browser do you can help me?
I thought was a ajax problem in a first moment but now... i don't know really well the asynchronus method for do this.
Comment: ok i will work on it, be patient (the purpose of my answer was mainly to give you the new url to use instead of feed method which is now deprecated). Does ajax/libs/jQuery you mentionned in your request works on Safari/iOS ?
Comment: in past yes, i ever used the jquery that i mentioned. your url work and i am really happy for that, is more than the all thing i done for fix the code in many many days, but  if i try to upload the code on web... with a computer o an android phone work, with any other browser on iphone no.
We can work about togheter if you want.

In past this libs worked https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js
And now i think is always ok for our scope, it worked in past on safari and iOS
Comment: You probably need to post a new query on stackoverflow focused on ajax / jquery / ios as it seems like there is a problem for a lot of developers  https://www.google.com/search?q=ajax+ios+problem , you will then have a faster response from the community. I will try to work on it in parallel but I have no experience on ios.
Comment: Test the other answer with iOs
Comment: for the moment dons't work, i really don't understand why, i am studing about but is really complicated. Thank you for help, i can offer you a bear or something to drink via paypal, because you are really friendly.

I continue to search a solution i don't know why before it working and now no.... i am really sad
Answer: Another solution without ajax and jQuery, using fetch https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

List ...

https://codepen.io/mikesteelson/pen/YzQKere
For iOS compatibilty, use instead

List ...

Comment: the console for iphone say: irregular expression i think is the ===  data.match(/(?=?table":).*(?=}\);)/g)[0]  thath dosn't work with ios devices
Comment: maybe i have to use the jquery?
Comment: hum, try with only `.then(data => document.getElementById("Vinorosato").innerHTML=data` to be sure that match is the cause. Quite sure that fetch() doesn't work in iOs instead.
Comment: with only:  .then(data => document.getElementById("Vinorosato").innerHTML=data

Show some frases :

google.visualization.Query.setResponse({"version":"0.6","reqId":"0","status":"ok","sig":"1939066001","table":{"cols":[{"id":"A","label":"","type":"string"},{"id":"B","label":"","type":"string"},{"id":"C","label":"","type":"number","pattern":"\u0022\u20AC\u0022#,##0"}],"rows":[{"c":[{"v":"Antipasto misto di mare "},{"v":"frutti di mare"}....

I think is the match the cause, because also on iphone i read this frases with the datas
Comment: Yes for me the format of data.match is the problem, because with an iphone i can read the codes above, with  any browser which is on an iphone i can see this data. So my question is: is there another way to print the data? without ` /(?=?table":).*(?=});)/g)`
Comment: Try `__________.innerHTML=myItems(data.substring(117).slice(0, -3))` , if notOK, remove myItems and give me the exact response
Comment: ITS WORKINGGGGG! you are AMAZING ! please give me your email, my is:

firstname.lastname@example.com i want offer you a drink for all what you have done!! Via paypal
Comment: Thx a lot Vitiello, and good news for iOs and Google Sheets ... I will appreciate just a virtual coffee, thx very much. Offer it to a disabled person that you know on my own behalf !


Emails from Form coming in empty?

Question: Wondering if anyone out there could help me spot the flaw in my form setup? Emails are coming through, but with none of the information entered by the message sender:

Email Body:
Name:
Email:
Existing Customer:
Org Type:
Message:

Here is the HTML:
<form action="email.php" method="POST" name="contact" enctype="text/plain">

            Name: <input type="text" name="name" id="name">
            Email: <input type="text" name="email" id="email">

            Have you written before?
            <input type="radio" name="existing" value="Yes" id="existingyes">Yes
            <input type="radio" name="existing" value="No" id="existingno">No

            How do you classify yourself? <select id="orgtype">
                <option>Charity</option>
                <option>Business</option>
                <option>Individual</option>
                <option>Meat Popcicle</option>
                <option>Other</option>
            </select>

            Thoughts? Questions? Comments

            <textarea name="essay" rows="3" cols="70" id="essay">...</textarea>

            <input type="submit" value="Yell At Us!">

And here is the PHP:
    <?php
  $name    = stripslashes($_POST['name']);
  $email   = stripslashes($_POST['email']);
  $existing   = stripslashes($_POST['existing']);
  $orgtype = stripslashes($_POST['orgtype']);
  $essay = stripslashes($_POST['essay']);
  $form_message = "Name: $name \nEmail: $email \nExisting Customer: $existing \nOrg Type: $orgtype \nMessage: $essay";
  $success = mail("email@example.com", "Online Form Submission", $form_message, "From: $email" );
  if ($success){
  print "<meta http-equiv=\"refresh\" content=\"0;URL=index.html\">";

    } else {

echo "Sorry error please try again...";

}

?>

Any help would be greatly appreciated!
Answer: remove the enctype="text/plain" from you're form tag.
<form action="email.php" method="POST" name="contact">
You can read about it here
method="post" enctype="text/plain" are not compatible?

Emails from Form coming in empty?


Every Cauchy sequence has a subsequence with the property $d(y_{p+1}, y_{q+1})\le d(y_p, y_q)/2$

Question: Let $(X,d)$ be a metric space and let $(x_n)_{n\in\mathbb{N}}$ be an infinite Cauchy sequence on $X$. Then there exists a subsequence $(x_{n_k})_{k\in\mathbb{N}}:=(y_k)_{k\in\mathbb{N}}$ such that
$$ d(y_{p+1},y_{q+1})\leq \frac{d(y_p,y_q)}{2}$$
for all $p,q\in\mathbb{N}$.
My question: how to extract such a subsequence?
Context: this answer on MO.
Answer: Let $Tx_p = \{x_k : k>p\}$ be the "tail" of $(x_k)$, and similarly for $Ty_p$. It suffices to construct $(y_k)$ such that
$$
\operatorname{diam} Ty_p\le \frac12\operatorname{dist}(y_p, Ty_p)\quad \forall \ p
\tag1$$
Indeed, if (1) holds then, taking WLOG $p<q$, we get
$$
d(y_{p+1},y_{q+1})\leq \operatorname{diam} Ty_p\le \frac12\operatorname{dist}(y_p, Ty_p) \le \frac12 {d(y_p,y_q)}
$$
as desired.
If the sequence $(x_n)$ is eventually constant, then we can make $(y_k)$ a constant sequence, which trivially satisfies (2).
Let $x = \lim x_n$ (if it exists; otherwise ignore the clauses involving $x$). Passing to a subsequence, we may assume $x_n\ne x$ for all $n$.
Let $y_1=x_1$. Suppose $y_1,\dots, y_k$ are chosen. Observe that:

$\operatorname{dist}(y_k, Tx_m)$ is nondecreasing with $m$, and is not always zero — otherwise $y_k$ would be equal to $x$.
$\operatorname{diam} Tx_m$ is nonincreasing and tends to zero, because $(x_n)$ is Cauchy.

So, there exists $m$ such that $\operatorname{diam} Tx_m  \le \frac12 \operatorname{dist}(y_k, Tx_m)$. Let $y_{k+1}=x_{m+1}$; then
$Ty_k\subset Tx_m$, which implies
$$\operatorname{diam} Ty_k \le \operatorname{diam} Tx_m  \le \frac12 \operatorname{dist}(y_k, Tx_m) \le \operatorname{dist}(y_k, Ty_k)$$
as desired.

The argument could be simplified by passing to the completion of $X$, where we have $x_n\to x$. Then all we need to do is pick a subsequence $y_{k}$ such that
$$
0<d(y_{k+1} , x) \le \frac16 d(y_k, x)
$$
since then $\operatorname{diam} Ty_k \le \frac13d(y_k, x)$ and $$\operatorname{dist}(y_k, Ty_k)\ge \frac56 d(y_k, x) \ge  2\operatorname{diam} Ty_k$$


Xamarin iOS - Push Notifications - Distinguish push notification clicked from arrived

Question: I'm creating a Xamarin.iOS application that includes push notifications.
I've noticed that if the app is not running (not just at the background), when a push notification arrived (with the correct payload), the OS will take over handling the notification and will present it to the user and if the user clicks on the notification while it closed, I will be able to get this information from the NSDictionary options parameter of the FinishedLaunching method (finding if it contains the UIApplication.LaunchOptionsRemoteNotificationKey key)
so far, everything is great.
but I have two scenarios,
1) the push notification arrives when the application is running.
2) the user clicked on a push notification that arrived earlier (while the app was closed) after he launches the app
for both scenarios, the method ReceivedRemoteNotification is invoked.
but for each scenario I want to do a different business logic, my question is:
How do I know if the ReceivedRemoteNotification was invoked by scenario 1 or scenario 2?
I've new to Xamarin and I've searched the web for it, but couldn't find a solution.
can anyone help me with this?
Thanks.
Comment: I don't think I've seen ReceivedRemoteNotification called when the app is started via user tap on a notification received while the app is running. I've only seen this called if the app is running when the notification is delivered at the device.
Answer: check the application state using the following condition, inside didReceiveRemoteNotification method,
UIApplicationState state = [[UIApplication sharedApplication] applicationState];
if (state == UIApplicationStateBackground || state == UIApplicationStateInactive)
{//write here...Application opened by tapping notification}

FYI- The above code is in Objective-c
Comment: Compared to my answer, this definitely looks worth a try!
Answer: I don't think I've seen ReceivedRemoteNotification called when the app is started via user tap on a notification received while the app is stopped. I've only seen this called if the app is running when the notification is delivered at the device. So we distinguish by passing a flag named isAppAlreadyRunning set false if called from FinishedLaunching, true if called from ReceivedRemoteNotification.
This seems to be working well in a shipping Xamarin.iOS app. All code is in AppDelegate.cs:
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{

...

    // Initialize Xamarin Forms and load the application.
    Xamarin.Forms.Forms.Init();
    LoadApplication(new Forms.App(0));

    // Check if App was opened by Push Notification.
    var keyName = new NSString("UIApplicationLaunchOptionsRemoteNotificationKey");
    if (options != null && options.Keys != null && options.Keys.Length != 0 && options.ContainsKey(keyName))
    {
        NSDictionary pushOptions = options.ObjectForKey(keyName) as NSDictionary;
        ProcessPushNotification(pushOptions, false);
    }

    return base.FinishedLaunching(app, options);
}

public override void ReceivedRemoteNotification(UIApplication app, NSDictionary userInfo)
{
    Debug.WriteLine("ReceivedRemoteNotification entered.");
    ProcessPushNotification(userInfo, true);
}

protected void ProcessPushNotification(NSDictionary userInfo, bool isAppAlreadyRunning)
{
    if (userInfo == null) return;
    if (isAppAlreadyRunning)
    {
        // do something with this knowledge...
    }

    ...
}

Comment: I'm going to try the approach proposed by @RJV Kumar as tweaked by OP, because it looks a lot more iOS-aware. Nice!
Comment: this solution is actually still helpful, this solution will work in the case where the app is not running on the device, the accepted answer it'll only work when the app is in the background.
Answer: Thank you very much @RJVKumar this is what I was looking for !
To help others this is the code in C#:
public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
{
    if (application.ApplicationState == UIApplicationState.Active)
    {
    }
    else if (application.ApplicationState == UIApplicationState.Background)
    {
    }
    else if (application.ApplicationState == UIApplicationState.Inactive)
    {
    }
}


Application throws a NullPointerException

Question: I created 3 Activities.

ElecBillActivity
AddBillActivity
ResultActivity

I successfully enterd into the second Activity using an Intent but as soon as I click the Submit button in the second Activity, I am getting an exception.
I tried many ways but I am unable to understand the problem.
This is my logcat
E/AndroidRuntime(  506): FATAL EXCEPTION: main
E/AndroidRuntime(  506): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.sai.android.billing/com.sai.android.billing.ResultActivity}: java.lang.NullPointerException
E/AndroidRuntime(  506):        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1544)
E/AndroidRuntime(  506):        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1638)
E/AndroidRuntime(  506):        at android.app.ActivityThread.access$1500(ActivityThread.java:117)
E/AndroidRuntime(  506):        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:928)
E/AndroidRuntime(  506):        at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(  506):        at android.os.Looper.loop(Looper.java:123)
E/AndroidRuntime(  506):        at android.app.ActivityThread.main(ActivityThread.java:3647)
E/AndroidRuntime(  506):        at java.lang.reflect.Method.invokeNative(NativeMethod)
E/AndroidRuntime(  506):        at java.lang.reflect.Method.invoke(Method.java:507)
E/AndroidRuntime(  506):        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
E/AndroidRuntime(  506):        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
E/AndroidRuntime(  506):        at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(  506): Caused by: java.lang.NullPointerException
E/AndroidRuntime(  506):        at com.sai.android.billing.ResultActivity.<init>(ResultActivity.java:21)
E/AndroidRuntime(  506):        at java.lang.Class.newInstanceImpl(Native Method)
E/AndroidRuntime(  506):        at java.lang.Class.newInstance(Class.java:1409)
E/AndroidRuntime(  506):        at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
E/AndroidRuntime(  506):        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1536)
E/AndroidRuntime(  506):        ... 11 more
W/ActivityManager(   70):   Force finishing activity com.sai.android.billing/.ResultActivity
W/ActivityManager(   70):   Force finishing activity com.sai.android.billing/.AddBillActivity
W/ActivityManager(   70): Activity pause timeout for HistoryRecord{4079d8f8 com.sai.android.billing/.ResultActivity}
I/ARMAssembler(   70): generated scanline__00000177:03515104_00001001_00000000 [91 ipp] (114 ins) at [0x445b36e0:0x445b38a8] in 1634844 ns
I/Process (  506): Sending signal. PID: 506 SIG: 9
I/ActivityManager(   70): Process com.sai.android.billing (pid 506) has died.
E/InputDispatcher(   70): channel '4060e840 com.sai.android.billing/com.sai.android.billing.ElecBillingActivity (server)' ~ Consumer closed input channel or an error occurred.  events=0x8
E/InputDispatcher(   70): channel '4060e840 com.sai.android.billing/com.sai.android.billing.ElecBillingActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
I/WindowManager(   70): WIN DEATH: Window{4060e840 com.sai.android.billing/com.sai.android.billing.ElecBillingActivity paused=false}
I/WindowManager(   70): WIN DEATH: Window{406f4868 com.sai.android.billing/com.sai.android.billing.AddBillActivity paused=true}
E/InputDispatcher(   70): Received spurious receive callback for unknown input channel.  fd=151, events=0x8
W/InputManagerService(   70): Got RemoteException sending setActive(false) notification to pid 506 uid 10038

I am also providing the link for my code.
As my problem seems to big and my class files are too big I provided the download link here.
As I am a new user I am unable to post the screenshots here.
Comment: Please post the relevant part of your code in the question. It should be around line 21 of your `ResultActivity` class judging by the LogCat output.
Answer: According to the logs you got a NullPointerException in ResultActivity.java on line 21... taking a look into your source code, this is caused by calling getIntent() which is a member function of Activity which can only be called after the Activity is created. Therefore, move your initialization code into the onCreate method.
Change your member definitions to:
private TextView resultOk;
int highLimit,lowLimit,highRate,lowRate,defaultRate,amount;
Bundle bundle;
String userName;
String meterNumber;
String prevReading;
String currReading;
int pR;
int cR;
int units;
String u;
String a;

Further on you are calling getIntent().getExtras() and store it in the variable bundle. But as you never put any extras in your Intent in AddBillActivity, bundle will be null and when you try bundle.getString(...) it will throw another NullPointerException!
First change to make is to give an android:id attribute to your RadioGroup in the form.xml file. Set it to radios and add the this line to your member variables in AddBillActivity:
public static RadioGroup radios;

As well as this line to the setUpViews method:
radios = (RadioGroup)findViewById(R.id.radios);

Then change the addTask method in AddBillActivity to
Intent intent1 = new Intent(AddBillActivity.this, ResultActivity.class);
intent1.putExtra("bill_name", billNameEditText.getText().toString());
intent1.putExtra("bill_number", billNumEditText.getText().toString());
intent1.putExtra("bill_previous", billPrevEditText.getText().toString());
intent1.putExtra("bill_current", billCurrEditText.getText().toString());
intent1.putExtra("radio", radios.getCheckedRadioButtonId());
startActivity(intent1);

And now you can get all those extras in your onCreate method in ResultActivity:
bundle = getIntent().getExtras();
userName = bundle.getString("bill_name");
meterNumber = bundle.getString("bill_number");
prevReading = bundle.getString("bill_previous");
currReading = bundle.getString("bill_current");
pR = Integer.parseInt(prevReading);
cR = Integer.parseInt(currReading);
units = pR - cR;
u = bundle.getString(String.valueOf(units));
a = bundle.getString(String.valueOf(units));

This should do it ;)
Comment: @Michael Rose Thank you for your reply.I applied the changes you have advised.But I am getting an other exception.My Logcat says

`E/AndroidRuntime(  622): Caused by: java.lang.NullPointerException
E/AndroidRuntime(  622):        at com.sai.android.billing.ResultActivity.onCrea
te(ResultActivity.java:38)`

I wrote that code using a tutorial as the reference,I will be very grateful to you if you can help me out!!
Comment: @Sai Ok, there we go... you call `getIntent().getExtras()` to get the `bundle` BUT you never put any extras in the intent! This should be done in your `AddBillActivity` before calling `startActivity(...)`. I will update my answer in a few minutes with the required changes!
Comment: @Michael Thanks a ton!! :)..its working now!!But I have a small problem.

`resultText.setText(getString(R.string.resultOk) +
    "\n" + userName
    + "\n" + u + "\n" + a);`

The output screen is showing :

               *name*
                null
                null
I am not able to populate the values in the output screen,can you please check the code if I have written anything wrong??

Thanks in advance!! :)
Comment: @Michael Here is the screenshot for the output... [link](http://tinyurl.com/3kouu9e)
Comment: Ahm, yeah I oversaw this, it's the same mistake you made with the other bundle / extra calls. The procedure with Intent extras is that you first `putExtra`s in your Intent and then you get all extras by calling the `getExtras()` method on an intent. Afterwards you can get any extra from the bundle by calling `get()`, I strongly recommend reading [this](http://developer.android.com/guide/topics/intents/intents-filters.html). You just want to get the string value of `units`, so use `units.toString()`.
Comment: Thank you for your valuable assistance..I understood the mistake and I made some changes to the code,its working good now,getting all right values.

The app is flawless now ;)

U ROCK :D :)


How many solution with the equation $f_{2013}(x)=\frac{x}{2013}$

Question:
let $f(x)=f_{1}(x)=\mid \cos{(2\pi x)}\mid,f_{2}(x)=f(f_{1}(x))=\mid \cos{(2\pi (\mid\cos{(2\pi x)}\mid)}\mid$
  $f_{n}(x)=f(f_{n-1}(x))$,

Question:

How many solution with the equation
  $$f_{2013}(x)=\dfrac{x}{2013}$$

This problem is from china students ask me,But I consider sometimes,and I can't it,I hope someone can help.
My try: I find $$\cos{(2\pi x)}=\dfrac{x}{2013}$$
Comment: Is this a contest problem?  (I see the number 2013 and am curious from where it came...)
Comment: If it's any help, since $\cos(x) = \cos(-x)$, you can remove all the absolute values just by assuming that $x > 0$.
Comment: To expound upon Patrick's comment: You can remove all but the *outermost* absolute value signs...
Comment: @anorton : Sure. I'm a bit tired.
Answer: The map
$$
\varphi : [0,1] \to [0,1], \qquad \varphi(t) = |\cos(2\pi t)|
$$
is surjective and continuous. During the interval $[0,1/4]$, $\varphi$ goes from $1$ to $0$. Then during the interval $[1/4,1/2]$, $\varphi$ goes from $0$ to $1$. Again during $[1/2,3/4]$, $\varphi$ goes from $1$ to $0$, and finally during $[3/4,1]$, $\varphi$ goes back from $0$ to $1$.
The line $y = x/2013$ must therefore cross the graph of $\varphi$ 4 times, namely the number of times the curve $(t,\varphi(t))$ goes from $\varphi(x_1) = 0$ to $\varphi(x_2) = 1$ or vice-versa.
If we iterate $\varphi$ to get $\varphi^2$, over each of those intervals of size $1/4$, $\varphi$ will go back and forth as explained above $4$ times, for a total of $16 = 4^2$ times. For $\varphi^3$, it will go back and forth $64 = 4^3$ times.
The number of such $x$ is therefore $4^{2013}$.
EDIT! Perhaps I should add : in the intervals where $\varphi$ goes from $0$ to $1$ (resp. $1$ to $0$), $\varphi$ is increasing (resp. decreasing), hence will intersect the line $y = x/2013$ precisely once.
Hope that helps,
Comment: Nice solution....
Comment: @juantheron : thanks :D


PHP errors not being displayed

Question: I'm using PHP with Apache on Ubuntu 12.10. Errors are not being displayed to the browser for some reason and I can't figure it out.
I have the following in my php.ini file:
error_reporting = E_ALL & ~E_DEPRECATED
display_errors = On
display_startup_errors = On
log_errors = On

I am also positive that I have edited the correct ini file by verifying it with php_ini_loaded_file(). I can also verify that the values are correctly set by doing the following in my script:
echo ini_get("display_errors"); // Outputs 1
echo ini_get("display_startup_errors"); // Outputs 1
echo ini_get("log_errors"); // Outputs 1
echo ini_get("error_reporting"); // Outputs -1

I have tried what seems like every possible combination of these settings (and restarting Apache after each change) and it is just not outputting errors. I am also not using ini_set anywhere in the script. It is being set only from the ini file.
Any ideas why errors aren't being displayed?
Update:
It turns out it IS showing some errors, but not all of them.
echo 'hello''; // Shows syntax error
trigger_error("E_USER_WARNING", E_USER_WARNING); // shows error
trigger_error("E_USER_NOTICE", E_USER_NOTICE); // shows error
trigger_error("E_USER_ERROR", E_USER_ERROR); // Doesn't show error

Comment: Are there actually errors occurring?
Comment: @MichaelHampton yes. If I add `trigger_error("Errormsg", E_USER_ERROR);` I get absolutely no output. Not even if anything was previously echoed. Removing that line and it is fine. Same goes with syntax errors.
Comment: have you check on the phpinfo for display_errors and error reporting ?
Comment: @Rikih. `phpinfo()` matches what I put above in `ini_get`.
Comment: It's impossible for these to be different. Even if you do `ini_set` and change one of the values it also changes the value in `phpinfo`.
Answer: It turns out the problem was a combination of PEBKAC and the Content-type header. When doing:
header('Content-Type: application/xhtml+xml; charset=UTF-8');

the browser then expects a valid XML document. When there are specific errors, it causes the document not to display in the browser at all even though content was sent. Viewing the page source shows that the error did, in fact, get successfully sent to the browser along with all the other code. My problem was that I assumed that nothing was getting echoed at all because all I saw was white.

PHP errors not being displayed


How to disable billing address in Drupal Commerce while using Paypal WPS

Question: I'm setting up a very simple online shop for a charity. They'll use Paypal WPS and don't want to collect customer's billing address as those will be entered in Paypal anyway. Is there a way to remove the billing address from Drupal Commerce.
I'm only using PayPal, so the aforementioned answer doesn't apply.
Comment: I think it's partly a duplicate but not necessarily because if PayPal is the only option then there is no need to handle different conditions.
Answer: If you do not need Billing Address section at all, it should be as simple as dragging Billing Information under disabled from any of checkout/review step.
Go to page 'admin/commerce/config/checkout' in order to disable Billing Section.
If you want Billing Address section to vanish conditionally based on payment method opted(in case you have multiple way of payment) then it is already answered here by Ryan himself.


Extra collapsed fieldset on node form

Question: I have an extra collapsed input format fieldset on my node form. It above all other elements, appears unrelated to any fields, and I can't tell where it's coming from. Not sure how to investigate where the source is.
I'm guessing that the Multistep module is the cause, but I need to at least figure out what field the form is coming from.
Answer: Your first option is to simply inspect the html of the form, it should have identifying markup in the HTML which you can then use to grep all your modules for.
Your second option is to implement hook_form_alter and output $form to see which form is generating it and whether there are any identifying markers there. You can use kpr() to output the results of $form using the Devel module to get nicer looking output. You can also use hook_form_alter to remove the fieldset if you want.
Comment: My fault for not specifying, but I'd done all of that. The HTML has no classes to clue in the field, and dsm() on the form with a form_alter() doesn't really help since it's pre-render.
Comment: Are you performing hook_form_alter() or hook_form_FORM_ID_alter() to check the dsm() output?

Extra collapsed fieldset on node form


Problem with violin finger placement changes with each string?

Question: I have a violin student who recently purchased a violin from a music shop. It's not a professional grade violin, but it is still a nice student model. My student's intonation seemed to get worse after he got it, and I finally noticed something I've never seen before...
Although each string is in perfect tune with each other, he has to place his fingers higher on the fingerboard for every higher string. For example, the G string finger placement is normal. The D finger placement is a little more spread out (i.e. the third finger on the D string isn't in tune unless it's higher than the third finger on the G string). And then the A and E string finger placements have to be even more spread out to be in tune. I hope that makes sense.
Anyway, I use tape to let him know where to place his fingers, and after going through each string, the tape isn't straight across the fingerboard as it usually is, but is tilted at quite a noticeable angle.
Can anyone tell me what the problem is? It must be a problem with the violin, but I'm not sure what it is. And it sounds like such a strange problem. I've been teaching for years, and have never seen this problem before. Obviously, he needs to get it fixed because it is affecting his playing and intonation.
Comment: Seems like the bridge isn't in the correct position - possibly slanting, but you'd notice that, wouldn't you?
Comment: I wondered about the bridge too. Also I wonder about the height of the strings above the fingerboard. The bridge hasn't been installed backwards has it?
Comment: I agree it's most likely the bridge placement. It should be parallel with the end of the fingerboard and should line up with the notches on the insides of the f-holes. Also make sure it is centered over the strings so there is the same amount of space between the fingerboard and strings on both sides. A new set of strings wouldn't hurt. If this doesn't solve the problem it is possible the neck is either loose or was mounted off line which is more serious.
Comment: Hi newcomer!  can you let us know what your skill level on the violin is, and whether you have any experience as a luthier, or in setting up a violin,  measuring bridge height  & position, etc?
Answer: This problem has not obvious solutions. I recommend bringing it to a luthier to get it checked. There are so many possible causes, like bridge tilting, bridge perpendicularity, string tension.
Answer: I would try and work out the possible causes and then go through and try and eliminate them.
The note produced by a vibrating string depends on the length, tension and composition of the string.
Apart from fingers depressing the string, the way the length can vary from string to string is if either the nut or the bridge is at an angle. This should be a relatively easy visual check.
I can't think of a way that the tension could vary across the length of the string, but maybe that is possible.
In a well made string the composition should be uniform.
In any case, unless I could see something obviously wrong with either the bridge or the nut my first attempt at narrowing down the problem would be to replace the strings with a known set. Ideally the music shop should have sold the violin with a good set of strings, but you never know. If changing the strings doesn't fix the problem then I would take the violin back to the shop.
Answer: There will always be a slight difference in the position of the notes on each string due to the different thickness and tensions of the strings. On the violin this difference is close enough that is is usually not noticeable.
The action setup and position of the bridge will cause tuning problems if setup incorrectly, especially if the action is too high. High action causes more deflection of the string, creating a difference in the final location of the fingered note on the different thickness and mass of each string.
The height at the nut, the scoop of the fingerboard, the height of the strings at the end of the fingerboard and the position of the bridge all need to be adjusted to within certain measurements to function correctly.
At the nut the strings should be about a third of the diameter of the string above the fingerboard. The E string about a quarter millimeter high. On new stock violins the nut is usually set high.
The scoop of the neck should not be too deep. Depressing the string at the nut and end of the fingerboard, the G string scoop shouldn't be deeper than about one mm.
The Bridge placement may be approximated by measuring the neck from the nut to the body joint, or where the top ends at the neck, and dividing this measurement in half, and then multiplying that number by three (to get a 2:3 ratio) to get the distance from the top at the neck to the bridge foot.
For many violins this will be 13 Centimeters from nut to neck, divided by 2 to get 6.5, times 3 = 19.5 cm from neck joint to bridge foot.
-- do not rely on the F hole notches for bridge placement. Some student model violins do not set these correctly. --
Once the bridge is set, the string height should be measured at the G and E strings at the end of the fingerboard. A commonly recommended height is about 5.5  mm at the G string and 3 - 3.5 mm at the E string.
If all the measurements are in range and there is still intonation problems, replacing the strings with a different set might help, but more likely there is something physically wrong with the instrument.


Issue accessing MS Access from IronPython

Question: I'm trying to run scripts in MS Access using IronPython in Spotfire. Thus far, I can't even get connected to MS Access.
Here is my code for connecting:
import clr
import System
clr.AddReference("System.Data")

from System.Data import DataSet
from System.Data.Odbc import OdbcConnection, OdbcDataAdapter

connectString = (
    "Driver={Microsoft Access Driver (*.mdb, *.accdb)};"
    "Dbq=\\\olgwfap1\Data\Development Division\Res Surv Eng\Personal Folders\Pruet\Data Team\SPOTFIRE\TIDELANDS\Tidelands_Spotifre.accdb;"
    "Uid=Admin;PWd=;"
)

query = "Select * From FOP_Calc"

connection = OdbcConnection(connectString)
adaptor = OdbcDataAdapter(query, connection)
dataSet = DataSet()
connection.Open()
adaptor.Fill(dataSet)
connection.Close()

Executing this, I get the following error:

System.Data.Odbc.OdbcException (0x80131937): ERROR [IM002]
  [Microsoft][ODBC Driver Manager] Data source name not found and no
  default driver specified    at
  System.Data.Odbc.OdbcConnection.HandleError(OdbcHandle hrHandle,
  RetCode retcode)    at
  System.Data.Odbc.OdbcConnectionHandle..ctor(OdbcConnection connection,
  OdbcConnectionString constr, OdbcEnvironmentHandle environmentHandle)
  at
  System.Data.Odbc.OdbcConnectionFactory.CreateConnection(DbConnectionOptions
  options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo,
  DbConnectionPool pool, DbConnection owningObject)    at
  System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection
  owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions
  userOptions)    at
  System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection
  owningConnection, TaskCompletionSource1 retry, DbConnectionOptions
  userOptions, DbConnectionInternal& connection)    at
  System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection
  outerConnection, DbConnectionFactory connectionFactory,
  TaskCompletionSource1 retry, DbConnectionOptions userOptions)    at
  System.Data.ProviderBase.DbConnectionInternal.OpenConnection(DbConnection
  outerConnection, DbConnectionFactory connectionFactory)    at
  System.Data.Odbc.OdbcConnection.Open()    at stub$296##296(Closure ,
  CallSite , CodeContext , Object )    at
  Microsoft.Scripting.Actions.MatchCaller.Call2[T0,T1,TRet](Func4
  target, CallSite site, Object[] args)    at
  Microsoft.Scripting.Actions.CallSite1.UpdateAndExecute(Object[] args)
  at
  Microsoft.Scripting.Actions.UpdateDelegates.Update2[T,T0,T1,TRet](CallSite
  site, T0 arg0, T1 arg1)    at $287##287(Closure , Scope ,
  LanguageContext )    at
  Spotfire.Dxp.Application.ScriptSupport.IronPythonScriptEngine.ExecuteForDebugging(String
  scriptCode, Dictionary2 scope, Stream outputStream)    at
  Spotfire.Dxp.Application.Scripting.ScriptService.ExecuteForDebugging(String
  scriptCode, Dictionary2 scope, Stream outputStream)    at
  Spotfire.Dxp.Application.Scripting.ScriptManager.<>c__DisplayClass14.b__f()
  at Spotfire.Dxp.Framework.Commands.CommandHistory.Transaction(Executor
  executor, Boolean visible, Boolean sticky, Guid stickyGuid)    at
  Spotfire.Dxp.Framework.Commands.CommandHistory.Transaction(String
  displayName, Executor executor)    at
  Spotfire.Dxp.Framework.DocumentModel.DocumentNode.Transaction(String
  displayName, Executor executor)    at
  Spotfire.Dxp.Application.Scripting.ScriptManager.ExecuteScriptForDebugging(String
  scriptCode, Dictionary`2 scriptArguments, String& output)    at
  Spotfire.Dxp.Forms.Framework.Scripting.ScriptEditDialog.RunButton_Click(Object
  sender, EventArgs e)

The file name is definitely correct so I'm assuming it's the default driver giving it trouble.
If it makes any difference, my SpotFire (which hosts the IronPython) is a 64 bit installation and I'm using MSOffice 32 bit (I do have 64 and 32 bit MS Access ODBC drivers installed though).
Any help is appreciated,
Thanks.
Comment: `Provider=` is used for OleDb connections.  For ODBC, you need something like `Driver={Microsoft Access Driver (*.mdb, *.accdb)};` instead.  See [Microsoft Access accdb ODBC Driver connection strings](https://www.connectionstrings.com/microsoft-access-accdb-odbc-driver/)
Comment: Good call, I made that change but am still getting the same error: connectString = (
 "Driver={Microsoft Access Driver (*.accdb)};"
 "Dbq=\\\olgwfap1\Data\Development Division\Res Surv Eng\Personal Folders\Pruet\Data Team\SPOTFIRE\TIDELANDS\Tidelands_Spotifre.accdb;"
)
Comment: Nuts!  Unfortunately my Python is way rusty and I've not done IronPython at all, so I don't know what's wrong now.  One point I wonder about though ... are you positive you have both the 32 and 64 bit Access drivers installed?  I understood that is not a configuration MS supports.
Comment: You are correct, I thought I did but trying to actually configure the 64 bit version throws an error saying "The specified DSN contains an architecture mismatch between the Driver and Application". So maybe it is a driver issue?
Comment: And yes, I did trying with both *.mdb, *.accdb and just *.accdb
Comment: I've never attempted to install both the 32 and 64 bit Access drivers on the same machine.  I can't help you there.  Sorry.
Answer: If your IronPython script is running in a 64-bit environment then you would need to have the 64-bit version of the Access Database Engine installed. Or conversely, if you have the 32-bit version of the Access Database Engine installed (because you have 32-bit Office) then your IronPython script needs to be running in a 32-bit environment.
It is possible to force both the 32-bit and 64-bit versions of the Access Database Engine to reside on the same machine but it is not recommended. It can cause problems with Office and is not a supported configuration.


Do we have any particular tonal center in mind when we are NOT listening music?

Question: Let say I sing or play song in C major. I feel that C note as home, or in other words, it has the quality of the tonic note for me. I stop playing the song. After 24 hours or any longer period, without listening or playing any other songs I will have 3 possibilities

I still will have in mind C as tonic.
I will have in mind random note as a tonic.
I will not have any feeling of tonal center. And any random note for me will not have any context. This random note will not have any scale degree at all for me.

Which of these three possibilities more likely to happen?
Answer: Remember that music isn't the only thing that has pitch. Most sounds in the natural world have a pitch as well, and a random sound outside could temporarily get stuck in our ears as a possible tonic.
For me—and keep in mind I don't have absolute pitch—I often find myself singing in B♭. To make a long story short, I think this is because a number of devices around my house are "in" B♭: my microwave, coffee grinder, and lawnmower all hum a B♭.
I say all of this because, in order to really answer this question, we'd need a complete vacuum of sound to really test it. As it stands, there is an immeasurable number of outside pitch influences that could, however temporarily, stand as tonic.
Comment: Is it possible that because the standard electrical hum in the United States is 60Hz (~B♭1), most of your electrical devices hum a B♭, resulting in you singing in B♭? (Europe and Asia, if I'm not mistaken, run at 50Hz instead)
Comment: Umm, a transposing lawnmower! Sounds interesting. Mine's at concert pitch, although it's occasionally at football pitch... And I had it tuned this season - goes better still.
Comment: Annoyingly sharp of G in the EU, yup.
Comment: @Tetsujin 50 Hz is actually closer to G than 60 Hz is to B♭. Both are better described as quarter-tones between G and G♯, and B♭ and B, respectively.
Comment: Haha, next time you're buying an electrical appliance you should ask if it's in Bb to complement your orchestra.
Comment: In the UK, the pips that the BBC play to mark the hour are 1kHz which is a slightly sharp B.  One time they dropped down to a B flat and a music professor commented on this and requested that they be left there.  Unfortunately for him, the engineer's reaction was to correct the fault and restore the 1kHz.  A pity an A or B flat would be nicer depending on your genre.  I used to play in a dance band and we tuned to B flat.
Comment: So we can assume that tonic can be switched unconsciously depend on enviroment (or maybe current tonic can depend on mood also?), without our will?
Comment: @DmitryKudryavtsev I would say tonic can be switched against our will, yes. But isn't that true of music in general?
Comment: I don't usually sing along to mains hum or coffee grinders but I remember singing along to ship's engine which was giving out a loud steady note.  Having a poor memory and not having perfect pitch, I can't say which note it was.
Comment: @badjohn - in the '60s, when caravanning, I used to use the BBC pips to keep my guitar in tune. But still had to tweak it up and down to play along with the pop songs, which weren't always at concert anyway. I always said that the pips ought to be B B...B.B.C...
Comment: What about background music though? You're unlikely to get through an hour or so without encountering music of some sort on tv or radio, on mobile phones, in shops - or indeed in elevators - even if you don't consciously listen to it..
Comment: @TomSharpe Very true. In my answer I was trying to focus on "non-musical" sounds that I worried would be ignored in the discussion.
Answer: If you have absolute pitch, then no.1 will be the answer.
No.2 for most people, when they will still be able to whistle or hum the tune in question, but having a random note as tonal centre/root/tonic. It won't really matter to them.
Any 'random note' will not have the feel of any 'tonic' until you decide on one - the same as original or not, doesn't matter. So no. 3 is virtually no.2, I think.
Whatever key it gets sung in later is of little consequence to most people - as long as it's sung in tune! It only really matters when other players (not singers, particularly) are involved, as a common key makes everything sound so much better...
Or have I missed the point of this question?
Comment: Isn't the point that we don't have a tonal centre without minding a certain tune or interval like a fourth up or a minor third down or any other  musical motif?
Answer: "Random" tonal center
This will depend on several factors. As @Tim mentioned, if you have absolute pitch, then your conjecture (1) is correct, and any tune in C will remain in C for you, and likewise for the other 11 keys.
As for your conjecture (2), this is most likely, but it isn't nearly as random as you may think! Even if we avoid listening to music for an extended period, there are sounds all around us:

the buzz of AC circuits, also known as mains hum, power line hum (60 Hz in USA (~B half flat), 50 Hz in most of the rest of the world (~G half sharp)).
If you are in a more rural setting, you may hear birdsong (varies by species) and the chirping of insects (varies by ambient temperature!).
In a more urban or industrial setting, the rumbling of vehicles and
machinery will have characteristic frequencies as well.

The more ear training you have, the more your brain will take these sounds and contextualize them into pitches and intervals, and these will form the basis of the "random" tonal center in your head. For example: if you are in USA, you will hear a mains hum of 60 Hz in your office. Outside, a semi truck is idling (call it ~39 Hz for this scenario). These two notes are B and D# (roughly), producing a B major chord in your head. If you start humming while listening to those sounds, the tune will likely be in B major. Note that if you heard the exact same truck outside your UK office, your tonal center would be Eb major instead.
Conjecture (3) is mostly for non-musicians, who as far as I can tell by talking to them, somehow don't have songs in their heads at all times (??), which is really hard for me to even consider.
Comment: *"If you start humming while listening to those sounds, the tune will likely be in B major"* Do you know this to be true? Have there been any studies to that effect? I'm not sure I buy that the tonal center is extremely biased towards those certain frequencies, especially because a friend of mine with absolute pitch goes walking with me sometimes, and whenever we find someone singing or whistling or humming, they tell me what key they're in, and so far it's been a random assortment of tonal centers (and more closely related to the original key of the song than to any particular note).
Comment: @user45266 My example was just that, an example. I also provided several other potential sources of pitch above which would lead to any number of different tonal centers. My point was not that everyone always hums in B major, but that upon hearing certain frequencies, one can be "steered" in the direction of keys related to those frequencies. Right now, I can hear a computer fan humming at F#3, and so the melodies in my head are using that pitch so as not cause too much dissonance.
Comment: My answer is very close to yours.
Answer: As Richard says, any noice in our environment, e.g. the "brumm" of a car, a plane or even a bee or a  fly can become a new tonic. I assume it is also depending of the range of our voice and the range of a song we have in mind whether a tone like the pitch fork A will become the tonic or the dominant of an eventual tune. I am speaking from my experience trying to acquire perfect pitch and always getting disturbed by environmental music or noise. The tonal center can also get lost simply by listening a modulating music piece. Sometimes I wake up in the morning and have still the sound of the fork in the right pitch in my ear. But this doesn't mean that when reading sheetmusic I find automatically the right pitch even I am used to derive the initial interval of a song from the fork pitch. This is always an activ act of concentration.
So to answer the question:
People with perfect pitch will find or keep the same tonal centre.(1)
All others - like me - are helplessly lost even if they are willing to find the same centre as you are asking. Randomly they may keep it. (2)
If we don't have a music piece in mind there will be no tonal centre. (3)
It sometimes happens that I try to find the A=440 (concert pitch) without thinking of a song. But then this A is rather the dominant of D than the tonic of A as I have probably the circle of fifths in mind or the upbeat of a fourth to a possible song. (4)
Answer: I quite like Richard's answer, but to offer a more narrow one: the concept of a tonal center is meaningless in the absence of music. There's nothing physically real about a tonal center; from a pure physics perspective it doesn't describe any property of vibrations in air. When we talk about a tonal center, we are talking about a very specific and socially constructed understanding of sounds that have been organised and/or presented in a particular way, as music.
Your point three is probably equivalent to this view.
I would personally describe the phenomenon Richard observes as a "potential tonal center for music yet to come, set by ambient sounds", but I can imagine that there are many contexts where it is convenient to treat this unwieldy phrase and concept as being essentially identical to a tonal center in my narrower sense of the word.
Answer: It's your voice. It is in my case. The note which i can hum with the least effort in expiration is G2. Unconsciously you do that.
Comment: I think my tinnitus is in the key of E. The 162.400~162.550 frequency of the tone of the [Emergency Alert System (EAS)](https://www.sigidwiki.com/wiki/Emergency_Alert_System_(EAS)) is "E3 minus 26(~24) cents" – [Frequency to Musical Note Converter](https://newt.phys.unsw.edu.au/music/note/)


Derivate of the cofactor and the determinant

Question: $\newcommand{\Cof}{\operatorname{Cof}}$
$\newcommand{\Det}{\operatorname{Det}}$
$\newcommand{\id}{\operatorname{Id}}$
$\newcommand{\tr}{\operatorname{Tr}}$
Let $A(t)$ be a smooth path in $M_d(\mathbb{R})$, $A(0)=A,\dot A(0)=B$.
By differentiation the identity $(\Cof A)^T \circ A=\Det A \cdot \id$, one gets
$$(*) \, \, \big(d(\Cof)_A(B)\big)^T \circ A + (\Cof A)^T \circ B = \tr (\Cof A)^T B) \cdot \id= \langle \Cof A , B\rangle \cdot \id$$
(The derivative of the determinant is known as Jacobi's formula).
From this, at least in the case when $A$ is invertible we can deduce that
$$ \big(d(\Cof)_A(B)\big)^T    = \big(\langle \Cof A , B\rangle \cdot \id -(\Cof A)^T \circ B \big)A^{-1},$$ hence
$$ d(\Cof)_A(B)   = (A^{T})^{-1}\big(\langle \Cof A , B\rangle \cdot \id - B^T \circ \Cof A  \big) $$
Questions:

Does equation $(*)$ uniquely determine $d(\Cof)_A(B)$ even when $A$ is singular? Is there a closed formula for $d(\Cof)_A(B)$ in this case?
Is there a more "direct way" to calculate $d(\Cof)_A(B)$? (without relying on Jacobi's formula)

Remark: As a corollary from $(*)$ we get $ \tr \bigg( \big(d(\Cof)_A(B)\big)^T \circ A \bigg) = (d-1) \tr (\Cof A)^T B) $
This is interesting since the cofactor essentially measures the action of the linear map $A$ on $d-1$ dimensional parallelepiped, so maybe there is a "geometric" way to see this immediately.
Answer: Let $Cof_{ij}(A)=(-1)^{i+j}\det(\Delta_{ij}(A))$, where $\Delta_{ij}(A)$ is the submatrix obtained from $A$ by deleting row $i$ and column $j$. Notice that $\Delta_{ij}(\cdot)$ is a linear transformation. Let $Adj(D)$ be the adjugate matrix of $D$.
Let $\{e_1,\ldots,e_d\}$ be the canonical basis of $\mathbb{R}^d$.
Now, $d(Cof)_A(e_me_n^t)=\lim_{h\rightarrow 0}\dfrac{Cof(A+h e_me_n^t)-Cof(A)}{h}$.
$Cof_{ij}(A+h e_me_n^t)=(-1)^{i+j}\det(\Delta_{ij}(A+h e_me_n^t))=$
$(-1)^{i+j}\det(\Delta_{ij}(A)+h \Delta_{ij}(e_me_n^t))=
(-1)^{i+j}\det(\Delta_{ij}(A)+h\ uv^t)=$
By the matrix determinant lemma,
$=(-1)^{i+j}\det(\Delta_{ij}(A))+(-1)^{i+j}h\ (v^tAdj(\Delta_{ij}(A))u)$
$=(-1)^{i+j}\det(\Delta_{ij}(A))+(-1)^{i+j}h\ tr(Adj(\Delta_{ij}(A))uv^t)$
$=(-1)^{i+j}\det(\Delta_{ij}(A))+(-1)^{i+j}h\ tr(Adj(\Delta_{ij}(A))\Delta_{ij}(e_me_n^t))$
$=Cof_{ij}(A)+h\ (-1)^{i+j}\ tr(Adj(\Delta_{ij}(A))\Delta_{ij}(e_me_n^t))$.
Thus, $d(Cof)_A(e_me_n^t)=((-1)^{i+j}\ tr(Adj(\Delta_{ij}(A))\Delta_{ij}(e_me_n^t)))_{i,j}$.
Since $B=\sum_{m,n=1}^db_{m,n}e_me_n^t$ then $d(Cof)_A(B)=((-1)^{i+j}\ tr(Adj(\Delta_{ij}(A))\Delta_{ij}(B)))_{i,j}$.
Comment: Thanks. I do not understand some details, though: What are $u,v$ (perhaps $e_i,e_j$)? Also, do you know if my equation $(*)$ determines $d(\Cof)_A(B)$ when $A$ is singular?
Comment: $\Delta_{ij}(e_{m}e_n^t)$ is a rank one matrix. I called it $uv^t$. Let me think about your second question.
Comment: If $rank(A)\leq d-2$ then $Cof(A)=0$ and your formula becomes $\big(d(\Cof)_A(B)\big)^t \circ A =0$. I cannot see a way to determine $\big(d(\Cof)_A(B)\big)^t $ from the equality $XA=0$, there are infinitely many solutions.
Comment: You are right. Thanks again!
Comment: You are welcome.
Answer: As mentioned by Daniel, when $\operatorname{rank}(A) \le d-2$, $\operatorname{Cof}(A)=0$, hence equation $(*)$ becomes
$$ \big(d(\operatorname{Cof})_A(B)\big)^T A=0$$
However, the equation $XA=0$ has infinitely many solutions, as can be seen as follows:
Look at the linear map $T:M_d \to M_d$, defined by $T(X)=X^TA$. $T$ is not surjective, since every matrix in its image has rank smaller than $d-1$. Thus, $T$ is not injective.


Expressao regular para pegar link Youtube em texto

Question: Tenho um texto no wordpress e nesse texto tem um link para youtube:

Saúde" todas as segundas-feiras, às 9h15, com reprise às
  sextas-feiras, a partir das 13 horas. Durante a exibição da
  atração, a apresentadora costuma receber profissionais da saúde para
  dar dicas de alimentação, medicação, postura e qualidade de vida aos
  telespectadores.
https://www.youtube.com/watch?v=tNR3lGyiLQA
Breve histórico da apresentadora: Gisela Savioli foi a nutricionista
  responsável pela alimentação dos

criei esse expressa, mas nao está dando certo, ainda está vindo null, alguem pode me ajudar?
public function getUrlFromContent($content){
    $video_url=null;
    $pattern = '/(youtu|y2u)(be)?\.(com|be)(\.br)?\/(watch\?v=)?[^"\&\?\/ ]{11}/i';
    preg_match($pattern, $content, $result_youtube);
    if (isset($result_youtube[0])) {
        $video_url = "http://" . $result_youtube[0];
    }
    return $video_url;
}

Comment: Funcionou a resposta?
Answer: Acho que isso pode ajudar, basicamente, alterei o $pattern.
<?php

$content = 'Saúde" todas as segundas-feiras, às 9h15, com reprise às sextas-feiras, a partir das 13 horas.

Durante a exibição da atração, a apresentadora costuma receber profissionais da saúde para dar dicas de alimentação, medicação, postura e qualidade de vida aos telespectadores.
https://www.youtube.com/watch?v=tNR3lGyiLQA

Breve histórico da apresentadora: Gisela Savioli foi a nutricionista responsável pela alimentação dos';

function getUrlFromContent($content){
    $video_url=null;
    $pattern = '~http(s){0,1}://(www.){0,1}(youtube.com/watch\?v=|y2u.be/|youtu.be/)[a-zA-Z0-9]{1,}~';
    // $pattern = '/(youtu|y2u)(be)?\.(com|be)(\.br)?\/(watch\?v=)?[^"\&\?\/ ]{11}/i';
    preg_match($pattern, $content, $result_youtube);
    if (isset($result_youtube[0])) {
        $video_url = $result_youtube[0];
    }
    return $video_url;
}

echo getUrlFromContent($content);

OBS: Editei para aceitar também links resumidos do Youtube.
Espero ter ajudado!
Answer: Como eu não sei se o link vai vir sempre com quebra de linha ao final defini que o tamanha da string que define o video tera entre 8 e 11 caracteres.
 ((https?:\/\/)?www\.youtube\.com\/watch\?\w=.{8,11})

Desta forma fica opcional entre :

https://www.youtube.com
http://www.youtube.com
www.youtube.com

Caso tenha quebra de linha ou espaço apos o link.
((https?:\/\/)?www\.youtube\.com\/watch\?\w=[^ \n]+)


Declare C# Class That Implements a Generic Interface

Question: Suppose I have an empty interface class IBaseInterface which is used only to "label" implementing classes as being interfaces themselves.
Is there any way to do something like this?
For example:
public class MyClass : T where T : IBaseInterface
{
}

Comment: How would the generic type work?
Comment: In .NET you better use attributes instead of empty interfaces if you just want to tag/mark a class for a specific behaviour.
Answer: Not like that, there isn't. I would strongly recommend using a composition pattern to try and achieve whatever you're trying. As an alternative, you might find DynamicProxy (or some other proxy solution) is what you're going for.
Answer: No, you can't do that, since the compiler has to know which interface the class implements when you declare the class. You can have generic parameters to the interface, but the actual interface has to be specified.
Answer: The type you're declaring isn't even generic. Something like this:
class MyClass<T> : T where T : IBaseInterface

could work under some circumstances (for example, if C++ templates were used instead of .Net generics), but it's simply not valid C# code.
I'm not sure what are the "labels" used for, but an interface with a property
ClassType ClassType { get; }

where
ClassType is an enum could work.


Distance Metrics For Binary Vectors

Question: I have vectors of same length consisting of 1 and 0. I am trying to find out how similar they are. So far I am using hamming distance that I calculate sum of one vector then sum of second vector and the difference between this is the difference of the days. With 1 and 0 it works pretty well.
My problem is that it doesn't reflect in any way where is the difference in the vectors and what is the variance of the error. I have thought of counting of how many 1 been misplaced to 1 of the next vector and how many 0 have been misplaced. It gives little bit more of information but still doesn't tell anything about the variance of the error.
The vectors are used to represent occupancy of house in time, with every 1 indicating that house is occupied and 0 that it is not. From this I am trying to predict how next day will look.
Comment: You seem to have defined Hamming distance incorrectly. It is not the sum of one minus the sum of the other it is the sum of the differences.
Comment: @Peter Actually, it's not that either.  Assuming you mean sum of *absolute values* of the differences (without which you cannot have a distance at all), you have described the L1 distance.  The Hamming distance is [the number of places in which the two vectors differ.](https://en.wikipedia.org/wiki/Hamming_distance)
Comment: How about edit distance?
Comment: any suggestion which distance would be more useful?
Comment: Do you have the "correct" data to CV with?
Comment: Well "correct" data you mean if I can then say this was correct and this wasn't. Nope I do not have, I am trying to find the best metrics on it.
Answer: Seems like you're looking for either the Jaccard distance or the Dice dissimilarity.
Jaccard distance:
$1 - \frac{|A \cap B|}{|A \cup B|}$
Dice dissimilarity:
$1 - \frac{2|A \cap B|}{|A| + |B|}$
These both are equal to zero if $A$ and $B$ are exactly the same, and one if they are completely different. However, Jaccard will "punish" differences more severely. Also note, Dice is not really a metric (doesn't satisfy triangle inequality) so it may not satisfy your needs.
The appropriate distance likely depends on the origin of the data and what you are trying to achieve, but those two are likely a good start.
Jaccard index
Sorensen-Dice index
Answer: In addition to Jaccard and Dice, I've had success with:

Cosine Similarity: $\text{cos}(\theta) = \frac{{\bf u} \cdot {\bf v}}{||{\bf u}|| \times ||{\bf v}||}$

Not a metric, only a similarity measure. See Angular similarity if metric is needed.

Rajski's distance: $1 - \frac{H(u;v)}{H(u,v)} $

H(u;v)=mutual information; H(u,v)=Joint Entropy

See this article for a good survey of binary similarity measures and distances.
Comment: The link is dead but the linked article was titled "A Survey of Binary Similarity and Distance Measures" by Choi et al 2010 and published in SYSTEMICS, CYBERNETICS AND INFORMATICS, ISSN 1690-4524, VOLUME 8 - NUMBER 1 - YEAR 2010
Comment: +1 for the link to the article!
Answer: Quick summary of metrics I used for a similar problem. Jaccard distance is also useful, as previously cited. Distance metric are defined over the interval [0,+∞] with 0=identity, while similarity metrics are defined over [0,1] with 1=identity.

a = nb positive bits for vector A
b = nb positive bits for vector B
c = nb of common positive bits between vector A and B
S = similarity
D = distance
Dice and Tanimoto metrics are monotonic (which means you will get the exact same ordering/ranking of the vectors ([B,C,D,..]) you will compare to a reference vector (A) by using these two metrics, although similarity values may differ).
Manhattan and Euclidian metrics are monotonic.
Cosine and Tanimoto metrics are always highly correlated but not strictly monotonic.
Tanimoto is the reference metric used in the field of drug discovery for problems that can be framed like yours. Its only issue is it is biased towards low values when your vectors contains very few positive bits.

Distance Metrics For Binary Vectors


How to simulate sample proportions near or at zero in a Monte Carlo simulation?

Question: I am running a chain of Monte Carlo simulations to estimate uncertainty in some model estimates (which are derived from a series of estimates). An important variables used in one of the steps is a sample proportion, which sometimes is near or at zero successes (e.g., 0 out of 20 fish were of hatchery-origin).
Here is a simplified example of my problem.

Simulate sample proportions and estimate confidence interval from the distribution
simulated_proportions = rbinom(n = 1000, size = 20, prob = 0) / 20
  quantile(simulated_proportions, probs = c(0.5, 0.025, 0.975))
    50%  2.5% 97.5%
      0     0     0
Compare simulated confidence intervals to Wilson-Score approximation
library(Hmisc)
  binconf(x = 0, n = 20, alpha = 0.05, method = "wilson")
   PointEst Lower     Upper
          0     0 0.1611252

My simulated data underestimate potential uncertainty in the sample proportion. It is important that uncertainty in this step is included in this step of the MC simulations.
Any advice on how to address this problem?
Comment: A coworker and myself have been banging our heads against our desks trying to figure this out today. We want to be able to capture the case where you made x observations, and didn't see any of what you're looking for, but there could be some of those. That's where rbinom breaks down, because a p=0 always gives 0. We think there might be some way to approximate it using the PropCIs package, and the scoreci function (which returns CI's based on the Wilson score) -- but haven't figured it out yet. Did you end up figuring out a way to do this?
Comment: @BDavis You appear to confuse the underlying probability with the outcome.  The distinction is this: you can flip a coin with a chance $p\gt 0$ of landing heads $n$ times, yet it is possible (maybe even probable) that you will see no heads, whence the *observed* proportion is zero.  This doesn't mean $p$ is zero!  Please re-read Maarten Buis's answer.
Comment: @BDavis - Yes, that is the problem I am running into. I have not found a solution. If you have any additional ideas, please share.
Answer: People have quite a specific idea of what a proportion is for these types of techniques: they imagine a given number of trials $n$, and the proportion is the number of "successes" divided by the number of trials. This means that there is only a limited number of proportions possible. For example: if you have 3 trials, then there are only 4 proportions possible: 0, 1/3, 2/3, 1. This discreteness of the parameter space makes the confidence interval for proportions such a well known hard problem.
Rbinom is thus not biased, it accurately represents the data generating mechanism often used for proportions. You seem to expect a continuous parameter space for a proportion. If you want to keep that, you will first need to think of a data generating mechanism that would result in such a continuous parameter space.
Comment: Thanks! I agree completely. Do you have any recommendations for a data generating mechanism?
Comment: That is the wrong way around. You start with a real problem, this implies a data generating mechanism, which you then implement in a simulation. Now you have a simulation, and are looking for a problem.  Don't start looking for problems, there are enough out there already...
Comment: I rephrased the question and problem. Maybe that will add some clarity.


How to estimate the parameters of a Gaussian distribution sample with outliers?

Question: I have a sample of length $N$, mostly taken from a Gaussian distribution with unknown mean and variance. Of those $N$ samples, some proportion of them (typically less than 1-2%) are outliers, taken from another Gaussian distribution with a larger mean (larger typically by 3+ standard deviations of the more common distribution). I'm interested in estimating the parameters of the more common "background" distribution so that I can isolate the outliers with some prescribed probability of false alarm.
Using the sample mean/variance are the obvious ways to attack this problem, but they are not sufficiently robust to outliers for my purposes (i.e. the presence of the outliers results in an additive bias in the estimates). I can estimate the mean more robustly using different sample statistics like the median or mode that are more resistant to outlier values. However, I'm not sure how to approach the estimation of the distribution variance in a similar manner.
Is there an accepted approach for such a problem?
Edit: I decided to add some more details in response to the commenters below who suggested perhaps fitting a Gaussian mixture model to the data. I'm not sure whether that would be a good approach or not. I want to estimate the parameters of the background distribution in order to select from two hypotheses:

There are no outliers; the sample consists of a Gaussian distribution with unknown parameters.
There are some outliers, located at unknown locations in the sample. While their exact distribution isn't known, I posit that it is reasonable to approximate it as a Gaussian distribution with a significantly larger mean than the background. If this hypothesis is true, I would like to identify the locations of all of those outliers.

So, I guess I was a bit misleading in the original question. I should have said that the sample "may contain some proportion of outliers."
In the case where there are no outliers of interest, I'm not sure that a GMM would give me good results. My goal is to identify the parameters of the underlying Gaussian distribution so that I can identify outliers with a known, controlled type I error probability. I'm going to look for some more information on robust methods for estimating the distribution's scale.
Comment: Do you know for sure that the outliers are taken from another Gaussian distribution? Do you have any hypothesis on the variance of this distribution, eg is it equal to the variance of the "background" distribution? Fitting a Gaussian mixture would be a solution.
Comment: Maybe useful https://en.wikipedia.org/wiki/Robust_statistics
Comment: (+1) On Elvis comment, if you know the distribution of the outliers, fitting a gaussian mixture would be a good solution.
Comment: @ziyuang: Thanks for the link. From an initial examination, that might be exactly what I'm looking for, specifically "robust measures of scale.'
Answer: Multivariate Case
Some very applicable research has been done by Rousseeuw et. al. See the paper here that deals with the Minimum Covariance Algorithm (the paper is very readable, I would recommend reading it).
The papers deals with finding a subset of the data that minimizes the covariance matrix (hence find the data that is most Normal-looking). It is very fast, and many libraries are available in python and R
The univariate case
Although the above deals with multivariate data, there does exist formulas for the minCovDet problem for the univariate case. See this question's answer for some details.
Comment: Could you please explain how this *multivariate* approach you reference should be applied to this *univariate* problem?
Comment: ah, I misinterpreted the question, edits to reflect this.
Answer: As far as I know, there are some tests for outliers. One of them is actually described in this paper. It's based on median absolute deviation of the sample elements. There's also more sophisticated methods like chi square, cochran, dixon tests. It's actually depends on what you're using, but for R, I would recommend outliers package.
After you get your outliers removed you can calculate mean or variance in usual way with less or no bias.
Comment: There will still be bias, because only a portion of the contamination distribution will typically be identified as outlying.
Answer: Well, for a very simple outlier filter, here's some R code:
x = rnorm(500)
bp = boxplot(x, plot = FALSE)

if (length(bp$out) > 0)
        x = x[-match(bp$out, x)]

Comment: The question is not about how to identify or exclude outliers: it is about how to estimate the parameters of the "background" distribution. Although the two may be related, a lot more work needs to be done once you believe you have an outlier detection method: then you have to assess the bias and efficiency of the resulting parameter estimates (presumably based on the dataset without the outliers). Please notice that most of the contamination distribution will *not* be identified as outlying because about half its values will be less than 3SD above the background mean.


Ruckus wireless AP and Dell PowerConnect configuration problems

Question: We are working on trying to get some Ruckus Access Points to work correctly on our network. Currently our network is as follows:
VLAN 10 - Servers
VLAN 11 – Computers/DHCP
VLAN 12 – Voice
VLAN 13 – Guest
We use Dell PowerConnect 6248P switches for our switches.
Port settings are as follows:
ZoneDirector 1100 is plugged into this port. Should be accessing the server VLAN and then allowing all other traffic.
interface ethernet 1/g2
classofservice trust ip-dscp
description 'Ruckus ZoneDirector 1100'
switchport mode general
switchport general pvid 10
switchport general allowed vlan add 10
switchport general allowed vlan add 11-13 tagged
exit
Access point is plugged into this port. The port has to be on VLAN 11 in order to get DHCP.
interface ethernet 1/g16
classofservice trust ip-dscp
description 'Ruckus - IT'
switchport mode general
switchport general pvid 11
switchport general allowed vlan add 10-12
switchport general allowed vlan add 13 tagged
exit
If we tag the traffic from the SSID as VLAN 11 data fails. If we leave the SSID tagged as 1 the data flows correctly.
Are there problems with passing tagged traffic to untagged ports? We are looking to see what we can do to get the SSID tagged as 11 instead of 1.
Any suggestions?
Answer: This appears to be behaving as expected.
Your access point (unless configured otherwise) is talking to the controller / network with untagged frames (traffic that isn't associated with any particular VLAN). In this case, it's talking on VLAN 11 (the configured PVID on it's port).
As the traffic from the AP is getting pushed onto VLAN 11 (and will be tagged with this VLAN when it egresses the switch), devices on that VLAN will be able to receive it, but only if their port is either untagged on VLAN 11 (has a PVID of 11) or is carrying tagged traffic for VLAN 11 and the client is configured to look for tagged traffic.
The controller is on a port that is configured to carry tagged traffic for VLAN 11, so will drr traffic from the VLAN. If the two are talking as you report, it suggests the controller has an interface which is associated with VLAN 11 and listens to the tagged traffic arriving on that port.
The reason it breaks when you switch port g16 to be tagged for VLAN 11 is that the access point isn't tagging it's traffic, so the switch won't egress it to a specific VLAN.
Comment: We have found that since the PVID of the port was 11 and we were trying to tag the traffic as 11 it was not working. We have been able to get any other SSID to be tagged as a different VLAN to correctly work on its own assigned VLAN. This was new to me so seemed strange that we had to leave at VLAN 1.
Answer: I suggest you open a case with Ruckus at their support site https://support.ruckuswireless.com/
At a glance it Looks like you are setting the port mode wrong. I "think" it should be mode trunk and not general.
The way I read that configuration it looks like you are setting one vlan (vlan 11) as the general port vlan.  That would explain why a tag of 1 works.
Give it a try with port mode trunk and see if it works.
Answer: Try avoiding switchport mode general.
Instead use switchport trunk mode and then switchport trunk native vlan vlan-id


$\hat{\theta}_{MLE}$ for $f_X(x)=\frac{1}{3\theta}, \quad -\theta < x < 2\theta$

Question: My goal is to find
$\hat{\theta}_{MLE}$ for $$X_1, ..., X_n \sim_{iid}f_X(x;\theta)=\frac{1}{3\theta}, \quad -\theta < x < 2\theta, \quad \theta \in (0,\infty)$$
I am looking at the likelihood function and I  have
$$L(\theta) = \prod_{i=1}^n \frac{1}{3\theta} \Bbb I_{-\theta<x_i<2\theta}=\frac{1}{(3\theta)^n} \Bbb I_{-\theta<X_{(1)}<X_{(n)}<2\theta}$$
This is where I find things a little tricky.
Intuitively speaking since $(3\theta)^{-n}$ is a decreasing function for $0<\theta$ I would want to say $X_{(1)}$ maximizes $L(\theta)$
However, that only happens when $0<X_{(1)}$.
If all $X_i$s are negative and $n$ is even, then I want to say that $X_{(n)}/2$ will maximize $L$.
Is there a particular way to deal with this problem or am I on the right ball park?
I appreciate your help.
Answer: Let me rephrase your observations in a way that may make things clearer to you.
You want $\theta$ to be as small as possible while satisfying $\theta > 0$ and $\theta \ge -X_{(1)}$ and $\theta \ge X_{(n)}/2$.
Comment: From there I am inclined to say that I want the smaller of the two.  So $\hat{\theta}_{MLE}=\min[{-X_{(1)},X_{(n)}}]$ ?
Comment: @hyg17 If you do that, will all the inequalities be satisfied?


Combining different accuracies

Question: Given a set of extracted data from different sources with different accuracies, how can I combine the accuracy of those who give the same output?
Example :
Data from source A are 80% correct
Data from source B are 85% correct
Data from source C are 90% correct

If two of the sources give the same result (ResultA) and the third disagrees (ResultB) what's the probability of (A) being correct? This is not a homework question. I am a software developer and I don't have a clue about statistics and probability.
Update :
I've done an experiment using a random number generator
Test 1 - 2 Possible outcomes (0/1) three methods (Acc: 0.5, 0.3, 0.1)
Samples      : 100000000
Method A     : 0,49993692
Method B     : 0,30023622
Method C     : 0,09994145
Method A+B   : 0,794567779569577
Method B+C   : 0,0455372643070089
Method C+A   : 0,205615801945512
Method A+B+C : 0,0455215295368209

Test 2 - 2 Possible outcomes (0/1) three methods (Acc: 0.8, 0.85, 0.9)
Samples      : 100000000
Method A     : 0,80003639
Method B     : 0,8500426
Method C     : 0,90005791
Method A+B   : 0,715942797491352
Method B+C   : 0,927408281972288
Method C+A   : 0,864147967527417
Method A+B+C : 0,995137034088319

That's the numbers I am looking for but I don't know how to calculate them...
Answer: So if I assume there is a single binary state (0 or 1) that is measured three times, where the three observations are independent, we can calculate the probability of each state.  This is a likelihood-based analysis without any real equations.
So for your example, A says 1, B says 1, and C says 0.  The two choices are it's really 0 or it's really 1.
If it's truly 0, the independent observation probabilities multiply like:
(1-0.80) * (1-0.85) * 0.90 = 0.027
If it's truly 1, the independent observation probabilities multiply like:
0.80 * 0.85 * (1-0.90) = 0.068
The idea is that each measurement was either correct (p) or incorrect (1-p) and contributes that term to the product.
We have to normalize these quantities to give a probability as the final answer:
The probability it's truly 1 is then 0.068 / (0.027 + 0.068) = 0.716.
The main idea is that you use your observation model to evaluate the two competing hypotheses (which state generated the data), and report a normalized probability.
Comment: Thanks for your answer. It seems that your calculation gives the opposite result from my experiment. Do you have any idea why is that?
Comment: How is it the opposite result?  Your empirical calculation of "method A+B" gives 0.7159, where my exact calculation gives (rounded) 0.716.
Comment: Indeed, I failed to spot it at first! Now I understand your logic and I have a working implementation. Is there a generalized formula that can handle more than 2 possible outcomes?
Answer: The above answer corresponds to a special case of a more general answer. First of all, it makes certain assumptions regarding the prior distribution of the true state and conditional independence assumptions, as noted by matted.
I'll try to provide the answer for the general case, showing where these assumptions come into picture. Assuming each data source is a noisy channel which outputs the true value with some probability, the question can be formulated as follows:
$P^* = P(y=1 | \hat{y}_A=1, \hat{y}_B=0, \hat{y}_C=1)=$ ?
Using Bayes rules, we can expand this conditional probability:
$P^* = \frac{P(y=1,\hat{y}_A=1, \hat{y}_B=0, \hat{y}_C=1)}{P(\hat{y}_A=1, \hat{y}_B=0, \hat{y}_C=1)}$
$P^* = \frac{P(y=1)P(\hat{y}_A=1, \hat{y}_B=0, \hat{y}_C=1 | y=1)}{P(y=1)P(\hat{y}_A=1, \hat{y}_B=0, \hat{y}_C=1 | y=1) + P(y=0)P(\hat{y}_A=1, \hat{y}_B=0, \hat{y}_C=1 | y=0)}$
The formula above can further be simplified by assuming that the observations from these noisy channels are conditionally independent from each other given the true value. Please note that this is a weaker assumption than saying noisy observations are marginally independent; hence less restrictive. The conditional independece assumption proves to be quite useful since it allows multiplication:
$P^* = \frac{P(y=1)\prod_{x\in\{A,B,C\}}P(\hat{y}_x | y=1)}{\sum_{\bar{y}\in\{0,1\}}P(\bar{y})\prod_{x\in\{A,B,C\}}P(\hat{y}_x | \bar{y})}$
The above solution is a special case of this since it assumes a uniform prior distribution of y, e.g. $P(y=1)=0.5$. Also note that each noisy output generation is a Bernoulli trial; e.g. $P(\hat{y}_x | y) = P_x^{I(\hat{y}_x = y)}(1-P_x)^{I(\hat{y}_x \neq y)}$ $\forall x\in\{A,B,C\}$ where $P_x$ is the probability of generating the true value of $y$ for the noisy channel $x$, and $I(s)$ is the identity function which returns 1 if the statement $s$ is true, and 0 otherwise.

Combining different accuracies


armazenar id do registo php

Question: Boas pessoal, o meu objetivo é armazenar o id do registo que foi inserido na base de dados
$sql = "insert into pacientes (Nome, idade, dataNascimento, estadoCivil, nacionalidade, naturalidade, morada, telemovel, niss, nif, situacaoEconomica, trabalho, salario, outros, possuiFamilia, familiarProximo, parentesco, moradaFamiliar, contactoFamiliar, inscritoCentroSaude, qual, medicoFamilia, contacto, sns, grupoSanguineo, antecendentesClinicos, informacoesAcompanhamento) values ('$nome', '$idade', '$dataNascimento', '$estadoCivil', '$nacionalidade', '$naturalidade', '$morada', '$telemovel', '$niss', '$nif', '$situacaoEconomica', '$trabalho', '$salario', '$outros', '$possuiFamilia', '$familiarProximo', '$parentesco', '$moradaFamiliar', '$contactoFamiliar', '$inseridoCentroSaude', '$qual', '$medicoFamilia', '$contacto', '$sns', '$grupoSanguineo', '$antecendentesClinicos', '$informacoesAcompanhamento')";

    $resultado = mysqli_query($ligacao,$sql);
    $numero = mysqli_affected_rows($ligacao);
    if($numero==1)
    {
        $codigo = mysqli_insert_id($ligacao);
        echo "Inserido com sucesso. ";

}

Eu aqui consigo armazenar o id deste registo atraves do mysqli_insert_id-$codigo = mysqli_insert_id($ligacao);
O meu problema é que eu a seguir queria armazenar o id do registo mas de outra query e já não posso usar a mesma forma porque o meu objetivo seria inserir numa outra tabela o id de registo de uma query e o id de registo de outra query
    $result = count($_POST["agregado"]);
    $agregado=$_POST["agregado"];
    $t=0;
    $m = 0;

    for($i=0; $i<$result; $i=$i+4)
    {

   $p=$i+1;
   $e=$p+1;
   $b = $e+1;

    $sql_1="insert into agregado (nome, parentesco, idade, bi) value('$agregado[$i]', '$agregado[$p]', '$agregado[$e]', '$agregado[$b]')";
    $resultado_1 = mysqli_query($ligacao, $sql_1);
    $sql_2 = "insert into utenteagregado (id_agregado, id_utente)  values ('1', '$codigo')";
    $resultado_2 = mysqli_query($ligacao, $sql_2);
}

    mysqli_close($ligacao);
}

Resumindo nesta linha  $sql_2 = "insert into utenteagregado (id_agregado, id_utente)  values ('1', '$codigo')"; onde tem o numero 1 eu quero inserir o id desta query $sql_1="insert into agregado (nome, parentesco, idade, bi) value('$agregado[$i]', '$agregado[$p]', '$agregado[$e]', '$agregado[$b]')";
Answer: Usa a função last_insert_id()
No teu caso:
$sql_1="insert into agregado (nome, parentesco, idade, bi) value('$agregado[$i]', '$agregado[$p]', '$agregado[$e]', '$agregado[$b]')";
$resultado_1 = mysqli_query($ligacao, $sql_1);
$sql_2 = "insert into utenteagregado (id_agregado, id_utente)  values (last_insert_id(), '$codigo')";
$resultado_2 = mysqli_query($ligacao, $sql_2);

Um comentário importante na documentação oficial:

The ID that was generated is maintained in the server on a
  per-connection basis. This means that the value returned by the
  function to a given client is the first AUTO_INCREMENT value generated
  for most recent statement affecting an AUTO_INCREMENT column by that
  client. This value cannot be affected by other clients, even if they
  generate AUTO_INCREMENT values of their own. This behavior ensures
  that each client can retrieve its own ID without concern for the
  activity of other clients, and without the need for locks or
  transactions.

e

LAST_INSERT_ID() returns
  only automatically generated AUTO_INCREMENT values. If you store an
  explicit value other than NULL or 0, it does not affect the value
  returned by LAST_INSERT_ID().
Comment: Obrigado, acho que já está a funcionar

armazenar id do registo php


Why do we say limits which go to infinity are not defined?

Question: I recently saw this article by oregonstate.edu about the differentiability of the function $y=\sqrt{X}$ at $x=0$ they claim that the derivative at $x=0$ does not exist.i understand the concept of one-sided differentiability and how the  $\lim_{h \to 0-} \frac{\sqrt{x+h}-\sqrt{x}}{h} $
does not exist but for values of greater than 0 and approaching from the right they say that the limit does not exist as it is positive infinity. my question is why isn't this limit defined surely we know it is approaching infinity so why can't we say it has an infinite slope
Comment: It's a matter of definition. The problem is obviously that the function is not defined for any negative value. You cannot compute the derivative using the definition as a limit of the difference quotient since the limit does not exist because the function is not defined in any left neighborhood of 0. Then of course $\lim_{h \to 0+} \frac{1} {\sqrt h} =+\infty $.
Comment: Why is "this article" not a link to it? I'd like to read what exactly it says, and that could explain it.
Comment: @superb rain: I too wonder why links, specific cites, etc. are often not included in certain questions (and I'm talking about those it's clear the OP knows them, rather than cases when the OP is trying to conceal the asking of a homework question). To me it seems obvious one would want to provide this information to others, and it's not an age or maturity issue I think, as I feel sure I would have done so even in high school (if internet math groups had existed and been available to me). Indeed, at my high school when I attended, *NO ONE* (not even myself, **(continued)**
Comment: Anyway, for such reasons, infinite slopes are usually referred to only when both left and right derivatives exist and they are $+$ or $-\infty $.
Comment: You don't say "is infinite". You say "does not exist".
Comment: I think you should make the title more general @The homeschooler
Comment: The limit from the right is positive infinity
Comment: It is typical in beginning calculus to not deal with infinite derivatives, and even in more advanced mathematics in which they might be discussed, it is typical for "differentiable" to mean "finitely differentiable". One can certainly discuss infinite derivatives (see [here](https://math.stackexchange.com/q/3639698/13130) and [here](https://math.stackexchange.com/q/661359/13130)), whether two-sided signed versions, two-sided unsigned versions, one-sided signed versions, or one-sided unsigned versions ("signed" means the difference quotient limit **(continued)**
Comment: must approach one of $-\infty$ and $+\infty,$ and "unsigned means the absolute value of the difference quotient limit approaches $\infty).$ In the case of $\sqrt{x},$ there is a right-sided derivative of $+\infty$ at $x=0.$ Usually when one wants to talk about allowing for infinite derivatives, one says things like "the derivative exists, finitely or infinitely" (and the "signed" version is nearly always intended when nothing explicit is said about signs).
Comment: even though I was beginning to study calculus (from a library book) before finishing 9th grade) took Algebra 1 before 9th grade (i.e. in Junior High), but we were still thoroughly taught about citing, as appropriate, specific textbook pages (or in library magazines or library books) and such in history and other assignments when answering essay questions for homework (or essays written when the class went to the library to allow us to research a topic).
Comment: @DaveL.Renfro Yes, they really should *want* to include it, given that we could then tell them exactly what/how they misunderstood (or in case it's in fact wrong, we could then confirm that). Apparently they're not interested in that.
Comment: I'm sorry but im not quite sure how to share a link on here
Comment: For sharing a link [see this](https://meta.stackoverflow.com/editing-help#links). FYI, I didn't know for the first year or two I was here, and I simply gave links the same way everyone else had done so for well over 10 years before Math. Stack Exchange began (for me, mostly in sci.math), which was to simply [paste the URL into the message](https://math.stackexchange.com/a/51308/13130) (as a separate line, if line breaks were respected) so that the reader could simply copy the URL and paste it into an internet browser's "URL location bar". Finally, someone told me how to do "in-line" URL links.
Answer: This question gets into subtleties of how we define derivatives in terms of unidirecional limits. Let's consider the outcome in two different number systems.
Real analysis
The derivative exists iff two one-sided derivatives exist with equal value. The right-derivative$$\left.\lim_{h\to0^+}\frac{\sqrt{x+h}-\sqrt{x}}{h}\right|_{x=0}=\lim_{h\to0^+}\frac{\sqrt{h}}{h}=\color{blue}{+\infty}$$ is an extended real number; the left-derivative $\lim_{h\to0^-}\frac{\sqrt{h}}{h}$ does not exist.
Complex analysis
$f^\prime(0)$ exists with value $L$ iff $\lim_{r\to0^+}\frac{f(re^{i\theta})-f(0)}{re^{i\theta}}=L$ for all $\theta\in\Bbb R$. For $f(z)=z^{1/2}=e^{\tfrac12\ln z}$,$$\lim_{r\to0^+}\frac{f(re^{i\theta})-f(0)}{re^{i\theta}}=\lim_{r\to0^+}\frac{\sqrt{r}e^{i\theta/2}}{re^{i\theta}}=\color{red}{\infty}$$is an extended complex number. Do not confuse $\color{blue}{+\infty}$ with $\color{red}{\infty}$.
One more point: if we'd been differentiating $x^{1/3}$ at $x=0$, the two-sided derivative would again not exist in real analysis, but this time for a different reason: the left-derivative would exist, but would be $-\infty$ rather than $+\infty$.
Comment: OK I see but the right one sided derivative is equal to positive infinity so is it correct to say that the one sided derivative is defined as positive infinity
Comment: @Thehomeschooler As long as "limit-is-infinity" statements are understood in their usual sense, yes. The definition of $\lim_{x\to a^+}g(x)=L$ isn't quite the same when $L=\infty$ as when $L\in\Bbb R$.