Java Code Compiles in Command Line but not NetBeans

Question: I am literally compiling the same java file in both command line and NetBeans but I get different results. It is maddening and confusing. The code itself is simple and it is correct in command line. I get "Error" in NetBeans. This should not vary as far as I can tell...
import java.io.*;
public class A3

{
    public static void main(String[] args)
    {
        BufferedReader fileReader = null;

        try
        {
            fileReader = new BufferedReader(new FileReader("input.txt"));
            String aLine = fileReader.readLine();
            String myTokens[] = aLine.split(" ");

            System.out.println("Token 1 = " + myTokens[0]);
            System.out.println("Token 2 = " + myTokens[1]);

            fileReader.close();
        }
        catch(IOException anException)
        {
            System.out.println("Error");
        }
    }
}

SOLVED! I was way overthinking things. Command line looks for the .txt file in the same directory as the .java. Which is logical. NetBeans looks in the root directory. Which is...yeah.
Comment: Well...at least tell what's the error?
Comment: Tested it in Netbeans 8.1 and it didn't throw an error. Can you please state the error you get?
Comment: `new FileReader("input.txt")` depends on the current directory - in the command line it is the directory your are in - in Netbeans it may be something else. Can you try with a full path instead?
Comment: Have u checked that the file name is thesame as the class name?
Comment: What are error are you seeing on the console? Tell us the error then we will help you!
Comment: does it have a package statement, or is it in the default package?
Comment: May be with `input.txt`.
Comment: do you supply arguments when you run it in Netbeans?
Comment: Do you get the error at runtime or at compile time? The question's title implies that you're getting it at compile time, but then you don't specify what is the error you're getting, and this is a little confusing I think.
Comment: The file is in the same directory, I didn't copy the line but it does have a package, and the "Error" it gives me is literally that line. Which I had set up as an exception in the code itself. Not a specific compile error.
run:
Error
BUILD SUCCESSFUL (total time: 0 seconds)
Answer: Error occurs at line (You can use debugger):
fileReader = new BufferedReader(new FileReader("input.txt"));

You can have a look:
Where does java look for files?


Interate objectKeys *ngFor

Question: I have a object like this
<code>"Stage" : { // -> vaga.stage
"ID01" : { // -> stage.code
  "abeb5220-2003-4b8b-a6d5-853a40ca7d60" : { //candidate
    "email" : "email@example.com",
    "name" : "Full name"
  }
}
</code>
}
hasProperty method
<code>     hasProperty(obj, property) {
    // debugger;
    return typeof obj == "object" && obj.hasOwnProperty(property);
  }
</code>
My Html file
<code><ng-container *ngIf="hasProperty(vaga.stage, stage.code)">
                  <div
                    ngxDraggable
                    (drag)="dragCandidate($event)"
                    class="candidate ngx-dnd-item"
                    [model]="{
                      codCandidate: candidate,
                      nameCandidate: vaga.stage[stage.code][candidate],
                      codeLastStage: stage.code,
                    }"
                    *ngFor="let candidate of objectKeys(vaga.stage[stage.code]); let i = index"
                  >
                    {{ vaga.stage[stage.code][candidate] }}
                  </div>
</code>
In html, how i fetch the name value of object?
Answer: Let assume the word "objectKeys" is representing your object in your window typescript.
<code>*ngFor = "let data of objectKeys">
    {{ data.Stage.ID01.abeb5220-2003-4b8b-a6d5-853a40ca7d60.name }}
</code>
Please let me know if this is working? I am still learning. Thank you.

Interate objectKeys *ngFor


How do I test whether two events are independent?

Question: I'm trying to understand how to mathematically determine whether two events are independent. This is for introduction to statistics, so the solution and explanation to this is likely very simple, yet there's something I'm not understanding.

Here's the question from my textbook:

A statistical experiment has 11 equally likely outcomes that are
denoted by a, b, c, d, e, f, g, h, i, j, k.
Event A = {b, d, e, j}
Event B = {a, c, f, j}

If two events, A and B, are independent, then $P(A) = P(A|B)$. Therefore if I want to determine whether the two events are independent, I need to solve for $P(A)$ and $P(A|B)$ to check whether they are equal.
However $P(A|B) = \frac{P(A∩B)}{P(B)}$, and this is where I get stuck, because I can't know which multiplication rule to use to figure out $P(A∩B)$ since I don't yet know whether the events are independent or not?
If the events are independent, then $P(A∩B) = P(A) * P(B)$. Otherwise if they are dependent, then $P(A∩B) = P(A) * P(B|A)$.
I know that I can solve the question from my textbook by looking at the outcomes that intersect between the two events, but is it possible to figure out whether the two events are independent solely by using the formulae above?
Comment: Computation of $~p(A \cap B)~$ does not (normally) require knowledge of whether $~A~$ and $~B~$ are independent events.  That is, the probability of both events occurring simultaneously can usually be done without analyzing the extent that one event's occurrence affects whether the other event occurs.
Comment: I think you need to tell us *something* about the events themselves?
Comment: @311411, I've updated my post with more details.
Comment: $P(A\cap B) = P(A) \times  P(B\mid A)$ is true, whether or not $A$ and $B$ are independent. $P(A\cap B) = P(A) \times  P(B)$ is true if and only if they are independent.
Comment: @Henry, sure, but then how do I calculate P(B|A)? I'd get stuck in a loop again unless I already know P(B|A) or P(A and B).
Comment: @user928112 You can see from your original question that clearly $P(A \text{ and } B)=\frac1{11}$ and that almost as clearly $P(B \mid A)=\frac1{4}$, based on $|\{j\}|=1$ and "equally likely"
Comment: @Henry, in this example, yes both are clearly known. However my question is a hypothetical one: could we determine interdependency if we only had P(A) and P(B) with and nothing else? Some of the other users have already stated that this would be impossible to do without trial and error.
Comment: Is this too simple, or is 'two' events far too few to make any test?
Answer: In your case $P(A)=4/11$, $P(B)=4/11$ and $A\cap B={j}$, $P(A \cap B)=1/11$. Now you can see whether A and B are independent.
Comment: Got it now. I was overthinking this and the solution seems to be simpler than I thought.
Answer: You figure out the independence of the events based on what they produce from the equations. If P(A∩B)=P(A)∗P(B) then the events are independent. If you have P(A) and are missing both P(A∩B) and P(B) then you don't have enough information to answer if the events are independent or not. Basically you need to have enough information to determine independency.
Comment: Well you just don't know other than based on the physical event that is happening. For example if a coin is flipped fairly then you use the independent equations. If the coin depends somehow on what happened previously then you need to know how it depends on that.
Comment: I have P(A) and P(B) but I am missing P(A∩B). I cannot calculate P(A∩B) on my own because that requires knowledge of whether the events are dependent or independent (which is what I am trying to figure out in the first place). Essentially, I can try P(A)∗P(B), but would have no idea whether the result is correct because that multiplication rule only applies to independent events.
Comment: kmitov has showed you how to find P(A and B)
Comment: Sorry I had commented and answered based on when the question had less information, refer to kmitov's answer for information about the specific problem
Comment: @Conor_Meise, I saw kmitov's solution to my specific problem, but you also answered a secondary question that I had around whether or not it's at all possible to figure out interdependency without knowledge of the physical event, and without prior knowledge of P(A and B). Thanks for clearing that up.
Answer:
Here's the question from my textbook:

A statistical experiment has 11 equally likely outcomes that are denoted by a, b, c, d, e, f, g, h, i, j, k.
Event A = {b, d, e, j}
Event B = {a, c, f, j}

Therefore $A\cap B = \{j\}$ and ...
Comment: And how would you determine P(A and B) if you had been given just P(A), P(B), and nothing else? Judging by Conor's comments, it seems that we wouldn't be able to do that. For one, we wouldn't know which multiplication rule to use since that itself requires prior knowledge on whether the events are dependent or not. That's mainly what I was hung up on rather than just the textbook question itself.
Comment: Take the intersection of $A$ and $B$ as sets. That is the very definition of $A \cap B$.


How to specify granularity for the Access log Timestamp field to display access log entries using Views?

Question: Normally when you select a date field in Views there is the option to specify the 'granularity'. Ie: Day, Hour, Minute etc... ie: When you add the 'Post date' field from a node.
Does this functionality not exist at all for the 'Access log: Timestamp' field, when displaying access log entries using Views?
This would be really helpful for displaying simple custom statistics, but it doesn't seem to exist and I'm not sure where to even look to add the functionality to the relevant module!
Answer: Maybe the Views Date Format SQL module is what you're looking for. Here are some details (from its project page):

The Views Date Format SQL module allows to format date fields using SQL. This enables group aggregation for date fields using the choosen granularity.
The core functionality is to remove the date formatting from render() and put it in query(). I.e. format date values using SQL's DATE_FORMAT rather than PHP's format_date. This is achieved by assigning a new default handler to node 'created' and 'changed' date fields. This handler extends and overrides views's build in views_handler_field_date.
The UI is completely unobtrusive, only a single checkbox "Use SQL to format dates" is added to the handler configuration popup.

As an illustration, and/or to better understand the challenge here, you may want to look at Graph node input over time (support date formatting on a continuous axis) also. Comment #3 of that issue states: 'The trouble here is that neither Views nor Date modules provide aggregation options for date-based fields.'.


Whitelabel on existing Angular 4/5/6/7 project

Question: I have an Angular 7 application and I need to create a white label project based on the that. In the white label I need to alter some of the components css and also add new routes / new components. What is the recommended way to approach this?
Answer: The Angular Command Line Interface allows you to generate boiler plate projects, Components, Services and much more. Instructions on how to install and use it can be found at Angular CLI
There are many, many advantages to using Angular's CLI. I do not recommend skipping learning it, even if things seem a lot easier to just go around it for now.


MFC component defocus event handler

Question: Is there a standard way to handle MFC Edit box defocus event? I mean if I click on the box enter something and then move on on the other component handling event gets fired? Thank you for any help!
Answer: Yes, Windows send the WM_KILLFOCUS.
MFC uses the EN_KILLFOCUS for edit boxes, IIRC.

MFC component defocus event handler


Mark an Azure AD device as compliant without using Intune

Question: We use MobileIron with on-prem Exchange but are now looking to move some of our users to Office 365. I would like to avoid using a Sentry if possible (i.e. have the user devices go to Office 365 for email etc. directly rather than via the extra hop of a Sentry) but at the same time I want to restrict such access to just company managed devices. Via Conditional Access policies I see that one can set access to be only from devices marked as compliant, but from what I see this is a flag only Intune can set. Is there a way of setting a device as compliant via something like MobileIron?
I am interested in hearing any other suggestions or experiences from others who've had to do something similar. We have a mix of iOS and Android devices all currently managed via MobileIron on-prem. Even if the workaround for now is to manually mark devices as compliant via Graph API or PowerShell that'll do too.
Answer: Based on Require device to be marked as compliant document, this option requires a device to be registered with Azure AD, and also to be marked as compliant by:

Intune
A third-party mobile device management (MDM) system that manages
Windows 10 devices via Azure AD integration. Third-party MDM systems
for device OS types other than Windows 10 are not supported.

So currently, iOS and Android devices are not supported.
BTW, Graph API or PowerShell configurations should be the same with what can be done on Azure portal.
Answer: Conditional Access Policies already allow non-windows OS devices. Use the filter to include "Trust Type" then select AD Registered or AD Joined as Device needed for non windows and windows devices. Then do a negative operator to say Block all access, UNLESS the Trust type is above. It works, we use it successfully. You just have to AD register your devices, Microsoft has notes on how to AD register devices.


Using values from a Datalist to populate a input field

Question: I am trying to populate an input field based off of a datalist selection. So if a person chooses the name jimmy.johns, the input field should populate with 5555555555. Here's my code.

<title>Countdown</title>
<input name="customer" list="customer" />
<datalist id="customer">
</datalist>

<input id = "phone" name ="phone" type = "text" placeholder = "Phone Number" value = ""/>

I'm thinking that all one would need to do is do something like
if (options == 'david.a.onezine'){
    document.getElementById('phone').innerHTML = phone[0];
 }

However that does not work. I have read up that I may need to use a event listener on the datalist, but I haven't used many eventlisteners so would I need to attach the onChange to the 'customer' input or the 'customer' datalist?
I am stuck and have the theoretical part in my head. I understand how it should work. I just don't know how to put it into code.
So if customer[1] is selected then phone[0] should populate in the phone input field. I'm just unsure as to how to code that in JavaScript. Id rather code JavaScript than jQuery.
Answer: The simplest way to perform the desired effect is to use an onchange event.

<title>Countdown</title>
<select name="customer" id="customer" onchange="getNumber()">
</select>

<input id = "phone" name ="phone" type = "text" placeholder = "Phone Number" value = ""/>

<select name="customer" id="customer" onchange="getNumber()">
</select>

<input id = "phone" name ="phone" type = "text" placeholder = "Phone Number" value = ""/>

First things first the two input boxes are setup. Notice that the first input now has an onchange event which is called anytime an input(any type) is changed. The reason the name input is now a  element is because it allows us take advantage of the selectedIndex variable, but it is cleaner semantically and will only register a "change" when one of the complete values is selected.
options += '<option value="defualt">Choose a Name</option>';

This is the default option that is seen when the page loads. It prevents the problem that if the user actually wanted to select the first option 'david.a.onezine', but it would not be registered as an actual change.
function getNumber(){
    var index = document.getElementById('customer').selectedIndex;

    if(index == 0){
        document.getElementById('phone').value = "";
    } else {
        document.getElementById('phone').value = phone[index-1];
    }
  }

Here is the function that is called anytime the selection list is changed. First the selected item is retrieved via the internal variable selectedIndex. If index is equal to 0 then that means the "default" value was selected and the phone input is set to an empty string, otherwise it will be set to phone[index-1] which is the number that belongs to whatever name was selected.
Edit:
Here is a modified version of getNumber() which will work with you code.
function getNumber(){
    var customervalue = document.getElementById('customerI').value;

    var i;
    var match = false;

    for(i = 0; i < arraylength; i++){
      if(customervalue == customer[i]){
        match = true;
        break;
      }
    }

    if(match == true){
      document.getElementById('phone').value = phone[i];
    } else {
      document.getElementById('phone').value = "";
    }
  }

Please note that a datalist is more for the perpose of auto-completion and so does not actually have an index or anything, but is meant for use by an input tag. Also the input must have an ID for getNumber() to work;
Comment: The function as it is will only work with a  tag(in this case customer). You could modify it to work with an input/datalist by doing the following `var customerval = document.getElementById('customer').value; var i; for(i = 0; i < arraylength; i++){ if(customerval == customer[i])break;` This would work. As for what event type you should use `onchange="getNumber()"` so it is only called when it is actually changed
Comment: Thanks a bunch, could I do the same thing with a datalist or does the datalist use a different index value?
Comment: It would work with your setup, however the change would not be registered until after the input lost focus and also you would have to check each value in the **customer** list to see if you find match
Comment: Should I use onblur = getNumber()? Ive been playing around with it and cant seem to get the second field to populate after selecting it. Ill keep playing around with it appreciate it.
Comment: Would this go into the getNumber() function?
Comment: I have edited the post above to include the getNumber() function and also added a few notes. This works with the datalist/input method.


Uploading multipile files using HTML file input

Question: i'm trying to upload a bunch of files using file type input with php i tried so far to make upload only one file and it worked the problem is that when i added [] to the name attribute it started to print Uploaded data error.
HTML
<form id="theform" action="upload.php" onsubmit="event.preventDefault(); return myFunction2();" method="post" enctype="multipart/form-data">
    <input id="file" name="uploadedFile[]" onchange="uptoserver();" style="display:none;"type="file" multiple>

            <button type="submit"  class="btn wbtn" style="font-family:Hana; font-size:18px; border:1px solid black !important;">
                 تكوين كشف
            </button>
            <button type="button" class="btn wbtn" style="font-family:Hana; font-size:18px; border:1px solid black !important;">
                 إضافة نموذج
            </button>

</form>

Javacript :
function myFunction2(){
    document.getElementById('file').click();
    console.log('reading form');
}

function uptoserver(){
    // var formscounter = parseInt(document.getElementById("counter").value);
    if(!document.getElementById("file").files.length == 0) {
        const form = document.getElementById('theform');
        form.submit();
        console.log('fucking working');
    }
}

upload.php

<?php
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo "Empty data, please select file";
    die;
}

if (!isset($_FILES["uploadedFile"])) {
    echo "Wrong data struct";
    die;
}

if ($_FILES["uploadedFile"]['error'] != 0) {
    echo "Uploaded data error";
    die;
}
$target_dir    = "uploads/";
$target_file   = $target_dir . basename($_FILES["uploadedFile"]["name"]);
$allowUpload   = true;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$maxfilesize   = 80000000;
$allowtypes    = array('jpg', 'png', 'jpeg', 'gif');

if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["uploadedFile"]["tmp_name"]);
    if($check !== false) {
        //
    } else {
        echo "This's not image file.";
        $allowUpload = false;
    }
}

if (file_exists($target_file)) {
    require "other\\fileExsist.php";
    $allowUpload = false;
}
if ($_FILES["uploadedFile"]["size"] > $maxfilesize) {
    require "other\\fileSize.php";
    $allowUpload = false;
}

if (!in_array($imageFileType,$allowtypes )) {
    require "other\\fileExtenstion.php";
    $allowUpload = false;
}

if ($allowUpload) {
    if (move_uploaded_file($_FILES["uploadedFile"]["tmp_name"], $target_file)) {
        //   echo "File ". basename( $_FILES["uploadedFile"]["name"]). " uploaded success.";
        //   echo $target_file;
        require "prepare.php";
        echo count($_FILES["uploadedFile"]);
    } else {
        echo "Error when upload file.";
    }
    // $total = count($_FILES['uploadedFile']['name']);

// // Loop through each file
// for( $i=0 ; $i < $total ; $i++ ) {

//   //Get the temp file path
//   $tmpFilePath = $_FILES['uploadedFile']['tmp_name'][$i];

//   //Make sure we have a file path
//   if ($tmpFilePath != ""){
//     //Setup our new file path
//     $newFilePath = "uploads/" . $_FILES['uploadedFile']['name'][$i];

//     //Upload the file into the temp dir
//     if(move_uploaded_file($tmpFilePath, $newFilePath)) {

//       //Handle other code here

//     }
//   }
// }
} else {
    echo "";
}
?>

Comment: Does this answer your question? [How can I select and upload multiple files with HTML and PHP, using HTTP POST?](https://stackoverflow.com/questions/1175347/how-can-i-select-and-upload-multiple-files-with-html-and-php-using-http-post)
Comment: You'd need to also modify the php so it loops through the list of uploaded files. You can't expect code which is only able to cope with one file to suddenly cope with several...it needs restructuring
Answer: Your original structure works perfectly fine because, when you're uploading a single file, line 18 is if ($_FILES["uploadedFile"]['error'] != 0), and this returns 0.
When you send through an array of files, even if a single file is sent, the uploadFile array is now an array of arrays, as below.
[_FILES] => Array
    (
        [uploadedFile] => Array
            (
                [name] => Array
                    (
                        [0] => funnyMusclePose.jpg
                    )

                [type] => Array
                    (
                        [0] => image/jpeg
                    )

                [tmp_name] => Array
                    (
                        [0] => C:\Development\wamp64\tmp\phpE949.tmp
                    )

                [error] => Array
                    (
                        [0] => 0
                    )

                [size] => Array
                    (
                        [0] => 735092
                    )

            )

    )

This means $_FILES["uploadedFile"]['error'] will always evaluate to true because it doesn't equal 0.
From here on out, you can wrap this entire function in a for() loop and iterate over each of the internal array items to get the data you're after, ie.
for($i = 0; $i < count($_FILES["uploadedFile"]["name"]); $i++) {
  if ($_FILES["uploadedFile"]['error'][$i] != 0)
  {
    echo "Uploaded data error";
    die;
  }
  $target_dir    = "uploads/";
  $target_file   = $target_dir . basename($_FILES["uploadedFile"]["name"][$i]);
  $allowUpload   = true;
  $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
  $maxfilesize   = 80000000;
  $allowtypes    = array('jpg', 'png', 'jpeg', 'gif');

  if(isset($_POST["submit"])) {
      $check = getimagesize($_FILES["uploadedFile"]["tmp_name"][$i]);
      if($check !== false)
      {
          //
      }
      else
      {
          echo "This's not image file.";
          $allowUpload = false;
      }
  }

  if (file_exists($target_file))
  {
      require "other\\fileExsist.php";
      $allowUpload = false;
  }
  if ($_FILES["uploadedFile"]["size"][$i] > $maxfilesize)
  {
      require "other\\fileSize.php";
      $allowUpload = false;
  }

  if (!in_array($imageFileType,$allowtypes ))
  {
      require "other\\fileExtenstion.php";
      $allowUpload = false;
  }

  // Add the rest of the code here
}


feynman lectures physics vol 1 chap 13 13-4 prove

Question: Hi guys I've recently into this Feynman's book and I have a question while reading it.
Last part of chap 13 he proves that

the force produced by the earth at a point on the surface or outside it is the same as if all the mass of the earth were located at its center.

Here's an url for image which he uses..
http://www.feynmanlectures.caltech.edu/img/FLP_I/f13-06/f13-06_tc_big.svgz
While proving that, he said

If we call $x$ the distance of a certain plane section from the center, then all the mass that is in a slice $dx$ is at the same distance $r$ from $P$, and the potential energy due to this ring is $−Gm′dm/r$. How much mass is in the small slice $dx$? An amount
  $dm=2\pi y\mu ds=\frac{2\pi y\mu dx}{\sin\theta}=\frac{2\pi y\mu dxa}{y}=2\pi a\mu dx$,
where $\mu=\frac{m}{4\pi a^2}$ is the surface density of mass on the spherical shell. (It is a general rule that the area of a zone of a sphere is proportional to its axial width.) Therefore the potential energy due to $dm$ is
  $dW=\frac{−Gm′dm}{r}=\frac{−Gm′2\pi a\mu dx}{r}$.
    But we see that
  $r^2=y^2+(R−x)^2=y^2+x^2+R^2−2Rx=a^2+R^2−2Rx$.

In this part I have some questions..
first how can I get $dm=2\pi y\mu ds=\frac{2\pi y\mu dx}{\sin\theta}=\frac{2\pi y\mu dxa}{y}=2\pi a\mu dx$ and $\mu = m/(4\pi a^2)$ ?
and secondly he sets $r^2=y^2+(R−x)^2$ but if theta exceeds $\pi/2$, then $r^2=y^2+(R+x)^2$
I have no idea how he ends up with

$W=\frac{Gm′2\pi a\mu}{R}\int_{R+a}^{R-a}dr=−Gm′2\pi a\mu\frac{2a}{R}=\frac{−Gm′(4\pi a2\mu)}{R}=\frac{−Gm′m}{R}$.

Could you explain these two things?
Comment: I hope you realize that you forgot to include a picture or some other explanation for many of the quantities. I've found them online, at http://www.feynmanlectures.caltech.edu/I_13.html
Comment: sorry I missed that.. I added right away :)
Answer: First question: $\mu$ is the surface density. The spherical shell has a mass $m$. The area of a sphere of radius $a$ is $4\pi a^2$. So $$\mu=\frac{m}{4\pi a^2}$$
Now we take a thin slice in this spherical shell, at distance $x$ from the center, and thickness $dx$ along this axis. You end up with something like a ring, but the side of the ring is tilted with respect to the axis of the ring. You can clearly see this in the figure. The radius of this ring is $y=a\sin\theta$. The thickness is $ds$, so the area is $2\pi y ds=2\pi a\sin\theta ds$. Like I've mentioned before, the side of the ring is tilted. $ds$ is perpendicular to the radius, so the tangent plane is making the an angle $90^\circ-\theta$ with respect to the horizontal(draw a horizontal at $ds$ and see). Then the projection on the horizontal axis is $dx=ds\cos(90^\circ-\theta)=ds\sin\theta$. Now putting it all together, the mass $dm$ of this ring is equal to the area multiplied by the surface mass density: $$dm=\mu2\pi yds=2\pi\mu a\sin\theta\frac{dx}{\sin\theta}=2\pi\mu a dx$$
Now for the second part: the distance between the center of the sphere and point $P$ is $R$. You are confused by the fact that it was not mentioned that $x$ is a signed quantity. It is positive for points in between the center of the spherical shell and the point $P$, but it is negative for points on the left of the center , in the figure. Those occur for $\theta\in(\pi/2,\pi]$. In your understanding $x$ is in fact $|x|$ from the lecture notes.
Let me know if anything else is unclear.
Comment: I got it! Thank you for your kind answer! :)
Comment: No problem. Glad to help


Why is square root taken for sample count "N" in standard deviation formula?

Question: I'm trying to understand a very basic concept of standard deviation.
From the formula $\sigma= \sqrt{ \dfrac{ \sum\limits_{i=1}^n (x_i-\mu)^2} N } $
I can't understand why should we halve the population "N"  i.e why do we want to take $\sqrt{N}$ when we didnt do ${N^2}$? Doesn't that skew the population that we are considering?
Shouldn't be the formula be $\sigma= \dfrac{ \sqrt{ \sum\limits_{i=1}^n (x_i-\mu)^2}  } {N} $
Answer: You're trying to find a "typical" deviation from the mean.
The variance is "the average squared distance from the mean".
The standard deviation is the square root of that.
That makes it the root-mean-square deviation from the mean.

Why would we use the average squared deviation? What makes variance
interesting? Among other things, because of a
basic fact about variances -
that the variance of a sum of uncorrelated variables is the sum of the individual variances. (This is covered in a number of
questions e.g. here
on CrossValidated. This handy feature is not shared, for example, by the mean absolute deviation.
Why take the square root of that? Because then it's in the same units as the original
observations. It measures a particular kind of 'typical distance' from the
mean (as mentioned, the RMS distance) - but because of the above property of variance - one that has
some nice features.
Answer: The standard deviation is the square root of the variance.
The variance is the average squared distance of the data from the mean.  Since an average is the sum divided by the number of items summed, the formula for the variance is:
$$
\text{Var}(X)=\text{E}[(X-\mu)^2] = \frac{\sum_{i=1}^N(x_i-\mu)^2}{N}
$$
Since, again, the standard deviation is simply the square root of this, the formula for the standard deviation is:
$$
\text{S.D.}(X)=\sqrt{\text{Var}(X)} = \sqrt{\frac{\sum_{i=1}^N(x_i-\mu)^2}{N}}
$$
Nothing has been added or changed about the assumptions or the variance here, we simply took the square root of the variance, because that's what the standard deviation is.
Comment: maybe it should be mentioned that this variance formula is only true for discrete uniforms. otherwise it might confuse the distinction between sample and population variance
Comment: @Taylor, I don't know what you mean. The formula for the variance is unrelated to the distribution.
Comment: the formula for (sample) variance is unrelated to the distribution (https://en.wikipedia.org/wiki/Expected_value#Definition)
Comment: @Taylor, I still don't know what you mean. The formula for the [variance](https://en.wikipedia.org/wiki/Variance#Definition) is unrelated to the distribution. To quote from the Wikipedia page, "The variance of a random variable, X, is the expected value of the squared deviation from the mean of X ... $\operatorname{Var}( X ) = E[(X − μ)^2]$. This definition encompasses random variables that are generated by processes that are discrete, continuous, neither, or mixed." The formula does not only hold for the discrete uniform.
Comment: Yes, that's right, if you take $\mu = EX$, but $E[(X-\mu)^2]$ does not necessarily equal, for any random variable $X$, $\frac{1}{N}\sum_i(x_i - \mu)^2$. For one, the first is a constant and the second is random. Actually it's not clear whether the sum runs over the support of $X$ or the number of samples. If the latter, it's weird that you know $\mu$, which is rare in practice. If the former, then yes, it's only true for discrete (because it's a sum) uniforms (because the weights are all uniform).
Comment: Also I personally try to stay away from using greek letters for moments. I prefer to use them for parameters of specific distributions, and stress that interpretations of parameters aren't always the moments. They are in the case of normals, but they aren't in the case of gammas, say.
Answer: First thing to understand is that standard deviation (std) is different than average absolute deviation. These two define different mathematical property about the data.
Unlike average absolute deviation, standard deviation (std) weighs more to the values that are far from mean, which is done by squaring the difference values.
E.g., For following four data points:     \begin{array}{|c|c|c|}
\hline
Data (x)& |x - mean| & (x-mean)^2 \\ \hline
 2 & 2 & 4\\ \hline
 -2  &2  &4\\ \hline
 -6  &6 &36\\ \hline
 6  &6 &36\\ \hline
\sum x =0 & \sum (|x-mean|) = 16 & \sum (x-mean)^2 = 80
\end{array}
average absolute deviation (aad) $= 16/4 = 4.0$, and
Standard deviation (std) = $\sqrt{80/4} = \sqrt 20 = 4.47 $
In the data, there are two points which are 6 distance away from mean, and two points which are 2 distance away from mean. So, deviation of 4.47 makes more sense than 4.
Since total observation are always $N$, for computing std we are not diving by $\sqrt N$, instead we divide the total variance by $N$, and take its square root, to bring it to the same unit as the original data.
Answer: I would agree that your definition of standard deviation $\sigma= \dfrac{ \sqrt{ \sum\limits_{i=1}^n (x_i-\mu)^2}  } {N} $ could be used to measure the spread of a population. However it is a harder concept to come up with. (And I think it is also harder to use to, for example, prove other theories.)
I don't know the exact history behind the invention of variance and standard deviation, but it should be roughly similar to:

We need a positive number to measure the spread; let us define variance = $\dfrac{ \sum\limits_{i=1}^n (x_i-\mu)^2} N $

This variance looks much bigger than the original values due to squaring; let us take square root of it to 'undo' the effect of squaring: $\sigma = \sqrt{\frac{\sum\limits_{i=1}^n (x_i-\mu)^2}{N}}$

So now we have a very simple relation $std = \sqrt{variance}$, hence $N$ is under square root.
Answer: @Mahesh Subramaniya - This is just mathematical twist.
When we have original value like $a/b = (-)d$. We can get same value using these two equations ${a}^2\diagup{b}=c$ and $\sqrt{c\diagup{b}}=d$.
E.g. just do it with ${-5}\diagup{2}$ = $-2.5$. But, we want only value not minus.
Now, ${-5}^2\diagup{2}=12.5$. And , $\sqrt{12.5\diagup{2}}=2.5$


UTF-8 & Unicode, what's with 0xC0 and 0x80?

Question: I've been reading about Unicode and UTF-8 in the last couple of days and I often come across a bitwise comparison similar to this :
int strlen_utf8(char *s)
{
  int i = 0, j = 0;
  while (s[i])
  {
    if ((s[i] & 0xc0) != 0x80) j++;
    i++;
  }
  return j;
}

Can someone clarify the comparison with 0xc0 and checking if it's the most significant bit ?
Thank you!
EDIT: ANDed, not comparison, used the wrong word ;)
Answer: It's not a comparison with 0xc0, it's a logical AND operation with 0xc0.
The bit mask 0xc0 is 11 00 00 00 so what the AND is doing is extracting only the top two bits:
    ab cd ef gh
AND 11 00 00 00
    -- -- -- --
  = ab 00 00 00

This is then compared to 0x80 (binary 10 00 00 00). In other words, the if statement is checking to see if the top two bits of the value are not equal to 10.
"Why?", I hear you ask. Well, that's a good question. The answer is that, in UTF-8, all bytes that begin with the bit pattern 10 are subsequent bytes of a multi-byte sequence:
                    UTF-8
Range              Encoding  Binary value
-----------------  --------  --------------------------
U+000000-U+00007f  0xxxxxxx  0xxxxxxx

U+000080-U+0007ff  110yyyxx  00000yyy xxxxxxxx
                   10xxxxxx

U+000800-U+00ffff  1110yyyy  yyyyyyyy xxxxxxxx
                   10yyyyxx
                   10xxxxxx

U+010000-U+10ffff  11110zzz  000zzzzz yyyyyyyy xxxxxxxx
                   10zzyyyy
                   10yyyyxx
                   10xxxxxx

So, what this little snippet is doing is going through every byte of your UTF-8 string and counting up all the bytes that aren't continuation bytes (i.e., it's getting the length of the string, as advertised). See this wikipedia link for more detail and Joel Spolsky's excellent article for a primer.

An interesting aside by the way. You can classify bytes in a UTF-8 stream as follows:

With the high bit set to 0, it's a single byte value.
With the two high bits set to 10, it's a continuation byte.
Otherwise, it's the first byte of a multi-byte sequence and the number of leading 1 bits indicates how many bytes there are in total for this sequence (110... means two bytes, 1110... means three bytes, etc).


Finding boundaries of a triple integral

Question:
Use cylindrical coordinates to find the volume of the solid that is inside the surface $r^2+z^2=20$ but not above the surface $z=r^2$.

My attempt:
$r^2\leq z\leq \sqrt{20-r^2}$ and the intersection of $r^2+z^2=20$ and $z=r^2$ is a circle $x^2+y^2=4$. Hence
$G=\{(r,\theta,z):0 \le r \le 2,0 \le \theta \le 2\pi, r^2 \le z \le \sqrt{20-r^2}\}$ and
$$Volume=\iiint_G dV=\int_0^2\int_0^{2\pi}\int_{r^2}^{\sqrt{20-r^2}} rdzd\theta dr$$
But According to solution the volumne consists of two portions, one inside the cylinder $r=2$ and one outside the cylinder:
$$V=\int_0^{2\pi}\int_0^{2}\int_{-\sqrt{20-r^2}}^{r^2} rdzdrd\theta+\int_0^{2\pi}\int_2^{\sqrt{20}}\int_{-\sqrt{20-r^2}}^{\sqrt{20-r^2}} rdzdrd\theta$$I couldn't visualize the volume. And how they got these limits$?$ Any help will be appreciated.
Thanks in advance.
Comment: Your set up seems fine to me, there is some wrong in the official solution or in the problem statement.
Comment: @user the official solutions are correct, have a look at the graph I've provided
Comment: @NinadMunshi Ah ok the volume "NOT ABOVE", I've misread this part and evaluated the "UP"! I fix accordingly.
Answer: Here is a picture in the $rz$-plane that might help.
As you can see, if one does the integral in the $z$ direction first, the integral must be split in two at the black line because we want the region below the paraboloid.
Comment: **the area not above the paraboloid** seems confusing to me. Because the enclosed volume is bounded by the sphere not the paraboloid.
Comment: @Dr.Antidode that is not true, the volume is enclosed by both as described by the problem.
Comment: Ah focusing your picture give me the answer. I should consider the whole volume under the paraboloid. Thanks @Ninad Munshi
Answer: The intersection is between a sphere and a paraboloid and we can evaluate the integral as a difference between the volume of the sphere and your set up for the part above the paraboloid that is
$$V=\frac43 \pi (\sqrt {20})^3-\int_0^{2\pi}d\theta\int_0^{2}rdr\int_{r^2}^{\sqrt {20-r^2}} dz$$
Comment: Agreed, but this is not other classes like Electromagnetism, this is multivariable calculus where the educational goal is to learn how to set up integrals. The symmetry is nice to *verify* answers in simple cases, and I have had students do this on multipart homeworks, but this way of thought leaves students high and dry for more complicated scenarios, and I would not indicate this as a good solution for that goal. It is precisely because the integrand doesn't matter that I feel it is dangerous to use it explicitly.
Comment: I wouldn't recommend symmetry approaches for triple integral problems. This does work in the case the integrand shares the same symmetry, but it would be a fair question to ask in a multivariable class to set up the integral for an arbitrary integrand $f(x,y,z)$ where this approach does not work.
Comment: @NinadMunshi In this case symmetry holds and it seems really the best approach to me.
Comment: This is simply my opinion after teaching multivariable for many years. It's kind of like using L'Hopital in a calculus one class when the instructor clearly wanted students to not use it, for example limits that look like $e$ or $\frac{\sin x}{x}$. The point is not to get the answer, but to learn how to set up the problems in specific ways, in this case cylindrical coordinates integrals. And this symmetry falls into the same category of learning traps.
Comment: @NinadMunshi I respect your opinion based on direct experience but for my experience I know that in other classes these kind of approach by symmetry are indicated as good solutions.More over here it seems to me that symmetry is not the key point, we are just avoiding one integarl using the well known formula for the volume of the sphere. it doesn't seem so bad to me.
Comment: @NinadMunshi Nice can hear these suggestions from you. Thanks a lot! Bye

Finding boundaries of a triple integral


Drupal 7 IMCE image paths

Question: I develop sites on my server then move them when ready. I just started using IMCE and everything works well other than the image path. For instance:
The path shows /test/sites/default/files/images/test.png however I want /sites/default/files/images/test.png so when I move the site I don't have to redo all the images.
I set the rewrite in the .hataccess file and I set the base url in settings.php. Is there something else I need to set?
Answer: If you develop your site in a sub folder, rather than a subdomain, you are going to be in for a bad time. All of your image paths and links are going to be incorrect. You are better of moving to a subdomain instead. If its already too late then use the Pathologic module to clean them up.

Pathologic is an input filter which can correct paths in links and
  images in your Drupal content in situations which would otherwise
  cause them to "break;" for example, if the URL of the site changes, or
  the content was moved to a different server. Pathologic can also solve
  the problem of missing images and broken links in your site's RSS
  feeds.

Drupal 7 IMCE image paths


XCode Tests keep failing

Question: I'm trying to run tests for my app, i'm able to get to a point where it launches the app in the simulator, but then gives this error and all tests fail:
2014-05-23 12:49:30.276 App[20472:60b] Cannot find executable for CFBundle 0xd04e190 </Users/Kalyan/Library/Developer/Xcode/DerivedData/App-gkggxfqpxbiszkbmoqpwtzlklpem/Build/Products/Debug-iphonesimulator/AppTests.octest> (not loaded)
IDEBundleInjection.c: Error loading bundle '/Users/Kalyan/Library/Developer/Xcode/DerivedData/App-gkggxfqpxbiszkbmoqpwtzlklpem/Build/Products/Debug-iphonesimulator/AppTests.octest'

I'm not sure what the issue is, but I have read many forums on this. Seems like its some sort of configuration issue but i'm not able to put a finger on it.
Some people mentioned in the simulator going to Simulator > Reset Content & Settings, but that didn't help.
I have tried reading the below to no avail:
Cannot find executable for CFBundle CertUIFramework.axbundle
https://github.com/kif-framework/KIF/issues/310
https://groups.google.com/forum/#!msg/rubymotion/_tcikfIkPNo/oIp9oCrZzcwJ
Is there anything else I haven't tried?
Answer: This took me forever to figure out, but just in case somebody else is having this issue, goto the project settings, and then click on the Tests project.
Goto Build Settings. Search for Wrapper Extensions under Packaging. Make sure it's the appropriate one. Currently it should be xctest.

XCode Tests keep failing


LWJGL .OBJ File reader sometimes disforming or not rendering the file

Question: I am working on a game with some friends, and to make life easier I decided all out 3D models are going to be made using .obj files, exported in programs like 3DSMax, Maya, and Blender3D.
So I have written a .obj file reader and tried it out in a simple scene, some .obj files rendered good (like a simple cube), some rendered really strangely, and then some didn't render at all. I was hoping someone could point out to me what I did wrong, the following code contains one class, with 2 embedded classed, one of which contains another embedded class. It  may get confusing, so you can copy and paste into a file for easier reading if needed.
The script reads line by line in the file and if it starts with "v" (vertex) it splits the line by space, and takes index 1 2 and 3 (x y and z) and stores the integer values in a class called Vertex, and adds it to an array of Vertex objects. a Vertex object acts just like a vector, only it contains two vectors, one for position, and one for the normals.
If the line starts with "vn" (Vertex Normal) it splits the line by " " and takes the indexes 1 2 and 3 and adds then to a Vertex object, which acts just like a vector so far, and then that Vertex is added to a different Vertex array specifically for normals.
Now here is the interesting part, when the line starts with "f" (Face) the line might look like:
f 1//3 5//3 6//1 2//4

each #1//#2, #1 is the index of the correct vertex, and #2 is the index for the proper normal. So I take each part of the line, splitted by " " and split it by "//" and took the vertex from the vertices array and the vertex from the normals array, set the vertices normals to the x y and z of the normal, made a Face object, and added it to a list of faces, which faces just hold 3 or 4 Vertex objects.
Hopefully this explaination might make the file not seem as messy.
Well, here is the code:
package org.ic3d.utils;

import java.io.*;
import org.ic3d.utils.ObjReader.Face.FaceStateException;
import org.lwjgl.opengl.GL11;

public class ObjReader
{
    public ObjReader(String file)
    {
        try
        {
            BufferedReader reader = new BufferedReader(new FileReader(new File(file)));
            parse(reader);
        }
        catch(Exception e)
        {
            System.out.println(file+" Failed To Load! Can't continue.");
            System.exit(0);
        }
    }

    /**
     * Parse all lines in the BufferedReader to convert the .obj file
     *
     * @param br - A BufferedReader object pointing to the desired .obj file
     * @throws IOException If the obj file can not be read for any reason.
     * @throws FaceStateException If the obj file is malformed and vertice are added to a face of different shape (tri - quad)
     */
    public void parse(BufferedReader br) throws IOException, FaceStateException
    {
        String s="";

        Vertex[] v1 = new Vertex[15000];
        Vertex[] n1 = new Vertex[15000];

        while((s = br.readLine())!=null)
        {
            if(s.startsWith("v"))
            {
                String[] pv = s.split(" ");

                Vertex vert_0x = new Vertex(Float.parseFloat(pv[1]), Float.parseFloat(pv[2]), Float.parseFloat(pv[3]));

                v1 = appendVert(v1, vert_0x);
            }
            if(s.startsWith("vn"))
            {
                String[] pv = s.split(" ");

                Vertex vert_0x = new Vertex(Float.parseFloat(pv[1]), Float.parseFloat(pv[2]), Float.parseFloat(pv[3]));

                n1 = appendVert(n1, vert_0x);
            }
            if(s.startsWith("f"))
            {
                String[] pv = s.split(" ");

                Vertex[] temp = new Vertex[pv.length-1];

                for(int i=1;i<pv.length;i++)
                {
                    String[] vn = pv[i].split("//");

                    Vertex v = v1[Integer.parseInt(vn[0])];

                    Vertex n = n1[Integer.parseInt(vn[1])];

                    v.setNormals(n.getX(), n.getY(), n.getZ());

                    temp = appendVert(temp, v);
                }
                try
                {
                    Face f = new Face(temp.length==3?Face.GL_FACE_TRI:Face.GL_FACE_QUAD, temp);
                    faces = appendFace(faces, f);
                }
                catch(FaceStateException e)
                {
                    throw e;
                }
            }
        }
    }
    private Vertex[] appendVert(Vertex[] l, Vertex v)
    {
        for(int i=0;i<l.length;i++)
        {
            if(l[i]==null)
            {
                l[i] = v;
                return l;
            }
        }
        System.out.println("Vertex[] can only hold "+l.length+" Vertices at one time");
        return l;
    }
    private Face[] appendFace(Face[] l, Face f)
    {
        for(int i=0;i<l.length;i++)
        {
            if(l[i]==null)
            {
                l[i] = f;
                return l;
            }
        }
        System.out.println("Face[] can only hold "+faces.length+" Faces at one time");
        return l;
    }
    public void renderTri(Face f, float x, float y, float z)
    {
        Vertex[] v = f.getVerts();

        GL11.glBegin(GL11.GL_TRIANGLES);

        Vertex cv = v[0];
        GL11.glNormal3f(cv.getNormalX(), cv.getNormalY(), cv.getNormalZ());
        GL11.glVertex3f(x+cv.getX(), y+cv.getY(), z+cv.getZ());

        cv = v[1];
        GL11.glNormal3f(cv.getNormalX(), cv.getNormalY(), cv.getNormalZ());
        GL11.glVertex3f(x+cv.getX(), y+cv.getY(), z+cv.getZ());

        cv = v[2];
        GL11.glNormal3f(cv.getNormalX(), cv.getNormalY(), cv.getNormalZ());
        GL11.glVertex3f(x+cv.getX(), y+cv.getY(), z+cv.getZ());

        GL11.glEnd();
    }
    public void renderQuad(Face f, float x, float y, float z)
    {
        Vertex[] v = f.getVerts();

        GL11.glBegin(GL11.GL_QUADS);

        Vertex cv = v[0];
        GL11.glNormal3f(cv.getNormalX(), cv.getNormalY(), cv.getNormalZ());
        GL11.glVertex3f(x+cv.getX(), y+cv.getY(), z+cv.getZ());

        cv = v[2];
        GL11.glNormal3f(cv.getNormalX(), cv.getNormalY(), cv.getNormalZ());
        GL11.glVertex3f(x+cv.getX(), y+cv.getY(), z+cv.getZ());

        cv = v[2];
        GL11.glNormal3f(cv.getNormalX(), cv.getNormalY(), cv.getNormalZ());
        GL11.glVertex3f(x+cv.getX(), y+cv.getY(), z+cv.getZ());

        cv = v[3];
        GL11.glNormal3f(cv.getNormalX(), cv.getNormalY(), cv.getNormalZ());
        GL11.glVertex3f(x+cv.getX(), y+cv.getY(), z+cv.getZ());

        GL11.glEnd();
    }
    public void render(float x, float y, float z)
    {
        GL11.glPushMatrix();
        for(Face f : faces)
        {
            if(f==null)
            {
                GL11.glPopMatrix();
                return;
            }
            else
            {
                switch(f.getType())
                {
                    case(3):
                    {
                        renderTri(f, x, y, z);
                    }
                    case(4):
                    {
                        renderQuad(f, x, y, z);
                    }
                }
            }
        }
        GL11.glPopMatrix();
    }
    public int listid=0;
    public Face[] faces = new Face[15000];
    public class Face
    {
        /**
         * Create a new Face object, Faces Hold 3 or 4 Vertex Objects, Polygons not accepted.
         * @param shape
         * @param verts
         * @throws FaceStateException - If the number of vertice in the Vertex[] is not equal to the face type set.
         */
        public Face(int shape, Vertex[] vertlist) throws FaceStateException{

            int vert_n = GL_FACE_NONE-shape;

            if(vertlist.length>vert_n)
            {
                throw new FaceStateException(vert_n+" Vertice faces can not hold "+verts.length+" vertices");
            }
            if(vertlist.length<vert_n)
            {
                throw new FaceStateException(vert_n+" Vertice faces must hold "+vert_n+" vertice, not "+verts.length+" vertices");
            }
            if(vert_n!=3 && vert_n!=4)
            {
                throw new FaceStateException("Faces can only be 3 or 4 vertice. Shapes besides QUAD and TRI are not allowed.");
            }
            type=vert_n;

            verts=vertlist;
        }
        public Vertex[] getVerts()
        {
            return verts;
        }
        public int getType()
        {
            return type;
        }
        public String getType(int i)
        {
            if(i==1)
            {
                return(type==3?"TRI":"QUAD");
            }
            else
            {
                return(type==3?"TRIANGLE":"QUAD");
            }
        }
        private Vertex[] verts;
        public static final int GL_FACE_QUAD = 3;
        public static final int GL_FACE_TRI = 4;
        public static final int GL_FACE_NONE = 7;
        private int type=7;
        public class FaceStateException extends Exception
        {
            public FaceStateException(String s)
            {
                super(s);
            }
            private static final long serialVersionUID = 1L;
        }
    }
    public class Vertex
    {
        public Vertex(float x, float y, float z)
        {
            _x=x;
            _y=y;
            _z=z;
        }
        public void setNormals(float x, float y, float z)
        {
            _nx=x;
            _ny=y;
            _nz=z;
        }
        public float getX()
        {
            return _x;
        }
        public float getY()
        {
            return _y;
        }
        public float getZ()
        {
            return _z;
        }
        public float getNormalX()
        {
            return _nx;
        }
        public float getNormalY()
        {
            return _ny;
        }
        public float getNormalZ()
        {
            return _nz;
        }
        public float[] getNormalXYZ()
        {
            return new float[]{_nx, _ny, _nz};
        }
        public void setXYZ(float x, float y, float z)
        {
            _x=x;
            _y=y;
            _z=z;
        }
        public float[] getXYZ()
        {
            return new float[]{_x, _y, _z};
        }
        private float _x;
        private float _y;
        private float _z;
        private float _nx;
        private float _ny;
        private float _nz;
    }
}

Comment: I don't know if you've experienced this, but when using your code, I had to decrement the index lookups when building the faces in order to get this to work.
Answer: I believe it's fairly simple fix, GL11.glEnd() is really not needed, you can start another render type using begin, without even ending it first. Try cutting the GL11.glEnd() to the end of your entire render script, see if that helps any:
public void render()
{
    Object1.render( 5, 0, 5);
    Object1.render(-5, 0,-5);
    Object2.render( 5, 0,-5);
    Object2.render(-5, 0, 5);
    GL11.glEnd();
}

Comment: thank you, that helped a lot, I was hoping I could end it inside the method though, but I didn't know I could start rendering trigons right from quads and vise-versa. thank you.


Checking Uniform Convergence

Question: Question:
Prove that the sequence of functions $f_n(x) = x^n$ converges uniformly to zero on any interval of the form $[0,\mu]$ if $\mu < 1$.
My Work:
Recalling the definition of uniform convergence, we say that $f_n(x) \to 0$ uniformly if $$\forall\epsilon>0 \ \exists N \ \forall n \ge N \ \forall x \in \mathrm{Dom}\,(f) \ \Big[\left|f_n(x) - 0 \right|\le \epsilon \Big] $$
Since $x \in [0,\mu]$, we have $x \le \mu \Rightarrow \left| f_n(x) -f(x) \right| \le \mu^N$. We want $\mu^N \le \epsilon$ for some large $N$, so taking the natural logarithm of the inequality, which we can do because the natural log is monotone increasing for $x >0$, we have $$ \mu^N \le \epsilon \Rightarrow N \ln \mu \le \ln \epsilon $$ Since $\mu, \epsilon < 0$ for $\epsilon$ sufficiently small, $\ln \mu, \ln \epsilon < 0$. So the inequality becomes $$ N \ge {\ln \epsilon \over \ln \mu}$$
This makes sense to write because ${\ln \epsilon \over \ln \mu}$ is a positive number, so we can always take $N \ge {\ln \epsilon \over \ln \mu}$.
My Question: How do I incorporate this $N$ into an appropriately worded proof? I know it would go along the lines of "Taking $N \ge {\ln \epsilon \over \ln \mu}$, we have $$ \mu^N - 0 \le \mu^{{\ln \epsilon \over \ln \mu}}  $$ By virtue of my previous calculation, I know this should be less than $\epsilon$, but I am not sure how to perform the necessary algebra. Its a small, but crucial detail.

Edit:
Thanks to Nate Eldrege, who pointed out that $a^b = \exp(b \ln a)$. So we have $$ \mu^{{\ln \epsilon \over \ln \mu}} = \mu ^{\ln(\epsilon - \mu)} = e^{\ln(\epsilon - \mu)}e^{\ln \mu} = \epsilon $$ So as required for any $n \ge N$,  where the value of $N$ is given above, we have $\mu^N - 0 \le \epsilon$.
Comment: Hint: $a^b = \exp(b \ln a)$.
Comment: I'd show uniform convergence differently: $f_n \to f$ uniformly means that $\|f-f_n\|_\infty \to 0$ means that $$\max_{x \in [0, \mu]} |f_n(x) - f(x)| \to 0$$

In this case, since $f=0$, this means that $$\max_{x \in [0, \mu]} |f_n(x) | \xrightarrow{n \to \infty} 0$$

To show this you need to find the extremal points of $f_n$. Since there are none with zero slope and since you know what $x^n$ looks like you see that there is one maximum on $[0, \mu]$ at $\mu$.
Comment: @Matt http://xkcd.com/105/
Comment: Remember that you solved $\mu^N = \epsilon$ to get this form of $N$. You should be able to go back again.
Comment: (continued) But then $\|f_n\|_\infty = \max_{x \in [0, \mu]} |f_n(x) | = \mu^n \xrightarrow{n \to \infty} 0$ since $\mu \in [0,1)$ which shows the claim.
Comment: And +1 for showing your work.
Comment: @Matt How confusing. I was about to post exactly what you wrote as an answer, but then realized you (me?!) already did it.
Comment: @Matt : ) Do you think I should make my comment into an answer? (Then one can see the avatar and confusion will be sorted.) I did not do that since it does not answer the question.
Answer: Seeing as I have found my answer, and this question needs no more work, I am posting Nate Eldredge's hint as an answer and accepting it so that this question moves off the "Unanswered" list:
Nate Eldredge: "Hint: $a^b = \exp(b \ln a)$"
Comment: But it will only let me accept my own answer in 2 days as I have just found out, so if someone posts an answer before then I'll accept it.

Checking Uniform Convergence


Idling Resource not working in second activity in android

Question: I have two Activities A and B. I am running a background thread for 500ms and update a TextView. Once the TextView is updated, I click on the TextView to go to B Activity. In Activity B I have another background thread which is running for 500ms and update a TextView in the B Activity. I am testing this flow using Espresso. I wait for the background thread to complete the execution using Idling Resource. I am facing a problem on using Idling Resource in B Activity. I have put down my code below:
MainActivityTest.java:
@RunWith(AndroidJUnit4.class)
@LargeTest
public class MainActivityTest {
    @Rule
    public ActivityTestRule<MainActivity> mainActivityActivityTestRule = new ActivityTestRule<>(MainActivity.class);

    private IdlingResource mIdlingResource;

    @Before
    public void registerIdlingResource(){
        mIdlingResource = mainActivityActivityTestRule.getActivity().getIdlingResource();
        // To prove that the test fails, omit this call:
//        Espresso.registerIdlingResources(mIdlingResource);
        IdlingRegistry.getInstance().register(mIdlingResource);
    }

    @Test
    public void mainScreenLoads(){
        onView(withId(R.id.my_text)).check(matches(ViewMatchers.withText("Boom")));
        onView(withId(R.id.my_text)).perform(click());
        onView(withId(R.id.second_text)).check(matches(ViewMatchers.withText("Boom")));
    }

    @After
    public void unregisterIdlingResource() {
        if (mIdlingResource != null) {
//            Espresso.unregisterIdlingResources(mIdlingResource);
            IdlingRegistry.getInstance().unregister(mIdlingResource);
        }
    }
}

A Activity:
public class MainActivity extends AppCompatActivity {

    CountingIdlingResource countingIdlingResource = new CountingIdlingResource("DATA_LOADER");

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

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

        countingIdlingResource.increment();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    Thread.sleep(500);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ((TextView)findViewById(R.id.my_text)).setText("Boom");
                        ((TextView)findViewById(R.id.my_text)).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                Intent intent = new Intent(MainActivity.this,SecondActivity.class);
                                startActivity(intent);
                            }
                        });
                        countingIdlingResource.decrement();
                    }
                });
            }
        }).start();
    }

    /**
     * Only called from test, creates and returns a new {@link SimpleIdlingResource}.
     */
    @VisibleForTesting
    @NonNull
    public IdlingResource getIdlingResource() {
        return countingIdlingResource;
    }
}

B Activity:
public class SecondActivity extends AppCompatActivity {

    CountingIdlingResource countingIdlingResource = new CountingIdlingResource("DATA_LOADER");

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

    @Override
    protected void onResume() {
        super.onResume();
        countingIdlingResource.increment();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    Thread.sleep(500);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ((TextView)findViewById(R.id.second_text)).setText("Boom");
//                        if (mIdlingResource != null) {
//                            mIdlingResource.setIdleState(true);
//                        }
                        countingIdlingResource.decrement();
                    }
                });
            }
        }).start();
    }
}

I am getting below error:
android.support.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: 'with text: is "Boom"' doesn't match the selected view.
Expected: with text: is "Boom"
Got: "AppCompatTextView{id=2131165282, res-name=second_text, visibility=VISIBLE, width=246, height=51, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=android.widget.LinearLayout$LayoutParams@94bfcec, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, text=Second Screen, input-type=0, ime-target=false, has-links=false}"

at dalvik.system.VMStack.getThreadStackTrace(Native Method)
at java.lang.Thread.getStackTrace(Thread.java:1566)
at android.support.test.espresso.base.DefaultFailureHandler.getUserFriendlyError(DefaultFailureHandler.java:90)
at android.support.test.espresso.base.DefaultFailureHandler.handle(DefaultFailureHandler.java:52)
at android.support.test.espresso.ViewInteraction.waitForAndHandleInteractionResults(ViewInteraction.java:314)
at android.support.test.espresso.ViewInteraction.check(ViewInteraction.java:291)
at com.example.sagarsuri.rxjavademo.MainActivityTest.mainScreenLoads(MainActivityTest.java:47)

Answer: You can use singleton class and control the idling resource from there.
class EspressoKIdlingResource {
companion object {
    val countingIdlingResource = CountingIdlingResource("data_loaded")

    fun getInstance() : CountingIdlingResource{
        return countingIdlingResource
    }

    fun increment(){
        countingIdlingResource.increment()
    }

    fun decrement(){
        countingIdlingResource.decrement()
    }
}

Answer: The reason is that you have two different CountingIdlingResource instances in both activties, and only one from Activity A was registered. You should implement the same method for returning IdlingResource in Activity B and use this answer to get correct Activity while running test.


Is it okay to use azure functions simply for API calls

Question: Requirements:

A time triggered background process to insert a record to a database table.
Runs over 10,000 requests every 00:00 (midnight)
Individual requests wouldn't last 1-2 seconds

We are planning to use two azure functions for this, steps below:

The 1st Azure Function (time triggered), runs a query then insert records to an azure storage queue.
New queue items will be picked up the 2nd Azure Function (queue trigger)

QUESTION: Is it okay to use Azure Function purely for API calls? for functions mentioned in 1. and 2. they would call an api, which contains the domain layer for select and insert operations.
Architecture looks like this:
Azure Function -> (http call) -> Api -> Application Service -> Domain Layer -> Data Layer

My thoughts are, functions won't be able to scale since the load will just be transferred to the api, not unless the api also scales with some sort of load balancing
Comment: The queue trigger will call the api?
Comment: @SaeedEsmaeelinejad Yes. Eventually
Comment: I think it's a backend-to-backend scenario and it's not needed to call api.  So if you want to use azure function you can use the application service directly or even you don't need azure function and just use something like Hangfire and schedule tasks.
Answer: Yes, you can build and customize an API on Azure Functions.
If you are using the C# language function app, you can create the HttpClient object to make HTTP calls from Azure function.
You can use any of the supported triggers to trigger your function app, and your function app will make the HTTP calls or the api calls.
As per Microsoft-Documentation  it says,

Azure Functions integrates with Azure API Management in the portal to let you expose your HTTP trigger function endpoints as REST APIs. These APIs are described using an OpenAPI definition.
Azure Functions integrates with Azure API Management in the portal to let you expose your HTTP trigger function endpoints as REST APIs.

Scale an Azure Function to handle 10,000+ requests per second.
Here are some blogs which might give an overview of handling 10000+ requests.
Scaling Azure Functions to make more requests
https://learn.microsoft.com/en-au/azure/load-testing/overview-what-is-azure-load-testing?WT.mc_id=DT-MVP-5001664
For further refer SO_thread and MSDN-Example for more details.


Difference between quantiles

Question: As far as I understood from its definition, quantile borders should divide a dataset into equal parts (or at least into almost equal parts, if the dataset doesn't have enough entries or has an odd number of elements). I used pandas function quantile to get quartiles from my dataset:
tquantiles = rawData['t'].quantile([0.25,0.5,0.75])

Output shows quantile border values:
0.25    -3.1
0.50     6.7
0.75    15.6
Name: t, dtype: float64

rawData is a result of a SQL query:
rawData = sqlio.read_sql_query('SELECT * ' +
'FROM cards ' +
'INNER JOIN weather ' +
'on ceil_time_3h(event_date) = weather.datetime', conn)

So, assuming that quantiles are equal, I try to compare the amount of objects between named values:
SELECT count("t") AS "25" FROM cards
INNER JOIN weather
on ceil_time_3h(event_date) = weather.datetime
WHERE t >= 15.6;

This is for the top 25%. Changing values, I selected quartiles, including the left border. Those values are not equal: 128829, 130150, 130250, 130266 for below 25%, 50%, 75% and above 75% respectively. Moreover, the sum of those counts is less than the number of elements in the dataset.
How do the quantiles differ from each other in my case? Why does the sum differ from the number of elements in the dataset?
Comment: It seems that your data are measured with resolution 0.1 and that the range is at least 18.7. My guess given the mention of "weather": Celsius temperatures.  Let's guess range 50: the tails beyond the quartiles are often longer than the difference between the quartiles.. That means of the order of 500 distinct values. It seems that your sample size is of the order of 500000, so on average each distinct value occurs about 1000 times, and ties are everywhere. It's also entirely possible that your data are quirkier than that if human readings are involved. Ties are likely to be the issue.
Comment: @NickCox you're absolutely right, it's temperature measured in celsius degrees with 568 distinct values, so I think ties are really issue in my case. Could you please post an answer, so I could accept it?
Comment: Why don't you use the window function `NTILE` directly? Anyway, I think this question is off-topic per our [FAQ](https://stats.stackexchange.com/help/on-topic).
Comment: Are you sure that your code is doing what you think it is? One way to check would be to try in another piece of software. For example, you could try this in R, or in Excel (assuming you are running a recent enough version that can cope with the number of rows!). Are your values of 't' integers?
Comment: It would be interesting to compare the result of your query for `WHERE t >= 15.6` to the result of the query `WHERE t > 15.6`: how do those two counts differ?
Answer: It seems that your data are measured with resolution 0.1 and that the range is at least 18.7. My guess given the mention of "weather" is that they are Celsius temperatures.
Let's guess that the variable has a range 50 in those units: the tails beyond the quartiles are often longer than the difference between the quartiles. That would mean of the order of 500 distinct values.
It seems that your sample size is of the order of 500000, so on average each distinct value occurs about 1000 times, and ties are everywhere.
It's also entirely possible that your data are quirkier than that if human readings are involved. Many observers use some final digits rather than others, although the quirks can vary, including preferences for 0 and 5 as final digits or for even digits.
Ties are likely to be the issue, together with a rule that the same values must be assigned to the same bin.

Difference between quantiles


how to update values in database where date = systemdate

Question: I have created a database application in C#. The program send automatically system date when it open. I have given this code to loading.
SqlCommand cmd = new SqlCommand(@"INSERT INTO summery_data
                         (date, total_h, work_h, delay_h, tfif, tth, th)
VALUES        (GetDate(),'','','','','','')", con);

so now I want to Update other values of the the table according to the date in database.
ex:-
SqlCommand cmd = new SqlCommand(@"UPDATE       summery_data
SET                tth ='" + test + " ' WHERE       date = '?????????????')", con);

the date should be Today system date;
Please help me to do that...!
Comment: You should have a tag related to sql.
Comment: Use `DateTime dt = DateTime.Now` , and use `dt.Day` , `dt.Month` , `dt.Year`
Answer: Assuming date column is a data type date and not datetime, you could strip off the time stamp from GetDate() to get an accurate match..
Update summary_data
Set tth = 'blah'
Where date = DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)
If the data type is a datetime then you can strip off the time stamp for both date and getdate() to get an accurate match..
Update summary_data
Set tth = 'blah'
Where DATEADD(dd, DATEDIFF(dd, 0, date), 0) = DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)


Simple Spring integration UDP example does not respond or release client

Question: I made a simple Spring Boot project to listen for UDP transmissions and save the results.  For the purposes of this question I will just have the handler print out the input.
Here is the configuration bean:
package com.wheresjim.udp.config

import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.integration.dsl.IntegrationFlow
import org.springframework.integration.ip.udp.UnicastReceivingChannelAdapter

@Configuration
class UdpConfig {

    private Integer port = 6767

    @Bean
    IntegrationFlow processUdpMessage() {
        IntegrationFlow
                .from(new UnicastReceivingChannelAdapter(port))
                .handle("udpService", "receive")
                .get()
    }
}

Here's the handler:
package com.wheresjim.udp.service

import org.springframework.messaging.Message
import org.springframework.stereotype.Component;

@Component
class UdpService {

    void receive(Message message) {
        String data = new String((byte[]) message.getPayload())
        System.out.print(data)
    }
}

Here's the client:
DatagramSocket socket = new DatagramSocket()
InetAddress address =  InetAddress.getByName('localhost')

String sendUDP(String msg, address, socket) {
    byte[] buf = msg.getBytes()
    println msg.getBytes().length
    DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 6767)
    socket.send(packet)
    packet = new DatagramPacket(buf, buf.length)
    socket.receive(packet)
    String received = new String(packet.getData(), 0, packet.getLength())
    return received
}

String testMsg = '<?xml version="1.0" encoding="UTF-8"?><TestMsg><Text>Hello World</Text></TestMsg>''

try {
    sendUDP(testMsg, address, socket)
} catch (Exception e) {
    e.printStackTrace()
} finally {
    socket.close()
}

When I send a message, it is received and displayed correctly.  However there is not an acknowledgment or reply sent to the client.  As such the client just hangs and I have to restart to send another message.  How can I get this to send a simple reply to allow multiple messages to be sent?
Please note, the language used is Groovy
Comment: What do you expect to be sent to that `socket.receive(packet)`  receive operation if you really don't send anything from the server side?
Comment: The response content doesn't really matter at this point, for the purpose of this question, it can be 'OK'
Comment: Right. But you even don't send that `OK` from the server. See `UnicastSendingMessageHandler` for that purpose: https://docs.spring.io/spring-integration/docs/current/reference/html/ip.html#outbound-udp-adapters-java-dsl-configuration
Comment: Specifically, see the documentation about how to configure application-level acks in the sending adapter https://docs.spring.io/spring-integration/docs/current/reference/html/ip.html#outbound-udp-adapters-xml-configuration `>The second reliability improvement allows an application-level acknowledgment protocol to be used. The receiver must send an acknowledgment to the sender within a specified time.` If you want to use your own client, you would have to emulate the encoding of the return information the adapter uses. See `DatagramPacketMessageMapper` for how that info is encoded in the packet
Comment: Or, as @ArtemBilan said, just send your own ack - configure the outbound adapter to use the same socket.
Answer: Thanks to the help from Artem and Gary, I was able to put together a simple solution.  I added a method to my UDPService that ACKs the incoming message, and I call it when I am finished processing the input:
void ackUdp(Message message) {

    String ackMessage = ''
    DatagramPacket ackPacket = new DatagramPacket(
            ackMessage.getBytes(),
            ackMessage.length(),
            InetAddress.getByName(message.getHeaders().get('ip_address')),
            message.getHeaders().get('ip_port')
    )

    DatagramSocket socket = new DatagramSocket()

    try {
        socket.send(ackPacket)
    } catch (Exception e) {
        e.printStackTrace()
    } finally {
        socket.close()
    }
}


Make SwiftUI document available as EnvironmentObject

Question: I am reading a FileDocument using SwiftUI. This document is available though a binding to the top-most view:
struct ContentView: View {
    @Binding var document: SomeDocument
    var body: some View {
        Text(self.document.someString)
        NestedChildViews().environmentObject(self.document)
    }
}

Is there are a way to turn this @Binding of the document into an @EnvironmentObject to make it available to all nested views? Simply replacing @Binding with @EnvironmentObject will not work, since FileDocument is a struct.
Property type 'SomeDocument' does not match that of the 'wrappedValue' property of its wrapper type 'EnvironmentObject'

Creating an in-between ObservableObject that is created as a @StateObject inside ContentView won't work, since it has to be initiated before the Binding to document is available:
struct ContentView: View {
    @Binding var document: SomeDocument
    @StateObject var sharedState = SomeSharedState(document: self.document) // won't work
}

What would be the best way to handle this in-between a document and a series of nested views without passing bindings between all levels of them?
Comment: what is SomeDocument and where it data come from?
Comment: Make sure `SomeDocument` conforms to `FileDocument` instead of `ReferenceFileDocument`. This will mean that your document is value based instead of reference based. After that you should be able to use `@Binding`.
Answer: You should initialize your @StateObject from within the view's init, since you are passing in the document into the init:
struct ContentView: View {

    @Binding var document: SomeDocument
    @StateObject var sharedState: SomeSharedState

    init(document: Binding<SomeDocument>) {
        _document = document
        _sharedState = StateObject(wrappedValue: SomeSharedState(document: document.projectedValue))
    }

    var body: some View {
        Text(document.someString)
            .environmentObject(sharedState)

            /* TEST TO SHOW IT WORKS
            .onAppear {
                DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
                    document = SomeDocument(someString: "New!")
                }
            }
            */
    }
}

class SomeSharedState: ObservableObject {
    @Published var document: Binding<SomeDocument>

    init(document: Binding<SomeDocument>) {
        _document = Published(initialValue: document)
    }
}


How to include an XAML icon in another XAML file

Question: I've downloaded the Visual Studio Image Library, which contains XAML icons. For example, this is the content of the file FolderClosed_16x.xaml:

<Viewbox Width="16" Height="16" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
  <Rectangle Width="16" Height="16">
    <Rectangle.Fill>
      <DrawingBrush>
        <DrawingBrush.Drawing>
          <DrawingGroup>
            <DrawingGroup.Children>
              <GeometryDrawing Brush="#00FFFFFF" Geometry="F1M0,0L16,0 16,16 0,16z" />
              <GeometryDrawing Brush="#FFF6F6F6" Geometry="F1M1.5,1L9.61,1 10.61,3 13.496,3C14.323,3,14.996,3.673,14.996,4.5L14.996,12.5C14.996,13.327,14.323,14,13.496,14L1.5,14C0.673,14,0,13.327,0,12.5L0,2.5C0,1.673,0.673,1,1.5,1" />
              <GeometryDrawing Brush="#FFEFEFF0" Geometry="F1M1.9998,3.0004L1.9998,4.0004 8.8738,4.0004 8.3738,3.0004z" />
              <GeometryDrawing Brush="#FFDBB679" Geometry="F1M2,3L8.374,3 8.874,4 2,4z M13.496,4L10,4 9.992,4 8.992,2 1.5,2C1.225,2,1,2.224,1,2.5L1,12.5C1,12.776,1.225,13,1.5,13L13.496,13C13.773,13,13.996,12.776,13.996,12.5L13.996,4.5C13.996,4.224,13.773,4,13.496,4" />
            </DrawingGroup.Children>
          </DrawingGroup>
        </DrawingBrush.Drawing>
      </DrawingBrush>
    </Rectangle.Fill>
  </Rectangle>
</Viewbox>

I've added this file to my project in Visual Studio. How do I use the icon in another XAML file? Pasting these lines inside my XAML file works as expected, but I'd like to keep all icon files in a directory and reference them in multiple places. Is this possible without modifying the icon files?
I'd like to use it like this in my MainWindow.xaml, but this doesn't work:
<ContentControl Template="{StaticResource Icons/FolderClosed_16x.xaml}" />

Comment: You have to add it to a resource dictionary and give it a x:Key then you can add it to the Content of the contentControl. eg. x:Key="MyViewBox" <ContentControl Content="{StaticResource MyViewBox}".  For more example, see here https://learn.microsoft.com/en-us/windows/apps/design/style/xaml-resource-dictionary
Comment: @NawedNabiZada Can you give an example of a resource dictionary that references an xaml file? The link you provided doesn't have such an example. Or am I misunderstanding it?
Comment: A resource dictionary is a xaml file.  But you can load a file isn't actually part of your project or compiled into it at run time.  Microsoft binned their technet gallery so the linked samples won't work but this describes one way to load an uncompiled xaml file off disk at run time. https://social.technet.microsoft.com/wiki/contents/articles/28797.wpf-dynamic-xaml.aspx
Answer: You should define the Viewbox as a type or resource.

Create new `UserControl´ (Project->Add user Control (WPF) in Visual Studio) called FolderClosed_16x.

Replace the contents of the FolderClosed_16x.xaml file with this:
 <Viewbox x:Class="WpfApp1.FolderClosed_16x"
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
          Width="16" Height="16">
     <Rectangle Width="16" Height="16">
         <Rectangle.Fill>
             <DrawingBrush>
                 <DrawingBrush.Drawing>
                     <DrawingGroup>
                         <DrawingGroup.Children>
                             <GeometryDrawing Brush="#00FFFFFF" Geometry="F1M0,0L16,0 16,16 0,16z" />
                             <GeometryDrawing Brush="#FFF6F6F6" Geometry="F1M1.5,1L9.61,1 10.61,3 13.496,3C14.323,3,14.996,3.673,14.996,4.5L14.996,12.5C14.996,13.327,14.323,14,13.496,14L1.5,14C0.673,14,0,13.327,0,12.5L0,2.5C0,1.673,0.673,1,1.5,1" />
                             <GeometryDrawing Brush="#FFEFEFF0" Geometry="F1M1.9998,3.0004L1.9998,4.0004 8.8738,4.0004 8.3738,3.0004z" />
                             <GeometryDrawing Brush="#FFDBB679" Geometry="F1M2,3L8.374,3 8.874,4 2,4z M13.496,4L10,4 9.992,4 8.992,2 1.5,2C1.225,2,1,2.224,1,2.5L1,12.5C1,12.776,1.225,13,1.5,13L13.496,13C13.773,13,13.996,12.776,13.996,12.5L13.996,4.5C13.996,4.224,13.773,4,13.496,4" />
                         </DrawingGroup.Children>
                     </DrawingGroup>
                 </DrawingBrush.Drawing>
             </DrawingBrush>
         </Rectangle.Fill>
     </Rectangle>
 </Viewbox>

Change the base type in FolderClosed_16x.xaml.cs to Viewbox:
 public partial class FolderClosed_16x : Viewbox
 {
     public FolderClosed_16x()
     {
         InitializeComponent();
     }
 }

Reference the control as usual from another view:
 <local:FolderClosed_16x />

Comment: Thank you! This works and answers the question. Since I'm new to WPF, I'm wondering if this is a good way to do it in your opinion. I didn't expect that I have to create a C# class for each icon.  Is there a simpler way to do it?
Comment: The other more common option is to define the `ViewBox` as a resource with an `x:Key` in a `ResourceDictionary`.
Answer: This is the solution that I ended up using. I have one xaml file in my project that contains all the icons and they all have an x:Key:
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Rectangle x:Key="FolderClosed" Width="16" Height="16" x:Shared="false">
        <Rectangle.Fill>
            <DrawingBrush>
                <DrawingBrush.Drawing>
                    <DrawingGroup>
                        <DrawingGroup.Children>
                            <GeometryDrawing Brush="#00FFFFFF" Geometry="F1M0,0L16,0 16,16 0,16z" />
                            <GeometryDrawing Brush="#FFF6F6F6" Geometry="F1M1.5,1L9.61,1 10.61,3 13.496,3C14.323,3,14.996,3.673,14.996,4.5L14.996,12.5C14.996,13.327,14.323,14,13.496,14L1.5,14C0.673,14,0,13.327,0,12.5L0,2.5C0,1.673,0.673,1,1.5,1" />
                            <GeometryDrawing Brush="#FFEFEFF0" Geometry="F1M1.9998,3.0004L1.9998,4.0004 8.8738,4.0004 8.3738,3.0004z" />
                            <GeometryDrawing Brush="#FFDBB679" Geometry="F1M2,3L8.374,3 8.874,4 2,4z M13.496,4L10,4 9.992,4 8.992,2 1.5,2C1.225,2,1,2.224,1,2.5L1,12.5C1,12.776,1.225,13,1.5,13L13.496,13C13.773,13,13.996,12.776,13.996,12.5L13.996,4.5C13.996,4.224,13.773,4,13.496,4" />
                        </DrawingGroup.Children>
                    </DrawingGroup>
                </DrawingBrush.Drawing>
            </DrawingBrush>
        </Rectangle.Fill>
    </Rectangle>

</ResourceDictionary>

In a file that uses the icon, I reference my icons file:
<Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Icons.xaml"/>

        </ResourceDictionary.MergedDictionaries>

    </ResourceDictionary>
</Window.Resources>

And in the same file, I use the icon like this:
<ContentControl Content="{StaticResource FolderClosed}" />


How to use service renderer with context theme?

Question: I have snippet code:
//Load block view (have override template)
$block = Block::load('views_block_1480647185');

// get render array
$render = \Drupal::entityTypeManager()
  ->getViewBuilder('block')
  ->view($block);

// get markup string
$markup = \Drupal::service('renderer')
  ->render($render);

kint($markup);

when i visit different url admin (example.com/admin/content), non-admin (example.com). Value markup is different.
In example.com/admin/content

In example.com (use override template view)

I think because url use different theme (bartik and seven).
So how can set markup value same value in url non-admin? How can do that with drupal service renderer?
Comment: What is the difference in markup?
Comment: @Eyal i've updated my answer.
Comment: Basically, you want to print the views results as if the theme was always betrik.
Comment: This seems like a complicated task. Can i ask why are you trying to do that?
Comment: Yes, i want user can preview block with default theme.But i can do that when call from admin theme.
Answer: Use the theme.manager service to set the active theme to what you desire, render the block and set the original active theme back.
/** @var \Drupal\Core\Theme\ThemeInitialization $theme_initialization */
$theme_initialization = \Drupal::service('theme.initialization');
$active_theme = \Drupal::theme()->getActiveTheme();
\Drupal::theme()->setActiveTheme($theme_initialization->getActiveThemeByName($theme));
// Render your block...
\Drupal::theme()->setActiveTheme($active_theme);

Comment: This can be tricky, because you have to find the correct timing to change the active theme.
Comment: Where do you put this code?
Comment: I don't thinking it matters
Comment: It should, In theory
Comment: If you change it right back then it should work.


How to calculate the series?

Question: How can we calculate the series:
$$
F(x)=\sum_{n=1}^{\infty}\frac{(-1)^n}{1-x^n}
$$
I found that
$$
F(x)=\sum_{n=1}^{\infty}(-1)^n\Big(\sum_{m=0}^{\infty}(x^n)^m\Big)=\sum_{m=0}^{\infty}\Big(1-\frac{1}{1+x^m}\Big).
$$
Any suggestion?
EDIT: I once set if $\vert x\vert<1$, but the series doesn't converge at all. So In what occasion does the series converge?
Comment: Got something from an answer below?
Answer: For every $|x|\gt1$, the series converges since $|x^n-1|\geqslant\frac12|x|^n$ for every $n$ large enough, and $$F(x)=\sum_{n\geqslant1}\frac{(-1)^{n+1}}{x^n-1}=\sum_{n\geqslant1}(-1)^{n+1}x^{-n}\frac1{1-x^{-n}}=\sum_{n\geqslant1}(-1)^{n+1}x^{-n}\sum_{k\geqslant0}x^{-nk},$$ that is, $$F(x)=\sum_{n\geqslant1}\alpha_nx^{-n},\qquad\alpha_n=\sum_{d\mid n}(-1)^{d+1}.$$
Note that $$\alpha_n=\sum_{d\mid n}1-2\sum_{d\mid n,\ d\ \mathrm{even}}1=\sigma_0(n)-2\sigma_0^{(e)}(n)=\sigma_0(n)-2\sigma_0(n/2)\mathbf 1_{n\ \text{even}},$$
see here,
where $\sigma_0(n)$ is the number of divisors of $n$. The generating function of the sequence $(\sigma_0(n))$ is known, hence all this yields, for every $|z|\lt1$, $z\ne0$,
$$F(z^{-1})=\frac{\psi_z(1)+\log(1-z)}{\log z}-2\frac{\psi_{z^2}(1)+\log(1-z^2)}{\log(z^2)},$$ and, finally, $$F(z^{-1})=\frac{\psi_z(1)-\psi_{z^2}(1)-\log(1+z)}{\log z}.$$ As usual, this formula, based on the so-called q-polygamma function (see also (5)-(6)-(7) there), is, as given, a mere rewriting of the series one started with.
Comment: Thank you. But What I asked is not real you answered.
Comment: @Did Your comparison was nicer. Really cool how the divisor function comes up too. +1
Comment: What is $\psi_{1/x}$?
Comment: @ZubinMukerjee Sorry, I somehow forgot to include the link I had in mind. Done now. Thanks.
Comment: @Did Thanks. Is there a typo in the MathWorld article, or am I bad at reading? It states the generating function and then says $\phi$ for $\psi$ (I think) ... they're talking about [this thing](http://mathworld.wolfram.com/q-PolygammaFunction.html) anyway, so I'll try to read that (haven't taken any complex analysis yet so I will probably not succeed in understanding it).
Comment: @Did: In my question, $a_n=\frac{(-1)^n}{1-x^n}$, while you stated that $a_n=\frac{1}{x^n-1}$. I don't think this two facts are equivalent.
Comment: @Roger209 Right, somehow the $(-1)^n$ had escaped me. Sorry about this. See revised version.
Comment: @ZubinMukerjee Yes.
Answer: The answer between the two horizontal lines was to the original question, which specified $|x| <1$.

This doesn't converge. If the sum is
$$
\sum_{n=1}^{\infty}a_n
$$
with
$$a_n = \frac{(-1)^n}{1-x^n}
$$
then, since $|x|<1$ we have $$\lim_{n\to\infty} x^n = 0 \qquad\Rightarrow\qquad \lim_{n\to\infty} 1-x^n = 1$$
This gives
$$\lim_{n\to\infty}a_n \,\,= \,\,\lim_{n\to\infty} \frac{(-1)^n}{1-x^n}\,\,\, =\,\,\, \lim_{n\to\infty} (-1)^n$$
Clearly, this limit doesn't exist. The terms don't go to zero, so the sum cannot possibly converge.

In response to your edited question, the condition on $x$ for which the series converges is exactly $|x|>1$.
When $x>1$ we get an alternating series in which the terms $a_n$ go to zero, so it must converge.
If $x<-1$, we get a non-alternating series in which the terms go to zero as well. This converges by comparison:
$$\sum\limits_{n=1}^{\infty} \frac{1}{(-x)^n-1} < 1 + \sum\limits_{n=1}^{\infty} \frac{1}{(\sqrt{-x})^n}$$
The right hand side above converges because it's a geometric series with a common ratio that is greater than zero and less than one.
Comment: Now you seem to use $t^n-1\geqslant t^{n/2}$ for every $t\gt1$. Is that so?
Comment: But what if $|x|>1$?
Comment: Oh, you are right. Thank you.
Comment: @DavidH $|x|<1$ is given in the question ...
Comment: @ZubinMukerjee: I'am sorry, but I just made a change. What shall we do now?
Comment: @Roger209 I've edited in an answer to your second question.
Comment: Alternating? $ $
Comment: @Did how is it now?
Comment: @Did That's what I was going for - I think that's true for all sufficiently large $n$
Comment: There are simpler ways (see the first line of my answer).

How to calculate the series?


Why my logic is failing in certain test cases?

Question: I am solving this problem on codeforces :
https://codeforces.com/contest/1492/problem/C
My code:
#include <bits/stdc++.h>
using namespace std;
#define int long long

int32_t main() {

      int n,m;
      cin>>n>>m;
      string str1,str2;
      cin>>str1;
      cin>>str2;

      int i=0;
      int p=0;
      vector<pair<int,int>>vec;
      while(i<n && p<m)
      {
          int j=i;
          int q=p;
          while(j<n-1 && str1[j+1]==str1[i])
          j++;
          while(q<m-1 && str2[q+1]==str2[p])
          q++;

          vec.push_back({i,i});
          vec.push_back({i+q-p,j});

          i=j+1;
          p=q+1;
      }
      int maxi=1;
      for(int i=0;i<vec.size()-1;i++)
      {
          maxi=max(maxi,vec[i+1].second-vec[i].first);
      }
    cout<<maxi<<endl;
    return 0;
}

My logic:
For each character in t , I am finding the maximum and minimum valid indexes in s which are possible to be taken.
Consider this example:
s-->"aaaabbbbbc"
t-->"aabc"

so my vector would be [(0,0) , (1,3) , (4,8) ,(9,9)]

However my code is failing in certain cases. Can someone point out the mistake?
Comment: If your aim is to learn C++ then do not use competitive coding sites, they teach you problem solving skills (true) but also horrible coding skills/styles (e.g. `#include `, `using namespace std`, using `#define int long long` etc....) Learn from C++ books or https://www.learncpp.com/. first and have a look at https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines. Your problem could wel be with operator precedences add extra `(` and `)` in your while loops to make more clear what you mean.
Comment: `#define int long long` OMG. Illegal code of course, you cannot redefine keywords like that. `int32_t main` is illegal too.
Comment: What in your question is specific to C++14 or 17 ? If there is none - please remove those tags.
Comment: @john this is a regular practice in competitive coding.
Comment: @VatsalAMehta That doesn't change the fact that it is not legal C++. Nor does it bring any benefit (that I can see). Certainly that style of coding isn't going to help in a job interview.
Answer: Your code doesn't seem to be implementing your algorithm. In the loop you have
      vec.push_back({i,i});
      vec.push_back({i+q-p,j});

So the resulting vector would be alternating pairs of equal indexes and (potentially) different indexes. But:
[(0,0) , (1,3) , (4,8) ,(9,9)]

The (4, 8) pair can't be produced by {i, i}. Further the first pair in your example doesn't fit your stated algorithm either, the first a can be (0, 2).
Your code also seems to assume the letters in the strings are sorted. But what about this input?
s = "aaabbbaaabbbccc";
t = "abc";

You would only match a with the first triplet of as and b with the first triplet of bs and break down on the c completely.


Por que o meu código não imprime?

Question: Gostaria de saber porque que esse código que estou criando não imprime nada quando eu o compilo:
<code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main (void)

{
    int dadoacerto, vidadrizzt, vidaartemis, dadod, dadoa, CAd = 8, CAa = 5, dadoataqdr, dadoataart;

    scanf("%d\n%d\n%d", &dadoacerto, &vidadrizzt, &vidaartemis);

    srand( (unsigned)time(NULL) );

    dadod = rand() % dadoacerto;
    dadoa = rand() % dadoacerto;

    if(dadod>dadoa)
    {
        dadoataqdr = rand() % 8;//Drizzt ataca primeiro

        if( dadoataqdr>CAa)
        {
            vidaartemis = vidaartemis - dadoataqdr;
            printf("Drizzt %d", dadoataqdr);
        }
    }
    else if(dadoa>dadod)
    {
        dadoataart = rand() % 5 + rand() % 5;

        if(dadoataart>CAd)
        {
            vidadrizzt = vidadrizzt - dadoataart;
            printf("Artemis %d", dadoataart);
        }
    }
    else if (dadoa==dadod)
    {
        dadoataqdr = rand() % 8;//Drizzt ataca primeiro

    if( dadoataqdr>CAa)
        {
            vidaartemis = vidaartemis - dadoataqdr;
            printf("Drizzt %d", dadoataqdr);
        }
    }

return 0;
}
</code>
Comment: Quando compila ou quando executa? Provavelmente não está entrando em nenhum `if`. Coloque um `else` para testar
Comment: A primeiro coisa que o programa faz é o `scanf()`. Certifica-te que introduzes 3 valores para o programa nao ficar parado nessa instrucao.
Comment: Quando clico em "compilar & executar" no DEV C++, não imprime nenhum valor, só a opção para a entrada dos valores de scanf
Comment: Sim, o scanf() esta correto
Answer: O seu programa esta com alguns erros de logica. Eu executei ele aqui e encontrei, acho, o principal problema pelo qual o seu programa não esta imprimindo uma saída. Esta ocorrendo o seguinte, quando o seu programa entra em um if, por exemplo o primeiro, ele vai ter que testar ainda para entra no if interno caso a condição seja falsa o codigo com o printf não será executado  e o programa não vai poder executar nem um outro comando dentro de um else, assim, ele não vai imprimir nada no final. Como eu não entendi muito bem qual a finalidade desse programa fica um pouco dificil arrumar, mas você so precisa tomar um pouco mas de cuidado com a lógica do if-esle.
Uma possivel sugestão seria você combinar as duas condições em um if só usando o operador &&.
Comment: Mas caso a primeira condição não seja satisfeita o programa não deveria testar o else if posterior?? ou seja, o primeiro if, o segundo e terceiro else if??
Comment: Sim, mas o que esta acontecendo é que o seu programa esta entrando, por exemplo, no primeiro if, mas não esta entrando no if dentro deste. Para você pode ver melhor a situação inclua um comando de printf dentro do primeiro if ai você entenderá o que esta acontecendo. E também com ele ja entrou em um if ele não vai entrar em nem um outro esle. E se ele não entrar no primeiro if e entra em um else-if depois pode acabar ocorrendo a mesma coisa do caso do primeiro.

Por que o meu código não imprime?